Debian Codegraph @

tests/lib/test_azure.py

raw
1 from __future__ import annotations
2
3 import pytest
4
5 from anthropic._models import FinalRequestOptions
6 from anthropic._exceptions import AnthropicError
7 from anthropic.lib.foundry import AnthropicFoundry, AsyncAnthropicFoundry
8
9
10 class TestAnthropicFoundry:
11 def test_basic_initialization_with_api_key(self) -> None:
12 """Test basic client initialization with API key."""
13 client = AnthropicFoundry(
14 api_key="test-key",
15 resource="example-resource",
16 )
17
18 assert client.api_key == "test-key"
19 assert str(client.base_url) == "https://example-resource.services.ai.azure.com/anthropic/"
20
21 def test_initialization_with_base_url(self) -> None:
22 """Test client initialization with base_url instead of resource."""
23 client = AnthropicFoundry(
24 api_key="test-key",
25 base_url="https://example.services.ai.azure.com/anthropic/",
26 )
27
28 assert str(client.base_url) == "https://example.services.ai.azure.com/anthropic/"
29
30 def test_initialization_with_azure_ad_token_provider(self) -> None:
31 """Test client initialization with Azure AD token provider."""
32
33 def token_provider() -> str:
34 return "test-token"
35
36 client = AnthropicFoundry(
37 azure_ad_token_provider=token_provider,
38 resource="example-resource",
39 )
40
41 assert client._azure_ad_token_provider is not None
42 assert client._get_azure_ad_token() == "test-token"
43
44 def test_initialization_from_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None:
45 """Test client initialization falls back to environment variables."""
46 monkeypatch.setenv("ANTHROPIC_FOUNDRY_API_KEY", "env-key")
47 monkeypatch.setenv("ANTHROPIC_API_VERSION", "2023-06-01")
48 monkeypatch.setenv("ANTHROPIC_FOUNDRY_RESOURCE", "env-resource")
49
50 client = AnthropicFoundry()
51
52 assert client.api_key == "env-key"
53 assert "env-resource.services.ai.azure.com" in str(client.base_url)
54
55 def test_missing_credentials_error(self) -> None:
56 """Test error raised when no credentials are provided."""
57 with pytest.raises(AnthropicError, match="Missing credentials"):
58 AnthropicFoundry(
59 resource="example-resource",
60 )
61
62 def test_missing_resource_error(self) -> None:
63 """Test error raised when neither resource nor base_url is provided."""
64 with pytest.raises(ValueError, match="base_url.*resource"):
65 AnthropicFoundry(
66 api_key="test-key",
67 )
68
69 def test_copy(self) -> None:
70 """Test copy() carries over the client configuration."""
71
72 def token_provider() -> str:
73 return "test-token"
74
75 client = AnthropicFoundry(
76 azure_ad_token_provider=token_provider,
77 resource="example-resource",
78 default_headers={"x-app": "1"},
79 max_retries=5,
80 )
81
82 copied = client.copy()
83 assert str(copied.base_url) == str(client.base_url)
84 assert copied._azure_ad_token_provider is token_provider
85 assert copied.default_headers.get("x-app") == "1"
86 assert copied.max_retries == 5
87 assert copied._client is client._client
88
89 def test_with_options_overrides(self) -> None:
90 """Test with_options() applies overrides while keeping everything else."""
91 client = AnthropicFoundry(
92 api_key="test-key",
93 resource="example-resource",
94 default_headers={"x-app": "1"},
95 )
96
97 derived = client.with_options(timeout=10, default_headers={"x-extra": "2"})
98 assert derived.timeout == 10
99 assert derived.api_key == "test-key"
100 assert str(derived.base_url) == str(client.base_url)
101 assert derived.default_headers.get("x-app") == "1"
102 assert derived.default_headers.get("x-extra") == "2"
103
104 def test_copy_x_stainless_helper_header_appends(self) -> None:
105 """x-stainless-helper accumulates across copies instead of being clobbered."""
106 client = AnthropicFoundry(
107 api_key="test-key",
108 resource="example-resource",
109 default_headers={"x-stainless-helper": "parent"},
110 )
111
112 copied = client.with_options(default_headers={"x-stainless-helper": "child"})
113 assert copied.default_headers.get("x-stainless-helper") == "parent, child"
114
115
116 class TestAsyncAnthropicFoundry:
117 @pytest.mark.asyncio
118 async def test_basic_initialization_with_api_key(self) -> None:
119 """Test basic async client initialization with API key."""
120 client = AsyncAnthropicFoundry(
121 api_key="test-key",
122 resource="example-resource",
123 )
124
125 assert client.api_key == "test-key"
126 assert str(client.base_url) == "https://example-resource.services.ai.azure.com/anthropic/"
127
128 @pytest.mark.asyncio
129 async def test_async_azure_ad_token_provider(self) -> None:
130 """Test async client with async Azure AD token provider."""
131
132 async def async_token_provider() -> str:
133 return "async-test-token"
134
135 client = AsyncAnthropicFoundry(
136 azure_ad_token_provider=async_token_provider,
137 resource="example-resource",
138 )
139
140 token = await client._get_azure_ad_token()
141 assert token == "async-test-token"
142
143 @pytest.mark.asyncio
144 async def test_initialization_from_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None:
145 """Test async client initialization falls back to environment variables."""
146 monkeypatch.setenv("ANTHROPIC_FOUNDRY_API_KEY", "env-key")
147 monkeypatch.setenv("ANTHROPIC_API_VERSION", "2023-06-01")
148 monkeypatch.setenv("ANTHROPIC_FOUNDRY_RESOURCE", "env-resource")
149
150 client = AsyncAnthropicFoundry()
151
152 assert client.api_key == "env-key"
153 assert "env-resource.services.ai.azure.com" in str(client.base_url)
154
155 def test_copy(self) -> None:
156 """Test copy() carries over the client configuration."""
157
158 async def async_token_provider() -> str:
159 return "async-test-token"
160
161 client = AsyncAnthropicFoundry(
162 azure_ad_token_provider=async_token_provider,
163 resource="example-resource",
164 max_retries=5,
165 )
166
167 copied = client.with_options(timeout=10)
168 assert str(copied.base_url) == str(client.base_url)
169 assert copied._azure_ad_token_provider is async_token_provider
170 assert copied.max_retries == 5
171 assert copied.timeout == 10
172
173 def test_copy_x_stainless_helper_header_appends(self) -> None:
174 """x-stainless-helper accumulates across copies instead of being clobbered."""
175 client = AsyncAnthropicFoundry(
176 api_key="test-key",
177 resource="example-resource",
178 default_headers={"x-stainless-helper": "parent"},
179 )
180
181 copied = client.with_options(default_headers={"x-stainless-helper": "child"})
182 assert copied.default_headers.get("x-stainless-helper") == "parent, child"
183
184
185 class TestFoundryDoesNotLeakAnthropicAPIKey:
186 """A stray ANTHROPIC_API_KEY in the environment must never be sent to the
187 Foundry endpoint as X-Api-Key, regardless of which auth mode is in use."""
188
189 def test_no_x_api_key_with_azure_ad_token_provider(self, monkeypatch: pytest.MonkeyPatch) -> None:
190 monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-should-not-leak")
191 client = AnthropicFoundry(resource="example-resource", azure_ad_token_provider=lambda: "azure-token")
192
193 options = client._prepare_options(FinalRequestOptions(method="post", url="/v1/messages"))
194 headers = client._build_request(options).headers
195
196 assert headers.get("x-api-key") is None
197 assert headers.get("authorization") == "Bearer azure-token"
198
199 def test_api_key_mode_sends_foundry_key_as_x_api_key(self, monkeypatch: pytest.MonkeyPatch) -> None:
200 monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-should-not-leak")
201 client = AnthropicFoundry(api_key="foundry-key", resource="example-resource")
202
203 options = client._prepare_options(FinalRequestOptions(method="post", url="/v1/messages"))
204 headers = client._build_request(options).headers
205
206 assert headers.get("x-api-key") == "foundry-key"
207 assert headers.get("api-key") == "foundry-key"
208 assert "sk-ant-should-not-leak" not in headers.values()
209
210 @pytest.mark.asyncio
211 async def test_async_no_x_api_key_with_azure_ad_token_provider(self, monkeypatch: pytest.MonkeyPatch) -> None:
212 monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-should-not-leak")
213
214 async def token_provider() -> str:
215 return "azure-token"
216
217 client = AsyncAnthropicFoundry(resource="example-resource", azure_ad_token_provider=token_provider)
218
219 options = await client._prepare_options(FinalRequestOptions(method="post", url="/v1/messages"))
220 headers = client._build_request(options).headers
221
222 assert headers.get("x-api-key") is None
223 assert headers.get("authorization") == "Bearer azure-token"
224
225 @pytest.mark.asyncio
226 async def test_async_api_key_mode_sends_foundry_key_as_x_api_key(self, monkeypatch: pytest.MonkeyPatch) -> None:
227 monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-should-not-leak")
228 client = AsyncAnthropicFoundry(api_key="foundry-key", resource="example-resource")
229
230 options = await client._prepare_options(FinalRequestOptions(method="post", url="/v1/messages"))
231 headers = client._build_request(options).headers
232
233 assert headers.get("x-api-key") == "foundry-key"
234 assert headers.get("api-key") == "foundry-key"
235 assert "sk-ant-should-not-leak" not in headers.values()
236
237
238 class TestFoundryCallerAuthHeaderCasing:
239 """A caller-supplied `Authorization` / `x-api-key` header isn't doubled up by Foundry's own, whatever its casing."""
240
241 def test_caller_authorization_header_wins_case_insensitively(self) -> None:
242 client = AnthropicFoundry(resource="example-resource", azure_ad_token_provider=lambda: "azure-token")
243
244 options = client._prepare_options(
245 FinalRequestOptions(method="post", url="/v1/messages", headers={"authorization": "Bearer per-request"})
246 )
247 headers = client._build_request(options).headers
248
249 assert headers.get_list("authorization") == ["Bearer per-request"]
250
251 def test_caller_api_key_header_wins_case_insensitively(self) -> None:
252 client = AnthropicFoundry(api_key="foundry-key", resource="example-resource")
253
254 options = client._prepare_options(
255 FinalRequestOptions(method="post", url="/v1/messages", headers={"X-Api-Key": "per-request-key"})
256 )
257 headers = client._build_request(options).headers
258
259 assert headers.get_list("x-api-key") == ["per-request-key"]
260
261 @pytest.mark.asyncio
262 async def test_async_caller_authorization_header_wins_case_insensitively(self) -> None:
263 async def token_provider() -> str:
264 return "azure-token"
265
266 client = AsyncAnthropicFoundry(resource="example-resource", azure_ad_token_provider=token_provider)
267
268 options = await client._prepare_options(
269 FinalRequestOptions(method="post", url="/v1/messages", headers={"authorization": "Bearer per-request"})
270 )
271 headers = client._build_request(options).headers
272
273 assert headers.get_list("authorization") == ["Bearer per-request"]
274
275 @pytest.mark.asyncio
276 async def test_async_caller_api_key_header_wins_case_insensitively(self) -> None:
277 client = AsyncAnthropicFoundry(api_key="foundry-key", resource="example-resource")
278
279 options = await client._prepare_options(
280 FinalRequestOptions(method="post", url="/v1/messages", headers={"X-Api-Key": "per-request-key"})
281 )
282 headers = client._build_request(options).headers
283
284 assert headers.get_list("x-api-key") == ["per-request-key"]