python - Django/python 测试 django 表单

标签 python django unit-testing django-forms

我正在测试我的项目,我需要测试django表单,但我不知道该怎么做,这是代码

if request.method == 'POST': # If the form has been submitted...
    name_add = request.POST.get("name")
    form = AddForm(request.POST) # A form bound to the POST datas
    not_add = 0
    if form.is_valid(): # All validation rules pass
        for n in Product.objects.filter(dashboard = curr_dashboard):
            if n.name == name_add:
                not_add = 1
        if not_add != 1:
            obj = form.save(commit=False)
            obj.dashboard = curr_dashboard
            obj.save()
            curr_buylist.add_product(obj.id)
            return HttpResponseRedirect(request.get_full_path()) # Redirect after POST
        else:
            forms.ValidationError("You already have this")
            return HttpResponseRedirect(request.get_full_path())

我在这里验证它并添加到数据库。但我该如何测试呢?这是我在测试中写的

def test_index_form(self):
    request = self.factory.post('main/index')
    request.user = User.objects.get(username= 'admin')
    response = index(request)

    self.assertEqual(response.status_code, 200)

最佳答案

我认为你的测试是一个好的开始。不幸的是,它只是测试表单无效的情况。除了测试状态代码之外,我还会测试是否正在加载正确的模板,也许还会测试未绑定(bind)的表单是否在上下文中(基本上测试 View 中的正确条件是否按预期执行):

self.assertTemplateUsed(response, 'your_template.html')
self.assertIsInstance(response.context['form'], AddForm)

在测试中提供有效的表单数据并确保按预期创建新对象也是一个想法。

将无效数据发布到您的 View 并检查是否按预期发出重定向也是一个好主意

关于python - Django/python 测试 django 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19521853/

相关文章:

python - Matplotlib:曲线接触轴边界。如何解决这个问题?

python - python 中有没有一种方法可以更改 yield from get 的处理顺序?

python - 在 Tkinter 中隐藏 TreeView 列

c# - 如何使用 Moq 模拟 SqlDataReader - 更新

javascript - Jasmine 期待(结果代码)。toBe(200 或 409)

python - 如果仅使用两个级别,Matplotlib 轮廓剖面线将不起作用

python - Django 下载名称为变量的 csv 文件

javascript - django 管理界面 change_form.html 将数据添加到 querydict/post?

python - 如何从 Python (Django) 中的 Google Analytics 获取最受欢迎的页面列表?

php - 使用 Laravel 5.5 中的 View 创建单元测试邮件将不起作用