Open lieric7766 opened 3 years ago
Running into this too and I was curious if anyone found a workaround for it?
For anyone else encountering this, there seems to be some magic around having a django_db_setup
fixture, which probably should be defined in a conftest.py
at project root. See https://pytest-django.readthedocs.io/en/latest/database.html#populate-the-database-with-initial-test-data for an example using django_db_setup
...
If I have session-scoped fixtures using django_db_blocker.unblock()
without a django_db_setup
fixture calling unblock()
first, I see those other fixtures using unblock()
hitting the wrong database as well. But once I add a django_db_setup
fixture, everything goes to the test database. Now, to ensure this gets called first, I think you will need every other session scoped fixture wanting database access to request it. And, you will have data persisting in the DB if you don't add teardown to clean it up (or, I suppose, drop the test database after every session).
For example:
conftest.py
import pytest
from myapp.models import User
@pytest.fixture(scope="session")
def django_db_setup(django_db_setup, django_db_blocker):
"""
Tie to test database, cleanup at the end.
"""
with django_db_blocker.unblock():
yield
User.objects.all().delete()
myapp/tests/fixtures.py
import pytest
from myapp.models import User
@pytest.fixture(scope="session")
def test_user(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
return User.objects.create_user( ... )
And yes, having the django_db_setup
fixture request itself seems to be part of the black magic here. I don't understand how this works to ensure the correct database is used, but it works with my project. I hope this becomes simpler and more straightforward with some of the work to resolve #514 !
when i tried this command
pytest -s --import-mode=importlib
it works fine. but when i tried thispytest -s --import-mode=importlib app/tests/test_filename.py
first time was a general fail output but after that i got this error:i checked my postgres database
test_dbname
first and select auth_user this table and it was empty i couldn't find this user i saved. i found it insert to my original databasedbname
auth_user table. it only occurred when i test specific test filemy
conftest.py
my project structure