gpt4 book ai didi

python - Pytest django 数据库访问不允许使用 django_db 标记

转载 作者:行者123 更新时间:2023-12-02 18:10:17 26 4
gpt4 key购买 nike

我正在使用 pytest,我在下面的 fixture ​​中遇到数据库访问问题。我到处都有 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:不允许访问数据库,使用“django_db”标记,或“db”或“transactional_db”装置来启用它。在行 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 documentation , django_db 如果您需要访问 fixture 内的 Django 数据库(在您的情况下为 class_test_set_up),标记可能无济于事:

enter image description here

在您的特定用例中,您正尝试在类范围内的 fixture 中访问 Django 数据库。从我能够查找的内容来看,django 似乎不支持这一点。

要解决您的问题,如文档中的说明所示,您的 fixture 应明确请求 db fixture 并且应删除类作用域:

@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)

注意 - 我会考虑使用 client来自 pytest-django 的 fixture ,而不是实现上面的 fixture 。

关于python - Pytest django 数据库访问不允许使用 django_db 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72486559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com