pytest-django
pytest-django copied to clipboard
Pass through Django data `fixtures` to TransactionTestCase
I am writing some tests which need to disable Django's autocommit, as the code under test manages this itself. However, after the first test case, the database is flushed, and any useful state that was created in the migrations or data fixtures are lost which causes subsequent tests to fail. Specifically, it's the records in the Site table that must be available for the subsequent tests.
I've created a Django data fixture, sites.json. However, there doesn't seem to be an easy way in pytest-django to ensure this is loaded before each test. The TransactionTestCase has a fixtures attribute which can be used for this purpose.
Ideally, mark.django_db should pass through a list of fixtures to the test case like so:
pytestmark = pytest.mark.django_db(transaction=True, fixtures=["sites.json"])
Edit: I have tried overriding the django_db fixture as per the example in the docs. However, this also gets flushed after the first transactional test.
Is there another way to handle this issue apart from adding the loaddata code to each test?
I'm having this same exact issue specifically because I have a data migration that adds Site records. I don't actually understand why data migrations aren't run before every test, or why transactional_db would wipe records that are created by migrations. This makes no sense to me.
The solution I've come up with is to add an autouse fixture that sets up sites correctly for all tests. This is a bad look though, we've now got a DRY violation, and if we add additional sites, the fixture has to change, leading to confusion.