Esempio n. 1
0
    def test_avatar_url(self, mock_storage_save, mock_storage_exists):
        # Avatar URL for normal profile is expected to be gravatar url for email.
        profile = ProfileFactory()
        self.assertEqual(
            profile.avatar_url,
            email_to_gravatar(profile.user.email, settings.DEFAULT_AVATAR_URL))
        # Avatar URL for normal profile with invalid email is expected to be gravatar url for email.
        user = UserFactory(invalid_email=True)
        profile = user.profile
        self.assertEqual(
            profile.avatar_url,
            email_to_gravatar(user._clean_email, settings.DEFAULT_AVATAR_URL))

        # Avatar URL for profile with no user account is expected to be gravatar url for fake family member email.
        profile = ProfileSansAccountFactory()
        self.assertEqual(
            profile.avatar_url,
            email_to_gravatar("*****@*****.**",
                              settings.DEFAULT_AVATAR_URL))

        # Avatar URL for profile with uploaded profile picture is expected to be the path to the picture.
        fake = Faker._get_faker()
        upfile = SimpleUploadedFile(fake.file_name(extension='png'),
                                    fake.image(image_format='png'),
                                    'image/png')
        mock_storage_save.return_value = "test_avatars/xyz.png"
        mock_storage_exists.return_value = True
        profile = ProfileFactory(avatar=upfile)
        self.assertEqual(profile.avatar_url,
                         f"{settings.MEDIA_URL}test_avatars/xyz.png")
Esempio n. 2
0
    def test_subregion(self):
        # An existing subregion object's type is expected to be CountryRegion
        # and its `iso_code` is expected to equal the `state_province` value
        # of the place.
        subregion = self.place.subregion
        self.assertIsInstance(subregion, CountryRegion)
        self.assertEqual(subregion.pk, self.region.pk)
        self.assertEqual(subregion.iso_code, self.place.state_province)
        # Saving the object is expected to be disabled.
        current_name = subregion.latin_name
        subregion.latin_name = "SUBSTITUTE"
        subregion.save()
        subregion.refresh_from_db()
        self.assertEqual(subregion.latin_name, current_name)

        # Modifying the `state_province` field of the place is expected to
        # result in a new subregion object.
        # This object's type is expected to be CountryRegion.
        # SIDE EFFECT: self.place.state_province is altered but not saved
        #              to the database; this shouldn't affect other tests.
        faker = Faker._get_faker(locale='zh-CN')
        self.place.state_province = faker.word()
        subregion, old_subregion = self.place.subregion, subregion
        self.assertIsNot(subregion, old_subregion)
        self.assertIsInstance(subregion, CountryRegion)
        self.assertNotEqual(subregion.pk, old_subregion.pk)

        # A non-existing subregion object's `latin_code` is expected to equal
        # the `state_province` value of the place.
        self.assertNotEqual(subregion.pk, self.region.pk)
        self.assertEqual(subregion.latin_code, self.place.state_province)
        # Saving the object is expected to be disabled.
        self.assertIsNone(subregion.pk)
        subregion.save()
        self.assertIsNone(subregion.pk)
Esempio n. 3
0
class UserBrowserFactory(DjangoModelFactory):
    class Meta:
        model = 'core.UserBrowser'
        exclude = ('BROWSERS', 'browser', 'PLATFORMS', 'platform',
                   'platform_token')

    BROWSERS = {
        'chrome': ("Google Chrome", r'Chrome/([0-9.]+)'),
        'firefox': ("Mozilla Firefox", r'Firefox/([0-9.]+)'),
        'internet_explorer': ("MSIE", r'MSIE ([0-9.]+)'),
        'opera': ("Opera", r'Version/([0-9.]+)'),
        'safari': ("Apple Safari", r'Version/([0-9.]+)'),
    }
    PLATFORMS = {
        'android': r'(Android) ([0-9.]+)',
        'ios': r'(i[a-zA-Z]+ OS) ([0-9_]+)',
        'linux': r'(Linux) ()',
        'mac': r'(Mac OS X) ([0-9_]+)',
        'windows': r'(Windows) (.+)',
    }

    user = factory.SubFactory('tests.factories.UserFactory', profile=None)
    browser = Faker('random_element', elements=BROWSERS.keys())
    user_agent_string = factory.LazyAttribute(
        lambda obj: getattr(Faker._get_faker(), obj.browser)())
    user_agent_hash = factory.LazyAttribute(
        lambda obj: md5(obj.user_agent_string.encode('utf-8')).hexdigest())
    browser_name = factory.LazyAttribute(
        lambda obj: obj.BROWSERS[obj.browser][0])

    @factory.lazy_attribute
    def browser_version(self):
        m = re.search(self.BROWSERS[self.browser][1], self.user_agent_string)
        return m.group(1) if m else ''

    platform = Faker('random_element', elements=PLATFORMS.keys())

    @factory.lazy_attribute
    def platform_token(self):
        return re.search(
            self.PLATFORMS[self.platform],
            getattr(Faker._get_faker(), f'{self.platform}_platform_token')())

    os_name = factory.LazyAttribute(lambda obj: obj.platform_token.group(1)
                                    if obj.platform_token else '')
    os_version = factory.LazyAttribute(lambda obj: obj.platform_token.group(2)
                                       if obj.platform_token else '')

    @factory.lazy_attribute
    def device_type(self):
        if not self.platform_token:
            return ''
        platform = self.platform_token.group(1)
        return ("Smartphone"
                if platform.startswith('iPhone') or platform == 'Android' else
                "Tablet" if platform.startswith('iPad') else "PC")
