封装接口测试脚本
Posted xiamaojjie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装接口测试脚本相关的知识,希望对你有一定的参考价值。
将get和post封装到一起,根据请求方式不同,决定调用的方法。调用的时候只调用一个就可以了。
import requests import json class Interface(): ‘‘‘练习接口测试‘‘‘ def send_post(self, url, data): ‘‘‘封装post请求‘‘‘ result = requests.post(url, data) assign = result.json() return json.dumps(assign, indent=4, sort_keys=True, ensure_ascii=False) def send_get(self, url, data): ‘‘‘封装get请求‘‘‘ result = requests.get(url, data) assign = result.json() return json.dumps(assign, indent=4, sort_keys=True, ensure_ascii=False) def run_main(self, url, method, data=None): ‘‘‘根据请求方式调用方法执行‘‘‘ res = None if method == ‘GET‘: res = self.send_get(url, data=None) else: res = self.send_post(url, data) return res if __name__ == ‘__main__‘: ‘‘‘调用执行‘‘‘ api = Interface() url = ‘https://api.apishop.net/common/weather/get15DaysWeatherByArea‘ data = { "apiKey": ‘chgaxvsf88f3858a15fa4426f4cbdd4d2a02b92ee0747f3‘, "area": ‘重庆‘, } print(api.run_main(url, ‘POST‘,data))
较为容易理解的写法:
import requests import json def send_post(url,data): ‘‘‘封装post请求‘‘‘ result = requests.post(url,data) assign = result.json() return json.dumps(assign,indent=4,sort_keys=True,ensure_ascii=False) def send_get(url,data): ‘‘‘封装get请求‘‘‘ result = requests.get(url,data) assign = result.json() return json.dumps(assign,indent=4,sort_keys=True,ensure_ascii=False) def main(url,method,data=None): ‘‘‘根据请求方式调用方法执行‘‘‘ if method == ‘GET‘: return send_get(url,data) else: return send_post(url,data) url = ‘https://api.apishop.net/common/weather/get15DaysWeatherByArea‘ data = { "apiKey":‘chgaxvsf88f3858a15fa4426f4cbdd4d2a02b92ee0747f3‘, "area":‘重庆‘, } #url = ‘https://mgapp.sitezt.cn/api/info/mgapp/index/getindexbanner‘ print(main(url,‘POST‘,data))
以上是关于封装接口测试脚本的主要内容,如果未能解决你的问题,请参考以下文章
python+pytest接口自动化-测试函数测试类/测试方法的封装
python+pytest接口自动化-测试函数测试类/测试方法的封装