I'd like to test a recursive function and then mock that same function out. For the first call, I want to actually call the function as it appears in my module. When it calls itself, I'd like to mock out the call using mock and specify the return value of this second recursive call.
A really simple example of what I mean:
def some_function(input_value):
if input_value == some_appropriate_value:
return foo
else:
return some_function(some_other_value)
How do I mock out some_function
the second time it is called? If I use something like a @mock.patch decorator, I can't actually test it as some_function
will be mocked out for all calls.
Any suggestions of how to do this? I couldn't find any obvious Stack Overflow questions discussing this.
If you save the function before patching you can call the correct version.
copy_of_foo = foo
with patch('...foo') as foo_mock:
copy_of_foo(args...)
In order to get your patched function to call differently you can try a few things: 1. side_effects and 2. subclassing a mock object to override the function call and keep a counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With