1, install requests,xlrd,json,unittest library
<1>pip Command installation :
pip install requests
pip install xlrd
pip install json
pip install unittest
<2> pycharm Install in

2, utilize Page Object Model Six categories of design concept creation Python Package( It can also be implemented according to the requirements of the project )

3, First in base Create one in the package Base_Page.py

<1> Import module , And create Base class , Encapsulating various request methods
import requests # Import requests modular class Base(): 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 comes params Parameters or data parameter , But not both , So it's used here None, And so on

<2> Adapted to interface use case execution , read Excel Watch time , Judge all kinds of requests , When which one , We'll do that
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> Simple debugging of several requests , Debugging passed , Then we can move on to the next item

You can also get what you need cookie The interface is encapsulated and saved :
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 will base Page verification of the code to do clear , Otherwise, these interfaces will always be called

4, again common Class commons.py file , And create common class

<1> Encapsulation log method

Here I added one data package , For storage xlrd surface , as well as html Report storage path ,log Log storage path
import os base_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)
)) log_path = base_path + '\\' + 'report' + '\\' + 'logs' report_html =
base_path+ '\\' + 'html' read_xlrd = base_path + '\\' + 'data' class Common():
# Encapsulation log method defget_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> Package read Excel Table method , Turn him into a dictionary , convenient json Format read
# read Excel Table method , It is convenient for 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 surface sheets= work_book.sheet_names() # Get all sheets page DatasList = [] 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 # The final return is in dictionary form There are keys and values
Why change the format ?
Here is how to design an automatic interface use case

The parameter value of the use case should be json Format write , No spaces
The output parameters of the expected results should also be used json Format write
Don't have it ’’ Use all the values "" wrap up
x

<3> Encapsulating a generation HTML Reporting methods
# Package one HTML Reporting methods 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)
The rest can be added , I have three basic enough

5, stay case Bao xiachuang test Use cases , And call our base Page wrapped request api as well as common Read in Excel Data table combination

<1> establish test_login.py

<2> Import unittest,common Under class commons class ,ddt Data driven ,Base Next base_page page
import unittest import ddt import Automatic interface test .common.commons as common from Automatic interface test
.base.Base_Page import Base
<3> build unittest Inside the framework , And fill in the method
import unittest import ddt import Automatic interface test .common.commons as common from Automatic interface test
.base.Base_Page import Base r = common.Common().ReadExcelTypeDict('cezxhi .xlsx'
) # Get specific Excel Table data @ddt.ddt # Import ddt modular class TestLogin(unittest.TestCase):
@classmethod defsetUpClass(cls) -> None: # setupclass Class method All use cases are executed once before they start cls.logs =
common.Common().get_logs() # Log import method cls.logs.debug(' Start writing interface automation test cases ')
@classmethod deftearDownClass(cls) -> None: cls.logs.debug(' End of automation interface use case ') def
setUp(self) -> None: self.logs.debug(' Start this interface use case ') def tearDown(self) -> None:
self.logs.debug(' Close this use case ') @ddt.data(*r) # introduce ddt modular , Read the data def test_logins(self,
pars): # Use case method name must begin with test pars The parameter is the data value of the received table import json # Import json modular dic = json.loads(
pars['body Parameter value ']) # take Excel The parameter values in the data are converted to json format url = pars[' Interface address '] # Get the request url yuqi =
pars[' Expected results '] # Get the expected results fs = pars[' Request method '] # How to get the request result = Base().requests_type(
method= fs,url = url,data = dic) # fill base Page request api self.assertEqual(result.text,
yuqi) # Make an assertion See if the use case passes
<4> Generate test report after executing use case :
if __name__ == '__main__': load = unittest.TestLoader().loadTestsFromTestCase(
TestLogin) # use loader Loading mode To find all that has been test Use case at the beginning suite = unittest.TestSuite([load,])
common.Common().GetHtmlResult(suite,' Login test case ')
<5> copy The current script path to execute , Add to run as python in

Finally, we run once

The console looks like this

Why 400 What about ? Because some interfaces are abnormal , such as url FALSE , Fewer incoming parameters , Aerial reference , So it's going to go wrong , In common sense

<6> Take a look at the generated test report

stay pycharm This is the case in China

And then we copy Check his path in the browser

Based on what I'm tracking , The first failure is because sessionId It can be changed , Each time the value is different , I hope you can find it here BUG, And properly handle every problem

I wish you all a happy life
Leave a message below the problem blog
Xiaoyou will try her best to answer

Technology
©2020 ioDraw All rights reserved
Java exercises 1: Simply define a car class New photo album app launched by Microsoft : Using cross platform framework React Native to write Chapter two Fundamentals of programming Programming exercises pandas Time order of webpack Code segmentation import()Vue slot slot: Default slot , Named slot , Scope slot Fundamentals of data analysis ——R language ( Processing missing values )C++ Implementation of matrix meteor shower effect PostMan Advanced Usage , Interface MD5+Secret autograph Sign The 12th Blue Bridge Cup B group C/C++ Provincial competition