jsonpath_rw模块-----解决接口自动化依赖响应值

如果解决自动化接口依赖响应值,例如B接口的参数值order_id  依赖A接口的返回的响应值jsonpath_rw就派上用场了

思路:将B接口的需要依赖的参数值作为一个参数,通过jsonpath_rw去匹配A接口响应值的数据,取出来再赋值到B的参数值中

B接口依赖:field_depend: - order_sn

A接口响应数据:

 data_depend:- data.list[0].order_sn

from jsonpath_rw import jsonpath, parse
order_sn =""
data = {
    "error_code": 0,
    "stu_info": [
        {
            "id": 309,
            "name": "小白",
            "sex": "男",
            "age": 28,
            "addr": "河南省济源市北海大道32号",
            "grade": "天蝎座",
            "phone": "18512572946",
            "gold": 100,
            "order_sn":"12435723438953485984"
        },
        {
            "id": 310,
            "name": "小白",
            "sex": "男",
            "age": 28,
            "addr": "河南省济源市北海大道32号",
            "grade": "天蝎座",
            "phone": "18516572946",
            "gold": 100,
            "order_sn": "74358943584390583454"
        }
    ]
}

json_expr = parse('stu_info[0].order_sn')
male = json_expr.find(data)
for math in male:
    order_sn = math.value
print(order_sn)
print([math.value for math in male])

前提:接口自动化测试中,存在依赖情况:test_02的某个请求参数的值,需要依赖test_01返回结果中某个字段的数据,所以就先需要拿到返回数据中特定字段的值。这里使用到python中jsonpath-rw库

1.下载安装

pip install jsonpath-rw

2.导入

from jsonpath_rw import jsonpath,parse

3.例子介绍

1.返回的match数据,但我们想要的是value数据

jsonpath_expr = parse('foo[*].baz')
data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]}
print([match for match in jsonpath_expr.find(data)])

运行结果:
[DatumInContext(value='news', path=Fields('baz'), context=DatumInContext(value={'baz': 'news'}, path=<jsonpath_rw.jsonpath.Index object at 0x025CA850>, context=DatumInContext(value=[{'baz': 'news'}, {'baz': 'music'}], path=Fields('foo'), context=DatumInContext(value={'foo': [{'baz': 'news'}, {'baz': 'music'}]}, path=This(), context=None)))), DatumInContext(value='music', path=Fields('baz'), context=DatumInContext(value={'baz': 'music'}, path=<jsonpath_rw.jsonpath.Index object at 0x025CA770>, context=DatumInContext(value=[{'baz': 'news'}, {'baz': 'music'}], path=Fields('foo'), context=DatumInContext(value={'foo': [{'baz': 'news'}, {'baz': 'music'}]}, path=This(), context=None))))]

2.获取匹配的数据match.value

jsonpath_expr = parse('foo[*].baz')
data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]}
print([match.value for match in jsonpath_expr.find(data)])
运行结果:
['news', 'music']

3.match.value返回数据是一个list,我们要获取特定的值

 jsonpath_expr = parse('foo[*].baz')
data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]}
print([match.value for match in jsonpath_expr.find(data)][0])

运行结果:
news

参考学习:https://www.cnblogs.com/ronyjay/p/11114848.html

 

上一篇:齐博x1标签之无刷新显示更多


下一篇:ctf-攻防世界-web:NewsCenter