There is a built-in unit testing framework in Python, the unittest module, which is used for unit testing. It encapsulates some methods of verifying the returned results and some initialization operations before execution of use cases.
Before talking about unittest, let's talk about a few concepts:
TestCase is also a test case
TestSuite A collection of multiple test cases is TestSuite
TestLoader is used to load TestCase into TestSuite
TestRunner is used to execute test cases, and the test results will be saved in the TestResult instance, including how many test cases were run, how many were successful, and how many failed.
Write a simple unit test case below
import unittest from BeautifulReport import BeautifulReport def calc(x,y): return x+y class TestCalc(unittest.TestCase): def test_pass_case(self): #The use case must start with test print('This passes the use case') res=calc(1,2) self.assertEqual(3,res) def setUp(self): #Execute the operation before each use case print('I am setup..') def tearDown(self): #Execute the operation after each use case print('I am teardown') @classmethod def setUpClass(cls): print('I am setupclass') @classmethod def tearDownClass(cls): print('I am teardownclass') def test_a(self): print('a') def test_fail_case(self): print('This is a failed test case') res=calc(9,8) self.assertEqual(98,res) if __name__=='__main__': #unittest.main() #Execute the case in this class alone # suite=unittest.TestSuite() # suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCalc)) # runner = unittest.TextTestRunner(verbosity=2) # runner.run(suite) suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(TestCalc))#All test cases in this class result=BeautifulReport(suite) result.report(filename='test report', description='description', log_path='.')
Some common assertions:
assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) bool(x) is True assertFalse(x) bool(x) is False assertIsNone(x) x is None assertIsNotNone(x) x is not None assertIn(a, b) a in b assertNotIn(a, b) a not in b
Then how to generate a test report, you need to add another module, HTMLTestRunner, this module needs to be installed by yourself, using the execution test case will generate an html test report, which will have the execution result of each test case, the code is as follows:
import HTMLTestRunner import unittest class MyTest(unittest.TestCase):#继承unittest.TestCase def tearDown(self): # Do operations after each test case is executed print('111') def setUp(self): # Do the operation before each test case is executed print(22222) def test_run(self): # self.assertEqual(1,1) self.assertIs(1,1) #test case def test_run2(self): # self.assertEqual(1,1) self.assertIs(1,1) #test case def test_run3(self): # self.assertEqual(1,1) self.assertIs(1,1) #test case def test_run1(self): # self.assertEqual(1,1) self.assertIs(1,1) #test case if __name__ == '__main__': test_suite = unittest.TestSuite() #Create a test set test_suite.addTest(MyTest('test_run1'))#Add test cases to the test suite #test_suite.addTest(unittest.makeSuite(MyTest))#Add all test methods using the makeSuite method fp = open('res.html','wb')#Open an html file that saves the result runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='api test report', description='test situation') #Generate the object that executes the use case runner.run(test_suite) #Execute the test suite
If we have many modules, many python files are written under each module, and each python file has test cases, then how to execute all the test cases in this directory, we must first find all the test cases in this directory python file, and then find the test cases in it and execute them one by one. The code is as follows:
import unittest,HTMLTestRunner suite = unittest.TestSuite() #Create a test suite all_cases = unittest.defaultTestLoader.discover('.','test_*.py') #Find all test cases in Python files starting with test in a directory for case in all_cases: suite.addTests(case)#Add all test cases fp = open('res.html','wb') runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title='all_tests',description='All test cases') runner.run(suite) #run test
When we perform continuous integration in the future, we will use Jenkins to automatically run the code, but the test reports generated above are all in html format, which Jenkins does not recognize, so they cannot be displayed in Jenkins. Then we need to generate some test reports that Jenkins knows. Jenkins knows the reports in xml format, so we need to use a new module, xmlrunner, to install directly pip install xmlrunner. The code is as follows:
import unittest import xmlrunner #import this module class My(unittest.TestCase): def test1(self,a,b,c): self.assertEqual(a+b,c) if __name__=='__main__': test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(My)) runner = xmlrunner.XMLTestRunner(output='report')#Specify the directory where the report is placed runner.run(test_suite)
Then we run, you can see that the report in xml format has been generated in the report directory, and the date is automatically added