[TIP] Not able to patch modules used in __init__.py

Paul Moore p.f.moore at gmail.com
Thu Aug 25 07:16:59 PDT 2016


On 25 August 2016 at 14:55, Sijo Jose <mailtosijojose at gmail.com> wrote:
> I've the following code in the __init__.py file
>
>     from time import sleep
>     from functools import wraps
>
>     def multi_try(func):
>         @wraps(func)
>         def inner(*args, **kwargs):
>             count = 0
>             while count < 5:
>                 resp = func(*args, **kwargs)
>                 if resp.status_code in [200, 201]:
>                     return resp
>                 sleep(1)
>                 count += 1
>         return inner
>
>
> While writing tests for the above decorator I'm not able to patch the the
> *time.sleep* properly.

The code here uses "sleep" (a module variable in your module) not
"time.sleep". So you need to patch "mymodule.sleep" rather than
"time.sleep", or do "import time" and use "time.sleep" in your
__init__.py.

Paul



More information about the testing-in-python mailing list