Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a sequence for an attribute while using create_batch in factory-boy?

Tags:

When using factory_boy in Django, how can I achieve this?

models.py

class TestModel(models.Model):
    name = CharField()
    order = IntegerField()

recipes.py

class TestModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = TestModel

    name = factory.LazyAttribute(lambda o: faker.word().title())
    order = 0

tests.py

recipes.TestModelFactory.create_batch(4, order=+10)

or

recipes.TestModelFactory.create_batch(4, order=seq(10))

or something along those lines, to achieve this result:

TestModel.objects.all().values_list('order', flat=True)

[10, 20, 30, 40]

UPDATE

Ty @trinchet for the idea. So I guess one solution would be:

class TestModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = TestModel

    name = factory.LazyAttribute(lambda o: faker.word().title())
    order = factory.Sequence(lambda n: n * 10)

But that would always set sequences on all my objects, without me being able to set values that I want.

A workaround that is:

class TestModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = TestModel

    name = factory.LazyAttribute(lambda o: faker.word().title())
    order = 0

And then in tests:

    recipes.MenuItemFactory.reset_sequence(1)

    recipes.MenuItemFactory.create_batch(
        4,
        parent=self.section_menu,
        order=factory.Sequence(lambda n: n * 10)
    )

Which will give me the result that I want. But this resets all the sequences. I want it to be able to dynamically set the sequence just for order.

like image 902
Saša Kalaba Avatar asked Aug 30 '18 14:08

Saša Kalaba


People also ask

What is Factoryboy?

factory_boy is a fixtures replacement based on thoughtbot's factory_bot. As a fixtures replacement tool, it aims to replace static, hard to maintain fixtures with easy-to-use factories for complex objects.

What is DjangoModelFactory?

DjangoModelFactory is a basic interface from factory_boy that gives "ORM powers" to your factories. It's main feature here is that it provides you with a common "create" and "build" strategies that you can use to generate objects in your tests.


1 Answers

Just in case someone find it helpful.

I've found this post trying to implement negative sort order sequence. And only in the create_batch call. So my use-case was

 MyModelFactory.create_batch(
     9,
     sort_order=factory.Sequence(lambda n: 10-n))
like image 125
Fallen Flint Avatar answered Oct 11 '22 15:10

Fallen Flint