运用python的requests模块进行接口测试
Python经常用requests模块来做http接口测试,requests库的方便易用我们可以通过Python中的requests库来完成向第三方发送http请求的场景
- 安装request库
pip install requests
- 用reque发送请求
import requests
requests.get(“https:....”) #发送GET请求
requests.post(“https:....”) #发送POST请求
requests.put(“https:....”) #发送PUT请求
requests.delete(“https:....”) #发送DELETE请求
requests.head(“https:....”) #发送HEAD请求
requests.options(“https:....”) #发送OPTIONS请求
- 参数传递
- 用聚合数据的天气预报查询系统为例
import requests
api_url='http://apis.juhe.cn/simpleWeather/query'
data={'key':'2d93d9e8d757d65aa3d5ffbe8a63ad64','city':'长沙'}
#把所有需要填写的参数用字典形式表示,并加入请求中
r=requests.get(api_url,data).json()
print(r)
- 上图可看出返回值都是以字典形式反映,则可以提取出其中某一个key做相应的断言
如下:
import requests
import unittest
class Weather_test(unittest.TestCase)
def weather_api(self):
api_url='http://apis.juhe.cn/simpleWeather/query'
data={'key':'2d93d9e8d757d65aa3d5ffbe8a63ad64','city':'长沙'}
res=requests.get(api_url,data)
actual =res.json()['reason']
expected='查询成功'
#把返回值的reason从字典中提取出来与预期结果做比对来进行断言
try:
self.assertEqual()
print('实际结果与预期结果一致')
except:
print("实际结果为{},预期结果为{}".format(actual,expected))