2017-06-05 126 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