Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking out a function on a repeated call with Python mock

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.

like image 539
Steven Maude Avatar asked Sep 20 '13 12:09

Steven Maude


1 Answers

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.

like image 75
ostler.c Avatar answered Nov 27 '22 17:11

ostler.c