如何仅将fixture从conftest.py应用于内部文件夹

2024-06-10 10:14:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个位于conftest.py中的夹具

@pytest.fixture(scope='module', autouse=True) 
def my_fixture():
    """
    Some useful code
    """

结构如下:

tests
 |
 |--first_folder
 |   |--__init__.py
 |   |--test_first_1.py
 |   |--test_first_2.py
 |   
 |--second_folder
 |   |--__init__.py
 |   |--test_second_1.py
 |
 |--__init__.py   
 |--conftest.py
 |--test_common_1.py

我希望该夹具仅在内部文件夹中自动使用测试脚本:在测试第一个\u 1.py测试第一个\u 2.py测试第二个\u 1.py,但不在测试第一个\u 1.py

我可以在每个内部文件夹中使用该装置创建conftest,但我不想复制代码

有没有办法将fixture from conftest应用于内部文件夹中的测试脚本,并在公共文件夹测试脚本中忽略它


Tags: pytest脚本文件夹initpytestfolderfixture
3条回答

一种可能的解决方案是,您不想更改文件夹的结构,即使用fixture中的request对象检查测试中使用的标记,因此,如果设置了特定标记,您可以执行任何操作:

@pytest.fixture(scope='module', autouse=True) 
def my_fixture(request):
    """
    Some useful code
    """
    if 'noautofixt' in request.keywords:
        return
    # more code

然后按如下方式标记您的测试:

@pytest.mark.noautofixt
def test_no_running_my_fixture():
    pass

@lmiguelvargasfanswer(+1)为我指明了正确的方向,我使用request解决了以下问题:

@pytest.fixture(scope='module', autouse=True)
def my_fixture(request):
    if request.config.invocation_dir.basename != 'tests':
        """
        Some useful code
        """

此装置将仅应用于内部文件夹中的测试脚本,因为调用文件夹名称不等于“测试”

您可以通过将文件夹“first folder”和“second folder”移动到新文件夹并在该新文件夹中具有conftest.py文件来实现此目的。像这样-

tests
 |
 | new folder
 |  | first_folder
 |  |  | __init__.py
 |  |  | test_first_1.py
 |  |  | test_first_2.py
 |  |
 |  | second_folder
 |  |  | __init__.py
 |  |  | test_second_1.py
 |  | conftest.py
 |
 | __init__.py   
 | conftest.py
 | test_common_1.py

相关问题 更多 >