用于(嵌套)数据结构部分比较的工具
matchlib的Python项目详细描述
匹配库
这个包提供了一种方便的方法来部分比较python数据结构 (通常是嵌套列表/字典)
安装
pip install matchlib
使用量
frommatchlibimportmatchesuser={'id':42,'name':'John Doe','email':'johndoe@gmail.com','posts':[{'id':1,'text':'some text'},{'id':2,'text':'lorem ipsum','comments':[42,142,242]}]}assertmatches(user,{'id':...,'name':'John Doe','email':'johndoe@gmail.com',...:...})
使用标准的==
运算符和matchlib.Partial
对象可以实现相同的效果:
frommatchlibimportPartialassertuser==Partial({'id':42,'email':'johndoe@gmail.com',...:...})
可以将...
“通配符”放置在任何嵌套级别。
假设我们只需要检查注释142
是否出现在特定的post:
assertuser==Partial({'posts':[...,{'id':2,'comments':[...,142,...],...:...}],...:...})
匹配规则很简单:
- 在列表和元组
...
中,匹配零个或多个元素,并保留顺序:Partial([1,2,...])==[1,2,3,4]Partial([1,2,...])==[1,2]Partial([1,2,...])!=[0,1,2]Partial([1,2,...])!=[2,1]
- 对于集合相同,但它们是无序的:
Partial({1,2,...})=={1,2}Partial({1,2,...})=={0,1,2,3}Partial({1,2,...})!={0,1,3}
- 因为dict value
...
匹配任何对象:Partial({'a':1,'b':...})=={'a':1,'b':2}
- 当dict key
...
匹配任何键时,如果关联值匹配:Partial({'a':1,...:2})=={'a':2,'b':2}
- 当作为传递时,键和值都匹配零个或多个任意键-值对:
Partial({'a':1,...:...})=={'a':1,'b':2,'c':3}
更多的黑客
mathchlib
提供一个Regex
对象,允许匹配任意字符串元素
(除非是dict键)针对正则表达式。
浮点数比较也支持pytest.approx
:
frompytestimportapproxfrommatchlibimportRegex,Partialaccount={'id':1,'balance':1007.62,'owner':{'email':'user42@domain.com',}}assertaccount==Partial({'id':...,'balance':approx(1000,0.1),'owner':{'email':Regex(r'\w+@domain\.com')}})
如果出于任何原因您不喜欢省略文字(...
)
matchlib.Any
对象可以互换使用