pytest 和 Django 事务数据库
pytest and Django transactional database
我使用生产数据库进行测试(实际上它是 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
test_example.py
def test_something(db, myfixture):
assert ...
我终于找到了解决方案。
将 fixtures 加载代码添加到 db
fixture:
conftest.py
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
@pytest.mark.django_db(transaction=True)
def test_something(db, myfixture):
assert ...
每次测试后,pytest 将刷新您的数据库并用固定数据填充它。
我使用生产数据库进行测试(实际上它是 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
test_example.py
def test_something(db, myfixture):
assert ...
我终于找到了解决方案。
将 fixtures 加载代码添加到 db
fixture:
conftest.py
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
@pytest.mark.django_db(transaction=True)
def test_something(db, myfixture):
assert ...
每次测试后,pytest 将刷新您的数据库并用固定数据填充它。