Reputation: 7301
I've been going through a lot of Django testing tutorials, but I'm a bit unsure as to how much to test. I'm primarily using classed based views
For instance, in testing my views, should I check all of the following:
Most of my views are class based views. I have a ListView, where I set the template_name, model and context_object_name. Should I be testing that these have been set correctly? There is no logic there so it seems a bit silly to test it since it is just configuration.
In testing models:
In testing forms (especially model forms)
A lot of these tests seems like I'm just testing configuration as opposed to logic. I know how to tests all the items as mentioned above, but when using class based views, the testing code can be 10x the amount of actuall code if I try to test everything.
So, my current idea is to test only places in my app where I add logic, not where it is only configuration. So if I override a method in a model form or in a view, I'll test that. Does this sound like a good approach or should I really be testing every little thing as mentioned above?
Upvotes: 4
Views: 77
Reputation: 5993
I suggest you to start with functional tests. They are for testing your entire stack, from the bottom up. For example, you have a model, a form, and a creation view. So you could have a test which just makes sure a user can open the creation form, and submitting that form results in the creation of an object. Just like a user does:
class CreationTestCase(TestCase):
def test_creation_page_get(self):
url = reverse('your_model_create')
response = self.client.get(url)
# Your page gave 200, so there are no severe configuration errors
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'your/template.html')
# The template context contains your form, so most probably you view did fine.
self.assertEqual(type(response.context['form']), YourForm)
def test_creation_page_post(self):
payload = {'field1': 1, 'field2': 2}
response = self.client.post(reverse('your_model_create'), payload)
# Your page redirected to a success url, so the view did ok.
self.assertRedirects(response, reverse('your-success-url'))
# The instance is actually created and contains the right data
instance = YourModel.objects.first()
self.assertEqual(instance.field1, payload['field1'])
Here we tested your urlconf, views, forms and models, by emulating user behaviour. Plus, you're free to change your underlying views and forms, keeping the same user workflow.
The biggest drawback of functional testing is speed. As you test your whole application, your testcase might take a lot of time.
Personally I tend to writing unit tests when I see the chunk of logic in the code I want to refactor, or it just seems to deserve testing.
In other words, test the behaviour, not the configuration.
Upvotes: 2