Mailing List Archive

New functionality for unittest.mock side_effect
I often want a side_effect of "if called with foo, return bar" functionality. This is really useful when the order of calls to your mock is indeterminate, so you can't just use an iterable. What I end up doing is writing a little function:

def f(x):
data = {
'foo': 'bar',
'baz': 'blah',
}
return data[x]

my_mock.side_effect = f

sometimes I wrap that up in a lambda, but either way it's fidgety boilerplate which obfuscates the intent. It would be nice if side_effect could accept a dict and provide the above functionality for free:

my_mock.side_effect = {
'foo': 'bar',
'baz': 'blah',
}

If could handle DEFAULT just like side_effect does now. And it could throw something more useful than KeyError if the key isn't found.

I could see the argument that "but dicts are themselves iterable, so this could break some existing mocks which depend on side_effect iterating over the dicts keys. That would be bizarre, but possible. The fix for that would be invent a new attribute, say, return_value_map, which does this, and say that it's an error to set more than one of {return_value, return_value_map, side_effect}.

Anyway, if I were to take a whack at coding this up, is it something that would be considered for a future release?




_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-leave@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/4A24FFKMN2PEB4GRERXUX2BUNVMZR2MA/
Code of Conduct: http://python.org/psf/codeofconduct/