django-crispy-form:单元测试由于辅助对象的TypeError而失败

时间:2014-07-22 22:26:38

标签: python django unit-testing django-crispy-forms django-unittest

有些基于this book的章节,我想对使用django-crispy-form创建的表单进行单元测试,但我收到以下错误:

  

TypeError:提供给{%crispy%}标记的辅助对象必须是crispy.helper.FormHelper对象。

表单(myapp/forms.py):

class MyBaseForm(forms.models.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyBaseForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-myForm'
        self.helper.form_method = 'POST'
        self.helper.form_action = ''
        self.helper.add_input(Submit('submit', 'Create'))

    class Meta:
        model = MyModel
        # [...]

class MyNewForm(MyBaseForm):

    def save(self):
        return MyModel.create_new(data=self.cleaned_data['data'])

视图(myapp/views.py):

@login_required
def event_new(request):
    if request.method == 'POST':
        form = MyNewForm(data=request.POST)
        if form.is_valid():
            event = form.save()
            return redirect(event)
    else:
        form = MyNewForm()
return render(request, 'event_new.html', {'form': form})

测试:

@patch('myapp.views.MyNewForm')
class MyNewViewUnitTest(TestCase):

    def setUp(self):
        self.t = unittest.TestCase()
        self.t.request = HttpRequest()
        self.t.request.POST['data'] = 'data'
        self.t.request.user = Mock()

    def test_passes_POST_data_to_Form(self, mockMyNewForm):
        event_new(self.t.request)
        mockMyNewForm.assert_called_once_with(data=self.t.request.POST)

我是否还要以某种方式模拟辅助对象?那会怎么做?非常感谢你!

1 个答案:

答案 0 :(得分:2)

迟到的答案,但今天遇到了这个问题。您需要将模拟类的帮助程序指定为FormHelper,以便在crispy模板中调用“isinstance”。最简单的方法是为crispy形式创建一个MagicMock子类:

class MockCrispyForm(MagicMock):
    helper = MagicMock(spec=FormHelper)
    helper.template = False  # necessary for templates to render
    def is_valid(self):
        return True  # optional if you want form to validate

@patch('myapp.views.MyNewForm', MockCrispyForm())
class MyNewViewUnitTest(TestCase):
    def setUp(self):
        self.t = unittest.TestCase()
        self.t.request = HttpRequest()
        self.t.request.POST['data'] = 'data'
        self.t.request.user = Mock()

    def test_passes_POST_data_to_Form(self):
        event_new(self.t.request)
        myapp.views.MyNewForm.assert_called_once_with(
            data=self.t.request.POST
        )