Esempio n. 4
0
 def password(self, create: bool, extracted: Sequence[Any], **kwargs):
     self.raw_password = (extracted
                          if extracted else Faker._get_faker().password(
                              length=42,
                              special_chars=True,
                              digits=True,
                              upper_case=True,
                              lower_case=True,
                          ))
     self.set_password(self.raw_password)
Esempio n. 5
0
 def test_manager_defaults(self, mock_config):
     model = self.factory._meta.model
     faker = Faker._get_faker()
     # The default validity period is expected to be 42 weeks.
     self.factory(
         confirmed_on=make_aware(faker.date_time_between('-288d', '-293d')))
     self.factory(
         confirmed_on=make_aware(faker.date_time_between('-295d', '-300d')))
     qs = model.all_objects.order_by('-id')
     self.assertFalse(qs[0].confirmed)
     self.assertTrue(qs[1].confirmed)
Esempio n. 6
0
 def test_save(self):
     # The advice content is expected to be transformed to a formatted description.
     faker = Faker._get_faker()
     for content in ([faker.sentence()], faker.sentences(2)):
         with self.subTest():
             advice = TravelAdviceFactory.build(
                 description="", content='\n\n'.join(content))
             self.assertIsNone(advice.pk)
             self.assertEqual(advice.description, "")
             advice.save()
             self.assertIsNotNone(advice.pk)
             self.assertEqual(
                 advice.description, "".join("<p>{}</p>\n".format(phrase)
                                             for phrase in content))
Esempio n. 7
0
    def test_validate_image_size(self):
        faker = Faker._get_faker()

        class DummyField:
            pass  # noqa: E701

        test_content = DummyField()  # Mocking the Django's ImageField.

        def prep_data(length):
            data = BytesIO(faker.binary(length=length))
            data.name = faker.file_name(category='image')
            data.content_type = faker.mime_type(category='image')
            data.size = length
            return data

        # A field with no underlying file is expected to pass the validation.
        with self.assertNotRaises(ValidationError):
            type(test_content).file = PropertyMock(
                side_effect=FileNotFoundError)
            validate_size(test_content)
            del type(test_content
                     ).file  # Clear the property mock for further testing.

        # File size lesser than or equal to 100 kB is expected to be accepted.
        for test_length in (10, 1024, 102400):
            test_content.file = prep_data(test_length)
            with self.subTest(size=test_length):
                with self.assertNotRaises(ValidationError):
                    validate_size(test_content)

        # File size larger than 100 kB is expected to fail the validation.
        for test_length in (102402, 102502):
            test_content.file = prep_data(test_length)
            with self.subTest(size=test_length):
                with self.assertRaises(ValidationError) as cm:
                    validate_size(test_content)
                with override_settings(LANGUAGE_CODE='en'):
                    self.assertStartsWith(
                        next(iter(cm.exception)),
                        "Please keep file size under 100.0 KB.")
                with override_settings(LANGUAGE_CODE='eo'):
                    self.assertStartsWith(
                        next(iter(cm.exception)),
                        "Bv. certigu ke dosiergrando estas sub 100,0 KB.")

        # Verify that client-side constraint is properly defined.
        self.assertTrue(hasattr(validate_size, 'constraint'))
        self.assertIn('maxlength', validate_size.constraint)
