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: 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.