How do you unit test form sets in Django?

Ok, so I need a unit test view, a more accurate form in the view. Therefore, I create such a unit test.

class ViewTest(TestCase): fixtures = ['fixture.json'] def setUp(self): self.client = Client() def test_company_create(self): post_data = { 'form-0-user': '', 'form-0-share': '', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': 10 } resp = self.client.post('/company/create/', post_data) self.assertFormError (resp, 'shareholder_formset', 'share', 'This field is required.') self.assertFormError (resp, 'shareholder_formset', 'user', 'This field is required.') 

Of course, I will return to the error

AttributeError: The "ShareholderFormFormSet" object does not have a 'field' attribute

Since formet has forms in it, not fields ..... So, what is the correct way to test a set of forms?

+6
source share
3 answers

This is a functional test (since you are viewing the view, perhaps ask for a model if you save it, etc.).

For forms, django-webtest is much easier to use; you don’t have to worry about these details: https://pypi.python.org/pypi/django-webtest

+2
source

As you point out, the form name argument in assertFormError is actually just the key in response.context_data. The key you use returns a list of forms in the form set. So, as you have discovered, it does not work with assertFormError.

One option is to use assertEqual and just do a direct comparison. Sort of:

 self.assertEqual(response.context_data[u'shareholder_formset'][form_index].errors['share'], 'This field is required.') 

I would also like to mention that my IDE (PyCharm) helped a lot with this. I worked on a similar problem. Turning on the debugger, setting a breakpoint after calling post () and checking the answer, gave a solution.

0
source

Django-basetestcase has some features that will help with this.

0
source

Source: https://habr.com/ru/post/944975/


All Articles