pytest,如何在测试之间保持数据库更改

eug*_*ene 4 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',
    }
Run Code Online (Sandbox Code Playgroud)

它可以很好地从现有数据库读取数据。现在我想运行两个测试,并希望我在前面的测试中所做的更改持续到 test2 (直到文件中的整个测试完成)

def test_1():

    user = User.objects.get(email='a@example.com')
    user.username = 'hello'
    user.save()


def test_2():

    user = User.objects.get(email='a@example.com')
    print(user.username)        # expect 'hello' but it's not
Run Code Online (Sandbox Code Playgroud)
  • 有范围“会话/模块”,想知道它是什么意思,会话意味着整个测试运行?

以下是我尝试过的,但不起作用..(来自https://github.com/pytest-dev/pytest-django/blob/master/docs/database.rst的底部)

在竞赛.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)
Run Code Online (Sandbox Code Playgroud)

在测试.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
Run Code Online (Sandbox Code Playgroud)

smo*_*uet 8

--reuse-db您可以使用以下选项重用数据库