8π
I guess this error is due to the fact that youβre trying to create the User on the test object directly. Therefore, the code will be executed before the Database is setup and hence the error.
You might try to create the User in a test method:
class TestUserModel:
def test_user_uuid_is_not_none(self):
user = User.objects.create()
assert user.uuid is not None
Or you could simply just run a test function
def test_user_uuid_is_not_none(self):
user = User.objects.create()
assert user.uuid is not None
If you need access to the User several times in your Test, create a fixture and use it in the test:
[conftest.py]
@pytest.fixture
def user() -> settings.AUTH_USER_MODEL:
# return the UserFactory (factoryboy)
return UserFactory()
[test_models.py]
import pytest
from django.contrib.auth import get_user_model
pytestmark = pytest.mark.django_db
User = get_user_model()
class TestUserModel:
def test_user_uuid_is_not_none(self, user: User):
assert user.uuid is not None
2π
From pytest docs:
By default your tests will fail if they try to access the database. Only if you explicitly request database access will this be allowed. This encourages you to keep database-needing tests to a minimum which is a best practice since next-to-no business logic should be requiring the database. Moreover it makes it very clear what code uses the database and catches any mistakes.
The easiest solution would be to add fixture as decorator:
@pytest.mark.django_db(True)
class TestUserModel():