Select pytest 在测试开始时动态测试 运行

Select pytest tests dynamically at the beginning of test run

我正在使用 pytest 为我的 Python 应用编写单元测试。我编写单元测试的大部分经验都来自 Jasmine 等 Javacript 框架,您可以在下一轮测试中使用单词 'fit' 将测试单独标记为 运行 或使用单词 [= 标记要排除的测试27=]。 'fit' 在开发过程中很好,当我只想 运行 非常特定的测试子集以减少 运行 时间和结果输出混乱时。 Xit 已经用 mark.skip 装饰器实现了,但我想要合适的。

我如何配置 pytest 来执行如下操作:

我知道我可以使用带有 -m 标志的命令行 select 测试到 运行,但我想动态检测 运行 可用测试的子集这样在开发过程中我就不必 运行 测试两个不同的命令,一个有 -m 标志,另一个没有标志。

我想 conftest.py 可能是添加此逻辑的地方,但我找不到太多关于它的配置的信息。

Pytest 插件pytest_collection_modifyitems 似乎是你需要的。 (将以下代码放入您的conftest.py

def pytest_collection_modifyitems(session, config, items):
    """ called after collection has been performed, may filter or re-order
    the items in-place."""

    found_only_marker = False
    for item in items.copy():
        if item.get_marker('only'):
            if not found_only_marker:
                items.clear()
                found_only_marker = True
            items.append(item)

列表 items 是收集的测试。

备注: list.copy只适用于python3,如果您使用python2,请参考:How to clone or copy a list?

思路很简单:

收集所有测试(项目)后,只需检查标记 'only' 是否存在于任何测试中。如果是,请清除列表 items 并仅添加标记为 only 的测试,如果不是,请保持原样。