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?
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 ...
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.
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
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.'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With