Python 模拟补丁局部函数
Python mock patch local function
我想检查是否调用了局部函数(在测试本身上声明)。
例如:
def test_handle_action():
action = "test"
user = "uid"
room = "room"
content = "test"
data = {}
def test_this(user, room, content, data):
pass
handlers = {action: test_this}
with mock.patch("handlers.handlers", handlers):
with mock.patch(".test_this") as f:
handle_action(action, user, room, content, data)
f.assert_called_with()
如何在测试中模拟函数 test_this
的路径?
使用 .test_this
我得到了错误:
E ValueError: Empty module name
如果 test_this
是模拟函数,您可以将 test_this
定义为模拟对象并在其上定义断言:
from unittest import mock
def test_handle_action():
# GIVEN
action = "test"
user = "uid"
room = "room"
content = "test"
data = {}
test_this = mock.Mock()
handlers = {action: test_this}
with mock.patch("handlers.handlers", handlers):
# WHEN
handle_action(action, user, room, content, data)
# THEN
test_this.assert_called_with(user, room, content, data)
我想检查是否调用了局部函数(在测试本身上声明)。
例如:
def test_handle_action():
action = "test"
user = "uid"
room = "room"
content = "test"
data = {}
def test_this(user, room, content, data):
pass
handlers = {action: test_this}
with mock.patch("handlers.handlers", handlers):
with mock.patch(".test_this") as f:
handle_action(action, user, room, content, data)
f.assert_called_with()
如何在测试中模拟函数 test_this
的路径?
使用 .test_this
我得到了错误:
E ValueError: Empty module name
如果 test_this
是模拟函数,您可以将 test_this
定义为模拟对象并在其上定义断言:
from unittest import mock
def test_handle_action():
# GIVEN
action = "test"
user = "uid"
room = "room"
content = "test"
data = {}
test_this = mock.Mock()
handlers = {action: test_this}
with mock.patch("handlers.handlers", handlers):
# WHEN
handle_action(action, user, room, content, data)
# THEN
test_this.assert_called_with(user, room, content, data)