Skip to content

Instantly share code, notes, and snippets.

@peterldowns
Created July 9, 2014 01:01
Show Gist options
  • Save peterldowns/c51711e5e68f5d96bd33 to your computer and use it in GitHub Desktop.
Save peterldowns/c51711e5e68f5d96bd33 to your computer and use it in GitHub Desktop.
Simple way of creating Mock objects from nested dictionaries.
import mock
def mock_object(data=None):
result = mock.MagicMock()
for key, value in data.iteritems():
if isinstance(value, dict):
result.configure_mock(**{
key: mock_object(value),
})
else:
result.configure_mock(**{
key: value,
})
return result
MyFactory = mock_object({
'return_value' : {
'type' : 'Factory',
'get_person' : {
'return_value' : {
'type' : 'Person',
'get_friends' : {
'side_effect' : ValueError("Too many friends"),
},
'get_enemies' : {
'return_value' : [],
},
'say_hello' : lambda: 'hello',
'say_hello_2' : {
'return_value' : 'hello',
},
},
},
},
})
factory = MyFactory()
assert factory.type == 'Factory'
person = factory.get_person()
assert person.type == 'Person'
try:
friends = person.get_friends()
except ValueError as e:
print '(caught raised error:) e'
enemies = person.get_enemies()
assert not enemies
r_hello = person.say_hello()
r_hello_2 = person.say_hello_2()
assert r_hello == r_hello_2
@peterldowns
Copy link
Author

Found this helper function useful while mocking the Stripe API in some unit tests – the functions I was testing did various things with results of consecutive API calls and their nested responses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment