首页 > 技术文章 > 接口断言--使用JSONSchema断言

tkliu 2021-03-17 11:45 原文

对于复杂的JSON结构,虽然可以使用JSONPath快速提取相应的值。然而对于JSON响应的整体结构和各字段类型,使用JSONSchema验证更加方便。
安装方法:

pip install jsonschema

一、基本使用
以上例中的响应结果为例:

    {
      "args": {
        "age": "12", 
        "name": "Kevin"
      }, 
      "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate", 
        "Host": "httpbin.org", 
        "User-Agent": "python-requests/2.22.0", 
        "X-Amzn-Trace-Id": "Root=1-5e7f618f-30ba932936a4a8e64ef5ea06"
      }, 
      "origin": "111.202.167.11", 
      "url": "https://httpbin.org/get?name=Kevin&age=12"
    }


    整个JSON结构可以描述为,整体为object类型,包含args、headers、orgin、url四个属性,其中args、headers是object类型,origin、url是字符串类型,使用JSONSchema语法描述如下:

    {
        "type": "object",
        "properties": {
            "args": {"type": "object"},
            "headers": {"type": "object"},
            "origin": {"type": "string"},
            "url": {"type": "string"}
        }
    }


    对于object对象,还可以使用required描述必须存在的属性。对于args、headers还可以继续添加properties描述其子属性,对于字符串还可以使用patten字段描述其符合的真正表达式。
    JSONSchema中的类型分为string、number、integer、array、object、boolean、null七种类型。其中,number包含整数和浮点数,integer仅限整数。JSONSchema每种类型常用的关键字如表3.3所示。

二、Schema中常用的关键字

(1)最外层
$schema 指定使用的JSONSchema协议版本
title 规则标题
description 规则描述

(2)通用
type 类型,string、number、integer、array、object、boolean、null

(3)string
miniLength 最小长度
maxLength 最大长度
pattern 匹配的正则表达式

(4)number/integer
minimum 最小值, 结合"exclusiveMinimum": True,不包含等于
maximum 最大值,结合"exclusiveMaximum": True,不包含等于
multipleOf 可被指定数字整除

(5) object
properites 子属性
patternProperties 子属性名满足正则表达式
required 必选子属性

(6)array
items 子元素
required 必选子元素
miniItems 最少子元素个数
maxItems 最大子元素个数

三、使用示例
完整示例如下:

          import requests
          import jsonschema
          res = requests.get('https://httpbin.org/get?name=Kevin&age=12')
          schema = {
              "type": "object",
              "properties": {
                  "args": {
                      "type": "object",
                      "required": ["name", "age"],
                      "properties": {
                          "name": {"type": "string", "pattern": "^Kevin$"},
                          "age": {"type": "string", "pattern": "^12$"}
                      }
                  },
                  "headers": {"type": "object"},
                  "origin": {"type": "string", "pattern": "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"},
                  "url": {"type": "string"}
              }
          } 

          jsonschema.validate(res.json(), schema)
          上例中,required限定,args必须有name和age两个子属性。
          name字段的pattern使用“^Kevin$”表示,必须以K开头,以n结尾,即完全等于Kevin。
          同样,断言通过时不会有任何输出,断言失败是则会抛出异常。

转链接:https://www.jianshu.com/p/a2793481107d

推荐阅读