[英]Pytest mock patch function not called
I am sure that a function is called (because of a print statement on it).我确信调用了 function(因为上面有打印语句)。
My test target is the function handle_action
.我的测试目标是 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)
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.如果我从handlers.dummy.handle_nothing
更改为handlers.handle_nothing
我会收到相同的错误。
The problem is that you are too late to patch, the name was already resolved at import time when the handlers
dict was created, ie when the code was imported :问题是你来不及打补丁,在创建handlers
字典时,名称已经在导入时解析,即在导入代码时:
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.到在您的测试中调用handle_action
时,名称handle_nothing
名称是否已用其他东西修补都无关紧要,因为handle_action
根本没有实际使用该名称。
Instead, you will need to patch the value in the handlers
dict directly.相反,您需要直接修补handlers
字典中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.