0

我正在使用工厂男孩来测试一些模型(不是 django),我想知道如何显示一个包含另一个工厂多个实例的列表的字段。例如具有类UserGroup

class User:
  name = StringType(required=True)

class Group:
  name = StringType(required=True)
  user = ModelType(User)

我想在用户工厂中显示一个名为的字段,其中包含该用户所属的所有组。运行工厂时默认显示两组[' group1 ',' group2 ']。

class UserFactory:
    name = factory.Faker('first_name')
    groups = factory.RelatedFactory(GroupFactory, 'user')

    class Meta:
        model = User


class GroupFactory:
    name = factory.Faker('word')
    user = factory.SubFactory(UserFactory)

    class Meta:
        model = Group

我曾尝试使用如上所示的相关工厂,但我不知道如何为相关字段定义默认值。是否有任何工厂男孩大师可以为这个问题带来一些启示?

4

1 回答 1

2

这在工厂男孩文档的通用食谱部分中提到:http: //factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship

如果您像在文档中一样创建 UserFactory,那么您可以在使用 UserFactory 时提供组:

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

    name = "John Doe"

    @factory.post_generation
    def groups(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for group in extracted:
                self.groups.add(group)

你可以像这样使用它:

group1 = GroupFactory()
UserFactory.create(groups=[group1,])

如果要为工厂创建的每个用户提供默认组,则可以在 if 中添加 else 子句:

@factory.post_generation
def groups(self, create, extracted, **kwargs):
    if not create:
        # Simple build, do nothing.
        return

    if extracted:
        # A list of groups were passed in, use them
        for group in extracted:
            self.groups.add(group)
    else:
        self.groups.add(GroupFactory(name='default group 1'))

文档中的示例使用的是 Django,所以我也在答案中使用了它。

于 2017-01-09T08:30:48.907 回答