- postman是一个跨平台的接口测试工具,下载链接在这里:https://www.getpostman.com/
- unittest是一个单元测试框架,python中安装:pip install unittest
- requests是一个发送http请求的库,安装:pip install requests
官方文档:http://docs.python-requests.org/en/master/user/quickstart/,
中文文档:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
以测试http://www.kuaidi100.com/query 为例:
有一个汇通快递的单号:350757819118
请求的url为http://www.kuaidi100.com/query?type=huitongkuaidi&postid=350757819118
用postman调试接口:
点击右上角的code,如下图:
以python--requests的格式复制:
复制得到的代码如下:
import requests url = "http://www.kuaidi100.com/query" querystring = {"type":"huitongkuaidi","postid":"350757819118"} headers = { 'cache-control': "no-cache", 'postman-token': "9794775a-f3eb-0322-1365-01b775fa9925" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)
新建py文件,命名为kuaidi.py,对复制的代码稍作调整:
import requests import unittest class KuaiDi(unittest.TestCase): def test_huitong_api(self): url = "http://www.kuaidi100.com/query" querystring = {"type":"huitongkuaidi","postid":"350757819118"} headers = { 'cache-control': "no-cache", 'postman-token': "9794775a-f3eb-0322-1365-01b775fa9925" } response = requests.request("GET", url, headers=headers, params=querystring).json() #print(response)
self.assertEqual(response['status'],'200') self.assertEqual(response['message'],'ok') if __name__ == '__main__': unittest.main()
运行结果:
总结:
postman可以帮助完成一半的工作
unittest+requests可以实现断言,方便持续集成
参考文档:http://www.testclass.net/interface/first_case/