Best practices:
- If it can break, it should be tested. This includes models, views,
forms, templates, validators, and so forth.
- Each test should generally only test one function.
- Keep it simple. You do not want to have to write tests on top of
other tests. Run tests whenever code is PULLed or PUSHed from the
repo and in the staging environment before PUSHing to production.
When upgrading to a newer version of Django:
-upgrade locally,
-run your test suite,
-fix bugs,
-PUSH to the repo and staging, and then
-test again in staging before shipping the code.
https://realpython.com/blog/python/testing-in-django-part-1-best-practices-and-examples/
Django provides a small set of tools that come in handy when writing tests.
The test client
The test client is a Python class that acts as a dummy Web browser, allowing you to test your views and interact with your Django-powered application programmatically.
Some of the things you can do with the test client are:
- Simulate GET and POST requests on a URL and observe the response –
everything from low-level HTTP (result headers and status codes) to
page content.
- See the chain of redirects (if any) and check the URL and status code
at each step.
- Test that a given request is rendered by a given Django template,
with a template context that contains certain values.
Overview and a quick example
To use the test client, instantiate django.test.Client and retrieve Web pages:
from django.test import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
200
response = c.get('/customer/details/')
response.content
'<!DOCTYPE html...'
As this example suggests, you can instantiate Client from within a session of the Python interactive interpreter.
Testing responses
The get() and post() methods both return a Response object. This Response object is not the same as the HttpResponse object returned by Django views; the test response object has some additional data useful for test code to verify.
Making requests
Use the django.test.Client class to make requests.
class Client(enforce_csrf_checks=False, **defaults)
Exceptions
If you point the test client at a view that raises an exception, that exception will be visible in the test case. You can then use a standard try ... except block or assertRaises() to test for exceptions.
Provided test case classes
Normal Python unit test classes extend a base class of unittest.TestCase. Django provides a few extensions of this base class:
Hierarchy of Django unit testing classes (TestCase subclasses)
Hierarchy of Django unit testing classes
For detailed information and more examples visit https://docs.djangoproject.com/en/1.7/topics/testing/tools/