python - Python 模拟补丁本地函数
问题描述
我想检查是否调用了本地函数(在测试本身上声明)。
例如:
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
解决方案
Iftest_this
是一个模拟函数,您可以定义test_this
为一个 Mock 对象并在其上定义断言:
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)
推荐阅读
- javascript - 单击时访问本地存储中的键值未按计划工作
- sql-server - 异步 AO 复制中的 SQL 数据库 - 备份后日志文件不保存
- swift - Xcode 中的上下文帮助未显示
- mysql - 单击 URL 后停止显示行。PHP MYSQLI
- python - 对 pandas 使用正确的分隔符
- r - Redshift 连接错误:找不到函数“JDBC”
- ios - 如何使用 OpenSans 自定义字体在 **Swift 4** 中为文本范围添加下划线和粗体
- stripe-payments - 如何为其他客户发送 Stripe 的测试 webhook?
- java - 如何在 JavaFX 中嵌入字体?
- android-sqlite - sqlitedatabase 更新 where 子句