首页 > 解决方案 > 数据库只读设置未从子文件夹中的 conftest.py 加载

问题描述

问题是我需要为一组测试设置一个特殊设置的 conftest。仅在这些测试中以只读模式使用实时数据库。单元文件夹中的其他测试使用 pytest 创建的空数据库。如果我从 tests_readonly_db 运行pytest testspytest tests/unitconftest 将无法识别。当我将 conftest 文件放在单元文件夹中时,它被识别出来。并运行这两个命令中的任何一个。但是当我pytest tests/unit/tests_readonly_db在 tests_readonly_db 文件夹中使用 conftest 运行时,它可以完美运行。还尝试在 tests_readonly_db 中创建另一个子文件夹,将测试放在那里,conftest.py 保持水平。不工作。

我想知道是否有办法实现所需的行为。找到了一些相关的答案,但无法完全理解它对我的情况有何帮助。例如: https ://stackoverflow.com/a/13686206/7744657

但如果

默认情况下,子目录中的 conftest.py 文件不会在工具启动时加载。

为什么它是从单元文件夹中加载的?

conftest.py

import pytest


@pytest.fixture(scope='session')
def django_db_setup():
    """Avoid creating/setting up the test database"""
    pass


@pytest.fixture
def db_access_without_rollback_and_truncate(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()
    request.addfinalizer(django_db_blocker.restore)

应用结构:

在此处输入图像描述

编辑

我刚刚用一个简单而愚蠢的夹具对此进行了测试。它有效。因此,在某些情况下未发现此特定数据库设置实际上是一个问题。这个简单的夹具似乎在任何情况下都有效。

import pytest


@pytest.fixture(scope='session')
def django_db_setup():
    """Avoid creating/setting up the test database"""
    pass


@pytest.fixture
def db_access_without_rollback_and_truncate(request, django_db_setup, django_db_blocker):
    django_db_blocker.unblock()
    request.addfinalizer(django_db_blocker.restore)


@pytest.fixture
def msg():
    return 'AAAAAAAAAAA----------------------------------------AAAAAAAAAA'

测试视图.py

@pytest.mark.django_db()
@pytest.mark.parametrize('uri, args', [
    some parameters.....
])
def test_views(uri, args, client, msg):
    print(msg)
    username = "john doe"
    password = "123456"

    client.login(username=username, password=password)

    if args:
        response = client.get(reverse(uri, args=args))
    else:
        response = client.get(reverse(uri))

    assert response.status_code == 200

标签: pythondjangopython-3.xtestingpytest

解决方案


推荐阅读