Count counts in Python unittests separately

Starting with version 3.4, Python supports a simple syntax for subtests when writing unit tests . A simple example might look like this:

import unittest

class NumbersTest(unittest.TestCase):

    def test_successful(self):
        """A test with subtests that will all succeed."""
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i, i)

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

When you run the tests, the output will be

python3 test_foo.py --verbose
test_successful (__main__.NumbersTest)
A test with subtests that will all succeed. ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

However, in my actual use cases, the subtests will depend on a more complex iteration and check for something that is very different for each subtest. Therefore, I would prefer that each subtest be counted and output as a separate test example in the output (in this example, it was done Ran 6 tests in...) to get a complete picture.

- unittest Python? , , .

+6
2

unittest.TestResult:

class NumbersTestResult(unittest.TestResult):
    def addSubTest(self, test, subtest, outcome):
        # handle failures calling base class
        super(NumbersTestResult, self).addSubTest(test, subtest, outcome)
        # add to total number of tests run
        self.testsRun += 1

NumbersTest run:

def run(self, test_result=None):
    return super(NumbersTest, self).run(NumbersTestResult())

, , .

+2

python 3.5.2, , , .

:

if __name__ == '__main__': 
    unittest.main(testRunner=unittest.TextTestRunner(resultclass=NumbersTestResult))

, . , NumbersTestResult, .

class NumbersTestResult(unittest.**Text**TestResult):
    def addSubTest(self, test, subtest, outcome):
        # handle failures calling base class
        super(NumbersTestResult, self).addSubTest(test, subtest, outcome)
        # add to total number of tests run
        self.testsRun += 1
0

Source: https://habr.com/ru/post/1681092/


All Articles