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

2024-03-04

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

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

My test:

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

我很困惑。我尝试过使用scope="session"就像在文档 https://pytest-django.readthedocs.io/en/latest/database.html#populate-the-database-with-initial-test-data与任一@pytest.mark.django_db马克,一个db固定装置(作为测试函数的参数),或两者都没有运气。我已经注释掉了测试的每一行,以找出哪一行触发了问题,但无法弄清楚。如果我从测试中删除所有依赖于数据库的固定装置/标记/代码并有一个简单的操作,我只能让测试运行assert True。我不认为问题出在我的 Django 设置中,因为开发服务器运行良好并且能够访问数据库。

我在这里缺少什么?


显然,这是一个“欺骗异常综合症”的案例。我进行了一次迁移,创建了具有权限的组,并且由于测试同时运行所有迁移,因此在进行该迁移之前,从未运行过创建迁移所依赖的权限的迁移后信号。

看起来,如果在实际测试开始运行之前存在任何与数据库相关的错误,就会引发此异常,这使得很难准确调试出了什么问题。我最终更新了迁移脚本以手动创建权限,以便迁移可以运行,并且错误消失了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

即使有标记,pytest-django 也不允许数据库访问 的相关文章

随机推荐