None

Creating Django Test Fixture

December 8, 2009

To dump the contents of a database to a json format file in order to use it as a test fixture:

./manage.py dumpdata --indent=2 > test_fixture.json

This will dump all applications in a project. Try and keep the size of the fixture down; it is loaded and removed before and after each test in your project is run.

Content Types

Because django automatically adds content types into the database when it does a syncdb, you'll need to remove all of the entries for "model": "contenttypes.contenttype" from the json file.

You can also remove some of the other models to make your fixture smaller:

  • sessions.session
  • auth.permission
  • sites.site (if you're not using the sites framework)
  • admin.logentry

Loading the fixture in a test

To load the fixture in a django test, declare it at the top of the file:

from django.test.client import Client
from django.test import TestCase

class HomeTestCase(TestCase):
    fixtures = ['test_fixture.json']

    def testHome(self):
        c = Client()
        response = c.get('/')
        self.assertEquals(response.status_code, 200)

        response = c.get('/sitemap.xml')
        self.assertEquals(response.status_code, 200)

For this to work the test_fixture.json file must be inside a fixtures dir inside an application, or in the directory specified by the FIXTURE_DIRS setting (similar to TEMPLATE_DIRS). If it can't find the fixture, you won't get an error, it'll just not load the data.

Tags: django test fixture json