【问题标题】:Pytest django database access not allowed with django_db markdjango_db 标记不允许 Pytest django 数据库访问
【发布时间】:2022-06-13 12:54:56
【问题描述】:

我正在使用 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: 的问题

【问题讨论】:

    标签: python django pytest fixtures


    【解决方案1】:

    根据pytest-django documentationdjango_db 标记可能无济于事,如果您需要访问夹具内的 Django 数据库(在您的情况下为class_test_set_up):

    在您的特定用例中,您正尝试在类范围的夹具中访问 django DB。从我能够查到的情况来看,django 似乎不支持。

    为了解决您的问题,正如文档中的注释所建议的那样,您的夹具应明确请求 db 夹具并应删除类范围:

    @pytest.fixture
    def class_test_set_up(request, db):
        if not hasattr(request.cls, 'client'):
            request.cls.client = Client()
            username = "username"
            user = User.objects.get(username=username)
            _set_current_user(user)
    

    注意 - 我会考虑使用 pytest-django 中的 client 夹具,而不是实现上面的夹具。

    【讨论】:

    • 我收到一个错误ScopeMismatch:您尝试使用类作用域请求对象访问函数作用域夹具数据库
    • @user3565923 似乎 pytest-django 不支持从类范围的夹具访问数据库,我更新了我的答案,希望有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多