Unit Test Fixtures¶
Overview¶
Fixtures in Django are essentially dumps of part of the database. They contain data for the various models and can be loaded in automatically for unit tests. This makes it quite easy for us to have various sets of data to test against.
For our tests, we currently have three sets of fixtures:
- reviewboard/accounts/fixtures/test_users.json - accounts/auth apps
- reviewboard/reviews/fixtures/test_reviewrequests.json - diffviewer/reviews apps
- reviewboard/scmtools/fixtures/test_scmtools.json - scmtools app
- reviewboard/site/fixtures/test_site.json - site app
Updating Fixtures¶
If you’re going to add to the existing fixtures, you’ll first want to modify settings_local.py, set your database to be sqlite3 (if it’s not already) and change the database name to something like unittests.db. Then:
./reviewboard/manage.py syncdb --noinput
./reviewboard/manage.py reset --noinput scmtools
./reviewboard/manage.py loaddata test_users test_scmtools test_reviewrequests test_site
This should populate your database with the test data.
After you’ve added to the data set, dump them back out:
./reviewboard/manage.py dumpdata --indent=4 auth accounts > reviewboard/accounts/fixtures/test_users.json
./reviewboard/manage.py dumpdata --indent=4 attachments changedescs diffviewer reviews > reviewboard/reviews/fixtures/test_reviewrequests.json
./reviewboard/manage.py dumpdata --indent=4 scmtools > reviewboard/scmtools/fixtures/test_scmtools.json
./reviewboard/manage.py dumpdata --indent=4 site > reviewboard/scmtools/fixtures/test_site.json
You can choose to only dump the data you’ve actually modified. If you’ve only created a review request, for example, feel free to just dump the diffviewer and reviews apps.
Using Fixtures in Tests¶
Using fixtures in tests is really easy. In your test class (which must be derived from django.test.TestCase), add a fixtures = [...] line listing the fixtures you intend to use. For example:
class MyTests(TestCase):
fixtures = ['test_users', 'test_reviewrequests', 'test_scmtools']
...
Note that there are some dependencies to remember. test_users can be included by itself, as can test_scmtools, but if you want to use test_reviewrequests, you must include both test_users and test_scmtools.