Last Updated: February 25, 2016
· hso

Speed up your Django tests

If you use django.test.TestCase to write your tests, most of the time you'll be preparing model instances in your setUp method:

from django.utils import unittest
from myapp.models import Animal

class AnimalTestCase(unittest.TestCase):
    def setUp(self):
        self.lion = Animal(name="lion", sound="roar") = Animal(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        self.assertEqual(self.lion.speak(), 'The lion says "roar"')
        self.assertEqual(, 'The cat says "meow"')

As your test cases grow, they take more and more time to run, partly because at the start of each test, before setUp() is run, Django will flush the database, returning the database to the state it was in directly after syncdb was called.

You can save some time using a class method instead:

def setUpClass(cls):
        cls.lion = Animal(name="lion", sound="roar") = Animal(name="cat", sound="meow")

Doing so will create the objects once per test case, speeding up your tests.