即使有标记,pytest-django 也不允许访问数据库

pytest-django won't allow database access even with mark

我很难弄清楚我的设置有什么问题。我正在尝试测试登录视图,无论我尝试什么,我都会得到:

Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

我的测试:

import pytest

from ..models import User


@pytest.mark.django_db
def test_login(client):
    # If an anonymous user accesses the login page:
    response = client.get('/users/login/')
    # Then the server should respond with a successful status code:
    assert response.status_code == 200

    # Given an existing user:
    user = User.objects.get(username='user')
    # If we attempt to log into the login page:
    response = client.post('/users/login/', {'username': user.username, 'password': 'somepass'})
    # Then the server should redirect the user to the default redirect location:
    assert response.status_code == 302

我的 conftest.py 文件,在同一个测试目录中:

import pytest

from django.core.management import call_command


@pytest.fixture(autouse=True)
def django_db_setup(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        call_command('loaddata', 'test_users.json')

我的 pytest.ini 文件(指定正确的 Django 设置文件):

[pytest]
DJANGO_SETTINGS_MODULE = config.settings

我被难住了。我试过像在 documentation 中一样使用 scope="session"@pytest.mark.django_db 标记,db 夹具(作为测试函数的参数),或者两者都没有运气。我已经注释掉了测试的每一行,以确定是哪一行触发了问题,但无法弄清楚。如果我从测试中删除所有依赖于 db 的 fixtures/marks/code 并有一个简单的 assert True,我只能将测试完全达到 运行。我不认为问题出在我的 Django 设置中,因为开发服务器 运行 正常并且能够访问数据库。

我在这里错过了什么?

显然这是 "deceiving exception syndrome" 的情况。我有一个创建具有权限的组的迁移,并且由于一次测试 运行 所有迁移,创建迁移所依赖的权限的 post-migrate 信号在进行该迁移之前从未 运行 .

似乎如果在实际测试开始 运行ning 之前有任何 database-related 错误,就会引发此异常,这使得很难准确调试到底出了什么问题。我最终更新了我的迁移脚本以手动创建权限,以便迁移可以 运行,错误消失了。

您可以根据官方文档在 conftest.py 中添加以下代码,以允许在没有 django_db 标记的情况下访问数据库。

@pytest.fixture(autouse=True)
def enable_db_access_for_all_tests(db):
    pass

参考:https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-give-database-access-to-all-my-tests-without-the-django-db-marker