What is pytests equivalent to setUpTestData in Django?

I have seen TestCase.setUpTestData which improves test speed quite a bit in my case.

I typically prefer pytest fixtures instead of the TestCase classes. However,when I make a session-scope fixture which does data preparation needed for all tests with the fixture, I get

RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

I followed https://stackoverflow.com/a/72261942/29412366, but that had no effect.

How can I store and re-use a DB state within a Django application when testing using pytest?

I use an in-memory sqlite3 DB.

I tried https://stackoverflow.com/a/72261942/29412366 :

@pytest.mark.django_db
@pytest.fixture(scope='session')
def thing(django_db_setup, django_db_blocker):
    del django_db_setup  # Cannot be used with usefixtures(..) it won't work
    with django_db_blocker.unblock():
        print('sleeping')
        Thing.objects.create(thing='hello')

and expected the test to run successfully + save time. Instead, I got the RuntimeError mentioned above.

(function-scoped fixtures work fine, but then I don't save any test execution time)

Вернуться на верх