如何防止 pytest 删除测试用例之间的数据库记录?

How can I prevent pytest to remove database records between test cases?

我使用预先创建的 postgres 数据库进行测试。这里是 pytest 设置:
pytest.ini:

[pytest]
norecursedirs = frontend static .svn _build tmp*    
DJANGO_SETTINGS_MODULE = src.settings.testing
addopts = --reuse-db

testing.py:

from .base import *

DEBUG = True

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'db',
        'USER': 'root',
        'PASSWORD': 'pass',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

测试装置:

@pytest.fixture(scope='session')
def user():
    return User.objects.create(name='Test', )

测试用例:

import pytest

pytestmark = pytest.mark.django_db


def test_user(user):
    print(user.pk) # returns pk of newly created user
    print(User.objects.all()) # returns queryset with one user


def test_user2(user):
    print(user.pk) # returns the same value as in the previous test 
    print(User.objects.all()) # returns empty queryset

我无法理解 pytest 装置的行为。每个会话创建一次模型实例,并且在多个测试用例中都是相同的。但实际的 db 值是不同的。 Pytest 在第一个测试用例后删除用户值。
我怎样才能防止这种行为并为所有测试会话保存我的数据库记录?

这不是 --reuse-db 的问题,因为用户在同一个测试中从一个测试移到了下一个测试 运行。

问题是您通过 session 范围设置夹具,这意味着每次测试 运行 将执行一次夹具,并且由于 Django 将在两者之间刷新数据库测试您的 User 实例不再可用于第二个测试。只需从夹具装饰器中删除范围:

@pytest.fixture()
def user():
    return User.objects.create(username='Test')

编辑: 来自 pytest-django docs "Once setup the database is cached for used for all subsequent tests and rolls back transactions to isolate tests from each other. This is the same way the standard Django TestCase uses the database."

我不明白您为什么要在测试之间使用完全相同的 User 实例,即使您要改变该特定实例也意味着测试将相互依赖。为了能够隔离测试,您应该能够按照测试的预期提供用户。