如何循环Python单元测试运行器的所有成功测试结果?

时间:2016-11-15 15:04:52

标签: python python-unittest

后:

import unittest 
loader = unittest.TestLoader()
tests = loader.discover('.')
testRunner = unittest.runner.TextTestRunner()
testResult = testRunner.run(tests)

我可以使用以下命令获取列表失败名称和消息:

for t in testResult.failures:
    print t[0].id()
    print t[1]

如何为成功做同样的事情?

我希望能够通过覆盖TextTestRunner中的某些内容来实现。什么是最简单的方法?

在Python 2.7上测试。

2 个答案:

答案 0 :(得分:5)

elethan让我朝着正确的方向前进:https://stackoverflow.com/a/40613695/895245

这是我在使用TextTestRunner(resultclass=并添加一个好的构造函数后得到的:

import unittest
from unittest.runner import TextTestResult

class TextTestResultWithSuccesses(TextTestResult):
    def __init__(self, *args, **kwargs):
        super(TextTestResultWithSuccesses, self).__init__(*args, **kwargs)
        self.successes = []
    def addSuccess(self, test):
        super(TextTestResultWithSuccesses, self).addSuccess(test)
        self.successes.append(test)

loader = unittest.TestLoader()
tests = loader.discover('.')
testRunner = unittest.runner.TextTestRunner(resultclass=TextTestResultWithSuccesses)
testResult = testRunner.run(tests)
for t in testResult.failures:
    print t[0].id()
    print t[1]
print
for t in testResult.errors:
    print t[0].id()
    print t[1]
print
for t in testResult.successes:
    print t.id()

答案 1 :(得分:2)

我过去做过类似的事情。我这样做的方法是首先创建一个测试结果类,该类继承自TestTextResult并使用自定义addSuccess方法,该方法将在每次测试成功时调用(addFailure是方法失败的测试会附加到failures):

from unittest.runner import TextTestResult, TextTestRunner

class MyTestResult(TextTestResult):

    successes = []    # As OP points out, this makes more sense as instance attribute 

    def addSuccess(self, test):
        super(TextTestResult, self).addSuccess(test)
        self.successes.append(test)    # add other info if you want

然后制作自己的自定义测试运行器,将自定义测试结果添加为resultclass

class MyTestRunner(TextTestRunner):

    resultclass = MyTestResult    
    # If this is your only customization, you can just pass 
    # the test runner class to `TextTestRunner`; see OP's answer