如何在使用 pytest 的测试之后*显示测试名称?

Way*_*ner 6 python pytest

大多数情况下,当我使用 pytest 时,输出非常非常长。一百多行。很多时候我想要这个输出,我真的想要。--tb=short是不是真的一个很好的办法。但是我不想在我的 tmux 窗口中向后滚动 200 行来找到我的测试输出,因为这很烦人。

我想要的是这样的:

______________________ >>test_my_test_with_a_lot_of_output _______________________
# imagine lots of test output here
______________________ <<test_my_test_with_a_lot_of_output _______________________
Run Code Online (Sandbox Code Playgroud)

我可以在 py.test 中使用一些标志或设置来实现这种输出吗?

Aar*_*gar 8

运行测试时使用“pytest -rA”

在这里查看文档


Cha*_*rat 5

您可以在主/根目录中添加一个夹具,conftest.py它会在每个测试用例之前和之后自动调用。喜欢

@pytest.fixture(scope='function', autouse=True)
def test_log(request):
    logging.info("Test '{}' STARTED".format(request.node.nodeid)) # Here logging is used, you can use whatever you want to use for logs
    def fin():
        logging.info("Test '{}' COMPLETED".format(request.node.nodeid))
    request.addfinalizer(fin)
Run Code Online (Sandbox Code Playgroud)

在这里,request.node.nodeid为您提供测试的名称。


Mar*_*oft 0

我找不到使用钩子实现此目的的简单方法。但这是我将如何实现这一点。但这并不是一个理想的实现。

# contest.py
import pytest
import _pytest

class TerminalReporter(_pytest.terminal.TerminalReporter):
    def _gettestname(self, rep):
        # actually "rename" original method for clarity
        return super()._getfailureheadline(rep)

    def _getfailureheadline(self, rep):
        # instead of test name
        # (which is originally printed at the top of report)
        # return prefixed name
        return '>>' + self._gettestname(rep)

    def _outrep_summary(self, rep):
        super()._outrep_summary(rep)
        # after printing test report end, print out test name again
        # XXX: here we hard-code color, so red will be used even for passed tests
        # (if passes logging is enabled)
        # You can add some more logic with analyzing report status
        self.write_sep('_', '<<' + self._gettestname(rep), red=True)

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    # overwrite original TerminalReporter plugin with our subclass
    # we want this hook to be executed after all other implementations
    # to be able to unregister original plugin
    reporter = TerminalReporter(config)
    config.pluginmanager.unregister(name='terminalreporter')
    config.pluginmanager.register(reporter, 'terminalreporter')
Run Code Online (Sandbox Code Playgroud)

要获得有关扩展此方法的灵感,请前往_pytest.terminal.TerinalReporter类源。