如何定义一个 pytest 夹具供给定测试子目录中的所有测试使用?

Ale*_*kov 7 python testing fixtures pytest

给定一个tests包含几个子目录的目录,每个子目录都包含测试模块,如何创建一个pytest在仅在特定子目录中找到的每个测试之前运行的固定装置?

\n\n
tests\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 subdirXX\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 test_module1.py\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 test_module2.py\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 subdirYY\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 test_module3.py\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 test_module4.py\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想要一个固定装置,该装置将在唯一的模块中找到的每个测试之前运行subdirYY(在本例中,在模块test_module3.py和中test_module4.py)。

\n\n

我目前有一个固定装置定义了两次,一次在每个模块内,该模块subdirYY可以工作,但是多余的:

\n\n
@pytest.fixture(autouse=True)\ndef clean_directory():\n   ...\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果无法实现这一点,则 中的每个测试都subdirYY用自定义标记 ( @pytest.mark.mycustommark) 进行装饰,因此确保在用特定自定义标记标记的每个测试之前运行某个固定装置也是一个可行的选择。

\n

Ron*_*ers 6

将您的自动使用装置放入conftest.py内的文件中subdirYY

有关更多信息,请参阅有关共享固定装置的 pytest 文档和有关自动使用固定装置的文档,其中特别提到conftest.py

如果在 conftest.py 文件中定义了自动使用固定装置,则其目录下的所有测试模块中的所有测试都将调用该固定装置。