Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5cdba7b

Browse files
committed
fix: add warning to retry target to avoid incorrect use
1 parent 405272c commit 5cdba7b

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-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: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,24 @@ def test_retry_target_non_retryable_error(utcnow, sleep):
128128
assert exc_info.value == exception
129129
sleep.assert_not_called()
130130

131+
@mock.patch("asyncio.sleep", autospec=True)
132+
@mock.patch(
133+
"google.api_core.datetime_helpers.utcnow",
134+
return_value=datetime.datetime.min,
135+
autospec=True,
136+
)
137+
@pytest.mark.asyncio
138+
async def test_retry_target_warning_for_retry(utcnow, sleep):
139+
predicate = retry.if_exception_type(ValueError)
140+
target = mock.AsyncMock(spec=["__call__"])
141+
142+
with pytest.warns(Warning) as exc_info:
143+
retry.retry_target(target, predicate, range(10), None)
144+
145+
assert len(exc_info) == 2
146+
assert str(exc_info[0].message) == retry._ASYNC_RETRY_WARNING
147+
sleep.assert_not_called()
148+
131149

132150
@mock.patch("time.sleep", autospec=True)
133151
@mock.patch("google.api_core.datetime_helpers.utcnow", autospec=True)

0 commit comments

Comments
 (0)