Django pytest,如何在测试之间保持数据库更改
我正在使用以下内部Django pytest,如何在测试之间保持数据库更改,django,pytest,Django,Pytest,我正在使用以下内部conftest.py @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'HOST': 'localhost', } 它从现有数据库中读取数据。
conftest.py
@pytest.fixture(scope='session')
def django_db_setup():
settings.DATABASES['default'] = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_db',
'HOST': 'localhost',
}
它从现有数据库中读取数据。
现在,我想运行两个测试,并希望我在前面的测试中所做的更改持续到test2(直到文件中的整个测试完成)
- 这里有“会话/模块”的范围,不知道它是什么意思,会话意味着整个测试运行
@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)
在test.py中
def test_1(db_no_rollback):
user = User.objects.get(email='a@example.com')
user.username = 'hello'
user.save()
def test_2(db_no_rollback):
user = User.objects.get(email='a@example.com')
print(user.username) # expect 'hello' but it's not
您可以使用pytest“fixtures”
import pytest
@pytest.fixture()
@pytest.mark.django_db(transaction=True)
def test_1():
user = User.objects.get(email='a@example.com')
user.username = 'hello'
user.save()
@pytest.mark.django_db(transaction=True)
def test_2(test_1):
user = User.objects.get(email='a@example.com')
assert user.username == 'hello'
在这种情况下,test_2将拥有test_1(fixture)中的所有db数据。您可以使用pytest“fixture”
import pytest
@pytest.fixture()
@pytest.mark.django_db(transaction=True)
def test_1():
user = User.objects.get(email='a@example.com')
user.username = 'hello'
user.save()
@pytest.mark.django_db(transaction=True)
def test_2(test_1):
user = User.objects.get(email='a@example.com')
assert user.username == 'hello'
在这种情况下,test_2将拥有test_1(fixture)中的所有db数据您可以通过使用
test--keepdb
选项防止破坏测试数据库。这将在运行之间保留测试数据库。如果数据库不存在,将首先创建它。还将应用任何迁移以使其保持最新。
查看链接。您可以使用
test--keepdb
选项防止测试数据库被破坏。这将在运行之间保留测试数据库。如果数据库不存在,将首先创建它。还将应用任何迁移以使其保持最新。
查看链接。您可以使用
--reuse DB
选项重用DB您可以使用--reuse DB
选项重用DB此选项用于djangotest
命令,而不是pytest此选项用于djangotest
命令,而不是pytest