你怎么能测试两个字典在python中与pytest相等

Joh*_*ike 12 python pytest python-3.x

试图断言具有嵌套内容的两个字典与pytest相互相等(顺序无关紧要).什么是pythonic方式呢?

lin*_*nqu 78

pytest 的魔力足够聪明。通过写作

assert {'a': {'b': 2, 'c': {'d': 4} } } == {'a': {'b': 2, 'c': {'d': 4} } }
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是公认的答案。当您断言两个字典相等时,所需的功能已经自动存在于 pytest 中。无需编写专用逻辑或从单元测试导入任何内容。 (4认同)
  • 它甚至不是 pytest。这只是使用常规的 Python 相等运算符。只有当断言失败时, pytest 的魔力才会开始显示字典和/或它们的差异。 (4认同)

Vin*_*aes 21

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

from unittest import TestCase
TestCase().assertDictEqual(expected_dict, actual_dict)
Run Code Online (Sandbox Code Playgroud)

  • 当 dict 很大并且我们看不到 diff 详细信息时,使用参数 maxDiff: test = TestCase() | 变体 test.maxDiff = 无 | test.assertEqual(expected_dict,actual_dict) (2认同)

Sza*_*lcs 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
Run Code Online (Sandbox Code Playgroud)


Wil*_*iam 5

General purpose way is to:

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
Run Code Online (Sandbox Code Playgroud)

  • 可行,但是事后找出两个对象之间的差异非常繁琐 (6认同)