接口测试--Day6
封装request
查看版本:
# 验证requests版本
pip show requests
# 验证pytest版本
pytest --version
开始的时候,分别对get和post使用不同的定义方法:
# Initiate http get request
def get(self):
try:
response = requests.get(self.url, params=self.params, headers=self.headers, timeout=float(timeout))
return response
except TimeoutError:
self.logger.error("Time out!")
return None
# Initiate http post method
def post(self):
try:
response = requests.post(self.url, headers=self.headers, data=self.data, files=self.files,timeout=float(timeout))
return response
except TimeoutError:
self.logger.error("Time out!")
return None
经研究所有这些请求最终使用的request方法,可以把请求方式作为参数传过去:

requests库封装了复杂的HTTP底层实现,只需简单几行代码即可发送GET、POST等常见接口请求,同时方便解析响应结果。
所有就对request方法进行了封装,使用execute_api_request函数,这样所有的接口就可以使用这一个方法去发起请求,从而减少代码量:
import re
import requests
from interfaceAuto.unit_tools.handle_data.yaml_handler import read_yaml, write_yaml
class SendRequests:
def __init__(self):
pass
@classmethod
def _text_encode(cls,res_text):
"""
处理接口返回值出现unicode编码,如: \\u798b
:param res_text:
:return:
"""
is_match = re.search(r"\\u[0-9a-fA-F]{4}", res_text)
if is_match:
results = res_text.encode().decode('unicode_escape')
else:
results = res_text
return results
def send_request(self, **kwargs):
session = requests.Session()
try:
response = session.request(**kwargs)
cookie_set = requests.utils.dict_from_cookiejar(response.cookies)
if cookie_set:
print(f'获取cookie: {cookie_set}')
except requests.exceptions.ConnectionError:
print("接口请求异常,可能是requst过多导致的错误")
except requests.exceptions.RequestException as e:
print('请求异常,请检查系统或数据是否正常!原因:{e}')
return response
def execute_api_request(self, api_name, url, method, header, case_name=None, cookie=None, file=None, **kwargs):
"""
发起接口请求
:param api_name: 接口名称
:param url: 接口地址
:param method: 请求方法
:param header: 请求头
:param case_name: 测试用例名称
:param cookie: cookie
:param file: 文件上传
:param kwargs: 未知数量的关键字参数
:return:
"""
response = self.send_request(method=method,
url=url,
headers=header,
cookies=cookie,
files=file,
timeout=10,
verify=False,
**kwargs)
return response
if __name__ == '__main__':
data = read_yaml('./../data/login.yaml')[0]
print(data)
url= data['baseInfo']['url']
method = data['baseInfo']['method']
header = data['baseInfo']['header']
print(header)
req_data = data['testCase'][0]['data']
send = SendRequests()
res=send.execute_api_request(api_name=None, url=url, method=method,header=None,data=req_data)
res_json=res.json() #响应返回值是一个字符串,要反序列化后成对象的形式
token = res_json['token']
user_id =res_json['userId']
write_yaml({'token':token, 'userId':user_id}) #获取token保存起来,一遍后续的接口使用,从而达到可以上下游可以复用的目的

浙公网安备 33010602011771号