【问题标题】:UserDict is not considered as a dict by unittestUserDict 不被单元测试视为字典
【发布时间】:2014-07-27 06:05:55
【问题描述】:
import unittest
from UserDict import UserDict

class MyDict(UserDict):
    def __init__(self, x):
        UserDict.__init__(self, x=x)

class Test(unittest.TestCase):
    def test_dict(self):
        m = MyDict(42)
        assert {'x': 42} == m # this passes
        self.assertDictEqual({'x': 42}, m) # failure at here

if __name__ == '__main__':
    unittest.main()

我明白了

AssertionError: Second argument is not a dictionary

我应该使用内置的dict 作为基类,而不是UserDict

【问题讨论】:

  • 可能吗? UserDict 是什么?它来自哪里(和why does the module have capital letters in its name?)?
  • 您始终可以将m 转换为dict:dict(m) 或使用m.data 而不是m
  • @alecxe Eww... 从来不知道。我猜提问者应该测试m.data
  • 首先,考虑一下你是否真的需要自己的 dict 类,这种情况很少见。其次,只是继承自dict,我不知道有什么理由要继承自UserDict。 (在非常旧的 python 版本中这是必需的)。

标签: python python-unittest


【解决方案1】:

问题在于assertDictEqual() 首先检查两个参数是否都是dict 实例:

def assertDictEqual(self, d1, d2, msg=None):
    self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
    self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
    ...

而且,UserDict 不是dict 的实例:

>>> m = UserDict(x=42)
>>> m
{'x': 42}
>>> isinstance(m, dict)
False

不要直接使用UserDict类,而是使用data属性,它包含一个真正的字典:

self.assertDictEqual({'x': 42}, m.data)

或者,正如其他人已经建议的那样,只需使用普通字典。

【讨论】:

    【解决方案2】:

    问题在于 UserDict 实际上不是 dict 对象,因为它是很久以前创建的,当时您无法从内置的 dict 类型继承。根据doc

    [UserDict] 已在很大程度上被直接从dict 继承的能力所取代...

    所以我可能只是从dict 继承并完成它;我没有看到 UserDict 提供的任何功能超过该选项。


    请注意,我个人也对 UserDict* 提出异议,因为模块名称为 violates PEP8,这很烦人。


    *直到八分钟前我才知道它的存在。

    【讨论】:

      【解决方案3】:

      来自 Python unittest 来源

      def assertDictEqual(self, d1, d2, msg=None):
          self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
          self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
      

      这两个参数必须是dict 的实例。

      不幸的是,UserDict 实例不是dict 的实例

      assert isinstance(m, dict) # this is False
      

      正如文档https://docs.python.org/2/library/userdict.html#module-UserDict 所说,您可以使用m.data 返回一个真实的dict

      IterableUserDict.data

      A real dictionary used to store the contents of the UserDict class.
      

      【讨论】:

        猜你喜欢
        • 2018-01-13
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        相关资源
        最近更新 更多