【问题标题】:testing django forms with pytest failing使用 pytest 测试 django 表单失败
【发布时间】: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


【解决方案1】:

问题在于monthForeignKey,所以你需要在data 中传递对象ID,如下所示:

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

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

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 2016-11-02
    • 2016-06-02
    • 2019-09-14
    • 2018-04-05
    • 2021-02-06
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多