Debian Codegraph @

tests/utils/test_http_client.py

raw symbols SCIP
1 # This file was auto-generated by Fern from our API Definition.
2
3 from typing import Any, Dict, Tuple, cast
4 from unittest.mock import AsyncMock, MagicMock, patch
5
6 import httpx
7 import pytest
8
9 from auth0.management.core.http_client import (
10 AsyncHttpClient,
11 HttpClient,
12 _build_url,
13 _should_retry,
14 get_request_body,
15 remove_none_from_dict,
16 )
17 from auth0.management.core.request_options import RequestOptions
18
19
20 # Stub clients for testing HttpClient and AsyncHttpClient
21 class _DummySyncClient:
22 """A minimal stub for httpx.Client that records request arguments."""
23
24 def __init__(self) -> None:
25 self.last_request_kwargs: Dict[str, Any] = {}
26
27 def request(self, **kwargs: Any) -> "_DummyResponse":
28 self.last_request_kwargs = kwargs
29 return _DummyResponse()
30
31
32 class _DummyAsyncClient:
33 """A minimal stub for httpx.AsyncClient that records request arguments."""
34
35 def __init__(self) -> None:
36 self.last_request_kwargs: Dict[str, Any] = {}
37
38 async def request(self, **kwargs: Any) -> "_DummyResponse":
39 self.last_request_kwargs = kwargs
40 return _DummyResponse()
41
42
43 class _DummyResponse:
44 """A minimal stub for httpx.Response."""
45
46 status_code = 200
47 headers: Dict[str, str] = {}
48
49
50 def get_request_options() -> RequestOptions:
51 return {"additional_body_parameters": {"see you": "later"}}
52
53
54 def get_request_options_with_none() -> RequestOptions:
55 return {"additional_body_parameters": {"see you": "later", "optional": None}}
56
57
58 def test_get_json_request_body() -> None:
59 json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None)
60 assert json_body == {"hello": "world"}
61 assert data_body is None
62
63 json_body_extras, data_body_extras = get_request_body(
64 json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None
65 )
66
67 assert json_body_extras == {"goodbye": "world", "see you": "later"}
68 assert data_body_extras is None
69
70
71 def test_get_files_request_body() -> None:
72 json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None)
73 assert data_body == {"hello": "world"}
74 assert json_body is None
75
76 json_body_extras, data_body_extras = get_request_body(
77 json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None
78 )
79
80 assert data_body_extras == {"goodbye": "world", "see you": "later"}
81 assert json_body_extras is None
82
83
84 def test_get_none_request_body() -> None:
85 json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None)
86 assert data_body is None
87 assert json_body is None
88
89 json_body_extras, data_body_extras = get_request_body(
90 json=None, data=None, request_options=get_request_options(), omit=None
91 )
92
93 assert json_body_extras == {"see you": "later"}
94 assert data_body_extras is None
95
96
97 def test_get_empty_json_request_body() -> None:
98 """Test that implicit empty bodies (json=None) are collapsed to None."""
99 unrelated_request_options: RequestOptions = {"max_retries": 3}
100 json_body, data_body = get_request_body(json=None, data=None, request_options=unrelated_request_options, omit=None)
101 assert json_body is None
102 assert data_body is None
103
104
105 def test_explicit_empty_json_body_is_preserved() -> None:
106 """Test that explicit empty bodies (json={}) are preserved and sent as {}.
107
108 This is important for endpoints where the request body is required but all
109 fields are optional. The server expects valid JSON ({}) not an empty body.
110 """
111 unrelated_request_options: RequestOptions = {"max_retries": 3}
112
113 # Explicit json={} should be preserved
114 json_body, data_body = get_request_body(json={}, data=None, request_options=unrelated_request_options, omit=None)
115 assert json_body == {}
116 assert data_body is None
117
118 # Explicit data={} should also be preserved
119 json_body2, data_body2 = get_request_body(json=None, data={}, request_options=unrelated_request_options, omit=None)
120 assert json_body2 is None
121 assert data_body2 == {}
122
123
124 def test_json_body_preserves_none_values() -> None:
125 """Test that JSON bodies preserve None values (they become JSON null)."""
126 json_body, data_body = get_request_body(
127 json={"hello": "world", "optional": None}, data=None, request_options=None, omit=None
128 )
129 # JSON bodies should preserve None values
130 assert json_body == {"hello": "world", "optional": None}
131 assert data_body is None
132
133
134 def test_data_body_preserves_none_values_without_multipart() -> None:
135 """Test that data bodies preserve None values when not using multipart.
136
137 The filtering of None values happens in HttpClient.request/stream methods,
138 not in get_request_body. This test verifies get_request_body doesn't filter None.
139 """
140 json_body, data_body = get_request_body(
141 json=None, data={"hello": "world", "optional": None}, request_options=None, omit=None
142 )
143 # get_request_body should preserve None values in data body
144 # The filtering happens later in HttpClient.request when multipart is detected
145 assert data_body == {"hello": "world", "optional": None}
146 assert json_body is None
147
148
149 def test_remove_none_from_dict_filters_none_values() -> None:
150 """Test that remove_none_from_dict correctly filters out None values."""
151 original = {"hello": "world", "optional": None, "another": "value", "also_none": None}
152 filtered = remove_none_from_dict(original)
153 assert filtered == {"hello": "world", "another": "value"}
154 # Original should not be modified
155 assert original == {"hello": "world", "optional": None, "another": "value", "also_none": None}
156
157
158 def test_remove_none_from_dict_empty_dict() -> None:
159 """Test that remove_none_from_dict handles empty dict."""
160 assert remove_none_from_dict({}) == {}
161
162
163 def test_remove_none_from_dict_all_none() -> None:
164 """Test that remove_none_from_dict handles dict with all None values."""
165 assert remove_none_from_dict({"a": None, "b": None}) == {}
166
167
168 def test_http_client_does_not_pass_empty_params_list() -> None:
169 """Test that HttpClient passes params=None when params are empty.
170
171 This prevents httpx from stripping existing query parameters from the URL,
172 which happens when params=[] or params={} is passed.
173 """
174 dummy_client = _DummySyncClient()
175 http_client = HttpClient(
176 httpx_client=dummy_client, # type: ignore[arg-type]
177 base_timeout=lambda: None,
178 base_headers=lambda: {},
179 base_url=lambda: "https://example.com",
180 )
181
182 # Use a path with query params (e.g., pagination cursor URL)
183 http_client.request(
184 path="resource?after=123",
185 method="GET",
186 params=None,
187 request_options=None,
188 )
189
190 # We care that httpx receives params=None, not [] or {}
191 assert "params" in dummy_client.last_request_kwargs
192 assert dummy_client.last_request_kwargs["params"] is None
193
194 # Verify the query string in the URL is preserved
195 url = str(dummy_client.last_request_kwargs["url"])
196 assert "after=123" in url, f"Expected query param 'after=123' in URL, got: {url}"
197
198
199 def test_http_client_passes_encoded_params_when_present() -> None:
200 """Test that HttpClient passes encoded params when params are provided."""
201 dummy_client = _DummySyncClient()
202 http_client = HttpClient(
203 httpx_client=dummy_client, # type: ignore[arg-type]
204 base_timeout=lambda: None,
205 base_headers=lambda: {},
206 base_url=lambda: "https://example.com/resource",
207 )
208
209 http_client.request(
210 path="",
211 method="GET",
212 params={"after": "456"},
213 request_options=None,
214 )
215
216 params = dummy_client.last_request_kwargs["params"]
217 # For a simple dict, encode_query should give a single (key, value) tuple
218 assert params == [("after", "456")]
219
220
221 @pytest.mark.asyncio
222 async def test_async_http_client_does_not_pass_empty_params_list() -> None:
223 """Test that AsyncHttpClient passes params=None when params are empty.
224
225 This prevents httpx from stripping existing query parameters from the URL,
226 which happens when params=[] or params={} is passed.
227 """
228 dummy_client = _DummyAsyncClient()
229 http_client = AsyncHttpClient(
230 httpx_client=dummy_client, # type: ignore[arg-type]
231 base_timeout=lambda: None,
232 base_headers=lambda: {},
233 base_url=lambda: "https://example.com",
234 async_base_headers=None,
235 )
236
237 # Use a path with query params (e.g., pagination cursor URL)
238 await http_client.request(
239 path="resource?after=123",
240 method="GET",
241 params=None,
242 request_options=None,
243 )
244
245 # We care that httpx receives params=None, not [] or {}
246 assert "params" in dummy_client.last_request_kwargs
247 assert dummy_client.last_request_kwargs["params"] is None
248
249 # Verify the query string in the URL is preserved
250 url = str(dummy_client.last_request_kwargs["url"])
251 assert "after=123" in url, f"Expected query param 'after=123' in URL, got: {url}"
252
253
254 @pytest.mark.asyncio
255 async def test_async_http_client_passes_encoded_params_when_present() -> None:
256 """Test that AsyncHttpClient passes encoded params when params are provided."""
257 dummy_client = _DummyAsyncClient()
258 http_client = AsyncHttpClient(
259 httpx_client=dummy_client, # type: ignore[arg-type]
260 base_timeout=lambda: None,
261 base_headers=lambda: {},
262 base_url=lambda: "https://example.com/resource",
263 async_base_headers=None,
264 )
265
266 await http_client.request(
267 path="",
268 method="GET",
269 params={"after": "456"},
270 request_options=None,
271 )
272
273 params = dummy_client.last_request_kwargs["params"]
274 # For a simple dict, encode_query should give a single (key, value) tuple
275 assert params == [("after", "456")]
276
277
278 def test_basic_url_joining() -> None:
279 """Test basic URL joining with a simple base URL and path."""
280 result = _build_url("https://api.example.com", "/users")
281 assert result == "https://api.example.com/users"
282
283
284 def test_basic_url_joining_trailing_slash() -> None:
285 """Test basic URL joining with a simple base URL and path."""
286 result = _build_url("https://api.example.com/", "/users")
287 assert result == "https://api.example.com/users"
288
289
290 def test_preserves_base_url_path_prefix() -> None:
291 """Test that path prefixes in base URL are preserved.
292
293 This is the critical bug fix - urllib.parse.urljoin() would strip
294 the path prefix when the path starts with '/'.
295 """
296 result = _build_url("https://cloud.example.com/org/tenant/api", "/users")
297 assert result == "https://cloud.example.com/org/tenant/api/users"
298
299
300 def test_preserves_base_url_path_prefix_trailing_slash() -> None:
301 """Test that path prefixes in base URL are preserved."""
302 result = _build_url("https://cloud.example.com/org/tenant/api/", "/users")
303 assert result == "https://cloud.example.com/org/tenant/api/users"
304
305
306 # ---------------------------------------------------------------------------
307 # Connection error retry tests
308 # ---------------------------------------------------------------------------
309
310
311 def _make_sync_http_client(mock_client: Any) -> HttpClient:
312 return HttpClient(
313 httpx_client=mock_client, # type: ignore[arg-type]
314 base_timeout=lambda: None,
315 base_headers=lambda: {},
316 base_url=lambda: "https://example.com",
317 )
318
319
320 def _make_async_http_client(mock_client: Any) -> AsyncHttpClient:
321 return AsyncHttpClient(
322 httpx_client=mock_client, # type: ignore[arg-type]
323 base_timeout=lambda: None,
324 base_headers=lambda: {},
325 base_url=lambda: "https://example.com",
326 async_base_headers=None,
327 )
328
329
330 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
331 def test_sync_retries_on_connect_error(mock_sleep: MagicMock) -> None:
332 """Sync: connection error retries on httpx.ConnectError."""
333 mock_client = MagicMock()
334 mock_client.request.side_effect = [
335 httpx.ConnectError("connection failed"),
336 _DummyResponse(),
337 ]
338 http_client = _make_sync_http_client(mock_client)
339
340 response = http_client.request(path="/test", method="GET")
341
342 assert response.status_code == 200
343 assert mock_client.request.call_count == 2
344 mock_sleep.assert_called_once()
345
346
347 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
348 def test_sync_retries_on_remote_protocol_error(mock_sleep: MagicMock) -> None:
349 """Sync: connection error retries on httpx.RemoteProtocolError."""
350 mock_client = MagicMock()
351 mock_client.request.side_effect = [
352 httpx.RemoteProtocolError("Remote end closed connection without response"),
353 _DummyResponse(),
354 ]
355 http_client = _make_sync_http_client(mock_client)
356
357 response = http_client.request(path="/test", method="GET")
358
359 assert response.status_code == 200
360 assert mock_client.request.call_count == 2
361 mock_sleep.assert_called_once()
362
363
364 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
365 def test_sync_connection_error_exhausts_retries(mock_sleep: MagicMock) -> None:
366 """Sync: connection error exhausts retries then raises."""
367 mock_client = MagicMock()
368 mock_client.request.side_effect = httpx.ConnectError("connection failed")
369 http_client = _make_sync_http_client(mock_client)
370
371 with pytest.raises(httpx.ConnectError):
372 http_client.request(
373 path="/test",
374 method="GET",
375 request_options={"max_retries": 2},
376 )
377
378 # 1 initial + 2 retries = 3 total attempts
379 assert mock_client.request.call_count == 3
380 assert mock_sleep.call_count == 2
381
382
383 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
384 def test_sync_connection_error_respects_max_retries_zero(mock_sleep: MagicMock) -> None:
385 """Sync: connection error respects max_retries=0."""
386 mock_client = MagicMock()
387 mock_client.request.side_effect = httpx.ConnectError("connection failed")
388 http_client = _make_sync_http_client(mock_client)
389
390 with pytest.raises(httpx.ConnectError):
391 http_client.request(
392 path="/test",
393 method="GET",
394 request_options={"max_retries": 0},
395 )
396
397 # No retries, just the initial attempt
398 assert mock_client.request.call_count == 1
399 mock_sleep.assert_not_called()
400
401
402 @pytest.mark.asyncio
403 @patch("auth0.management.core.http_client.asyncio.sleep", new_callable=AsyncMock)
404 async def test_async_retries_on_connect_error(mock_sleep: AsyncMock) -> None:
405 """Async: connection error retries on httpx.ConnectError."""
406 mock_client = MagicMock()
407 mock_client.request = AsyncMock(
408 side_effect=[
409 httpx.ConnectError("connection failed"),
410 _DummyResponse(),
411 ]
412 )
413 http_client = _make_async_http_client(mock_client)
414
415 response = await http_client.request(path="/test", method="GET")
416
417 assert response.status_code == 200
418 assert mock_client.request.call_count == 2
419 mock_sleep.assert_called_once()
420
421
422 @pytest.mark.asyncio
423 @patch("auth0.management.core.http_client.asyncio.sleep", new_callable=AsyncMock)
424 async def test_async_retries_on_remote_protocol_error(mock_sleep: AsyncMock) -> None:
425 """Async: connection error retries on httpx.RemoteProtocolError."""
426 mock_client = MagicMock()
427 mock_client.request = AsyncMock(
428 side_effect=[
429 httpx.RemoteProtocolError("Remote end closed connection without response"),
430 _DummyResponse(),
431 ]
432 )
433 http_client = _make_async_http_client(mock_client)
434
435 response = await http_client.request(path="/test", method="GET")
436
437 assert response.status_code == 200
438 assert mock_client.request.call_count == 2
439 mock_sleep.assert_called_once()
440
441
442 @pytest.mark.asyncio
443 @patch("auth0.management.core.http_client.asyncio.sleep", new_callable=AsyncMock)
444 async def test_async_connection_error_exhausts_retries(mock_sleep: AsyncMock) -> None:
445 """Async: connection error exhausts retries then raises."""
446 mock_client = MagicMock()
447 mock_client.request = AsyncMock(side_effect=httpx.ConnectError("connection failed"))
448 http_client = _make_async_http_client(mock_client)
449
450 with pytest.raises(httpx.ConnectError):
451 await http_client.request(
452 path="/test",
453 method="GET",
454 request_options={"max_retries": 2},
455 )
456
457 # 1 initial + 2 retries = 3 total attempts
458 assert mock_client.request.call_count == 3
459 assert mock_sleep.call_count == 2
460
461
462 # ---------------------------------------------------------------------------
463 # base_max_retries constructor parameter tests
464 # ---------------------------------------------------------------------------
465
466
467 def test_sync_http_client_default_base_max_retries() -> None:
468 """HttpClient defaults to base_max_retries=2."""
469 http_client = HttpClient(
470 httpx_client=MagicMock(), # type: ignore[arg-type]
471 base_timeout=lambda: None,
472 base_headers=lambda: {},
473 )
474 assert http_client.base_max_retries == 2
475
476
477 def test_async_http_client_default_base_max_retries() -> None:
478 """AsyncHttpClient defaults to base_max_retries=2."""
479 http_client = AsyncHttpClient(
480 httpx_client=MagicMock(), # type: ignore[arg-type]
481 base_timeout=lambda: None,
482 base_headers=lambda: {},
483 )
484 assert http_client.base_max_retries == 2
485
486
487 def test_sync_http_client_custom_base_max_retries() -> None:
488 """HttpClient accepts a custom base_max_retries value."""
489 http_client = HttpClient(
490 httpx_client=MagicMock(), # type: ignore[arg-type]
491 base_timeout=lambda: None,
492 base_headers=lambda: {},
493 base_max_retries=5,
494 )
495 assert http_client.base_max_retries == 5
496
497
498 def test_async_http_client_custom_base_max_retries() -> None:
499 """AsyncHttpClient accepts a custom base_max_retries value."""
500 http_client = AsyncHttpClient(
501 httpx_client=MagicMock(), # type: ignore[arg-type]
502 base_timeout=lambda: None,
503 base_headers=lambda: {},
504 base_max_retries=5,
505 )
506 assert http_client.base_max_retries == 5
507
508
509 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
510 def test_sync_base_max_retries_zero_disables_retries(mock_sleep: MagicMock) -> None:
511 """Sync: base_max_retries=0 disables retries when no request_options override."""
512 mock_client = MagicMock()
513 mock_client.request.side_effect = httpx.ConnectError("connection failed")
514 http_client = HttpClient(
515 httpx_client=mock_client, # type: ignore[arg-type]
516 base_timeout=lambda: None,
517 base_headers=lambda: {},
518 base_url=lambda: "https://example.com",
519 base_max_retries=0,
520 )
521
522 with pytest.raises(httpx.ConnectError):
523 http_client.request(path="/test", method="GET")
524
525 # No retries, just the initial attempt
526 assert mock_client.request.call_count == 1
527 mock_sleep.assert_not_called()
528
529
530 @pytest.mark.asyncio
531 @patch("auth0.management.core.http_client.asyncio.sleep", new_callable=AsyncMock)
532 async def test_async_base_max_retries_zero_disables_retries(mock_sleep: AsyncMock) -> None:
533 """Async: base_max_retries=0 disables retries when no request_options override."""
534 mock_client = MagicMock()
535 mock_client.request = AsyncMock(side_effect=httpx.ConnectError("connection failed"))
536 http_client = AsyncHttpClient(
537 httpx_client=mock_client, # type: ignore[arg-type]
538 base_timeout=lambda: None,
539 base_headers=lambda: {},
540 base_url=lambda: "https://example.com",
541 base_max_retries=0,
542 )
543
544 with pytest.raises(httpx.ConnectError):
545 await http_client.request(path="/test", method="GET")
546
547 # No retries, just the initial attempt
548 assert mock_client.request.call_count == 1
549 mock_sleep.assert_not_called()
550
551
552 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
553 def test_sync_request_options_override_base_max_retries(mock_sleep: MagicMock) -> None:
554 """Sync: request_options max_retries overrides base_max_retries."""
555 mock_client = MagicMock()
556 mock_client.request.side_effect = [
557 httpx.ConnectError("connection failed"),
558 httpx.ConnectError("connection failed"),
559 _DummyResponse(),
560 ]
561 http_client = HttpClient(
562 httpx_client=mock_client, # type: ignore[arg-type]
563 base_timeout=lambda: None,
564 base_headers=lambda: {},
565 base_url=lambda: "https://example.com",
566 base_max_retries=0, # base says no retries
567 )
568
569 # But request_options overrides to allow 2 retries
570 response = http_client.request(
571 path="/test",
572 method="GET",
573 request_options={"max_retries": 2},
574 )
575
576 assert response.status_code == 200
577 # 1 initial + 2 retries = 3 total attempts
578 assert mock_client.request.call_count == 3
579
580
581 @pytest.mark.asyncio
582 @patch("auth0.management.core.http_client.asyncio.sleep", new_callable=AsyncMock)
583 async def test_async_request_options_override_base_max_retries(mock_sleep: AsyncMock) -> None:
584 """Async: request_options max_retries overrides base_max_retries."""
585 mock_client = MagicMock()
586 mock_client.request = AsyncMock(
587 side_effect=[
588 httpx.ConnectError("connection failed"),
589 httpx.ConnectError("connection failed"),
590 _DummyResponse(),
591 ]
592 )
593 http_client = AsyncHttpClient(
594 httpx_client=mock_client, # type: ignore[arg-type]
595 base_timeout=lambda: None,
596 base_headers=lambda: {},
597 base_url=lambda: "https://example.com",
598 base_max_retries=0, # base says no retries
599 )
600
601 # But request_options overrides to allow 2 retries
602 response = await http_client.request(
603 path="/test",
604 method="GET",
605 request_options={"max_retries": 2},
606 )
607
608 assert response.status_code == 200
609 # 1 initial + 2 retries = 3 total attempts
610 assert mock_client.request.call_count == 3
611
612
613 @patch("auth0.management.core.http_client.time.sleep", return_value=None)
614 def test_sync_base_max_retries_used_as_default(mock_sleep: MagicMock) -> None:
615 """Sync: base_max_retries is used when request_options has no max_retries."""
616 mock_client = MagicMock()
617 mock_client.request.side_effect = [
618 httpx.ConnectError("fail"),
619 httpx.ConnectError("fail"),
620 httpx.ConnectError("fail"),
621 _DummyResponse(),
622 ]
623 http_client = HttpClient(
624 httpx_client=mock_client, # type: ignore[arg-type]
625 base_timeout=lambda: None,
626 base_headers=lambda: {},
627 base_url=lambda: "https://example.com",
628 base_max_retries=3,
629 )
630
631 response = http_client.request(path="/test", method="GET")
632
633 assert response.status_code == 200
634 # 1 initial + 3 retries = 4 total attempts
635 assert mock_client.request.call_count == 4
636
637
638 @pytest.mark.asyncio
639 @patch("auth0.management.core.http_client.asyncio.sleep", new_callable=AsyncMock)
640 async def test_async_base_max_retries_used_as_default(mock_sleep: AsyncMock) -> None:
641 """Async: base_max_retries is used when request_options has no max_retries."""
642 mock_client = MagicMock()
643 mock_client.request = AsyncMock(
644 side_effect=[
645 httpx.ConnectError("fail"),
646 httpx.ConnectError("fail"),
647 httpx.ConnectError("fail"),
648 _DummyResponse(),
649 ]
650 )
651 http_client = AsyncHttpClient(
652 httpx_client=mock_client, # type: ignore[arg-type]
653 base_timeout=lambda: None,
654 base_headers=lambda: {},
655 base_url=lambda: "https://example.com",
656 base_max_retries=3,
657 )
658
659 response = await http_client.request(path="/test", method="GET")
660
661 assert response.status_code == 200
662 # 1 initial + 3 retries = 4 total attempts
663 assert mock_client.request.call_count == 4
664
665
666 # ---------------------------------------------------------------------------
667 # _should_retry unit tests
668 # ---------------------------------------------------------------------------
669
670
671 def _make_response(status_code: int) -> httpx.Response:
672 return httpx.Response(status_code=status_code, content=b"")
673
674
675 @pytest.mark.parametrize(
676 "status_code",
677 [408, 409, 429, 500, 501, 502, 503, 504, 599],
678 )
679 def test_should_retry_retryable_status_codes(status_code: int) -> None:
680 """Legacy mode: retries on 408, 409, 429, and all >= 500."""
681 assert _should_retry(_make_response(status_code)) is True
682
683
684 @pytest.mark.parametrize(
685 "status_code",
686 [200, 201, 301, 400, 401, 403, 404],
687 )
688 def test_should_not_retry_non_retryable_status_codes(status_code: int) -> None:
689 assert _should_retry(_make_response(status_code)) is False
690
691
692 def test_should_retry_599_upper_boundary() -> None:
693 """Legacy mode retries on >= 500, which includes 599."""
694 assert _should_retry(_make_response(599)) is True
695
696
697 # ---------------------------------------------------------------------------
698 # RequestOptions timeout resolution tests (timeout / deprecated timeout_in_seconds)
699 # ---------------------------------------------------------------------------
700
701
702 def _sync_client_with_base_timeout(base_timeout: Any) -> Tuple[HttpClient, _DummySyncClient]:
703 dummy_client = _DummySyncClient()
704 http_client = HttpClient(
705 httpx_client=dummy_client, # type: ignore[arg-type]
706 base_timeout=lambda: base_timeout,
707 base_headers=lambda: {},
708 base_url=lambda: "https://example.com",
709 )
710 return http_client, dummy_client
711
712
713 def test_sync_request_options_timeout_used() -> None:
714 """The new `timeout` request option is passed through to httpx (in seconds)."""
715 http_client, dummy_client = _sync_client_with_base_timeout(60)
716 http_client.request(path="/test", method="GET", request_options={"timeout": 30})
717 assert dummy_client.last_request_kwargs["timeout"] == 30
718
719
720 def test_sync_request_options_timeout_in_seconds_still_works() -> None:
721 """The deprecated `timeout_in_seconds` request option remains backwards compatible."""
722 http_client, dummy_client = _sync_client_with_base_timeout(60)
723 http_client.request(path="/test", method="GET", request_options={"timeout_in_seconds": 45})
724 assert dummy_client.last_request_kwargs["timeout"] == 45
725
726
727 def test_sync_request_options_timeout_takes_precedence() -> None:
728 """When both are set, `timeout` wins over `timeout_in_seconds` (same seconds unit)."""
729 http_client, dummy_client = _sync_client_with_base_timeout(60)
730 http_client.request(path="/test", method="GET", request_options={"timeout": 30, "timeout_in_seconds": 45})
731 assert dummy_client.last_request_kwargs["timeout"] == 30
732
733
734 def test_sync_request_options_timeout_falls_back_to_base() -> None:
735 """When neither key is set, the client-level base timeout is used."""
736 http_client, dummy_client = _sync_client_with_base_timeout(60)
737 http_client.request(path="/test", method="GET", request_options=None)
738 assert dummy_client.last_request_kwargs["timeout"] == 60
739
740
741 def test_sync_request_options_timeout_none_falls_back_to_deprecated() -> None:
742 """An explicit `timeout=None` (dynamic caller) falls back to the deprecated `timeout_in_seconds`."""
743 http_client, dummy_client = _sync_client_with_base_timeout(60)
744 request_options = cast(RequestOptions, {"timeout": None, "timeout_in_seconds": 45})
745 http_client.request(path="/test", method="GET", request_options=request_options)
746 assert dummy_client.last_request_kwargs["timeout"] == 45
747
748
749 @pytest.mark.asyncio
750 async def test_async_request_options_timeout_takes_precedence() -> None:
751 """Async: `timeout` wins over the deprecated `timeout_in_seconds`."""
752 dummy_client = _DummyAsyncClient()
753 http_client = AsyncHttpClient(
754 httpx_client=dummy_client, # type: ignore[arg-type]
755 base_timeout=lambda: 60,
756 base_headers=lambda: {},
757 base_url=lambda: "https://example.com",
758 async_base_headers=None,
759 )
760 await http_client.request(path="/test", method="GET", request_options={"timeout": 30, "timeout_in_seconds": 45})
761 assert dummy_client.last_request_kwargs["timeout"] == 30