Math and Pencil writes a lot of unit tests in Django. Over the years, we have compiled a number of helpers we use across multiple projects. Here is a list of “best practices” we have compiled.
Split your unit tests into separate files. It makes maintaining them much easier, and it also allows you to run a single test or a set of tests from the command line. The following is an example directory structure from a Math & Pencil
Writing Unit Tests With Session Data
In general, avoid storing state-based data in a session. If you are going to store something in a session, and you want a unit test to make sure the view or code is working properly, you can bootstrap your session in your setUp function as follows:
In the example above, I am bootstrapping my session with the variable page_id.
Sometimes private functions in Django can take requests as input parameters. If you need to unit test these
functions, you are going to need access to a Django request. You can use this class to gain access to the request object
Your unit test would look something like this:
Use Python Mock
The mock module has a number of built in methods that enhance unit testing. You can use the module to mock api calls, patch classes/functions, deleting attributes, etc. Add this to your arsenal as soon as possible.
If you have account data, user data, company data, address, etc … you no longer have to hard code them thanks to Faker. Faker generates a variety of different data, randomly, and is extremely useful in unit tests and for bootstrapping data.
Testing AJAX Calls
Testing AJAX calls isn’t hard, but you should always load the response as JSON (using your favorite JSON module) and then write test to ensure the correct data is returned.
If you have a view or function that sends and email, Django has built in unit testing modules to let you test if the email was sent. It also lets you check the content (subject + body) of the email.
Mocking the Facebook API
Do you use Facebook’s Graph API? If so, we develop this class to mock the facebook API in unit tests:
You can use this class in a unit tests as follows:
If you are interested in Django, machine learning, math, and/or statistics you can following me on twitter: @josephmisiti
If you need help with Django or Machine Learning, contact my firm at firstname.lastname@example.org