首页 > 解决方案 > 未调用 Pytest 模拟补丁函数

问题描述

我确信调用了一个函数(因为上面有一个 print 语句)。

我的测试目标是handle_action一个名为__init__.py

PS。我的猜测是模块的名称 ( __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_nothinghandlers.handle_nothing我得到同样的错误。

我不知道,其他模拟工作正常。

也许是文件名?(代码在__init__.py

标签: pythonpytestpython-mock

解决方案


问题是你来不及打补丁,名字在导入时已经解析了,当handlers字典被创建时,即当代码被导入时:

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

handle_action您的测试中调用时,名称handle_nothingname 是否已用其他东西修补并不重要,因为该名称实际上根本没有被使用handle_action

相反,您需要直接修补handlersdict 中的值。


推荐阅读