python坚韧地重试,禁用unittest的"wait" [英] python retry with tenacity, disable `wait` for unittest

查看:129
本文介绍了python坚韧地重试,禁用unittest的"wait"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 tenacity 库来使用其@retry装饰器.

I am using the tenacity library to use its @retry decorator.

我正在使用它来创建一个函数,该函数可以在失败的情况下多次重复执行HTTP请求.

I am using this to make a function which makes a HTTP-request "repeat" multiple times in case of failure.

这是一个简单的代码段:

Here is a simple code snippet:

@retry(stop=stop_after_attempt(7), wait=wait_random_exponential(multiplier=1, max=60))
def func():
   ...
   requests.post(...)

该函数使用强度wait参数在两次调用之间等待一段时间.

The function uses the tenacity wait-argument to wait some time in between calls.

该功能与@retry -decorator一起正常工作.

The function together with the @retry-decorator seems to work fine.

但是我还有一个单元测试,可以检查该函数在发生故障的情况下是否确实被调用了7次.由于两次尝试之间的此wait,因此此测试需要很多时间.

But I also have a unit-test which checks that the function gets called indeed 7 times in case of a failure. This test takes a lot of time because of this wait in beetween tries.

是否有可能仅在单元测试中禁用等待时间?

Is it possible to somehow disable the wait-time only in the unit-test?

推荐答案

该解决方案来自坚韧不拔的维护者本人,在此Github问题中:

The solution came from the maintainer of tenacity himself in this Github issue: https://github.com/jd/tenacity/issues/106

您可以简单地临时更改单元测试的等待功能:

You can simply change the wait function temporarily for your unit test:

from tenacity import wait_none

func.retry.wait = wait_none()

这篇关于python坚韧地重试,禁用unittest的"wait"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