Skip to content

Commit bfb40e6

Browse files
fix: add warning to retry target to avoid incorrect usage (#543)
* fix: add warning to retry target to avoid incorrect use * fix: add comment for predicate * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: omair <[email protected]> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent ffd958f commit bfb40e6

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

google/api_core/retry.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ def check_if_exists():
6262
import random
6363
import sys
6464
import time
65+
import inspect
66+
import warnings
6567
from typing import Any, Callable, TypeVar, TYPE_CHECKING
6668

6769
import requests.exceptions
@@ -84,6 +86,7 @@ def check_if_exists():
8486
_DEFAULT_MAXIMUM_DELAY = 60.0 # seconds
8587
_DEFAULT_DELAY_MULTIPLIER = 2.0
8688
_DEFAULT_DEADLINE = 60.0 * 2.0 # seconds
89+
_ASYNC_RETRY_WARNING = "Using the synchronous google.api_core.retry.Retry with asynchronous calls may lead to unexpected results. Please use google.api_core.retry_async.AsyncRetry instead."
8790

8891

8992
def if_exception_type(
@@ -201,7 +204,10 @@ def retry_target(
201204

202205
for sleep in sleep_generator:
203206
try:
204-
return target()
207+
result = target()
208+
if inspect.isawaitable(result):
209+
warnings.warn(_ASYNC_RETRY_WARNING)
210+
return result
205211

206212
# pylint: disable=broad-except
207213
# This function explicitly must deal with broad exceptions.

tests/unit/test_retry.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,26 @@ def test_retry_target_non_retryable_error(utcnow, sleep):
129129
sleep.assert_not_called()
130130

131131

132+
@mock.patch("asyncio.sleep", autospec=True)
133+
@mock.patch(
134+
"google.api_core.datetime_helpers.utcnow",
135+
return_value=datetime.datetime.min,
136+
autospec=True,
137+
)
138+
@pytest.mark.asyncio
139+
async def test_retry_target_warning_for_retry(utcnow, sleep):
140+
predicate = retry.if_exception_type(ValueError)
141+
target = mock.AsyncMock(spec=["__call__"])
142+
143+
with pytest.warns(Warning) as exc_info:
144+
# Note: predicate is just a filler and doesn't affect the test
145+
retry.retry_target(target, predicate, range(10), None)
146+
147+
assert len(exc_info) == 2
148+
assert str(exc_info[0].message) == retry._ASYNC_RETRY_WARNING
149+
sleep.assert_not_called()
150+
151+
132152
@mock.patch("time.sleep", autospec=True)
133153
@mock.patch("google.api_core.datetime_helpers.utcnow", autospec=True)
134154
def test_retry_target_deadline_exceeded(utcnow, sleep):

0 commit comments

Comments
 (0)