Esempio n. 8
0
 def test_active_status_flag(self):
     faker = Faker._get_faker()
     test_data = [
         ("in past", False,
          TravelAdviceFactory(
              active_from=faker.date_between('-30d', '-15d'),
              active_until=faker.date_between('-14d', '-2d'))),
         ("in past", False,
          TravelAdviceFactory(active_from=None,
                              active_until=faker.date_between(
                                  '-30d', '-2d'))),
         ("in future", False,
          TravelAdviceFactory(active_from=faker.date_between('+2d', '+14d'),
                              active_until=faker.date_between(
                                  '+15d', '+30d'))),
         ("in future", False,
          TravelAdviceFactory(active_from=faker.date_between('+2d', '+30d'),
                              active_until=None)),
         ("in present", True,
          TravelAdviceFactory(active_from=faker.date_between('-30d', '-2d'),
                              active_until=faker.date_between(
                                  '+2d', '+30d'))),
         ("in present", True,
          TravelAdviceFactory(active_from=faker.date_between('-30d', '-2d'),
                              active_until=faker.date_between(
                                  '+2d', '+30d'))),
         ("in present", True,
          TravelAdviceFactory(active_from=faker.date_between(
              '-30d', 'today'),
                              active_until=None)),
         ("in present", True,
          TravelAdviceFactory(active_from=None,
                              active_until=faker.date_between(
                                  'today', '+30d'))),
         ("in present", True,
          TravelAdviceFactory(active_from=None, active_until=None)),
         ("in present", True,
          TravelAdviceFactory(active_from=date.today(),
                              active_until=date.today()))
     ]
     qs = TravelAdvice.objects.get_queryset().order_by('id')
     self.assertEqual(len(qs), len(test_data))
     for i, (time_tag, active_flag, advice) in enumerate(test_data):
         with self.subTest(start=str(advice.active_from),
                           stop=str(advice.active_until),
                           era=time_tag):
             self.assertEqual(qs[i].pk, advice.pk)
             self.assertEqual(qs[i].is_active, active_flag)
Esempio n. 9
0
 def active_from(self):
     faker = Faker._get_faker()
     if self.in_past:
         faked_date = faker.optional_value('date_between',
                                           start_date='-365d',
                                           end_date='-200d')
     elif self.in_future:
         faked_date = faker.date_between(start_date='+2d', end_date='+199d')
     elif self.in_present:
         faked_date = faker.optional_value('date_between',
                                           start_date='-200d',
                                           end_date='-2d')
     else:
         faked_date = faker.optional_value('date_object',
                                           end_datetime='+5y')
     return faked_date
Esempio n. 10
0
    def test_avatar_exists(self, mock_storage_save, mock_storage_exists):
        # Profile with no uploaded profile picture is expected to return False.
        profile = ProfileFactory()
        self.assertFalse(profile.avatar_exists())

        # Profile with uploaded profile picture not saved on disk is expected to return False.
        fake = Faker._get_faker()
        upfile = SimpleUploadedFile(fake.file_name(extension='png'),
                                    fake.image(image_format='png'),
                                    'image/png')
        mock_storage_save.return_value = "test_avatars/xyz.png"
        mock_storage_exists.return_value = False
        profile = ProfileFactory(avatar=upfile)
        self.assertFalse(profile.avatar_exists())

        # Profile with uploaded profile picture properly saved on disk is expected to return True.
        mock_storage_exists.return_value = True
        self.assertTrue(profile.avatar_exists())
Esempio n. 11
0
    def test_clean_recipients(self):
        faker = Faker._get_faker()

        # Writing to a deceased user is expected to raise an error.
        form = CustomAnonymousWriteForm(sender=AnonymousUser(),
                                        data={
                                            'recipients':
                                            self.recipient_deceased.username,
                                            'subject': faker.sentence(),
                                            'body': faker.paragraph(),
                                            'email': faker.email(),
                                        })
        self.assertFalse(form.is_valid())
        self.assertIn('recipients', form.errors)
        self.assertEqual(form.errors['recipients'], [
            "Some usernames are rejected: {}.".format(
                self.recipient_deceased.username)
        ])

        # Writing to a user who is alive is expected to result in no errors.
        form = CustomAnonymousWriteForm(sender=AnonymousUser(),
                                        data={
                                            'recipients':
                                            self.recipient_living.username,
                                            'subject': faker.sentence(),
                                            'body': faker.paragraph(),
                                            'email': faker.email(),
                                        })
        self.assertTrue(form.is_valid())

        # Writing to a user without profile is expected to result in no errors.
        form = CustomAnonymousWriteForm(sender=AnonymousUser(),
                                        data={
                                            'recipients':
                                            UserFactory(profile=None),
                                            'subject': faker.sentence(),
                                            'body': faker.paragraph(),
                                            'email': faker.email(),
                                        })
        self.assertTrue(form.is_valid())
