Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 226
Piotr Dobrogost Avatar asked Feb 29 '12 16:02

Piotr Dobrogost


People also ask

How much time should I spend on unit testing?

Typical time budgeted on writing unit tests is about 1 day for every feature that takes 3-4 days of heads down coding. But that can vary with a lot of factors. 99% code coverage is great. Unit tests are great.

Does unit testing save time?

Unit Tests allows you to make big changes to code quickly. You know it works now because you've run the tests, when you make the changes you need to make, you need to get the tests working again. This saves hours. TDD helps you to realise when to stop coding.

How long should unit test suite take to run?

Still, it seems as though a 10 second short-term attention span is more or less hard-wired into the human brain. Thus, a unit test suite used for TDD should run in less than 10 seconds. If it's slower, you'll be less productive because you'll constantly lose focus.

Does Unittest run tests in order?

Note that the order in which the various test cases will be run is determined by sorting the test function names with respect to the built-in ordering for strings.


2 Answers

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 
like image 130
horejsek Avatar answered Oct 05 '22 22:10

horejsek


You can use pytest with --durations=0 and it will give you execution time for each test

like image 34
Michel Samia Avatar answered Oct 05 '22 22:10

Michel Samia