Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Erik Svedin
Author

Share


Creating fixtures for testing in Django

Erik SvedinErik Svedin

When running tests Django automatically creates a clean database using the same settings you have in your settings.py file. However if we want to test some behaviour that has to do with our models we need to fill the database with some content. Since manually creating every model we want to test is quite an annoying task, a better way to approach this is using fixtures.

What are fixtures and how to create them?

Fixtures is basically a known set of data which will fill up the database. A simple way to create fixtures is to dump your existing database. This can be done on a per app level by running:

python manage.py dumpdata APP_NAME > APP_NAME/fixtures/APP_NAME_TESTDATA.json

This will dump your apps data to a json file under the fixtures directory in your app. Other available formats are .xml and .yaml (see https://docs.djangoproject.com/en/1.8/ref/django-admin/#dumpdata-app-label-app-label-app-label-model for more options).

In your settings.py file you will need to tell django about where your fixtures reside like this:

FIXTURE_DIRS = ('APP_NAME/fixtures/')

Using fixtures when running tests

The last step in the tutorial is to actually use the testdata we generated in our tests. Your testcase should be subclassing the TestCaseclass from the django.test module. Then all you need to do is add the fixtures attribute to it:
fixtures = ['APP_NAME_TESTDATA.json']

Erik Svedin
Author

Erik Svedin

Comments