如何在 pytest 中将自定义部分添加到终端报告

Jea*_* T. 4 python pytest

pytest中,当测试用例失败时,报告中会显示以下类别:

  • 失败详情
  • 捕获的标准输出调用
  • 捕获的 stderr 调用
  • 捕获的调用日志

py测试报告

我想添加一些额外的自定义部分(我有一个并行运行的服务器,并且希望在专用部分中显示该服务器记录的信息)。

我怎样才能做到这一点(如果可能的话)?

谢谢


笔记

我目前在源代码中找到了以下内容,但不知道这是否是正确的方法

节点.py

class Item(Node):
    ...
    def add_report_section(self, when, key, content):
        """
        Adds a new report section, similar to what's done internally
        to add stdout and stderr captured output:: 
        ...
        """
Run Code Online (Sandbox Code Playgroud)

报告.py

class BaseReport:
    ...

    @property
    def caplog(self):
        """Return captured log lines, if log capturing is enabled

        .. versionadded:: 3.5
        """
        return "\n".join(
            content for (prefix, content) in self.get_sections("Captured log")
        )
Run Code Online (Sandbox Code Playgroud)

hoe*_*ing 5

要将自定义部分添加到终端输出,您需要附加到report.sections列表。这可以直接在 hookimpl 中完成pytest_report_teststatus,也可以在其他钩子中间接完成(通过 hookwrapper);实际的实现在很大程度上取决于您的特定用例。例子:

# conftest.py

import os
import random
import pytest

def pytest_report_teststatus(report, config):
    messages = (
        'Egg and bacon',
        'Egg, sausage and bacon',
        'Egg and Spam',
        'Egg, bacon and Spam'
    )

    if report.when == 'teardown':
        line = f'{report.nodeid} says:\t"{random.choice(messages)}"'
        report.sections.append(('My custom section', line))


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)
    if content:
        terminalreporter.ensure_newline()
        terminalreporter.section('My custom section', sep='-', blue=True, bold=True)
        terminalreporter.line(content)
Run Code Online (Sandbox Code Playgroud)

测试示例:

def test_spam():
     assert True

def test_eggs():
     assert True


def test_bacon():
     assert False
Run Code Online (Sandbox Code Playgroud)

运行测试时,您应该My custom section在底部看到蓝色标题,并包含每个测试的消息:

collected 3 items

test_spam.py::test_spam PASSED
test_spam.py::test_eggs PASSED
test_spam.py::test_bacon FAILED

============================================= FAILURES =============================================
____________________________________________ test_bacon ____________________________________________

    def test_bacon():
>        assert False
E        assert False

test_spam.py:9: AssertionError
---------------------------------------- My custom section -----------------------------------------
test_spam.py::test_spam says:   "Egg, bacon and Spam"
test_spam.py::test_eggs says:   "Egg and Spam"
test_spam.py::test_bacon says:  "Egg, sausage and bacon"
================================ 1 failed, 2 passed in 0.07 seconds ================================
Run Code Online (Sandbox Code Playgroud)