Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python unittest - wrong test count

I'm writing a testing environment for a MOOC, and I have the following unit-test class, which examines the output of a method called search. The idea is to iterate over several inputs (in this case there are 2) using subTest.

Here's my code:

import unittest
import sys
from io import StringIO
import ex1
import ex1sol

class Ex1TestCase(unittest.TestCase):

    def setUp(self):
        self.orig_stdout = sys.stdout
        self.test_lst = [4, 7, 2, 3, 1]
        self.nums_to_search = [7, 8]

    def tearDown(self):
        sys.stdout = self.orig_stdout

    def test_1(self):
        for n in self.nums_to_search:
            with self.subTest(n=n):
                # get test output
                new_stdout = StringIO()
                sys.stdout = new_stdout
                ex1.search(self.test_lst, n)
                test_output =new_stdout.getvalue().strip()
                # get solution output
                new_stdout = StringIO()
                sys.stdout = new_stdout
                ex1sol.search(self.test_lst, n)
                sol_output = new_stdout.getvalue().strip()
                # compare
                self.assertEqual(test_output, sol_output)


if __name__ == '__main__':
    unittest.main()

Here's what's weird - I have 2 test-cases (which I run using a for loop inside the test_1 method. However, on the one hand my console output is:

Ran 1 test in 0.001s

OK

Process finished with exit code 0

On the other hand, pycharm claims that I passed 3 tests: enter image description here I can figure that the output is because eventually I run only a single test method, but I can't explain the 3-tests issue.

My questions:

  1. What's the explanation of the behavior described above?
  2. How can I make my unittest-program to display the results for 2 tests (not 1 or 3)?
like image 434
noamgot Avatar asked Aug 22 '26 00:08

noamgot


1 Answers

I came here googling for a similar problem and can answer your first question:
PyCharm counts every test method (here test_1) and every subtest as one test. You have one test method, which does two subtests (for 7 and 8), so PyCharm displays 3 total tests.

like image 197
Olaf Avatar answered Aug 23 '26 14:08

Olaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!