FactoryBoy为SubFactory的属性赋值属性

时间:2013-07-31 18:55:56

标签: python django unit-testing factory-boy

在FactoryBoy中定义ModelFactory时,我需要访问SubFactory创建的另一个模型的属性,并将其分配给此ModelFactory的属性。

这就是我想要做的事情:

import factory
class MyModelFactory(factory.DjangoModelFactory):
    FACTORY_FOR = MyModel

    created_by = factory.SubFactory(AdminUserFactory)**.id**

显然这不起作用,因为没有AdminUser对象来访问MyModelFactory类定义中的id。

这就是我所做的,但它很难看:

import factory
class MyModelFactory(factory.DjangoModelFactory):
    FACTORY_FOR = MyModel

    dummy_created_by = factory.SubFactory(AdminUserFactory)
    created_by = factory.LazyAttribute(lambda o: o.dummy_created_by.id)

    @classmethod
    def _create(cls, target_class, *args, **kwargs):
        del kwargs['dummy_created_by']
        return super(MyModelFactory, cls)._created(
            target_class, *args, **kwargs)

我试图通读Factory_Boy docs,但没有看到允许我懒惰地访问该属性的类或函数。有没有人有任何建议?

3 个答案:

答案 0 :(得分:3)

从factoryboy 2.4.0开始,您可以使用exclude。这使您可以向工厂添加一个不会传递到模型类的参数

import factory
class MyModelFactory(factory.DjangoModelFactory):
    created_by = factory.SubFactory(AdminUserFactory)
    created_by_id = factory.LazyAttribute(lambda o: o.created_by.id)

    class Meta:
        model = MyModel
        exclude = ['created_by']

我已经将OP示例转换为使用created_by_id,但是您可以对其进行重命名以使其对您有意义。

答案 1 :(得分:2)

使用SelfAttribute

class MyModelFactory(factory.django.DjangoModelFactory):
    FACTORY_FOR = MyModel
    dummy_created_by = factory.SubFactory(AdminUserFactory)
    created_by = factory.SelfAttribute('dummy_created_by.id')

答案 2 :(得分:0)

尝试使用Mixer

from mixer.backend.django import mixer

mixer.blend(MyModel, created_by=lambda: mixer.blend(AdminUser).id)