Search code examples
pythonpytestpython-mock

Pytest mock patch function not called


I am sure that a function is called (because of a print statement on it).

My test target is the function handle_action.

__init__.py

from .dummy import HANDLE_NOTHING, handle_nothing

handlers = {
    HANDLE_NOTHING: handle_nothing,
}


def handle_action(action, user, room, content, data):
    func = handlers.get(action)

    if func:
        func(user, room, content, data)

Unit test

import mock

from handlers import HANDLE_NOTHING, handle_action


def test_handle_dummy_action():
    action = HANDLE_NOTHING
    user = "uid"
    room = "room"
    content = "test"
    data = {}

    with mock.patch("handlers.dummy.handle_nothing") as f:
        handle_action(action, user, room, content, data)

        f.assert_called_with()

When I run I get:

E           AssertionError: expected call not found.
E           Expected: handle_nothing()
E           Actual: not called.

If I change from handlers.dummy.handle_nothing to handlers.handle_nothing I receive the same error.


Solution

  • The problem is that you are too late to patch, the name was already resolved at import time when the handlers dict was created, i.e. when the code was imported:

    handlers = {
        HANDLE_NOTHING: handle_nothing,  # <-- name lookup of "handle_nothing" happens now!
    }
    

    By the time handle_action is called in your test, it doesn't matter if the name handle_nothing name has been patched with something else, because that name is not actually used by handle_action at all.

    Instead, you will need to patch the value in the handlers dict directly.