1. Install requests, xlrd, json, unittest libraries
<1>pip command installation:
pip install requests
pip install xlrd
pip install json
pip install unittest
<2> Install in pycharm
2. Use the Page Object Model design concept to create six types of Python Packages (can also be implemented according to project requirements)
3. First create a Base_Page.py in the base package
<1>Import the module and create a Base class to encapsulate various request methods
import requests #Import requests module classBase(): def method_post(self, url, params = None, data = None, headers = None, files = None): return requests.post(url = url,params = params,data = data,headers = headers,files = files) def method_get(self, url, params = None, data = None, headers = None, files = None): return requests.get(url = url,params = params,data = data,headers = headers,files = files) def method_put(self, url, params = None, data = None, headers = None, files = None): return requests.put(url = url,params = params,data = data,headers = headers,files = files) def method_delete(self,url,params = None,data = None,headers = None,files = None): return requests.delete(url = url,params = params,data = data,headers = headers,files = files)
Because every request will have params parameters or data parameters, but it is impossible for both to exist, so None is used here, and so on.
<2>Adapted to the execution of interface use cases, when reading the Excel table, various types of requests are judged, and when they match which one, which one is executed
def requests_type(self, method, url, params = None, data = None, headers = None, files = None): if method =='post' or method =='POST': return self.method_post(url = url,params = params,data = data,headers = headers,files = files) elif method =='get' or method =='GET': return self.method_get(url = url,params = params,data = data,headers = headers,files = files) elif method =='put' or method =='PUT': return requests.put(url = url,params = params,data = data,headers = headers,files = files) elif method =='delete' or method =='DELETE': return requests.delete(url = url,params = params,data = data,headers = headers,files = files)
<3> Simply debug several requests. If the debugging is successful, then we can proceed to the next item
You can also encapsulate and save the interface that needs to get the cookie:
def Get_Login_cookie(self,data): res = self.method_post(url = "Request URL",data = data) return {"userId":str(res.json()['result']['userId']),"sessionId":res.json()['result'][ 'sessionId']}
After that, we need to clear these codes for base page verification, otherwise these interfaces will always be adjusted.
Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected. If you don’t want to experience the feeling of not being able to find resources when studying on your own, having no one to answer your questions, and persisting for a few days before giving up. You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc. Share their experience, and also share many live lectures and technical salons You can learn for free! Focus on it! Open source! ! ! QQ group number: 110685036
4. Create the commons.py file under the common class and create the common class
<1> Encapsulating log method
Here I added a data package to store the xlrd table, as well as the html report storage path and log storage path.
log_path = r'D:\PycharmProjects\Automation Interface\Automation Interface Test\report\logs' report_html = r'D:\PycharmProjects\Automation Interface\Automation Interface Test\report\html' read_xlrd = r'D:\PycharmProjects\Automation Interface\Automation Interface Test\data' class Common(): #Encapsulation log method def get_logs(self,path = log_path): import logging,time logs = logging.getLogger() logs.setLevel(logging.DEBUG) path = path + '/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.log' write_file = logging.FileHandler(path,'a + ',encoding='utf-8') write_file.setLevel(logging.DEBUG) set_logs = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(levelname)s - %(message)s') write_file.setFormatter(set_logs) pycharm_text = logging.StreamHandler() pycharm_text.setFormatter(set_logs) logs.addHandler(write_file) logs.addHandler(pycharm_text) return logs
<2> Encapsulate the method of reading Excel table and convert it into dictionary form to facilitate reading in json format
# Read Excel table method to facilitate subsequent reading of interface use case data def ReadExcelTypeDict(self,file_name,path = read_xlrd): path = path + '/' + file_name import xlrd work_book = xlrd.open_workbook(path) #Open Excel table sheets = work_book.sheet_names() # Get all sheets pages DataList = [] for sheet in sheets: sheets = work_book.sheet_by_name(sheet) nrows = sheets.nrows for i in range(0,nrows): values = sheets.row_values(i) DatasList.append(values) title_list = DatasList[0] content_list = DatasList[1:] new_list = [] for content in content_list: dic = {} for i in range(len(content)): dic[title_list[i]] = content[i] new_list.append(dic) return new_list #Finally returned in dictionary form with keys and values
Why convert the format?
This involves how to design an automation interface use case
The parameter values of the use case must be written in json format without spaces.
The expected result parameters must also be written in json format.
If there is no ‘ ‘ value, it must be wrapped with ” “
<3>Encapsulate a method of generating HTML reports
# Encapsulate an HTML report method def GetHtmlResult(self,suite,title,path = report_html): import HTMLTestReportCN,time path = path + '/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.html' with open(path,'wb + ') as f: run = HTMLTestReportCN.HTMLTestRunner(stream=f, description='User-related interface test report', tester='Xiaobai', title = title) run.run(suite)
If there are others that need to be added, you can continue to add them. The three I have here are basically enough.
5. Create a test case under the case package, and call the request api we encapsulated in the base page and read the Excel data table in common for joint use
<1>Create test_login.py
<2> Import unittest, commons class under common class, ddt data driver, base_page page under Base
import unittest import ddt import automated interface testing.common.commons as common from automated interface testing.base.Base_Page import Base
<3> Build the inside of the unittest framework and fill in the methods
import unittest import ddt import automated interface testing.common.commons as common from automated interface testing.base.Base_Page import Base r = common.Common().ReadExcelTypeDict('cezxhi .xlsx') # Get specific Excel table data @ddt.ddt #Import ddt module class TestLogin(unittest.TestCase): @classmethod def setUpClass(cls) -> None: # setupclass class method is executed once before all use cases start cls.logs = common.Common().get_logs() # Import log method cls.logs.debug('Start writing interface automated test cases') @classmethod def tearDownClass(cls) -> None: cls.logs.debug('Automation interface use case ends') def setUp(self) ->None: self.logs.debug('Start this interface use case') def tearDown(self) ->None: self.logs.debug('End this use case') @ddt.data(*r) #Introduce the ddt module and read the obtained data def test_logins(self,pars): # The use case method name must start with the test pars parameter as the received table data value import json #Import json module dic = json.loads(pars['body parameter value']) # Convert parameter values in Excel data to json format url = pars['interface address'] # Get the request url yuqi = pars['Expected result'] # Get the expected result fs = pars['request method'] # Get the request method result = Base().requests_type(method = fs,url = url,data = dic) # Fill in the request api of the base page self.assertEqual(result.text,yuqi) # Make assertions to see if the use case passes
<4> Generate a test report after executing the use case:
if __name__ == '__main__': load = unittest.TestLoader().loadTestsFromTestCase(TestLogin) #Use the loader loading method to find all use cases starting with test suite = unittest.TestSuite([load,]) common.Common().GetHtmlResult(suite,'Login test case')
If you want to exchange experiences on software testing, interface testing, automated testing, and interviews. If you are interested, you can add software testing communication: 1085991341, and there will also be technical exchanges with peers.
<5> Copy the path of the script currently to be executed and add it to the running mode of python
Finally, let’s run it
The console looks like this
Why is there 400? Because some interfaces are abnormal, such as wrong url, few parameters or empty parameters are passed in, so errors will occur. This is common sense.
<6> Look at the generated test report
This is what happens in pycharm
Then we copy his path and view it in the browser
According to the information I tracked, the first failure was because the sessionId can change, and the value is different every time. I also hope that everyone can find the BUG and properly handle every problem.
I hope the above content is helpful to you. Friends who have been helped are welcome to like and comment.
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeHomepageOverview 383353 people are learning the system