五:使用python进行组织编写接口测试用例
接口测试其实就是几个步骤。
- 拿到接口的url地址
- 查看接口是用什么方式发送
- 添加请求头,请求体
- 发送查看返回结果,校验返回结果是否正确
明白了接口测试的测试步骤,那么我们就可以来组织我们的代码。
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'])
结果:
['学习', '研究', '课题', '书房', '结论', '考虑', '沉思', '努力', '想出']
ps:我们看看利用工具测试该接口
接下来我们来引入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": "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__': 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)
执行后,会在当前目录下生成测试报告,截图如下:
其他接口的测试方法也是这个思路,