jsonpath_rw模块-----解决接口自动化依赖响应值
2021/11/21 23:44:51
本文主要是介绍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
这篇关于jsonpath_rw模块-----解决接口自动化依赖响应值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-16Vue3资料:新手入门必读教程
- 2024-11-16Vue3资料:新手入门全面指南
- 2024-11-16Vue资料:新手入门完全指南
- 2024-11-16Vue项目实战:新手入门指南
- 2024-11-16React Hooks之useEffect案例详解
- 2024-11-16useRef案例详解:React中的useRef使用教程
- 2024-11-16React Hooks之useState案例详解
- 2024-11-16Vue入门指南:从零开始搭建第一个Vue项目
- 2024-11-16Vue3学习:新手入门教程与实践指南
- 2024-11-16Vue3学习:从入门到初级实战教程