【问题标题】:Execute pytest hooks only when test is marked with custom marker仅在使用自定义标记标记测试时执行 pytest 挂钩
【发布时间】:2020-11-03 18:40:34
【问题描述】:

所以我在pytest.ini 文件中定义了自定义标记

[pytest]
markers =
    foomark: Mark a test as foo

每当运行标有foomark 的测试时,我还需要通过一组特殊的钩子脚本实现来使用/执行该测试,这些脚本实现进入conftest.py

def pytest_foo_hook(request):
    print("This is a foo-marked test.")

pytest.ini 位于项目根目录中。 conftest.py 必须放在每个包含项目测试/测试套件的子文件夹中。问题在于,标有foomark 的测试分布在多个包中,并且我需要为每个包添加钩子实现,从而产生大量样板代码。也不能为所有测试定义钩子脚本。

有没有办法将标记与一组 pytest 钩子脚本实际链接,以仅在标记有 foomark 的测试上执行?

【问题讨论】:

  • 你不能只检查钩子中的标记(使用类似request.node.iter_markers())吗?

标签: python unit-testing pytest


【解决方案1】:

因此,正如 MrBean Bremen 指出并注意到 here,每个钩子脚本实现中可访问的请求对象都包含调用测试的标记。执行此操作时,仍将为套件的所有测试执行该钩子,但它可以过滤掉具有标记 foomark 的测试。对于我的用例来说,这就足够了。简单的解决方案可能如下所示:

def pytest_foo_hook(request):
    for marker in request.node.iter_markers():
        if marker.name == 'foomark':
            print("This is a foo-marked test.")

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2021-04-02
    • 2020-12-13
    • 1970-01-01
    • 2013-03-28
    • 2011-08-20
    • 1970-01-01
    • 2015-05-14
    相关资源
    最近更新 更多