我最近熟悉了 pytest 以及如何使用它conftest.py来定义在我的测试中自动发现和导入的装置。我很清楚它是如何conftest.py工作的以及如何使用它,但我不确定为什么这在某些基本场景中被认为是最佳实践。
假设我的测试是这样构建的:
tests/
--test_a.py
--test_b.py
Run Code Online (Sandbox Code Playgroud)
正如文档和网络上有关 pytest 的各种文章所建议的,最佳实践是定义一个文件,其中包含一些要在和conftest.py中使用的固定装置。为了更好地组织我的装置,我可能需要以语义上有意义的方式将它们分成单独的文件,例如。、、 然后将它们作为插件导入.test_a.pytest_b.pydb_session_fixtures.pydataframe_fixtures.pyconftest.py
tests/
--test_a.py
--test_b.py
--conftest.py
--db_session_fixtures.py
--dataframe_fixtures.py
Run Code Online (Sandbox Code Playgroud)
在conftest.py我会有:
import pytest
pytest_plugins = ["db_session_fixtures", "dataframe_fixtures"]
Run Code Online (Sandbox Code Playgroud)
我将能够在我的测试用例中无缝地使用db_session_fixtures和 ,而无需任何额外的代码。dataframe_fixtures
虽然这很方便,但我觉得它可能会损害可读性。例如,如果我不按conftest.py上述方式使用,我可能会写成test_a.py
from .dataframe_fixtures import my_dataframe_fixture
def test_case_a(my_dataframe_fixture):
#some tests
Run Code Online (Sandbox Code Playgroud)
并照常使用固定装置。
缺点是它需要我导入固定装置,但显式导入提高了测试用例的可读性,让我一目了然地知道固定装置来自哪里,就像任何其他 python 模块一样。
我是否忽略了这个解决方案的缺点或其他conftest.py带来的优点,使其成为设置 pytest 测试套件时的最佳实践?