如何定义给定测试子目录中所有测试使用的 pytest fixture?
How to define a pytest fixture to be used by all tests within a given tests subdirectory?
给定一个目录 tests
,其中有几个子目录,每个子目录都包含测试模块,如何创建一个 pytest
fixture 以便 运行 在仅在特定子目录中找到每个测试之前?
tests
├── __init__.py
├── subdirXX
│ ├── test_module1.py
│ ├── test_module2.py
│ ├── __init__.py
├── subdirYY
│ ├── test_module3.py
│ ├── test_module4.py
│ ├── __init__.py
我想要一个夹具,它会 运行 在每个测试之前只在 subdirYY
的模块中找到(在这种情况下,在模块 test_module3.py
和 test_module4.py
).
我目前有一个固定装置定义了两次,一次在 subdirYY
中的每个模块中,它可以工作但是是多余的:
@pytest.fixture(autouse=True)
def clean_directory():
...
如果无法实现,subdirYY
中的每个测试都使用自定义标记 (@pytest.mark.mycustommark
) 进行装饰,因此请确保某个固定装置将 运行在每个带有特定自定义标记的测试之前也是一个可行的选择。
将您的 autouse fixture 放入 conftest.py
文件中 subdirYY
.
有关详细信息,请参阅有关 sharing fixtures and the docs on autouse fixtures 的 pytest 文档,其中特别提到 conftest.py
:
if an autouse fixture is defined in a conftest.py file then all tests in all test modules belows its directory will invoke the fixture.
给定一个目录 tests
,其中有几个子目录,每个子目录都包含测试模块,如何创建一个 pytest
fixture 以便 运行 在仅在特定子目录中找到每个测试之前?
tests
├── __init__.py
├── subdirXX
│ ├── test_module1.py
│ ├── test_module2.py
│ ├── __init__.py
├── subdirYY
│ ├── test_module3.py
│ ├── test_module4.py
│ ├── __init__.py
我想要一个夹具,它会 运行 在每个测试之前只在 subdirYY
的模块中找到(在这种情况下,在模块 test_module3.py
和 test_module4.py
).
我目前有一个固定装置定义了两次,一次在 subdirYY
中的每个模块中,它可以工作但是是多余的:
@pytest.fixture(autouse=True)
def clean_directory():
...
如果无法实现,subdirYY
中的每个测试都使用自定义标记 (@pytest.mark.mycustommark
) 进行装饰,因此请确保某个固定装置将 运行在每个带有特定自定义标记的测试之前也是一个可行的选择。
将您的 autouse fixture 放入 conftest.py
文件中 subdirYY
.
有关详细信息,请参阅有关 sharing fixtures and the docs on autouse fixtures 的 pytest 文档,其中特别提到 conftest.py
:
if an autouse fixture is defined in a conftest.py file then all tests in all test modules belows its directory will invoke the fixture.