接口测试-JsonShema断言

接口测试-JsonShema断言

当接口测试返回的响应非常多字段时,不可能一个个字段去断言,这个时候就可以利用schema格式校验的方式去断言

python 用法

1 下载依赖包
	pip install jsonschema
2 获取响应schema

schema内容一般有以下两种获取方式

  1. 直接从接口文档中获取,部分接口文档可以
  2. 可以获取json响应后再转换网上进行转换
  • 先获取响应
 {
   "code": 200,
    "message": "成功",
    "data": {
        "status": 1,
        "tips": "等待扫描",
        "token": null
    },
    "timestamp": 1656932916768
}
  • 进行转换
{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "$ref": "#/definitions/Welcome",
    "definitions": {
        "Welcome": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "code": {
                    "type": "integer"
                },
                "message": {
                    "type": "string"
                },
                "data": {
                    "$ref": "#/definitions/Data"
                },
                "timestamp": {
                    "type": "integer"
                }
            },
            "required": [
                "code",
                "data",
                "message",
                "timestamp"
            ],
            "title": "Welcome"
        },
        "Data": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "status": {
                    "type": "integer"
                },
                "tips": {
                    "type": "string"
                },
                "token": {
                    "type": "null"
                }
            },
            "required": [
                "status",
                "tips",
                "token"
            ],
            "title": "Data"
        }
    }
}
3 进行断言
    def test_get_list(self, desc, name):
        schema = 'json_schema' # json_schema是我们转换得到的schema
        res = {
		   "code": 200,
		    "message": "成功",
		    "data": {
		        "status": 1,
		        "tips": "等待扫描",
		        "token": null
		    },
		    "timestamp": 1656932916768
		}
        validate(res, schema)
	
		# 也可以将schema存成一个json文件后进行读取校验
		schema_json = json.loads(open('file_path','r',encoding='utf-8').read())
		validate(res, schema)

Java用法

我用java做接口都是借助rest assured 框架的 所以这里也是介绍使用rest assured的方式进行schema断言;如果有兴趣的话大家也可以去了解一下这个框架

  • 前面两步是一样的
  • 执行断言如下
	given()
	    .get("http://localhost:8000/rest-assured.json")  // 接口地址
	    .then()
	    .body(matchesJsonSchemaInClasspath("json_schema.json")) // 获取到body后进行schema校验
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值