eugene
eugene

Reputation: 41665

pytest, how to keep database change between test

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

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

Upvotes: 4

Views: 11031

Answers (3)

smoquet
smoquet

Reputation: 371

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

Upvotes: 9

Saber Solooki
Saber Solooki

Reputation: 1220

You can prevent the test databases from being destroyed by using the test --keepdb option. This will preserve the test database between runs. If the database does not exist, it will first be created. Any migrations will also be applied in order to keep it up to date. Look at this link.

Upvotes: 0

VelikiiNehochuha
VelikiiNehochuha

Reputation: 4363

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)

Upvotes: 4

Related Questions