python - 未调用 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_nothing
为handlers.handle_nothing
我得到同样的错误。
我不知道,其他模拟工作正常。
也许是文件名?(代码在__init__.py
)
解决方案
问题是你来不及打补丁,名字在导入时已经解析了,当handlers
字典被创建时,即当代码被导入时:
handlers = {
HANDLE_NOTHING: handle_nothing, # <-- name lookup of "handle_nothing" happens now!
}
在handle_action
您的测试中调用时,名称handle_nothing
name 是否已用其他东西修补并不重要,因为该名称实际上根本没有被使用handle_action
。
相反,您需要直接修补handlers
dict 中的值。
推荐阅读
- regex - Vala regex using groups with subgroups keeps ending in a segmentationfault
- algorithm - 使用动态编程计算赢得比赛的机会
- java - 将更改直接填充到弹性搜索
- php - 从mysql中的多个表中删除
- angular - Angular 4中控件的动态添加
- ansible - Ansible 与 Packer
- typescript - 对“对象”类型感到困惑?
- javascript - 在自动完成中仅渲染某些项目
- excel - 我可以让 excel 刷新约 500 个查询吗?
- jquery - 如何在 jQuery 3.3.1 上访问对象的 jQuery 事件句柄数组