pytest - 从测试中分离夹具逻辑

pytest - sepearate fixture logic from the tests

我有几个包想要编写 pytest 测试。所有的包都应该使用相同的夹具逻辑,所以我想让公共测试逻辑(夹具)位于一些公共路径中,每个包测试都应该位于自己的路径中。

Repository 1:
=============
/path/to/PackageA/test_A.py
/path/to/PackageB/test_B.py

Repository 2:
=============
/different_path/to/Common/conftest.py

问题是,当我在 test_A.pytest_B.py 上 运行 pytest 时,pytest 找不到在 [=16= 中定义的固定装置]. 尝试使用 --confcutdir 选项,但没有成功...

唯一对我有用的场景是 运行ning pytest 来自 /different_path/to/Common/,同时设置 pytest.ini testpath = /path/to/PackageA/(顺便说一句 运行ning pytest /path/to/PackageA/ 没用)。

该问题的答案是将 Common 转换为 pytest 插件。如果您已经为那个 Common 项目创建了一个 setup.py,只需将其添加到您的 setup 调用中即可:

# the following makes a plugin available to pytest
entry_points = {
    'pytest11': [
        'common = Common.plugin',
    ]
},

不过,您必须将 Common/conftest.py 重命名为 plugin.py(或 conftest.py 以外的其他名称),因为 py.test 会特殊处理该文件名。

如果您没有 Commonsetup.py,那么您可以通过将 addopts = -p Common.plugin 添加到 PackageA/pytest.ini 让 py.test 将其用作插件] 和 PackageB/pytest.ini.