コード例 #1
0
ファイル: test_django.py プロジェクト: f4bsch/mixer
    def test_many_to_many_through(self):
        mixer = Mixer()
        pointa = mixer.blend('django_app.pointa')
        self.assertTrue(pointa.other.all())

        pointb = mixer.blend('pointb')
        pointa = mixer.blend('pointa', other=pointb)
        self.assertEqual(list(pointa.other.all()), [pointb])
コード例 #2
0
ファイル: test_django.py プロジェクト: erm0l0v/mixer
    def test_register(self):
        mixer = Mixer()
        mixer.register(Rabbit, {
            'title': lambda: 'Mr. Rabbit'
        })

        rabbit = mixer.blend(Rabbit)
        self.assertEqual(rabbit.title, 'Mr. Rabbit')
コード例 #3
0
    def setUp(self):
        self.tree = create_nomenclature_tree("UK")

        self.model_classes = [Chapter, Section, Heading, SubHeading, Commodity]

        self.mixer = Mixer()

        for model_class in self.model_classes:
            self.mixer.register(model_class, nomenclature_tree=self.tree)
コード例 #4
0
 def setUp(self):
     self.mo_admin_instance = MemberOrganisationOwnerAdmin(
         CompanyOrganisationOwner, AdminSite()
     )
     self.main_user_credentials = {
         'username': '******',
         'password': '******',
     }
     self.group = Group.objects.get(name=self.group_name)
     self.request_factory = RequestFactory()
     self.mixer = Mixer(locale='en')
コード例 #5
0
ファイル: test_importer.py プロジェクト: uktrade/dit-helpdesk
    def test_check_countries_consistency_via_command(self):
        mixer = Mixer()
        country_missing_roo = mixer.blend(
            Country,
            name="Test Country 2",
            country_code="BX",
            scenario="TEST_TA",
        )
        country_missing_roo.save()

        with self.assertLogs("rules_of_origin.ingest.importer",
                             level="ERROR") as warning_log:
            call_command("check_rules_of_origin")

        # Assert 'BX - Test Country 2' is in the error message to sentry
        self.assertIn("BX - Test Country 2", str(warning_log.output))
コード例 #6
0
ファイル: test_django.py プロジェクト: ropable/mixer
def mixer(request):
    if VERSION > (1, 8):
        call_command('migrate', interactive=False, verbosity=0)
    else:
        call_command('syncdb', interactive=False, verbosity=0)
    request.addfinalizer(lambda: call_command('flush', interactive=False, verbosity=0))
    return Mixer()
コード例 #7
0
    def setUp(self):
        Country.objects.all().delete()

        mixer = Mixer()

        self.country = mixer.blend(
            Country,
            name="Test Country",
            country_code="XT",
            has_eu_trade_agreement=False,
            scenario="STICKER_TRADES",
            content_url="gotgotgotneed.com",
            trade_agreement_title="The Very Agreeable Agreement",
            trade_agreement_type="Football Sticker Swap",
            roo_guidance_url="igetfabianbartezineverypackforgodssake.com",
        )
        self.country.save()
コード例 #8
0
    def handle(self, *args, **options):
        batch_size = 5000
        book_cap, reader_cap = 100000, 50000
        mixer = Mixer(commit=False)

        books = mixer.cycle(book_cap).blend(Book)
        readers = mixer.cycle(reader_cap).blend(Reader)

        for i in range(0, reader_cap, batch_size):
            Reader.objects.bulk_create(readers[i:i + batch_size])

        for i in range(0, len(books), batch_size):
            Book.objects.bulk_create(books[i:i + batch_size])

        for book in books:
            index = random.randrange(1, reader_cap)
            book.readers.add(readers[index])
コード例 #9
0
ファイル: test_importer.py プロジェクト: uktrade/dit-helpdesk
    def setUp(self):
        mixer = Mixer()

        self.country = mixer.blend(
            Country,
            name="Test Country",
            country_code="XT",
            trade_agreement_title="The White-Gold Concordat",
        )

        self.gsp_country = mixer.blend(
            Country,
            name="Test Country 2",
            country_code="BX",
            scenario="TEST_TA",
        )

        self.commodity = mixer.blend(Commodity, commodity_code="0100000000")
コード例 #10
0
ファイル: test_django.py プロジェクト: checko/mixer
    def test_fields(self):
        from .django_app.models import Rabbit

        mixer = Mixer()
        rabbit = mixer.blend('django_app.rabbit')

        self.assertTrue(isinstance(rabbit, Rabbit))
        self.assertTrue(rabbit.id)
        self.assertTrue(rabbit.pk)
        self.assertEqual(rabbit.pk, 1)
        self.assertEqual(len(rabbit.title), 16)
        self.assertTrue(isinstance(rabbit.active, bool))
        self.assertTrue(isinstance(rabbit.created_at, datetime.date))
        self.assertTrue(isinstance(rabbit.updated_at, datetime.datetime))
        self.assertTrue(isinstance(rabbit.opened_at, datetime.time))
        self.assertTrue('@' in rabbit.email)
        self.assertTrue(rabbit.speed)
        self.assertTrue(rabbit.description)
コード例 #11
0
ファイル: test_django.py プロジェクト: f4bsch/mixer
    def test_fields(self):
        mixer = Mixer()
        rabbit = mixer.blend('django_app.rabbit')

        self.assertTrue(isinstance(rabbit, Rabbit))
        self.assertTrue(rabbit.id)
        self.assertTrue(rabbit.pk)
        self.assertEqual(rabbit.pk, 1)
        self.assertEqual(len(rabbit.title), 16)
        self.assertTrue(isinstance(rabbit.active, bool))
        self.assertTrue(isinstance(rabbit.created_at, datetime.date))
        self.assertTrue(isinstance(rabbit.updated_at, datetime.datetime))
        self.assertTrue(isinstance(rabbit.opened_at, datetime.time))
        self.assertTrue('@' in rabbit.email)
        self.assertTrue(rabbit.speed)
        self.assertTrue(rabbit.description)
        self.assertEqual(rabbit.picture.read(), b'pylama\n')

        rabbit = mixer.blend('rabbit')
        self.assertTrue(rabbit)
コード例 #12
0
ファイル: test_django.py プロジェクト: f4bsch/mixer
    def test_random_fields(self):
        mixer = Mixer(fake=False)
        rabbit = mixer.blend('django_app.rabbit')

        self.assertTrue(isinstance(rabbit, Rabbit))
        self.assertTrue(rabbit.id)
        self.assertTrue(rabbit.pk)
        self.assertEqual(rabbit.pk, 1)
        self.assertEqual(len(rabbit.title), 16)
        self.assertTrue(isinstance(rabbit.active, bool))
        self.assertTrue(isinstance(rabbit.created_at, datetime.date))
        self.assertTrue(isinstance(rabbit.updated_at, datetime.datetime))
        self.assertTrue(isinstance(rabbit.opened_at, datetime.time))
        self.assertTrue('@' in rabbit.email)
        self.assertTrue(rabbit.description)
        self.assertTrue(rabbit.some_field)
        self.assertTrue(rabbit.money)

        hat = mixer.blend('django_app.hat', color=mixer.random)
        self.assertTrue(hat.color in ('RD', 'GRN', 'BL'))
コード例 #13
0
ファイル: test_django.py プロジェクト: f4bsch/mixer
    def test_custom(self):
        mixer = Mixer()
        mixer.register(Rabbit, {
            'title': lambda: 'Mr. Rabbit'
        })

        rabbit = mixer.blend(Rabbit)
        self.assertEqual(rabbit.title, 'Mr. Rabbit')

        from mixer.backend.django import GenFactory

        def getter(*args, **kwargs):
            return "Always same"

        class MyFactory(GenFactory):
            generators = {models.CharField: getter}

        gen = MyFactory.gen_maker(models.CharField)
        self.assertEqual(gen(), "Always same")

        mixer = Mixer(factory=MyFactory, fake=False)
        self.assertEqual(mixer._Mixer__factory, MyFactory)

        test = mixer.blend(Rabbit)
        self.assertEqual(test.title, "Always same")
コード例 #14
0
    def test_random_fields(self):
        from .django_app.models import Rabbit

        mixer = Mixer(fake=False)
        rabbit = mixer.blend('django_app.rabbit')

        self.assertTrue(isinstance(rabbit, Rabbit))
        self.assertTrue(rabbit.id)
        self.assertTrue(rabbit.pk)
        self.assertEqual(rabbit.pk, 1)
        self.assertEqual(len(rabbit.title), 16)
        self.assertTrue(isinstance(rabbit.active, bool))
        self.assertTrue(isinstance(rabbit.created_at, datetime.date))
        self.assertTrue(isinstance(rabbit.updated_at, datetime.datetime))
        self.assertTrue(isinstance(rabbit.opened_at, datetime.time))
        self.assertTrue('@' in rabbit.email)
        self.assertTrue(rabbit.description)
        self.assertTrue(rabbit.some_field)
        self.assertTrue(rabbit.money)

        hat = mixer.blend('django_app.hat', color=mixer.random)
        self.assertTrue(hat.color in ('RD', 'GRN', 'BL'))
