Debian Codegraph @

tests/lib/test_stainless_helpers.py

raw
1 from __future__ import annotations
2
3 import json
4
5 import respx
6 import httpx2
7 import pytest
8
9 from anthropic import Anthropic, AsyncAnthropic, _compat
10 from anthropic.types.beta import BetaToolParam
11 from anthropic._base_client import _APPEND_HEADERS
12 from anthropic.lib._stainless_helpers import (
13 STAINLESS_HELPER_HEADER,
14 tag_helper,
15 helper_header,
16 )
17
18 from ..conftest import base_url
19
20
21 class _Tool:
22 """Stands in for a `@beta_tool` / toolset object: `tools=` takes anything with a `to_dict()`."""
23
24 def to_dict(self) -> BetaToolParam:
25 return {"name": "t", "description": "d", "input_schema": {"type": "object"}}
26
27
28 class _TaggedTuple(tuple): # type: ignore[type-arg]
29 """Same for file tuples, mirroring `mcp_resource_to_file`'s return value."""
30
31
32 def test_helper_header() -> None:
33 assert helper_header("BetaToolRunner") == {STAINLESS_HELPER_HEADER: "BetaToolRunner"}
34
35
36 def test_helper_header_is_an_append_header() -> None:
37 # `merge_headers` only appends keys it knows about — keep this aligned
38 assert STAINLESS_HELPER_HEADER in _APPEND_HEADERS
39
40
41 def _message_json() -> dict[str, object]:
42 return {
43 "id": "msg_abc123",
44 "type": "message",
45 "role": "assistant",
46 "model": "claude-sonnet-4-5",
47 "content": [{"type": "text", "text": "hi"}],
48 "stop_reason": "end_turn",
49 "stop_sequence": None,
50 "usage": {"input_tokens": 1, "output_tokens": 1},
51 }
52
53
54 def _file_json() -> dict[str, object]:
55 return {
56 "id": "file_abc123",
57 "type": "file",
58 "created_at": "2026-01-01T00:00:00Z",
59 "filename": "data.json",
60 "mime_type": "application/json",
61 "size_bytes": 2,
62 }
63
64
65 @pytest.mark.respx(base_url=base_url)
66 class TestSyncWireHeaders:
67 def test_caller_tag_is_appended_not_clobbered(self, client: Anthropic, respx_mock: respx.MockRouter) -> None:
68 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
69
70 tool = _Tool()
71 tag_helper(tool, "mcp_tool")
72 client.beta.messages.create(
73 model="claude-sonnet-4-5",
74 max_tokens=16,
75 messages=[{"role": "user", "content": "hello"}],
76 tools=[tool],
77 extra_headers={"X-Stainless-Helper": "caller-tag"},
78 )
79
80 request = respx_mock.calls.last.request
81 values = request.headers.get_list(STAINLESS_HELPER_HEADER)
82 assert values == ["mcp_tool, caller-tag"]
83 assert json.loads(request.content)["tools"] == [tool.to_dict()]
84
85 def test_file_upload_tag_is_appended_not_clobbered(self, client: Anthropic, respx_mock: respx.MockRouter) -> None:
86 respx_mock.post("/v1/files").mock(return_value=httpx2.Response(200, json=_file_json()))
87
88 file = _TaggedTuple(("data.json", b"{}", "application/json"))
89 tag_helper(file, "mcp_resource_to_file")
90 client.files.upload(file=file, extra_headers={"X-Stainless-Helper": "caller-tag"})
91
92 request = respx_mock.calls.last.request
93 values = request.headers.get_list(STAINLESS_HELPER_HEADER)
94 assert values == ["mcp_resource_to_file, caller-tag"]
95
96 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only")
97 def test_parse_sends_single_header_line(self, client: Anthropic, respx_mock: respx.MockRouter) -> None:
98 # regression: the literal tag and the collected tags used to land under
99 # two casings of the key, producing two header lines on the wire
100 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
101
102 client.beta.messages.parse(
103 model="claude-sonnet-4-5",
104 max_tokens=16,
105 messages=[{"role": "user", "content": "hello"}],
106 tools=[_Tool()],
107 )
108
109 request = respx_mock.calls.last.request
110 values = request.headers.get_list(STAINLESS_HELPER_HEADER)
111 assert values == ["beta.messages.parse"]
112 assert json.loads(request.content)["tools"] == [_Tool().to_dict()]
113
114 def test_count_tokens_takes_a_tool_object(self, client: Anthropic, respx_mock: respx.MockRouter) -> None:
115 respx_mock.post("/v1/messages/count_tokens").mock(return_value=httpx2.Response(200, json={"input_tokens": 3}))
116 result = client.beta.messages.count_tokens(
117 model="claude-sonnet-4-5", messages=[{"role": "user", "content": "hello"}], tools=[_Tool()]
118 )
119 assert result.input_tokens == 3
120 assert json.loads(respx_mock.calls.last.request.content)["tools"] == [_Tool().to_dict()]
121
122 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only")
123 def test_parse_merges_caller_extra_headers(self, client: Anthropic, respx_mock: respx.MockRouter) -> None:
124 # caller-supplied betas, user_profile_id, and extra_headers must all
125 # survive parse()'s merge alongside the helper tag
126 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
127
128 client.beta.messages.parse(
129 model="claude-sonnet-4-5",
130 max_tokens=16,
131 messages=[{"role": "user", "content": "hello"}],
132 betas=["fake-beta-2026-01-01"],
133 user_profile_id="upi_123",
134 extra_headers={"X-Custom": "1", "X-Stainless-Helper": "caller-tag"},
135 )
136
137 headers = respx_mock.calls.last.request.headers
138 assert headers["anthropic-beta"] == "fake-beta-2026-01-01"
139 assert headers["anthropic-user-profile-id"] == "upi_123"
140 assert headers["X-Custom"] == "1"
141 # helper tag accumulates with the caller's on one line (append-header semantics)
142 assert headers.get_list(STAINLESS_HELPER_HEADER) == ["beta.messages.parse, caller-tag"]
143
144 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only")
145 def test_parse_caller_beta_header_overrides(self, client: Anthropic, respx_mock: respx.MockRouter) -> None:
146 # extra_headers win outright on non-append headers, matching create()
147 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
148
149 client.beta.messages.parse(
150 model="claude-sonnet-4-5",
151 max_tokens=16,
152 messages=[{"role": "user", "content": "hello"}],
153 extra_headers={"anthropic-beta": "explicit-only"},
154 )
155
156 headers = respx_mock.calls.last.request.headers
157 assert headers["anthropic-beta"] == "explicit-only"
158
159
160 @pytest.mark.respx(base_url=base_url)
161 class TestAsyncWireHeaders:
162 async def test_caller_tag_is_appended_not_clobbered(
163 self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter
164 ) -> None:
165 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
166
167 tool = _Tool()
168 tag_helper(tool, "mcp_tool")
169 await async_client.beta.messages.create(
170 model="claude-sonnet-4-5",
171 max_tokens=16,
172 messages=[{"role": "user", "content": "hello"}],
173 tools=[tool],
174 extra_headers={"X-Stainless-Helper": "caller-tag"},
175 )
176
177 request = respx_mock.calls.last.request
178 values = request.headers.get_list(STAINLESS_HELPER_HEADER)
179 assert values == ["mcp_tool, caller-tag"]
180 assert json.loads(request.content)["tools"] == [tool.to_dict()]
181
182 async def test_file_upload_tag_is_appended_not_clobbered(
183 self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter
184 ) -> None:
185 respx_mock.post("/v1/files").mock(return_value=httpx2.Response(200, json=_file_json()))
186
187 file = _TaggedTuple(("data.json", b"{}", "application/json"))
188 tag_helper(file, "mcp_resource_to_file")
189 await async_client.files.upload(file=file, extra_headers={"X-Stainless-Helper": "caller-tag"})
190
191 request = respx_mock.calls.last.request
192 values = request.headers.get_list(STAINLESS_HELPER_HEADER)
193 assert values == ["mcp_resource_to_file, caller-tag"]
194
195 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only")
196 async def test_parse_sends_single_header_line(
197 self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter
198 ) -> None:
199 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
200
201 await async_client.beta.messages.parse(
202 model="claude-sonnet-4-5",
203 max_tokens=16,
204 messages=[{"role": "user", "content": "hello"}],
205 tools=[_Tool()],
206 )
207
208 request = respx_mock.calls.last.request
209 values = request.headers.get_list(STAINLESS_HELPER_HEADER)
210 assert values == ["beta.messages.parse"]
211 assert json.loads(request.content)["tools"] == [_Tool().to_dict()]
212
213 async def test_count_tokens_takes_a_tool_object(
214 self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter
215 ) -> None:
216 respx_mock.post("/v1/messages/count_tokens").mock(return_value=httpx2.Response(200, json={"input_tokens": 3}))
217 result = await async_client.beta.messages.count_tokens(
218 model="claude-sonnet-4-5", messages=[{"role": "user", "content": "hello"}], tools=[_Tool()]
219 )
220 assert result.input_tokens == 3
221 assert json.loads(respx_mock.calls.last.request.content)["tools"] == [_Tool().to_dict()]
222
223 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only")
224 async def test_parse_merges_caller_extra_headers(
225 self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter
226 ) -> None:
227 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
228
229 await async_client.beta.messages.parse(
230 model="claude-sonnet-4-5",
231 max_tokens=16,
232 messages=[{"role": "user", "content": "hello"}],
233 betas=["fake-beta-2026-01-01"],
234 user_profile_id="upi_123",
235 extra_headers={"X-Custom": "1", "X-Stainless-Helper": "caller-tag"},
236 )
237
238 headers = respx_mock.calls.last.request.headers
239 assert headers["anthropic-beta"] == "fake-beta-2026-01-01"
240 assert headers["anthropic-user-profile-id"] == "upi_123"
241 assert headers["X-Custom"] == "1"
242 assert headers.get_list(STAINLESS_HELPER_HEADER) == ["beta.messages.parse, caller-tag"]
243
244 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse() response post-parser is pydantic-v2 only")
245 async def test_parse_caller_beta_header_overrides(
246 self, async_client: AsyncAnthropic, respx_mock: respx.MockRouter
247 ) -> None:
248 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, json=_message_json()))
249
250 await async_client.beta.messages.parse(
251 model="claude-sonnet-4-5",
252 max_tokens=16,
253 messages=[{"role": "user", "content": "hello"}],
254 extra_headers={"anthropic-beta": "explicit-only"},
255 )
256
257 headers = respx_mock.calls.last.request.headers
258 assert headers["anthropic-beta"] == "explicit-only"