Search code examples
pythonpython-2.7testingmockingfactory-boy

How to specify list size using FactoryBoy


Let's assume i have this model:

class FooContainerModel(object):
    def __init__(self, foos):
        self.foos = foos

I want to be able to decide how many foos will be created at creation time, eg.

model = FooContainerFactory(count=15)

Tried factories like

class FooContainerFactory(factory.Factory):
    class Meta:
        model = FooContainerModel

    foos = factory.List([Foo() for _ in xrange(20)]) # fixed amount
    foos = factory.lazy_attribute(lambda o: [Foo() for _ in xrange(20)]) # same

Of course I can manually create list of Foo() with desired length and instantiate FooContainerModel, but it's not what I want. Any solutions?


Solution

  • I've got no idea how FactoryBoy works, but this strategy usually works for me when I need dynamic properties on fields in Django models:

    def FooContainerFactory(factory.Factory):
    
        def __init__(self, count=20, *args, **kwargs):
            self.foos = factory.List([Foo() for _ in range(20)])
            super(FooContainerFactory, self).__init__(*args, **kwargs)
    
        class Meta:
            model = FooContainerModel