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
You can reuse the DB with the --reuse-db
option
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With