程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python unittest learning notes

編輯:Python

The main structure of this paper
The first part :UnitTest brief introduction
The second part : Introduction to basic concepts
The third part : Each concept is explained in detail
The fourth part : Program operation
The fifth part : Output of test report

One 、UnitTest brief introduction

UnitTest yes Python Built in test framework , It is mainly applicable to unit testing , And manage and encapsulate multiple test cases .

Two 、 Introduction to basic concepts

( One ) The test case -testcase
Test cases are the bottom layer of the test framework ( similar , Brick is the most basic thing in a house )
The design of each use case , Just like functional use cases , Try to include multiple test points
( Two ) Test firmware -testfixture
Test firmware = Fixed test code ( namely : Test the same parts of the code )
eg: Test an interface , The interface address can be accessed through setup() To initialize , Then each test case can directly call the initialized interface address
For example, through teardown() To finish the test .
( 3、 ... and ) test suite -testsuit
The test suite brings together multiple test cases , It can be understood as A collection of test cases .
( Four ) Test runner -testrunner
Test runner yes To provide a running environment for test cases , Through it run() Method to execute the test case , And output the test results after execution .

3、 ... and 、 Each concept is explained in detail

( One ) The test case

Import Unittest modular ;
Define a test class ( Inherit unittest.TestCase Base class ), A test case is encapsulated in a function
A test class can contain multiple test cases .

( Two ) Test firmware

Put duplicate code together ,
What it does : Reduce redundant code ; It is convenient for later code maintenance
For example, the login check above , In every use case url,
We can go through setup() take url To initialize

 r = requests.post(self.url, json=form)
message = r.json()["message"]
self.assertEqual(message, " success !")

setUp A function is a function of a test case Common part , Like a global variable , For other functions to call , Other functions need not be defined repeatedly , Directly through variable self.url call .

( 3、 ... and ) test suite

The test suite is mainly used to add test cases , How to add use cases , This article mainly introduces three kinds of :
1. adopt TestSuite() Add use cases

def suite():
""" Definition suit() function , Used to return the created test suite instance :return: """
# call TestSuite() Function to generate a test suite instance 
suite = unittest.TestSuite()
# Use addTest Method to add a single test case 
suite.addTest(testSet0Setup("test_set0_0"))
# Use addTests Method to add multiple test cases 
suite.addTests([testSet0Setup("test_set0_1"),testSet0Setup("test_set0_2"),testSet0Setup("test_set0_3")])
return suite

Run code

if __name__ =="__main__":
# Build a runner object 
runner = unittest.TextTestRunner()
#run() call suite() Test case construction 
runner.run(suite())


adopt addTest Add use cases , It is suitable for less test cases , If there are more use cases , Other ways can be considered .

2. adopt makeSuite() Add use cases

def suite():
#makeSuite() It can directly indicate that there is a class below , Case name has been test The first test case is added to the test suite 
suite =unittest.makeSuite(testSet0Setup,"test")
return suite

makeSuite(testSet0Setup,“test”) take testSet0Setup In the “test” The first test case is added to the test suite
obviously : One line of code can add all the required use cases
however : inflexible , Only all... Can be added

Test cases can be extracted from multiple files , And then through TestSuite(suite0,suite1) Combine multiple suites into one test suite instance

def suite():
suite0 =unittest.makeSuite(testSet0Setup,"test")
suite1 = unittest.makeSuite(testSet0, "test")
suite = unittest.TestSuite(suite0,suite1)
return suite

3. adopt defaultTestLoader.discover() Add test coverage

( Four ) test run

Mode one :
runner = unittest.TextTestRunner()
#run() call suite() Test case construction
runner.run(suite())
Mode two : You can also encapsulate all operations into one main(), function unittest.main() that will do

( 5、 ... and ) Test report

unittest The test framework is python Built in framework , But there is no test report output , You need to download and import a third-party module HTMLTestRunner, With HTML Store test results in the form , And will be saved in the form of a report .
HTMLTestRunner Extension module failed to pass pip Installation , The download address is as follows :
http://tungwaiyip.info/software/HTMLTestRunner.html
take py Files in python Installed directory ilb Under the folder , Because it's based on python2 Development , For compatibility python3 grammar , The file needs to be modified as follows :

Line number Before the change After modification 94import StringIOimport io539StringIO.StringIO()io.StringIO()631print >>sys.stderr, ‘\nTime Elapsed: %s’ % (self.stopTime-self.startTime)print(sys.stderr, ‘\nTime Elapsed: %s’ % (self.stopTime-self.startTime))642if not rmap.has_key(cls):if not cls in rmap :766uo = o.decode(‘latin-1’)uo =e772ue = e.decode(‘latin-1’)uo =e778output = saxutils.escape(uo+ue)output = saxutils.escape(str(uo)+str(ue)),

I use HTMLTestRunner The file link is as follows
link : https://pan.baidu.com/s/1vHjiHqaqJkeUWKMl6mwy1g Extraction code : mqen

if __name__ == "__main__":
filepath = "./htmlreport.html"
fp = open(filepath,"wb")
suite = unittest.TestSuite()
suite.addTest(TestAssert("testAssertIn"))
runner = HTMLTestRunner(stream= fp,title= " Test report ",description=" Looking forward to success ")
runner.run(suite)
fp.close()

Run the file to generate the following report :

When generating the test report section , When the test report cannot be generated , For specific solutions, please refer to the following articles :
https://blog.csdn.net/qq_44801116/article/details/125444133?spm=1001.2014.3001.5501


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved