Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest, how to keep database change between test

Tags:

django

pytest

I'm using the following inside conftest.py

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'my_db',
        'HOST': 'localhost',
    }

it reads data from existing DB fine. Now I want to run two tests and want the change I made in preceding tests to persist until test2 (until the whole tests in the file is finished)

def test_1():

    user = User.objects.get(email='[email protected]')
    user.username = 'hello'
    user.save()


def test_2():

    user = User.objects.get(email='[email protected]')
    print(user.username)        # expect 'hello' but it's not
  • there's scope `session/module' and wonder what it means, session means the whole test run?

Following is what I have tried, but doesn't work.. (from bottom of https://github.com/pytest-dev/pytest-django/blob/master/docs/database.rst)

In contest.py

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'my_db',
        'HOST': 'localhost',
    }

@pytest.fixture
def db_no_rollback(request, django_db_setup, django_db_blocker):
    # https://github.com/pytest-dev/pytest-django/blob/master/docs/database.rst
    django_db_blocker.unblock()
    request.addfinalizer(django_db_blocker.restore)

in test.py

def test_1(db_no_rollback):

    user = User.objects.get(email='[email protected]')
    user.username = 'hello'
    user.save()


def test_2(db_no_rollback):

    user = User.objects.get(email='[email protected]')
    print(user.username)        # expect 'hello' but it's not
like image 245
eugene Avatar asked Sep 06 '25 03:09

eugene


2 Answers

You can reuse the DB with the --reuse-db option

like image 125
smoquet Avatar answered Sep 07 '25 22:09

smoquet


You can use pytest 'fixtures'

import pytest

@pytest.fixture()
@pytest.mark.django_db(transaction=True)
def test_1():

    user = User.objects.get(email='[email protected]')
    user.username = 'hello'
    user.save()

@pytest.mark.django_db(transaction=True)
def test_2(test_1):

    user = User.objects.get(email='[email protected]')
    assert user.username == 'hello'

in this case test_2 will have all db data from test_1(fixture)

like image 44
VelikiiNehochuha Avatar answered Sep 07 '25 21:09

VelikiiNehochuha