pytest-django icon indicating copy to clipboard operation
pytest-django copied to clipboard

Suggestion: module-level fixtures for populating a database

Open nbelakovski-mssm opened this issue 5 months ago • 0 comments

I had a lot of trouble figuring out how to set up my tests given that various tests needed different things in the database, and some tests used live_server which removes all data from the database at the end of the particular test (this prevented me from using a session level fixture, since the live_server test would get rid of all the data that the session level fixture adds to the db)

I also didn't want tests to interfere with each other, and I finally came up with the following solution:

from django.db import transaction 
import pytest

@pytest.fixture(scope='module')
def self_restoring_test_setup(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        with transaction.atomic():
            sid = transaction.savepoint()
            yield
            transaction.savepoint_rollback(sid)

However, this feels like something the plugin should provide. I tried using various fixtures like db and transactional_db, but I kept getting issues with ScopeMismatch because they are scoped at the default function level.

I also tried various things to get the live_server tests to roll back the database to where it had been before with serialized_rollback and such things, but they didn't work. Actually the solution above could probably be applied to a live_server test just as effectively.

I'm not entirely sure how a fixture like the above would fit within this plugin but I hope you find it helpful.

nbelakovski-mssm avatar Sep 13 '24 01:09 nbelakovski-mssm