current position:Home>Python interface automation test framework (tools) -- interface test tool requests

Python interface automation test framework (tools) -- interface test tool requests

2022-02-01 17:24:42 I tested it first

「 This is my participation 11 The fourth of the yuegengwen challenge 29 God , Check out the activity details :2021 One last more challenge

Preface

This is an episode , There's a whole bunch of python Basic grammar , Then the tool arrived , Then write down according to the catalogue , To the code layer , But in many code examples requests library , I believe some students will look at a loss , What is this , Why is it here ? So the author goes back and makes up another article , Said at the end ,requests Library code , But what it does , I can think of it as an interface testing tool .

requests

Enclosed requests Document address

It's unnecessary to introduce too many functions , Let's simply say , It can satisfy your daily http Interface testing of the protocol and what else do you want to do with it , Fine !

The code implements your first interface test

pip install requests # install requests library

  • Take the user login interface as an example :/login/ByMobile
import requests

url = "http://127.0.0.1:5000/login/ByMobile"
data = {'zone': 86, 'mobile': 13800138000, 'code': 1231}
res = requests.get(url,params = data)
print(res)
 Copy code 
  • Step 1 guide library , Which library do you want to use , Just introduce it first ;
  • Step 2: prepare parameters : Address of the interface 、 Parameters 、requests Request method of
    • Parameters need to be mentioned , Without incident , All parameters are in dict Data type display
  • Step 3: debugging results , The direct printout is the response status code
#  Yes res Request the output of the result object to test 

print(res) #  Output :<Response [200]>

print(res.status_code) #  Output :200

print(res.json()) #  Output : {'code': 0, 'msg': ' Login successful '}

print(res.text) #  Output :
{
  "code": 0,
  "msg": " Login successful "
}

print(res.content) #  Output binary :b'{\n "code": 0, \n "msg": "\xe7\x99\xbb\xe5\xbd\x95\xe6\x88\x90\xe5\x8a\x9f"\n}\n'

print(res.headers) #  Output response header information :{'Content-Type': 'application/json', 'Content-Length': '42', 'Server': 'Werkzeug/1.0.1 Python/3.7.5', 'Date': 'Tue, 30 Nov 2021 10:04:29 GMT'}
 Copy code 
  • The above is roughly requests Common output content of response object ; Does it feel rich .

Follow the gourd

requests Can support get、post Common methods , It can also receive and request through different parameters , It can be a form 、json object 、params、 There are also different parameters such as uploading files .

It's not here that matters , But we need to encapsulate , It means no matter how it's spread outside , Inside requests How do the parameters and forms of the request correspond to the correct ; So here we need to package , take requests This tool library is being packaged


import json

import requests

from utils.logger import getLog


log = getLog()

class HandleRequests(object):
    ''' classdocs:requests Wrap a layer of , For parameters data、json Distinguish  '''


    def __init__(self):
        ''' Constructor: initialization requests object  '''
        self.http = requests.Session()

    
    def __call__(self, method, url, data=None, **kwargs):
        """ Magic method call """
        
        self.method = method.upper()
        
        if isinstance(data, str):
            try:
                data = json.loads(data)
            except json.JSONDecodeError as error:
                data = eval(data)                log.error("{} The data contains python object , Such as :None\False\True, You can't turn it into dict object :{}".format(data, error))
                            
        if self.method == "POST":
            res = self.http.request(self.method, url, json=data, verify=True, **kwargs)
        elif self.method == "GET":
            res = self.http.request(self.method, url, params=data, verify=True, **kwargs)
        else:
            log.info(" Request method {}, Temporary does not support !!!".format(self.method))
        
        return res
 Copy code 

Expand

Speaking of requests library , Haven't you ever used it to make webservice Interface testing ?

I'm sorry , It really doesn't seem to have , But use suds Third party library to complete .

  • With python2.7 Version as an example , download suds
#  Guide pack 
from suds.xsd.doctor import ImportDoctor, Import
from suds.client import Client

#  These are like soap In the agreement xml Header format , Can comment , Just outputting client Information is just less information 
imp = Import('http://www.w3.org/2001/XMLSchema',
location='http://www.w3.org/2001/XMLSchema.xsd')
imp.filter.add('http://WebXml.com.cn/')

doctor = ImportDoctor(imp)
#  Address 
url="http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl"
client=Client(url,doctor=doctor)
#  Output webservice All the information about the interface : Include request methods 、 Request parameters, etc 
print client
res=client.service.qqCheckOnline("1251111111")
#  Deployment of output xml Format , It's the value of the tag pair 
print res
 Copy code 

copyright notice
author[I tested it first],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011724398888.html

Random recommended