Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test formsets in Django?

Ok, so i need to unit test a view, more precise form in a view . So 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.')

Ofcourse i get back an error

AttributeError: 'ShareholderFormFormSet' object has no attribute 'fields'

Because formset has forms in it, not fields..... So what is the correct way to test a formset?

like image 585
Viktor Avatar asked May 14 '13 13:05

Viktor


People also ask

How do you write a test case in Django project?

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...

Does Django use Unittest?

Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.


2 Answers

That's a functional test (since you go through the view, request possibly the model if you save it, etc.).

For the forms, django-webtest is a lot easier to use; you won't have to worry about these details with it: https://pypi.python.org/pypi/django-webtest

like image 102
François Constant Avatar answered Nov 15 '22 10:11

François Constant


Django now has implemented an assertFormsetError.

django-basetestcase has a feature that will let you test the formset apart from the view, not requiring a response.

formset = MyFormSet(formset_data)

self.formset_error_test(
    formset,
    form_index=3,
    field='my_field',
    message='My error message.'
)
like image 33
Carl Brubaker Avatar answered Nov 15 '22 09:11

Carl Brubaker