python_ unit testing unittest

Unit testing unittest

 1, unit test

 1 import unittest
 2 def add(a,b):
 3     return a + b
 4 result = add(1,1)
 5 
 6 class AddTest(unittest.TestCase): #继承unittest.TestCase
 7     def test_normal(self):
 8         result = add(1,1)
 9         self.assertEqual(2,result)  #assertEqual是判断两个值是否相等
10 
11     def test_error(self):
12         result = add(1,1)
13         self.assertEqual(1,result,'Error calculation result ' )
 14  
15 unittest.main ()   # identifying which class of all test cases, the test case must begin test

2, implementation of test cases generated test report

. 1  Import the unittest
 2  DEF the Add (A, B):
 . 3      return A + B
 . 4 Result = the Add (1,1 )
 . 5  Import HTMLTestRunner
 . 6  Import BeautifulReport AS BFR
 . 7  class AddTest (of unittest.TestCase):
 . 8      @classmethod
 . 9      DEF setUpClass ( CLS):    # all use cases will execute it before performing 
10          Print ( ' setUpClass ' )
 . 11  
12 is      @classmethod
 13 is      DEF tearDownClass (CLS):   #All the use cases after performing performs its 
14          Print ( ' tearDownClass ' )
 15  
16      DEF the setUp (Self):    # each prior embodiment performs will be executed with it first 
. 17          Print ( ' Setup ' )
 18 is  
. 19      DEF the tearDown (Self):   # each after performing the embodiment are performed with it 
20 is          Print ( ' the tearDown ' )
 21 is  
22 is      DEF test_normal (Self):
 23 is          Result = the Add (1,1 )
 24          self.assertEqual (2 , Result)
 25          Print( ' Test_normal ' )
 26 is  
27  # assertEqual check whether the two values, like 
28      DEF test_error (Self):
 29          Result = the Add (1,1 )
 30          self.assertEqual (. 1, Result, ' result of the calculation error ' )
 31 is          # Self .assertIn (. 1, [1,2,3,3]) 
32          Print ( ' test_error ' )
 33 is  
34 is      DEF test_all (Self):   # in accordance with the first letter has to perform 
35          Print ( ' test_all ' )
 36  
37 [     DEF test_zero (Self):
 38 is          Print ( ' test_zero ' )
 39  
40  # unittest.main () 
41 is  
42 is  # TestCase 
43 is  # TestSuite # embodiments use set 
44 is  # TestRunner test run # 
45  # testloader lookup test # 
46 is  
47 a test_suite = the unittest .makeSuite (AddTest)    # all test cases to traverse the inside of the class 
48  # File Open = ( 'report.html', 'WB') 
49  # Runner = HTMLTestRunner.HTMLTestRunner (File, title = 'test report') 
50  # Runner. RUN (a test_suite) 
51 is # file.close()
52 
53 report = bfr.BeautifulReport(test_suite)
54 report.report(filename='bf_report.html',description='测试报告',)

 

Guess you like

Origin www.cnblogs.com/xumb/p/11964563.html