Python单元测试 - 用列表声明字典 [英] Python unittest - asserting dictionary with lists

查看:161
本文介绍了Python单元测试 - 用列表声明字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While writing some tests for my class, I encountered interesting simple problem. I would like to assertDictEqual two dictionaries containing some list. But this lists may not be sorted in a same way -> which results in failed test

示例:

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

根据列表中元素的顺序不定期失败

This fail from time to time, depending on order of elements in list

FAIL: test_myobject_export_into_dictionary
------------------------------------
-  'neighbours': [1,2,3],
+  'neighbours': [1,3,2],

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

Any ideas how to assert this in a simple way?

我正在考虑使用设置而不是列表或比较前排序列表。

I was thinking about using set instead of list or sorting lists before comparison.

推荐答案

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

assert_that(obj.exportToDict(), has_entries(
                                    { 'state': 2347,
                                      'neighbours': contains_inanyorder(1,2,3) }))

(第一个值2347实际上被包含在一个隐含的等于_ / code>匹配器中。)

(The first value 2347 actually gets wrapped in an implicit equal_to matcher.)

这篇关于Python单元测试 - 用列表声明字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