• 技术分享 | 接口自动化测试之JSON Schema模式该如何使用?


    原文链接

    JSON Schema 模式是一个词汇表,可用于注释和验证 JSON 文档。在实际工作中,对接口返回值进行断言校验,除了常用字段的断言检测以外,还要对其他字段的类型进行检测。对返回的字段一个个写断言显然是非常耗时的,这个时候就需要一个模板,可以定义好数据类型和匹配条件,除了关键参数外,其余可直接通过此模板来断言,JSON Schema 可以完美实现这样的需求。

    JSON Schema 官网:

    http://json-schema.org/implementations.html

    环境准备

    安装 JSON Schema 包

    • Python 版本
    pip install jsonschema
    
    
    • 1
    • 2
    • Java 版本
    
        io.rest-assured
        json-schema-validator
        3.0.1
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    JSON Schema 的使用

    JSON Schema 模板生成

    首先要借助于 JSON Schema tool 的网站 https://www.jsonschema.net/,将返回 json 字符串复制到页面左边,然后点击 INFER SHCEMA,就会自动转换为 schema json 文件类型,会将每个地段的返回值类型都设置一个默认类型,在 pattern 中也可以写正则进行匹配。
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K12bEfqU-1659923704774)(upload://rWFXH62wcBJrNH0xcCf6O7w1UJA.png)]

    点击“设置”按钮会出现各个类型返回值更详细的断言设置,这个就是 schema 最常用也是最实用的功能。也可以对每种类型的字段最更细化的区间值校验或者断言,例如长度、取值范围等。

    点击复制按钮,可以将生成的 schema 模板保存下来。

    实战练习

    接下来会发起一个 post 请求,验证响应值中的 url 字段与 origin 字段是否都为 string 类型。

    Python版本

    import requests
    from jsonschema import validate
    def test_schema():
        schema = {
              "type": "object",
              "properties": {
                "url": {
                  "type": "string"
                },
                "origin": {
                  "type":"string"
                }
              }
            }
        r = requests.post("https://httpbin.ceshiren.com/post")
        validate(instance=r.json(), schema=schema)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    如果将 origin 的 type 写成 number ,则会出现报错:

    import requests
    from jsonschema import validate
    def test_schema():
        schema = {
              "type": "object",
              "properties": {
                "url": {
                  "type": "string"
                },
                "origin": {
                  "type":"number"
                }
              }
            }
        r = requests.post("https://httpbin.ceshiren.com/post")
        validate(instance=r.json(), schema=schema)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    返回报错信息

    > raise error
    E jsonschema.exceptions.ValidationError: 'xxx.xxx.xxx.xxx' is not of type 'number'
    E Failed validating 'type' in schema['properties']['origin']:
    E {'type': 'number'}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    同理,若将 url 的 type 改为 number,也会有报错提示。

    > raise error
    E jsonschema.exceptions.ValidationError: 'https://httpbin.ceshiren.com/post' is not of type 'number'   
    E Failed validating 'type' in schema['properties']['url']:
    E {'type': 'number'}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Java 版本

    JsonValidator.json 文件中存放校验文件,校验响应值中的 url 字段与 origin 字段是否都为 string 类型,文件内容为:

      "type": "object",
      "properties": {
        "url": {
          "type": "string"
        },
        "origin": {
          "type":"string"
        }
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    同 Python 版本一致,以下代码校验响应值是否符合 JsonValidator.json 文件中规定的格式要求。

    import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
    import static io.restassured.RestAssured.*;
    
    public class Requests {
        public static void main(String[] args) {
            //定义请求头信息的contentType为application/json
            given().when().
                    post("https://httpbin.ceshiren.com/post").
                    then().assertThat().
                    body(matchesJsonSchemaInClasspath("JsonValidator.json"));
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    ⬇️ 复制“下方链接”,提升测试核心竞争力!

    你好呀,喜欢这篇文章的话记得点个“赞”哦!大家的支持很重要~() PS:有问题可以联系我们哦

    更多技术文章分享和免费资料领取

  • 相关阅读:
    Postgresql随手记(10)动态执行EXECUTING语法解析过程
    Rust中的闭包
    【一】初步认识数据库
    如何运营独立站?
    金仓数据库KingbaseES客户端编程开发框架-Hibernate Spatial(3. Hibernate-Spatial 配置)
    No141.精选前端面试题,享受每天的挑战和学习
    设计资讯 | 迷你PC:配备 Ryzen 9 芯片组和 7 英寸触摸屏,与 Mac Studio 大小相当
    树的直径 树形dp+2次dfs
    Android里获取正在前端运行的Activity的包名
    一款WPF开发的网易云音乐客户端 - DMSkin-CloudMusic
  • 原文地址:https://blog.csdn.net/hog_ceshiren/article/details/126221943