Skip to content

Instantly share code, notes, and snippets.

@jmatthias
Created May 22, 2014 20:19
Show Gist options
  • Save jmatthias/701d90e96b9c2d7bbce4 to your computer and use it in GitHub Desktop.
Save jmatthias/701d90e96b9c2d7bbce4 to your computer and use it in GitHub Desktop.
A `MagicMock` which maps dictionary methods to a sample dictionary.
def DictionaryMock(_sample_dict, methods=None):
""" A mock dictionary.
Makes it easier to check that the correct values are being retrieved
from a dictionary.
'_sample_dict': A dictionary of test values. Dictionary lookups will get
values from this dictionary. """
if methods is None:
methods = [
'__getitem__',
'__setitem__',
'__delitem__',
'__iter__',
'__len__',
'__contains__',
'keys',
'values',
'items',
'get',
'pop',
'popitem',
'clear',
'update',
'setdefault',
]
mock_dict = MagicMock(*pargs, **kwargs)
mock_dict._sample_dict = _sample_dict
def make_side_effect(method_name):
def side_effect(*pargs, **kwargs):
sample_method = getattr(mock_dict._sample_dict, method_name)
return sample_method(*pargs, **kwargs)
return side_effect
for method_name in methods:
mock_method = getattr(mock_dict, method_name)
mock_method.side_effect = make_side_effect(method_name)
return mock_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment