| 1032 | @pytest.mark.respx(base_url=base_url) |
| 1033 | @pytest.mark.parametrize("failure_mode", ["status", "exception"]) |
| 1034 | def test_retries_taken( |
| 1035 | self, |
| 1036 | client: Anthropic, |
| 1037 | failures_before_success: int, |
| 1038 | failure_mode: Literal["status", "exception"], |
| 1039 | respx_mock: MockRouter, |
| 1040 | ) -> None: |
| 1041 | client = client.with_options(max_retries=4) |
| 1042 | |
| 1043 | nb_retries = 0 |
| 1044 | |
| 1045 | def retry_handler(_request: httpx.Request) -> httpx.Response: |
| 1046 | nonlocal nb_retries |
| 1047 | if nb_retries < failures_before_success: |
| 1048 | nb_retries += 1 |
| 1049 | if failure_mode == "exception": |
| 1050 | raise RuntimeError("oops") |
| 1051 | return httpx.Response(500) |
| 1052 | return httpx.Response(200) |
| 1053 | |
| 1054 | respx_mock.post("/v1/messages").mock(side_effect=retry_handler) |
| 1055 | |
| 1056 | response = client.messages.with_raw_response.create( |
| 1057 | max_tokens=1024, |
| 1058 | messages=[ |
| 1059 | { |
| 1060 | "content": "Hello, world", |
| 1061 | "role": "user", |
| 1062 | } |
| 1063 | ], |
| 1064 | model="claude-opus-4-6", |
| 1065 | ) |
| 1066 | |
| 1067 | assert response.retries_taken == failures_before_success |
| 1068 | assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success |
| 1069 | |
| 1070 | @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) |
| 1071 | @mock.patch("anthropic._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) |