assert校验

  1. # 普通值校验
  2. assert response.json()['data']['stocks'][0]['name'] == '中国全通'
  3. # 校验某个特定属性的值是否为期望值
  4. assert jsonpath.jsonpath(
  5. response.json(),"$.data.stocks[?(@.symbol == '00633')].name")[0] == '中国全通'

hamcrest校验

使用:assertthat( 实际值, 校验值_) 更多用法参考官方文档https://github.com/hamcrest/PyHamcrest

示例:

  1. from hamcrest import *
  2. # 校验实际值与期望值是否相等
  3. assert_that(
  4. jsonpath.jsonpath(response.json(), "$.data.stocks[?(@.symbol == '00633')].name")[0],
  5. equal_to('中国全通')
  6. )
  7. # 校验列表是否包含某些元素
  8. assert_that(['a', 'b', 'c'], any_of(has_items('a', 'b'),has_items('m', 'd')))

schema校验

schema在线生成器:https://www.jsonschema.net/ schema官方文档:http://json-schema.org/learn/getting-started-step-by-step.html

  1. jsonschema是一种基于JSON格式定义JSON数据结构的规范
  2. (1)描述现有数据格式
  3. (2)干净的可读的文档
  4. (3)完整的结构验证,可用于自动化测试和验证客户端提交的数据

json schema结构

结构 描述
$schema 指出此架构是根据标准的特定草稿编写的
$id 定义schema的URI,并解析模式中其他URI引用的基URI
title 对schema的描述信息
description 对schema的描述信息
type 校验类型
required 必选属性列表
properties 校验属性(包括必选和非必选属性)

Json schema 本身是一个JSON字符串,type 和 properties 用来定义json 属性的类型和约束,required 是对必选属性进行约束。(参考文档:https://www.jianshu.com/p/8278eb2458c4?winzoom=1

type为string

 {
     "$id": "#/properties/data/properties/stocks/items/properties/name",
     "type": "string",
     "title": "The Name Schema",
     "default": "",
     "examples": [
       "中国全通"
     ],
     "pattern": "^(.*)$"
   }
关键字 描述
maxLength 定义字符串的最大长度,>=0
minLength 定义字符串的最小长度,>=0
pattern 用正则表达式约束字符串

type为integer或number

 {
     "$id": "#/properties/data/properties/stocks/items/properties/price",
     "type": "integer",
     "title": "The Type Schema",
     "default": 0,
     "minimum": 0,
     "exclusiveMinimum": true,
     "examples": [
       30
     ]
   }
关键字 描述
minimum 最小值(验证时默认包含最小值)
exclusiveMinimum 依赖于minimum存在,为true时,表示验证的值不包含最小值(大于最小值),为false时,验证的值包含最小值(大于等于)
maximum 约束属性,最大值
exclusiveMaximum 与exclusiveMinimum用法相同
multipleOf 是某数的倍数,必须大于0的整数

schema校验response的关键代码

schema = json.load(open("schem.json"))
validate(instance=r.json(), schema=schema)