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()
I got
AssertionError: Second argument is not a dictionary
Should I use the built-in dict
as the base class, instead of UserDict
?
The problem is that assertDictEqual()
first checks that both arguments are dict
instances:
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')
...
And, UserDict
is not an instance of dict
:
>>> m = UserDict(x=42)
>>> m
{'x': 42}
>>> isinstance(m, dict)
False
Instead of using UserDict
class directly, use the data
property, which contains a real dictionary:
self.assertDictEqual({'x': 42}, m.data)
Or, as others already suggested, just use a regular dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With