Getting Python's unittest results in a tearDown() method

前端 未结 13 1360
野的像风
野的像风 2020-11-28 22:40

Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I\'m running Selenium scripts, and I\'d like to do some reporti

13条回答
  •  星月不相逢
    2020-11-28 23:07

    I think the proper answer to your question is that there isn't a clean way to get test results in tearDown(). Most of the answers here involve accessing some private parts of the python unittest module and in general feel like workarounds. I'd strongly suggest avoiding these since the test results and test cases are decoupled and you should not work against that.

    If you are in love with clean code (like I am) I think what you should do instead is instantiating your TestRunner with your own TestResult class. Then you could add whatever reporting you wanted by overriding these methods:

    addError(test, err)
    Called when the test case test raises an unexpected exception. err is a tuple of the form returned by sys.exc_info(): (type, value, traceback).
    
    The default implementation appends a tuple (test, formatted_err) to the instance’s errors attribute, where formatted_err is a formatted traceback derived from err.
    
    addFailure(test, err)
    Called when the test case test signals a failure. err is a tuple of the form returned by sys.exc_info(): (type, value, traceback).
    
    The default implementation appends a tuple (test, formatted_err) to the instance’s failures attribute, where formatted_err is a formatted traceback derived from err.
    
    addSuccess(test)
    Called when the test case test succeeds.
    
    The default implementation does nothing.
    

提交回复
热议问题