Q: I mocked in my test, but the actual code didn’t pick it up! WTF?

# in the test
<MagicMock name='some_function' id='140508395699216'>

# in the source
<function some_function at 0x7fcaa8eadd40>

Here’s the code.

test.py

from bar import do_thing

# We want to test that `do_thing` calls `some_function`, so we mock
# `some_function`.
@patch("foo.some_function")
def test_do_thing(mocked_some_function):

  do_thing()

  # Check that it was called.
  mocked_some_function.assert_called()

foo.py

def some_function():
  pass

bar.py

from foo import some_function
def do_thing():
  some_function()

A: Mock where used, not where defined.

  • the test imports bar
  • bar imports foo
  • foo.some_function is copied as bar.some_function
  • the test mocks foo.some_function

When you break it down into something simple, it’s easy to see. The test is using bar.some_function, so mock that instead!

https://docs.python.org/3/library/unittest.mock.html#where-to-patch