Python assertEqal字符串-忽略其中的一部分

时间:2019-06-16 08:57:31

标签: python unit-testing

我正在使用python 3.6.7

在测试中,我使用assertEqual来比较字符串对象。这些字符串包含一些时间数据。由于测试之间的数据不同,因此我想忽略此数据。可以吗?

例如,这是可比较的对象:

obj1 = '{"field1": "field1", "field2": "field2", "created_at": "2019-06-16T07:12:46.429536Z", "field2": "field3"}'

我想做类似的事情:

obj1 = '{"field1": "field1", "field2": "field2", "created_at": ANY, "field2": "field3"}'
obj2 = '{"field1": "field1", "field2": "field2", "created_at": "2019-06-16T07:12:46.429536Z", "field2": "field3"}'
assertEqual(obj1, obj2)

2 个答案:

答案 0 :(得分:2)

由于字符串是序列化的json对象,所以我宁愿比较数据而不是表示形式,该表示形式可能会变化并随机破坏测试。例如:

import json
v1 = json.loads(obj1)
v2 = json.loads(obj2)

del v1['created_at']
del v2['created_at']
assertEqual(v1, v2)

答案 1 :(得分:0)

您只需在比较之前使用正则表达式从字符串中删除此部分

import re
obj1 = '{"field1": "field1", "field2": "field2", "created_at": ANY, "field2": "field3"}'
obj2 = '{"field1": "field1", "field2": "field2", "created_at": "2019-06-16T07:12:46.429536Z", "field2": "field3"}'

obj1 = re.sub(r' "created_at[^,]*,', '', obj1)
obj2 = re.sub(r' "created_at[^,]*,', '', obj2)
assertEqual(obj1, obj2)