Python unittest - 使用列表断言字典

sju*_*dǝʊ 11 python dictionary unit-testing assert

在为我的课写一些测试时,我遇到了一个有趣的简单问题.我想assertDictEqual包含一些列表的两个字典.但是这个列表可能没有以相同的方式排序 - >导致测试失败

例:

def test_myobject_export_into_dictionary(self):
    obj = MyObject()
    resulting_dictionary = {
            'state': 2347,
            'neighbours': [1,2,3]
        }
    self.assertDictEqual(resulting_dictionary, obj.exportToDict())
Run Code Online (Sandbox Code Playgroud)

这有时会失败,具体取决于列表中元素的顺序

FAIL: test_myobject_export_into_dictionary
------------------------------------
-  'neighbours': [1,2,3],
+  'neighbours': [1,3,2],
Run Code Online (Sandbox Code Playgroud)

任何想法如何以简单的方式断言?

我想在比较之前使用set代替list或排序列表.

Jon*_*eid 7

您可以尝试PyHamcrest (更正示例)

assert_that(obj.exportToDict(), has_entries(
                                    { 'state': 2347,
                                      'neighbours': contains_inanyorder(1,2,3) }))
Run Code Online (Sandbox Code Playgroud)

(第一个值2347实际上包含在隐式equal_to匹配器中.)