所需工具:postman、python+pycharm、requests、unittest
- postman可以帮助我们完成50%左右的工作,比如调试接口,导出部分代码等
- 使用unittest重构用例可以帮助我们添加断言,提供在命令行执行的能力
测试接口:
地址:https://www.v2ex.com/api/nodes/show.json
Method: GET
Authentication: None(无鉴权)
接受参数: name,此处测试数据name=python,即https://www.v2ex.com/api/nodes/show.json?name=python
响应数据:
{
"avatar_large": "https://cdn.v2ex.com/navatar/8613/985e/90_large.png?m=1617509636",
"name": "python",
"avatar_normal": "https://cdn.v2ex.com/navatar/8613/985e/90_normal.png?m=1617509636",
"title": "Python",
"url": "https://www.v2ex.com/go/python",
"topics": 14287,
"footer": "",
"header": "\u8fd9\u91cc\u8ba8\u8bba\u5404\u79cd Python \u8bed\u8a00\u7f16\u7a0b\u8bdd\u9898\uff0c\u4e5f\u5305\u62ec Django\uff0cTornado \u7b49\u6846\u67b6\u7684\u8ba8\u8bba\u3002\u8fd9\u91cc\u662f\u4e00\u4e2a\u80fd\u591f\u5e2e\u52a9\u4f60\u89e3\u51b3\u5b9e\u9645\u95ee\u9898\u7684\u5730\u65b9\u3002",
"title_alternative": "Python",
"avatar_mini": "https://cdn.v2ex.com/navatar/8613/985e/90_mini.png?m=1617509636",
"stars": 9549,
"aliases": [
],
"root": false,
"id": 90,
"parent_node_name": "programming"
}
断言:返回的结果里,id必须是90,name必须等于python
使用postman调试接口
选择右上角的Code菜单,导出为python requests的代码,拷贝
导出的代码应该是这个样子的:
导出的代码只是3A里的Arrange和Act,我们使用unittest来重构代码:
import requests
import unittest
class V2exAPITestCase(unittest.TestCase):
def test_node_api(self):
url = "https://www.v2ex.com/api/nodes/show.json"
querystring = {"name":"python"}
response = requests.request("GET", url, params=querystring).json()
self.assertEqual(response['name'], 'python')
self.assertEqual(response['id'], 90)
if __name__ == '__main__':
#unitest.main()函数用来测试类中以 test 开头的测试用例
unittest.main()