Esempio n. 12
0
    def test_validate_image_type(self):
        faker = Faker._get_faker()
        data = BytesIO(faker.binary(length=10))
        data.name = faker.file_name(category='image')

        class DummyField:
            pass  # noqa: E701

        test_content = DummyField()  # Mocking the Django's ImageField.

        with self.assertNotRaises(ValidationError):
            # A field with no underlying file is expected to pass the validation.
            validate_image(test_content)
            type(test_content).file = PropertyMock(
                side_effect=FileNotFoundError)
            validate_image(test_content)
            del type(test_content
                     ).file  # Clear the property mock for further testing.
            # A field with file of unknown content type is expected to pass the validation.
            test_content.file = data
            validate_image(test_content)
            # A field with file of content type 'image' is expected to pass the validation.
            data.content_type = faker.mime_type(category='image')
            validate_image(test_content)

        # A field with file of unsupported content type is expected to fail validation.
        for category in [
                'application', 'audio', 'message', 'model', 'multipart',
                'text', 'video'
        ]:
            data.content_type = faker.mime_type(category=category)
            with self.subTest(content_type=data.content_type):
                with self.assertRaises(ValidationError) as cm:
                    validate_image(test_content)
                with override_settings(LANGUAGE_CODE='en'):
                    self.assertEqual(next(iter(cm.exception)),
                                     "File type is not supported.")
                with override_settings(LANGUAGE_CODE='eo'):
                    self.assertEqual(next(iter(cm.exception)),
                                     "Dosiertipo ne akceptebla.")
Esempio n. 13
0
    def setUpTestData(cls):
        cls.host_required_fields = [
            'birth_date',
        ]
        cls.book_required_fields = [
            'birth_date',
            'gender',
            'first_name',
            'last_name',
        ]
        cls.config = SiteConfiguration.get_solo()
        cls.faker = Faker._get_faker()
        TaggedProfile = namedtuple('TaggedProfile', 'obj, tag')

        cls.profile_with_no_places = TaggedProfile(ProfileFactory(), "simple")
        cls.profile_with_no_places_deceased = TaggedProfile(ProfileFactory(deceased=True), "deceased")

        profile = ProfileFactory()
        cls.profile_hosting = TaggedProfile(profile, "hosting")
        PlaceFactory(owner=profile, available=True)

        profile = ProfileFactory()
        cls.profile_meeting = TaggedProfile(profile, "meeting")
        PlaceFactory(owner=profile, available=False, have_a_drink=True)

        profile = ProfileFactory()
        cls.profile_hosting_and_meeting = TaggedProfile(profile, "hosting & meeting")
        PlaceFactory(owner=profile, available=True)
        PlaceFactory(owner=profile, available=False, tour_guide=True)

        profile = ProfileFactory()
        cls.profile_in_book = TaggedProfile(profile, "in book (simple)")
        PlaceFactory(owner=profile, available=True, in_book=True)

        profile = ProfileFactory()
        cls.profile_in_book_complex = TaggedProfile(profile, "in book (complex)")
        PlaceFactory(owner=profile, available=True, in_book=True)
        PlaceFactory(owner=profile, available=True, in_book=False)
        PlaceFactory(owner=profile, available=False, have_a_drink=True, in_book=False)
