[英]UserDict is not considered as a dict by unittest
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
吗?
问题是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)
或者,正如其他人已经建议的那样,只需使用常规字典。
来自Python unittess源码
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返回真正的字典。
IterableUserDict.data
A real dictionary used to store the contents of the UserDict class.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.