14-Python-对比校验神器-deepdiff库

简介: 14-Python-对比校验神器-deepdiff库

前言

  • 在接口自动化中会遇到想要得出两次响应体(json值)差异,本篇来学习的deepdiff库可以解决这问题

deepdiff库

安装

pip install deepdiff

说明

  • deepdiff模块常用来校验两个对象是否一致,并找出其中差异之处,它提供了:
  • DeepDiff:比较两个对象,对象可以是字段、字符串等可迭代的对象
  • DeepSearch:在对象中搜索其他对象
  • DeepHash:根据对象的内容进行哈希处理

DeepDiff

  • 作用:比较两个对象,对象可以是字段、字符串等可迭代的对象

说明:

  • type_changes:类型改变的key
  • values_changed:值发生变化的key
  • dictionary_item_added:字典key添加
  • dictionary_item_removed:字段key删除

对比json

# -*-coding:utf-8一*-
# @Time:2023/4/16
# @Author: DH
from deepdiff import DeepDiff
# json校验
json_one = {
    'code': 0,
    "message": "失败",
    'data': {
        'id': 1
    }
}
json_two = {
    'code': 1,
    "message": "成功",
    'data': {
        'id': 1
    }
}
print(DeepDiff(json_one, json_two))
# 输出
"""
{'values_changed': {"root['code']": {'new_value': 1, 'old_value': 0}, "root['message']": {'new_value': '成功', 'old_value': '失败'}}}
root['code'] : 改变值的路径
new_value : 新值
old_value :原值
"""

列表校验

  • cutoff_distance_for_pairs: (1 >= float > 0,默认值=0.3);通常结合ignore_order=true使用,用于结果中展示差异的深度。值越高,则结果中展示的差异深度越高。
from deepdiff import DeepDiff
t1 = [[[1.0, 666], 888]]
t2 = [[[20.0, 666], 999]]
print(DeepDiff(t1, t2, ignore_order=True, cutoff_distance_for_pairs=0.5))
print(DeepDiff(t1, t2, ignore_order=True)) # 默认为0.3
print(DeepDiff(t1, t2, ignore_order=True, cutoff_distance_for_pairs=0.2))
"""
{'values_changed': {'root[0][0]': {'new_value': [20.0, 666], 'old_value': [1.0, 666]}, 'root[0][1]': {'new_value': 999, 'old_value': 888}}}
{'values_changed': {'root[0]': {'new_value': [[20.0, 666], 999], 'old_value': [[1.0, 666], 888]}}}
{'values_changed': {'root[0]': {'new_value': [[20.0, 666], 999], 'old_value': [[1.0, 666], 888]}}}
"""

忽略字符串类型

  • ignore_string_type_changes :忽略校验字符串类型,默认为False
print(DeepDiff(b'hello', 'hello', ignore_string_type_changes=True))
print(DeepDiff(b'hello', 'hello'))
"""
输出:
{}
{'type_changes': {'root': {'old_type': <class 'bytes'>, 'new_type': <class 'str'>, 'old_value': b'hello', 'new_value': 'hello'}}}
"""

忽略大小写

  • ignore_string_case:忽略大小写,默认为False
from deepdiff import DeepDiff
print(DeepDiff(t1='Hello', t2='heLLO'))
print(DeepDiff(t1='Hello', t2='heLLO', ignore_string_case=True))
"""
输出:
{'values_changed': {'root': {'new_value': 'heLLO', 'old_value': 'Hello'}}}
{}
"""

DeepSearch

  • 作用:在对象中搜索其他对象

查找字典key/value

from deepdiff import DeepSearch
json_three = {
    'code': 1,
    "message": "成功",
    'data': {
        'id': 1
    }
}
# 查找key
print(DeepSearch(json_three, "code"))
print(DeepSearch(json_three, "name"))
# 查找value
print(DeepSearch(json_three, 1))
"""
输出:
{'matched_paths': ["root['code']"]}
{}
{'matched_values': ["root['code']", "root['data']['id']"]}
"""
# 正则 use_regexp
obj = ["long somewhere", "string", 0, "somewhere great!"]
# 使用正则表达式
item = "some*"
ds = DeepSearch(obj, item, use_regexp=True)
print(ds)
# 强校验 strict_checking 默认True
item = '0'
ds = DeepSearch(obj, item, strict_checking=False)
# ds = DeepSearch(obj, item)  # 默认True
print(ds)
# 大小写敏感  case_sensitive  默认 False 敏感
item = 'someWhere'
ds = DeepSearch(obj, item, case_sensitive=True)
print(ds)

DeepHash

  • 作用:根据对象的内容进行哈希处理
