python unittest

直接上代码===

mathfunc类中有如下几个函数

 1 def add(a,b):
 2     return a+b
 3 
 4 def minus(a,b):
 5     return a-b
 6 
 7 def multi(a,b):
 8     return a*b
 9 
10 def divide(a,b):
11     return a/b

test_mathfunc类如下:

 1 #coding=utf-8
 2 '''
 3 Created on 2018年8月24日
 4 
 5 @author: yanerfree
 6 '''
 7 import unittest
 8 from mathfunc import *
 9 import logging
10 import logging.config
11 import HTMLTestRunner
12 import time
13 
14 conf_path = "../conf/log.conf"
15 logging.config.fileConfig(conf_path)
16 logger = logging.getLogger()
17 
18 class TestMathFunc(unittest.TestCase):
19     """Test mathfunc.py"""
20       
21     @classmethod
22     def setUpClass(cls):
23         print "This setUpClass() method only called once."
24 
25     @classmethod
26     def tearDownClass(cls):
27         print "This tearDownClass() method only called once too."
28          
29     def setUp(self):
30         print "do something before test"
31         
32     def test_add(self):
33         """test method add(a,b)"""
34         logger.info("add")
35         self.assertEqual(3, add(1,2), "1+2=3 ?")
36         self.assertNotEqual(3, add(2,2), "2+2!=3 ?")
37 
38     def test_minus(self):
39         """test method minus(a,b)"""
40         logger.info("minus")
41         self.assertEqual(1, minus(3,2), "3-2=1 ?")
42         self.assertNotEqual(2, minus(3,2), "3-2!=2 ?")
43         
44     def tearDown(self):
45         print "do something after test"
46 
47 if __name__ == '__main__':
48     #html Report
49     tamp =int(time.strftime('%Y%m%d%H%M', time.localtime(time.time())))
50     file_path = file(r'./%s_result.html'%str(tamp),'wb')
51     runner = HTMLTestRunner.HTMLTestRunner(file_path)
52     suite = unittest.TestSuite()
53     suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestMathFunc))
54 
55     runner.run(suite)
56     '''
57     #show on console
58     suite = unittest.TestSuite()
59     suite.addTest(TestMathFunc("test_add"))
60     suite.addTest(TestMathFunc("test_minus"))
61     
62     unittest.TextTestRunner(verbosity=2).run(suite)
63     '''
64 '''
65 if __name__ == '__main__':
66     #save to file
67     suite = unittest.TestSuite()
68     suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestMathFunc))
69 
70     with open('UnittestTextReport.txt', 'a') as f:
71         runner = unittest.TextTestRunner(stream=f, verbosity=2)
72         runner.run(suite)
73  '''
74     
原文地址:https://www.cnblogs.com/yaner2018/p/9552988.html