Debian Codegraph @

tests/lib/test_bedrock_mantle.py

raw
1 from __future__ import annotations
2
3 import threading
4
5 import httpx2
6 import pytest
7
8 from anthropic import AnthropicBedrockMantle, AsyncAnthropicBedrockMantle
9
10 MANTLE_MESSAGES_URL = "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages"
11
12
13 class GetAuthHeadersRecorder:
14 """Stands in for `anthropic.lib.bedrock._mantle.get_auth_headers` and records each call's kwargs."""
15
16 def __init__(self) -> None:
17 self.calls: list[dict[str, object]] = []
18
19 def __call__(self, **kwargs: object) -> dict[str, str]:
20 self.calls.append(kwargs)
21 return {"Authorization": "AWS4-HMAC-SHA256 ...", "X-Amz-Date": "20260327T000000Z"}
22
23
24 @pytest.fixture
25 def get_auth_headers_recorder(monkeypatch: pytest.MonkeyPatch) -> GetAuthHeadersRecorder:
26 recorder = GetAuthHeadersRecorder()
27 monkeypatch.setattr("anthropic.lib.bedrock._mantle.get_auth_headers", recorder)
28 return recorder
29
30
31 class TestBaseURL:
32 def test_derives_base_url_from_region(self) -> None:
33 client = AnthropicBedrockMantle(
34 api_key="test-key",
35 aws_region="us-east-1",
36 )
37 assert str(client.base_url).startswith("https://bedrock-mantle.us-east-1.api.aws/anthropic")
38
39 def test_different_region(self) -> None:
40 client = AnthropicBedrockMantle(
41 api_key="test-key",
42 aws_region="us-west-2",
43 )
44 assert str(client.base_url).startswith("https://bedrock-mantle.us-west-2.api.aws/anthropic")
45
46 def test_uses_base_url_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
47 monkeypatch.setenv("ANTHROPIC_BEDROCK_MANTLE_BASE_URL", "https://custom.example.com")
48 client = AnthropicBedrockMantle(
49 api_key="test-key",
50 )
51 assert str(client.base_url).startswith("https://custom.example.com")
52
53 def test_base_url_arg_takes_precedence_over_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
54 monkeypatch.setenv("ANTHROPIC_BEDROCK_MANTLE_BASE_URL", "https://from-env.example.com")
55 client = AnthropicBedrockMantle(
56 api_key="test-key",
57 base_url="https://from-arg.example.com",
58 )
59 assert str(client.base_url).startswith("https://from-arg.example.com")
60
61 def test_raises_without_region_or_base_url(self) -> None:
62 with pytest.raises(Exception, match="No AWS region or base URL found"):
63 AnthropicBedrockMantle(
64 api_key="test-key",
65 )
66
67
68 class TestSigV4ServiceName:
69 def test_uses_bedrock_mantle_service_name(self, get_auth_headers_recorder: GetAuthHeadersRecorder) -> None:
70 client = AnthropicBedrockMantle(
71 aws_access_key="AKID",
72 aws_secret_key="secret",
73 aws_region="us-east-1",
74 )
75
76 request = httpx2.Request(
77 "POST",
78 MANTLE_MESSAGES_URL,
79 headers={"content-type": "application/json"},
80 content=b'{"model": "claude-sonnet-4-20250514"}',
81 )
82 client._prepare_request(request)
83
84 assert len(get_auth_headers_recorder.calls) == 1
85 assert get_auth_headers_recorder.calls[0]["service_name"] == "bedrock-mantle"
86 assert request.headers["Authorization"] == "AWS4-HMAC-SHA256 ..."
87
88
89 class TestEnvironmentVariables:
90 def test_uses_mantle_api_key_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
91 monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "mantle-key")
92 client = AnthropicBedrockMantle(
93 base_url="https://example.com",
94 )
95 assert client.api_key == "mantle-key"
96
97 def test_falls_back_to_aws_api_key_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
98 monkeypatch.setenv("ANTHROPIC_AWS_API_KEY", "aws-key")
99 client = AnthropicBedrockMantle(
100 base_url="https://example.com",
101 )
102 assert client.api_key == "aws-key"
103
104 def test_mantle_api_key_takes_precedence_over_aws(self, monkeypatch: pytest.MonkeyPatch) -> None:
105 monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "mantle-key")
106 monkeypatch.setenv("ANTHROPIC_AWS_API_KEY", "aws-key")
107 client = AnthropicBedrockMantle(
108 base_url="https://example.com",
109 )
110 assert client.api_key == "mantle-key"
111
112 def test_region_from_aws_region_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
113 monkeypatch.setenv("AWS_REGION", "eu-west-1")
114 client = AnthropicBedrockMantle(
115 api_key="test-key",
116 )
117 assert client.aws_region == "eu-west-1"
118 assert client.base_url == "https://bedrock-mantle.eu-west-1.api.aws/anthropic/"
119
120 def test_region_from_aws_default_region_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
121 monkeypatch.delenv("AWS_REGION", raising=False)
122 monkeypatch.setenv("AWS_DEFAULT_REGION", "ap-southeast-1")
123 client = AnthropicBedrockMantle(
124 api_key="test-key",
125 )
126 assert client.aws_region == "ap-southeast-1"
127
128
129 class TestEndpointRestrictions:
130 def _make_client(self) -> AnthropicBedrockMantle:
131 return AnthropicBedrockMantle(
132 api_key="test-key",
133 base_url="https://example.com",
134 )
135
136 def test_completions_not_available(self) -> None:
137 client = self._make_client()
138 assert not hasattr(client, "completions")
139
140 def test_models_not_available(self) -> None:
141 client = self._make_client()
142 assert not hasattr(client, "models")
143
144 def test_messages_available(self) -> None:
145 client = self._make_client()
146 assert client.messages is not None
147
148 def test_beta_messages_available(self) -> None:
149 client = self._make_client()
150 assert client.beta.messages is not None
151
152 def test_beta_models_not_available(self) -> None:
153 client = self._make_client()
154 assert not hasattr(client.beta, "models")
155
156 def test_beta_files_not_available(self) -> None:
157 client = self._make_client()
158 assert not hasattr(client.beta, "files")
159
160 def test_beta_skills_not_available(self) -> None:
161 client = self._make_client()
162 assert not hasattr(client.beta, "skills")
163
164
165 class TestAuthPrecedence:
166 def test_api_key_arg_uses_api_key_mode(self) -> None:
167 client = AnthropicBedrockMantle(
168 api_key="my-key",
169 aws_region="us-east-1",
170 )
171 assert client._use_sigv4 is False
172 assert client.api_key == "my-key"
173
174 def test_aws_creds_use_sigv4_mode(self) -> None:
175 client = AnthropicBedrockMantle(
176 aws_access_key="AKID",
177 aws_secret_key="secret",
178 aws_region="us-east-1",
179 )
180 assert client._use_sigv4 is True
181 assert client.api_key is None
182
183 def test_api_key_mode_returns_bearer_auth_header(self) -> None:
184 client = AnthropicBedrockMantle(
185 api_key="my-key",
186 aws_region="us-east-1",
187 )
188 assert client.auth_headers == {"Authorization": "Bearer my-key"}
189
190 def test_sigv4_mode_returns_empty_auth_headers(self) -> None:
191 client = AnthropicBedrockMantle(
192 aws_access_key="AKID",
193 aws_secret_key="secret",
194 aws_region="us-east-1",
195 )
196 assert client.auth_headers == {}
197
198 def test_skip_auth_returns_empty_auth_headers(self) -> None:
199 client = AnthropicBedrockMantle(
200 skip_auth=True,
201 base_url="https://example.com",
202 )
203 assert client.auth_headers == {}
204
205
206 class TestSkipAuth:
207 def test_skip_auth_does_not_sign_request(self, get_auth_headers_recorder: GetAuthHeadersRecorder) -> None:
208 client = AnthropicBedrockMantle(
209 skip_auth=True,
210 base_url="https://example.com",
211 )
212
213 request = httpx2.Request("POST", "https://example.com/v1/messages", content=b"{}")
214 client._prepare_request(request)
215
216 assert get_auth_headers_recorder.calls == []
217 assert "Authorization" not in request.headers
218
219
220 class TestPartialCredentials:
221 def test_access_key_only_raises(self) -> None:
222 with pytest.raises(ValueError, match="aws_access_key.*without.*aws_secret_key"):
223 AnthropicBedrockMantle(
224 aws_access_key="AKID",
225 aws_region="us-east-1",
226 )
227
228 def test_secret_key_only_raises(self) -> None:
229 with pytest.raises(ValueError, match="aws_secret_key.*without.*aws_access_key"):
230 AnthropicBedrockMantle(
231 aws_secret_key="secret",
232 aws_region="us-east-1",
233 )
234
235
236 class TestAsyncClient:
237 def test_async_client_has_same_restrictions(self) -> None:
238 client = AsyncAnthropicBedrockMantle(
239 api_key="test-key",
240 base_url="https://example.com",
241 )
242 assert not hasattr(client, "completions")
243 assert not hasattr(client, "models")
244 assert client.messages is not None
245 assert client.beta.messages is not None
246 assert not hasattr(client.beta, "models")
247 assert not hasattr(client.beta, "files")
248 assert not hasattr(client.beta, "skills")
249
250 def test_async_base_url_from_region(self) -> None:
251 client = AsyncAnthropicBedrockMantle(
252 api_key="test-key",
253 aws_region="us-east-1",
254 )
255 assert client.base_url == "https://bedrock-mantle.us-east-1.api.aws/anthropic/"
256
257 @pytest.mark.asyncio()
258 async def test_sigv4_signing_runs_off_event_loop(self, monkeypatch: pytest.MonkeyPatch) -> None:
259 client = AsyncAnthropicBedrockMantle(
260 aws_access_key="AKID",
261 aws_secret_key="secret",
262 aws_region="us-east-1",
263 )
264 signing_threads: list[int] = []
265
266 def fake_get_auth_headers(**_: object) -> dict[str, str]:
267 signing_threads.append(threading.get_ident())
268 return {"Authorization": "AWS4-HMAC-SHA256 stub"}
269
270 monkeypatch.setattr("anthropic.lib.bedrock._mantle.get_auth_headers", fake_get_auth_headers)
271
272 request = httpx2.Request(
273 "POST", "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages", content=b"{}"
274 )
275 await client._prepare_request(request)
276
277 assert len(signing_threads) == 1
278 assert signing_threads[0] != threading.get_ident()
279 assert request.headers["Authorization"] == "AWS4-HMAC-SHA256 stub"
280
281
282 class TestCopy:
283 def test_copy_preserves_config(self) -> None:
284 client = AnthropicBedrockMantle(
285 api_key="test-key",
286 aws_region="us-east-1",
287 )
288 copied = client.copy()
289 assert copied.base_url == client.base_url
290 assert copied.aws_region == client.aws_region
291
292 def test_copy_overrides_region(self) -> None:
293 client = AnthropicBedrockMantle(
294 api_key="test-key",
295 aws_region="us-east-1",
296 )
297 copied = client.copy(aws_region="us-west-2")
298 assert copied.aws_region == "us-west-2"
299
300 def test_copy_x_stainless_helper_header_appends(self) -> None:
301 # `x-stainless-helper` accumulates across copies instead of being clobbered
302 client = AnthropicBedrockMantle(
303 api_key="test-key",
304 aws_region="us-east-1",
305 default_headers={"x-stainless-helper": "parent"},
306 )
307 copied = client.copy(default_headers={"x-stainless-helper": "child"})
308 assert copied.default_headers["x-stainless-helper"] == "parent, child"
309
310 def test_async_copy_x_stainless_helper_header_appends(self) -> None:
311 # `x-stainless-helper` accumulates across copies instead of being clobbered
312 client = AsyncAnthropicBedrockMantle(
313 api_key="test-key",
314 aws_region="us-east-1",
315 default_headers={"x-stainless-helper": "parent"},
316 )
317 copied = client.copy(default_headers={"x-stainless-helper": "child"})
318 assert copied.default_headers["x-stainless-helper"] == "parent, child"