from deepdiff import DeepHash
# 对对象进行hash
json_four = {
    'code': 1,
    "message": "成功",
    'data': {
        'id': 1
    }
}
print(DeepHash(json_four))

extract

  • extract : 根据路径查询值
from deepdiff import extract
# 根据路径查询值
obj = {1: [{'2': 666}, 3], 2: [4, 5]}
path = "root[1][0]['2']"
value = extract(obj, path)
print(value)
"""
输出:
666
"""

grep

  • 搜索
from deepdiff import grep
obj = ["long somewhere", "string", 0, "somewhere great!"]
item = "somewhere"
ds = obj | grep(item)
print(ds)
# use_regexp 为True 表示支持正则
obj = ["something here", {"long": "somewhere", "someone": 2, 0: 0, "somewhere": "around"}]
ds = obj | grep("some.*", use_regexp=True)
print(ds)
# 根据值查询路径
obj = {1: [{'2': 'b'}, 3], 2: [4, 5, 5]}
result = obj | grep(5)
print(result)
"""
输出:
{'matched_values': ['root[2][1]', 'root[2][2]']}
"""

相关文章
|
2天前
|
机器学习/深度学习 人工智能 算法
Python在计算机视觉(CV)中扮演重要角色,得益于其丰富的库如OpenCV、Pillow和Scikit-image。
【7月更文挑战第5天】Python在计算机视觉(CV)中扮演重要角色,得益于其丰富的库如OpenCV、Pillow和Scikit-image。CV涉及图像处理、模式识别和机器学习,用于图像理解和生成。Python的跨平台特性和活跃社区使其成为CV的理想工具。基本流程包括图像获取、预处理、特征提取、分类识别及图像生成。例如,面部识别通过预处理图像,使用如`cv2.CascadeClassifier`进行检测;物体检测类似,但需适应不同目标;图像生成则利用GAN创造新图像。
17 4
|
23小时前
|
Java 测试技术 开发者
Python:使用标准库编写单元测试
在现代软件开发中,编写单元测试是确保代码质量和可靠性的重要步骤。Python 提供了一个内置的单元测试框架,称为 unittest,它可以帮助开发者方便地编写和运行测试。本文将详细介绍如何使用 unittest 编写单元测试。
|
2天前
|
数据可视化 数据挖掘 API
数据可视化秘籍聚焦Python的Matplotlib和Seaborn库,它们是数据分析的得力工具。
【7月更文挑战第5天】数据可视化秘籍聚焦Python的Matplotlib和Seaborn库,它们是数据分析的得力工具。Matplotlib是基础库,提供高度自定义的2D图表,而Seaborn在其上构建,提供美观的统计图形。文章介绍了如何用两者画线图、散点图、条形图、饼图和直方图,展示数据趋势和关系。
|
4天前
|
存储 JSON 算法
|
5天前
|
Python
Python基本文件操作及os库
以上仅为Python文件操作和os库的基本用法,实际使用中需要根据具体需求进行调整。
9 1
|
6天前
|
Python
Python基本文件操作及os库
以上仅为Python文件操作和os库的基本用法,实际使用中需要根据具体需求进行调整。
10 1
|
2天前
|
存储 消息中间件 数据挖掘
Python实时数据分析:利用丰富的库(如Pandas, PySpark, Kafka)进行流处理,涵盖数据获取、预处理、处理、存储及展示。
【7月更文挑战第5天】Python实时数据分析:利用丰富的库(如Pandas, PySpark, Kafka)进行流处理,涵盖数据获取、预处理、处理、存储及展示。示例代码展示了从Kafka消费数据,计算社交媒体活跃度和物联网设备状态,并可视化结果。适用于监控、故障检测等场景。通过学习和实践,提升实时数据分析能力。
8 0
|
2天前
|
数据采集 数据挖掘 大数据
Pandas是Python数据分析的核心库,基于NumPy,提供DataFrame结构处理结构化数据
【7月更文挑战第5天】Pandas是Python数据分析的核心库,基于NumPy,提供DataFrame结构处理结构化数据。它支持缺失值处理(dropna()、fillna())、异常值检测(Z-Score、IQR法)和重复值管理(duplicated()、drop_duplicates())。此外,数据转换包括类型转换(astype())、数据标准化(Min-Max、Z-Score)以及类别编码(get_dummies())。这些功能使得Pandas成为大数据预处理的强大工具。
|
5天前
|
机器学习/深度学习 自然语言处理 算法框架/工具
Python的常用库
【7月更文挑战第2天】Python的常用库
6 0
|
6天前
|
数据采集 分布式计算 DataWorks
DataWorks产品使用合集之如何使用Python 3的Pandas库
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
23 0