Esempio n. 14
0
    def test_too_near_past_validator(self):
        validator5 = TooNearPastValidator(5)
        self.assertNotEqual(validator5, None)
        self.assertNotEqual(validator5, object())
        self.assertNotEqual(validator5, TooFarPastValidator(5))
        self.assertNotEqual(validator5, 5)
        self.assertEqual(validator5, validator5)
        self.assertEqual(validator5, TooNearPastValidator(5.0))

        faker = Faker._get_faker()
        with patch('hosting.validators.date',
                   Mock(today=Mock(return_value=date(2024, 2, 29)))):
            for date_value in (faker.date_between_dates(
                    date_start=date(2000, 2, 1),
                    date_end=date(2019, 2, 27)), date(2019, 2, 28)):
                with self.subTest(date_value=date_value):
                    with self.assertNotRaises(ValidationError):
                        validator5(date_value)

            for date_value in (faker.date_between_dates(
                    date_start=date(2019, 3, 1), date_end=date(2024, 2, 28)),
                               date(2019, 3, 1), date(2024, 2,
                                                      28), date(2024, 2, 29),
                               faker.date_between_dates(
                                   date_start=date(2024, 3, 1),
                                   date_end=date(2030, 1, 15))):
                with self.subTest(date_value=date_value):
                    with self.assertRaises(ValidationError) as cm:
                        validator5(date_value)
                    with override_settings(LANGUAGE_CODE='en'):
                        self.assertEqual(
                            next(iter(cm.exception)),
                            "Ensure this value is less than or equal to 2019-02-28."
                        )
                    with override_settings(LANGUAGE_CODE='eo'):
                        self.assertEqual(
                            next(iter(cm.exception)),
                            "Certigu ke ĉi tiu valoro estas malpli ol aŭ egala al 2019-02-28."
                        )
Esempio n. 15
0
 def form_submission_tests(self, *, lang, obj=None):
     random_email = Faker._get_faker().email(safe=False)
     for new_email in (" ", random_email):
         page = self.app.get(
             reverse('profile_email_update', kwargs={
                 'pk': self.user.pk,
                 'slug': self.user.autoslug}),
             user=self.user.user,
         )
         page.form['email'] = new_email
         page = page.form.submit()
         self.user.refresh_from_db()
         self.assertRedirects(
             page,
             '{}#e{}'.format(
                 reverse('profile_edit', kwargs={
                     'pk': self.user.pk,
                     'slug': self.user.autoslug}),
                 self.user.pk,
             )
         )
         self.assertEqual(self.user.email, new_email.strip())
Esempio n. 16
0
 def active_until(self):
     faker = Faker._get_faker()
     if self.in_past:
         faked_date = faker.date_between(start_date='-199d', end_date='-2d')
     elif self.in_future:
         faked_date = faker.optional_value('date_between',
                                           start_date='+200d',
                                           end_date='+365d')
     elif self.in_present:
         faked_date = faker.optional_value('date_between',
                                           start_date='+2d',
                                           end_date='+200d')
     else:
         if self.active_from:
             start, end = self.active_from, self.active_from + timedelta(
                 days=365)
             faked_date = faker.optional_value('date_between_dates',
                                               date_start=start,
                                               date_end=end)
         else:
             faked_date = faker.optional_value('date_object',
                                               end_datetime='+5y')
     return faked_date
Esempio n. 17
0
    def test_mass_html_mail(self):
        test_data = list()
        faker = Faker._get_faker()
        for i in range(random.randint(3, 7)):
            test_data.append((
                # subject line
                faker.sentence(),
                # content: plain text & html
                faker.word(), "<strong>{}</strong>".format(faker.word()),
                # author email (ignored) & emails of recipients
                "test@ps", [],
            ))
            for j in range(random.randint(1, 3)):
                test_data[i][4].append(faker.company_email())

        result = send_mass_html_mail(test_data)
        self.assertEqual(result, len(test_data))
        self.assertEqual(len(mail.outbox), len(test_data))
        for i in range(len(test_data)):
            for j in range(len(test_data[i][4])):
                self.assertEqual(mail.outbox[i].subject, test_data[i][0])
                self.assertEqual(mail.outbox[i].from_email, settings.DEFAULT_FROM_EMAIL)
                self.assertEqual(mail.outbox[i].to, test_data[i][4])
Esempio n. 18
0
    def test_valid_object(self):
        Cls = namedtuple('ObjectWithFields',
                         'pk, name, date_joined, date_deleted')
        obj = Cls(pk=1023,
                  name="John",
                  date_joined="2011-02-03",
                  date_deleted="2018-07-06")
        with self.subTest(obj=obj):
            page = Template(self.template_string).render(
                Context({'my_obj': obj}))
            self.assertEqual(
                page,
                "d64d289bce1a4d5a355bf948a58af770842a008d74bd375f57d182375838994c"
            )

        faker = Faker._get_faker()
        first_obj = Cls(pk=faker.pyint(),
                        name=faker.first_name(),
                        date_joined=faker.past_date(),
                        date_deleted=faker.future_date())
        hash_of_obj = ""
        object_list = [first_obj]
        for i in range(15):
            obj = Cls(pk=first_obj.pk,
                      date_joined=first_obj.date_joined,
                      name=faker.first_name(),
                      date_deleted=faker.future_date())
            object_list.append(obj)
        for obj in object_list:
            with self.subTest(obj=obj):
                page = Template(self.template_string).render(
                    Context({'my_obj': obj}))
                self.assertRegex(page, r'^[a-f0-9]{64}$')
                if obj is first_obj:
                    hash_of_obj = page
                else:
                    self.assertEqual(page, hash_of_obj)
