Reputation: 65530
I am using Django 1.8. I have been writing tests for my Django API in one long file called test_api.py
. The structure of the file has been as follows:
def setUpModule():
management.call_command('loaddata', 'frontend/fixtures/data.json',
verbosity=0)
management.call_command('my_custom_command')
def tearDownModule():
management.call_command('flush', verbosity=0, interactive=False)
class TestAPIBNFViews(TestCase):
def test_api_view_list_all(self):
url = '/api/1.0/bnf_code'
# do testing
def test_api_view_query(self):
# more testint
The fixtures and management command being loaded once before all the tests run, and so far this has worked great.
Now however the file is getting long and unwieldy, and I want to split it into multiple files. I've created multiple files called test_list
and test_query
and given each a setUpModule
section as above.
However, firstly this isn't DRY, and secondly when I run python manage.py test
, lots of the tests fail with duplicate foreign key errors like:
ProgrammingError: relation "frontend_sha_id" already exists
I guess this isn't surprising, since the tests are trying to create the test database multiple times.
However, if I remove setUpModule
from all but the first test (listed alphabetically by filename), the other tests fail because they can't see any data.
How can I run setUpModule
once, before all the tests run, and still keep the tests in separate files for convenience?
Upvotes: 3
Views: 713
Reputation: 19902
Instead of using a global setUpModule
for both test classes, you can alternatively use setUpTestData
once at each TestCase
class. From Django documentation: Testing tools:
The class-level atomic block ... allows the creation of initial data at the class level, once for the whole
TestCase
.
Upvotes: 1