Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for mocking sleep when retrying async functions #440

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
features:
- |
Unit tests can now mock ``nap.asyncio_sleep`` to skip waiting when retrying
asynchronous functions, similar to mocking ``nap.time.sleep`` for
synchronous ones.
6 changes: 4 additions & 2 deletions tenacity/_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
import functools
import sys
import typing as t
from asyncio import sleep

from tenacity import AttemptManager
from tenacity import BaseRetrying
from tenacity import DoAttempt
from tenacity import DoSleep
from tenacity import RetryCallState
from tenacity.nap import async_sleep

WrappedFnReturnT = t.TypeVar("WrappedFnReturnT")
WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable[..., t.Awaitable[t.Any]])
Expand All @@ -34,7 +34,9 @@ class AsyncRetrying(BaseRetrying):
sleep: t.Callable[[float], t.Awaitable[t.Any]]

def __init__(
self, sleep: t.Callable[[float], t.Awaitable[t.Any]] = sleep, **kwargs: t.Any
self,
sleep: t.Callable[[float], t.Awaitable[t.Any]] = async_sleep,
**kwargs: t.Any,
) -> None:
super().__init__(**kwargs)
self.sleep = sleep
Expand Down
10 changes: 10 additions & 0 deletions tenacity/nap.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import time
import typing
from asyncio import sleep as asyncio_sleep

if typing.TYPE_CHECKING:
import threading
Expand All @@ -41,3 +42,12 @@ def __call__(self, timeout: typing.Optional[float]) -> None:
# NOTE(harlowja): this may *not* actually wait for timeout
# seconds if the event is set (ie this may eject out early).
self.event.wait(timeout=timeout)


async def async_sleep(seconds: float) -> None:
"""
Async sleep strategy that delays execution for a given number of seconds.

To mock waiting for unit testing patch `tenacity.nap.asyncio_sleep` with a no-op.
"""
await asyncio_sleep(seconds)
11 changes: 11 additions & 0 deletions tests/test_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import asyncio
import inspect
import unittest
import unittest.mock
from functools import wraps

import pytest
Expand Down Expand Up @@ -211,6 +212,16 @@ async def test_async_retying_iterator(self):
await _async_function(thing)


class TestAsyncSleepMocking(unittest.TestCase):
@asynctest
async def test_mock_sleep(self):
mock = unittest.mock.AsyncMock()
with unittest.mock.patch("tenacity.nap.asyncio_sleep", mock):
thing = NoIOErrorAfterCount(3)
await _retryable_coroutine(thing)
assert mock.await_count == 3


# make sure mypy accepts passing an async sleep function
# https://github.com/jd/tenacity/issues/399
async def my_async_sleep(x: float) -> None:
Expand Down