How to know time spent on each test when using unittest?

前端 未结 7 1405
-上瘾入骨i
-上瘾入骨i 2021-02-05 00:37

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

How to add timing of each test when using unittest?

7条回答
  •  佛祖请我去吃肉
    2021-02-05 01:19

    I suppose, that it's not possible for now: http://bugs.python.org/issue4080.

    But you can do something like this:

    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)
    

    Result:

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

提交回复
热议问题