Pytest模拟补丁函数未被调用。

3

我确定某个函数被调用了(因为在该函数中有一个打印语句)。

我的测试目标是函数 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)

单元测试

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()

当我运行时,出现以下信息:
E           AssertionError: expected call not found.
E           Expected: handle_nothing()
E           Actual: not called.

如果我从handlers.dummy.handle_nothing改为handlers.handle_nothing,我会收到相同的错误。
1个回答

3
问题在于你太晚进行了修补,当 handlers 字典被创建时,即代码被导入时,名称已经被解析:

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

当测试中调用handle_action时,handle_nothing的名称是否已被替换为其他内容并不重要,因为handle_action根本不使用该名称。

相反,您需要直接在handlers字典中修补值。


哦!那很有道理。谢谢! - Rodrigo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接