injson 接口测试校验

Apache License 2.0
Python
Windows, Mac, Linux
tonglei · 2018年06月08日 · 1936 次阅读 · 7 条评论

injson

测试一个 json 是否在另一个 json 中,并返回不一致的键值对;同时可以以变量的形式提取对应路径上的字段值。

项目地址: https://github.com/tonglei100/injson

安装

pip install injson

使用

from injson import check


sub = {"code": 200,
       "error": "hello, world",
       "name": "<name>",                # 以 <name> 扩起来的字符串视为变量 name \
       "phone": "<phone>",              # 该变量将从 parent 中对应位置提取值
       "result": [
           {"sweetest": "OK",
            "status": "<status>"
            },
           {"ages": [1, 2, 4],
            "status": "yes"
            },
           {"sonar": "OK",
            "status": "yes"
            }
       ],
       }

parent = {"code": 200,
          "error": "you are bad",
          "name": "Leo",
          "result": [
              {"sweetest": "Fail",
               "status": "NO"
               },
              {"sweetest": "OK",
               "status": "NO"
               },
              {"ages": [1, 2, 3],
               "status": "yes"
               },
              {"sonar": "OK",
               "status": "yes"
               }
          ],
          }

result = check(sub, parent)
print(result)

打印结果

注: 下面的 json 格式是已美化后的结果

{
    "code": 2,                          # 键值对不一致的个数,当值为 0 时,表示全部一致

    "result": {                         # 比较出不一致的键值对,并放在此 dict
        "/error": {                     # 键的路径,以 / 开头
            "code": 1,                  # 错误类型:1-值不一致,2-数据类型不一致,3-键不存在
            "sv": "hello,word",         # 全拼为 sub_value, sub json 中改键的值
            "pp": "/error",             # 全拼为 parent_path, parent json 中对应键的路径
            "pv": "you are bad"         # 全拼为 parent_value, parent json 中对应键的值
        },

        "/result[1].ages": {            # 如果是 list,则以 [i] 表示路径
            "code": 1,
            "sv": [1, 2, 4],
            "pp": "/result[2].ages", # 对于 list,其下标不一定一致。
            "pv": [ 1, 2, 3]
        }
    },

    "var": {                            # 获取对应键位置上的值,并放在此 dict
        "name": "Leo",
        "phone": None,                  # 如果某个键在 parent 中不存在,则其值为 None,但不会报错
        "status": "NO"
    }
}
评论列表
aibreze 发表于 2020年03月09日

问下,返回的 json 接口数据里边有时间日期,等关键字段,进行接口效验时咋处理的,预期结果不带时间日期这些字段,能效验成功吗

tonglei 发表于 2018年11月05日

@Mes 我们的假设是 json 的子集判断,也就是只判断预期字段存在(或指定字段不存在)

如果想判断 2 个 json 完全一致,那需要再反向判断一次

Mes 发表于 2018年11月01日

你好,测试了一下,实际参数比预期结果多出不存在的字段时,仍然是返回 code:0 的。目前是还没做这个判断吗?

tonglei 发表于 2018年09月05日

@leeya 目前只能是确定的值,后续考虑做类型,范围判断

leeya 发表于 2018年09月04日

能判断 json 中某一个键值不为空吗?

tonglei 发表于 2018年07月04日

@hshj1989 你是说 json 中键的顺序吗?和 python 中的字典一样,支持无序排列

少侠好功夫 发表于 2018年07月04日

两个 json 需要顺序一致嘛