Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 299 lines 10 KB
Raw
1 """HTTP status errors from the generated client must be ``ComposioError``s.
2
3 The generated client (``composio_client``) has its own exception root, so an
4 invalid API key or any other 4xx/5xx response used to escape
5 ``except ComposioError`` (issue #4537). ``HttpClient`` now builds those errors
6 as subclasses of both the generated class and ``ComposioError``, so SDK callers
7 can catch one root while existing ``except APIStatusError`` handlers, including
8 the SDK's own, keep working.
9 """
10
11 import copy
12 import pickle
13 import typing as t
14 from unittest.mock import Mock
15
16 import composio_client
17 import httpx
18 import pytest
19 from composio_client import ProjectAuth
20
21 from composio import api_error_details, exceptions
22 from composio.client import HttpClient
23 from composio.core.models.base import allow_tracking
24 from composio.core.models.tools import Tools
25 from composio.core.models.triggers import Triggers
26
27
28 @pytest.fixture(autouse=True)
29 def disable_telemetry():
30 """Disable telemetry for all tests to prevent thread issues."""
31 token = allow_tracking.set(False)
32 yield
33 allow_tracking.reset(token)
34
35
36 def _client_returning(
37 status: int,
38 *,
39 max_retries: int = 0,
40 calls: t.Optional[t.List[httpx.Request]] = None,
41 body: t.Optional[object] = None,
42 ) -> HttpClient:
43 def handler(request: httpx.Request) -> httpx.Response:
44 if calls is not None:
45 calls.append(request)
46 return httpx.Response(
47 status,
48 json=body if body is not None else {"error": {"message": "nope"}},
49 # Keep retry backoff short in tests.
50 headers={"retry-after-ms": "1"},
51 )
52
53 return HttpClient(
54 provider="test",
55 auth=ProjectAuth("sk-test"),
56 base_url="https://backend.invalid",
57 max_retries=max_retries,
58 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
59 )
60
61
62 @pytest.mark.parametrize(
63 ("status", "client_error"),
64 [
65 (400, composio_client.BadRequestError),
66 (401, composio_client.AuthenticationError),
67 (403, composio_client.PermissionDeniedError),
68 (404, composio_client.NotFoundError),
69 (409, composio_client.ConflictError),
70 (422, composio_client.UnprocessableEntityError),
71 (429, composio_client.RateLimitError),
72 (500, composio_client.InternalServerError),
73 (418, composio_client.APIStatusError),
74 ],
75 )
76 def test_status_errors_are_composio_errors(
77 status: int, client_error: t.Type[composio_client.APIStatusError]
78 ) -> None:
79 client = _client_returning(status)
80
81 with pytest.raises(exceptions.ComposioError) as exc_info:
82 client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
83
84 error = exc_info.value
85 assert isinstance(error, client_error)
86 assert isinstance(error, composio_client.APIStatusError)
87 assert error.status_code == status
88 assert error.message
89
90
91 def test_status_error_exposes_the_server_error_details() -> None:
92 body = {
93 "error": {
94 "message": "toolkit GMAIL version 20250114_00 is retired and can no longer be executed",
95 "code": 1410,
96 "slug": "TOOLKIT_VERSION_RETIRED",
97 "status": 410,
98 "request_id": "req_body",
99 "suggested_fix": "Pin 20261101_00",
100 }
101 }
102 client = _client_returning(410, body=body)
103
104 with pytest.raises(composio_client.APIStatusError) as exc_info:
105 client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
106
107 error = exc_info.value
108 details = api_error_details(error)
109 assert error.status_code == 410
110 assert details.api_error_code == 1410
111 assert details.suggested_fix == "Pin 20261101_00"
112 assert details.possible_fixes == ["Pin 20261101_00"]
113 assert error.request_id == "req_body"
114 assert "toolkit GMAIL version 20250114_00 is retired" in str(error)
115 assert "{" not in str(error)
116
117
118 def test_status_errors_strip_control_characters() -> None:
119 body = {
120 "error": {
121 "message": "denied\x1b[31m\n[!] run: evil",
122 "code": 1403,
123 "slug": "FORBIDDEN",
124 "status": 403,
125 "suggested_fix": "retry\x1b]0;owned\x07 now",
126 }
127 }
128 client = _client_returning(403, body=body)
129
130 with pytest.raises(composio_client.PermissionDeniedError) as exc_info:
131 client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
132
133 error = exc_info.value
134 details = api_error_details(error)
135 assert "denied [!] run: evil" in str(error)
136 assert details.suggested_fix == "retry now"
137 assert details.possible_fixes == ["retry now"]
138 assert not any(ord(char) < 32 or 127 <= ord(char) <= 159 for char in str(error))
139
140
141 def test_possible_fixes_fall_back_to_the_status() -> None:
142 body = {
143 "error": {
144 "message": "connected account belongs to another project",
145 "code": 1403,
146 "slug": "FORBIDDEN",
147 "status": 403,
148 }
149 }
150 client = _client_returning(403, body=body)
151
152 with pytest.raises(composio_client.PermissionDeniedError) as exc_info:
153 client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
154
155 details = api_error_details(exc_info.value)
156 assert details.api_error_code == 1403
157 assert details.suggested_fix is None
158 assert details.possible_fixes == [
159 "Ensure your API key and the connected account are allowed to run this tool"
160 ]
161
162
163 def test_possible_fixes_use_the_api_error_code_for_a_missing_account() -> None:
164 body = {
165 "error": {
166 "message": "No connected account found",
167 "code": 1803,
168 "slug": "CONNECTED_ACCOUNT_NOT_FOUND",
169 "status": 400,
170 }
171 }
172 client = _client_returning(400, body=body)
173
174 with pytest.raises(composio_client.BadRequestError) as exc_info:
175 client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
176
177 details = api_error_details(exc_info.value)
178 assert details.possible_fixes == [
179 "Ensure the connected account exists and is active in your Composio dashboard"
180 ]
181
182
183 def test_possible_fixes_do_not_blame_the_slug_for_a_rate_limit() -> None:
184 body = {
185 "error": {
186 "message": "slow down",
187 "code": 1429,
188 "slug": "RATE_LIMITED",
189 "status": 429,
190 }
191 }
192 client = _client_returning(429, body=body)
193
194 with pytest.raises(composio_client.RateLimitError) as exc_info:
195 client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
196
197 details = api_error_details(exc_info.value)
198 assert details.possible_fixes == [
199 "Wait before retrying",
200 "Reduce how many requests your organization sends per minute",
201 ]
202
203
204 def test_status_error_without_the_envelope_has_no_api_details() -> None:
205 client = _client_returning(400, body={"unexpected": True})
206
207 with pytest.raises(composio_client.APIStatusError) as exc_info:
208 client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
209
210 details = api_error_details(exc_info.value)
211 assert details.api_error_code is None
212 assert details.suggested_fix is None
213 assert details.possible_fixes == [
214 "Ensure the tool slug is correct and the input arguments for the tool is valid"
215 ]
216
217
218 def test_invalid_api_key_is_catchable_as_composio_error() -> None:
219 client = _client_returning(401)
220
221 try:
222 client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
223 except exceptions.ComposioError as error:
224 assert isinstance(error, composio_client.AuthenticationError)
225 else:
226 pytest.fail("expected the 401 to raise")
227
228
229 def test_error_classes_are_reused_across_requests() -> None:
230 client = _client_returning(401)
231 raised = []
232 for _ in range(2):
233 with pytest.raises(composio_client.AuthenticationError) as exc_info:
234 client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
235 raised.append(type(exc_info.value))
236
237 assert raised[0] is raised[1]
238 assert raised[0].__name__ == "AuthenticationError"
239
240
241 def test_schema_fetch_auth_error_is_a_composio_error() -> None:
242 tools = Tools(client=_client_returning(401), provider=Mock())
243
244 with pytest.raises(composio_client.AuthenticationError) as exc_info:
245 tools.get_raw_composio_tool_by_slug("SLACK_FETCH_CONVERSATION_HISTORY")
246
247 assert isinstance(exc_info.value, exceptions.ComposioError)
248 assert not isinstance(exc_info.value, exceptions.ToolNotFoundError)
249
250
251 def test_trigger_type_not_found_mapping_still_applies() -> None:
252 triggers = Triggers(client=_client_returning(404))
253
254 with pytest.raises(exceptions.TriggerTypeNotFound) as exc_info:
255 triggers.create(slug="NONEXISTENT_TRIGGER", user_id="user")
256
257 assert isinstance(exc_info.value.__cause__, composio_client.NotFoundError)
258
259
260 def test_without_retries_client_raises_composio_error() -> None:
261 client = _client_returning(401)
262
263 with pytest.raises(exceptions.ComposioError) as exc_info:
264 client.without_retries.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
265
266 assert isinstance(exc_info.value, composio_client.AuthenticationError)
267
268
269 def test_error_after_exhausted_retries_is_composio_error() -> None:
270 calls: t.List[httpx.Request] = []
271 client = _client_returning(503, max_retries=2, calls=calls)
272
273 with pytest.raises(exceptions.ComposioError) as exc_info:
274 client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
275
276 assert isinstance(exc_info.value, composio_client.InternalServerError)
277 assert len(calls) == 3
278
279
280 @pytest.mark.parametrize(
281 "clone",
282 [lambda error: pickle.loads(pickle.dumps(error)), copy.deepcopy],
283 ids=["pickle", "deepcopy"],
284 )
285 def test_status_errors_survive_serialization(
286 clone: t.Callable[[BaseException], BaseException],
287 ) -> None:
288 client = _client_returning(401)
289 with pytest.raises(exceptions.ComposioError) as exc_info:
290 client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
291 error = exc_info.value
292
293 restored = clone(error)
294
295 assert type(restored) is type(error)
296 assert isinstance(restored, composio_client.AuthenticationError)
297 assert isinstance(restored, exceptions.ComposioError)
298 assert t.cast(composio_client.APIStatusError, restored).status_code == 401
299 assert str(restored) == str(error)