我去吹吹风
V1
2021/05/09阅读:192主题:红绯
接口自动化测试框架实战:Requests方法的封装
“本来想着结合实际来进行代码的分享,但一直也没有找到演示的网站。为了加快进度,我想了想,索性还是把学习教程的笔记直接分享了吧。至于你怎么用,结合自己公司的实际进行改造即可。
”
这个教程整个学下来,你会发现很简单。其中很绕的地方,我会多分几个章节来写。
当时学习的时候,也是搞了很长时间。现在回过头去看,发现也还挺简单的。主要是当时遇到困难,没有坚持,丢了好长时间。最后一鼓作气,最终拿下。
接口测试框架流程
如果你学过这个教程的话,你一眼就能看出来这是哪家的。我在简书是直接贴了源码的。 咱也要有自己原创的东西,所以我会在里面融入自己的改造。大家也可以结合自己公司的实际,借鉴其思想,进行搭建。
【注】测试用例编写,我们稍后会提供样例,所以此步骤我们跳过了。项目搭建按照上一节思路篇建好目录即可。
requests库的使用
这个前面我们分享读官方教程的文章。我之前搞过一段时间的爬虫,会感觉这块很简单。
本教程不会涉及很复杂的东西,所以这部分知识我们暂时忽略。有需要,我们再搞几个章节分享。
requests方法的初步封装
没有什么需要发挥的地方,这里直接抄写了官方的教程。
requests方法的重构
总结一下
方法封装: Get封装 Post封装 Get/Post重构
方法重构:封装requests公共方法
-
增加cookies,headers参数 2.增加函数判断url是否以https/http开头 3.根据参数method判断get/post请求 -
重构Post方法 -
重构Get方法
源码分享
import requests
# from utils.LogUtil import my_log
#1、创建封装get方法
def requests_get(url,headers):
#2、发送requests get请求
r = requests.get(url,headers = headers)
#3、获取结果相应内容
code = r.status_code
try:
body = r.json()
except Exception as e:
body = r.text
#4、内容存到字典
res = dict()
res["code"] = code
res["body"] = body
#5、字典返回
return res
#post方法封装
#1、创建post方法
def requests_post(url,json=None,headers=None):
#2、发送post请求
r= requests.post(url,json=json,headers=headers)
#3、获取结果内容
code = r.status_code
try:
body = r.json()
except Exception as e:
body = r.text
#4、内容存到字典
res = dict()
res["code"] = code
res["body"] = body
#5、字典返回
return res
#重构
#1、创建类
class Request:
#2、定义公共方法
def __init__(self):
# self.log = my_log("Requests")
pass
def requests_api(self,url,data = None,json=None,headers=None,cookies=None,method="get"):
if method =="get":
#get请求
# self.log.debug("发送get请求")
r = requests.get(url, data = data, json=json, headers=headers,cookies=cookies)
elif method == "post":
#post请求
# self.log.debug("发送post请求")
r = requests.post(url,data = data, json=json, headers=headers,cookies=cookies)
#2. 重复的内容,复制进来
#获取结果内容
code = r.status_code
try:
body = r.json()
except Exception as e:
body = r.text
#内容存到字典
res = dict()
res["code"] = code
res["body"] = body
#字典返回
return res
#3、重构get/post方法
#get
#1、定义方法
def get(self,url,**kwargs):
#2、定义参数
#url,json,headers,cookies,method
#3、调用公共方法
return self.requests_api(url,method="get",**kwargs)
def post(self,url,**kwargs):
#2、定义参数
#url,json,headers,cookies,method
#3、调用公共方法
return self.requests_api(url,method="post",**kwargs)

作者介绍
我去吹吹风
V1