コード例 #15
0
    def test_fields(self):
        from .django_app.models import Rabbit

        mixer = Mixer()
        rabbit = mixer.blend('django_app.rabbit')

        self.assertTrue(isinstance(rabbit, Rabbit))
        self.assertTrue(rabbit.id)
        self.assertTrue(rabbit.pk)
        self.assertEqual(rabbit.pk, 1)
        self.assertEqual(len(rabbit.title), 16)
        self.assertTrue(isinstance(rabbit.active, bool))
        self.assertTrue(isinstance(rabbit.created_at, datetime.date))
        self.assertTrue(isinstance(rabbit.updated_at, datetime.datetime))
        self.assertTrue(isinstance(rabbit.opened_at, datetime.time))
        self.assertTrue('@' in rabbit.email)
        self.assertTrue(rabbit.speed)
        self.assertTrue(rabbit.description)
        self.assertEqual(rabbit.picture.read(), b'pylama\n')

        rabbit = mixer.blend('rabbit')
        self.assertTrue(rabbit)
コード例 #16
0
ファイル: test_django.py プロジェクト: ropable/mixer
def test_custom(mixer):
    mixer.register(
        Rabbit,
        title=lambda: 'Mr. Rabbit',
        speed=lambda: mixer.faker.small_positive_integer(99))

    rabbit = mixer.blend(Rabbit, speed=mixer.RANDOM, percent=23)
    assert isinstance(rabbit.speed, decimal.Decimal)
    assert isinstance(rabbit.percent, float)
    assert rabbit.title == 'Mr. Rabbit'

    from mixer.backend.django import GenFactory

    def getter(*args, **kwargs):
        return "Always same"

    class MyFactory(GenFactory):
        generators = {models.CharField: getter}

    fabric = MyFactory.get_fabric(models.CharField)
    assert fabric() == "Always same"

    mixer = Mixer(factory=MyFactory, fake=False)
    assert mixer._Mixer__factory == MyFactory

    test = mixer.blend(Rabbit)
    assert test.title == "Always same"

    @mixer.middleware('auth.user')
    def encrypt_password(user): # noqa
        user.set_password(user.password)
        return user

    user = mixer.blend('auth.User', password='******')
    assert user.check_password('test')

    user = user.__class__.objects.get(pk=user.pk)
    assert user.check_password('test')
コード例 #17
0
ファイル: tests_safety.py プロジェクト: vvd23d/django-celery
 def setUp(self):
     super().setUp()
     self.src.events = []
     self.safe_mixer = Mixer(commit=False)
コード例 #18
0
ファイル: tests_safety.py プロジェクト: vvd23d/django-celery
class TestEventSourceSafety(GoogleCalendarTestCase):
    def setUp(self):
        super().setUp()
        self.src.events = []
        self.safe_mixer = Mixer(commit=False)

    def test_is_safe_by_default(self):
        """
        By default all should be safe
        """
        self.assertTrue(self.src._ExternalEventSource__is_safe())

    def test_is_safe_with_10_events(self):
        """
        Try to replace 10 events by 8 events
        """
        for i in range(0, 10):
            mixer.blend(ExternalEvent, teacher=self.teacher, src=self.src)

        for i in range(0, 8):  # create 8 non-saved events
            self.src.events.append(
                self.safe_mixer.blend(ExternalEvent,
                                      teacher=self.teacher,
                                      src=self.src))

        self.assertTrue(self.src._ExternalEventSource__is_safe())

    def test_is_safe_to_delete_10_recurring_event(self):
        """
        Try to replace 12 events (10 of them recurring) with 2 events
        """
        mixer.blend(ExternalEvent, teacher=self.teacher,
                    src=self.src)  # some event
        parent_event = mixer.blend(
            ExternalEvent, teacher=self.teacher,
            src=self.src)  # this event will be parent to 10 others

        for i in range(0, 10):
            mixer.blend(ExternalEvent,
                        teacher=self.teacher,
                        src=self.src,
                        parent=parent_event)

        for i in range(0, 2):  # create 2 non-saved events
            self.src.events.append(
                self.safe_mixer.blend(ExternalEvent,
                                      teacher=self.teacher,
                                      src=self.src))

        self.assertTrue(self.src._ExternalEventSource__is_safe())

    def test_unsafe_with_zero_events(self):
        """
        Try to replace 10 events by 0 events
        """
        for i in range(0, 10):
            mixer.blend(ExternalEvent, teacher=self.teacher, src=self.src)

        self.assertFalse(self.src._ExternalEventSource__is_safe())

    def test_unsafe_with_more_then_two_times_difference(self):
        """
        Try to replace 10 events by 3 events
        """
        for i in range(0, 10):
            mixer.blend(ExternalEvent, teacher=self.teacher, src=self.src)

        for i in range(0, 3):  # create 3 non-saved events
            self.src.events.append(
                self.safe_mixer.blend(ExternalEvent,
                                      teacher=self.teacher,
                                      src=self.src))

        self.assertFalse(self.src._ExternalEventSource__is_safe())
コード例 #19
0
ファイル: test_django.py プロジェクト: checko/mixer
    def test_relation(self):
        mixer = Mixer()

        hole = mixer.blend('django_app.hole', title='hole4')
        self.assertEqual(hole.owner.pk, 1)
        self.assertEqual(hole.title, 'hole4')

        hat = mixer.blend('django_app.hat')
        self.assertFalse(hat.owner)
        self.assertEqual(hat.brend, 'wood')
        self.assertTrue(hat.color in ('RD', 'GRN', 'BL'))

        hat = mixer.blend('django_app.hat', owner=mixer.select)
        self.assertTrue(hat.owner)

        silk = mixer.blend('django_app.silk')
        self.assertFalse(silk.hat.owner)

        silk = mixer.blend('django_app.silk', hat__owner__title='booble')
        self.assertTrue(silk.hat.owner)
        self.assertEqual(silk.hat.owner.title, 'booble')

        door = mixer.blend('django_app.door', hole__title='flash',
                           hole__size=244)
        self.assertTrue(door.hole.owner)
        self.assertEqual(door.hole.title, 'flash')
        self.assertEqual(door.hole.size, 244)

        door = mixer.blend('django_app.door')
        self.assertNotEqual(door.hole.title, 'flash')

        num = mixer.blend('django_app.number', doors=[door])
        self.assertEqual(num.doors.get(), door)

        num = mixer.blend('django_app.number')
        self.assertEqual(num.doors.count(), 1)

        num = mixer.blend('django_app.number', doors__size=42)
        self.assertEqual(num.doors.all()[0].size, 42)

        tag = mixer.blend('django_app.tag', customer=mixer.random)
        self.assertTrue(tag.customer)
