【问题标题】:python retry with retrying, disable for unittest [duplicate]python重试重试,禁用unittest [重复]
【发布时间】:2019-06-19 01:29:36
【问题描述】:

编辑:由于 Tenacity 是最近的重试,所以这个问题可以被认为是链接问题的重复,解决方案是升级到 Tenacity。

类似于this question,我想在python中对一个具有重试装饰器的函数进行单元测试:

from retrying import retry # from retrying pypi module

WAIT_EXPONENTIAL_MULTIPLIER = 4 * 1000  # ms
STOP_MAX_ATTEMPT_NUMBER = 5

@retry(
   wait_exponential_multiplier=WAIT_EXPONENTIAL_MULTIPLIER,
   stop_max_attempt_number=STOP_MAX_ATTEMPT_NUMBER
)
def get_from_remote(key):
    raise ValueError() # for example

在我的单元测试中,有时我想调用此函数而不重试,有时使用不同的参数。

我尝试在setUp()/tearDown() 中设置变量,但没有成功。我尝试修补重试装饰器,但它也不起作用。

【问题讨论】:

    标签: python mocking python-unittest python-tenacity


    【解决方案1】:

    由于这条线,不确定这是否可能

    Retrying(*dargs, **dkw).call(f, *args, **kw)
    

    retryingRetrying 实例是在函数运行时即时创建的,无法再更改其属性。

    一种方法是保留未修饰的引用 在运行时功能和装饰老式。

    from retrying import retry
    
    WAIT_EXPONENTIAL_MULTIPLIER = 1 * 1000  # ms
    
    # the "normal" decorator
    retry_dec = retry(wait_exponential_multiplier=WAIT_EXPONENTIAL_MULTIPLIER)
    
    # the undecorated function
    def get_from_remote_undecorated(key):
        raise ValueError()
    
    # this is the "normal" decorated function
    get_from_remote = retry_dec(get_from_remote_undecorated)
    

    这可以在单元测试中重复:

    # some test
    retry_dec_test_1 = retry(wait_exponential_multiplier=WAIT_EXPONENTIAL_MULTIPLIER)
    get_from_remote_test_1 = retry_dec_test_1(get_from_remote_undecorated)
    
    # another test with different parameters
    retry_dec_test_2 = retry(stop_max_attempt_number=STOP_MAX_ATTEMPT_NUMBER)
    get_from_remote_test_2 = retry_dec_test_2 (get_from_remote_undecorated)
    

    但我对这种方法并不满意,我会努力寻找更好的解决方案。

    【讨论】:

    • 经过一番研究,我发现tenacity是推荐使用的包,所以尝试通过重试来解决这个问题有点浪费。
    • 你可以在 python 中做任何事情。它并不总是很漂亮,但get_from_remote.im_func.func_closure[1].cell_contents["stop_max_attempt_number"] = 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2011-02-17
    • 2020-11-14
    • 2021-08-17
    相关资源
    最近更新 更多