In this post, I introduce testing in Django and discuss the two common ways of performing tests: using Doctests and using the library unittest.
You’ll learn how to start writing your first test as well as the main differences between these two ways of testing.
Note: this post uses the old Test Suit, used in Django < 1.6. This is because I prefer how it discovers my test files. If you don’t like it… wait for a post on Nose, which will come soon 🙂
Introduction to Django Testing
There are two different types of tests:
– Unit tests are isolated tests that cover a very small and specific area of code, like a single function of your application.
– Integration tests are larger tests that cover multiple aspects of your application, and ensure that all its functionalities are well integrated with each other.
I recommend you focus on unit tests. They are much easier to write and debug, and the more unit tests you have, the less integration tests you’ll need to write. Moreover, unit tests should be faster, so write a looot of them 🙂
You’ll see that inside each app folder of your project there is a tests.py file. Here, we will substitute this file by a directory named tests that will contain our tests, grouped in different files depending on what they are testing, i.e. models, views, forms, etc. Don’t forget to create an empty __init__.py file inside this folder, to indicate it is as a module.
$ cd myapp
$Â rm tests.py
$Â mkdir tests
$Â cd tests
$Â touch __init__.py tests_forms.py tests_models.py tests_views.py
To run your tests you should type:
$ python manage.py test myapp
In my case, I got an error saying
Creating test database for alias ‘default’…
Got an error creating the test database: permission denied to create database
Type ‘yes’ if you would like to try deleting the test database ‘test_myprojectdb’, or ‘no’ to cancel:Â
This was because I was using PostgreSQL and the postgres user defined in my settings.py, with a given username, file didn’t have permissions to create a database. If it your case, you can solve this by giving that user the requested permissions:
$ psql -h localhost
# ALTER USER username CREATEDB;
# \q
This time, your tests should run correctly.
This post focuses on testing using the old Test Suite. If you are using Django 1.6 you can obtain the old behavior by including the following in your settings.py file
TEST_RUNNER = ‘django.test.simple.DjangoTestSuiteRunner’
There are to different ways of writing a test using: Doctests and Unittests. We’ll explain each of them in detail.
Doctests
Doctests are tests written inside a string. They can be placed either in one of the test files inside the test folder, or in the models.py file. These two places are the ones that the test runner will look for doctests. An example of such a test is given in the Django docs:
File: marinamele_doctest_django_example.py
------------------------------------------
# Based on Example in https://docs.djangoproject.com/en/1.5/topics/testing/doctests/
from django.db import models
class Animal(models.Model):
"""
An animal that makes noise
# Create an animal
>>> lion = Animal.objects.create(name="lion", sound="roar")
# Test it makes the correct noise
>>> lion.speak()
'The lion says "roar"'
"""
name = models.CharField(max_length=20)
sound = models.CharField(max_length=20)
def speak(self):
return 'The %s says "%s"' % (self.name, self.sound)
Notice that the doctest format is simply the output of your Pyhton shell. Therefore, if you are testing in your shell and it works, you can make a simple copy and paste to create the doctest 🙂
If you place doctests in the tests folder, in a file named mydoctests.py, you’ll have to edit the __init__.py file to indicate the test runner that that file contains doctests. Open the __init__.py file and write:
import mydoctests
__test__ = {‘Doctest’: mydoctests}
Moreover, when you run your doctests with
$ python manage.py test myapp
you will see something like
Ran 1 test in 0.005s OK
which indicates that all your doctests were ok. Yes, the test runner sees all your doctests as a single one test. This is why I like better the second option for writing tests 🙂
Unittests
On the other hand, we can write tests using the library unittest. An example of a unit test is:
File: marinamele_unittest_example.py
------------------------------------
from django.test import TestCase
class TestExample(TestCase):
"""
Here you can define multiple tests, but all must begin
with test_
"""
def setUp(self):
"""
Optional. Define here your initial setup for your tests
"""
self.a = "my test"
def tearDown(self):
"""
Optional. This will be executed after running your tests
"""
del self.a
def test_example(self):
self.assertEqual("my test", self.a)
def test_example2(self):
b = 2
self.assertNotEqual(b, "two")
Note that we import django.test.TestCase, which enhances the unittest.TestCase class, and then create our tests as functions. We can also use the setUp function to define a initial context in which all these tests will be run and an ending tearDown function that will be executed at the end of each test.
Hope it is useful! 🙂
+1 if you want to read more about testing in Django!
Learn how to perform Doctests and Unittest in #Django http://t.co/fwZjpITgOk
— Marina Mele (@Marina_Mele) March 9, 2014
Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)