Skip to content

Instantly share code, notes, and snippets.

@simanacci
Forked from peterldowns/mock_object.py
Created July 4, 2021 13:01
Show Gist options
  • Save simanacci/0eaeb3fdc46f14915c65a981146bbb14 to your computer and use it in GitHub Desktop.
Save simanacci/0eaeb3fdc46f14915c65a981146bbb14 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment