How can I conditionally call the original method in a mock?
In this example I only want to fake a return value if bar=='x'
. Otherwise I want to call the original method.
def mocked_some_method(bar):
if bar=='x':
return 'fake'
return some_how_call_original_method(bar)
with mock.patch('mylib.foo.some_method', mocked_some_method):
do_some_stuff()
I know that it is a bit strange. If I want to fake mylib.foo.some_method
in side do_some_stuff()
it should be condition-less. All (not some) calls to some_method
should be mocked.
In my case it is an integration test, not a s tiny unittest and mylib.foo.some_method
is a kind of dispatcher which gets used very often. And in one case I need to fake the result.
Update
I wrote this question four years ago. Today, it feels very strange to do conditional mocking. Mocks should only get used in tests. Tests (and production code) should be simple and small. Tests should be conditionless. As I wrote this question, we still used huge production methods and long test. Today, I follow these rules (simple methods, conditionless tests ...). I wrote my findings down: my programming guidelines
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…