| 1 |
"""Header names (and media types) are case-insensitive; the SDK carries headers as plain dicts |
| 2 |
until `BaseClient._build_headers`, and `httpx2.Headers` keeps and sends both entries of a dict that |
| 3 |
holds two case-variants of one name, so every merge / lookup / `Omit()` before that point must fold case. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
from typing import Any, Dict, Type, Union, Iterator, cast |
| 9 |
from unittest import mock |
| 10 |
|
| 11 |
import httpx2 |
| 12 |
import pytest |
| 13 |
|
| 14 |
from anthropic import Anthropic, AsyncAnthropic |
| 15 |
from anthropic._types import Omit |
| 16 |
from anthropic._models import FinalRequestOptions |
| 17 |
from anthropic._base_client import make_request_options |
| 18 |
|
| 19 |
from .utils import update_env |
| 20 |
|
| 21 |
base_url = "http://127.0.0.1:4010" |
| 22 |
api_key = "my-anthropic-api-key" |
| 23 |
|
| 24 |
ClientClass = Union[Type[Anthropic], Type[AsyncAnthropic]] |
| 25 |
|
| 26 |
both_clients = pytest.mark.parametrize("client_cls", [Anthropic, AsyncAnthropic], ids=["sync", "async"]) |
| 27 |
|
| 28 |
|
| 29 |
def make_client(client_cls: ClientClass, **kwargs: Any) -> Anthropic | AsyncAnthropic: |
| 30 |
kwargs.setdefault("api_key", api_key) |
| 31 |
return client_cls(base_url=base_url, _strict_response_validation=True, **kwargs) |
| 32 |
|
| 33 |
|
| 34 |
def build(client: Anthropic | AsyncAnthropic, **options: Any) -> httpx2.Request: |
| 35 |
return client._build_request(FinalRequestOptions.construct(method="post", url="/foo", **options)) |
| 36 |
|
| 37 |
|
| 38 |
@pytest.fixture |
| 39 |
def no_ambient_credentials() -> Iterator[None]: |
| 40 |
"""No API key, auth token or credentials provider discoverable from the environment.""" |
| 41 |
with mock.patch("anthropic._client.default_credentials", return_value=None): |
| 42 |
with update_env( |
| 43 |
ANTHROPIC_API_KEY=Omit(), |
| 44 |
ANTHROPIC_AUTH_TOKEN=Omit(), |
| 45 |
ANTHROPIC_CUSTOM_HEADERS=Omit(), |
| 46 |
): |
| 47 |
yield |
| 48 |
|
| 49 |
|
| 50 |
class TestBuildHeaders: |
| 51 |
"""SDK defaults < `default_headers` < `extra_headers`, whatever the casing.""" |
| 52 |
|
| 53 |
@both_clients |
| 54 |
def test_default_headers_replace_sdk_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 55 |
client = make_client(client_cls, default_headers={"user-agent": "my-app/1.0"}) |
| 56 |
|
| 57 |
request = build(client) |
| 58 |
|
| 59 |
assert request.headers.get_list("user-agent") == ["my-app/1.0"] |
| 60 |
|
| 61 |
@both_clients |
| 62 |
def test_default_headers_replace_client_subclass_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 63 |
# `anthropic-version` is added by the `Anthropic` subclass after the custom headers are spread in |
| 64 |
client = make_client(client_cls, default_headers={"Anthropic-Version": "2099-01-01"}) |
| 65 |
|
| 66 |
request = build(client) |
| 67 |
|
| 68 |
assert request.headers.get_list("anthropic-version") == ["2099-01-01"] |
| 69 |
|
| 70 |
@both_clients |
| 71 |
def test_extra_headers_replace_default_headers_case_insensitively(self, client_cls: ClientClass) -> None: |
| 72 |
client = make_client(client_cls, default_headers={"X-Foo": "from-client"}) |
| 73 |
|
| 74 |
request = build(client, **make_request_options(extra_headers={"x-foo": "from-request"})) |
| 75 |
|
| 76 |
assert request.headers.get_list("x-foo") == ["from-request"] |
| 77 |
|
| 78 |
def test_extra_headers_replace_generated_header_param_case_insensitively(self) -> None: |
| 79 |
requests: list[httpx2.Request] = [] |
| 80 |
|
| 81 |
def handler(request: httpx2.Request) -> httpx2.Response: |
| 82 |
requests.append(request) |
| 83 |
return httpx2.Response(200, json={"data": [], "has_more": False, "first_id": None, "last_id": None}) |
| 84 |
|
| 85 |
client = make_client(Anthropic, http_client=httpx2.Client(transport=httpx2.MockTransport(handler))) |
| 86 |
|
| 87 |
client.beta.models.list(betas=["from-betas-param"], extra_headers={"Anthropic-Beta": "from-extra-headers"}) |
| 88 |
|
| 89 |
assert requests[0].headers.get_list("anthropic-beta") == ["from-extra-headers"] |
| 90 |
|
| 91 |
@both_clients |
| 92 |
def test_extra_headers_replace_sdk_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 93 |
client = make_client(client_cls) |
| 94 |
|
| 95 |
request = build(client, **make_request_options(extra_headers={"Anthropic-Version": "2099-01-01"})) |
| 96 |
|
| 97 |
assert request.headers.get_list("anthropic-version") == ["2099-01-01"] |
| 98 |
|
| 99 |
@both_clients |
| 100 |
def test_api_key_header_override_does_not_send_two_credentials(self, client_cls: ClientClass) -> None: |
| 101 |
client = make_client(client_cls, api_key="sk-client-key") |
| 102 |
|
| 103 |
request = build(client, **make_request_options(extra_headers={"x-api-key": "sk-request-key"})) |
| 104 |
|
| 105 |
assert request.headers.get_list("x-api-key") == ["sk-request-key"] |
| 106 |
|
| 107 |
@both_clients |
| 108 |
def test_authorization_default_header_does_not_send_two_credentials(self, client_cls: ClientClass) -> None: |
| 109 |
client = make_client( |
| 110 |
client_cls, api_key=None, auth_token="client-token", default_headers={"authorization": "Bearer gateway"} |
| 111 |
) |
| 112 |
|
| 113 |
request = build(client) |
| 114 |
|
| 115 |
assert request.headers.get_list("authorization") == ["Bearer gateway"] |
| 116 |
|
| 117 |
@both_clients |
| 118 |
def test_custom_headers_env_var_is_overridden_case_insensitively(self, client_cls: ClientClass) -> None: |
| 119 |
with update_env(ANTHROPIC_CUSTOM_HEADERS="x-foo: from-env"): |
| 120 |
client = make_client(client_cls, default_headers={"X-Foo": "from-kwarg"}) |
| 121 |
|
| 122 |
request = build(client) |
| 123 |
|
| 124 |
assert request.headers.get_list("x-foo") == ["from-kwarg"] |
| 125 |
|
| 126 |
|
| 127 |
class TestOmit: |
| 128 |
"""`Omit()` removes a header whatever the casing.""" |
| 129 |
|
| 130 |
@both_clients |
| 131 |
def test_extra_headers_omit_removes_default_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 132 |
client = make_client(client_cls, default_headers={"X-Foo": "bar"}) |
| 133 |
|
| 134 |
request = build(client, **make_request_options(extra_headers={"x-foo": Omit()})) |
| 135 |
|
| 136 |
assert "x-foo" not in request.headers |
| 137 |
|
| 138 |
@both_clients |
| 139 |
def test_extra_headers_omit_removes_sdk_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 140 |
client = make_client(client_cls) |
| 141 |
|
| 142 |
request = build(client, **make_request_options(extra_headers={"x-stainless-lang": Omit()})) |
| 143 |
|
| 144 |
assert "x-stainless-lang" not in request.headers |
| 145 |
|
| 146 |
@both_clients |
| 147 |
def test_default_headers_omit_removes_client_subclass_header_case_insensitively( |
| 148 |
self, client_cls: ClientClass |
| 149 |
) -> None: |
| 150 |
client = make_client(client_cls, default_headers={"Anthropic-Version": Omit()}) |
| 151 |
|
| 152 |
request = build(client) |
| 153 |
|
| 154 |
assert "anthropic-version" not in request.headers |
| 155 |
|
| 156 |
@both_clients |
| 157 |
def test_with_options_omit_removes_default_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 158 |
client = make_client(client_cls, default_headers={"X-Foo": "bar"}).with_options( |
| 159 |
default_headers=cast("dict[str, str]", {"x-foo": Omit()}) |
| 160 |
) |
| 161 |
|
| 162 |
request = build(client) |
| 163 |
|
| 164 |
assert "x-foo" not in request.headers |
| 165 |
|
| 166 |
@both_clients |
| 167 |
def test_default_headers_omit_removes_per_request_sdk_header(self, client_cls: ClientClass) -> None: |
| 168 |
client = make_client(client_cls, default_headers={"X-Stainless-Retry-Count": Omit()}) |
| 169 |
|
| 170 |
request = build(client) |
| 171 |
|
| 172 |
assert "x-stainless-retry-count" not in request.headers |
| 173 |
|
| 174 |
|
| 175 |
class TestCopy: |
| 176 |
"""`with_options(default_headers=...)` replaces the parent's header whatever the casing.""" |
| 177 |
|
| 178 |
@both_clients |
| 179 |
def test_with_options_replaces_default_header_case_insensitively(self, client_cls: ClientClass) -> None: |
| 180 |
client = make_client(client_cls, default_headers={"X-Foo": "parent"}).with_options( |
| 181 |
default_headers={"x-foo": "child"} |
| 182 |
) |
| 183 |
|
| 184 |
request = build(client) |
| 185 |
|
| 186 |
assert request.headers.get_list("x-foo") == ["child"] |
| 187 |
|
| 188 |
@both_clients |
| 189 |
def test_with_options_does_not_accumulate_case_variants(self, client_cls: ClientClass) -> None: |
| 190 |
client = ( |
| 191 |
make_client(client_cls) |
| 192 |
.with_options(default_headers={"X-Foo": "one"}) |
| 193 |
.with_options(default_headers={"x-foo": "two"}) |
| 194 |
.with_options(default_headers={"X-FOO": "three"}) |
| 195 |
) |
| 196 |
|
| 197 |
request = build(client) |
| 198 |
|
| 199 |
assert request.headers.get_list("x-foo") == ["three"] |
| 200 |
|
| 201 |
|
| 202 |
@pytest.mark.usefixtures("no_ambient_credentials") |
| 203 |
class TestValidateHeaders: |
| 204 |
"""A caller-supplied `X-Api-Key` / `Authorization` header, or an explicit `Omit()` of one, counts as auth |
| 205 |
being configured whatever its casing.""" |
| 206 |
|
| 207 |
@both_clients |
| 208 |
@pytest.mark.parametrize( |
| 209 |
"headers", |
| 210 |
[ |
| 211 |
pytest.param({"x-api-key": "sk-from-header"}, id="x-api-key"), |
| 212 |
pytest.param({"X-API-Key": "sk-from-header"}, id="X-API-Key"), |
| 213 |
pytest.param({"authorization": "Bearer from-header"}, id="authorization"), |
| 214 |
pytest.param({"AUTHORIZATION": "Bearer from-header"}, id="AUTHORIZATION"), |
| 215 |
], |
| 216 |
) |
| 217 |
def test_auth_supplied_via_default_headers(self, client_cls: ClientClass, headers: Dict[str, str]) -> None: |
| 218 |
client = make_client(client_cls, api_key=None, default_headers=headers) |
| 219 |
|
| 220 |
request = build(client) |
| 221 |
|
| 222 |
((name, value),) = headers.items() |
| 223 |
assert request.headers.get_list(name) == [value] |
| 224 |
|
| 225 |
@both_clients |
| 226 |
@pytest.mark.parametrize( |
| 227 |
"headers", |
| 228 |
[ |
| 229 |
pytest.param({"x-api-key": "sk-from-header"}, id="x-api-key"), |
| 230 |
pytest.param({"authorization": "Bearer from-header"}, id="authorization"), |
| 231 |
], |
| 232 |
) |
| 233 |
def test_auth_supplied_via_extra_headers(self, client_cls: ClientClass, headers: Dict[str, str]) -> None: |
| 234 |
client = make_client(client_cls, api_key=None) |
| 235 |
|
| 236 |
request = build(client, **make_request_options(extra_headers=headers)) |
| 237 |
|
| 238 |
((name, value),) = headers.items() |
| 239 |
assert request.headers.get_list(name) == [value] |
| 240 |
|
| 241 |
@both_clients |
| 242 |
def test_auth_supplied_via_custom_headers_env_var(self, client_cls: ClientClass) -> None: |
| 243 |
with update_env(ANTHROPIC_CUSTOM_HEADERS="x-api-key: sk-from-env"): |
| 244 |
client = make_client(client_cls, api_key=None) |
| 245 |
|
| 246 |
request = build(client) |
| 247 |
|
| 248 |
assert request.headers.get_list("x-api-key") == ["sk-from-env"] |
| 249 |
|
| 250 |
@both_clients |
| 251 |
@pytest.mark.parametrize("header", ["x-api-key", "authorization"]) |
| 252 |
def test_auth_explicitly_omitted(self, client_cls: ClientClass, header: str) -> None: |
| 253 |
client = make_client(client_cls, api_key=None) |
| 254 |
|
| 255 |
request = build(client, **make_request_options(extra_headers={header: Omit()})) |
| 256 |
|
| 257 |
assert header not in request.headers |
| 258 |
|
| 259 |
@both_clients |
| 260 |
def test_auth_explicitly_omitted_on_the_client(self, client_cls: ClientClass) -> None: |
| 261 |
client = make_client(client_cls, api_key=None, default_headers={"x-api-key": Omit()}) |
| 262 |
|
| 263 |
request = build(client) |
| 264 |
|
| 265 |
assert "x-api-key" not in request.headers |
| 266 |
|
| 267 |
|
| 268 |
class TestMultipartContentType: |
| 269 |
"""A caller-supplied multipart `Content-Type` gets a boundary and the JSON body as form fields, whatever the casing.""" |
| 270 |
|
| 271 |
@both_clients |
| 272 |
def test_lowercase_multipart_content_type(self, client_cls: ClientClass) -> None: |
| 273 |
client = make_client(client_cls) |
| 274 |
|
| 275 |
request = build( |
| 276 |
client, |
| 277 |
json_data={"purpose": "test"}, |
| 278 |
files=[("file", ("hello.txt", b"hello", "text/plain"))], |
| 279 |
**make_request_options(extra_headers={"content-type": "multipart/form-data"}), |
| 280 |
) |
| 281 |
|
| 282 |
content_types = request.headers.get_list("content-type") |
| 283 |
assert len(content_types) == 1, content_types |
| 284 |
assert content_types[0].startswith("multipart/form-data; boundary=") |
| 285 |
assert b'name="purpose"' in request.read() |
| 286 |
|
| 287 |
def test_multipart_media_type_is_matched_case_insensitively(self) -> None: |
| 288 |
client = make_client(Anthropic) |
| 289 |
|
| 290 |
request = build( |
| 291 |
client, |
| 292 |
json_data={"purpose": "test"}, |
| 293 |
files=[("file", ("hello.txt", b"hello", "text/plain"))], |
| 294 |
**make_request_options(extra_headers={"Content-Type": "Multipart/Form-Data"}), |
| 295 |
) |
| 296 |
|
| 297 |
content_types = request.headers.get_list("content-type") |
| 298 |
assert len(content_types) == 1, content_types |
| 299 |
assert "boundary=" in content_types[0] |
| 300 |
assert b'name="purpose"' in request.read() |