Possible to mock function such that one parameter is always set to a specified value?

55 views Asked by At

For example, suppose I have the function:

def foo(var1, var2):
    print '%s, %s' % (var1, var2)

Is it possible using Mock or another tool to temporarily override the function such that the second value is always set to some value, like lorem ipsum?

foo('hello', 'world') # prints "hello, lorem ipsum"
foo('goonight', 'moon') # prints "goodnight, lorem ipsum"

I would still need to change foo() even when it's nested in another function/class:

def greet(name):
    foo('hello', name)


greet('john') # prints "hello, lorem ipsum"

This is intended to be used as a way to force a consistent action when unit testing. Seems like a simple problem, but haven't managed to find a good option yet.

Thanks!

1

There are 1 answers

0
chepner On

Save a reference to the original function, then patch it with a function that calls the original with the fixed second argument.

original_foo = foo  
# Or whatever name actually needs to be patched 
with mock.patch('__main__.foo', lambda x, y: original_foo(x, 'lorem ipsum')):
    # do stuff involving foo

The important thing is that the patched object cannot refer to foo directly, since the lookup of the name foo would occur in the context where the name foo has already been patched, leading to an infinite loop.