在做python+requests做接口自动化测试时,我们一般会将requests请求进行二次封装,比如:post请求、get请求、put请求等等,如下
'''
接口关键字驱动类,用于提供自动化接口测试的关键字方法
'''
import json
import allure
import jsonpath
import requests
class ApiKey:
# 基于jsonpath获取数据的关键字,用于提取所需要的内容
def get_text(self,data,key):
# loads将json格式数据转换为字典格式
# dumps将字典格式的内容转换为json格式
dict_data = json.loads(data)
value_list = jsonpath.jsonpath(dict_data,key)
return value_list[0]
@allure.step("发送get请求")
# get请求的封装
def get(self,url, params=None, **kwargs):
return requests.get(url, params=params, **kwargs)
@allure.step("发送post请求")
# post请求的封装
def post(self,url, data=None, **kwargs):
return requests.post(url, data=data, **kwargs)
但是我发现这种封装方法还可以做进一步优化,我们先来看看post、get接口的源代码
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
r"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
所有的方法最后return的都是一个request,调用请求的时候,代码是讲获取的URL、data等参数连同请求方式一起传递到request中,那么我们就可以在接口二次封装时,直接封装request请求,同时传递请求方式和参数就行,比如:
'''
接口关键字驱动类,用于提供自动化接口测试的关键字方法
'''
import json
import allure
import jsonpath
import requests
class ApiKey:
# 基于jsonpath获取数据的关键字,用于提取所需要的内容
def get_text(self, data, key):
# loads将json格式数据转换为字典格式
# dumps将字典格式的内容转换为json格式
dict_data = json.loads(data)
value_list = jsonpath.jsonpath(dict_data, key)
return value_list[0]
@allure.step("发送request请求")
def request(self, method, **kwargs):
return requests.request(method, **kwargs)
而method我们可以直接从接口测试用例中获取,这样所有请求接口都直接调用一个方法就行。