You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Mock中assert_any_call断言不匹配的问题求助

Python Mock中assert_any_call断言不匹配的问题求助

我遇到了一个Python Mock断言的棘手问题,明明看起来参数完全匹配,但使用assert_any_call时却总是断言失败,实在摸不着头脑,想请大家帮忙排查下问题所在。

背景代码

我要断言的日志调用代码如下:

...
logger.warning('Backup quantity is 0, supplied uuids %s, matched machines: %s', uuids, machines)
...

我的单元测试代码

下面是我单元测试的最后几行代码,前两行是为了排查问题加的临时代码:

# 故意写失败的断言,用来打印实际的调用记录
logger.warning.assert_not_called()

# 打印我准备在断言中使用的参数,方便和实际调用对比
print('Backup quantity is 0, supplied uuids %s, matched machines: %s', [vm3_uuid], VirtualMachine.objects.none())

# 实际要执行的目标断言
logger.warning.assert_any_call('Backup quantity is 0, supplied uuids %s, matched machines: %s', [vm3_uuid], VirtualMachine.objects.none())

测试输出详情

  1. assert_not_called的错误输出
    执行这条故意失败的断言后,得到了实际的调用记录:
AssertionError: Expected 'warning' to not have been called. Called 2 times.
Calls: [call('Backup quantity is 0, supplied uuids %s, matched machines: %s', ['232d7937-975c-457b-8a11-ac473d0e04a0'], <QuerySet []>),
 call('%s %s cannot find proxmox UUID from BIS', 'DEF-456', 'vm4')]
  1. print语句的输出
    用来对比参数的print语句输出结果:
Backup quantity is 0, supplied uuids %s, matched machines: %s ['232d7937-975c-457b-8a11-ac473d0e04a0'] <QuerySet []>
  1. assert_any_call的失败输出
    执行目标断言时,得到的错误提示:
AssertionError: warning('Backup quantity is 0, supplied uuids %s, matched machines: %s', ['232d7937-975c-457b-8a11-ac473d0e04a0'], <QuerySet []>) call not found

我的疑问

我反复对比了实际调用的参数和我在断言里传入的参数,看起来完全一致啊,实在想不通为什么assert_any_call会断言失败。是不是我漏看了什么特别明显的细节?

备注:内容来源于stack exchange,提问作者James Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:44:27