| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import datetime |
| 4 |
from test import DUMMY_POOL |
| 5 |
from unittest import mock |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from urllib3.exceptions import ( |
| 10 |
ConnectTimeoutError, |
| 11 |
InvalidHeader, |
| 12 |
MaxRetryError, |
| 13 |
ReadTimeoutError, |
| 14 |
ResponseError, |
| 15 |
SSLError, |
| 16 |
) |
| 17 |
from urllib3.response import HTTPResponse |
| 18 |
from urllib3.util.retry import RequestHistory, Retry |
| 19 |
|
| 20 |
|
| 21 |
class TestRetry: |
| 22 |
def test_string(self) -> None: |
| 23 |
"""Retry string representation looks the way we expect""" |
| 24 |
retry = Retry() |
| 25 |
assert ( |
| 26 |
str(retry) |
| 27 |
== "Retry(total=10, connect=None, read=None, redirect=None, status=None)" |
| 28 |
) |
| 29 |
for _ in range(3): |
| 30 |
retry = retry.increment(method="GET") |
| 31 |
assert ( |
| 32 |
str(retry) |
| 33 |
== "Retry(total=7, connect=None, read=None, redirect=None, status=None)" |
| 34 |
) |
| 35 |
|
| 36 |
def test_retry_both_specified(self) -> None: |
| 37 |
"""Total can win if it's lower than the connect value""" |
| 38 |
error = ConnectTimeoutError() |
| 39 |
retry = Retry(connect=3, total=2) |
| 40 |
retry = retry.increment(error=error) |
| 41 |
retry = retry.increment(error=error) |
| 42 |
with pytest.raises(MaxRetryError) as e: |
| 43 |
retry.increment(error=error) |
| 44 |
assert e.value.reason == error |
| 45 |
|
| 46 |
def test_retry_higher_total_loses(self) -> None: |
| 47 |
"""A lower connect timeout than the total is honored""" |
| 48 |
error = ConnectTimeoutError() |
| 49 |
retry = Retry(connect=2, total=3) |
| 50 |
retry = retry.increment(error=error) |
| 51 |
retry = retry.increment(error=error) |
| 52 |
with pytest.raises(MaxRetryError): |
| 53 |
retry.increment(error=error) |
| 54 |
|
| 55 |
def test_retry_higher_total_loses_vs_read(self) -> None: |
| 56 |
"""A lower read timeout than the total is honored""" |
| 57 |
error = ReadTimeoutError(DUMMY_POOL, "/", "read timed out") |
| 58 |
retry = Retry(read=2, total=3) |
| 59 |
retry = retry.increment(method="GET", error=error) |
| 60 |
retry = retry.increment(method="GET", error=error) |
| 61 |
with pytest.raises(MaxRetryError): |
| 62 |
retry.increment(method="GET", error=error) |
| 63 |
|
| 64 |
def test_retry_total_none(self) -> None: |
| 65 |
"""if Total is none, connect error should take precedence""" |
| 66 |
error = ConnectTimeoutError() |
| 67 |
retry = Retry(connect=2, total=None) |
| 68 |
retry = retry.increment(error=error) |
| 69 |
retry = retry.increment(error=error) |
| 70 |
with pytest.raises(MaxRetryError) as e: |
| 71 |
retry.increment(error=error) |
| 72 |
assert e.value.reason == error |
| 73 |
|
| 74 |
timeout_error = ReadTimeoutError(DUMMY_POOL, "/", "read timed out") |
| 75 |
retry = Retry(connect=2, total=None) |
| 76 |
retry = retry.increment(method="GET", error=timeout_error) |
| 77 |
retry = retry.increment(method="GET", error=timeout_error) |
| 78 |
retry = retry.increment(method="GET", error=timeout_error) |
| 79 |
assert not retry.is_exhausted() |
| 80 |
|
| 81 |
def test_retry_default(self) -> None: |
| 82 |
"""If no value is specified, should retry connects 3 times""" |
| 83 |
retry = Retry() |
| 84 |
assert retry.total == 10 |
| 85 |
assert retry.connect is None |
| 86 |
assert retry.read is None |
| 87 |
assert retry.redirect is None |
| 88 |
assert retry.other is None |
| 89 |
|
| 90 |
error = ConnectTimeoutError() |
| 91 |
retry = Retry(connect=1) |
| 92 |
retry = retry.increment(error=error) |
| 93 |
with pytest.raises(MaxRetryError): |
| 94 |
retry.increment(error=error) |
| 95 |
|
| 96 |
retry = Retry(connect=1) |
| 97 |
retry = retry.increment(error=error) |
| 98 |
assert not retry.is_exhausted() |
| 99 |
|
| 100 |
assert Retry(0).raise_on_redirect |
| 101 |
assert not Retry(False).raise_on_redirect |
| 102 |
|
| 103 |
def test_retry_other(self) -> None: |
| 104 |
"""If an unexpected error is raised, should retry other times""" |
| 105 |
other_error = SSLError() |
| 106 |
retry = Retry(connect=1) |
| 107 |
retry = retry.increment(error=other_error) |
| 108 |
retry = retry.increment(error=other_error) |
| 109 |
assert not retry.is_exhausted() |
| 110 |
|
| 111 |
retry = Retry(other=1) |
| 112 |
retry = retry.increment(error=other_error) |
| 113 |
with pytest.raises(MaxRetryError) as e: |
| 114 |
retry.increment(error=other_error) |
| 115 |
assert e.value.reason == other_error |
| 116 |
|
| 117 |
def test_retry_read_zero(self) -> None: |
| 118 |
"""No second chances on read timeouts, by default""" |
| 119 |
error = ReadTimeoutError(DUMMY_POOL, "/", "read timed out") |
| 120 |
retry = Retry(read=0) |
| 121 |
with pytest.raises(MaxRetryError) as e: |
| 122 |
retry.increment(method="GET", error=error) |
| 123 |
assert e.value.reason == error |
| 124 |
|
| 125 |
def test_status_counter(self) -> None: |
| 126 |
resp = HTTPResponse(status=400) |
| 127 |
retry = Retry(status=2) |
| 128 |
retry = retry.increment(response=resp) |
| 129 |
retry = retry.increment(response=resp) |
| 130 |
msg = ResponseError.SPECIFIC_ERROR.format(status_code=400) |
| 131 |
with pytest.raises(MaxRetryError, match=msg): |
| 132 |
retry.increment(response=resp) |
| 133 |
|
| 134 |
def test_backoff(self) -> None: |
| 135 |
"""Backoff is computed correctly""" |
| 136 |
max_backoff = Retry.DEFAULT_BACKOFF_MAX |
| 137 |
|
| 138 |
retry = Retry(total=100, backoff_factor=0.2) |
| 139 |
assert retry.get_backoff_time() == 0 # First request |
| 140 |
|
| 141 |
retry = retry.increment(method="GET") |
| 142 |
assert retry.get_backoff_time() == 0 # First retry |
| 143 |
|
| 144 |
retry = retry.increment(method="GET") |
| 145 |
assert retry.backoff_factor == 0.2 |
| 146 |
assert retry.total == 98 |
| 147 |
assert retry.get_backoff_time() == 0.4 # Start backoff |
| 148 |
|
| 149 |
retry = retry.increment(method="GET") |
| 150 |
assert retry.get_backoff_time() == 0.8 |
| 151 |
|
| 152 |
retry = retry.increment(method="GET") |
| 153 |
assert retry.get_backoff_time() == 1.6 |
| 154 |
|
| 155 |
for _ in range(10): |
| 156 |
retry = retry.increment(method="GET") |
| 157 |
|
| 158 |
assert retry.get_backoff_time() == max_backoff |
| 159 |
|
| 160 |
def test_configurable_backoff_max(self) -> None: |
| 161 |
"""Configurable backoff is computed correctly""" |
| 162 |
max_backoff = 1 |
| 163 |
|
| 164 |
retry = Retry(total=100, backoff_factor=0.2, backoff_max=max_backoff) |
| 165 |
assert retry.get_backoff_time() == 0 # First request |
| 166 |
|
| 167 |
retry = retry.increment(method="GET") |
| 168 |
assert retry.get_backoff_time() == 0 # First retry |
| 169 |
|
| 170 |
retry = retry.increment(method="GET") |
| 171 |
assert retry.backoff_factor == 0.2 |
| 172 |
assert retry.total == 98 |
| 173 |
assert retry.get_backoff_time() == 0.4 # Start backoff |
| 174 |
|
| 175 |
retry = retry.increment(method="GET") |
| 176 |
assert retry.get_backoff_time() == 0.8 |
| 177 |
|
| 178 |
retry = retry.increment(method="GET") |
| 179 |
assert retry.get_backoff_time() == max_backoff |
| 180 |
|
| 181 |
retry = retry.increment(method="GET") |
| 182 |
assert retry.get_backoff_time() == max_backoff |
| 183 |
|
| 184 |
def test_configurable_retry_after_max(self) -> None: |
| 185 |
"""Configurable retry after is computed correctly""" |
| 186 |
max_retry_after = Retry.DEFAULT_RETRY_AFTER_MAX |
| 187 |
|
| 188 |
retry = Retry() |
| 189 |
assert retry.parse_retry_after(str(max_retry_after)) == max_retry_after |
| 190 |
assert retry.parse_retry_after(str(max_retry_after + 1)) == max_retry_after |
| 191 |
|
| 192 |
retry = Retry(retry_after_max=1) |
| 193 |
assert retry.parse_retry_after(str(1)) == 1 |
| 194 |
assert retry.parse_retry_after(str(2)) == 1 |
| 195 |
|
| 196 |
def test_backoff_jitter(self) -> None: |
| 197 |
"""Backoff with jitter is computed correctly""" |
| 198 |
max_backoff = 1 |
| 199 |
jitter = 0.4 |
| 200 |
retry = Retry( |
| 201 |
total=100, |
| 202 |
backoff_factor=0.2, |
| 203 |
backoff_max=max_backoff, |
| 204 |
backoff_jitter=jitter, |
| 205 |
) |
| 206 |
assert retry.get_backoff_time() == 0 # First request |
| 207 |
|
| 208 |
retry = retry.increment(method="GET") |
| 209 |
assert retry.get_backoff_time() == 0 # First retry |
| 210 |
|
| 211 |
retry = retry.increment(method="GET") |
| 212 |
assert retry.backoff_factor == 0.2 |
| 213 |
assert retry.total == 98 |
| 214 |
assert 0.4 <= retry.get_backoff_time() <= 0.8 # Start backoff |
| 215 |
|
| 216 |
retry = retry.increment(method="GET") |
| 217 |
assert 0.8 <= retry.get_backoff_time() <= max_backoff |
| 218 |
|
| 219 |
retry = retry.increment(method="GET") |
| 220 |
assert retry.get_backoff_time() == max_backoff |
| 221 |
|
| 222 |
retry = retry.increment(method="GET") |
| 223 |
assert retry.get_backoff_time() == max_backoff |
| 224 |
|
| 225 |
def test_zero_backoff(self) -> None: |
| 226 |
retry = Retry() |
| 227 |
assert retry.get_backoff_time() == 0 |
| 228 |
retry = retry.increment(method="GET") |
| 229 |
retry = retry.increment(method="GET") |
| 230 |
assert retry.get_backoff_time() == 0 |
| 231 |
|
| 232 |
def test_backoff_reset_after_redirect(self) -> None: |
| 233 |
retry = Retry(total=100, redirect=5, backoff_factor=0.2) |
| 234 |
retry = retry.increment(method="GET") |
| 235 |
retry = retry.increment(method="GET") |
| 236 |
assert retry.get_backoff_time() == 0.4 |
| 237 |
redirect_response = HTTPResponse(status=302, headers={"location": "test"}) |
| 238 |
retry = retry.increment(method="GET", response=redirect_response) |
| 239 |
assert retry.get_backoff_time() == 0 |
| 240 |
retry = retry.increment(method="GET") |
| 241 |
retry = retry.increment(method="GET") |
| 242 |
assert retry.get_backoff_time() == 0.4 |
| 243 |
|
| 244 |
def test_sleep(self) -> None: |
| 245 |
# sleep a very small amount of time so our code coverage is happy |
| 246 |
retry = Retry(backoff_factor=0.0001) |
| 247 |
retry = retry.increment(method="GET") |
| 248 |
retry = retry.increment(method="GET") |
| 249 |
retry.sleep() |
| 250 |
|
| 251 |
def test_status_forcelist(self) -> None: |
| 252 |
retry = Retry(status_forcelist=range(500, 600)) |
| 253 |
assert not retry.is_retry("GET", status_code=200) |
| 254 |
assert not retry.is_retry("GET", status_code=400) |
| 255 |
assert retry.is_retry("GET", status_code=500) |
| 256 |
|
| 257 |
retry = Retry(total=1, status_forcelist=[418]) |
| 258 |
assert not retry.is_retry("GET", status_code=400) |
| 259 |
assert retry.is_retry("GET", status_code=418) |
| 260 |
|
| 261 |
# String status codes are not matched. |
| 262 |
retry = Retry(total=1, status_forcelist=["418"]) # type: ignore[list-item] |
| 263 |
assert not retry.is_retry("GET", status_code=418) |
| 264 |
|
| 265 |
def test_allowed_methods_with_status_forcelist(self) -> None: |
| 266 |
# None allowed_methods means to retry on any method. |
| 267 |
retry = Retry(status_forcelist=[500], allowed_methods=None) |
| 268 |
assert retry.is_retry("GET", status_code=500) |
| 269 |
assert retry.is_retry("POST", status_code=500) |
| 270 |
|
| 271 |
# Criteria of allowed_methods and status_forcelist are ANDed. |
| 272 |
retry = Retry(status_forcelist=[500], allowed_methods=["POST"]) |
| 273 |
assert not retry.is_retry("GET", status_code=500) |
| 274 |
assert retry.is_retry("POST", status_code=500) |
| 275 |
|
| 276 |
def test_false_allowed_methods(self) -> None: |
| 277 |
# False is also accepted to mean retry on any method, since 1.26.x |
| 278 |
retry = Retry(status_forcelist=[500], allowed_methods=False) # type: ignore[arg-type] |
| 279 |
assert retry.is_retry("POST", status_code=500) |
| 280 |
|
| 281 |
def test_empty_allowed_methods(self) -> None: |
| 282 |
with pytest.warns(FutureWarning) as records: |
| 283 |
retry = Retry(status_forcelist=[500], allowed_methods=[]) |
| 284 |
assert retry.is_retry("GET", status_code=500) |
| 285 |
msg = ( |
| 286 |
"Using an empty collection for 'allowed_methods' option to retry " |
| 287 |
"on any verb is deprecated and will skip retries for all verbs " |
| 288 |
"in urllib3 v3.0. Instead use Retry(..., allowed_methods=None)." |
| 289 |
) |
| 290 |
record = records[0] |
| 291 |
assert isinstance(record.message, Warning) |
| 292 |
assert record.message.args[0] == msg |
| 293 |
|
| 294 |
def test_exhausted(self) -> None: |
| 295 |
assert not Retry(0).is_exhausted() |
| 296 |
assert Retry(-1).is_exhausted() |
| 297 |
assert Retry(1).increment(method="GET").total == 0 |
| 298 |
|
| 299 |
@pytest.mark.parametrize("total", [-1, 0]) |
| 300 |
def test_disabled(self, total: int) -> None: |
| 301 |
with pytest.raises(MaxRetryError): |
| 302 |
Retry(total).increment(method="GET") |
| 303 |
|
| 304 |
def test_error_message(self) -> None: |
| 305 |
retry = Retry(total=0) |
| 306 |
with pytest.raises(MaxRetryError, match="read timed out") as e: |
| 307 |
retry = retry.increment( |
| 308 |
method="GET", error=ReadTimeoutError(DUMMY_POOL, "/", "read timed out") |
| 309 |
) |
| 310 |
assert "Caused by redirect" not in str(e.value) |
| 311 |
|
| 312 |
retry = Retry(total=1) |
| 313 |
retry = retry.increment("POST", "/") |
| 314 |
with pytest.raises(MaxRetryError, match=ResponseError.GENERIC_ERROR) as e: |
| 315 |
retry = retry.increment("POST", "/") |
| 316 |
assert "Caused by redirect" not in str(e.value) |
| 317 |
assert isinstance(e.value.reason, ResponseError) |
| 318 |
|
| 319 |
retry = Retry(total=1) |
| 320 |
response = HTTPResponse(status=500) |
| 321 |
msg = ResponseError.SPECIFIC_ERROR.format(status_code=500) |
| 322 |
retry = retry.increment("POST", "/", response=response) |
| 323 |
with pytest.raises(MaxRetryError, match=msg) as e: |
| 324 |
retry = retry.increment("POST", "/", response=response) |
| 325 |
assert "Caused by redirect" not in str(e.value) |
| 326 |
|
| 327 |
retry = Retry(connect=1) |
| 328 |
retry = retry.increment(error=ConnectTimeoutError("conntimeout")) |
| 329 |
with pytest.raises(MaxRetryError, match="conntimeout") as e: |
| 330 |
retry = retry.increment(error=ConnectTimeoutError("conntimeout")) |
| 331 |
assert "Caused by redirect" not in str(e.value) |
| 332 |
|
| 333 |
def test_history(self) -> None: |
| 334 |
retry = Retry(total=10, allowed_methods=frozenset(["GET", "POST"])) |
| 335 |
assert retry.history == tuple() |
| 336 |
connection_error = ConnectTimeoutError("conntimeout") |
| 337 |
retry = retry.increment("GET", "/test1", None, connection_error) |
| 338 |
test_history1 = (RequestHistory("GET", "/test1", connection_error, None, None),) |
| 339 |
assert retry.history == test_history1 |
| 340 |
|
| 341 |
read_error = ReadTimeoutError(DUMMY_POOL, "/test2", "read timed out") |
| 342 |
retry = retry.increment("POST", "/test2", None, read_error) |
| 343 |
test_history2 = ( |
| 344 |
RequestHistory("GET", "/test1", connection_error, None, None), |
| 345 |
RequestHistory("POST", "/test2", read_error, None, None), |
| 346 |
) |
| 347 |
assert retry.history == test_history2 |
| 348 |
|
| 349 |
response = HTTPResponse(status=500) |
| 350 |
retry = retry.increment("GET", "/test3", response, None) |
| 351 |
test_history3 = ( |
| 352 |
RequestHistory("GET", "/test1", connection_error, None, None), |
| 353 |
RequestHistory("POST", "/test2", read_error, None, None), |
| 354 |
RequestHistory("GET", "/test3", None, 500, None), |
| 355 |
) |
| 356 |
assert retry.history == test_history3 |
| 357 |
|
| 358 |
def test_retry_method_not_allowed(self) -> None: |
| 359 |
error = ReadTimeoutError(DUMMY_POOL, "/", "read timed out") |
| 360 |
retry = Retry() |
| 361 |
with pytest.raises(ReadTimeoutError): |
| 362 |
retry.increment(method="POST", error=error) |
| 363 |
|
| 364 |
def test_retry_default_remove_headers_on_redirect(self) -> None: |
| 365 |
retry = Retry() |
| 366 |
|
| 367 |
assert retry.remove_headers_on_redirect == { |
| 368 |
"authorization", |
| 369 |
"proxy-authorization", |
| 370 |
"cookie", |
| 371 |
} |
| 372 |
|
| 373 |
def test_retry_set_remove_headers_on_redirect(self) -> None: |
| 374 |
retry = Retry(remove_headers_on_redirect=["X-API-Secret"]) |
| 375 |
|
| 376 |
assert retry.remove_headers_on_redirect == {"x-api-secret"} |
| 377 |
|
| 378 |
@pytest.mark.parametrize("value", ["-1", "+1", "1.0", "\xb2"]) # \xb2 = ^2 |
| 379 |
def test_parse_retry_after_invalid(self, value: str) -> None: |
| 380 |
retry = Retry() |
| 381 |
with pytest.raises(InvalidHeader): |
| 382 |
retry.parse_retry_after(value) |
| 383 |
|
| 384 |
@pytest.mark.parametrize( |
| 385 |
"value, expected", [("0", 0), ("1000", 1000), ("\t42 ", 42)] |
| 386 |
) |
| 387 |
def test_parse_retry_after(self, value: str, expected: int) -> None: |
| 388 |
retry = Retry() |
| 389 |
assert retry.parse_retry_after(value) == expected |
| 390 |
|
| 391 |
@pytest.mark.parametrize("respect_retry_after_header", [True, False]) |
| 392 |
def test_respect_retry_after_header_propagated( |
| 393 |
self, respect_retry_after_header: bool |
| 394 |
) -> None: |
| 395 |
retry = Retry(respect_retry_after_header=respect_retry_after_header) |
| 396 |
new_retry = retry.new() |
| 397 |
assert new_retry.respect_retry_after_header == respect_retry_after_header |
| 398 |
|
| 399 |
@pytest.mark.parametrize( |
| 400 |
"retry_after_header,respect_retry_after_header,sleep_duration", |
| 401 |
[ |
| 402 |
("3600", True, 3600), |
| 403 |
("3600", False, None), |
| 404 |
# Will sleep due to header is 1 hour in future |
| 405 |
("Mon, 3 Jun 2019 12:00:00 UTC", True, 3600), |
| 406 |
# Won't sleep due to not respecting header |
| 407 |
("Mon, 3 Jun 2019 12:00:00 UTC", False, None), |
| 408 |
# Won't sleep due to current time reached |
| 409 |
("Mon, 3 Jun 2019 11:00:00 UTC", True, None), |
| 410 |
# Won't sleep due to current time reached + not respecting header |
| 411 |
("Mon, 3 Jun 2019 11:00:00 UTC", False, None), |
| 412 |
# Handle all the formats in RFC 7231 Section 7.1.1.1 |
| 413 |
("Mon, 03 Jun 2019 11:30:12 GMT", True, 1812), |
| 414 |
("Monday, 03-Jun-19 11:30:12 GMT", True, 1812), |
| 415 |
# Assume that datetimes without a timezone are in UTC per RFC 7231 |
| 416 |
("Mon Jun 3 11:30:12 2019", True, 1812), |
| 417 |
], |
| 418 |
) |
| 419 |
@pytest.mark.parametrize( |
| 420 |
"stub_timezone", |
| 421 |
[ |
| 422 |
"UTC", |
| 423 |
"Asia/Jerusalem", |
| 424 |
None, |
| 425 |
], |
| 426 |
indirect=True, |
| 427 |
) |
| 428 |
@pytest.mark.usefixtures("stub_timezone") |
| 429 |
def test_respect_retry_after_header_sleep( |
| 430 |
self, |
| 431 |
retry_after_header: str, |
| 432 |
respect_retry_after_header: bool, |
| 433 |
sleep_duration: int | None, |
| 434 |
) -> None: |
| 435 |
retry = Retry(respect_retry_after_header=respect_retry_after_header) |
| 436 |
|
| 437 |
with ( |
| 438 |
mock.patch( |
| 439 |
"time.time", |
| 440 |
return_value=datetime.datetime( |
| 441 |
2019, 6, 3, 11, tzinfo=datetime.timezone.utc |
| 442 |
).timestamp(), |
| 443 |
), |
| 444 |
mock.patch("time.sleep") as sleep_mock, |
| 445 |
): |
| 446 |
# for the default behavior, it must be in RETRY_AFTER_STATUS_CODES |
| 447 |
response = HTTPResponse( |
| 448 |
status=503, headers={"Retry-After": retry_after_header} |
| 449 |
) |
| 450 |
|
| 451 |
retry.sleep(response) |
| 452 |
|
| 453 |
# The expected behavior is that we'll only sleep if respecting |
| 454 |
# this header (since we won't have any backoff sleep attempts) |
| 455 |
if respect_retry_after_header and sleep_duration is not None: |
| 456 |
sleep_mock.assert_called_with(sleep_duration) |
| 457 |
else: |
| 458 |
sleep_mock.assert_not_called() |