python 单元测试-unittest

时间:2021-03-31 23:57:46

参考资料:https://docs.python.org/3.4/library/unittest.html#module-unittest

一张图解决问题:

python 单元测试-unittest

涉及5块内容:case、suite、loader、runner、result

1 case:

TestCase(测试用例) :所有测试用例的基本类,给一个测试方法的名字,返回一个测试用例实例。

2 suite:

TestSuite(测试套):组织测试用例的实例,支持测试用例的添加和删除,最终将传递给testRunner进行测试执行

3 loader:

TestLoader(测试用例加载器): 测试用例加载器,其包括多个加载测试用例的方法。返回一个测试套件

4 runner:

TextTestRunner(测试用例执行):进行测试用例执行的实例,其中的run(test)会执行TestSuite/TestCase中的run(result)方法

TextTestResult(用例结果记录):测试的结果会保存到TextTestResult实例中,包括运行了多少测试用例,成功了多少,失败了多少等信息

5 result

TestResult(测试结果):记录测试的最终结果


官方例子:测试 random module的3个功能

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):   

    def setUp(self):
        self.seq = list(range(10))

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, list(range(10)))

        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

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

解释如下:

A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.

The crux of each test is a call to assertEqual() to check for an expected result; assertTrue() to verify a condition; or assertRaises() to verify that an expected exception gets raised. These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report.

When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test. In the example, setUp() was used to create a fresh sequence for each test.

The final block shows a simple way to run the tests. unittest.main() provides a command-line interface to the test script. When run from the command line, the above script produces an output that looks like this:

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK