如果是涉及流量回放,或者是数据对比,这里应该是可以提供一些思路的。
场景一:流量回放,将线上的参数做埋点,记录下来,然后通过这些参数,比对正式环境&预发环境的数据是否一致。通常会作用于,一个回归验证预发,是否影响线上功能,其次是对于重构类接口,做一个快速的质量验证。因为参数源于线上,所以更贴近与真实的用户环境。
1、对获取的数据做一个处理,一般都是按json格式处理,json.loads()
2、对数据做一个排序,如果是字典,可以通过json.dumps(sort-key=True),按关键字母排序,列表,可以考虑用sorted(key=) 按照一定的key值进行排序
3、可以自己去写对比函数,将数据每一行都提取出来,再一一去对比(或是是有一个比较简单的,用deepdiff.Deepdiff 这个函数去进行对比。)
这里主要学习一下deepdiff 这个函数的一些使用方法:
class deepdiff.diff.DeepDiff(t1, t2, ignore_order=False, report_repetition=False, significant_digits=None, number_format_notation='f', exclude_paths=None, exclude_regex_paths=None, exclude_types=None, ignore_type_in_groups=None, ignore_string_type_changes=False, ignore_numeric_type_changes=False, ignore_type_subclasses=False, ignore_string_case=False, number_to_string_func=None, verbose_level=1, view='text', hasher=None, **kwargs)
目前可能主要关注的是:
1、如果需要忽略有重复的内容,用到ignore_order =True,这个时候,需要同时设置report_repetition=True
2、如果需要忽略数字类型更换,ignore_numeric_type_changes设置为True ,则认为10和10.0相同
3、不区分大小写的时候,通过设置ignore_string_case=False,字符串将不区分大小写进行比较。
from deepdiff import DeepDiff
t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3.0]}}
t3 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3.0]}}
ddiff = DeepDiff(t1, t2, ignore_order=True)
ddiff2 = DeepDiff(t1, t2, ignore_order=False)
ddiff3 = DeepDiff(t1, t3, ignore_numeric_type_changes=True)
print(ddiff)
print(ddiff2)
print(ddiff3)
###############
{}
{'values_changed': {"root[4]['b'][1]": {'new_value': 3, 'old_value': 2}, "root[4]['b'][2]": {'new_value': 2, 'old_value': 3}}, 'iterable_item_added': {"root[4]['b'][3]": 3.0}}
{}
举例说明
看一下DeepDiff 的返回值
a={
"data":[
{
"name": "hello1",
"id":"1234565"
},
{
"id": "000001",
"aa": "11111",
"name": "hello2"
}
],
"a":"1111111",
"c":"popo",
"b":3
}
b={
"data": [
{
"id": "000001",
"name": "hello2",
"aa":"11111"
},
{
"id": "1234565",
"name": "hello4"
}
],
"b": 3.0,
"d": 'ppo'
}
a =data_sort(a,"id").result() #按照规则,先排序
b = data_sort(b, "id").result() #按照规则,先排序
diff =DeepDiff(a,b)
print(diff)
############################
值:
{'type_changes': {"root['b']": {'old_type': <class 'int'>, 'new_type': <class 'float'>, 'old_value': 3, 'new_value': 3.0}}, 'dictionary_item_added': [root['d']], 'dictionary_item_removed': [root['a'], root['c']], 'values_changed': {"root['data'][1]['name']": {'new_value': 'hello4', 'old_value': 'hello1'}}}
DeepDiff的对比例子
主要是以下4种内容返回
1、type_changes:类型改变的key
2、values_changed:值发生变化的key 【DeepDiff(a,b)】【{"root['data'][1]['name']": {'new_value': 'hello4', 'old_value': 'hello1'} 会有一个path : value(old_value,代表是第一个可迭代对象(a)的值,new_value 代表是第二个可迭代对象(b)的值)】
3、dictionary_item_added:字典key添加 (DeepDiff(a,b) 这个主要是b 比a 多了的key)
4、dictionary_item_removed:字段key删除 (DeepDiff(a,b) 这个主要是b 比a 少了的key)