pytest和Django事务数据库

pytest和Django事务数据库,django,pytest,pytest-django,Django,Pytest,Pytest Django,我使用生产数据库进行测试(实际上它是docker中的测试数据库)。问题是:如何使测试在该数据库的事务中运行。我需要像@pytest.mark.django_db(transaction=True)一样的行为,但需要生产数据库 当前设置: conftest.py @pytest.fixture(scope='session') def django_db_setup(): """Avoid creating/setting up the test database""" pass

我使用生产数据库进行测试(实际上它是docker中的测试数据库)。问题是:如何使测试在该数据库的事务中运行。我需要像
@pytest.mark.django_db(transaction=True)
一样的行为,但需要生产数据库

当前设置:

conftest.py

@pytest.fixture(scope='session')
def django_db_setup():
    """Avoid creating/setting up the test database"""
    pass


@pytest.fixture
def db(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()


@pytest.fixture
def myfixture(db):
    ...
    return SomeObject
from django.core.management import call_command

@pytest.fixture
def db(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()
    call_command('loaddata', 'fixture.json')
test_example.py

def test_something(db, myfixture):
    assert ...
@pytest.mark.django_db(transaction=True)
def test_something(db, myfixture):
    assert ...

我终于找到了解决办法

将夹具加载代码添加到
db
夹具:

conftest.py

@pytest.fixture(scope='session')
def django_db_setup():
    """Avoid creating/setting up the test database"""
    pass


@pytest.fixture
def db(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()


@pytest.fixture
def myfixture(db):
    ...
    return SomeObject
from django.core.management import call_command

@pytest.fixture
def db(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()
    call_command('loaddata', 'fixture.json')
并使用
@pytest.mark.django_db(transaction=True)
进行测试:

test_example.py

def test_something(db, myfixture):
    assert ...
@pytest.mark.django_db(transaction=True)
def test_something(db, myfixture):
    assert ...
每次测试后,pytest将刷新您的数据库,并用夹具数据填充数据库。

全部在设置中: