I have sorted out some software testing materials and interview materials (interface automation, web automation, app automation, performance security, test development, etc.), friends who need it can join my learning exchange qun at the end of the article, and get it by yourself without routine~
python + request + unittest + HTMLTestRunner
First introduce the requests module of python:
Introduction to the use of requests: a quick start to requests
Environment Description:
1.WIN 7, 64 bit
2.Python3.4.3 (pip-8.1.2)
3. Requests -> pip install requests
4. The unittest -> unittest framework is the unit test framework that comes with python. Python2.1 and later versions have put unittest into the python development package as a standard block, so unittest does not need to be installed separately.
5. The test report is generated using HTMLTestRunner.
Test ideas:
1. Write a script test for each http interface one by one. (The submitted json string is directly placed in the data dictionary. Excel and other test cases are not used here to write test cases. The test cases are directly realized by scripts.)
2. After writing the test scripts of all the interfaces, since one interface has several test cases, all the py scripts of the same interface should be encapsulated into methods, and each interface should be encapsulated into an interface class.
3. Use testsuite to directly call these interface classes to construct a test set; or use unittest to automatically identify test cases, the discover() method provided in the TestLoader class.
(Naming rules: the interface name should start with test_XXX)
Just connect all the interface test cases to build automated tests.
4. Finally, use HTMLTestRunner to generate a test report.
PUT: Upload the specified URL, usually for modification, which can be understood as an update in the database.
DELETE: Delete the specified resource.
In interface testing, generally speaking, post creates data, get obtains all data after successful creation and the specified data, put can modify the data after successful creation, and delete is the specified resource.
Directory Structure:
An example of a single interface test:
post (modify)
import requests import json def get_token(): url1 = "https://**********/Token/get" content = {'appId':'***','appSecret':'******'} web = requests.get(url=url1,params=content) print(web.url) print(web. text) ty = web.text a = json. loads(ty) b = a.get('Data') apptoken = b.get('Token') return apptoken if __name__ == '__main__': get_token() Copy Code
get(query)
import requests import json def test_qualification_add(): url = "http://xxx.xxx.xxx/audit/api/xxx/get" #test interface url headers = {"Content-Type":"application/json"} data = { #Parameters transmitted by the interface "token": "abcdefg", "id": 1, "param": { "QuId":1 } } r = requests.post(url = url,json = data,headers = headers) #send request #return r.json print (r.text) #Get the response message print (r. status_code) if __name__=="__main__": test_qualification_add() Copy Code
the
Among them, the two writing methods of requests.post and requests.request can realize the request.
In the process of interface testing, the incoming parameters are tested by testing methods such as boundary value testing, error derivation testing, and equivalence class testing. Then an interface requires many test cases.
The following is an example of encapsulation as an interface class:
(An interface addresses a class, and each method is a test case)
(The setUp() and tearDown() methods will act on the beginning and end of each test case respectively. If the setUp() and tearDown() in each class do the same thing, then you can encapsulate your own test class , such as the code:)\
import requests import json import unittest class MyTest(unittest.TestCase): #The class that encapsulates the initialization and restoration of the test environment def setUp(self): # Put the code that can operate on the data, such as the initialization of mysql, momgodb, etc., the database is not operated here! print("start test") pass def tearDown(self): #relative to setUp() print("end test") pass class test_xxx_get(MyTest): #Encapsulate this interface into a class, the following method is a specific test case '''Interface name: get qualification''' #This describes the interface name def test_xxx_get(self): '''Test case 1: Haha''' #This describes the interface use case name self.url = "http://xxx.xxx.xxx/audit/api/xxx/get" #request url self.headers = {"Content-Type":"application/json"} self.data = { #request parameters "token": "abcdefg", "id": 1, "param": { "QuId": 14 } } #self. is used in method attributes, indicating that it is an attribute of the method and will not affect the attributes of other methods. r = requests. post(url = self. url, json = self. data, headers = self. headers) #return r.json() print(self.r.text) print(self.r.status_code) self.assertIn("true",self.r.text) #Assertion to judge whether the interface returns meet the requirements, you can write multiple assertions! if __name__=="__main__": unittest. main() Copy Code
unittest provides a global main() method, which can be used to easily turn a unit test block into a test script that can be run directly;
The main() method uses the TestLoader class to search for all the test methods contained in the block that start with the name “test” and execute it automatically;\
The default order of executing methods is: load test cases according to the order of ASCII codes, and the order of numbers and letters is: 0-9, A-Z, a-z. So the test case method starting with A will be executed first, and the test case method starting with a will be executed later.
Therefore, each interface class and test case should be named after test*, as shown in the figure below:
(Test cases are placed in the same folder:)
\
How to write runtest.py:
import unittest import json import requests from HTMLTestRunner import HTMLTestRunner import time #Load test files (load as many interfaces as there are, and add them one by one) import test_creative_add import test_creative_get import test_qualification_add import test_qualification_get import test_qualification_reflesh #Construct test set suite = unittest.TestSuite() #Instantiation The addTest() method of the #TestSuite class assembles the test methods in different test classes into the test suite. #Add test case==》Interface file name. Interface class (method is other use cases of this interface), every test case must be added! ! ! suite.addTest(test_creative_add.test_creative_add("test_creative_add")) #Add creativity suite.addTest(test_creative_get.test_creative_get("test_creative_get")) #Get creative suite.addTest(test_qualification_add.test_qualification_add("test_qualification_add"))#Increase qualification suite.addTest(test_qualification_get.test_qualification_get("test_qualification_get"))#Get qualification suite.addTest(test_qualification_reflesh.test_qualification_reflesh("test_qualification_reflesh"))#Update qualification if __name__=="__main__": testunit = unittest. TestSuite() testunit. addTest(suite) # Get the current time according to a certain format now = time.strftime("%Y-%m-%d %H_%M_%S") #Define the report storage path filename = './' + now + 'test_result.html' fp = open(filename,"wb") #define test report runner = HTMLTestRunner(stream = fp, title = "xxx interface test report", description = "Test case execution:") # run the test runner. run(testunit) fp.close() #Close the file object and write the data to disk Copy Code
If there are hundreds of test cases, it will be very troublesome to add test cases one by one in the runtest script. In fact, it can be done in one step with discover().
Discover function introduction:
discover(start_dir, pattern=’test*.py’, top_level_dir=None)
Find all test modules in the specified directory, and recursively find the test blocks in the subdirectory. Only the matching file names will be loaded. If the startup is not a top-level directory, then the top-level directory must be specified separately.
start_dir: The block name to be tested or the directory of the test case.
pattern=’test .py’: Indicates the matching principle of the use case file name. This matches all .py type files whose file name starts with test, and represents any number of characters.
top_level_dir=None : The top-level directory of the test block, if there is no top-level directory, the default is None.
The test cases here are all placed in the same directory, all in the form of test*.py! ! (as pictured above)\
runtest2.py writing method:
import unittest import json import requests from HTMLTestRunner import HTMLTestRunner import time #Define the directory of the test case as the current directory test_dir = './' discover = unittest.defaultTestLoader.discover(test_dir, pattern = 'test*.py') if __name__=="__main__": # Get the current time according to a certain format now = time.strftime("%Y-%m-%d %H-%M-%S") #Define the report storage path filename = './' + now + 'test_result.html' fp = open(filename,"wb") #define test report runner = HTMLTestRunner(stream = fp, title = "xxx interface test report", description = "Test case execution:") # run the test runner. run(discover) fp.close() #close report file Copy Code
the
Integrate automated testing to send test reports:
runtest_mail.py
import unittest import requests from HTMLTestRunner import HTMLTestRunner import time import os import smtplib from email.mime.text import MIMEText from email.header import Header #======Define sending mail======== def send_mail(file_new): f = open(file_new,'rb') mail_body = f. read() f. close() msg = MIMEText(mail_body,'html','utf-8') msg['Subject'] = Header('xxx Interface Automation Test Report','utf-8') smtp = smtplib. SMTP() smtp.connect('smtp.sina.com') smtp.login('[email protected]','xxx336..') smtp.sendmail('[email protected]','[email protected]',msg.as_string()) smtp. quit() print('The mail has been sent! Pay attention to check.') #====== Find the test directory and find the latest generated test report ====== def new_report(test_report): lists = os.listdir(test_report) lists.sort(key=lambda fn:os.path.getmtime(test_report + '\' + fn)) file_new = os.path.join(test_report,lists[-1]) print(file_new) return file_new if __name__ == "__main__": test_dir = "D:\dsp_testpro\test_case" test_report = "D:\dsp_testpro\test_report" discover = unittest.defaultTestLoader.discover(test_dir, pattern = 'test*.py') # Get the current time according to a certain format now = time.strftime("%Y-%m-%d_%H-%M-%S-") #Define the report storage path filename = test_report + "" + now + 'result.html' fp = open(filename,'wb') #define test report runner = HTMLTestRunner(stream = fp, title = "xxx interface test report", description = "Test case execution:") # run the test runner. run(discover) fp.close() #close report file new_report = new_report(test_report) send_mail(new_report) Copy Code
Mail as follows:
Finally, I would like to thank everyone who has read my article carefully. Seeing the fans’ growth and attention all the way, there is always a need for reciprocity. Although it is not a very valuable thing, if you need it, you can take it away: strong>
These materials should be the most comprehensive and complete preparation warehouse for friends who are engaged in [software testing]. This warehouse has also accompanied me through the most difficult journey, and I hope it can help you too! Everything should be done as early as possible, especially in the technical industry, we must improve our technical skills. I hope it will be helpful to everyone…If you don’t want to experience the feeling of not being able to find information, no one answering questions, and giving up after a few days of self-study, you can join our test exchange group below to discuss and exchange together study.
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeWeb crawlerrequests257979 people are studying systematically