python失败的测试,错误和成功的数量Unittest

时间:2015-08-06 13:14:46

标签: python unit-testing

我想制作测试统计数据的饼图 - 显示多少传递并失败。

如何获得通过和失败的测试数量?

我正在使用python 2.7,所以_outcomeForDoCleanups不起作用

1 个答案:

答案 0 :(得分:0)

假设您在unittest.TestCase的子类中定义了许多测试,您可以创建一个测试套件,一个TestResult对象,然后运行测试:

import unittest

class TestThings(unittest.TestCase):
    def test_success(self):
        self.assertEqual(1, 1)

    def test_fail(self):
        self.assertEqual(1, 2)

    def test_error(self):
        1/0

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestThings)
    results = unittest.TestResult()
    suite.run(results)
    print results

输出:

<unittest.result.TestResult run=3 errors=1 failures=1>

您可以使用results对象获取统计信息:

>>> results.testsRun
3
>>> results.errors
[(<__main__.TestThings testMethod=test_error>, 'Traceback (most recent call last):\n  File "ut2.py", line 11, in test_error\n    1/0\nZeroDivisionError: integer division or modulo by zero\n')]
>>> num_errors = len(results.errors)
>>> num_errors
1
>>> results.failures
[(<__main__.TestThings testMethod=test_fail>, 'Traceback (most recent call last):\n  File "ut2.py", line 8, in test_fail\n    self.assertEqual(1, 2)\nAssertionError: 1 != 2\n')]
>>> num_failures = len(results.failures)
>>> num_failures
1
>>> num_successful = results.testsRun - num_failures - num_errors
>>> num_successful
1