繁体   English   中英

如何仅将 conftest.py 中的夹具应用到内部文件夹

[英]How to apply fixture from conftest.py to inner folders only

我有一个位于 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

我希望该夹具仅在内部文件夹测试脚本中自动使用:在test_first_1.pytest_first_2.pytest_second_1.py中,但不在 test_common_1.py中。

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

有什么方法可以将 conftest 中的夹具应用到内部文件夹中的测试脚本并在公共文件夹测试脚本中忽略它?

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

@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

您可以通过将文件夹“第一个文件夹”和“第二个文件夹”移动到一个新文件夹并在该新文件夹中有一个 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

如果您只想为测试模块的子集自动使用顶级 conftest 固定装置,则指导是使用全局变量pytestmark (参考: pytestmark ;教程: 标记整个类或模块)。

在您的情况下,您需要为在tests/conftest.py autouse定义的夹具禁用自动使用:

# tests/conftest.py
import pytest

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

然后在您想要启用自动使用的任何模块中,设置全局变量pytestmark例如

# tests/first_folder/test_first_1.py
import pytest

pytestmark = pytest.mark.usefixtures('my_fixture')

def test_first_feature():
    result = something(my_fixture)  # autouse of my_fixture
    assert result == expected

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM