之前有不少文章讲解了如何使用Jmeter进行接口测试,其实使用Python也可以进行接口测试,并且很简单。
Requests安装
首先要安装requests的依赖库,使用pip install requests安装即可
假设有一个接口:当用户传入姓名和地点时,就返回一些restaurant:
URL:http://pythontest.com/getrestaurant/
入参:username、location
Get方法
如果是Get方法,那么可以通过如下代码去测试:
#coding=utf-8
import requests
url = "http://pythontest.com/getrestaurant?"
# 接口请求的URL
headers = {
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
}
testdatas = ["Alice","","张三",]
# 需要测试的数据场景,username为英文Alice、Ali、空值、中文张三
for testdata in testdatas:
# 发送请求
data = {'username': testdata, 'location': 'zh'}
# 发送请求的参数及数据
response = requests.get(url,headers=headers,data=data