在pytest失败的情况下测试django表单



我不确定下面的断言失败的原因。

有人能给我一个反馈吗?我是django的pytest新手。

测试表单

@pytest.fixture
def product():
month = Month.objects.create(name="november", slug="november")
user = User.objects.create(username="james", password="password")
obj = Product.objects.create(
user=user,
name="broom",
price=19.99,
quantity=1,
month=month,
)

data = {
'user':user,
'name':obj.name,
'price':obj.price,
'quantity':obj.quantity,
'month':month
}
form = ProductForm(data=data)
yield form
def test_product_form_with_data(product):
assert True is not None
assert True == product.is_valid()

以下是我从航站楼得到的信息。

追溯错误。

_______________________________________________________________________________________ test_product_form_with_data ________________________________________________________________________________________
product = <ProductForm bound=True, valid=False, fields=(name;price;quantity;month)>
def test_product_form_with_data(product):
assert True is not None
>       assert True == product.is_valid()
E       assert True == False
E         -True
E         +False
tests/test_forms.py:42: AssertionError

型号.py

class Product(models.Model):
month = models.ForeignKey(Month, on_delete=models.CASCADE, related_name='months')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
name = models.CharField(max_length=30)
slug = models.SlugField(max_length=30, db_index=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveSmallIntegerField(default=0)  
created = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=True)

forms.py

class ProductForm(ModelForm):
class Meta:
model = Product
fields = [
'name', 
'price', 
'quantity',
'month',
]

我真的很感谢你的反馈,帮助我理解我在使用fixture时试图用数据测试这个表单时做错了什么。

问题是monthForeignKey,因此您需要在data中传递对象ID,类似于以下内容:

data = {
'user':user,
'name':obj.name,
'price':obj.price,
'quantity':obj.quantity,
'month':month.pk,
}

对于user,您可能会遇到同样的问题,但实际上user不在表单处理的字段列表中(参见ProductForm.Meta.fields(,因此它将被忽略。您可以决定将其从数据中删除,也可以将其添加到fields中。

最新更新