Esempio n. 19
0
    def setUpTestData(cls):
        cls.faker = Faker._get_faker()

        cls.expected_fields = [
            'first_name',
            'last_name',
            'names_inversed',
            'title',
            'birth_date',
        ]

        cls.place_with_family = PlaceFactory()
        cls.profile_one = ProfileSansAccountFactory(pronoun="", description="")
        cls.place_with_family.family_members.add(cls.profile_one)
        # Verify that family member is stored and force populating cache.
        assert len(cls.place_with_family.family_members_cache()) == 1
        cls.place_anon_family = PlaceFactory()
        cls.profile_two = ProfileSansAccountFactory(first_name="",
                                                    last_name="",
                                                    pronoun="",
                                                    description="")
        cls.place_anon_family.family_members.add(cls.profile_two)
        # Verify that family member is stored and force populating cache.
        assert len(cls.place_anon_family.family_members_cache()) == 1
Esempio n. 20
0
    def setUpTestData(cls):
        cls.config = SiteConfiguration.get_solo()
        cls.faker = Faker._get_faker()
        cls.all_countries = Countries().countries.keys()

        cls.expected_fields = [
            'country',
            'type',
            'number',
            'comments',
        ]

        cls.profile_one = ProfileFactory()
        cls.phone1_valid = PhoneFactory(profile=cls.profile_one)
        cls.phone2_valid = PhoneFactory(profile=cls.profile_one)
        cls.phone3_deleted = PhoneFactory(
            profile=cls.profile_one,
            deleted_on=make_aware(cls.faker.date_time_this_decade()))

        cls.profile_two = ProfileFactory()
        cls.phone4_valid = PhoneFactory(profile=cls.profile_two)
        cls.phone5_deleted = PhoneFactory(
            profile=cls.profile_two,
            deleted_on=make_aware(cls.faker.date_time_this_decade()))
Esempio n. 21
0
import random
from typing import List, Optional, Set, Tuple

from factory import Factory, Faker, SubFactory

from pythonium import Explosion, Galaxy, Planet, Ship
from pythonium.core import Position
from pythonium.ship_type import ShipType
from pythonium.vectors import Transfer

fake = Faker._get_faker()
MAP_SIZE = (fake.pyint(min_value=10), fake.pyint(min_value=10))


def fake_positions(
    map_size: Tuple[int, int],
    amount: int = 1,
    exclude: Optional[List[Position]] = None,
):
    exclude = exclude or []

    def get_available_points(size: int, excluded: Set):
        all_points = set(range(size))
        all_points.discard(excluded)
        return list(all_points)

    excluded_x = [p[0] for p in exclude]
    excluded_y = [p[1] for p in exclude]
    x_coordinates = get_available_points(map_size[0], set(excluded_x))
    y_coordinates = get_available_points(map_size[1], set(excluded_y))
    random.shuffle(x_coordinates)
import random

from bson import ObjectId
from factory import Dict, Faker, LazyAttribute, SelfAttribute, Sequence, SubFactory, sequence
from factory.fuzzy import reseed_random, FuzzyInteger, FuzzyChoice
from factory.mongoengine import MongoEngineFactory

from facebook_objects import *

# Set random to generate the same data set each time
seed = 41
random.seed(seed)
reseed_random(seed)  # set random seed for factory.fuzzy
Faker._get_faker().seed(seed)  # set random state for factory.Faker

# ToDo: implement different FbRawPost instances with the same profile
#   see: http://stackoverflow.com/questions/39345286/how-to-create-factory-boy-factories-for-django-models-with-the-same-foreign-key
# ToDo: make a separate factory with all non random fields for easy testing?

# Tweak: make length of lists (comment, likes,..) random, and not =n
# Tweak: Make like_count and comment_count the numer of likes and comments iso random int


