| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
import os |
| 5 |
import re |
| 6 |
import sys |
| 7 |
import enum |
| 8 |
import json |
| 9 |
import base64 |
| 10 |
import logging |
| 11 |
import pathlib |
| 12 |
import ipaddress |
| 13 |
from types import MappingProxyType |
| 14 |
from typing import Any, cast |
| 15 |
from datetime import date, datetime, timezone, timedelta |
| 16 |
from itertools import islice |
| 17 |
from collections import UserString, deque |
| 18 |
from collections.abc import Mapping, Callable, Iterator, Sequence |
| 19 |
from typing_extensions import override |
| 20 |
|
| 21 |
import httpx2 |
| 22 |
import pytest |
| 23 |
import pydantic |
| 24 |
from respx import MockRouter |
| 25 |
from respx.models import Call as MockRequestCall |
| 26 |
|
| 27 |
from anthropic import Anthropic, AsyncAnthropic |
| 28 |
from anthropic._types import omit, not_given |
| 29 |
from anthropic._utils import is_mapping, is_sequence |
| 30 |
from anthropic._compat import PYDANTIC_V1, model_copy, model_parse |
| 31 |
from anthropic._models import BaseModel, construct_type |
| 32 |
from anthropic._constants import FILE_INPUT_MARKERS |
| 33 |
from anthropic.pagination import SyncPage, AsyncPage |
| 34 |
from anthropic._base_client import BaseClient, make_request_options |
| 35 |
from anthropic._utils._json import openapi_dumps_str |
| 36 |
from anthropic._utils._prepare import ( |
| 37 |
serialize_data, |
| 38 |
async_serialize_data, |
| 39 |
prepare_request_data, |
| 40 |
async_prepare_request_data, |
| 41 |
) |
| 42 |
|
| 43 |
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") |
| 44 |
|
| 45 |
SAMPLE_FILE_PATH = pathlib.Path(__file__).parent.joinpath("sample_file.txt") |
| 46 |
SAMPLE_FILE_BASE64 = "SGVsbG8sIHdvcmxkIQo=" |
| 47 |
|
| 48 |
# where the client looks the file input markers up on each request; the package's own depend on the API |
| 49 |
# spec and may be empty, so the tests that read file inputs pin `MARKERS` there |
| 50 |
MARKERS_ATTR = "anthropic._utils._prepare.FILE_INPUT_MARKERS" |
| 51 |
MARKERS = (("type", "base64", "data"),) |
| 52 |
|
| 53 |
|
| 54 |
class Send: |
| 55 |
"""Sends request params through a client whose transport records the request and answers `{}`.""" |
| 56 |
|
| 57 |
request: httpx2.Request |
| 58 |
"""the last request that went over the wire""" |
| 59 |
|
| 60 |
def __init__(self, client: Anthropic | AsyncAnthropic) -> None: |
| 61 |
transport = httpx2.MockTransport(self._record) |
| 62 |
self._client: Anthropic | AsyncAnthropic |
| 63 |
if isinstance(client, Anthropic): |
| 64 |
self._client = client.with_options(http_client=httpx2.Client(transport=transport), max_retries=0) |
| 65 |
else: |
| 66 |
self._client = client.with_options(http_client=httpx2.AsyncClient(transport=transport), max_retries=0) |
| 67 |
|
| 68 |
def _record(self, request: httpx2.Request) -> httpx2.Response: |
| 69 |
self.request = request |
| 70 |
return httpx2.Response(200, json={}) |
| 71 |
|
| 72 |
async def __call__(self, body: object, *, extra_body: Mapping[str, object] | None = None) -> Any: |
| 73 |
"""The JSON that `body` is sent as, or `None` when the request went out without content.""" |
| 74 |
options = make_request_options(extra_body=extra_body) |
| 75 |
if isinstance(self._client, Anthropic): |
| 76 |
self._client.post("/foo", body=body, options=options, cast_to=httpx2.Response) |
| 77 |
else: |
| 78 |
await self._client.post("/foo", body=body, options=options, cast_to=httpx2.Response) |
| 79 |
return json.loads(self.request.content) if self.request.content else None |
| 80 |
|
| 81 |
async def query( |
| 82 |
self, |
| 83 |
query: Mapping[str, object] | None = None, |
| 84 |
*, |
| 85 |
extra_query: Mapping[str, object] | None = None, |
| 86 |
extra_body: Mapping[str, object] | None = None, |
| 87 |
default_query: Mapping[str, object] | None = None, |
| 88 |
) -> dict[str, str]: |
| 89 |
"""The query string that `query` is sent as, parsed back into a dict.""" |
| 90 |
options = make_request_options(query=query, extra_query=extra_query, extra_body=extra_body) |
| 91 |
client = self._client.with_options(default_query=default_query) |
| 92 |
if isinstance(client, Anthropic): |
| 93 |
client.get("/foo", options=options, cast_to=httpx2.Response) |
| 94 |
else: |
| 95 |
await client.get("/foo", options=options, cast_to=httpx2.Response) |
| 96 |
return dict(self.request.url.params) |
| 97 |
|
| 98 |
async def form(self, body: Mapping[str, object]) -> bytes: |
| 99 |
"""The multipart content that `body` is sent as next to a file.""" |
| 100 |
options = make_request_options(extra_headers={"Content-Type": "multipart/form-data; boundary=boundary"}) |
| 101 |
files = [("file", b"contents")] |
| 102 |
if isinstance(self._client, Anthropic): |
| 103 |
self._client.post("/foo", body=body, files=files, options=options, cast_to=httpx2.Response) |
| 104 |
else: |
| 105 |
await self._client.post("/foo", body=body, files=files, options=options, cast_to=httpx2.Response) |
| 106 |
return self.request.content |
| 107 |
|
| 108 |
|
| 109 |
@pytest.fixture(params=[True, False], ids=["sync", "async"]) |
| 110 |
def client( |
| 111 |
request: pytest.FixtureRequest, client: Anthropic, async_client: AsyncAnthropic |
| 112 |
) -> Anthropic | AsyncAnthropic: |
| 113 |
return client if request.param else async_client |
| 114 |
|
| 115 |
|
| 116 |
@pytest.fixture |
| 117 |
def send(client: Anthropic | AsyncAnthropic) -> Send: |
| 118 |
return Send(client) |
| 119 |
|
| 120 |
|
| 121 |
def b64_obj(data: object) -> Any: |
| 122 |
return {"type": "base64", "media_type": "image/png", "data": data} |
| 123 |
|
| 124 |
|
| 125 |
def image_block(data: object) -> Any: |
| 126 |
return {"type": "image", "source": b64_obj(data)} |
| 127 |
|
| 128 |
|
| 129 |
def _no_retry_delay(*_args: Any, **_kwargs: Any) -> float: |
| 130 |
return 0.01 |
| 131 |
|
| 132 |
|
| 133 |
class Item(BaseModel): |
| 134 |
id: str |
| 135 |
|
| 136 |
|
| 137 |
class DuckReader: |
| 138 |
"""Has a `read` method, but is none of the types `is_base64_file_input` accepts.""" |
| 139 |
|
| 140 |
def __init__(self) -> None: |
| 141 |
self.read_calls = 0 |
| 142 |
|
| 143 |
def read(self) -> str: |
| 144 |
self.read_calls += 1 |
| 145 |
return "a\nb\n" |
| 146 |
|
| 147 |
|
| 148 |
class IterableDuckReader(DuckReader): |
| 149 |
"""Defines `__iter__`, but is no sequence, set or iterator.""" |
| 150 |
|
| 151 |
def __iter__(self) -> Iterator[str]: |
| 152 |
return iter(["a", "b"]) |
| 153 |
|
| 154 |
|
| 155 |
class BrokenIterable: |
| 156 |
def __iter__(self) -> Iterator[str]: |
| 157 |
raise AssertionError("must not be iterated") |
| 158 |
|
| 159 |
@override |
| 160 |
def __str__(self) -> str: |
| 161 |
return "broken" |
| 162 |
|
| 163 |
|
| 164 |
class BarePathLike: |
| 165 |
"""An `os.PathLike` that is not a `pathlib.Path`; nothing reads these.""" |
| 166 |
|
| 167 |
def __fspath__(self) -> str: |
| 168 |
return str(SAMPLE_FILE_PATH) |
| 169 |
|
| 170 |
|
| 171 |
class Perm(enum.IntFlag): |
| 172 |
R = 4 |
| 173 |
W = 2 |
| 174 |
X = 1 |
| 175 |
|
| 176 |
|
| 177 |
class Shade(enum.Flag): |
| 178 |
LIGHT = 1 |
| 179 |
DARK = 2 |
| 180 |
|
| 181 |
|
| 182 |
class Level(enum.IntEnum): |
| 183 |
LOW = 1 |
| 184 |
|
| 185 |
|
| 186 |
class Tag(str): |
| 187 |
pass |
| 188 |
|
| 189 |
|
| 190 |
class Count(int): |
| 191 |
pass |
| 192 |
|
| 193 |
|
| 194 |
class Matryoshka(Sequence["Matryoshka"]): |
| 195 |
"""Holds a fresh object of its own kind, however deep the walk goes.""" |
| 196 |
|
| 197 |
@override |
| 198 |
def __len__(self) -> int: |
| 199 |
return 1 |
| 200 |
|
| 201 |
@override |
| 202 |
def __getitem__(self, index: Any) -> Any: |
| 203 |
if index == 0: |
| 204 |
return Matryoshka() |
| 205 |
raise IndexError(index) |
| 206 |
|
| 207 |
|
| 208 |
class StrPath(str): |
| 209 |
"""A `str` that is also an `os.PathLike`.""" |
| 210 |
|
| 211 |
def __fspath__(self) -> str: |
| 212 |
return str(self) |
| 213 |
|
| 214 |
|
| 215 |
async def test_strips_omit_and_not_given(send: Send) -> None: |
| 216 |
assert await send({"foo": "bar", "baz": omit, "qux": not_given}) == {"foo": "bar"} |
| 217 |
assert await send({"a": {"b": omit, "c": {"d": not_given, "e": 1}}}) == {"a": {"c": {"e": 1}}} |
| 218 |
assert await send({"items": [{"keep": True, "drop": omit}, {"drop": not_given}]}) == {"items": [{"keep": True}, {}]} |
| 219 |
assert await send([{"a": omit}]) == [{}] |
| 220 |
|
| 221 |
|
| 222 |
async def test_extra_body_is_merged_in(send: Send) -> None: |
| 223 |
assert await send( |
| 224 |
{"a": 1}, extra_body={"b": ("x",), "c": {"d": omit}, "e": [{"f": not_given}], "g": Item(id="1")} |
| 225 |
) == {"a": 1, "b": ["x"], "c": {}, "e": [{}], "g": {"id": "1"}} |
| 226 |
assert await send( |
| 227 |
{"model": "m", "keep": True, "nested": {"a": 1}}, extra_body={"model": omit, "nested": {"b": ("x",), "c": omit}} |
| 228 |
) == {"keep": True, "nested": {"b": ["x"]}} |
| 229 |
assert await send({"a": 1}, extra_body={"a": not_given}) == {"a": 1} |
| 230 |
|
| 231 |
|
| 232 |
async def test_keeps_none(send: Send) -> None: |
| 233 |
assert await send({"foo": None, "bar": {"baz": None}, "items": [None]}) == { |
| 234 |
"foo": None, |
| 235 |
"bar": {"baz": None}, |
| 236 |
"items": [None], |
| 237 |
} |
| 238 |
assert await send(None) is None |
| 239 |
|
| 240 |
|
| 241 |
LISTS: list[Callable[[], object]] = [ |
| 242 |
lambda: [1, 2], |
| 243 |
lambda: (1, 2), |
| 244 |
lambda: range(1, 3), |
| 245 |
lambda: deque([1, 2]), |
| 246 |
lambda: {1, 2}, |
| 247 |
lambda: frozenset((1, 2)), |
| 248 |
lambda: {1: "a", 2: "b"}.keys(), |
| 249 |
lambda: {"a": 1, "b": 2}.values(), |
| 250 |
lambda: (i for i in (1, 2)), |
| 251 |
lambda: iter([1, 2]), |
| 252 |
lambda: map(int, "12"), |
| 253 |
] |
| 254 |
|
| 255 |
|
| 256 |
@pytest.mark.parametrize("make", LISTS) |
| 257 |
async def test_sequences_sets_views_and_iterators_are_sent_as_lists(send: Send, make: Callable[[], object]) -> None: |
| 258 |
assert await send({"k": make(), "nested": [make()]}) == {"k": [1, 2], "nested": [[1, 2]]} |
| 259 |
assert await send(make()) == [1, 2] |
| 260 |
assert await send({"items": {1: "a"}.items()}) == {"items": [[1, "a"]]} |
| 261 |
|
| 262 |
await send.query({"k": [1, 2]}) |
| 263 |
as_list = send.request.url.query |
| 264 |
await send.query({"k": make()}) |
| 265 |
assert send.request.url.query == as_list |
| 266 |
|
| 267 |
|
| 268 |
@pytest.mark.parametrize( |
| 269 |
"value", |
| 270 |
[ |
| 271 |
pytest.param(ipaddress.ip_network("10.0.0.0/30"), id="ip_network"), |
| 272 |
pytest.param(IterableDuckReader(), id="only __iter__"), |
| 273 |
pytest.param(BrokenIterable(), id="__iter__ raises"), |
| 274 |
pytest.param(Shade, id="Enum class"), |
| 275 |
pytest.param(memoryview(b"ab"), id="memoryview"), |
| 276 |
], |
| 277 |
) |
| 278 |
async def test_other_iterables_are_not_iterated(send: Send, value: object) -> None: |
| 279 |
# in a body they are left to the encoder, in a query they are sent as their `str()` |
| 280 |
for body in ({"k": value}, [value]): |
| 281 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 282 |
await send(body) |
| 283 |
assert await send.query({"k": value}) == {"k": str(value)} |
| 284 |
|
| 285 |
|
| 286 |
async def test_siblings_are_prepared_in_document_order(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 287 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 288 |
# two values drawing from one iterator are drained first to last |
| 289 |
words = iter(["FIRST", "SECOND"]) |
| 290 |
assert await send({"messages": [{"content": islice(words, 1)}, {"content": islice(words, 1)}]}) == { |
| 291 |
"messages": [{"content": ["FIRST"]}, {"content": ["SECOND"]}] |
| 292 |
} |
| 293 |
|
| 294 |
# and a reader shared by two file inputs is read by the first of them |
| 295 |
reader = io.BytesIO(b"Hello, world!") |
| 296 |
assert await send({"content": [image_block(reader), image_block(reader)]}) == { |
| 297 |
"content": [image_block("SGVsbG8sIHdvcmxkIQ=="), image_block("")] |
| 298 |
} |
| 299 |
|
| 300 |
with pytest.raises(FileNotFoundError, match="first.png"): |
| 301 |
await send({"a": b64_obj(pathlib.Path("first.png")), "b": [b64_obj(pathlib.Path("second.png"))]}) |
| 302 |
|
| 303 |
|
| 304 |
async def test_scalars(send: Send) -> None: |
| 305 |
assert await send({"s": "str", "i": 1, "f": 1.5, "t": True}) == {"s": "str", "i": 1, "f": 1.5, "t": True} |
| 306 |
assert await send("bare") == "bare" |
| 307 |
assert await send(3) == 3 |
| 308 |
|
| 309 |
|
| 310 |
async def test_scalar_subclasses_are_sent_as_their_value(send: Send) -> None: |
| 311 |
# flags are iterable since Python 3.11, each member yielding itself |
| 312 |
assert await send( |
| 313 |
{ |
| 314 |
"perm": Perm.R | Perm.W, |
| 315 |
"one": Perm.W, |
| 316 |
"none": Perm(0), |
| 317 |
"level": Level.LOW, |
| 318 |
"tag": Tag("t"), |
| 319 |
"count": Count(3), |
| 320 |
} |
| 321 |
) == {"perm": 6, "one": 2, "none": 0, "level": 1, "tag": "t", "count": 3} |
| 322 |
assert await send(Perm.W) == 2 |
| 323 |
assert await send([Perm.R | Perm.X, Tag("t")]) == [5, "t"] |
| 324 |
|
| 325 |
query = {"perm": Perm.R | Perm.W, "one": Perm.W, "none": Perm(0), "flags": re.I, "tag": Tag("t"), "count": Count(3)} |
| 326 |
assert await send.query(query) == {key: str(value) for key, value in query.items()} |
| 327 |
|
| 328 |
|
| 329 |
async def test_user_strings_are_not_iterated(send: Send) -> None: |
| 330 |
# iterating one yields one-character `UserString`s, never reaching a plain value |
| 331 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 332 |
await send({"s": UserString("ab")}) |
| 333 |
assert await send.query({"s": UserString("ab")}) == {"s": "ab"} |
| 334 |
|
| 335 |
|
| 336 |
async def test_endless_nesting_is_rejected(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 337 |
monkeypatch.setattr("anthropic._utils._prepare.MAX_DEPTH", 50) |
| 338 |
with pytest.raises(ValueError, match="maximum nesting depth"): |
| 339 |
await send({"x": Matryoshka()}) |
| 340 |
with pytest.raises(ValueError, match="maximum nesting depth"): |
| 341 |
await send.query({"x": Matryoshka()}) |
| 342 |
|
| 343 |
|
| 344 |
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) |
| 345 |
async def test_serialize_data(sync: bool) -> None: |
| 346 |
def body() -> object: |
| 347 |
return { |
| 348 |
"nested": MappingProxyType({"keep": (1, 2), "drop": omit}), |
| 349 |
"when": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc), |
| 350 |
} |
| 351 |
|
| 352 |
if sync: |
| 353 |
serialized = serialize_data(body(), location="body") |
| 354 |
assert serialized == openapi_dumps_str(prepare_request_data(body(), location="body")) |
| 355 |
else: |
| 356 |
serialized = await async_serialize_data(body(), location="body") |
| 357 |
assert serialized == openapi_dumps_str(await async_prepare_request_data(body(), location="body")) |
| 358 |
assert serialized == '{"nested":{"keep":[1,2]},"when":"2024-01-02T03:04:05+00:00"}' |
| 359 |
|
| 360 |
|
| 361 |
@pytest.mark.parametrize( |
| 362 |
"value, iso", |
| 363 |
[ |
| 364 |
pytest.param(datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc), "2024-01-02T03:04:05+00:00", id="aware"), |
| 365 |
pytest.param(datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05", id="naive"), |
| 366 |
pytest.param( |
| 367 |
datetime(2024, 1, 2, 3, 4, 5, 678901, tzinfo=timezone(timedelta(hours=-5))), |
| 368 |
"2024-01-02T03:04:05.678901-05:00", |
| 369 |
id="microseconds", |
| 370 |
), |
| 371 |
pytest.param(date(2024, 1, 2), "2024-01-02", id="date"), |
| 372 |
], |
| 373 |
) |
| 374 |
async def test_dates_are_prepared_as_iso_strings( |
| 375 |
send: Send, client: Anthropic | AsyncAnthropic, value: date, iso: str |
| 376 |
) -> None: |
| 377 |
given = {"at": value, "nested": {"at": value}, "items": (value, {"at": [value]})} |
| 378 |
expected = {"at": iso, "nested": {"at": iso}, "items": [iso, {"at": [iso]}]} |
| 379 |
|
| 380 |
# what hooks and middleware see |
| 381 |
assert prepare_request_data(given, location="query") == expected |
| 382 |
if isinstance(client, Anthropic): |
| 383 |
assert prepare_request_data(given, location="body") == expected |
| 384 |
else: |
| 385 |
assert await async_prepare_request_data(given, location="body") == expected |
| 386 |
|
| 387 |
# and what goes over the wire, in a body, a query and a multipart form |
| 388 |
assert await send(given) == expected |
| 389 |
assert await send(value) == iso |
| 390 |
assert await send({"a": 1}, extra_body=given) == {"a": 1, **expected} |
| 391 |
await send.query(expected) |
| 392 |
as_strings = send.request.url.query |
| 393 |
await send.query(given) |
| 394 |
assert send.request.url.query == as_strings |
| 395 |
await send.query(extra_query=given) |
| 396 |
assert send.request.url.query == as_strings |
| 397 |
assert iso.encode() in await send.form(given) |
| 398 |
assert await send.form(given) == await send.form(expected) |
| 399 |
|
| 400 |
|
| 401 |
async def test_preserves_key_order(send: Send) -> None: |
| 402 |
schema = {"type": "object", "properties": {"zeta": {"type": "string"}, "alpha": {"type": "integer"}, "mid": {}}} |
| 403 |
|
| 404 |
await send({"tools": ({"name": "t", "input_schema": MappingProxyType(schema), "beta": omit},), "model": "m"}) |
| 405 |
|
| 406 |
assert ( |
| 407 |
send.request.content |
| 408 |
== b'{"tools":[{"name":"t","input_schema":{"type":"object","properties":{"zeta":{"type":"string"},"alpha":{"type":"integer"},"mid":{}}}}],"model":"m"}' |
| 409 |
) |
| 410 |
|
| 411 |
|
| 412 |
async def test_pydantic_models_are_dumped(send: Send) -> None: |
| 413 |
class MyModel(BaseModel): |
| 414 |
foo: str |
| 415 |
when: datetime |
| 416 |
unset: str | None = None |
| 417 |
from_: str | None = pydantic.Field(alias="from", default=None) |
| 418 |
|
| 419 |
def make(data: dict[str, Any]) -> dict[str, MyModel]: |
| 420 |
"""The model holding `data`, made in each of the ways a model gets made.""" |
| 421 |
return { |
| 422 |
"constructor": MyModel(**data), |
| 423 |
"validation": model_parse(MyModel, data), |
| 424 |
"construct": MyModel.construct(**data), |
| 425 |
"construct_type": cast(MyModel, construct_type(type_=MyModel, value=data)), |
| 426 |
"copy": model_copy(MyModel(**data)), |
| 427 |
} |
| 428 |
|
| 429 |
when = datetime(2023, 2, 23, 14, 16, 36, tzinfo=timezone.utc) |
| 430 |
sent_when = "2023-02-23T14:16:36Z" if not PYDANTIC_V1 else "2023-02-23T14:16:36+00:00" |
| 431 |
|
| 432 |
for made, model in make({"foo": "hi", "when": when, "from": "there"}).items(): |
| 433 |
assert await send({"m": model, "l": [model]}) == { |
| 434 |
"m": {"foo": "hi", "when": sent_when, "from": "there"}, |
| 435 |
"l": [{"foo": "hi", "when": sent_when, "from": "there"}], |
| 436 |
}, made |
| 437 |
for made, model in make({"foo": "hi", "when": when, "unset": None, "other": True}).items(): |
| 438 |
# a `None` that was given counts as set, and unknown keys are kept |
| 439 |
assert await send(model) == {"foo": "hi", "when": sent_when, "unset": None, "other": True}, made |
| 440 |
|
| 441 |
assert await send(MyModel.construct(foo="hi!")) == {"foo": "hi!"} |
| 442 |
assert await send(MyModel.construct()) == {} |
| 443 |
|
| 444 |
|
| 445 |
async def test_pydantic_mismatched_types(send: Send) -> None: |
| 446 |
class MyModel(BaseModel): |
| 447 |
foo: str |
| 448 |
|
| 449 |
model = MyModel.construct(foo=True) |
| 450 |
|
| 451 |
if PYDANTIC_V1: |
| 452 |
assert await send(model) == {"foo": True} |
| 453 |
else: |
| 454 |
with pytest.warns(UserWarning): |
| 455 |
assert await send(model) == {"foo": True} |
| 456 |
|
| 457 |
|
| 458 |
async def test_api_exclude(send: Send) -> None: |
| 459 |
class Parsed(BaseModel): |
| 460 |
__api_exclude__ = {"parsed"} |
| 461 |
text: str |
| 462 |
parsed: object = None |
| 463 |
|
| 464 |
assert await send({"c": [Parsed.construct(text="x", parsed={"a": 1})]}) == {"c": [{"text": "x"}]} |
| 465 |
|
| 466 |
|
| 467 |
class LateBoundBlock(BaseModel): |
| 468 |
type: str |
| 469 |
child: LateBoundChild | None = None |
| 470 |
|
| 471 |
|
| 472 |
class LateBoundChild(BaseModel): |
| 473 |
x: int |
| 474 |
|
| 475 |
|
| 476 |
class LateBoundMessage(BaseModel): |
| 477 |
content: list[LateBoundBlock] |
| 478 |
|
| 479 |
|
| 480 |
async def test_models_with_unresolved_forward_references(send: Send) -> None: |
| 481 |
# response models may be instances of classes with unresolved forward references; the request options |
| 482 |
# holding them are still dumped for the debug log, which only works because the body was prepared first |
| 483 |
message = model_parse(LateBoundMessage, {"content": [{"type": "late"}]}) |
| 484 |
|
| 485 |
assert await send({"messages": [{"role": "assistant", "content": message.content}]}) == { |
| 486 |
"messages": [{"role": "assistant", "content": [{"type": "late"}]}] |
| 487 |
} |
| 488 |
|
| 489 |
|
| 490 |
async def test_query_params(send: Send) -> None: |
| 491 |
assert await send.query( |
| 492 |
{"created_at[gte]": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc), "x": omit, "y": not_given, "n": None}, |
| 493 |
extra_query={"x": "1"}, |
| 494 |
) == {"created_at[gte]": "2024-01-02T03:04:05+00:00", "x": "1"} |
| 495 |
assert send.request.url.query == b"created_at%5Bgte%5D=2024-01-02T03%3A04%3A05%2B00%3A00&x=1" |
| 496 |
assert await send.query({"on": date(2024, 1, 2), "flag": True, "n": 3}) == { |
| 497 |
"on": "2024-01-02", |
| 498 |
"flag": "true", |
| 499 |
"n": "3", |
| 500 |
} |
| 501 |
|
| 502 |
|
| 503 |
async def test_empty_query_params_are_left_unset(send: Send, caplog: pytest.LogCaptureFixture) -> None: |
| 504 |
caplog.set_level(logging.DEBUG, logger="anthropic._base_client") |
| 505 |
|
| 506 |
def logged_options() -> str: |
| 507 |
[message] = [m for m in (r.getMessage() for r in caplog.records) if m.startswith("Request options:")] |
| 508 |
caplog.clear() |
| 509 |
return message |
| 510 |
|
| 511 |
# so the logged request options, dumped with `exclude_unset`, only name them when there are any |
| 512 |
await send({"a": 1}) |
| 513 |
assert "'params'" not in logged_options() |
| 514 |
await send.query({"limit": 10}) |
| 515 |
assert "'params': {'limit': 10}" in logged_options() |
| 516 |
await send.query(extra_query={"limit": 10}) |
| 517 |
assert "'params': {'limit': 10}" in logged_options() |
| 518 |
|
| 519 |
|
| 520 |
async def test_extra_query_omit_removes_default_query(send: Send) -> None: |
| 521 |
default_query = {"foo": "bar", "keep": "1"} |
| 522 |
|
| 523 |
assert await send.query(extra_query={"foo": omit}, default_query=default_query) == {"keep": "1"} |
| 524 |
assert await send.query({"a": "b"}, extra_query={"other": omit, "x": not_given}, default_query=default_query) == { |
| 525 |
"foo": "bar", |
| 526 |
"keep": "1", |
| 527 |
"a": "b", |
| 528 |
} |
| 529 |
# whereas an `Omit` under `query` itself is dropped like any other |
| 530 |
assert await send.query({"foo": omit}, default_query=default_query) == {"foo": "bar", "keep": "1"} |
| 531 |
|
| 532 |
|
| 533 |
async def test_base64_file_input(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 534 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 535 |
|
| 536 |
assert await send(b64_obj("bar")) == b64_obj("bar") |
| 537 |
assert await send(b64_obj(SAMPLE_FILE_PATH)) == b64_obj(SAMPLE_FILE_BASE64) |
| 538 |
assert await send(b64_obj(io.StringIO("Hello, world!"))) == b64_obj("SGVsbG8sIHdvcmxkIQ==") |
| 539 |
assert await send(b64_obj(io.BytesIO(b"Hello, world!"))) == b64_obj("SGVsbG8sIHdvcmxkIQ==") |
| 540 |
|
| 541 |
pdf = {"type": "base64", "media_type": "application/pdf", "data": SAMPLE_FILE_PATH} |
| 542 |
assert await send({"type": "document", "source": pdf}) == { |
| 543 |
"type": "document", |
| 544 |
"source": {"type": "base64", "media_type": "application/pdf", "data": SAMPLE_FILE_BASE64}, |
| 545 |
} |
| 546 |
|
| 547 |
assert await send({"type": "base64"}) == {"type": "base64"} |
| 548 |
assert await send({"type": "base64", "data": None}) == {"type": "base64", "data": None} |
| 549 |
assert await send({"type": "base64", "data": [1]}) == {"type": "base64", "data": [1]} |
| 550 |
|
| 551 |
items = (b64_obj(SAMPLE_FILE_PATH), "given", MappingProxyType(b64_obj(io.BytesIO(b"Hello, world!")))) |
| 552 |
assert await send({"items": items}) == { |
| 553 |
"items": [b64_obj(SAMPLE_FILE_BASE64), "given", b64_obj("SGVsbG8sIHdvcmxkIQ==")] |
| 554 |
} |
| 555 |
assert await send({"items": (b for b in [b64_obj(SAMPLE_FILE_PATH)])}) == {"items": [b64_obj(SAMPLE_FILE_BASE64)]} |
| 556 |
assert await send({"x": {"a": b64_obj(SAMPLE_FILE_PATH), "b": "given"}}) == { |
| 557 |
"x": {"a": b64_obj(SAMPLE_FILE_BASE64), "b": "given"} |
| 558 |
} |
| 559 |
assert await send( |
| 560 |
{"a": 1}, extra_body={"doc": b64_obj(SAMPLE_FILE_PATH), "docs": [b64_obj(io.BytesIO(b"Hello, world!"))]} |
| 561 |
) == {"a": 1, "doc": b64_obj(SAMPLE_FILE_BASE64), "docs": [b64_obj("SGVsbG8sIHdvcmxkIQ==")]} |
| 562 |
|
| 563 |
monkeypatch.setattr(MARKERS_ATTR, ()) |
| 564 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 565 |
await send(b64_obj(SAMPLE_FILE_PATH)) |
| 566 |
|
| 567 |
|
| 568 |
async def test_get_does_not_prepare_a_body(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 569 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 570 |
pulled: list[int] = [] |
| 571 |
|
| 572 |
def items() -> Iterator[int]: |
| 573 |
pulled.append(1) |
| 574 |
yield 1 |
| 575 |
|
| 576 |
missing = b64_obj(pathlib.Path("does-not-exist.png")) |
| 577 |
|
| 578 |
# nothing of a body is sent, so nothing in it is read either |
| 579 |
assert await send.query({"a": "b"}, extra_body={"doc": missing, "items": items()}) == {"a": "b"} |
| 580 |
assert not send.request.content |
| 581 |
assert pulled == [] |
| 582 |
|
| 583 |
with pytest.raises(FileNotFoundError): |
| 584 |
await send({"a": 1}, extra_body={"doc": missing}) |
| 585 |
|
| 586 |
|
| 587 |
async def test_query_params_are_never_read(send: Send, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 588 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 589 |
path = tmp_path.joinpath("note.txt") |
| 590 |
path.write_bytes(b"not its path") |
| 591 |
content = base64.b64encode(b"not its path").decode() |
| 592 |
|
| 593 |
for query in (await send.query({"doc": b64_obj(path)}), await send.query(extra_query={"doc": b64_obj(path)})): |
| 594 |
assert str(path) in query.values() |
| 595 |
assert content not in query.values() |
| 596 |
|
| 597 |
|
| 598 |
@pytest.mark.parametrize( |
| 599 |
"body", |
| 600 |
[ |
| 601 |
pytest.param({"b": b"bytes"}, id="bytes"), |
| 602 |
pytest.param({"data": SAMPLE_FILE_PATH}, id="untyped data"), |
| 603 |
pytest.param({"type": "text", "media_type": "text/plain", "data": SAMPLE_FILE_PATH}, id="text source"), |
| 604 |
pytest.param({"type": ["base64"], "data": SAMPLE_FILE_PATH}, id="list type"), |
| 605 |
pytest.param({"type": "base64", "file": SAMPLE_FILE_PATH, "data": "given"}, id="other data key"), |
| 606 |
], |
| 607 |
) |
| 608 |
async def test_bytes_and_files_elsewhere_are_rejected( |
| 609 |
send: Send, body: object, monkeypatch: pytest.MonkeyPatch |
| 610 |
) -> None: |
| 611 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 612 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 613 |
await send(body) |
| 614 |
|
| 615 |
|
| 616 |
async def test_text_mode_files_elsewhere_are_rejected( |
| 617 |
send: Send, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch |
| 618 |
) -> None: |
| 619 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 620 |
# text-mode handles are iterables of `str` lines, but are never sent as a list of them |
| 621 |
path = tmp_path.joinpath("note.txt") |
| 622 |
path.write_text("a\nb\n") |
| 623 |
text = io.StringIO("a\nb\n") |
| 624 |
|
| 625 |
with open(path) as handle: |
| 626 |
for value in (text, handle): |
| 627 |
for body in ({"x": value}, {"l": [value]}, {"type": "text", "data": value}): |
| 628 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 629 |
await send({"nested": body}) |
| 630 |
assert value.tell() == 0 |
| 631 |
|
| 632 |
|
| 633 |
async def test_objects_with_a_read_method_are_not_files(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 634 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 635 |
# not even inside a base64 source: what gets read is decided by type, not by the methods present |
| 636 |
duck = DuckReader() |
| 637 |
|
| 638 |
for body in ({"x": duck}, {"l": [duck]}, (duck,), image_block(duck)): |
| 639 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 640 |
await send(body) |
| 641 |
|
| 642 |
assert duck.read_calls == 0 |
| 643 |
|
| 644 |
|
| 645 |
@pytest.mark.parametrize( |
| 646 |
"file", |
| 647 |
[ |
| 648 |
pytest.param(BarePathLike(), id="bare PathLike"), |
| 649 |
pytest.param(StrPath(SAMPLE_FILE_PATH), id="PathLike str"), |
| 650 |
], |
| 651 |
) |
| 652 |
async def test_other_path_likes_are_not_read(send: Send, file: object, monkeypatch: pytest.MonkeyPatch) -> None: |
| 653 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 654 |
# whether in a typed image source or in any mapping of that shape, and without looking the path up |
| 655 |
for body in (image_block(file), {"metadata": b64_obj(file)}): |
| 656 |
with pytest.raises(TypeError, match="only pathlib.Path and file objects are read") as exc_info: |
| 657 |
await send(body) |
| 658 |
assert str(exc_info.value).startswith(f"Cannot read {type(file)};") |
| 659 |
|
| 660 |
|
| 661 |
async def test_file_objects_must_read_as_bytes(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 662 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 663 |
|
| 664 |
class OddReader(io.RawIOBase): |
| 665 |
@override |
| 666 |
def read(self, size: int = -1) -> Any: # noqa: ARG002 |
| 667 |
return 3 |
| 668 |
|
| 669 |
with pytest.raises(RuntimeError, match="Could not read bytes from .*; Received <class 'int'>"): |
| 670 |
await send(b64_obj(OddReader())) |
| 671 |
|
| 672 |
|
| 673 |
async def test_pathlike_str_outside_file_slots_is_a_string(send: Send, monkeypatch: pytest.MonkeyPatch) -> None: |
| 674 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 675 |
body = {"foo": StrPath("tests/sample_file.txt"), "items": [StrPath("x")]} |
| 676 |
|
| 677 |
assert await send(body) == {"foo": "tests/sample_file.txt", "items": ["x"]} |
| 678 |
|
| 679 |
|
| 680 |
def layout(value: object) -> object: |
| 681 |
"""The identity and contents of `value` and of everything inside it.""" |
| 682 |
contents = value |
| 683 |
if is_mapping(value): |
| 684 |
contents = [(key, layout(item)) for key, item in value.items()] |
| 685 |
elif is_sequence(value) and not isinstance(value, str): |
| 686 |
contents = [layout(item) for item in value] |
| 687 |
return id(value), type(value), contents |
| 688 |
|
| 689 |
|
| 690 |
@pytest.mark.parametrize( |
| 691 |
"make_body, sent", |
| 692 |
[ |
| 693 |
pytest.param( |
| 694 |
lambda: {"a": {"b": omit, "c": 1}, "items": [{"d": None}, ({"t": (1, 2)},)]}, |
| 695 |
{"a": {"c": 1}, "items": [{"d": None}, [{"t": [1, 2]}]]}, |
| 696 |
id="nested", |
| 697 |
), |
| 698 |
pytest.param( |
| 699 |
lambda: { |
| 700 |
"a": [{"b": omit, "c": (1, 2)}], |
| 701 |
"foo": b64_obj(SAMPLE_FILE_PATH), |
| 702 |
"items": [(b64_obj(SAMPLE_FILE_PATH),)], |
| 703 |
}, |
| 704 |
{"a": [{"c": [1, 2]}], "foo": b64_obj(SAMPLE_FILE_BASE64), "items": [[b64_obj(SAMPLE_FILE_BASE64)]]}, |
| 705 |
id="path", |
| 706 |
), |
| 707 |
pytest.param( |
| 708 |
lambda: {"doc": b64_obj(io.BytesIO(b"Hello, world!"))}, |
| 709 |
{"doc": b64_obj("SGVsbG8sIHdvcmxkIQ==")}, |
| 710 |
id="file object", |
| 711 |
), |
| 712 |
], |
| 713 |
) |
| 714 |
async def test_idempotent_and_does_not_mutate_input( |
| 715 |
send: Send, make_body: Callable[[], object], sent: object, monkeypatch: pytest.MonkeyPatch |
| 716 |
) -> None: |
| 717 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 718 |
body = make_body() |
| 719 |
before = layout(body) |
| 720 |
|
| 721 |
assert await send(body) == sent |
| 722 |
assert layout(body) == before |
| 723 |
assert await send(sent) == sent |
| 724 |
|
| 725 |
|
| 726 |
async def test_deep_nesting(send: Send, client: Anthropic | AsyncAnthropic, monkeypatch: pytest.MonkeyPatch) -> None: |
| 727 |
monkeypatch.setattr(MARKERS_ATTR, MARKERS) |
| 728 |
|
| 729 |
# untyped JSON fields (`input_schema`, ...) can nest past the recursion limit |
| 730 |
def nested(depth: int) -> object: |
| 731 |
data: object = {"type": "base64", "dropped": omit, "data": SAMPLE_FILE_PATH} |
| 732 |
for i in range(depth): |
| 733 |
data = {"k": data} if i % 2 else (data,) |
| 734 |
return data |
| 735 |
|
| 736 |
depth = 5 * sys.getrecursionlimit() |
| 737 |
if isinstance(client, Anthropic): |
| 738 |
prepared = prepare_request_data(nested(depth), location="body") |
| 739 |
else: |
| 740 |
prepared = await async_prepare_request_data(nested(depth), location="body") |
| 741 |
for i in reversed(range(depth)): |
| 742 |
prepared = prepared["k"] if i % 2 else prepared[0] |
| 743 |
assert prepared == {"type": "base64", "data": SAMPLE_FILE_BASE64} |
| 744 |
|
| 745 |
# sent end to end from less deep only because `json` itself recurses once per level before Python 3.12 |
| 746 |
depth = sys.getrecursionlimit() - 100 |
| 747 |
await send({"metadata": nested(depth)}) |
| 748 |
|
| 749 |
assert send.request.content.endswith( |
| 750 |
b'{"type":"base64","data":"SGVsbG8sIHdvcmxkIQo="}' + b"]}" * (depth // 2) + b"}" |
| 751 |
) |
| 752 |
|
| 753 |
|
| 754 |
async def test_circular_reference(send: Send) -> None: |
| 755 |
self_dict: dict[str, object] = {} |
| 756 |
self_dict["self"] = self_dict |
| 757 |
with pytest.raises(ValueError, match="Circular reference detected"): |
| 758 |
await send({"metadata": self_dict}) |
| 759 |
|
| 760 |
self_list: list[object] = [] |
| 761 |
self_list.append(self_list) |
| 762 |
with pytest.raises(ValueError, match="Circular reference detected"): |
| 763 |
await send({"items": self_list}) |
| 764 |
|
| 765 |
inner: dict[str, object] = {} |
| 766 |
indirect = {"a": [{"b": (inner,)}]} |
| 767 |
inner["back"] = indirect |
| 768 |
with pytest.raises(ValueError, match="Circular reference detected"): |
| 769 |
await send(indirect) |
| 770 |
|
| 771 |
shared = {"a": 1, "l": [{"b": 2}]} |
| 772 |
assert await send({"x": shared, "y": shared, "both": (shared, shared)}) == { |
| 773 |
"x": shared, |
| 774 |
"y": shared, |
| 775 |
"both": [shared, shared], |
| 776 |
} |
| 777 |
|
| 778 |
# freed generator items can have their `id()` reused by later ones; that must not read as a cycle |
| 779 |
def rows() -> Iterator[dict[str, object]]: |
| 780 |
for i in range(50): |
| 781 |
yield {"k": [i]} |
| 782 |
|
| 783 |
def pages() -> Iterator[dict[str, object]]: |
| 784 |
for _ in range(3): |
| 785 |
yield {"x": rows()} |
| 786 |
|
| 787 |
assert await send({"items": pages()}) == {"items": [{"x": [{"k": [i]} for i in range(50)]} for _ in range(3)]} |
| 788 |
|
| 789 |
|
| 790 |
class TestClient: |
| 791 |
# the route stays uncalled when the package has no file input markers |
| 792 |
@pytest.mark.respx(base_url=base_url, assert_all_called=False) |
| 793 |
async def test_file_input_markers(self, respx_mock: MockRouter, client: Anthropic | AsyncAnthropic) -> None: |
| 794 |
route = respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={})) |
| 795 |
sources = [{discriminator: tag, field: SAMPLE_FILE_PATH} for discriminator, tag, field in FILE_INPUT_MARKERS] |
| 796 |
prepared = [{discriminator: tag, field: SAMPLE_FILE_BASE64} for discriminator, tag, field in FILE_INPUT_MARKERS] |
| 797 |
unmatched = {discriminator: [tag] for discriminator, tag, _ in FILE_INPUT_MARKERS} |
| 798 |
|
| 799 |
if isinstance(client, Anthropic): |
| 800 |
for source in sources: |
| 801 |
client.post("/foo", body={"x": source}, cast_to=httpx2.Response) |
| 802 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 803 |
client.post("/foo", body={"x": {**unmatched, "data": SAMPLE_FILE_PATH}}, cast_to=httpx2.Response) |
| 804 |
else: |
| 805 |
for source in sources: |
| 806 |
await client.post("/foo", body={"x": source}, cast_to=httpx2.Response) |
| 807 |
with pytest.raises(TypeError, match="is not JSON serializable"): |
| 808 |
await client.post("/foo", body={"x": {**unmatched, "data": SAMPLE_FILE_PATH}}, cast_to=httpx2.Response) |
| 809 |
|
| 810 |
assert route.call_count == len(FILE_INPUT_MARKERS) |
| 811 |
bodies = [json.loads(call.request.content) for call in cast("list[MockRequestCall]", route.calls)] |
| 812 |
assert bodies == [{"x": source} for source in prepared] |
| 813 |
|
| 814 |
@pytest.mark.respx(base_url=base_url) |
| 815 |
async def test_generator_body_survives_retries( |
| 816 |
self, respx_mock: MockRouter, client: Anthropic | AsyncAnthropic, monkeypatch: pytest.MonkeyPatch |
| 817 |
) -> None: |
| 818 |
monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _no_retry_delay) |
| 819 |
route = respx_mock.post("/foo").mock( |
| 820 |
side_effect=[httpx2.Response(500, json={}), httpx2.Response(200, json={})], |
| 821 |
) |
| 822 |
body = {"items": ({"i": i} for i in range(2))} |
| 823 |
options = make_request_options(extra_body={"x": (i for i in range(3))}) |
| 824 |
|
| 825 |
if isinstance(client, Anthropic): |
| 826 |
client.with_options(max_retries=1).post("/foo", body=body, options=options, cast_to=httpx2.Response) |
| 827 |
else: |
| 828 |
await client.with_options(max_retries=1).post("/foo", body=body, options=options, cast_to=httpx2.Response) |
| 829 |
|
| 830 |
assert route.call_count == 2 |
| 831 |
calls = cast("list[MockRequestCall]", route.calls) |
| 832 |
assert [c.request.content for c in calls] == [b'{"items":[{"i":0},{"i":1}],"x":[0,1,2]}'] * 2 |
| 833 |
|
| 834 |
@pytest.mark.respx(base_url=base_url) |
| 835 |
async def test_extra_query_iterator_survives_pagination( |
| 836 |
self, respx_mock: MockRouter, client: Anthropic | AsyncAnthropic |
| 837 |
) -> None: |
| 838 |
route = respx_mock.get("/foo").mock( |
| 839 |
side_effect=[ |
| 840 |
httpx2.Response(200, json={"data": [{"id": "1"}], "last_id": "c1", "has_more": True}), |
| 841 |
httpx2.Response(200, json={"data": [{"id": "2"}], "last_id": None, "has_more": False}), |
| 842 |
] |
| 843 |
) |
| 844 |
options = make_request_options(query={"limit": 1}, extra_query={"tags": iter(["red", "blue"])}) |
| 845 |
|
| 846 |
if isinstance(client, Anthropic): |
| 847 |
pages = client.get_api_list("/foo", model=Item, page=SyncPage[Item], options=options) |
| 848 |
ids = [item.id for item in pages] |
| 849 |
else: |
| 850 |
async_pages = client.get_api_list("/foo", model=Item, page=AsyncPage[Item], options=options) |
| 851 |
ids = [item.id async for item in async_pages] |
| 852 |
|
| 853 |
assert ids == ["1", "2"] |
| 854 |
first, second = (call.request.url for call in cast("list[MockRequestCall]", route.calls)) |
| 855 |
assert b"red" in first.query and b"blue" in first.query |
| 856 |
assert second.params["after_id"] == "c1" |
| 857 |
assert second.copy_remove_param("after_id").query == first.query |