In unit tests I need to load fixtures, as below:
class TestQuestionBankViews(TestCase): # Load fixtures fixtures = ['qbank'] def setUp(self): login = self.client.login(email="[email protected]",password="welcome") def test_starting_an_exam_view(self): candidate = Candidate.objects.get(email="[email protected]") .......etc def test_review_view(self): self.assertTrue(True) ......... def test_review_view2(self): self.assertTrue(True) .........
Problem:
These fixtures are loading for every test, i.e. before test_review_view, test_review_view2, etc., as Django flushes the database after every test.
This behaviour is causing tests to take a long time to complete.
How can I prevent this redundant fixture loading?
Is there a way to load fixtures in setUp
and flush them when the test class is finished, instead of flushing between every test?
Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library.
A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command.
Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.
Using django-nose and a bit of code, you can do exactly what you asked for. With django-nose, you can have per-package, per-module and per-class setup and teardown functions. That allows you to load your fixtures in one of the higher-up setup functions and disable the django.test.TestCase's resetting of the fixtures between tests.
Here is an example test file:
from django.test import TestCase from django.core import management def setup(): management.call_command('loaddata', 'MyFixture.json', verbosity=0) def teardown(): management.call_command('flush', verbosity=0, interactive=False) class MyTestCase(TestCase): def _fixture_setup(self): pass def test_something(self): self.assertEqual(1, 1)
Notice that setup and teardown are outside of the class. The setup will be run before all the test classes in this file, and the teardown will be run after all test classes.
Inside the class, you will notice the def _fixture_setup(self) method. This overrides the function that resets the database in between each test.
Keep in mind that if your tests write anything to the database, this could invalidate your tests. So any other tests that need fixtures reloaded for each test should be put in a different test file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With