class Profile_SubFactory(MongoEngineFactory):
    class Meta:
        model = Profile

    id = Sequence(lambda n: '1%07d' % n)
    name = Faker(provider='name', locale='nl_NL')

Esempio n. 23
0
    def test_manager_flags(self, mock_config):
        model = self.factory._meta.model
        faker = Faker._get_faker()
        existing_items_count = {
            manager_name: getattr(model, manager_name).count()
            for manager_name in ['objects', 'objects_raw', 'all_objects']
        }
        from_period = lambda start, end: make_aware(
            faker.date_time_between(start, end))
        test_data = [
            self.factory(),
            self.factory(confirmed_on=from_period('-30d', '-20d')),
            self.factory(confirmed_on=from_period('-60d', '-40d'),
                         deleted_on=from_period('-10d', '-2d')),
            self.factory(checked_on=from_period('-30d', '-20d')),
            self.factory(checked_on=from_period('-60d', '-40d'),
                         deleted_on=from_period('-10d', '-2d')),
        ]

        # The `objects` manager is expected to fetch only non-deleted,
        # annotated, instances of the model.
        qs = model.objects.order_by('id')
        with self.subTest(manager='objects'):
            self.assertEqual(len(qs), 3 + existing_items_count['objects'])
            for obj in qs:
                self.assertTrue(hasattr(obj, 'deleted'))
                self.assertFalse(obj.deleted,
                                 msg=f"object deleted on = {obj.deleted_on}")
                self.assertTrue(hasattr(obj, 'confirmed'))
                self.assertTrue(hasattr(obj, 'checked'))

        # The `objects_raw` manager is expected to fetch only non-deleted,
        # non-annotated, instances of the model.
        qs = model.objects_raw.order_by('id')
        with self.subTest(manager='objects_raw'):
            self.assertEqual(len(qs), 3 + existing_items_count['objects_raw'])
            for obj in qs:
                self.assertFalse(hasattr(obj, 'deleted'))
                self.assertIsNone(obj.deleted_on)
                self.assertFalse(hasattr(obj, 'confirmed'))
                self.assertFalse(hasattr(obj, 'checked'))

        # The `all_objects` manager is expected to fetch all instances of
        # the model, with boolean flag annotations.
        qs = model.all_objects.order_by('-id')
        with self.subTest(manager='all_objects'):
            self.assertEqual(len(qs), 5 + existing_items_count['all_objects'])
            for obj in qs:
                self.assertTrue(hasattr(obj, 'deleted'))
                self.assertIs(obj.deleted, True if obj.deleted_on else False)
                self.assertTrue(hasattr(obj, 'confirmed'))
                self.assertTrue(hasattr(obj, 'checked'))

        # Object which was confirmed within the confirmation validity period
        # is expected to have the 'confirmed' flag set to True.
        self.assertEqual(qs[3].pk, test_data[1].pk)
        self.assertTrue(qs[3].confirmed)
        # Object which was confirmed outside the confirmation validity period
        # is expected to have the 'confirmed' flag set to False.
        self.assertEqual(qs[2].pk, test_data[2].pk)
        self.assertFalse(qs[2].confirmed)
        # Object which was checked within the confirmation validity period
        # is expected to have the 'checked' flag set to True.
        self.assertEqual(qs[1].pk, test_data[3].pk)
        self.assertTrue(qs[1].checked)
        # Object which was checked outside the confirmation validity period
        # is expected to have the 'checked' flag set to True.
        # (Check exvalidation is turned off at the moment.)
        self.assertEqual(qs[0].pk, test_data[4].pk)
        self.assertTrue(qs[0].checked)
Esempio n. 24
0
 def content(obj, n):
     faker = Faker._get_faker(locale='la')
     policy_date = faker.date(
         pattern='%Y-%m-%d') if obj.from_date is None else obj.from_date
     policy_text = faker.text()
     return f"{{# {policy_date} #}}<p>Policy {n:03d}</p>\n{policy_text}"
Esempio n. 25
0
 def name(self):
     return Faker._get_faker().city().upper()
Esempio n. 26
0
 def platform_token(self):
     return re.search(
         self.PLATFORMS[self.platform],
         getattr(Faker._get_faker(), f'{self.platform}_platform_token')())
Esempio n. 27
0
 def setUpTestData(cls):
     cls.sender = UserFactory()
     cls.recipient = UserFactory(deceased_user=True)
     cls.faker = Faker._get_faker()