With the following fixture and tests, the tests pass: from deals.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
Result:
============ test session starts =============
myapp/tests/pytest_test.py::test_1 PASSED
myapp/tests/pytest_test.py::test_2 PASSED
But if I change the scope to 'module' the second one fail:
@pytest.fixture(scope='module')
def myfixture(django_db_blocker):
with django_db_blocker.unblock():
load_deals()
Result:
============ test session starts =============
myapp/tests/pytest_test.py::test_1 PASSED
myapp/tests/pytest_test.py::test_2 FAILED
The issue is with the DB not being persisted, as I cann see I can access the created deal if I return it in the fixture, but the DB is empty.
========= 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 []>
And if I run only test_2 it works of course:
============ test session starts =============
myapp/tests/pytest_test.py::test_2 PASSED
I've got many tests that share the same fixture, it would be a lot faster if the fixture could run only once as the load_deals() is quite slow.
It looks like I can reuse the name django_db_setup as a fixture, and the scope='session' works, but I need to run different fixtures depending on the tests.
I'm using python 3.6.1 - pytest 3.1.2 - pytest-django 3.1.2 with mariadb 10.1
Any idea on how to make this work?