pythonmocking

How to mock a dictionary in Python


Let's say I have a function like this:

def do_something(dict_obj):
   # access to the dict_obj then do some stuff
   eg.
   if dict_obj['doors']:
      do_something_with_doors()
   map_car_make(dict_obj['make'])
   ...

   if dict_obj['is_active']:
        do_something_else()

I want to mock the dict_obj to have is_active element and don't care the rest, how do I do that?


Solution

  • How to mock a dictionary in Python is a good/direct question someone else can search, so:

    1. I suggest MagicMock instead of Mock
    2. Overload the __getitem__
    from unittest.mock import MagicMock
    
    m = MagicMock()
    d = {'key_1': 'value'}
    m.__getitem__.side_effect = d.__getitem__
    
    # dict behaviour
    m['key_1'] # => 'value'
    m['key_2'] # => raise KeyError
    
    # mock behaviour
    m.foo(42)
    m.foo.assert_called_once_with(43) # => raise AssertionError
    

    Related Questions:

    === EDIT ===

    As a function for direct copy/pasting

    def mock_dict(d):
      m = MagicMock()
      m.__getitem__.side_effect = d.__getitem__
      return m