Saiful Azad
Saiful Azad

Reputation: 1921

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

Upvotes: 21

Views: 13860

Answers (2)

Ryan Ginstrom
Ryan Ginstrom

Reputation: 14121

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)

Upvotes: 5

Paul
Paul

Reputation: 471

Use factory.List:

class ParentOfUsers(factory.Factory):
    users = factory.List([
        factory.SubFactory(UserFactory) for _ in range(5)
    ])

Upvotes: 37

Related Questions