繁体   English   中英

如何在python中测试两个字典是否与pytest相等

[英]How can you test that two dictionaries are equal with pytest in python

试图用 pytest 断言具有嵌套内容的两个字典彼此相等(顺序无关紧要)。 这样做的pythonic方法是什么?

不要花时间自己编写这个逻辑。 只需使用默认测试库unittest提供的功能即可

from unittest import TestCase
TestCase().assertDictEqual(expected_dict, actual_dict)

我想一个简单的断言相等测试应该没问题:

>>> d1 = {n: chr(n+65) for n in range(10)}
>>> d2 = {n: chr(n+65) for n in range(10)}
>>> d1 == d2
True
>>> l1 = [1, 2, 3]
>>> l2 = [1, 2, 3]
>>> d2[10] = l2
>>> d1[10] = l1
>>> d1 == d2
True
>>> class Example:
    stub_prop = None
>>> e1 = Example()
>>> e2 = Example()
>>> e2.stub_prop = 10
>>> e1.stub_prop = 'a'
>>> d1[11] = e1
>>> d2[11] = e2
>>> d1 == d2
False

通用方法是:

import json

# Make sure you sort any lists in the dictionary before dumping to a string

dictA_str = json.dumps(dictA, sort_keys=True)
dictB_str = json.dumps(dictB, sort_keys=True)

assert dictA_str == dictB_str
assert all(v == actual_dict[k] for k,v expected_dict.items()) and len(expected_dict) == len(actual_dict)

pytest 的魔法已经够聪明了。 通过写作

assert {'a': 1} == {'a': 1}

你将有一个关于平等的嵌套测试。

你的问题不是很具体,但据我所知,你要么试图检查长度是否相同

a = [1,5,3,6,3,2,4]
b = [5,3,2,1,3,5,3]

if (len(a) == len(b)):
    print True
else:
    print false

或检查列表值是否相同

import collections

compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
compare([1,2,3], [1,2,3,3])
print compare #answer would be false
compare([1,2,3], [1,2,3])
print compare #answer would be true

但对于字典,你也可以使用

x = dict(a=1, b=2)
y = dict(a=2, b=2)

if(x == y):
    print True
else:
    print False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM