一、 全量字段校验
概念
校验接⼝返回响应后果的全副字段
利用场景
一般断言,无奈判断的 字段,通过全量字段校验补救
校验内容
* 字段值 * 字段名 或 字段值的类型
校验流程
1.定义 校验规定(json语法) 2.⽐对 响应数据 是否 合乎 校验规定
装置jsonschema
pip install jsonschema
二、 校验形式
2.1 工具校验
https://www.jsonschemavalidator.net
校验规定
待校验数据
校验后果
2.2 代码校验
#1.导包 import jsonschema#2.待校验数据data ={ "success": true, "code": 10000, "message": "操作胜利"}#3.校验规定schema = { "type": "object", "properties": { "success": { "type": "boolean" }, "code": { "type": "integer" }, "message": { "type": "string" } }, "required": [ "success", "code", "message" ]}#4.校验数据print(jsonschema.validate(instance=data, schema=schema))
查验校验后果
- 校验通过:返回 None
校验失败
- schema 规定谬误,返回 SchemaError
- json 数据谬误,返回 ValidationError
三、jsonschema语法
关键字一:type
作用:束缚数据类型
语法:{"type": "数据类型"}
"""integer —— 整数string —— 字符串object —— 对象array —— 数组 - 对应 python 列表number —— 整数/⼩数null —— 空值 - 对应 python Noneboolean —— 布尔值 - 对应 true / false"""
关键字二:properties
阐明:是 type关键字的辅助。用于 type 的值为 object 的场景。
作用:指定 对象中 每个字段的校验规定。 能够嵌套应用。
语法:{ "type": "object", "properties": { "字段名1":{规定}, "字段名2":{规定}, ...... } }
案例
# 筹备数据data = { "success": True, "code": 10000, "message": "操作胜利", "money": 6.66, "address": None, "data": { "name": "tom", "age": 18 }, "luckyNumber": [6, 8, 9]}
关键字三:required
作用:校验对象中必须存在的字段。字段名必须是字符串,且唯⼀
语法: { "required": ["字段名1", "字段名2", ...] }
关键字四:const
作用:校验字段值是⼀个固定值。等价于 断言中 == 用法
语法: { "字段名":{"const": 具体值}}
关键字五:pattern
作用:指定正则表达式,对字符串进行含糊匹配
正则表达式,用不罕用的符号,排列组合,从大量 字符串 数据中, 按指定条件 筛选 数据
"""根底正则举例:1 蕴含字符串:hello 相似于 断言中的 in2 以字符串结尾 ^: ^hello 如:hello,world3 以字符串结尾 $: hello$ 如:hello中国,4 匹配[]内任意1个字符[]: [0-9]匹配任意⼀个数字 [a-z]匹任意一个小写字母 [cjfew9823]匹配任意一个5 匹配指定次数{}: [0-9]{6}匹配6位数字。"""
案例
# 导包import jsonschema# 校验数据data = { "success": False, "code": 10000, "message": "xxx登录胜利", "data": { "age": 20, "name": "lily" }}# 校验规定schema = { "type": "object", "properties": { "success": { "type": "boolean", }, "code": { "type": "integer" }, "message": { "pattern": "登录胜利$" }, "data": { "type": "object", "properties": { "age": { "const": 20 }, "name": { "const": "lily" } }, "required": ["age", "name"] } }, "required": ["success", "code", "message", "data"]}# 校验print(jsonschema.validate(instance=data, schema=schema))