使用python+requests编写接口测试用例
好了,有了前几章的的基础,写下来我把前面的基础整合一下,来一个实际的接口测试练习吧。
接口测试流程
- 1.拿到接口的URL地址
- 2.查看接口是用什么方式发送
- 3.添加请求头、请求体
- 4.发送查看返回结果,校验返回结果是否正确
我们知道了接口测试的步骤,下面我们开始组织我们的代码:
import requests
# 接口的url
url = "http://fanyi.baidu.com/v2transapi"
# 接口的参数
params = {
"from":"en",
"to":"zh",
"query": "test"
}
r = requests.request("post", url, params=params)
# 打印返回结果
print(r.text)
# 为了让结果看的更加清楚一点,我取来翻译的字段
import json
d = json.loads(r.text)
print(d['liju_result']['tag'])
结果:
['试验', '测验', '考验', '化验', '考查', '受试验', '受测验', '受考验', '测得结果']
(结果很长,截取最后的)
修改参数后的请求:
import requests
url = "http://fanyi.baidu.com/v2transapi"
params = {
"from":"en",
"to":"zh",
"query": "study" #
}
r = requests.request("post", url, params=params)
import json
d = json.loads(r.text)
print(d['liju_result']['tag'])
结果:
['学习', '研究', '课题', '书房', '结论', '考虑', '沉思', '努力', '想出']
引入unittest单元测试框架集成接口测试:
import requests,unittest,json
class Testbaiduapi(unittest.TestCase):
def setUp(self):
url = "http://fanyi.baidu.com/v2transapi"
def testzhen(self):
params = {
"from":"en",
"to":"zh",
"query": "study" #
}
url = "http://fanyi.baidu.com/v2transapi"
r = requests.request("post", url, params=params)
r=json.loads(r.text)
assert u'学习' in r['liju_result']['tag']
def testzhen1(self):
params = {
"from":"en",
"to":"h",
"query": "study" #
}
url = "http://fanyi.baidu.com/v2transapi"
r = requests.request("post", url, params=params)
r=json.loads(r.text)
assert u'学习' in r['liju_result']['tag']
def tearDown(self):
pass
if __name__=='__main__':
unittest.main(verbosity=2)
在python中,提供了HTMLTestRunner.py来生成测试报告,把该文件下载后,直接放到python安装文件的lib的目录下,
就可以导入该模块使用了,见该实现的代码:
import requests,unittest,json,HTMLTestRunner
class Testbaiduapi(unittest.TestCase):
def setUp(self):
url = "http://fanyi.baidu.com/v2transapi"
def testzhen(self):
params = {
"from":"en",
"to":"zh",
"query": "study" #
}
url = "http://fanyi.baidu.com/v2transapi"
r = requests.request("post", url, params=params)
r=json.loads(r.text)
assert u'学习' in r['liju_result']['tag']
def testzhen2(self):
params = {
"from":"en",
"to":"h",
"query": "stud" #
}
url = "http://fanyi.baidu.com/v2transapi"
r = requests.request("post", url, params=params)
r=json.loads(r.text)
assert u'学' in r['liju_result']['tag']
def tearDown(self):
pass
if __name__=='__main__':
report_dir= r's.html'
re_open= open(report_dir,'wb')
suite=unittest.TestLoader().loadTestsFromTestCase(Testbaiduapi)
runner=HTMLTestRunner.HTMLTestRunner(
stream=re_open,
title=u'百度翻译api接口测试报告',
description=u'百度翻译api接口测试详情'
)
runner.run(suite)