Pytest django доступ к базе данных не разрешен с меткой django_db
Я использую pytest и у меня проблема с доступом к базе данных в фикстуре ниже. У меня везде стоит метка django_db.
[test_helpers.py]
import pytest
from django.test import Client
from weblab.middleware.localusermiddleware import _set_current_user
@pytest.fixture(scope="class")
@pytest.mark.django_db
def class_test_set_up(request):
request.cls.client = Client()
username = "username"
user = User.objects.get(username=username)
_set_current_user(user)
Я получаю
RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
В строке user = User.objects.get(username=username)
[test_tmp_fixture.py]
import pytest
from tests.factories.sample.test_factories import TestFactory
from tests.tests_helpers.test_helpers import class_test_set_up
SIZE = 5
@pytest.mark.django_db
@pytest.fixture(scope="class")
def set_up_objs(request):
request.cls.factory = TestFactory
request.instance.objs = request.cls.factory.create_batch(SIZE)
@pytest.mark.django_db
@pytest.mark.usefixtures("class_test_set_up", "set_up_objs")
class TestTest:
@pytest.mark.django_db
def test_test(self):
print("Hello Pytest")
Моя установка - pytest-7.0.1 с плагинами: lazy-fixture-0.6.3, Faker-13.3.2, django-4.5.2 и django версии 3.2.12
В консоли трассировки показаны проблемы с /pytest_lazyfixture.py:39:
Согласно документации pytest-django, метка django_db
может не помочь, если вам нужен доступ к базе данных Django внутри фикстуры (class_test_set_up
в вашем случае):
Чтобы решить вашу проблему, как указано в документации, ваше приспособление должно явно запросить db
приспособление:
@pytest.fixture(scope="class")
def class_test_set_up(request, db):
request.cls.client = Client()
username = "username"
user = User.objects.get(username=username)
_set_current_user(user)