Python基础学习九 单元测试

 1 import unittest
 2 import HTMLTestRunner #产生测试报告
 3 from BeautifulReport import BeautifulReport
 4 
 5 def calc(x,y):
 6     return x+y
 7 
 8 class TestCalc(unittest.TestCase):
 9     def test_pass_case(self):
10         '''这是通过的测试用例'''#用例描述,只能是这样的格式
11         print('通过用例')
12         res = calc(1,2)
13         self.assertEqual(3,res)
14         self.assertNotEqual(2,3)
15 
16     #每个用例运行之前,都会执行它
17     def setUp(self):
18         print('我是setup。。。')
19 
20     # 每个用例运行完成后,都会执行它
21     def tearDown(self):
22         print('我是teardown。。。')
23 
24     # 所有的用例运行之前,都会执行它
25     @classmethod
26     def setUpClass(cls):
27         print('我是setupclass。。。')
28 
29     # 所有的用例运行之后,都会执行它
30     @classmethod
31     def tearDownClass(cls):
32         print('我是teardownclass。。。')
33 
34     def testa(self):
35         print('a')
36     def test_fail_case(self):
37         '''这是失败的测试用例''' #用例描述
38         print('用例失败!')
39         res = calc(9,8)
40         self.assertEqual(98,res)
41     def test_haha(self):
42         '''哈哈哈'''
43         self.assertEqual(1,2)
44 
45 if __name__ == '__main__':  #用于自测试
46     # unittest.main()#他会帮你运行当前这个Python里面所有的测试用例
47     suite = unittest.TestSuite()#定义一个测试套件
48 
49     #单个测试用例添加
50     # suite.addTest(TestCalc('test_pass_case'))
51     # suite.addTest(TestCalc('testa'))
52     # suite.addTest(TestCalc('test_fail_case'))
53 
54     # 批量添加  #将这个类里面所有的测试用例
55     suite.addTest(unittest.makeSuite(TestCalc))
56 
57     # 普通报告模板
58     # f = open('report0307.html','wb') #打开一个测试报告文件
59     # runner = HTMLTestRunner.HTMLTestRunner(stream=f,
60     #                                        title='测试结果',
61     #                                        description='描述')
62     # runner.run(suite)#运行
63 
64     # # 好看的报告模板!!
65     result = BeautifulReport(suite)
66     result.report(filename = 'louis_test_report',description='描述',log_path = '.')
原文地址:https://www.cnblogs.com/louis-w/p/8532827.html