打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Pytest-接口请求实例(GET单参数和参数化请求)

对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"
}

分析:

接口测试主要验证数据的正确性

代码实现

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

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python+pytest接口自动化参数关联
【原创】爆肝23页教程,自研关键字驱动框架
httprunner 3.x学习10 - parameters 参数化
一个测试API的pytest框架
[接口测试_B] 13 pytest+requests实战练习
Python 中 Mock 到底该怎么玩?一篇文章告诉你(超全)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服