希望在pytest输出中查看取消选择的测试及其节点ID的列表

2024-10-17 06:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有选项列出cli输出中取消选择的测试以及触发其取消选择的标记

我知道,在有许多测试的套件中,这并不是一个好的默认设置,但在api测试之类的测试中,这是一个有用的选项,因为测试可能会更加有限

数字摘要

collected 21 items / 16 deselected / 5 selected 

在尝试组织标记并查看ci生成中发生的情况时,这很有帮助,但还不够


Tags: 标记ciapicli套件选项情况items
1条回答
网友
1楼 · 发布于 2024-10-17 06:27:28

pytest有一个hookspec^{}用于访问取消选择的测试。示例:将此代码添加到测试根目录中的conftest.py

def pytest_deselected(items):
    if not items:
        return
    config = items[0].session.config
    reporter = config.pluginmanager.getplugin("terminalreporter")
    reporter.ensure_newline()
    for item in items:
        reporter.line(f"deselected: {item.nodeid}", yellow=True, bold=True)

现在运行测试将为您提供类似以下内容的输出:

$ pytest -vv
...
plugins: cov-2.8.1, asyncio-0.10.0
collecting ...
deselected: test_spam.py::test_spam
deselected: test_spam.py::test_bacon
deselected: test_spam.py::test_ham
collected 4 items / 3 deselected / 1 selected
...

如果您想要另一种格式的报告,只需将取消选择的项存储在配置中,并将它们用于其他地方的所需输出,例如pytest_terminal_summary

# conftest.py

import os

def pytest_deselected(items):
    if not items:
        return
    config = items[0].session.config
    config.deselected = items


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    reports = terminalreporter.getreports('')
    content = os.linesep.join(text for report in reports for secname, text in report.sections)
    deselected = getattr(config, "deselected", [])
    if deselected:
        terminalreporter.ensure_newline()
        terminalreporter.section('Deselected tests', sep='-', yellow=True, bold=True)
        content = os.linesep.join(item.nodeid for item in deselected)
        terminalreporter.line(content)

给出输出:

$ pytest -vv
...
plugins: cov-2.8.1, asyncio-0.10.0
collected 4 items / 3 deselected / 1 selected                                                     

...

                     Deselected tests                     -
test_spam.py::test_spam
test_spam.py::test_bacon
test_spam.py::test_ham
================================= 1 passed, 3 deselected in 0.01s =================================

相关问题 更多 >