コード例 #20
0
class PromoteRegulationGroupsTestCase(TestCase):
    """
    Test promote_regulation_groups
    """
    def setUp(self):
        self.tree = create_nomenclature_tree("UK")

        self.model_classes = [Chapter, Section, Heading, SubHeading, Commodity]

        self.mixer = Mixer()

        for model_class in self.model_classes:
            self.mixer.register(model_class, nomenclature_tree=self.tree)

    def test_models_without_regulations(self):

        for model_class in self.model_classes:
            obj = self.mixer.blend(model_class)
            self.assertFalse(obj.regulationgroup_set.exists())
            promote_regulation_groups(obj)
            self.assertFalse(obj.regulationgroup_set.exists())
            obj.delete()

    def test_models_with_regulations(self):
        model_classes = [
            (Chapter, "chapters"),
            (Section, "sections"),
            (Heading, "headings"),
            (SubHeading, "subheadings"),
            (Commodity, "commodities"),
        ]

        for model_class, relation_attr in model_classes:
            obj = self.mixer.blend(model_class)
            regulation = self.mixer.blend(RegulationGroup,
                                          **{relation_attr: obj})

            promote_regulation_groups(obj)
            self.assertEqual(obj.regulationgroup_set.count(), 1)
            self.assertEqual(obj.regulationgroup_set.first(), regulation)

            regulation.delete()
            obj.delete()

    def test_models_in_one_level_hierarchy_gets_promoted(self):
        """
        Test simple hierarchy

        Before:
        Heading    - No regulation
           |
        Commodity  - <RegulationGroup: A>

        After:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - No regulation
        """
        heading = self.mixer.blend(Heading)
        commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(RegulationGroup, commodities=commodity)

        self.assertFalse(heading.regulationgroup_set.exists())
        self.assertEqual(commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertFalse(commodity.regulationgroup_set.exists())

    def test_models_duplicated_in_one_level_hierarchy_gets_merged(self):
        """
        Test simple hierarchy

        Before:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - <RegulationGroup: A>

        After:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - No regulation
        """
        heading = self.mixer.blend(Heading)
        commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(RegulationGroup,
                                      headings=heading,
                                      commodities=commodity)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertFalse(commodity.regulationgroup_set.exists())

    def test_models_multi_children_in_one_level_hierarchy_gets_promoted(self):
        """
        Test simple hierarchy with multiple children

        Before:
                       Heading - No regulation
                                 |
                   ______________________________
                  |                              |
        Commodity - <RegulationGroup: A>    Commodity - <RegulationGroup: A>

        After:
                       Heading - <RegulationGroup: A>
                                 |
                   ______________________________
                  |                              |
        Commodity - No regulation    Commodity - No regulation
        """
        heading = self.mixer.blend(Heading)
        a_commodity = self.mixer.blend(Commodity, heading=heading)
        b_commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(RegulationGroup,
                                      commodities=[a_commodity, b_commodity])

        self.assertFalse(heading.regulationgroup_set.exists())
        self.assertEqual(a_commodity.regulationgroup_set.count(), 1)
        self.assertEqual(b_commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertFalse(a_commodity.regulationgroup_set.exists())
        self.assertFalse(b_commodity.regulationgroup_set.exists())

    def test_models_duplicated_multi_children_in_one_level_hierarchy_gets_merged(
            self):
        """
        Test simple hierarchy with multiple children

        Before:
                       Heading - <RegulationGroup: A>
                                 |
                   ______________________________
                  |                              |
        Commodity - <RegulationGroup: A>    Commodity - <RegulationGroup: A>

        After:
                       Heading - <RegulationGroup: A>
                                 |
                   ______________________________
                  |                              |
        Commodity - No regulation    Commodity - No regulation
        """
        heading = self.mixer.blend(Heading)
        a_commodity = self.mixer.blend(Commodity, heading=heading)
        b_commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(RegulationGroup,
                                      headings=heading,
                                      commodities=[a_commodity, b_commodity])

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(a_commodity.regulationgroup_set.count(), 1)
        self.assertEqual(b_commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertFalse(a_commodity.regulationgroup_set.exists())
        self.assertFalse(b_commodity.regulationgroup_set.exists())

    def test_models_multi_children_multi_regulations_in_one_level_hierarchy_gets_promoted(
        self, ):
        """
        Test simple hierarchy with multiple children multiple regulations

        Before:
                       Heading - No regulation
                                 |
                   ------------------------------
                  |                              |
        Commodity - <RegulationGroup: A>    Commodity - <RegulationGroup: A>
                    <RegulationGroup: B>

        After:
                       Heading - <RegulationGroup: A>
                                 |
                   ------------------------------
                  |                              |
        Commodity - <RegulationGroup: B>    Commodity - No regulation
        """
        heading = self.mixer.blend(Heading)
        a_commodity = self.mixer.blend(Commodity, heading=heading)
        b_commodity = self.mixer.blend(Commodity, heading=heading)
        a_regulation = self.mixer.blend(RegulationGroup,
                                        commodities=[a_commodity, b_commodity])
        b_regulation = self.mixer.blend(RegulationGroup,
                                        commodities=[a_commodity])

        self.assertFalse(heading.regulationgroup_set.exists())
        self.assertEqual(a_commodity.regulationgroup_set.count(), 2)
        self.assertEqual(b_commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), a_regulation)
        self.assertTrue(a_commodity.regulationgroup_set.count(), 1)
        self.assertEqual(a_commodity.regulationgroup_set.first(), b_regulation)
        self.assertFalse(b_commodity.regulationgroup_set.exists())

    def test_models_in_multi_level_hierarchy_gets_promoted(self):
        """
        Test multi level hierarchy

        Before:
        Chapter      - No RegulationGroup
           |
        Section      - No RegulationGroup
           |
        Heading      - No RegulationGroup
           |
        SubHeading   - No RegulationGroup
           |
        Commodity    - <RegulationGroup: A>

        After:
        Chapter      - <RegulationGroup: A>
           |
        Section      - No RegulationGroup
           |
        Heading      - No RegulationGroup
           |
        SubHeading   - No RegulationGroup
           |
        Commodity    - No RegulationGroup
        """
        section = self.mixer.blend(Section)
        chapter = self.mixer.blend(Chapter, section=section)
        heading = self.mixer.blend(Heading, chapter=chapter)
        sub_heading = self.mixer.blend(SubHeading, heading=heading)
        commodity = self.mixer.blend(Commodity, parent_subheading=sub_heading)
        regulation = self.mixer.blend(RegulationGroup, commodities=commodity)

        self.assertFalse(section.regulationgroup_set.exists())
        self.assertFalse(chapter.regulationgroup_set.exists())
        self.assertFalse(heading.regulationgroup_set.exists())
        self.assertFalse(sub_heading.regulationgroup_set.exists())
        self.assertEqual(commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(section)

        self.assertEqual(section.regulationgroup_set.count(), 1)
        self.assertEqual(section.regulationgroup_set.first(), regulation)
        self.assertFalse(chapter.regulationgroup_set.exists())
        self.assertFalse(heading.regulationgroup_set.exists())
        self.assertFalse(sub_heading.regulationgroup_set.exists())
        self.assertFalse(commodity.regulationgroup_set.exists())

    def test_models_multi_children_in_multi_level_hierarchy_gets_promoted(
            self):
        """
        Test multi children level hierarchy
        """
        section = self.mixer.blend(Section)

        a_chapter = self.mixer.blend(Chapter, section=section)
        b_chapter = self.mixer.blend(Chapter, section=section)
        chapters = [a_chapter, b_chapter]

        a_a_heading = self.mixer.blend(Heading, chapter=a_chapter)
        a_b_heading = self.mixer.blend(Heading, chapter=a_chapter)
        b_a_heading = self.mixer.blend(Heading, chapter=b_chapter)
        b_b_heading = self.mixer.blend(Heading, chapter=b_chapter)
        headings = [a_a_heading, a_b_heading, b_a_heading, b_b_heading]

        a_a_a_sub_heading = self.mixer.blend(SubHeading, heading=a_a_heading)
        a_a_b_sub_heading = self.mixer.blend(SubHeading, heading=a_a_heading)
        a_b_a_sub_heading = self.mixer.blend(SubHeading, heading=a_b_heading)
        a_b_b_sub_heading = self.mixer.blend(SubHeading, heading=a_b_heading)
        b_a_a_sub_heading = self.mixer.blend(SubHeading, heading=b_a_heading)
        b_a_b_sub_heading = self.mixer.blend(SubHeading, heading=b_a_heading)
        b_b_a_sub_heading = self.mixer.blend(SubHeading, heading=b_b_heading)
        b_b_b_sub_heading = self.mixer.blend(SubHeading, heading=b_b_heading)
        sub_headings = [
            a_a_a_sub_heading,
            a_a_b_sub_heading,
            a_b_a_sub_heading,
            a_b_b_sub_heading,
            b_a_a_sub_heading,
            b_a_b_sub_heading,
            b_b_a_sub_heading,
            b_b_b_sub_heading,
        ]

        a_a_a_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_a_a_sub_heading)
        a_a_a_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_a_a_sub_heading)
        a_a_b_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_a_b_sub_heading)
        a_a_b_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_a_b_sub_heading)
        a_b_a_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_b_a_sub_heading)
        a_b_a_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_b_a_sub_heading)
        a_b_b_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_b_b_sub_heading)
        a_b_b_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=a_b_b_sub_heading)
        b_a_a_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_a_a_sub_heading)
        b_a_a_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_a_a_sub_heading)
        b_a_b_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_a_b_sub_heading)
        b_a_b_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_a_b_sub_heading)
        b_b_a_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_b_a_sub_heading)
        b_b_a_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_b_a_sub_heading)
        b_b_b_a_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_b_b_sub_heading)
        b_b_b_b_commodity = self.mixer.blend(
            Commodity, parent_subheading=b_b_b_sub_heading)
        commodities = [
            a_a_a_a_commodity,
            a_a_a_b_commodity,
            a_a_b_a_commodity,
            a_a_b_b_commodity,
            a_b_a_a_commodity,
            a_b_a_b_commodity,
            a_b_b_a_commodity,
            a_b_b_b_commodity,
            b_a_a_a_commodity,
            b_a_a_b_commodity,
            b_a_b_a_commodity,
            b_a_b_b_commodity,
            b_b_a_a_commodity,
            b_b_a_b_commodity,
            b_b_b_a_commodity,
            b_b_b_b_commodity,
        ]

        regulation = self.mixer.blend(RegulationGroup,
                                      commodities=[c.pk for c in commodities])

        self.assertFalse(section.regulationgroup_set.exists())
        for chapter in chapters:
            self.assertFalse(chapter.regulationgroup_set.exists())
        for heading in headings:
            self.assertFalse(heading.regulationgroup_set.exists())
        for sub_heading in sub_headings:
            self.assertFalse(sub_heading.regulationgroup_set.exists())
        for commodity in commodities:
            self.assertEqual(commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(section)

        self.assertEqual(section.regulationgroup_set.count(), 1)
        self.assertEqual(section.regulationgroup_set.first(), regulation)
        for chapter in chapters:
            self.assertFalse(chapter.regulationgroup_set.exists())
        for heading in headings:
            self.assertFalse(heading.regulationgroup_set.exists())
        for sub_heading in sub_headings:
            self.assertFalse(sub_heading.regulationgroup_set.exists())
        for commodity in commodities:
            self.assertFalse(commodity.regulationgroup_set.exists())

    def test_models_multi_regulations_multi_children_in_multi_level_hierarchy_gets_promoted(
        self, ):
        """
        Test multi regulations and multi children level hierarchy
        """
        section = self.mixer.blend(Section)

        a_chapter = self.mixer.blend(Chapter,
                                     chapter_code="a",
                                     section=section)
        b_chapter = self.mixer.blend(Chapter,
                                     chapter_code="b",
                                     section=section)

        a_a_heading = self.mixer.blend(Heading,
                                       heading_code="a_a",
                                       chapter=a_chapter)
        a_b_heading = self.mixer.blend(Heading,
                                       heading_code="a_b",
                                       chapter=a_chapter)
        b_a_heading = self.mixer.blend(Heading,
                                       heading_code="b_a",
                                       chapter=b_chapter)
        b_b_heading = self.mixer.blend(Heading,
                                       heading_code="b_b",
                                       chapter=b_chapter)
        headings = [a_a_heading, a_b_heading, b_a_heading, b_b_heading]

        a_a_a_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="a_a_a",
                                             heading=a_a_heading)
        a_a_b_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="a_a_b",
                                             heading=a_a_heading)
        a_b_a_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="a_b_a",
                                             heading=a_b_heading)
        a_b_b_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="a_b_b",
                                             heading=a_b_heading)
        b_a_a_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="b_a_a",
                                             heading=b_a_heading)
        b_a_b_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="b_a_b",
                                             heading=b_a_heading)
        b_b_a_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="b_b_a",
                                             heading=b_b_heading)
        b_b_b_sub_heading = self.mixer.blend(SubHeading,
                                             commodity_code="b_b_b",
                                             heading=b_b_heading)
        sub_headings = [
            a_a_a_sub_heading,
            a_a_b_sub_heading,
            a_b_a_sub_heading,
            a_b_b_sub_heading,
            b_a_a_sub_heading,
            b_a_b_sub_heading,
            b_b_a_sub_heading,
            b_b_b_sub_heading,
        ]

        a_a_a_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_a_a_a",
            parent_subheading=a_a_a_sub_heading)
        a_a_a_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_a_a_b",
            parent_subheading=a_a_a_sub_heading)
        a_a_b_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_a_b_a",
            parent_subheading=a_a_b_sub_heading)
        a_a_b_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_a_b_b",
            parent_subheading=a_a_b_sub_heading)
        a_b_a_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_b_a_a",
            parent_subheading=a_b_a_sub_heading)
        a_b_a_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_b_a_b",
            parent_subheading=a_b_a_sub_heading)
        a_b_b_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_b_b_a",
            parent_subheading=a_b_b_sub_heading)
        a_b_b_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="a_b_b_b",
            parent_subheading=a_b_b_sub_heading)
        b_a_a_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_a_a_a",
            parent_subheading=b_a_a_sub_heading)
        b_a_a_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_a_a_b",
            parent_subheading=b_a_a_sub_heading)
        b_a_b_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_a_b_a",
            parent_subheading=b_a_b_sub_heading)
        b_a_b_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_a_b_b",
            parent_subheading=b_a_b_sub_heading)
        b_b_a_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_b_a_a",
            parent_subheading=b_b_a_sub_heading)
        b_b_a_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_b_a_b",
            parent_subheading=b_b_a_sub_heading)
        b_b_b_a_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_b_b_a",
            parent_subheading=b_b_b_sub_heading)
        b_b_b_b_commodity = self.mixer.blend(
            Commodity,
            commodity_code="b_b_b_b",
            parent_subheading=b_b_b_sub_heading)
        commodities = [
            a_a_a_a_commodity,
            a_a_a_b_commodity,
            a_a_b_a_commodity,
            a_a_b_b_commodity,
            a_b_a_a_commodity,
            a_b_a_b_commodity,
            a_b_b_a_commodity,
            a_b_b_b_commodity,
            b_a_a_a_commodity,
            b_a_a_b_commodity,
            b_a_b_a_commodity,
            b_a_b_b_commodity,
            b_b_a_a_commodity,
            b_b_a_b_commodity,
            b_b_b_a_commodity,
            b_b_b_b_commodity,
        ]

        a_regulation_commodities = commodities
        a_regulation = self.mixer.blend(
            RegulationGroup,
            title="a_regulation",
            commodities=[c.pk for c in a_regulation_commodities],
        )
        b_regulation_commodities = commodities[:8]
        b_regulation = self.mixer.blend(
            RegulationGroup,
            title="b_regulation",
            commodities=[c.pk for c in b_regulation_commodities],
        )
        c_regulation_commodities = commodities[:4]
        c_regulation = self.mixer.blend(
            RegulationGroup,
            title="c_regulation",
            commodities=[c.pk for c in c_regulation_commodities],
        )
        d_regulation_commodities = commodities[:2]
        d_regulation = self.mixer.blend(
            RegulationGroup,
            title="d_regulation",
            commodities=[c.pk for c in d_regulation_commodities],
        )
        e_regulation_commodities = commodities[:1]
        e_regulation = self.mixer.blend(
            RegulationGroup,
            title="e_regulation",
            commodities=[c.pk for c in e_regulation_commodities],
        )

        promote_regulation_groups(section)

        self.assertEqual(section.regulationgroup_set.count(), 1)
        self.assertEqual(section.regulationgroup_set.first(), a_regulation)

        self.assertEqual(a_chapter.regulationgroup_set.count(), 1)
        self.assertEqual(a_chapter.regulationgroup_set.first(), b_regulation)
        self.assertFalse(b_chapter.regulationgroup_set.exists())

        self.assertEqual(a_a_heading.regulationgroup_set.count(), 1)
        self.assertEqual(a_a_heading.regulationgroup_set.first(), c_regulation)
        for heading in headings[1:]:
            self.assertFalse(heading.regulationgroup_set.exists())

        self.assertEqual(a_a_a_sub_heading.regulationgroup_set.count(), 1)
        self.assertEqual(a_a_a_sub_heading.regulationgroup_set.first(),
                         d_regulation)
        for sub_heading in sub_headings[1:]:
            self.assertFalse(sub_heading.regulationgroup_set.exists())

        self.assertEqual(a_a_a_a_commodity.regulationgroup_set.count(), 1)
        self.assertEqual(a_a_a_a_commodity.regulationgroup_set.first(),
                         e_regulation)
        for commodity in commodities[1:]:
            self.assertFalse(commodity.regulationgroup_set.exists())

    def test_models_in_simple_sub_heading_hierarchy_gets_promoted(self):
        """
        Test simple sub heading hierarchy

        Before:
        Sub Heading    - No regulation
           |
        Sub Heading    - No regulation
           |
        Commodity      - <RegulationGroup: A>

        After:
        Sub Heading    - <RegulationGroup: A>
           |
        Sub Heading    - No regulation
           |
        Commodity  - No regulation
        """
        a_sub_heading = self.mixer.blend(SubHeading)
        b_sub_heading = self.mixer.blend(SubHeading,
                                         parent_subheading=a_sub_heading)
        commodity = self.mixer.blend(Commodity,
                                     parent_subheading=b_sub_heading)
        regulation = self.mixer.blend(RegulationGroup, commodities=commodity)

        self.assertFalse(a_sub_heading.regulationgroup_set.exists())
        self.assertFalse(b_sub_heading.regulationgroup_set.exists())
        self.assertEqual(commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(a_sub_heading)

        self.assertEqual(a_sub_heading.regulationgroup_set.count(), 1)
        self.assertEqual(a_sub_heading.regulationgroup_set.first(), regulation)
        self.assertFalse(b_sub_heading.regulationgroup_set.exists())
        self.assertFalse(commodity.regulationgroup_set.exists())

    def test_models_in_simple_sub_heading_and_heading_hierarchy_gets_promoted(
            self):
        """
        Test simple sub heading hierarchy

        Before:
        Heading        - No regulation
           |
        Sub Heading    - No regulation
           |
        Sub Heading    - No regulation
           |
        Commodity      - <RegulationGroup: A>

        After:
        Heading        - <RegulationGroup: A>
           |
        Sub Heading    - No regulation
           |
        Sub Heading    - No regulation
           |
        Commodity  - No regulation
        """
        heading = self.mixer.blend(Heading)
        a_sub_heading = self.mixer.blend(SubHeading, heading=heading)
        b_sub_heading = self.mixer.blend(SubHeading,
                                         parent_subheading=a_sub_heading)
        commodity = self.mixer.blend(Commodity,
                                     parent_subheading=b_sub_heading)
        regulation = self.mixer.blend(RegulationGroup, commodities=commodity)

        self.assertFalse(a_sub_heading.regulationgroup_set.exists())
        self.assertFalse(b_sub_heading.regulationgroup_set.exists())
        self.assertEqual(commodity.regulationgroup_set.count(), 1)

        promote_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertFalse(a_sub_heading.regulationgroup_set.exists())
        self.assertFalse(b_sub_heading.regulationgroup_set.exists())
        self.assertFalse(commodity.regulationgroup_set.exists())
コード例 #21
0
def create_object(model, *, data=None, commit=True):
    if data is None:
        data = {}
    mixer = Mixer(commit=commit)
    return mixer.blend(model, **data)
コード例 #22
0
def create_three_objects_of(model, common_data=None):
    if common_data is None:
        common_data = {}
    mixer = Mixer()
    return mixer.cycle(count=3).blend(model, **common_data)
コード例 #23
0
ファイル: _test_mixer.py プロジェクト: rg3915/boilerplate
person.treatment
person.first_name
person.last_name
person.cpf
person.birthday
person.email
person.phone
person.blocked

mixer.blend(Person).birthday

#-----------------------------------------
from mixer.backend.django import mixer
from myproject.core.models import Person

mixer = Mixer(locale='pt_br')
person = mixer.blend(Person)
person.first_name
person.last_name

person.faker.name()
# person.faker.gender()
# person.faker.treatment()
person.faker.first_name()
person.faker.last_name()
person.faker.cpf()
person.faker.date_time()
person.faker.iso8601()
person.faker.email()
person.faker.phone_number()
# person.faker.blocked()
コード例 #24
0
ファイル: factory.py プロジェクト: francom77/splitapp
    def make_movement(cls, *args, **kwargs):
        params = cls.default_movement.copy()
        params.update(kwargs)
        instance = Mixer().blend('wallet.Movement', **params)

        return instance
コード例 #25
0
class BaseAdminTestCase:
    fixtures = ['bcm.json', 'groups.json']
    """
    We have to inherit from "object" here cause TestCase is something like singleton
    and if TestCase will be specified here, base class will be tested too with errors
    """

    url_prefix = None  # 'mo_admin' / 'go_admin'
    group_name = None  # 'MO Admins' / 'GO Admins'
    mo_admin_instance = None
    main_user_credentials = None
    group = None
    request_factory = None
    mixer = None

    def setUp(self):
        self.mo_admin_instance = MemberOrganisationOwnerAdmin(
            CompanyOrganisationOwner, AdminSite()
        )
        self.main_user_credentials = {
            'username': '******',
            'password': '******',
        }
        self.group = Group.objects.get(name=self.group_name)
        self.request_factory = RequestFactory()
        self.mixer = Mixer(locale='en')

    def create_required_instances(self):
        user11 = self.create_django_user(self.main_user_credentials)
        user12 = self.create_django_user()
        user21 = self.create_django_user()

        mo1 = self.mixer.blend(
            MemberOrganisation,
            name='GS1 France',
            country=Country.objects.get(name='France')
        )
        mo2 = self.mixer.blend(
            MemberOrganisation,
            name='GS1 Belgium',
            country=Country.objects.get(name='Belgium')
        )

        mo1_user1 = self.mixer.blend(
            MemberOrganisationUser, organization=mo1, user=user11, is_admin=True
        )
        mo1_user2 = self.mixer.blend(
            MemberOrganisationUser, organization=mo1, user=user12, is_admin=True
        )
        mo2_user1 = self.mixer.blend(MemberOrganisationUser, organization=mo2, user=user21)

        mo_owner1 = self.mixer.blend(
            MemberOrganisationOwner, organization_user=mo1_user1, organization=mo1
        )
        mo_owner2 = self.mixer.blend(
            MemberOrganisationOwner, organization_user=mo2_user1, organization=mo2
        )

        co_fields = self.get_force_random_fields_for_mixer(
            CompanyOrganisation,
            company='CO1 Test',
            member_organisation=mo1,
            country=mo1.country,
            active=True,
            excluded_fields=['created']
        )
        co1 = self.mixer.blend(CompanyOrganisation, **co_fields)

        co_fields = self.get_force_random_fields_for_mixer(
            CompanyOrganisation,
            company='CO2 Test',
            member_organisation=mo2,
            country=mo2.country,
            active=True,
            excluded_fields=['created']
        )
        co2 = self.mixer.blend(CompanyOrganisation, **co_fields)

        co1_user1 = self.mixer.blend(
            CompanyOrganisationUser,
            user=user11, organization=co1, is_admin=True,
        )

        co2_user1 = self.mixer.blend(
            CompanyOrganisationUser,
            user=user21, organization=co2, is_admin=True,
        )

        co1_owner = self.mixer.blend(
            CompanyOrganisationOwner, organization_user=co1_user1, organization=co1
        )

        co2_owner = self.mixer.blend(
            CompanyOrganisationOwner, organization_user=co2_user1, organization=co2
        )

        co1_prefix1 = self.mixer.blend(Prefix, company_organisation=co1, member_organisation=mo1)
        co2_prefix1 = self.mixer.blend(Prefix, company_organisation=co2, member_organisation=mo2)

        co1_log1 = self.mixer.blend(Log)
        co2_log1 = self.mixer.blend(Log)

        return {
            variable_name: instance
            for variable_name, instance in locals().items()
            if isinstance(instance, models.Model)
        }

    def create_django_user(self, user_credentials=None, add_to_group=True):

        if user_credentials:
            user = User(**user_credentials)
            user.set_password(self.main_user_credentials['password'])
            user.save()
        else:
            user = self.mixer.blend(User)

        if add_to_group:
            user.groups.add(self.group)
        return user

    def get_force_random_fields_for_mixer(self, model_class, excluded_fields=None, **kwargs):
        """
        Mixer sets default values from model,
        but it raises errors when blank=False and default='' at the same time,
        so we have to force fields to be set by random values

        :param model_class:
        :param excluded_fields: ('id', )  # prevent to randomize some fields
        :param kwargs: field_name=instance or value  # predefined field values
        :return: dict of field_names: random/predefined values
        """

        excluded_fields = {'id'} | set(excluded_fields or [])

        co_fields = {
            field.name: self.mixer.RANDOM
            for field in model_class._meta.fields if field.name not in excluded_fields
        }

        for field_name, field_value in kwargs.items():
            co_fields[field_name] = field_value

        return co_fields

    @classmethod
    def model_instance_to_post_data(cls, instance):
        data = serializers.serialize('json', [instance, ])
        post_data = json.loads(data)
        post_data = post_data[0]['fields']

        for field in instance._meta.fields:
            # splitting date and time for admin forms
            if isinstance(field, DateTimeField):
                field_datetime = parse_datetime(post_data[field.name])
                post_data[f'{field.name}_0'] = str(field_datetime.date())
                post_data[f'{field.name}_1'] = str(field_datetime.time())
                del post_data[field.name]
            if not field.serialize and isinstance(field, models.ForeignKey):
                post_data[field.name] = getattr(instance, field.name).pk

        return post_data

    def get_urls_by_types(self, url_types, excluded_apps=None):
        """
        Filters url list by types like: "changelist", "add", "change", "delete"
        """

        excluded_apps = excluded_apps if excluded_apps else []
        url_names = list()

        for url in self.mo_admin_instance.get_urls():
            if not url.name:
                continue
            if not url.name.startswith(self.url_prefix):
                continue

            denied_app_urls = [
                app_name for app_name in excluded_apps
                if url.name.startswith(f'{self.url_prefix}_{app_name}')
            ]
            if denied_app_urls:
                continue

            if any(url_type in url.name for url_type in url_types):
                url_names.append(reverse(f'admin:{url.name}'))

        return url_names

    def get_url_for_model(self, model_class, action, pk=None):
        app_label = model_class._meta.app_label
        model_name = model_class._meta.model_name

        return (
            reverse(
                f'admin:{self.url_prefix}_{app_label}_{model_name}_{action}',
                args=(pk,) if pk else None))

    def test_changelist_add_urls_non_authorized_user(self):
        """
        Non authorized users must receive 302 http response to login page
        """

        url_names = self.get_urls_by_types(['changelist', 'add'], excluded_apps=['auth'])

        for url_name in url_names:
            response = self.client.get(url_name)
            self.assertEqual(
                response.status_code, 302,
                f'URL "{url_name}" should be denied for non authorized users'
            )

    def test_changelist_add_urls_authorized_user(self):
        """
        Authorized and authenticated users must receive 200 http response
        """

        login_result = self.client.login(**self.main_user_credentials)
        self.assertTrue(login_result, 'Can\'t login to with test user credentials')

        url_names = self.get_urls_by_types(
            ['changelist', 'add'],
            excluded_apps=['auth','member_organisations',]
        )
        for url_name in url_names:
            response = self.client.get(url_name)
            self.assertEqual(
                response.status_code, 200,
                f'URL "{url_name}" should be allowed for authorized/authenticated users'
            )

    def perform_adding_tests(self, models_config):
        for model_class, model_conf in models_config.items():
            if not model_conf:
                continue

            predefined_fields = model_conf.get('predefined_fields', {})

            model_fields = self.get_force_random_fields_for_mixer(
                model_class, excluded_fields=['created'], **predefined_fields
            )
            model_instance = self.mixer.blend(model_class, **model_fields)
            model_instance.delete()  # it seems mixer doesn't care about his commit=False
            post_data = self.model_instance_to_post_data(model_instance)

            self.assertFalse(
                model_class.objects.filter(**predefined_fields).exists(),
                f'the {model_class} instance with predefined data: '
                f'"{predefined_fields}" mustn\'t be in the test database before submitting'
            )

            # instance creating is here
            model_add_url = self.get_url_for_model(model_class, 'add')
            response = self.client.post(model_add_url, data=post_data)

            self.assertEqual(
                response.status_code, 302,
                f'Should be a redirect after an instance submitting, model: "{model_class}"'
            )

            self.assertEqual(
                response.url,
                self.get_url_for_model(model_class, 'changelist'),
                f'Wrong redirect url after an instace adding, model: "{model_class}"'
            )

            self.assertTrue(
                model_class.objects.filter(**predefined_fields).exists(),
                f'CompanyOrganisation "{model_instance}" must be '
                f'in the test database after submitting'
            )

    def perform_deleting_tests(self, models_config):
        for model_class, model_conf in models_config.items():
            if 'model_instance' not in model_conf:
                continue

            model_instance = model_conf['model_instance']
            post_data = {'post': 'yes'}

            co_url = self.get_url_for_model(model_class, 'delete', model_instance.pk)

            # instance creating is here
            response = self.client.post(co_url, data=post_data)

            self.assertEqual(
                response.status_code, 302,
                f'Should be a redirect after an instance submitting, model: "{model_class}"'
            )

            self.assertEqual(
                response.url,
                self.get_url_for_model(model_class, 'changelist'),
                f'Wrong redirect url after an instace removing for {model_class}'
            )

            self.assertFalse(
                model_class.objects.filter(pk=model_instance.pk).exists(),
                f'"{model_instance}" must be removed here already'
            )
コード例 #26
0
import pytest
from django.contrib.auth import get_user_model
from django.urls import resolve
from mixer.backend.django import Mixer

User = get_user_model()
mixer = Mixer(commit=False)


@pytest.fixture
def create_user():
    user = User.objects.create_user(email='*****@*****.**')
    yield user
    if user:
        user.delete()


@pytest.mark.django_db(transaction=True)
def test_create_user(create_user):
    assert create_user.email == '*****@*****.**'


@pytest.mark.django_db(transaction=True)
def test_get_absolute_url(create_user):
    path = create_user.get_absolute_url()
    assert resolve(path).view_name == 'accounts:profile'
コード例 #27
0
import random
import sys

from django.contrib.auth import get_user_model
from django.core.management import BaseCommand, call_command
from main.models import Customer, Manager
from mixer.backend.django import Mixer

User = get_user_model()
mixer = Mixer()


class Command(BaseCommand):
    def handle(self, *args, **options):
        self.create_user()
        manager = None
        for i in range(400000):
            if i == 0 or i % 3:
                manager = mixer.blend(Manager)

            mixer.blend(
                Customer,
                phone_number=random.choice([mixer.faker.phone_number(), None]),
                manager=manager,
            )
            if i % 10000 == 0:
                self.stdout.write(f"Added {i} customers")

    def create_user(self):
        credentials = {
            "username": "******",
コード例 #28
0
class InheritedRegulationGroupsTestCase(TestCase):
    """
    Test regulation groups manager inherited
    """

    def setUp(self):
        self.tree = create_nomenclature_tree("UK")

        self.model_classes = [Chapter, Section, Heading, SubHeading, Commodity]

        self.mixer = Mixer()

        for model_class in self.model_classes:
            self.mixer.register(model_class, nomenclature_tree=self.tree)

    def test_models_without_regulation_groups(self):

        for model_class in self.model_classes:
            obj = self.mixer.blend(model_class)
            self.assertFalse(obj.regulationgroup_set.exists())
            regulation_groups = RegulationGroup.objects.inherited(obj)
            self.assertEqual(set(regulation_groups), set([]))
            obj.delete()

    def test_model_with_regulation(self):
        model_classes = [
            (Chapter, "chapters"),
            (Section, "sections"),
            (Heading, "headings"),
            (SubHeading, "subheadings"),
            (Commodity, "commodities"),
        ]

        for model_class, relation_attr in model_classes:
            obj = self.mixer.blend(model_class)

            a_regulation = self.mixer.blend(RegulationGroup, **{relation_attr: obj})
            b_regulation = self.mixer.blend(RegulationGroup, **{relation_attr: obj})

            self.assertEqual(obj.regulationgroup_set.count(), 2)

            regulation_groups = RegulationGroup.objects.inherited(obj)
            self.assertEqual(set(regulation_groups), set([a_regulation, b_regulation]))

            a_regulation.delete()
            b_regulation.delete()
            obj.delete()

    def test_models_in_one_level_hierarchy_single_regulation(self):
        heading = self.mixer.blend(Heading)
        regulation = self.mixer.blend(RegulationGroup, headings=heading)
        commodity = self.mixer.blend(Commodity, heading=heading)

        commodity_regulation_groups = RegulationGroup.objects.inherited(commodity)
        self.assertEqual(set(commodity_regulation_groups), set([regulation]))

        heading_regulation_groups = RegulationGroup.objects.inherited(heading)
        self.assertEqual(set(heading_regulation_groups), set([regulation]))

    def test_models_multi_regulation_groups_one_level_hierarchy(self):
        heading = self.mixer.blend(Heading)
        commodity = self.mixer.blend(Commodity, heading=heading)

        a_regulation = self.mixer.blend(RegulationGroup, headings=heading)
        b_regulation = self.mixer.blend(RegulationGroup, commodities=commodity)

        commodity_regulation_groups = RegulationGroup.objects.inherited(commodity)
        self.assertEqual(
            set(commodity_regulation_groups), set([a_regulation, b_regulation])
        )

        heading_regulation_groups = RegulationGroup.objects.inherited(heading)
        self.assertEqual(set(heading_regulation_groups), set([a_regulation]))

    def test_models_same_regulation_multiple_times_one_level_hierarchy(self):
        heading = self.mixer.blend(Heading)
        commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(
            RegulationGroup, headings=heading, commodities=commodity
        )

        commodity_regulation_groups = RegulationGroup.objects.inherited(commodity)
        self.assertEqual(set(commodity_regulation_groups), set([regulation]))

        heading_regulation_groups = RegulationGroup.objects.inherited(heading)
        self.assertEqual(set(heading_regulation_groups), set([regulation]))

    def test_model_multi_level_hierarchy_one_regulation(self):
        section = self.mixer.blend(Section)
        regulation = self.mixer.blend(RegulationGroup, sections=section)
        chapter = self.mixer.blend(Chapter, section=section)
        heading = self.mixer.blend(Heading, chapter=chapter)
        sub_heading = self.mixer.blend(SubHeading, heading=heading)
        commodity = self.mixer.blend(Commodity, parent_subheading=sub_heading)

        commodity_regulation_groups = RegulationGroup.objects.inherited(commodity)
        self.assertEqual(set(commodity_regulation_groups), set([regulation]))

        sub_heading_regulation_groups = RegulationGroup.objects.inherited(sub_heading)
        self.assertEqual(set(sub_heading_regulation_groups), set([regulation]))

        heading_regulation_groups = RegulationGroup.objects.inherited(heading)
        self.assertEqual(set(heading_regulation_groups), set([regulation]))

        chapter_regulation_groups = RegulationGroup.objects.inherited(chapter)
        self.assertEqual(set(chapter_regulation_groups), set([regulation]))

        section_regulation_groups = RegulationGroup.objects.inherited(section)
        self.assertEqual(set(section_regulation_groups), set([regulation]))

    def test_model_multi_level_hierarchy_single_regulation(self):
        section = self.mixer.blend(Section)
        chapter = self.mixer.blend(Chapter, section=section)
        heading = self.mixer.blend(Heading, chapter=chapter)
        sub_heading = self.mixer.blend(SubHeading, heading=heading)
        commodity = self.mixer.blend(Commodity, parent_subheading=sub_heading)
        regulation = self.mixer.blend(
            RegulationGroup,
            sections=section,
            chapters=chapter,
            headings=heading,
            sub_headings=sub_heading,
            commodities=commodity,
        )

        commodity_regulation_groups = RegulationGroup.objects.inherited(commodity)
        self.assertEqual(set(commodity_regulation_groups), set([regulation]))

        sub_heading_regulation_groups = RegulationGroup.objects.inherited(sub_heading)
        self.assertEqual(set(sub_heading_regulation_groups), set([regulation]))

        heading_regulation_groups = RegulationGroup.objects.inherited(heading)
        self.assertEqual(set(heading_regulation_groups), set([regulation]))

        chapter_regulation_groups = RegulationGroup.objects.inherited(chapter)
        self.assertEqual(set(chapter_regulation_groups), set([regulation]))

        section_regulation_groups = RegulationGroup.objects.inherited(section)
        self.assertEqual(set(section_regulation_groups), set([regulation]))

    def get_model_multi_level_hierarchy_multiple_regulation_groups(self):
        section = self.mixer.blend(Section)
        section_regulation = self.mixer.blend(RegulationGroup, sections=section)

        chapter = self.mixer.blend(Chapter, section=section)
        chapter_regulation = self.mixer.blend(RegulationGroup, chapters=chapter)

        heading = self.mixer.blend(Heading, chapter=chapter)
        heading_regulation = self.mixer.blend(RegulationGroup, headings=heading)

        sub_heading = self.mixer.blend(SubHeading, heading=heading)
        sub_heading_regulation = self.mixer.blend(
            RegulationGroup, sub_headings=sub_heading
        )

        commodity = self.mixer.blend(Commodity, parent_subheading=sub_heading)
        commodity_regulation = self.mixer.blend(RegulationGroup, commodities=commodity)

        commodity_regulation_groups = RegulationGroup.objects.inherited(commodity)
        self.assertEqual(
            set(commodity_regulation_groups),
            set(
                [
                    section_regulation,
                    chapter_regulation,
                    heading_regulation,
                    sub_heading_regulation,
                    commodity_regulation,
                ]
            ),
        )

        sub_heading_regulation_groups = RegulationGroup.objects.inherited(sub_heading)
        self.assertEqual(
            set(sub_heading_regulation_groups),
            set(
                [
                    section_regulation,
                    chapter_regulation,
                    heading_regulation,
                    sub_heading_regulation,
                ]
            ),
        )

        heading_regulation_groups = RegulationGroup.objects.inherited(heading)
        self.assertEqual(
            set(heading_regulation_groups),
            set([section_regulation, chapter_regulation, heading_regulation]),
        )

        chapter_regulation_groups = RegulationGroup.objects.inherited(chapter)
        self.assertEqual(
            set(chapter_regulation_groups),
            set([section_regulation, chapter_regulation]),
        )

        section_regulation_groups = RegulationGroup.objects.inherited(section)
        self.assertEqual(set(section_regulation_groups), set([section_regulation]))

    def test_regulation_groups_in_multiple_hierarchies(self):
        a_commodity = self.mixer.blend(Commodity)
        a_regulation = self.mixer.blend(RegulationGroup, commodities=a_commodity)

        b_commodity = self.mixer.blend(Commodity)
        b_regulation = self.mixer.blend(RegulationGroup, commodities=b_commodity)

        a_commodity_regulation_groups = RegulationGroup.objects.inherited(a_commodity)
        self.assertEqual(set(a_commodity_regulation_groups), set([a_regulation]))

        b_commodity_regulation_groups = RegulationGroup.objects.inherited(b_commodity)
        self.assertEqual(set(b_commodity_regulation_groups), set([b_regulation]))
コード例 #29
0
    def make_membership(cls, *args, **kwargs):
        params = cls.default_membership.copy()
        params.update(kwargs)
        instance = Mixer().blend('events.Membership', **params)

        return instance
コード例 #30
0
ファイル: test_django.py プロジェクト: ropable/mixer
def test_random_fields():
    mixer = Mixer(fake=False)

    hat = mixer.blend('django_app.hat', color=mixer.RANDOM)
    assert hat.color in ('RD', 'GRN', 'BL')
コード例 #31
0
    def test_relation(self):
        mixer = Mixer()

        hole = mixer.blend('django_app.hole', title='hole4')
        self.assertEqual(hole.owner.pk, 1)
        self.assertEqual(hole.title, 'hole4')

        hat = mixer.blend('django_app.hat')
        self.assertFalse(hat.owner)
        self.assertEqual(hat.brend, 'wood')
        self.assertTrue(hat.color in ('RD', 'GRN', 'BL'))

        hat = mixer.blend('django_app.hat', owner=mixer.select)
        self.assertTrue(hat.owner)

        silk = mixer.blend('django_app.silk')
        self.assertFalse(silk.hat.owner)

        silk = mixer.blend('django_app.silk', hat__owner__title='booble')
        self.assertTrue(silk.hat.owner)
        self.assertEqual(silk.hat.owner.title, 'booble')

        door = mixer.blend('django_app.door', hole__title='flash',
                           hole__size=244)
        self.assertTrue(door.hole.owner)
        self.assertEqual(door.hole.title, 'flash')
        self.assertEqual(door.hole.size, 244)

        door = mixer.blend('django_app.door')
        self.assertNotEqual(door.hole.title, 'flash')

        num = mixer.blend('django_app.number', doors=[door])
        self.assertEqual(num.doors.get(), door)

        num = mixer.blend('django_app.number')
        self.assertEqual(num.doors.count(), 1)

        num = mixer.blend('django_app.number', doors__size=42)
        self.assertEqual(num.doors.all()[0].size, 42)

        tag = mixer.blend('django_app.tag', customer=mixer.random)
        self.assertTrue(tag.customer)
コード例 #32
0
class ReplicateRegulationGroupsTestCase(TestCase):
    """
    Test promote_regulation_groups
    """
    def setUp(self):
        self.tree = create_nomenclature_tree("UK")

        self.model_classes = [Chapter, Section, Heading, SubHeading, Commodity]

        self.mixer = Mixer()

        for model_class in self.model_classes:
            self.mixer.register(model_class, nomenclature_tree=self.tree)

    def test_models_without_regulations(self):
        for model_class in self.model_classes:
            obj = self.mixer.blend(model_class)
            self.assertFalse(obj.regulationgroup_set.exists())
            replicate_regulation_groups(obj)
            self.assertFalse(obj.regulationgroup_set.exists())
            obj.delete()

    def test_models_with_regulations(self):
        model_classes = [
            (Chapter, "chapters"),
            (Section, "sections"),
            (Heading, "headings"),
            (SubHeading, "subheadings"),
            (Commodity, "commodities"),
        ]

        for model_class, relation_attr in model_classes:
            obj = self.mixer.blend(model_class)
            regulation = self.mixer.blend(RegulationGroup,
                                          **{relation_attr: obj})

            replicate_regulation_groups(obj)
            self.assertEqual(obj.regulationgroup_set.count(), 1)
            self.assertEqual(obj.regulationgroup_set.first(), regulation)

            regulation.delete()
            obj.delete()

    def test_models_in_one_level_hierarchy_gets_replicated(self):
        """
        Test simple hierarchy

        Before:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - No regulation

        After:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - <RegulationGroup: A>
        """
        heading = self.mixer.blend(Heading)
        commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(RegulationGroup, headings=heading)

        self.assertTrue(heading.regulationgroup_set.exists())
        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertFalse(commodity.regulationgroup_set.exists())
        self.assertEqual(commodity.regulationgroup_set.count(), 0)

        replicate_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertEqual(commodity.regulationgroup_set.count(), 1)
        self.assertEqual(commodity.regulationgroup_set.first(), regulation)

    def test_models_duplicated_in_one_level_hierarchy_gets_merged(self):
        """
        Test simple hierarchy

        Before:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - <RegulationGroup: A>

        After:
        Heading    - <RegulationGroup: A>
           |
        Commodity  - <RegulationGroup: A>
        """
        heading = self.mixer.blend(Heading)
        commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(RegulationGroup,
                                      headings=heading,
                                      commodities=commodity)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(commodity.regulationgroup_set.count(), 1)

        replicate_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertEqual(commodity.regulationgroup_set.count(), 1)
        self.assertEqual(commodity.regulationgroup_set.first(), regulation)

    def test_models_multi_children_in_one_level_hierarchy_gets_replicated(
            self):
        """
        Test simple hierarchy with multiple children

        Before:
                       Heading - <RegulationGroup: A>
                                 |
                   ______________________________
                  |                              |
        Commodity - No regulation    Commodity - No regulation

        After:
                       Heading - <RegulationGroup: A>
                                 |
                   ______________________________
                  |                              |
        Commodity - <RegulationGroup: A>    Commodity - <RegulationGroup: A>
        """
        heading = self.mixer.blend(Heading)
        a_commodity = self.mixer.blend(Commodity, heading=heading)
        b_commodity = self.mixer.blend(Commodity, heading=heading)
        regulation = self.mixer.blend(
            RegulationGroup,
            headings=heading,
        )

        self.assertEquals(heading.regulationgroup_set.count(), 1)
        self.assertFalse(a_commodity.regulationgroup_set.exists())
        self.assertFalse(b_commodity.regulationgroup_set.exists())

        replicate_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertEqual(a_commodity.regulationgroup_set.count(), 1)
        self.assertEqual(a_commodity.regulationgroup_set.first(), regulation)
        self.assertEqual(b_commodity.regulationgroup_set.count(), 1)
        self.assertEqual(b_commodity.regulationgroup_set.first(), regulation)

    def test_models_multi_children_multi_regulations_in_one_level_hierarchy_gets_replicated(
        self, ):
        """
        Test simple hierarchy with multiple children multiple regulations

        Before:
                       Heading - <RegulationGroup: A>
                                 <RegulationGroup: B>
                                 |
                   ------------------------------
                  |                              |
        Commodity - No regulation    Commodity - No regulation

        After:
                       Heading - <RegulationGroup: A>
                                 <RegulationGroup: B>
                                 |
                   ------------------------------
                  |                              |
        Commodity - <RegulationGroup: A>    Commodity - <RegulationGroup: A>
                    <RegulationGroup: B>                <RegulationGroup: B>
        """
        heading = self.mixer.blend(Heading)
        a_commodity = self.mixer.blend(Commodity, heading=heading)
        b_commodity = self.mixer.blend(Commodity, heading=heading)
        a_regulation = self.mixer.blend(RegulationGroup, headings=heading)
        b_regulation = self.mixer.blend(RegulationGroup, headings=heading)

        self.assertEqual(heading.regulationgroup_set.count(), 2)
        self.assertFalse(a_commodity.regulationgroup_set.exists())
        self.assertFalse(b_commodity.regulationgroup_set.exists())

        replicate_regulation_groups(heading)

        self.assertEqual(heading.regulationgroup_set.count(), 2)
        self.assertIn(a_regulation, heading.regulationgroup_set.all())
        self.assertIn(b_regulation, heading.regulationgroup_set.all())
        self.assertEqual(a_commodity.regulationgroup_set.count(), 2)
        self.assertIn(a_regulation, a_commodity.regulationgroup_set.all())
        self.assertIn(b_regulation, a_commodity.regulationgroup_set.all())
        self.assertEqual(b_commodity.regulationgroup_set.count(), 2)
        self.assertIn(a_regulation, b_commodity.regulationgroup_set.all())
        self.assertIn(b_regulation, b_commodity.regulationgroup_set.all())

    def test_models_in_multi_level_hierarchy_gets_promoted(self):
        """
        Test multi level hierarchy

        Before:
        Chapter      - <RegulationGroup: A>
           |
        Section      - No RegulationGroup
           |
        Heading      - No RegulationGroup
           |
        SubHeading   - No RegulationGroup
           |
        Commodity    - No RegulationGroup

        After:
        Chapter      - <RegulationGroup: A>
           |
        Section      - <RegulationGroup: A>
           |
        Heading      - <RegulationGroup: A>
           |
        SubHeading   - <RegulationGroup: A>
           |
        Commodity    - <RegulationGroup: A>
        """
        section = self.mixer.blend(Section)
        chapter = self.mixer.blend(Chapter, section=section)
        heading = self.mixer.blend(Heading, chapter=chapter)
        sub_heading = self.mixer.blend(SubHeading, heading=heading)
        commodity = self.mixer.blend(Commodity, parent_subheading=sub_heading)
        regulation = self.mixer.blend(RegulationGroup, sections=section)

        self.assertEqual(section.regulationgroup_set.count(), 1)
        self.assertFalse(chapter.regulationgroup_set.exists())
        self.assertFalse(heading.regulationgroup_set.exists())
        self.assertFalse(sub_heading.regulationgroup_set.exists())
        self.assertFalse(commodity.regulationgroup_set.exists())

        replicate_regulation_groups(section)

        self.assertEqual(section.regulationgroup_set.count(), 1)
        self.assertEqual(section.regulationgroup_set.first(), regulation)
        self.assertEqual(chapter.regulationgroup_set.count(), 1)
        self.assertEqual(chapter.regulationgroup_set.first(), regulation)
        self.assertEqual(heading.regulationgroup_set.count(), 1)
        self.assertEqual(heading.regulationgroup_set.first(), regulation)
        self.assertEqual(sub_heading.regulationgroup_set.count(), 1)
        self.assertEqual(sub_heading.regulationgroup_set.first(), regulation)
        self.assertEqual(commodity.regulationgroup_set.count(), 1)
        self.assertEqual(commodity.regulationgroup_set.first(), regulation)
コード例 #33
0
import random
from django.contrib.gis.geos import Point
from mixer.backend.django import Mixer
from rest_framework import status, serializers
from rest_framework.generics import RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from faker import Faker

from good_spot.places.models import Place, PlaceType

fake = Faker()
mixer = Mixer(commit=False)
mocked_objects_count = 10
place_rating_choice = list(range(1, 5))

place_types = []

place_type_choice = ["bar", "restaurant", "night club"]
pl_i = 1
for pl_type in place_type_choice:
    place_type = mixer.blend(PlaceType)
    place_type.id = pl_i
    place_type.name = pl_type
    place_types.append(place_type)
    pl_i += 1


def make_place(place_id):
    place = mixer.blend(Place)
    place.id = place_id
コード例 #34
0
import pytest
from mixer.backend.django import Mixer
from django.test import RequestFactory
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from accounts.views import UserProfileView, RegistrationFormView

User = get_user_model()
mixer = Mixer(commit=False, fake=True)


def test_get_registrationview():
    path = reverse('accounts:register')
    factory = RequestFactory()
    user = AnonymousUser()
    request = factory.get(path)
    request.user = user
    response = RegistrationFormView(request=request)
    assert response.template_name == 'registration/registration_form.html'


@pytest.fixture
@pytest.mark.django_db(transaction=True)
def user():
    user = mixer.blend(User)
    return User.objects.create_user(email=f'{user.email}',
                                    password='******')


@pytest.mark.django_db(transaction=True)
コード例 #35
0
def main(project_dir):
    project_dir = project_dir or u'/'.join(os.getcwd().split(u'/')[:-3])
    sys.path.append(project_dir)
    sys.path.append(os.path.join(project_dir, u'apps'))
    os.environ[u'DJANGO_SETTINGS_MODULE'] = u'settings'

    import django
    django.setup()

    from mixer.backend.django import mixer, Mixer
    from catalog.models import Maker, BrandMaker, Brand, \
        PrintTypeMaker, PrintType, CategorySite, CategoryXML, \
        Product, ProductAttachment, ProductParamsOther, \
        ProductParamsPack, ProductParamsStock, \
        SubProduct, SubProductParamsOther, SubProductParamsStock, \
        Status, Settings, OrderReference

    # Generate a random maker
    maker_s = mixer.cycle(5).blend(Maker)

    # Generate a random status
    status_s = mixer.cycle(5).blend(Status)

    # Create filters
    i = 0
    for k, v in {
            'default': ['По умолчанию', 'title', 0, 0],
            'NAZ': ['По названию (А-Я)', 'title', 0, 1],
            'NZA': ['По названию (Я-А)', 'title', 1, 2]
    }.items():
        OrderReference(name=k,
                       official=v[0],
                       field_name=v[1],
                       field_order=v[2],
                       position=v[3]).save()
        i += 1

    # Generate a random brand
    brand_s = mixer.cycle(5).blend(Brand)
    brand_maker_s = mixer.cycle(20).blend(BrandMaker,
                                          maker=mixer.SELECT,
                                          brand=(bm for bm in brand_s * 4))

    # Generate a random print type
    print_type_s = mixer.cycle(5).blend(PrintType)
    print_type_maker_s = mixer.cycle(20).blend(
        PrintTypeMaker,
        maker=mixer.SELECT,
        print_type=(pt for pt in print_type_s * 4))

    # Generate a random category site
    mixer = Mixer(commit=False)
    category_site_parent_s = mixer.cycle(5).blend(CategorySite)
    for cat_site_parent in category_site_parent_s:
        print(cat_site_parent.slug_title)
        cat_site_parent_obj = CategorySite.add_root(
            title=cat_site_parent.title,
            slug_title=cat_site_parent.slug_title,
            preview=cat_site_parent.preview,
            content=cat_site_parent.content,
            show=cat_site_parent.show,
            image=CATEGORY_SITE_IMAGE,
            position=cat_site_parent.position)
        cat_site_parent_obj.save()

        category_site_child_s = mixer.cycle(5).blend(CategorySite)
        for cat_site_child in category_site_child_s:
            cat_site_child_obj = cat_site_parent_obj.add_child(
                title=cat_site_child.title,
                slug_title=cat_site_child.slug_title,
                preview=cat_site_child.preview,
                content=cat_site_child.content,
                show=cat_site_child.show,
                image=CATEGORY_SITE_IMAGE,
                position=cat_site_child.position)
            cat_site_child_obj.save()

    # Generate a random category xml
    mixer = Mixer(commit=False)
    for maker in Maker.objects.all():
        category_xml_parent_s = mixer.cycle(5).blend(
            CategoryXML,
            maker=maker,
            category_site=(category_site
                           for category_site in CategorySite.objects.filter(
                               depth=1)),
            cat_id=(i for i in range(1, 9)))
        for cat_xml_parent in category_xml_parent_s:
            cat_xml_parent_obj = CategoryXML.add_root(
                maker=maker,
                title=cat_xml_parent.title,
                cat_id=cat_xml_parent.cat_id,
                category_site=cat_xml_parent.category_site,
                import_fl=1)
            cat_xml_parent_obj.save()

            category_xml_child_s = mixer.cycle(5).blend(
                CategoryXML,
                maker=maker,
                category_site=(
                    category_site
                    for category_site in CategorySite.objects.filter(depth=2)),
                cat_id=(i for i in range(
                    int(cat_xml_parent.cat_id) * 10,
                    int(cat_xml_parent.cat_id) * 10 + 10)))

            for cat_xml_child in category_xml_child_s:
                cat_xml_child_obj = cat_xml_parent_obj.add_child(
                    maker=maker,
                    title=cat_xml_child.title,
                    cat_id=cat_xml_child.cat_id,
                    category_site=cat_xml_child.category_site,
                    import_fl=1)
                cat_xml_child_obj.save()

    # Generate a random product
    mixer = Mixer(commit=True)
    for maker in Maker.objects.all():
        product_s = mixer.cycle(50).blend(
            Product,
            maker=maker,
            brand=(brand
                   for brand in list(BrandMaker.objects.filter(maker=maker)) *
                   100),
            status=Status.objects.all()[0],
            small_image=PRODUCT_IMAGE,
            big_image=PRODUCT_IMAGE,
            super_big_image=PRODUCT_IMAGE,
            code=(str(x) for x in range(1000, 10000, 2)),
            category_xml=(
                cat_xml
                for cat_xml in list(CategoryXML.objects.filter(maker=maker)) *
                100),
            print_type=(print_type for print_type in
                        list(PrintTypeMaker.objects.filter(maker=maker)) *
                        100),
            import_fl=1)

        # Generate a random product attachment
        product_attachment_s = mixer.cycle(100).blend(
            ProductAttachment,
            maker=maker,
            product=(product for product in
                     list(Product.objects.filter(maker=maker).all()) * 2),
            file=PRODUCT_IMAGE,
            image=PRODUCT_IMAGE)
        print(Product.objects.filter(maker=maker).all())

        # Generate a random product params pack
        product_params_pack_s = mixer.cycle(300).blend(
            ProductParamsPack,
            maker=maker,
            abbr=(
                item
                for product in list(Product.objects.filter(maker=maker).all())
                for item in
                ['amount', 'weight', 'volume', 'sizex', 'sizey', 'sizez']),
            product=(
                product
                for product in list(Product.objects.filter(maker=maker).all())
                for i in range(0, 6)),
            pack_id=0)

        # Generate a random product params stock
        product_params_stock_s = mixer.cycle(250).blend(
            ProductParamsStock,
            maker=maker,
            abbr=(
                item
                for product in list(Product.objects.filter(maker=maker).all())
                for item in
                ['amount', 'free', 'inwayamount', 'inwayfree', 'enduserprice']
            ),
            product=(
                product
                for product in list(Product.objects.filter(maker=maker).all())
                for i in range(0, 5)))

        # Generate a random product params other
        product_params_other_s = mixer.cycle(150).blend(
            ProductParamsOther,
            maker=maker,
            abbr=(
                item
                for product in list(Product.objects.filter(maker=maker).all())
                for item in ['product_size', 'weight', 'matherial']),
            product=(
                product
                for product in list(Product.objects.filter(maker=maker).all())
                for i in range(0, 3)))

        # Generate a random subproduct attachment
        subproduct_s = mixer.cycle(100).blend(
            SubProduct,
            maker=maker,
            code=(str(x) for x in range(1000, 10000, 2)),
            product=(product for product in
                     list(Product.objects.filter(maker=maker).all()) * 2))

        # Generate a random subproduct params stock
        subproduct_params_stock_s = mixer.cycle(500).blend(
            SubProductParamsStock,
            maker=maker,
            abbr=(
                item for subproduct in list(
                    SubProduct.objects.filter(maker=maker).all()) for item in
                ['amount', 'free', 'inwayamount', 'inwayfree', 'enduserprice']
            ),
            sub_product=(subproduct for subproduct in list(
                SubProduct.objects.filter(maker=maker).all())
                         for i in range(0, 5)))

        # Generate a random subproduct params other
        subproduct_params_other_s = mixer.cycle(200).blend(
            SubProductParamsOther,
            maker=maker,
            abbr=(item for subproduct in list(
                SubProduct.objects.filter(maker=maker).all())
                  for item in ['size_code', 'weight']),
            sub_product=(subproduct for subproduct in list(
                SubProduct.objects.filter(maker=maker).all())
                         for i in range(0, 2)))

    # Generate a random settings
    settings = mixer.blend(Settings)
def mixer(request):
    call_command('migrate', interactive=False, verbosity=0)
    request.addfinalizer(
        lambda: call_command('flush', interactive=False, verbosity=0))
    return Mixer()
コード例 #37
0
    def make_event(cls, *args, **kwargs):
        params = cls.default_event.copy()
        params.update(kwargs)
        instance = Mixer().blend('events.Event', **params)

        return instance