如何使用pytest在Python中测试两个字典是否相等

68

尝试使用 pytest 断言两个具有嵌套内容的 Python 字典相互相等(顺序无关)。有没有更符合 Python 风格的方法?


14
你尝试过使用assert d1 == d2吗?另外,你的嵌套内容是什么? - Szabolcs
6个回答

72

pytest的魔力非常聪明。只需编写:

assert {'a': {'b': 2, 'c': {'d': 4} } } == {'a': {'b': 2, 'c': {'d': 4} } }

您将进行一个嵌套的等式测试。


4
这应该是被接受的答案。当你断言两个字典相等时,pytest已经自动提供了所需的功能。既不需要编写专用逻辑,也不需要从unittest导入任何内容。 - monotasker
4
这甚至不是pytest。这只是使用常规的Python等式运算符。只有在断言失败时,pytest的魔力才会启动以显示字典及/或它们之间的差异。 - Jonathan Hartley

60

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

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

2
当字典很大时,我们无法看到不同的细节,可以使用带有maxDiff参数的变量: test = TestCase() | test.maxDiff = None | test.assertEqual(expected_dict, actual_dict) - Dmytro Ivashchenko

9
我想一个简单的等式断言测试应该没问题:
>>> 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

6

通用的方法是:

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

6
可以这样翻译:这个方法是可行的,但之后找出两个对象之间的差异非常繁琐。 - linqu

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

5
这是不必要的。如果两个字典相等,那么它们的长度必定相同,并且它们的元素也将相同。只需使用dict1==dict2即可。而且为了严谨起见,如果需要逐项检查,则还需要遍历嵌套元素。 - user4396006
所述的简单评估执行的是按多维度检查,而不是is运算符,它仅检查内存指针。 - user4396006

-4

你的问题不是很具体,但根据我理解,你要么想检查长度是否相同。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接