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

测试函数write_standalone_end_of_event调用次数遇AssertionError问题

问题:单元测试无法捕获函数调用次数

参考相关建议搭建测试代码,想要验证write_standalone_end_of_event函数的调用次数,但运行测试时抛出AssertionError: 0 != 1——调试过程中明明看到函数被调用了一次,但测试代码就是无法捕获这次调用。

业务代码(exchanges.impl.bats.mcformat.py)

def delete_data(...): 
    exg = exchanges.impl.bate.parser.Exchange
    securities = [one_item]
    
    for security in securities: 
        exg.write_standalone_end_of_event

测试代码(unit_test_package)

with patch('exchanges.impl.bate.parser.Exchange.write_standalone_end_of_event') as function:
    bats.protocol.sec_id_in_batch = {1: 'dummy1'}
    bats.protocol.transaction_end(exg, fields, values, msgtype, sequence)
    assert function.gacs.call_count == 1

问题排查与解决方案

1. 业务代码未实际调用函数

看业务代码里的循环行:exg.write_standalone_end_of_event——这只是引用了函数对象,没有加括号执行调用,所以实际函数根本没被触发。调试时可能误判了执行流程,修正后应该是:

for security in securities: 
    exg.write_standalone_end_of_event()  # 加上括号完成调用

2. 测试断言存在笔误

测试代码里写的function.gacs.call_count是错误的,unittest.mock.patch返回的Mock对象直接通过call_count属性获取调用次数,应该改成:

assert function.call_count == 1

3. 确认Patch路径的正确性

确保你patch的路径和业务代码中实际调用函数的路径完全一致:

  • 如果业务代码中是直接通过exchanges.impl.bate.parser.Exchange类调用方法,当前patch路径是对的;
  • 如果业务代码里是先导入Exchange类再使用(比如from exchanges.impl.bate.parser import Exchange),那需要patch业务代码文件中导入的那个Exchange,而不是原模块的路径。比如业务代码在exchanges.impl.bats.mcformat里导入了Exchange,那patch路径应该是'exchanges.impl.bats.mcformat.Exchange.write_standalone_end_of_event'。

内容的提问来源于stack exchange,提问作者Patrick_Chong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:35:24