使用以下夹具和测试,测试通过: from deal.models import Deal
@pytest.fixture(scope='function')
def myfixture(django_db_blocker):
with django_db_blocker.unblock():
new_deal = Deal()
new_deal.name = 'Alice'
new_deal.save()
@pytest.mark.django_db
def test_1(myfixture):
print(myfixture)
deals = Deal.objects.all()
assert deals
@pytest.mark.django_db
def test_2(myfixture):
print(myfixture)
deals = Deal.objects.all()
assert deals
结果:
============ test session starts =============
myapp/tests/pytest_test.py::test_1 PASSED
myapp/tests/pytest_test.py::test_2 PASSED
但是,如果我将范围更改为“模块”,则第二个失败:
@pytest.fixture(scope='module')
def myfixture(django_db_blocker):
with django_db_blocker.unblock():
load_deals()
结果:
============ test session starts =============
myapp/tests/pytest_test.py::test_1 PASSED
myapp/tests/pytest_test.py::test_2 FAILED
问题在于数据库没有被持久化,因为我看不到如果我在夹具中返回它,我可以访问创建的交易,但数据库是空的。
========= FAILURES =========
_________ test_2 _________
myfixture = id: 1, name='Alice'
@pytest.mark.django_db
def test_2(myfixture):
print(myfixture)
deals = Deal.objects.all()
> assert deals
E assert <QuerySet []>
如果我只运行 test_2 它当然可以:
============ test session starts =============
myapp/tests/pytest_test.py::test_2 PASSED
我有许多共享相同夹具的测试,如果夹具只能运行一次会快得多,因为 load_deals() 非常慢。
看起来我可以重用名称 django_db_setup 作为夹具,并且 scope='session' 有效,但我需要根据测试运行不同的夹具。
我正在使用 python 3.6.1 - pytest 3.1.2 - pytest-django 3.1.2 和 mariadb 10.1
关于如何使这项工作的任何想法?