python—deepdiff包学习

2,940 阅读2分钟

简介

主要用来对比两个对象之间的差异性,搜索某个元素是都在一个对象中,对一个可迭代对象进行hash运算。

应用场景

自动化脚本测试

安装

pip install deepdiff==4.3.2

Python 3.7.6 

pip 20.1.1

主要组成部分

DeepDiff:比较两个对象,对象可以是字段、字符串等可迭代的对象
DeepSearch:在对象中搜索其他对象
DeepHash:根据对象的内容进行哈希处理

DeepDiff使用

文本文件对比

from deepdiff import DeepDiff
class Diff():    
    def file_compare(self):        
        '''文件内容对比        
        '''        
        with open("a.log", 'r', encoding='utf-8') as file:            
            file_a = file.read()        
        with open("b.log", "r", encoding='utf-8') as file:            
            file_b = file.read()        
        rs = DeepDiff(file_a, file_b)        
        print(rs)

if __name__ == "__main__":    
    di = Diff()    
    di.file_compare()

#测试
$ cat a.log
this is a message !!!

$ cat b.log
this is a message

$ python diff.py
{'values_changed': {'root': {'new_value': 'this is a message', 'old_value': 'this is a message !!!'}}}

json文件对比

def json_file_compare(self):        
    '''json文件对比        
    '''        
    with open("a.log", 'r', encoding='utf-8') as file:            
        file_a = json.loads(file.read())        
    with open("b.log", "r", encoding='utf-8') as file:            
        file_b = json.loads(file.read())        
    rs = DeepDiff(file_a, file_b)        
    print(rs)

$ cat a.log
{    "username":"ouyangjun",    "birth":"1992",    "school":"changchunligongdaxue",    "age":"27",    "filename":"a.log",    "iterable_removed":[1,2,3,4]}
$ cat b.log
{    "username":"ouyangjun",    "birth":"1992",    "school":"panshiwuzhong",    "age":27,    "name":"",    "iterable_add":[1,2,3,4]}
$ python diff.py
{'type_changes': {"root['age']": {'old_type': <class 'str'>, 'new_type': <class 'int'>, 'old_value': '27', 'new_value': 27}}, 'dictionary_item_added': [root['iterable_add'], root['name']], 'dictionary_item_removed': [root['iterable_removed'], root['filename']], 'values_changed': {"root['school']": {'new_value': 'panshiwuzhong', 'old_value': 'changchunligongdaxue'}}}


以上两个测试案例结果主要是对比对象之间的值、类型前后之间的变化以及删除的或者增加的情况key进行了结果输出。

主要包含以下四种情况

  1. type_changes:类型改变的key
  2. values_changed:值发生变化的key
  3. dictionary_item_added:字典key添加
  4. dictionary_item_removed:字段key删除


DeepSearch使用

查找指定元素是否存在

from deepdiff import grep
class Diff():    def search_text(self):        '''DeepDiff实例        '''        obj = {            "long":"somewhere",            "string":2,            0:0,            "somewhere":"around",            "a":{"b":{"c":{"d":"somewhere"}}}        }        # 使用grep类似管道过滤方式        rs = data | grep("somewhere")        print(rs)        # 使用DeepSearch搜索对象        res = DeepSearch(data, "somewhere")        print(res)
python diff.py
{'matched_paths': {"root['somewhere']"}, 'matched_values': {"root['long']", "root['a']['b']['c']['d']"}}
python diff.py
{'matched_paths': {"root['somewhere']"}, 'matched_values': {"root['long']", "root['a']['b']['c']['d']"}}


DeepHash使用

主要用来对对象进行hash运算

class Diff():    
    def data_hash(self):        
        '''数据进行hash运算        
        '''        
        data = {1:2, "a":"b"}        
        # 获取对象hash值        
        rs = DeepHash(data)        
        print(rs)        
        # 获取对象id值        
        print(id(data))        
        # 获取当前对象hash值        
        print(rs[data])


总结

deepdiff主要可在在单元测试,自动化测试上给予我们很大的方便,能让我们更快速的对别与预期的结果是否一致;如果业务中有业务API升级改造场景也可以使用,对比api不同版本之间的差异化。


以上源码位置:gitee.com/oyjjpp/zyuc…


参考