【问题标题】:Pytest mock patch function not called未调用 Pytest 模拟补丁函数
【发布时间】:2021-04-07 20:02:30
【问题描述】:

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

我的测试目标是一个名为__init__.py的文件上的函数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 我会遇到同样的错误。

我不知道,其他模拟效果很好。

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

【问题讨论】:

    标签: python pytest python-mock


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 哦!这就说得通了。谢谢!
    猜你喜欢
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2020-10-29
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多