使用unittest时如何知道每个测试花费的时间?

使用unittest时如何知道每个测试花费的时间?

问题描述:

Unittest 仅显示运行所有测试所花费的总时间,但未分别显示每个测试所花费的时间.

Unittest presents only total time spent on running all tests but does not present time spent on each test separately.

使用unittest时如何添加每个测试的时间?

How to add timing of each test when using unittest?

我想,现在不可能:http://bugs.python.org/issue4080.

但是你可以这样做:

import unittest
import time

class SomeTest(unittest.TestCase):
    def setUp(self):
        self.startTime = time.time()

    def tearDown(self):
        t = time.time() - self.startTime
        print('%s: %.3f' % (self.id(), t))

    def testOne(self):
        time.sleep(1)
        self.assertEqual(int('42'), 42)

    def testTwo(self):
        time.sleep(2)
        self.assertEqual(str(42), '42')

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(SomeTest)
    unittest.TextTestRunner(verbosity=0).run(suite)

结果:

__main__.SomeTest.testOne: 1.001
__main__.SomeTest.testTwo: 2.002
----------------------------------------------------------------------
Ran 2 tests in 3.003s

OK