1

This code runs, does not error, but does not mock out the function like I would like. Why not? Also, clearly, these functions are not "side effects", they are pure functions, but AFAIK, that is the syntax used to mock out a function using the standard Python mocking library.

# mocking test
from mock import mock


def local_f(a, b):
    print "default local_f(%d,%d)" % (a, b)
    return a + b


def local_f2(a, b):
    print "local_f2(%d,%d)" % (a, b)
    return a * b


def go():
    print "(before) testing simple_f: %s" % local_f(3, 4)

    with mock.patch('mock_test.local_f',
                    side_effect=local_f2) as mock_function_obj:
        print "type(mock_function_obj) = %s" % type(mock_function_obj)
        print "(with) testing simple_f: %s" % local_f(3, 4)

    print "(after) testing simple_f: %s" % local_f(3, 4)

if __name__ == "__main__":
    go()
clay
  • 18,138
  • 28
  • 107
  • 192

1 Answers1

1

Mocking has to happen with respect to the module you are mocking. In your particular case, you are mocking with respect to __main__. I'm assuming mock_test is the name of the file containing the code you posted? Therefore, your patch should look like this:

with mock.patch('__main__.local_f')

Sample output after making my change to your code:

default local_f(3,4)
(before) testing simple_f: 7
type(mock_function_obj) = <class 'mock.MagicMock'>
local_f2(3,4)
(with) testing simple_f: 12
default local_f(3,4)
(after) testing simple_f: 7
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • That worked! Yes, `mock_test` is the file or module. Please explain this. Why `__main__`? that isn't the module, what is it? I need to get this working in a larger project. – clay Sep 29 '15 at 01:06
  • That is the current module's name. So, you performing a `python mock_test.py` that assigns the global `__name__` = `__main__`. This is actually why at the bottom of your python script you had to put that condition for `if __name__ == "__main__"`. It tells the interpreter that if it is the current module, then execute what is inside that condition. In your case it is `go()`. This here is a fantastic explanation: http://stackoverflow.com/questions/419163/what-does-if-name-main-do – idjaw Sep 29 '15 at 01:11
  • 1
    Ah, `__name__` is the name of the current module. When you run directly, that is the string `"__main__"` not `"mock_tests"`. Got it!!! Thanks!!! – clay Sep 29 '15 at 01:26
  • Awesome! I just deleted a bunch of posts I was writing explaining that! :) Glad you got it. Good luck. – idjaw Sep 29 '15 at 01:37