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 410 lines 14.9 KB
Raw
1 """Tests for the ``composio.webhooks`` namespace."""
2
3 import warnings
4 from unittest.mock import Mock
5
6 import pytest
7 from composio_client import omit
8 from composio_client.types import (
9 WebhookSubscriptionCreateResponse,
10 WebhookSubscriptionListResponse,
11 )
12
13 from composio import exceptions
14 from composio.core.models.triggers import Triggers
15 from composio.core.models.triggers import WebhookVersion as TriggersWebhookVersion
16 from composio.core.models.webhooks import (
17 WebhookEndpoints,
18 Webhooks,
19 WebhookSubscriptions,
20 WebhookVersion,
21 )
22 from tests.conftest import mock_http_client
23
24
25 @pytest.fixture
26 def mock_client() -> Mock:
27 client = mock_http_client()
28 client.webhook_subscriptions = Mock()
29 client.webhook_endpoints = Mock()
30 return client
31
32
33 @pytest.fixture
34 def subscriptions(mock_client: Mock) -> WebhookSubscriptions:
35 return WebhookSubscriptions(client=mock_client)
36
37
38 @pytest.fixture
39 def endpoints(mock_client: Mock) -> WebhookEndpoints:
40 return WebhookEndpoints(client=mock_client)
41
42
43 class TestWebhooksNamespace:
44 def test_mounts_sub_namespaces(self, mock_client):
45 webhooks = Webhooks(client=mock_client)
46
47 assert isinstance(webhooks.subscriptions, WebhookSubscriptions)
48 assert isinstance(webhooks.endpoints, WebhookEndpoints)
49 assert webhooks.subscriptions._client is mock_client
50 assert webhooks.endpoints._client is mock_client
51
52 def test_webhook_version_is_shared_with_triggers(self):
53 assert TriggersWebhookVersion is WebhookVersion
54
55
56 class TestWebhookSubscriptions:
57 def test_list(self, subscriptions, mock_client):
58 mock_client.webhook_subscriptions.list.return_value = "listed"
59
60 assert subscriptions.list() == "listed"
61 mock_client.webhook_subscriptions.list.assert_called_once_with(
62 limit=omit, cursor=omit
63 )
64
65 def test_list_forwards_pagination(self, subscriptions, mock_client):
66 subscriptions.list(limit=5, cursor="abc")
67
68 mock_client.webhook_subscriptions.list.assert_called_once_with(
69 limit=5, cursor="abc"
70 )
71
72 def test_get(self, subscriptions, mock_client):
73 mock_client.webhook_subscriptions.retrieve.return_value = "sub"
74
75 assert subscriptions.get("sub_123") == "sub"
76 mock_client.webhook_subscriptions.retrieve.assert_called_once_with("sub_123")
77
78 def test_update_omits_absent_fields(self, subscriptions, mock_client):
79 mock_client.webhook_subscriptions.update.return_value = "updated"
80
81 assert subscriptions.update("sub_123", webhook_url="https://x") == "updated"
82 mock_client.webhook_subscriptions.update.assert_called_once_with(
83 "sub_123", webhook_url="https://x", enabled_events=omit, version=omit
84 )
85
86 def test_update_normalizes_events_and_version(self, subscriptions, mock_client):
87 subscriptions.update(
88 "sub_123",
89 enabled_events=("composio.trigger.message",),
90 version=WebhookVersion.V2,
91 )
92
93 mock_client.webhook_subscriptions.update.assert_called_once_with(
94 "sub_123",
95 webhook_url=omit,
96 enabled_events=["composio.trigger.message"],
97 version="V2",
98 )
99
100 def test_delete(self, subscriptions, mock_client):
101 mock_client.webhook_subscriptions.delete.return_value = "deleted"
102
103 assert subscriptions.delete("sub_123") == "deleted"
104 mock_client.webhook_subscriptions.delete.assert_called_once_with("sub_123")
105
106 def test_rotate_secret(self, subscriptions, mock_client):
107 mock_client.webhook_subscriptions.rotate_secret.return_value = "rotated"
108
109 assert subscriptions.rotate_secret("sub_123") == "rotated"
110 mock_client.webhook_subscriptions.rotate_secret.assert_called_once_with(
111 "sub_123"
112 )
113
114 def test_list_event_types(self, subscriptions, mock_client):
115 mock_client.webhook_subscriptions.list_event_types.return_value = "types"
116
117 assert subscriptions.list_event_types() == "types"
118 mock_client.webhook_subscriptions.list_event_types.assert_called_once_with()
119
120
121 class TestWebhookSubscriptionsSet:
122 def test_creates_when_none_exists(self, subscriptions, mock_client):
123 webhook_url = "https://example.com/webhooks/composio"
124 raw = {
125 "id": "sub_123",
126 "webhook_url": webhook_url,
127 "version": "V3",
128 "enabled_events": ["composio.trigger.message"],
129 "secret": "whsec_abc",
130 }
131 mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
132 mock_client.webhook_subscriptions.create.return_value = raw
133
134 result = subscriptions.set(webhook_url=webhook_url)
135
136 mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1)
137 mock_client.webhook_subscriptions.create.assert_called_once_with(
138 webhook_url=webhook_url,
139 enabled_events=["composio.trigger.message"],
140 version="V3",
141 )
142 mock_client.webhook_subscriptions.update.assert_not_called()
143 assert result == raw
144
145 def test_updates_first_existing(self, subscriptions, mock_client):
146 webhook_url = "https://example.com/webhooks/composio"
147 raw = {
148 "id": "sub_123",
149 "webhook_url": webhook_url,
150 "version": "V2",
151 "enabled_events": ["composio.connected_account.expired"],
152 }
153 mock_client.webhook_subscriptions.list.return_value = Mock(
154 items=[Mock(id="sub_123")]
155 )
156 mock_client.webhook_subscriptions.update.return_value = raw
157
158 result = subscriptions.set(
159 webhook_url=webhook_url,
160 enabled_events=["composio.connected_account.expired"],
161 version=WebhookVersion.V2,
162 )
163
164 mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1)
165 mock_client.webhook_subscriptions.update.assert_called_once_with(
166 "sub_123",
167 webhook_url=webhook_url,
168 enabled_events=["composio.connected_account.expired"],
169 version="V2",
170 )
171 mock_client.webhook_subscriptions.create.assert_not_called()
172 assert result == raw
173
174 def test_normalizes_pydantic_response_models(self, subscriptions, mock_client):
175 mock_client.webhook_subscriptions.list.return_value = (
176 WebhookSubscriptionListResponse.model_validate(
177 {
178 "items": [],
179 "total_pages": 0,
180 "current_page": 1,
181 "total_items": 0,
182 }
183 )
184 )
185 mock_client.webhook_subscriptions.create.return_value = (
186 WebhookSubscriptionCreateResponse.model_validate(
187 {
188 "id": "sub_1",
189 "webhook_url": "https://x",
190 "version": "V3",
191 "enabled_events": ["composio.trigger.message"],
192 "secret": "whsec_abc",
193 "created_at": "2026-01-01",
194 "updated_at": "2026-01-02",
195 }
196 )
197 )
198
199 result = subscriptions.set(webhook_url="https://x")
200
201 assert result == {
202 "id": "sub_1",
203 "webhook_url": "https://x",
204 "version": "V3",
205 "enabled_events": ["composio.trigger.message"],
206 "secret": "whsec_abc",
207 "created_at": "2026-01-01",
208 "updated_at": "2026-01-02",
209 }
210 assert isinstance(result["version"], str)
211 assert type(result["version"]) is str
212
213 def test_normalizes_unvalidated_response_models_without_warnings(
214 self, subscriptions, mock_client
215 ):
216 # The client builds response models without validation, so enum fields
217 # hold plain strings.
218 mock_client.webhook_subscriptions.list.return_value = (
219 WebhookSubscriptionListResponse.model_construct(items=[])
220 )
221 mock_client.webhook_subscriptions.create.return_value = (
222 WebhookSubscriptionCreateResponse.model_construct(
223 id="sub_1",
224 webhook_url="https://x",
225 version="V3",
226 enabled_events=["composio.trigger.message"],
227 secret="whsec_abc",
228 created_at="2026-01-01",
229 updated_at="2026-01-02",
230 )
231 )
232
233 with warnings.catch_warnings():
234 warnings.simplefilter("error")
235 result = subscriptions.set(webhook_url="https://x")
236
237 assert result["version"] == "V3"
238
239 def test_normalizes_camel_case_wire_keys(self, subscriptions, mock_client):
240 mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
241 mock_client.webhook_subscriptions.create.return_value = {
242 "id": "sub_1",
243 "webhookUrl": "https://x",
244 "version": "V3",
245 "enabledEvents": ["composio.trigger.message"],
246 "createdAt": "2026-01-01",
247 }
248
249 result = subscriptions.set(webhook_url="https://x")
250
251 assert result == {
252 "id": "sub_1",
253 "webhook_url": "https://x",
254 "version": "V3",
255 "enabled_events": ["composio.trigger.message"],
256 "created_at": "2026-01-01",
257 }
258
259 @pytest.mark.parametrize(
260 "raw",
261 [
262 pytest.param({}, id="empty"),
263 pytest.param(
264 {"webhook_url": "https://x", "version": "V3", "enabled_events": []},
265 id="missing-id",
266 ),
267 pytest.param(
268 {"id": "sub_1", "webhook_url": "https://x", "enabled_events": []},
269 id="missing-version",
270 ),
271 pytest.param(
272 {
273 "id": "sub_1",
274 "webhook_url": "https://x",
275 "version": "V3",
276 "enabled_events": ["composio.trigger.message", 42],
277 },
278 id="non-string-event",
279 ),
280 pytest.param("not-an-object", id="not-an-object"),
281 ],
282 )
283 def test_rejects_malformed_create_response(self, subscriptions, mock_client, raw):
284 mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
285 mock_client.webhook_subscriptions.create.return_value = raw
286
287 with pytest.raises(
288 exceptions.ValidationError, match="malformed webhook subscription"
289 ):
290 subscriptions.set(webhook_url="https://x")
291
292 @pytest.mark.parametrize(
293 "listed",
294 [
295 pytest.param({}, id="missing-items"),
296 pytest.param({"items": None}, id="null-items"),
297 pytest.param({"items": [{"id": 42}]}, id="non-string-id"),
298 pytest.param({"items": [{}]}, id="item-without-id"),
299 ],
300 )
301 def test_rejects_malformed_list_probe_before_writing(
302 self, subscriptions, mock_client, listed
303 ):
304 mock_client.webhook_subscriptions.list.return_value = listed
305
306 with pytest.raises(
307 exceptions.ValidationError, match="malformed webhook subscription list"
308 ):
309 subscriptions.set(webhook_url="https://x")
310 mock_client.webhook_subscriptions.create.assert_not_called()
311 mock_client.webhook_subscriptions.update.assert_not_called()
312
313 def test_rejects_empty_webhook_url(self, subscriptions, mock_client):
314 with pytest.raises(exceptions.ValidationError):
315 subscriptions.set(webhook_url="")
316 mock_client.webhook_subscriptions.list.assert_not_called()
317
318 def test_rejects_empty_events(self, subscriptions, mock_client):
319 with pytest.raises(exceptions.ValidationError):
320 subscriptions.set(webhook_url="https://x", enabled_events=[])
321 mock_client.webhook_subscriptions.list.assert_not_called()
322
323
324 class TestTriggersDelegation:
325 def test_set_webhook_subscription_delegates_to_webhooks(self, mock_client):
326 """``triggers.set_webhook_subscription`` issues the same call sequence
327 as ``webhooks.subscriptions.set`` and returns the same shape."""
328 mock_client.triggers_types = Mock()
329 mock_client.trigger_instances = Mock()
330 resource = mock_client.webhook_subscriptions
331 resource.list.return_value = Mock(items=[Mock(id="sub_9")])
332 resource.update.return_value = {
333 "id": "sub_9",
334 "webhook_url": "https://x",
335 "version": "V3",
336 "enabled_events": ["composio.trigger.message"],
337 }
338
339 via_triggers = Triggers(client=mock_client).set_webhook_subscription(
340 webhook_url="https://x"
341 )
342 triggers_calls = (
343 resource.list.call_args_list,
344 resource.update.call_args_list,
345 resource.create.call_args_list,
346 )
347 mock_client.reset_mock()
348 resource.list.return_value = Mock(items=[Mock(id="sub_9")])
349 resource.update.return_value = {
350 "id": "sub_9",
351 "webhook_url": "https://x",
352 "version": "V3",
353 "enabled_events": ["composio.trigger.message"],
354 }
355
356 via_webhooks = WebhookSubscriptions(client=mock_client).set(
357 webhook_url="https://x"
358 )
359
360 assert via_triggers == via_webhooks
361 assert triggers_calls == (
362 resource.list.call_args_list,
363 resource.update.call_args_list,
364 resource.create.call_args_list,
365 )
366
367
368 class TestWebhookEndpoints:
369 def test_list(self, endpoints, mock_client):
370 mock_client.webhook_endpoints.list.return_value = "listed"
371
372 assert endpoints.list() == "listed"
373 mock_client.webhook_endpoints.list.assert_called_once_with(toolkit_slug=omit)
374
375 def test_list_with_toolkit_filter(self, endpoints, mock_client):
376 endpoints.list(toolkit_slug="github")
377
378 mock_client.webhook_endpoints.list.assert_called_once_with(
379 toolkit_slug="github"
380 )
381
382 def test_get(self, endpoints, mock_client):
383 mock_client.webhook_endpoints.retrieve.return_value = "endpoint"
384
385 assert endpoints.get("we_1") == "endpoint"
386 mock_client.webhook_endpoints.retrieve.assert_called_once_with("we_1")
387
388 def test_create(self, endpoints, mock_client):
389 mock_client.webhook_endpoints.create.return_value = "created"
390
391 assert endpoints.create(toolkit_slug="github", client_id="cid") == "created"
392 mock_client.webhook_endpoints.create.assert_called_once_with(
393 toolkit_slug="github", client_id="cid"
394 )
395
396 def test_replace(self, endpoints, mock_client):
397 mock_client.webhook_endpoints.replace.return_value = "replaced"
398
399 assert endpoints.replace("we_1", data={"secret": "s"}) == "replaced"
400 mock_client.webhook_endpoints.replace.assert_called_once_with(
401 "we_1", data={"secret": "s"}
402 )
403
404 def test_update(self, endpoints, mock_client):
405 mock_client.webhook_endpoints.update.return_value = "updated"
406
407 assert endpoints.update("we_1", data={"secret": "s"}) == "updated"
408 mock_client.webhook_endpoints.update.assert_called_once_with(
409 "we_1", data={"secret": "s"}
410 )