python测试api接口

时间:2021-10-29 01:57:13

在开发中,需要测试web-api的接口 spring mvc 使用单元测试非常方便,但是,受不了单元测试的启动速度。用python写了一个小脚本,用于测试接口,

测试脚本配置文件

api.yaml

server:
url: http://127.0.0.1:9000/ihome/ api:
name:
#api-v2-neighbor-list.yaml
- api/v2/neighbor/list

api-v2-neighbor-list.yaml

接口配置文件

method:
post
data:
#post 的 body 的json
postSid: a1
userSid: u2

python 脚本

import requests, json, yaml, sys

def apiTest(apiName):
f = open("api.yaml")
obj = yaml.safe_load(f)
f.close() if apiName != "":
runApi(obj["server"]["url"] + apiName, apiName.replace("/", "-") + ".yaml")
return; apis = obj['api']["name"]
for api in apis:
runApi(obj["server"]["url"] + api, api.replace("/", "-") + ".yaml") def runApi(url, dataFile):
headers = {'Content-Type' : 'application/json; charset=UTF-8',
'X-Requested-With' : 'XMLHttpRequest',
'Connection' : 'keep-alive',
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'
} f = open(dataFile)
obj = yaml.safe_load(f)
f.close() s = requests.session() if obj["method"] == "get":
r = s.get(url= url, headers = headers)
if obj["method"] == "post":
r = s.post(url= url , data = json.dumps(obj["data"]), headers = headers) status = r.status_code
if status != 200:
print "\x1b[31mfail: status-> {} {}\x1b[0m".format(status, url)
return resp = json.loads(r.text)
if resp["success"] == 0:
print "\x1b[32mpass: {}\x1b[0m".format(url)
else:
print "\x1b[31mfail: {} message: {}\x1b[0m".format(url, resp["message"].encode('utf-8')) def main():
apiName = ""
if len(sys.argv) > 1:
apiName = sys.argv[1] apiTest(apiName) if __name__ == '__main__':
main()