Django:如何对更新视图/表单进行单元测试 [英] Django: How to unit test Update Views/Forms

查看:25
本文介绍了Django:如何对更新视图/表单进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的更新表单和视图进行单元测试.我在创建和更新表单中都使用了 Django Crispy Forms.UpdateForm 继承了 CreateForm 并对提交按钮文本进行了小的更改.CreateView 和 UpdateView 非常相似.它们具有相同的模型、模板和 success_url.它们的区别在于使用各自的表单,CreateView继承django.views.generic.CreateView,UpdateView继承django.views.generic.edit.UpdateView.

I'm trying to unit test my update forms and views. I'm using Django Crispy Forms for both my Create and Update Forms. UpdateForm inherits CreateForm and makes a small change to the submit button text. The CreateView and UpdateView are very similar. They have the same model, template, and success_url. They differ in that they use their respective forms, and CreateView inherits django.views.generic.CreateView, and UpdateView inherits django.views.generic.edit.UpdateView.

网站运行良好.我可以毫无问题地创建和编辑对象.但是,我下面显示的第二个测试失败了.如何测试我的 UpdateForm?

The website works fine. I can create and edit an object without a problem. However, my second test shown below fails. How do I test my UpdateForm?

任何帮助将不胜感激.谢谢.

Any help would be appreciated. Thanks.

此测试通过:

class CreateFormTest(TestCase):

    def setUp(self):
        self.valid_data = {
            'x': 'foo',
            'y': 'bar',
        }

    def test_create_form_valid(self):
        """ Test CreateForm with valid data """
        form = CreateForm(data=self.valid_data)
        self.assertTrue(form.is_valid())
        obj = form.save()
        self.assertEqual(obj.x, self.valid_data['x'])

此测试失败:

class UpdateFormTest(TestCase):
    def setUp(self):
        self.obj = Factories.create_obj()  # Creates the object

    def test_update_form_valid(self):
        """ Test UpdateForm with valid data """
        valid_data = model_to_dict(self.obj)
        valid_data['x'] = 'new'
        form = UpdateForm(valid_data)
        self.assertTrue(form.is_valid())
        case = form.save()
        self.assertEqual(case.defendant, self.valid_data['defendant']

推荐答案

当使用已经创建的对象预填充 ModelForm 时,您可以使用 instance将对象传递给表单的关键字参数.

When pre-populating a ModelForm with an object that has already been created you can use the instance keyword argument to pass the object to the form.

form = SomeForm(instance=my_obj)

这可以在测试中完成,例如在 OP<;或在视图中编辑已创建的对象.调用 save() 时,现有对象将更新而不是创建新对象.

This can be done in a test, such as in the OP< or in a view to edit an object that has already been created. When calling save() the existing object will updated instead of creating a new one.

这篇关于Django:如何对更新视图/表单进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