Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

factory-boy create a list of SubFactory for a Factory

I am using django 1.6 and factory-boy.

class UserFactory(factory.Factory):
   class Meta:
      model = models.User

   username = factory.Sequence(lambda n: 'user%d' % n)

Here username is a simple CharField in model. So that each time I am calling UserFactory() I am saving and getting unique user named object.

In factory-boy I can use factory.SubFactory(SomeFactory).

How I can generate list of SomeFactory in ParentOfSomeFactory ?

So that, if I call ParentOfSomeFactory() I will create list of SomeFactory as well as ParentOfSomeFactory database

like image 217
Saiful Azad Avatar asked Nov 09 '16 12:11

Saiful Azad


2 Answers

Use factory.List:

class ParentOfUsers(factory.Factory):
    users = factory.List([
        factory.SubFactory(UserFactory) for _ in range(5)
    ])
like image 181
Paul Avatar answered Nov 19 '22 10:11

Paul


You could provide a list with factory.Iterator

import itertools
import factory

# cycle through the same 5 users
users = itertools.cycle(
    (UserFactory() for _ in range(5))
)

class ParentFactory(factory.Factory):
    user = factory.Iterator(users)
like image 4
Ryan Ginstrom Avatar answered Nov 19 '22 09:11

Ryan Ginstrom