Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

I got

AssertionError: Second argument is not a dictionary

Should I use the built-in dict as the base class, instead of UserDict?

like image 885
neuront Avatar asked Sep 30 '22 15:09

neuront


1 Answers

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.

like image 176
alecxe Avatar answered Oct 04 '22 20:10

alecxe