我正在为以下Django模型创建工厂:
class Book(models.Model):
tenant = models.ForeignKey('elearning.Tenant')
book_id = models.IntegerField()
ean = models.CharField(max_length=13, null=False)
title = models.CharField(verbose_name="titel", max_length=200)
author_name = models.CharField(max_length=200)
description = models.TextField()
price_id = models.IntegerField()
buy_option_text = models.CharField(max_length=50)
loan_days = models.IntegerField(null=True)
type = 'Yindoboek'
我去了这家工厂:
class BookFactory(factory.django.DjangoModelFactory):
class Meta:
model = Book
tenant = factory.SubFactory(TenantFactory)
book_id = factory.LazyFunction(lambda: random.randint(1, 1000))
ean = factory.LazyFunction(
lambda: ''.join(
random.choice(string.ascii_uppercase) for _ in range(6)
) + ''.join(random.choice(string.digits) for _ in range(6))
)
title = factory.Faker('company')
author_name = factory.Faker('name_male')
description = factory.Faker('text')
price_id = factory.LazyFunction(lambda: random.randint(1, 1000))
buy_option_text = factory.Faker('sentence')
loan_days = factory.LazyFunction(lambda: random.randint(1, 150))
type = 'Yindoboek'
但是,当我尝试运行以下测试时:
def test_factory_matches_model(self):
""" Verify that the factory generates a valid Book instance """
self.assertTrue(self.book)
self.assertTrue(self.book.tenant)
它崩溃并显示以下错误:
TypeError: 'type' is an invalid keyword argument for this function
FactoryBoy似乎在type
模型中触发Book
'field',该模型不是Django字段实例,而是一个常量。
如果我从工厂排除此字段,则测试将通过-但我宁愿不删除字段(重点是测试所有字段/组合)-所以我想知道是否有解决此问题的方法,有人知道解决方案吗?
答案 0 :(得分:0)
我找到了答案:
根据documentation,非字段参数应放在单独的Params
类中。
工作模型如下:
class BookFactory(factory.django.DjangoModelFactory):
class Meta:
model = Book
tenant = factory.SubFactory(TenantFactory)
book_id = factory.LazyFunction(lambda: random.randint(1, 1000))
ean = factory.LazyFunction(
lambda: ''.join(
random.choice(string.ascii_uppercase) for _ in range(6)
) + ''.join(random.choice(string.digits) for _ in range(6))
)
title = factory.Faker('company')
author_name = factory.Faker('name_male')
description = factory.Faker('text')
price_id = factory.LazyFunction(lambda: random.randint(1, 1000))
buy_option_text = factory.Faker('sentence')
loan_days = factory.LazyFunction(lambda: random.randint(1, 150))
class Params:
type = 'Yindoboek'