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

如何对使用tenacity库的重试函数做单元测试,验证其执行3次重试

验证tenacity重试函数执行3次的单元测试方法

首先要明确:tenacity默认仅在函数抛出异常时才会触发重试逻辑,所以你需要先修改目标函数,让它抛出异常(或构造触发异常的测试场景),否则即使添加了重试装饰器,函数也只会执行一次。

下面提供两种可行的单元测试实现方式:

方法一:用计数器追踪调用次数

借助可变对象(比如列表)记录调用次数,避免不可变变量的作用域限制:

from tenacity import retry, stop_after_attempt
import unittest

# 修改函数,抛出异常触发重试
@retry(stop=stop_after_attempt(3))
def func():
    raise ValueError("测试重试触发异常")

class TestRetryCount(unittest.TestCase):
    def test_retry_executes_three_times(self):
        call_count = [0]  # 用列表存储计数,保证内部修改能被外部读取
        
        def tracked_call():
            call_count[0] += 1
            return func()
        
        try:
            tracked_call()
        except ValueError:
            pass  # 捕获预期的异常,避免测试中断
        
        self.assertEqual(call_count[0], 3)

if __name__ == "__main__":
    unittest.main()

方法二:用unittest.mock统计调用次数

利用mock对象的call_count属性直接获取调用次数,实现更简洁:

from tenacity import retry, stop_after_attempt
import unittest
from unittest.mock import Mock

# 修改函数,抛出异常触发重试
@retry(stop=stop_after_attempt(3))
def func():
    raise ValueError("测试重试触发异常")

class TestRetryCount(unittest.TestCase):
    def test_retry_executes_three_times(self):
        # 用Mock包装原函数,自动统计调用次数
        mocked_func = Mock(wraps=func)
        
        try:
            mocked_func()
        except ValueError:
            pass
        
        self.assertEqual(mocked_func.call_count, 3)

if __name__ == "__main__":
    unittest.main()

如果你的func原本是在特定业务条件下抛出异常,只需在测试中构造对应的异常触发场景即可,不需要修改原函数逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:02:37