对v2ex网址查看论坛节点信息的api进行测试
请求内容如下:
Url:https://www.v2ex.com/api/nodes/show.json
Method:GET
Authentication:None
请求参数:name:节点名称
返回结果如下:
{ "avatar_large": "https://cdn.v2ex.com/navatar/8613/985e/90_large.png?m=1610084956", "name": "python", "avatar_normal": "https://cdn.v2ex.com/navatar/8613/985e/90_normal.png?m=1610084956", "title": "Python", "url": "https://www.v2ex.com/go/python", "topics": 14187, "footer": "", "header": "这里讨论各种 Python 语言编程话题,也包括 Django,Tornado 等框架的讨论。这里是一个能够帮助你解决实际问题的地方。", "title_alternative": "Python", "avatar_mini": "https://cdn.v2ex.com/navatar/8613/985e/90_mini.png?m=1610084956", "stars": 9498, "aliases": [], "root": false, "id": 90, "parent_node_name": "programming" }
分析:
接口测试主要验证数据的正确性
- 测试数据:name=python
- 接口地址: https://www.v2ex.com/api/nodes/show.json
- 断言:通过返回结果可以看到 id是固定的“90”,name也是固定的“python”
代码实现
import requests class TestApi(object): domian = 'https://www.v2ex.com/' def test_node1(self): path = 'api/nodes/show.json?name=python' url = self.domian + path res = requests.get(url).json() assert res["name"] == "python" assert res["id"] == 90
这只是固定一个name进行请求,如果多个name呢:
代码如下
import requests import pytest class TestV2exApi(object): domian = 'https://www.v2ex.com/' @pytest.fixture(params=['python','java','go','nodejs']) def lang(self,request): return request.param def test_node(self,lang): path = 'api/nodes/show.json?name=%s' %lang url = self.domian + path res = requests.get(url).json() assert res["name"] == lang assert 0 #模拟错误请求,查看具体参数值
如果要多个参数字段时,代码如下
import requests import pytest class TestApiWithExpectation(object): domain = 'https://www.v2ex.com/' @pytest.mark.parametrize('name,node_id',[('python',90),('java', 63), ('go', 375), ('nodejs', 436)]) def test_node2(self,name,node_id): path = 'api/nodes/show.json?name=%s' %(name) url = self.domain + path res = requests.get(url).json() assert res['name'] == name assert res['id'] == node_id assert 0