python3+requests:使用类封装接口测试脚本

转载请注明出处:https://www.cnblogs.com/shapeL/p/9045439.html

前言:接口测试用例较多,我们不可能每个用例都写一次requests,get或者requests,post等,所以对共用方法要进行封装处理

第一次修改:将get请求和post请求单独定义出来,使用过程中根据不同类型的请求直接调用对应的方法

 import requests
import json def send_post(url,data,headers):
response = requests.post(url=url,data=data,headers=headers).json()
return json.dumps(response,sort_keys=True,indent=4) def send_get(url,data,headers):
response = requests.get(url=url,data=data,headers=headers).json()
return json.dumps(response,sort_keys=True,indent=4) def run_main(url,headers,method,data=None):
respose = None
if method == 'GET':
respose = send_get(url,data,headers)
else:
respose = send_post(url,data,headers)
return respose url = 'https://...'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
print(run_main(url,headers,method='POST'))

第二次修改:用class进行封装,主函数中创建一个实例run来调用类中的方法

 import requests
import json
class Runmain:
def send_post(self,url,data,headers):
response = requests.post(url=url,data=data,headers=headers).json()
return json.dumps(response,sort_keys=True,indent=) def send_get(self,url,params,headers):
response = requests.get(url=url,params=params,headers=headers).json()
return json.dumps(response,sort_keys=True,indent=) def run_main(self,url,params,data,headers,method):
respose = None
if method == 'GET':
respose = self.send_get(url,params,headers)
else:
respose = self.send_post(url,data,headers)
return respose if __name__ == '__main__':
run = Runmain()
url = 'https://...'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
print(run.run_main(url,params=None,data=None,headers=headers,method='POST'))

第三次修改:第二次修改,每次都需要实例化后再调用对应的方法;

改进办法:使用__init__方法实现:只要实例化类时候就会调用__init__方法

 import requests
import json
class Runmain:
def __init__(self,url,params,data,headers,method):
self.response = self.run_main(url,params,data,headers,method) def send_post(self,url,data,headers):
response = requests.post(url=url,data=data,headers=headers).json()
return json.dumps(response,sort_keys=True,indent=) def send_get(self,url,params,headers):
response = requests.get(url=url,params=params,headers=headers).json()
return json.dumps(response,sort_keys=True,indent=) def run_main(self,url,params,data,headers,method):
respose = None
if method == 'GET':
respose = self.send_get(url,params,headers)
else:
respose = self.send_post(url,data,headers)
return respose if __name__ == '__main__':
url = 'https://...'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
run = Runmain(url,params=None,data=None,headers=headers,method='POST')
print(run.response)

备注:对python中类,实例不了解的同学,可以参考:

http://yangcongchufang.com/%E9%AB%98%E7%BA%A7python%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80/python-object-class.html

上一篇:关于css中为什么要设置html和body的高度?


下一篇:jquery轮播图片(无插件简单版)