Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest and Django transactional database

I use production database for tests (actually it's test database in docker). The question is: how to make tests run in transactions against this database. I need the same behavior like @pytest.mark.django_db(transaction=True) but with production database.

Current setup:

conftest.py

@pytest.fixture(scope='session')
def django_db_setup():
    """Avoid creating/setting up the test database"""
    pass


@pytest.fixture
def db(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()


@pytest.fixture
def myfixture(db):
    ...
    return SomeObject

test_example.py

def test_something(db, myfixture):
    assert ...
like image 522
Ilya Avatar asked Oct 17 '25 22:10

Ilya


1 Answers

Finally I've found the solution.

Add fixtures loading code to db fixture:

conftest.py

from django.core.management import call_command

@pytest.fixture
def db(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()
    call_command('loaddata', 'fixture.json')

And use @pytest.mark.django_db(transaction=True) with tests:

test_example.py

@pytest.mark.django_db(transaction=True)
def test_something(db, myfixture):
    assert ...

After each test pytest will flush your database and fill it with fixtures data.

like image 56
Ilya Avatar answered Oct 20 '25 23:10

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!