factory-boy create a list of SubFactory for a Factory
Asked Answered
S

2

21

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

Samella answered 9/11, 2016 at 12:35 Comment(2)
Just to make sure, even if you create a list of sub factories, the field type is still non-list type field, how you wanted to handle it? in your example, what would you do if the lambda would return list?Griner
what would you do if the lambda would return list? So that if I call ParentOfSomeFactory() It will automatically create and save a list of SomeFactory model at database. I dont want to create it manually.Samella
S
37

Use factory.List:

class ParentOfUsers(factory.Factory):
    users = factory.List([
        factory.SubFactory(UserFactory) for _ in range(5)
    ])
Syllabify answered 15/3, 2018 at 12:6 Comment(0)
A
5

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)
Assail answered 6/8, 2017 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.