2017-06-05 139 views
3

大多数情况下,当我使用pytest时,输出非常非常长。超过一百行。而且我经常需要这个输出,我真的这么做。 --tb=short不是真的是一个很好的办法。但我不想在我的tmux窗口中向后滚动200行来查找我的测试输出,因为那是也是超级烦人。如何在使用pytest进行测试后显示测试名*?

我很想有是这样的:

______________________ >>test_my_test_with_a_lot_of_output _______________________ 
# imagine lots of test output here 
______________________ <<test_my_test_with_a_lot_of_output _______________________ 

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

回答

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') 

有关将此方法扩展到_pytest.terminal.TerinalReporter类源的灵感。

1

您可以在您的主/根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) 

在这里,request.node.nodeid给你一个你的测试的名称。

+0

不错的做法。但是,一个小问题是'STARTED'将在测试设置子句中打印,'test'在测试拆卸子句中打印出来:'[capture stdout setup] Test abc STARTED; [capture stdout call]这里的长输出... [capture stdout teardown] Test abc COMPLETED'但是这种方法比我的优雅得多。 – MarSoft