如何在Django中使用Factory Boy将值传递给依赖模型?

时间:2016-09-17 10:51:24

标签: python django factory-boy

林'在开源django网络应用程序上工作,我希望使用Factory Boy来帮助我为某些测试设置模型,但是几个小时后阅读文档并查看示例,我想我需要接受失败并在这里问。

我的客户模型看起来有点像这样:

class Customer(models.Model):

    def save(self, *args, **kwargs):
        if not self.full_name:
            raise ValidationError('The full_name field is required')
        super(Customer, self).save(*args, **kwargs)


    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name='customer',
        null=True
    )

    created = models.DateTimeField()
    created_in_billing_week = models.CharField(max_length=9)
    full_name = models.CharField(max_length=255)
    nickname = models.CharField(max_length=30)
    mobile = models.CharField(max_length=30, default='', blank=True)
    gocardless_current_mandate = models.OneToOneField(
        BillingGoCardlessMandate,
        on_delete=models.SET_NULL,
        related_name='in_use_for_customer',
        null=True,
    )

我也在使用django.contrib.auth的标准Django用户模型。

这是我的工厂代码:

class UserFactory(DjangoModelFactory):

    class Meta:
        model = get_user_model()


class CustomerFactory(DjangoModelFactory):

    class Meta:
        model = models.Customer

    full_name = fake.name()
    nickname = factory.LazyAttribute(lambda obj: obj.full_name.split(' ')[0])

    created = factory.LazyFunction(timezone.now)
    created_in_billing_week = factory.LazyAttribute(lambda obj: str(get_billing_week(obj.created)))

    mobile = fake.phone_number()

    user = factory.SubFactory(UserFactory, username=nickname,
        email="{}@example.com".format(nickname))

就我而言,我希望能够像这样生成客户

CustomerFactory(fullname="Joe Bloggs")

并使用正确的用户名和电子邮件地址生成相应的用户。

现在,我收到了这个错误:

  AttributeError: The parameter full_name is unknown. Evaluated attributes are {'email': '<factory.declarations.LazyAttribute object at 0x111d999e8>@example.com'}, definitions are {'email': '<factory.declarations.LazyAttribute object at 0x111d999e8>@example.com', 'username': <DeclarationWrapper for <factory.declarations.LazyAttribute object at 0x111d999e8>>}.

我认为这是因为我在客户中依赖于懒惰属性,在创建用户工厂之前不会调用该属性。

对于它的价值,可以看到完整模型here on the github repo

1 个答案:

答案 0 :(得分:1)

在这种情况下,最好的方法是从the customer declarations中选择值:

class CustomerFactory(DjangoModelFactory):

    class Meta:
        model = models.Customer

    full_name = factory.Faker('name')
    nickname = factory.LazyAttribute(lambda obj: obj.full_name.split(' ')[0])

    created = factory.LazyFunction(timezone.now)
    created_in_billing_week = factory.LazyAttribute(lambda obj: str(get_billing_week(obj.created)))

    mobile = factory.Faker('phone_number')

    user = factory.SubFactory(
        UserFactory,
        username=factory.SelfAttribute('..nickname'),
        email=factory.LazyAttribute(lambda u: "{}@example.com".format(u.username)))
    )

另外,使用factory.Faker('field_name')获取每个实例的随机值:类声明中的行fullname = fake.name() 等同于:

DEFAULT_FULL_NAME = fake.name()

class CustomerFactory(DjangoModelFactory):
    full_name = DEFAULT_FULL_NAME

    class Meta:
        model = models.customer

factory.Faker('name')相当于:

class CustomerFactory(DjangoModelFactory):
    full_name = factory.LazyFunction(fake.name)

    class Meta:
        model = models.customer

fake.name()将为使用此工厂构建的每个模型提供不同的名称。