Loading fixtures in django unit tests

I'm trying to start writing unit tests for django and I'm having some questions about fixtures:

I made a fixture of my whole project db (not certain application) and I want to load it for each test, because it looks like loading only the fixture for certain app won't be enough.

I'd like to have the fixture stored in /proj_folder/fixtures/proj_fixture.json.

I've set the FIXTURE_DIRS = ('/fixtures/',) in my settings.py. Then in my testcase I'm trying

fixtures = ['proj_fixture.json']

but my fixtures don't load. How can this be solved? How to add the place for searching fixtures? In general, is it ok to load the fixture for the whole test_db for each test in each app (if it's quite small)? Thanks!


Solution 1:

I've specified path relative to project root in the TestCase like so:

from django.test import TestCase

class MyTestCase(TestCase):
    fixtures = ['/myapp/fixtures/dump.json',]
    ...

and it worked without using FIXTURE_DIRS

Solution 2:

Good practice is using PROJECT_ROOT variable in your settings.py:

import os.path
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
FIXTURE_DIRS = (os.path.join(PROJECT_ROOT, 'fixtures'),)

Solution 3:

Do you really have a folder /fixtures/ on your hard disk?

You probably intended to use:

FIXTURE_DIRS = ('/path/to/proj_folder/fixtures/',)

Solution 4:

Instead of creating fixures folder and placing fixtures in them (in every app), a better and neater way to handle this would be to put all fixtures in one folder at the project level and load them.

from django.core.management import call_command

class TestMachin(TestCase):

    def setUp(self):
        # Load fixtures
        call_command('loaddata', 'fixtures/myfixture', verbosity=0)

Invoking call_command is equivalent to running :

 manage.py loaddata /path/to/fixtures 

Solution 5:

Saying you have a project named hello_django with api app.

Following are steps to create fixtures for it:

  1. Optional step: create fixture file from database: python manage.py dumpdata --format=json > api/fixtures/testdata.json
  2. Create test directory: api/tests
  3. Create empty file __init__.py in api/tests
  4. Create test file: test_fixtures.py
from django.test import TestCase

class FixturesTestCase(TestCase):
  fixtures = ['api/api/fixtures/testdata.json']
  def test_it(self):
    # implement your test here
  1. Run the test to load fixtures into the database: python manage.py test api.tests