【发布时间】:2020-03-12 16:15:19
【问题描述】:
我不确定为什么下面的断言失败了。
有人可以给我反馈吗,我是 django pytest 的新手。
test.forms
@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
models.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',
]
非常感谢您的反馈,以帮助我了解在使用夹具时尝试使用数据测试此表单时我做错了什么。
【问题讨论】:
-
请分享
ProductForm的代码。另外,一个不相关的说明:你不需要调用save(),create方法已经为你保存了对象。 -
@bug 我刚刚更新了forms.py
-
抱歉,既然是ModelForm,还需要分享
Product:) -
@bug 我已经在上面更新了
标签: python django python-3.x forms unit-testing