Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 03:37 UTC
| 1 | import logging |
| 2 | import time |
| 3 | import typing as t |
| 4 | import warnings |
| 5 | from unittest.mock import Mock, patch |
| 6 | |
| 7 | import httpx |
| 8 | import pytest |
| 9 | from composio_client import ( |
| 10 | BadRequestError, |
| 11 | ConflictError, |
| 12 | ProjectAuth, |
| 13 | RateLimitError, |
| 14 | omit, |
| 15 | ) |
| 16 | |
| 17 | from composio import exceptions |
| 18 | from composio.client import HttpClient |
| 19 | from composio.core.models.connected_accounts import ( |
| 20 | AuthScheme, |
| 21 | ConnectedAccounts, |
| 22 | ConnectionRequest, |
| 23 | ) |
| 24 | |
| 25 | |
| 26 | def _set_initiate_response(mock_client, body, headers=None): |
| 27 | """SEC-339: route an `initiate()` mock response through the |
| 28 | ``with_raw_response.create`` surface that the SDK consumes for |
| 29 | deprecation-header gating. |
| 30 | |
| 31 | ``headers`` defaults to ``None`` (no Deprecation header → no warning, |
| 32 | matching custom-auth-config / non-OAuth-scheme behavior). Pass |
| 33 | ``{"Deprecation": "@..."}`` to simulate the apollo retiring branch. |
| 34 | """ |
| 35 | raw = Mock() |
| 36 | raw.parse.return_value = body |
| 37 | raw.headers = headers or {} |
| 38 | mock_client.connected_accounts.with_raw_response.create.return_value = raw |
| 39 | return raw |
| 40 | |
| 41 | |
| 42 | class TestAuthScheme: |
| 43 | def test_oauth2_with_access_token_sets_active_status(self): |
| 44 | scheme = AuthScheme() |
| 45 | options = {"access_token": "test_token", "refresh_token": "test_refresh"} |
| 46 | |
| 47 | state = scheme.oauth2(options) |
| 48 | |
| 49 | assert state["auth_scheme"] == "OAUTH2" |
| 50 | assert state["val"]["access_token"] == "test_token" |
| 51 | assert state["val"]["refresh_token"] == "test_refresh" |
| 52 | assert state["val"]["status"] == "ACTIVE" |
| 53 | |
| 54 | def test_oauth2_without_access_token_sets_initializing_status(self): |
| 55 | scheme = AuthScheme() |
| 56 | options = {"client_id": "id", "client_secret": "secret"} |
| 57 | |
| 58 | state = scheme.oauth2(options) |
| 59 | |
| 60 | assert state["auth_scheme"] == "OAUTH2" |
| 61 | assert state["val"]["client_id"] == "id" |
| 62 | assert state["val"]["client_secret"] == "secret" |
| 63 | assert state["val"]["status"] == "INITIALIZING" |
| 64 | |
| 65 | def test_oauth2_with_empty_access_token_sets_initializing_status(self): |
| 66 | scheme = AuthScheme() |
| 67 | state = scheme.oauth2({"access_token": ""}) |
| 68 | |
| 69 | assert state["val"]["status"] == "INITIALIZING" |
| 70 | |
| 71 | def test_oauth2_honors_explicit_status_override(self): |
| 72 | scheme = AuthScheme() |
| 73 | state = scheme.oauth2({"access_token": "test_token", "status": "INITIALIZING"}) |
| 74 | |
| 75 | assert state["val"]["status"] == "INITIALIZING" |
| 76 | |
| 77 | def test_oauth1_with_both_tokens_sets_active_status(self): |
| 78 | scheme = AuthScheme() |
| 79 | state = scheme.oauth1({"oauth_token": "tok", "oauth_token_secret": "secret"}) |
| 80 | |
| 81 | assert state["auth_scheme"] == "OAUTH1" |
| 82 | assert state["val"]["oauth_token"] == "tok" |
| 83 | assert state["val"]["oauth_token_secret"] == "secret" |
| 84 | assert state["val"]["status"] == "ACTIVE" |
| 85 | |
| 86 | def test_oauth1_without_secret_sets_initializing_status(self): |
| 87 | scheme = AuthScheme() |
| 88 | state = scheme.oauth1({"oauth_token": "tok"}) |
| 89 | |
| 90 | assert state["auth_scheme"] == "OAUTH1" |
| 91 | assert state["val"]["status"] == "INITIALIZING" |
| 92 | |
| 93 | def test_oauth1_with_empty_token_sets_initializing_status(self): |
| 94 | scheme = AuthScheme() |
| 95 | state = scheme.oauth1({"oauth_token": "", "oauth_token_secret": "secret"}) |
| 96 | |
| 97 | assert state["val"]["status"] == "INITIALIZING" |
| 98 | |
| 99 | def test_oauth1_honors_explicit_status_override(self): |
| 100 | scheme = AuthScheme() |
| 101 | state = scheme.oauth1( |
| 102 | { |
| 103 | "oauth_token": "tok", |
| 104 | "oauth_token_secret": "secret", |
| 105 | "status": "INITIALIZING", |
| 106 | } |
| 107 | ) |
| 108 | |
| 109 | assert state["val"]["status"] == "INITIALIZING" |
| 110 | |
| 111 | @pytest.mark.parametrize( |
| 112 | "method_name, expected_auth_scheme, expected_status", |
| 113 | [ |
| 114 | ("api_key", "API_KEY", "ACTIVE"), |
| 115 | ("basic", "BASIC", "ACTIVE"), |
| 116 | ("bearer_token", "BEARER_TOKEN", "ACTIVE"), |
| 117 | ("google_service_account", "GOOGLE_SERVICE_ACCOUNT", "ACTIVE"), |
| 118 | ("no_auth", "NO_AUTH", "ACTIVE"), |
| 119 | ("calcom_auth", "CALCOM_AUTH", "ACTIVE"), |
| 120 | ("billcom_auth", "BILLCOM_AUTH", "ACTIVE"), |
| 121 | ("basic_with_jwt", "BASIC_WITH_JWT", "ACTIVE"), |
| 122 | ], |
| 123 | ) |
| 124 | def test_auth_scheme_helpers_set_expected_auth_scheme_and_status( |
| 125 | self, method_name, expected_auth_scheme, expected_status |
| 126 | ): |
| 127 | scheme = AuthScheme() |
| 128 | method = getattr(scheme, method_name) |
| 129 | options = {"foo": "bar"} |
| 130 | |
| 131 | state = method(options) # type: ignore[misc] |
| 132 | |
| 133 | assert state["auth_scheme"] == expected_auth_scheme |
| 134 | assert state["val"]["foo"] == "bar" |
| 135 | assert state["val"]["status"] == expected_status |
| 136 | |
| 137 | |
| 138 | class TestConnectionRequestPolling: |
| 139 | """Backoff and 429 handling, on a fake clock that only ``sleep`` moves.""" |
| 140 | |
| 141 | @staticmethod |
| 142 | def _clock(monkeypatch): |
| 143 | clock = {"now": 0.0} |
| 144 | monkeypatch.setattr(time, "time", lambda: clock["now"]) |
| 145 | monkeypatch.setattr( |
| 146 | time, "sleep", lambda s: clock.__setitem__("now", clock["now"] + s) |
| 147 | ) |
| 148 | return clock |
| 149 | |
| 150 | @staticmethod |
| 151 | def _rate_limited(retry_after=None): |
| 152 | headers = {} if retry_after is None else {"retry-after": retry_after} |
| 153 | request = httpx.Request("GET", "https://backend.invalid") |
| 154 | response = httpx.Response(429, headers=headers, request=request) |
| 155 | return RateLimitError("slow down", response=response, body=None) |
| 156 | |
| 157 | @staticmethod |
| 158 | def _request(client): |
| 159 | return ConnectionRequest( |
| 160 | id="conn-1", status="PENDING", redirect_url=None, client=client |
| 161 | ) |
| 162 | |
| 163 | def _poll_times(self, monkeypatch, timeout): |
| 164 | clock = self._clock(monkeypatch) |
| 165 | times = [] |
| 166 | pending = Mock(status="PENDING") |
| 167 | |
| 168 | def retrieve(nanoid): |
| 169 | times.append(clock["now"]) |
| 170 | return pending |
| 171 | |
| 172 | client = Mock() |
| 173 | client.connected_accounts.retrieve.side_effect = retrieve |
| 174 | with pytest.raises(exceptions.ComposioSDKTimeoutError): |
| 175 | self._request(client).wait_for_connection(timeout=timeout) |
| 176 | return times |
| 177 | |
| 178 | def test_backs_off_from_1s_to_a_5s_cap(self, monkeypatch): |
| 179 | times = self._poll_times(monkeypatch, 30.0) |
| 180 | assert times[:7] == [0.0, 1.0, 2.5, 4.75, 8.125, 13.125, 18.125] |
| 181 | |
| 182 | def test_sends_about_16_requests_in_the_default_wait(self, monkeypatch): |
| 183 | assert len(self._poll_times(monkeypatch, 60.0)) == 16 |
| 184 | |
| 185 | def test_polls_one_last_time_at_the_deadline(self, monkeypatch): |
| 186 | assert self._poll_times(monkeypatch, 3.0) == [0.0, 1.0, 2.5, 3.0] |
| 187 | |
| 188 | def test_waits_as_long_as_a_429_asks_then_keeps_polling(self, monkeypatch): |
| 189 | clock = self._clock(monkeypatch) |
| 190 | active = Mock(status="ACTIVE") |
| 191 | client = Mock() |
| 192 | client.connected_accounts.retrieve.side_effect = [ |
| 193 | self._rate_limited("10"), |
| 194 | active, |
| 195 | ] |
| 196 | |
| 197 | assert self._request(client).wait_for_connection(timeout=60.0) is active |
| 198 | assert clock["now"] == 10.0 |
| 199 | |
| 200 | @pytest.mark.parametrize( |
| 201 | "timeout,retry_after,elapsed", [(1.0, "3", 6.0), (25.0, "10", 25.0)] |
| 202 | ) |
| 203 | def test_does_not_restart_client_retries_after_timeout( |
| 204 | self, monkeypatch, timeout, retry_after, elapsed |
| 205 | ): |
| 206 | clock = self._clock(monkeypatch) |
| 207 | requests = [] |
| 208 | |
| 209 | def handler(request): |
| 210 | requests.append(request) |
| 211 | return httpx.Response( |
| 212 | 429, |
| 213 | headers={"retry-after": retry_after}, |
| 214 | json={"error": {"message": "x"}}, |
| 215 | ) |
| 216 | |
| 217 | client = HttpClient( |
| 218 | provider="test", |
| 219 | auth=ProjectAuth("test-api-key"), |
| 220 | base_url="https://backend.invalid", |
| 221 | http_client=httpx.Client(transport=httpx.MockTransport(handler)), |
| 222 | ) |
| 223 | |
| 224 | with pytest.raises(exceptions.ComposioSDKTimeoutError): |
| 225 | self._request(client).wait_for_connection(timeout=timeout) |
| 226 | |
| 227 | assert clock["now"] == elapsed |
| 228 | assert len(requests) == 3 |
| 229 | |
| 230 | def test_waiting_by_id_survives_a_429_on_its_first_request(self, monkeypatch): |
| 231 | clock = self._clock(monkeypatch) |
| 232 | active = Mock(status="ACTIVE") |
| 233 | client = Mock() |
| 234 | client.connected_accounts.retrieve.side_effect = [ |
| 235 | self._rate_limited("10"), |
| 236 | active, |
| 237 | ] |
| 238 | |
| 239 | result = ConnectedAccounts(client=client).wait_for_connection( |
| 240 | id="conn-1", timeout=60.0 |
| 241 | ) |
| 242 | |
| 243 | assert result is active |
| 244 | assert clock["now"] == 10.0 |
| 245 | client.connected_accounts.retrieve.assert_called_with(nanoid="conn-1") |
| 246 | |
| 247 | def test_waiting_by_id_sends_one_request_when_already_active(self, monkeypatch): |
| 248 | self._clock(monkeypatch) |
| 249 | client = Mock() |
| 250 | client.connected_accounts.retrieve.return_value = Mock(status="ACTIVE") |
| 251 | |
| 252 | ConnectedAccounts(client=client).wait_for_connection(id="conn-1", timeout=60.0) |
| 253 | |
| 254 | assert client.connected_accounts.retrieve.call_count == 1 |
| 255 | |
| 256 | def test_a_nan_timeout_times_out_after_one_poll(self, monkeypatch): |
| 257 | clock = self._clock(monkeypatch) |
| 258 | client = Mock() |
| 259 | client.connected_accounts.retrieve.return_value = Mock(status="PENDING") |
| 260 | |
| 261 | with pytest.raises(exceptions.ComposioSDKTimeoutError): |
| 262 | self._request(client).wait_for_connection(timeout=float("nan")) |
| 263 | |
| 264 | assert clock["now"] == 0.0 |
| 265 | assert client.connected_accounts.retrieve.call_count == 1 |
| 266 | |
| 267 | @pytest.mark.parametrize("retry_after", ["5", "60"]) |
| 268 | def test_does_not_repoll_at_the_deadline_after_a_429( |
| 269 | self, monkeypatch, retry_after |
| 270 | ): |
| 271 | clock = self._clock(monkeypatch) |
| 272 | client = Mock() |
| 273 | client.connected_accounts.retrieve.side_effect = self._rate_limited(retry_after) |
| 274 | |
| 275 | with pytest.raises(exceptions.ComposioSDKTimeoutError): |
| 276 | self._request(client).wait_for_connection(timeout=5.0) |
| 277 | |
| 278 | assert clock["now"] == 5.0 |
| 279 | assert client.connected_accounts.retrieve.call_count == 1 |
| 280 | |
| 281 | def test_reads_a_date_format_retry_after(self, monkeypatch): |
| 282 | clock = self._clock(monkeypatch) |
| 283 | # 1,000,000 seconds after the epoch, which is where the clock starts here. |
| 284 | clock["now"] = 1_000_000.0 |
| 285 | client = Mock() |
| 286 | client.connected_accounts.retrieve.side_effect = [ |
| 287 | self._rate_limited("Mon, 12 Jan 1970 13:47:00 GMT"), |
| 288 | Mock(status="ACTIVE"), |
| 289 | ] |
| 290 | |
| 291 | self._request(client).wait_for_connection(timeout=60.0) |
| 292 | |
| 293 | assert clock["now"] == 1_000_020.0 |
| 294 | |
| 295 | @pytest.mark.parametrize( |
| 296 | "retry_after", [None, "soon", "nan", "inf", "Thu, 01 Jan 1970 00:00:00 GMT"] |
| 297 | ) |
| 298 | def test_keeps_its_usual_delay_without_a_usable_retry_after( |
| 299 | self, monkeypatch, retry_after |
| 300 | ): |
| 301 | clock = self._clock(monkeypatch) |
| 302 | client = Mock() |
| 303 | client.connected_accounts.retrieve.side_effect = [ |
| 304 | self._rate_limited(retry_after), |
| 305 | Mock(status="ACTIVE"), |
| 306 | ] |
| 307 | |
| 308 | self._request(client).wait_for_connection(timeout=60.0) |
| 309 | |
| 310 | assert clock["now"] == 1.0 |
| 311 | |
| 312 | |
| 313 | class TestConnectionRequest: |
| 314 | def test_wait_for_connection_returns_when_active(self, monkeypatch): |
| 315 | mock_client = Mock() |
| 316 | pending = Mock() |
| 317 | pending.status = "PENDING" |
| 318 | active = Mock() |
| 319 | active.status = "ACTIVE" |
| 320 | mock_client.connected_accounts.retrieve.side_effect = [pending, active] |
| 321 | |
| 322 | req = ConnectionRequest( |
| 323 | id="conn-123", |
| 324 | status="PENDING", |
| 325 | redirect_url=None, |
| 326 | client=mock_client, |
| 327 | ) |
| 328 | |
| 329 | # Control time to avoid real sleep. Use a monotonic counter instead of a |
| 330 | # finite list, because other code (e.g. tracing) may also call time.time(). |
| 331 | current_time = {"value": 0.0} |
| 332 | |
| 333 | def fake_time(): |
| 334 | value = current_time["value"] |
| 335 | current_time["value"] += 0.1 |
| 336 | return value |
| 337 | |
| 338 | monkeypatch.setattr(time, "time", fake_time) |
| 339 | monkeypatch.setattr(time, "sleep", lambda *_args, **_kwargs: None) |
| 340 | |
| 341 | result = req.wait_for_connection(timeout=1.0) |
| 342 | |
| 343 | assert result is active |
| 344 | assert req.status == "ACTIVE" |
| 345 | assert mock_client.connected_accounts.retrieve.call_count == 2 |
| 346 | mock_client.connected_accounts.retrieve.assert_called_with(nanoid="conn-123") |
| 347 | |
| 348 | def test_wait_for_connection_times_out(self, monkeypatch): |
| 349 | mock_client = Mock() |
| 350 | pending = Mock() |
| 351 | pending.status = "PENDING" |
| 352 | mock_client.connected_accounts.retrieve.return_value = pending |
| 353 | |
| 354 | req = ConnectionRequest( |
| 355 | id="conn-timeout", |
| 356 | status="PENDING", |
| 357 | redirect_url=None, |
| 358 | client=mock_client, |
| 359 | ) |
| 360 | |
| 361 | # Simulate time moving forward until the timeout is exceeded. Again, use |
| 362 | # a monotonic counter so extra calls to time.time() do not exhaust test |
| 363 | # data. |
| 364 | current_time = {"value": 0.0} |
| 365 | |
| 366 | def fake_time(): |
| 367 | value = current_time["value"] |
| 368 | current_time["value"] += 0.6 |
| 369 | return value |
| 370 | |
| 371 | monkeypatch.setattr(time, "time", fake_time) |
| 372 | monkeypatch.setattr(time, "sleep", lambda *_args, **_kwargs: None) |
| 373 | |
| 374 | with pytest.raises(exceptions.ComposioSDKTimeoutError) as excinfo: |
| 375 | req.wait_for_connection(timeout=1.0) |
| 376 | |
| 377 | assert "Timeout while waiting for connection conn-timeout" in str(excinfo.value) |
| 378 | |
| 379 | @pytest.mark.parametrize("terminal_status", ["FAILED", "EXPIRED", "REVOKED"]) |
| 380 | def test_wait_for_connection_fails_fast_on_terminal_status( |
| 381 | self, monkeypatch, terminal_status |
| 382 | ): |
| 383 | mock_client = Mock() |
| 384 | terminal = Mock() |
| 385 | terminal.status = terminal_status |
| 386 | mock_client.connected_accounts.retrieve.return_value = terminal |
| 387 | |
| 388 | req = ConnectionRequest( |
| 389 | id="conn-terminal", |
| 390 | status="PENDING", |
| 391 | redirect_url=None, |
| 392 | client=mock_client, |
| 393 | ) |
| 394 | |
| 395 | # Patch `time.time` defensively — matches sibling tests. |
| 396 | current_time = {"value": 0.0} |
| 397 | |
| 398 | def fake_time(): |
| 399 | value = current_time["value"] |
| 400 | current_time["value"] += 0.1 |
| 401 | return value |
| 402 | |
| 403 | monkeypatch.setattr(time, "time", fake_time) |
| 404 | monkeypatch.setattr(time, "sleep", lambda *_args, **_kwargs: None) |
| 405 | |
| 406 | with pytest.raises(exceptions.SDKError) as excinfo: |
| 407 | req.wait_for_connection(timeout=10.0) |
| 408 | |
| 409 | assert "conn-terminal" in str(excinfo.value) |
| 410 | assert terminal_status in str(excinfo.value) |
| 411 | # One retrieve call only — no polling once we hit a terminal state. |
| 412 | assert mock_client.connected_accounts.retrieve.call_count == 1 |
| 413 | |
| 414 | def test_wait_for_connection_does_not_treat_inactive_as_terminal(self, monkeypatch): |
| 415 | mock_client = Mock() |
| 416 | inactive = Mock() |
| 417 | inactive.status = "INACTIVE" |
| 418 | active = Mock() |
| 419 | active.status = "ACTIVE" |
| 420 | mock_client.connected_accounts.retrieve.side_effect = [inactive, active] |
| 421 | |
| 422 | req = ConnectionRequest( |
| 423 | id="conn-inactive-recover", |
| 424 | status="PENDING", |
| 425 | redirect_url=None, |
| 426 | client=mock_client, |
| 427 | ) |
| 428 | |
| 429 | current_time = {"value": 0.0} |
| 430 | |
| 431 | def fake_time(): |
| 432 | value = current_time["value"] |
| 433 | current_time["value"] += 0.1 |
| 434 | return value |
| 435 | |
| 436 | monkeypatch.setattr(time, "time", fake_time) |
| 437 | monkeypatch.setattr(time, "sleep", lambda *_args, **_kwargs: None) |
| 438 | |
| 439 | result = req.wait_for_connection(timeout=1.0) |
| 440 | |
| 441 | assert result is active |
| 442 | assert req.status == "ACTIVE" |
| 443 | assert mock_client.connected_accounts.retrieve.call_count == 2 |
| 444 | |
| 445 | def test_from_id_uses_client_retrieve(self): |
| 446 | mock_client = Mock() |
| 447 | retrieved = Mock() |
| 448 | retrieved.status = "PENDING" |
| 449 | mock_client.connected_accounts.retrieve.return_value = retrieved |
| 450 | |
| 451 | req = ConnectionRequest.from_id("conn-from-id", client=mock_client) |
| 452 | |
| 453 | mock_client.connected_accounts.retrieve.assert_called_once_with( |
| 454 | nanoid="conn-from-id" |
| 455 | ) |
| 456 | assert req.id == "conn-from-id" |
| 457 | assert req.status == "PENDING" |
| 458 | assert req.redirect_url is None |
| 459 | |
| 460 | |
| 461 | class TestConnectedAccounts: |
| 462 | @pytest.fixture |
| 463 | def mock_client(self): |
| 464 | client = Mock() |
| 465 | client.connected_accounts.retrieve = Mock() |
| 466 | client.connected_accounts.list = Mock() |
| 467 | client.connected_accounts.delete = Mock() |
| 468 | client.connected_accounts.update_status = Mock() |
| 469 | client.connected_accounts.refresh = Mock() |
| 470 | client.connected_accounts.create = Mock() |
| 471 | client.connected_accounts.patch = Mock() |
| 472 | client.link.create = Mock() |
| 473 | return client |
| 474 | |
| 475 | @pytest.fixture |
| 476 | def connected_accounts(self, mock_client): |
| 477 | return ConnectedAccounts(client=mock_client) |
| 478 | |
| 479 | def test_constructor_binds_methods(self, connected_accounts, mock_client): |
| 480 | assert connected_accounts.get is mock_client.connected_accounts.retrieve |
| 481 | assert connected_accounts.list is mock_client.connected_accounts.list |
| 482 | assert connected_accounts.delete is mock_client.connected_accounts.delete |
| 483 | assert ( |
| 484 | connected_accounts.update_status |
| 485 | is mock_client.connected_accounts.update_status |
| 486 | ) |
| 487 | |
| 488 | def test_refresh_is_deprecated_and_delegates(self, connected_accounts, mock_client): |
| 489 | mock_client.connected_accounts.refresh.return_value = {"status": "ok"} |
| 490 | |
| 491 | with pytest.warns( |
| 492 | exceptions.ComposioDeprecationWarning, match="refresh\\(\\) is deprecated" |
| 493 | ): |
| 494 | result = connected_accounts.refresh( |
| 495 | "conn-1", query_redirect_url="https://example.com/callback" |
| 496 | ) |
| 497 | |
| 498 | assert result == {"status": "ok"} |
| 499 | mock_client.connected_accounts.refresh.assert_called_once_with( |
| 500 | "conn-1", query_redirect_url="https://example.com/callback" |
| 501 | ) |
| 502 | |
| 503 | def test_refresh_forwards_request_options(self, connected_accounts, mock_client): |
| 504 | with pytest.warns(exceptions.ComposioDeprecationWarning): |
| 505 | connected_accounts.refresh("conn-1", timeout=3) # type: ignore[call-arg] |
| 506 | |
| 507 | mock_client.connected_accounts.refresh.assert_called_once_with( |
| 508 | "conn-1", timeout=3 |
| 509 | ) |
| 510 | |
| 511 | def test_refresh_ignores_removed_validate_credentials( |
| 512 | self, connected_accounts, mock_client |
| 513 | ): |
| 514 | with pytest.warns(exceptions.ComposioDeprecationWarning) as record: |
| 515 | connected_accounts.refresh("conn-1", validate_credentials=True) |
| 516 | |
| 517 | assert any("validate_credentials" in str(w.message) for w in record) |
| 518 | mock_client.connected_accounts.refresh.assert_called_once_with("conn-1") |
| 519 | |
| 520 | def test_revoke_delegates_to_client(self, connected_accounts, mock_client): |
| 521 | mock_client.connected_accounts.revoke.return_value = {"revoked_tokens": []} |
| 522 | |
| 523 | result = connected_accounts.revoke("conn-1") |
| 524 | |
| 525 | assert result == {"revoked_tokens": []} |
| 526 | mock_client.connected_accounts.revoke.assert_called_once_with("conn-1") |
| 527 | |
| 528 | def test_revoke_maps_400_to_not_supported(self, connected_accounts, mock_client): |
| 529 | mock_client.connected_accounts.revoke.side_effect = _make_status_error( |
| 530 | BadRequestError, "toolkit does not support revocation" |
| 531 | ) |
| 532 | |
| 533 | with pytest.raises( |
| 534 | exceptions.ComposioConnectedAccountRevocationNotSupportedError |
| 535 | ) as info: |
| 536 | connected_accounts.revoke("conn-1") |
| 537 | |
| 538 | assert "conn-1" in str(info.value) |
| 539 | assert "toolkit does not support revocation" in str(info.value) |
| 540 | assert isinstance(info.value.__cause__, BadRequestError) |
| 541 | |
| 542 | def test_revoke_maps_409_to_not_revokable(self, connected_accounts, mock_client): |
| 543 | mock_client.connected_accounts.revoke.side_effect = _make_status_error( |
| 544 | ConflictError, "connection is not ACTIVE" |
| 545 | ) |
| 546 | |
| 547 | with pytest.raises( |
| 548 | exceptions.ComposioConnectedAccountNotRevokableError |
| 549 | ) as info: |
| 550 | connected_accounts.revoke("conn-1") |
| 551 | |
| 552 | assert "not in a revokable state" in str(info.value) |
| 553 | assert isinstance(info.value.__cause__, ConflictError) |
| 554 | |
| 555 | def test_revoke_does_not_swallow_other_errors( |
| 556 | self, connected_accounts, mock_client |
| 557 | ): |
| 558 | mock_client.connected_accounts.revoke.side_effect = RuntimeError("boom") |
| 559 | |
| 560 | with pytest.raises(RuntimeError): |
| 561 | connected_accounts.revoke("conn-1") |
| 562 | |
| 563 | def test_complete_auth_delegates_to_client(self, connected_accounts, mock_client): |
| 564 | mock_client.connected_accounts.complete_auth.return_value = { |
| 565 | "connected_account_id": "ca_1", |
| 566 | "toolkit_slug": "github", |
| 567 | } |
| 568 | |
| 569 | result = connected_accounts.complete_auth( |
| 570 | user_id="user-1", session_uri="session-abc" |
| 571 | ) |
| 572 | |
| 573 | assert result == {"connected_account_id": "ca_1", "toolkit_slug": "github"} |
| 574 | mock_client.connected_accounts.complete_auth.assert_called_once_with( |
| 575 | user_id="user-1", session_uri="session-abc" |
| 576 | ) |
| 577 | |
| 578 | def test_enable_and_disable_partials(self, connected_accounts, mock_client): |
| 579 | connected_accounts.enable("conn-1") |
| 580 | connected_accounts.disable("conn-2") |
| 581 | |
| 582 | mock_client.connected_accounts.update_status.assert_any_call( |
| 583 | "conn-1", enabled=True |
| 584 | ) |
| 585 | mock_client.connected_accounts.update_status.assert_any_call( |
| 586 | "conn-2", enabled=False |
| 587 | ) |
| 588 | |
| 589 | def test_initiate_raises_when_multiple_accounts_and_not_allow_multiple( |
| 590 | self, connected_accounts, mock_client |
| 591 | ): |
| 592 | mock_accounts = Mock() |
| 593 | mock_accounts.items = [Mock(), Mock()] |
| 594 | mock_client.connected_accounts.list.return_value = mock_accounts |
| 595 | |
| 596 | with pytest.raises(exceptions.ComposioMultipleConnectedAccountsError): |
| 597 | connected_accounts.initiate( |
| 598 | user_id="user-1", auth_config_id="auth-1", allow_multiple=False |
| 599 | ) |
| 600 | |
| 601 | def test_initiate_filters_by_active_status_when_checking_existing_accounts( |
| 602 | self, connected_accounts, mock_client |
| 603 | ): |
| 604 | """ |
| 605 | Test that initiate only considers ACTIVE accounts when checking for duplicates. |
| 606 | This ensures expired or inactive accounts don't block new connection creation. |
| 607 | """ |
| 608 | mock_accounts = Mock() |
| 609 | mock_accounts.items = [] |
| 610 | mock_client.connected_accounts.list.return_value = mock_accounts |
| 611 | |
| 612 | mock_response = Mock() |
| 613 | mock_response.id = "conn-123" |
| 614 | mock_response.connection_data.val.status = "PENDING" |
| 615 | mock_response.connection_data.val.redirect_url = "https://redirect" |
| 616 | _set_initiate_response(mock_client, mock_response) |
| 617 | |
| 618 | connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1") |
| 619 | |
| 620 | # Verify that list is called with statuses=["ACTIVE"] to filter only active accounts |
| 621 | mock_client.connected_accounts.list.assert_called_once_with( |
| 622 | user_ids=["user-1"], auth_config_ids=["auth-1"], statuses=["ACTIVE"] |
| 623 | ) |
| 624 | |
| 625 | def test_initiate_warns_and_creates_when_allow_multiple( |
| 626 | self, connected_accounts, mock_client, caplog |
| 627 | ): |
| 628 | mock_accounts = Mock() |
| 629 | mock_accounts.items = [Mock(), Mock()] |
| 630 | mock_client.connected_accounts.list.return_value = mock_accounts |
| 631 | |
| 632 | mock_response = Mock() |
| 633 | mock_response.id = "conn-123" |
| 634 | mock_response.connection_data.val.status = "PENDING" |
| 635 | mock_response.connection_data.val.redirect_url = "https://redirect" |
| 636 | _set_initiate_response(mock_client, mock_response) |
| 637 | |
| 638 | config = { |
| 639 | "auth_scheme": "API_KEY", |
| 640 | "val": {"key": "secret", "status": "ACTIVE"}, |
| 641 | } |
| 642 | |
| 643 | with caplog.at_level(logging.WARNING): |
| 644 | result = connected_accounts.initiate( |
| 645 | user_id="user-1", |
| 646 | auth_config_id="auth-1", |
| 647 | callback_url="https://cb", |
| 648 | allow_multiple=True, |
| 649 | config=config, |
| 650 | ) |
| 651 | |
| 652 | mock_client.connected_accounts.list.assert_called_once_with( |
| 653 | user_ids=["user-1"], auth_config_ids=["auth-1"], statuses=["ACTIVE"] |
| 654 | ) |
| 655 | call_kwargs = ( |
| 656 | mock_client.connected_accounts.with_raw_response.create.call_args.kwargs |
| 657 | ) |
| 658 | assert call_kwargs["auth_config"] == {"id": "auth-1"} |
| 659 | assert call_kwargs["connection"]["user_id"] == "user-1" |
| 660 | assert call_kwargs["connection"]["callback_url"] == "https://cb" |
| 661 | assert call_kwargs["connection"]["state"] == config |
| 662 | |
| 663 | assert isinstance(result, ConnectionRequest) |
| 664 | assert result.id == "conn-123" |
| 665 | assert result.status == "PENDING" |
| 666 | assert result.redirect_url == "https://redirect" |
| 667 | assert "[Warn:AllowMultiple] Multiple connected accounts found" in caplog.text |
| 668 | |
| 669 | def test_link_builds_payload_and_returns_connection_request( |
| 670 | self, connected_accounts, mock_client |
| 671 | ): |
| 672 | # link() now mirrors initiate() and pre-flights list() to enforce the |
| 673 | # allow_multiple guard; default to no existing connections here. |
| 674 | no_accounts = Mock() |
| 675 | no_accounts.items = [] |
| 676 | mock_client.connected_accounts.list.return_value = no_accounts |
| 677 | |
| 678 | mock_response = Mock() |
| 679 | mock_response.connected_account_id = "conn-999" |
| 680 | mock_response.redirect_url = "https://redirect" |
| 681 | mock_client.link.create.return_value = mock_response |
| 682 | |
| 683 | result = connected_accounts.link( |
| 684 | user_id="user-1", |
| 685 | auth_config_id="auth-1", |
| 686 | callback_url="https://cb", |
| 687 | ) |
| 688 | |
| 689 | call_kwargs = mock_client.link.create.call_args.kwargs |
| 690 | assert call_kwargs["auth_config_id"] == "auth-1" |
| 691 | assert call_kwargs["user_id"] == "user-1" |
| 692 | assert call_kwargs["callback_url"] == "https://cb" |
| 693 | |
| 694 | assert isinstance(result, ConnectionRequest) |
| 695 | assert result.id == "conn-999" |
| 696 | assert result.status == "INITIATED" |
| 697 | assert result.redirect_url == "https://redirect" |
| 698 | |
| 699 | def test_link_omits_callback_url_when_not_provided( |
| 700 | self, connected_accounts, mock_client |
| 701 | ): |
| 702 | no_accounts = Mock() |
| 703 | no_accounts.items = [] |
| 704 | mock_client.connected_accounts.list.return_value = no_accounts |
| 705 | |
| 706 | mock_response = Mock() |
| 707 | mock_response.connected_account_id = "conn-000" |
| 708 | mock_response.redirect_url = None |
| 709 | mock_client.link.create.return_value = mock_response |
| 710 | |
| 711 | connected_accounts.link(user_id="user-1", auth_config_id="auth-1") |
| 712 | |
| 713 | call_kwargs = mock_client.link.create.call_args.kwargs |
| 714 | assert call_kwargs["auth_config_id"] == "auth-1" |
| 715 | assert call_kwargs["user_id"] == "user-1" |
| 716 | assert call_kwargs["callback_url"] is omit |
| 717 | |
| 718 | def test_link_raises_when_active_connection_exists_and_not_allow_multiple( |
| 719 | self, connected_accounts, mock_client |
| 720 | ): |
| 721 | """link() guards against duplicate connections, mirroring initiate().""" |
| 722 | existing = Mock() |
| 723 | existing.items = [Mock()] |
| 724 | mock_client.connected_accounts.list.return_value = existing |
| 725 | |
| 726 | with pytest.raises(exceptions.ComposioMultipleConnectedAccountsError): |
| 727 | connected_accounts.link(user_id="user-1", auth_config_id="auth-1") |
| 728 | |
| 729 | mock_client.connected_accounts.list.assert_called_once_with( |
| 730 | user_ids=["user-1"], auth_config_ids=["auth-1"], statuses=["ACTIVE"] |
| 731 | ) |
| 732 | mock_client.link.create.assert_not_called() |
| 733 | |
| 734 | def test_link_skips_guard_when_allow_multiple_is_true( |
| 735 | self, connected_accounts, mock_client |
| 736 | ): |
| 737 | """allow_multiple=True bypasses the guard and proceeds with link.create.""" |
| 738 | existing = Mock() |
| 739 | existing.items = [Mock()] |
| 740 | mock_client.connected_accounts.list.return_value = existing |
| 741 | |
| 742 | mock_response = Mock() |
| 743 | mock_response.connected_account_id = "conn-new" |
| 744 | mock_response.redirect_url = "https://redirect" |
| 745 | mock_client.link.create.return_value = mock_response |
| 746 | |
| 747 | result = connected_accounts.link( |
| 748 | user_id="user-1", |
| 749 | auth_config_id="auth-1", |
| 750 | alias="work", |
| 751 | allow_multiple=True, |
| 752 | ) |
| 753 | |
| 754 | call_kwargs = mock_client.link.create.call_args.kwargs |
| 755 | assert call_kwargs["alias"] == "work" |
| 756 | assert result.id == "conn-new" |
| 757 | |
| 758 | def test_initiate_with_oauth2_tokens_returns_active_connection_request( |
| 759 | self, connected_accounts, mock_client |
| 760 | ): |
| 761 | mock_accounts = Mock() |
| 762 | mock_accounts.items = [] |
| 763 | mock_client.connected_accounts.list.return_value = mock_accounts |
| 764 | |
| 765 | mock_response = Mock() |
| 766 | mock_response.id = "conn-active" |
| 767 | mock_response.connection_data.val.status = "ACTIVE" |
| 768 | mock_response.connection_data.val.redirect_url = None |
| 769 | _set_initiate_response(mock_client, mock_response) |
| 770 | |
| 771 | scheme = AuthScheme() |
| 772 | config = scheme.oauth2( |
| 773 | {"access_token": "tok", "refresh_token": "ref", "expires_in": 3600} |
| 774 | ) |
| 775 | |
| 776 | result = connected_accounts.initiate( |
| 777 | user_id="user-1", auth_config_id="auth-1", config=config |
| 778 | ) |
| 779 | |
| 780 | assert isinstance(result, ConnectionRequest) |
| 781 | assert result.id == "conn-active" |
| 782 | assert result.status == "ACTIVE" |
| 783 | assert result.redirect_url is None |
| 784 | |
| 785 | def test_wait_for_connection_delegates_to_connection_request(self, mock_client): |
| 786 | connected_accounts = ConnectedAccounts(client=mock_client) |
| 787 | |
| 788 | with patch( |
| 789 | "composio.core.models.connected_accounts.ConnectionRequest.wait_for_connection", |
| 790 | return_value="connected", |
| 791 | ) as mock_wait: |
| 792 | result = connected_accounts.wait_for_connection(id="conn-123", timeout=42.0) |
| 793 | |
| 794 | mock_wait.assert_called_once_with(timeout=42.0) |
| 795 | assert result == "connected" |
| 796 | # The wait does all the fetching, so its 429 handling covers every request. |
| 797 | mock_client.connected_accounts.retrieve.assert_not_called() |
| 798 | |
| 799 | |
| 800 | def _make_status_error(error_type: t.Type[Exception], message: str): |
| 801 | """Build an ``APIStatusError`` subclass instance for testing error mappers. |
| 802 | |
| 803 | The composio_client error constructor signatures are internal — rather |
| 804 | than depend on them, we stub a minimal object that ``str(error)`` |
| 805 | surfaces the message and which is recognized as the given type by |
| 806 | ``isinstance``. This mirrors how production responses arrive: the error |
| 807 | class with a message body. |
| 808 | """ |
| 809 | error = error_type.__new__(error_type) |
| 810 | Exception.__init__(error, message) |
| 811 | return error |
| 812 | |
| 813 | |
| 814 | def _make_bad_request_error(message: str): |
| 815 | """Build a BadRequestError instance for testing the error mapper.""" |
| 816 | from composio_client import BadRequestError |
| 817 | |
| 818 | return _make_status_error(BadRequestError, message) |
| 819 | |
| 820 | |
| 821 | class TestConnectedAccountsAcl: |
| 822 | """Tests for SHARED accounts surface on ``link()`` and |
| 823 | ``composio.experimental.update_acl()``.""" |
| 824 | |
| 825 | @pytest.fixture |
| 826 | def mock_client(self): |
| 827 | client = Mock() |
| 828 | client.connected_accounts.retrieve = Mock() |
| 829 | client.connected_accounts.list = Mock() |
| 830 | client.connected_accounts.delete = Mock() |
| 831 | client.connected_accounts.update_status = Mock() |
| 832 | client.connected_accounts.refresh = Mock() |
| 833 | client.connected_accounts.create = Mock() |
| 834 | client.connected_accounts.patch = Mock() |
| 835 | client.link.create = Mock() |
| 836 | # Default: no existing connections, so link() doesn't trip the guard. |
| 837 | no_accounts = Mock() |
| 838 | no_accounts.items = [] |
| 839 | client.connected_accounts.list.return_value = no_accounts |
| 840 | # Default link.create response — overridden per test where the |
| 841 | # response shape matters. |
| 842 | default_link = Mock() |
| 843 | default_link.connected_account_id = "ca_test_shared" |
| 844 | default_link.redirect_url = "https://redirect" |
| 845 | client.link.create.return_value = default_link |
| 846 | return client |
| 847 | |
| 848 | @pytest.fixture |
| 849 | def connected_accounts(self, mock_client): |
| 850 | return ConnectedAccounts(client=mock_client) |
| 851 | |
| 852 | @pytest.fixture |
| 853 | def experimental(self, mock_client): |
| 854 | from composio.core.models.experimental import ExperimentalAPI |
| 855 | |
| 856 | return ExperimentalAPI(client=mock_client) |
| 857 | |
| 858 | # -- link() forwards the experimental block ----------------------------- |
| 859 | |
| 860 | def test_link_forwards_experimental_block(self, connected_accounts, mock_client): |
| 861 | connected_accounts.link( |
| 862 | user_id="user_creator", |
| 863 | auth_config_id="auth_config_123", |
| 864 | experimental={ |
| 865 | "account_type": "SHARED", |
| 866 | "acl_config_for_shared": { |
| 867 | "allow_all_users": True, |
| 868 | "not_allowed_user_ids": ["user_bob"], |
| 869 | }, |
| 870 | }, |
| 871 | ) |
| 872 | |
| 873 | call_kwargs = mock_client.link.create.call_args.kwargs |
| 874 | assert call_kwargs["experimental"] == { |
| 875 | "account_type": "SHARED", |
| 876 | "acl_config_for_shared": { |
| 877 | "allow_all_users": True, |
| 878 | "not_allowed_user_ids": ["user_bob"], |
| 879 | }, |
| 880 | } |
| 881 | |
| 882 | def test_link_omits_experimental_when_not_provided( |
| 883 | self, connected_accounts, mock_client |
| 884 | ): |
| 885 | connected_accounts.link( |
| 886 | user_id="user_creator", |
| 887 | auth_config_id="auth_config_123", |
| 888 | ) |
| 889 | |
| 890 | call_kwargs = mock_client.link.create.call_args.kwargs |
| 891 | assert call_kwargs["experimental"] is omit |
| 892 | |
| 893 | def test_link_preserves_explicit_empty_lists(self, connected_accounts, mock_client): |
| 894 | """An empty list is meaningful (clear the allow/deny list).""" |
| 895 | connected_accounts.link( |
| 896 | user_id="user_creator", |
| 897 | auth_config_id="auth_config_123", |
| 898 | experimental={ |
| 899 | "account_type": "SHARED", |
| 900 | "acl_config_for_shared": { |
| 901 | "allowed_user_ids": [], |
| 902 | "not_allowed_user_ids": [], |
| 903 | }, |
| 904 | }, |
| 905 | ) |
| 906 | |
| 907 | call_kwargs = mock_client.link.create.call_args.kwargs |
| 908 | assert call_kwargs["experimental"]["acl_config_for_shared"] == { |
| 909 | "allowed_user_ids": [], |
| 910 | "not_allowed_user_ids": [], |
| 911 | } |
| 912 | |
| 913 | def test_link_maps_acl_only_for_shared_to_typed_error( |
| 914 | self, connected_accounts, mock_client |
| 915 | ): |
| 916 | mock_client.link.create.side_effect = _make_bad_request_error( |
| 917 | "acl_config_for_shared is only valid on SHARED connections." |
| 918 | ) |
| 919 | |
| 920 | with pytest.raises(exceptions.ComposioAclOnlyForSharedError): |
| 921 | connected_accounts.link( |
| 922 | user_id="user_creator", |
| 923 | auth_config_id="auth_config_123", |
| 924 | experimental={ |
| 925 | "account_type": "PRIVATE", |
| 926 | "acl_config_for_shared": {"allow_all_users": True}, |
| 927 | }, |
| 928 | ) |
| 929 | |
| 930 | def test_link_rethrows_non_acl_bad_request_errors( |
| 931 | self, connected_accounts, mock_client |
| 932 | ): |
| 933 | unrelated = _make_bad_request_error("auth_config_id is required") |
| 934 | mock_client.link.create.side_effect = unrelated |
| 935 | |
| 936 | from composio_client import BadRequestError |
| 937 | |
| 938 | with pytest.raises(BadRequestError): |
| 939 | connected_accounts.link( |
| 940 | user_id="user_creator", auth_config_id="auth_config_123" |
| 941 | ) |
| 942 | |
| 943 | # -- experimental.update_acl() body construction + mapper --------------- |
| 944 | |
| 945 | def test_update_acl_serializes_nested_body(self, experimental, mock_client): |
| 946 | response = Mock() |
| 947 | response.id = "ca_abc" |
| 948 | response.status = "ACTIVE" |
| 949 | response.success = True |
| 950 | mock_client.connected_accounts.patch.return_value = response |
| 951 | |
| 952 | result = experimental.update_acl( |
| 953 | "ca_abc", |
| 954 | allow_all_users=True, |
| 955 | not_allowed_user_ids=["user_bob"], |
| 956 | ) |
| 957 | |
| 958 | mock_client.connected_accounts.patch.assert_called_once_with( |
| 959 | "ca_abc", |
| 960 | experimental={ |
| 961 | "acl_config_for_shared": { |
| 962 | "allow_all_users": True, |
| 963 | "not_allowed_user_ids": ["user_bob"], |
| 964 | } |
| 965 | }, |
| 966 | ) |
| 967 | assert result is response |
| 968 | |
| 969 | def test_update_acl_omits_absent_fields(self, experimental, mock_client): |
| 970 | experimental.update_acl("ca_abc", allowed_user_ids=["user_alice"]) |
| 971 | |
| 972 | mock_client.connected_accounts.patch.assert_called_once_with( |
| 973 | "ca_abc", |
| 974 | experimental={ |
| 975 | "acl_config_for_shared": {"allowed_user_ids": ["user_alice"]} |
| 976 | }, |
| 977 | ) |
| 978 | |
| 979 | def test_update_acl_preserves_empty_array(self, experimental, mock_client): |
| 980 | experimental.update_acl("ca_abc", allowed_user_ids=[]) |
| 981 | |
| 982 | mock_client.connected_accounts.patch.assert_called_once_with( |
| 983 | "ca_abc", |
| 984 | experimental={"acl_config_for_shared": {"allowed_user_ids": []}}, |
| 985 | ) |
| 986 | |
| 987 | def test_update_acl_rejects_all_none(self, experimental, mock_client): |
| 988 | with pytest.raises(exceptions.ValidationError): |
| 989 | experimental.update_acl("ca_abc") |
| 990 | mock_client.connected_accounts.patch.assert_not_called() |
| 991 | |
| 992 | def test_update_acl_maps_acl_only_for_shared_to_typed_error( |
| 993 | self, experimental, mock_client |
| 994 | ): |
| 995 | mock_client.connected_accounts.patch.side_effect = _make_bad_request_error( |
| 996 | "acl_config_for_shared is only valid on SHARED connections." |
| 997 | ) |
| 998 | |
| 999 | with pytest.raises(exceptions.ComposioAclOnlyForSharedError): |
| 1000 | experimental.update_acl("ca_abc", allow_all_users=True) |
| 1001 | |
| 1002 | def test_update_acl_rethrows_non_acl_bad_request_errors( |
| 1003 | self, experimental, mock_client |
| 1004 | ): |
| 1005 | unrelated = _make_bad_request_error("some other 400") |
| 1006 | mock_client.connected_accounts.patch.side_effect = unrelated |
| 1007 | |
| 1008 | from composio_client import BadRequestError |
| 1009 | |
| 1010 | with pytest.raises(BadRequestError): |
| 1011 | experimental.update_acl("ca_abc", allow_all_users=True) |
| 1012 | |
| 1013 | def test_update_acl_requires_client(self): |
| 1014 | from composio.core.models.experimental import ExperimentalAPI |
| 1015 | |
| 1016 | with pytest.raises(exceptions.ValidationError): |
| 1017 | ExperimentalAPI().update_acl("ca_abc", allow_all_users=True) |
| 1018 | |
| 1019 | # -- list(account_type=...) — flat experimental filter ----------------- |
| 1020 | |
| 1021 | def test_list_forwards_account_type_filter(self, connected_accounts, mock_client): |
| 1022 | connected_accounts.list(account_type="SHARED", user_ids=["user_creator"]) |
| 1023 | mock_client.connected_accounts.list.assert_called_once_with( |
| 1024 | account_type="SHARED", user_ids=["user_creator"] |
| 1025 | ) |
| 1026 | |
| 1027 | |
| 1028 | # SEC-339: initiate() must gate its ComposioDeprecationWarning on the response |
| 1029 | # `Deprecation` HTTP header (RFC 9745) that apollo emits only on the |
| 1030 | # retiring branch (Composio-managed + redirectable OAuth). These tests pin |
| 1031 | # that contract so the previous false-positive behavior — warning purely |
| 1032 | # off auth_scheme, which over-fired for custom auth configs — can't come |
| 1033 | # back. See https://docs.composio.dev/docs/changelog/2026/04/24 |
| 1034 | class TestInitiateDeprecationHeaderGate: |
| 1035 | @pytest.fixture |
| 1036 | def mock_client(self): |
| 1037 | client = Mock() |
| 1038 | client.connected_accounts.list = Mock() |
| 1039 | return client |
| 1040 | |
| 1041 | @pytest.fixture(autouse=True) |
| 1042 | def _reset_warning_flag(self): |
| 1043 | """Reset the module-level one-time warning guard before each test |
| 1044 | so warning emission is deterministic regardless of test order.""" |
| 1045 | import composio.core.models.connected_accounts as ca_mod |
| 1046 | |
| 1047 | ca_mod._legacy_initiate_warning_emitted = False |
| 1048 | yield |
| 1049 | ca_mod._legacy_initiate_warning_emitted = False |
| 1050 | |
| 1051 | @staticmethod |
| 1052 | def _no_existing_accounts(mock_client): |
| 1053 | empty = Mock() |
| 1054 | empty.items = [] |
| 1055 | mock_client.connected_accounts.list.return_value = empty |
| 1056 | |
| 1057 | @staticmethod |
| 1058 | def _make_response(): |
| 1059 | body = Mock() |
| 1060 | body.id = "conn-dep" |
| 1061 | body.connection_data.val.status = "INITIATED" |
| 1062 | body.connection_data.val.redirect_url = "https://redirect" |
| 1063 | return body |
| 1064 | |
| 1065 | def test_warns_once_when_response_carries_deprecation_header(self, mock_client): |
| 1066 | """Managed + redirectable-OAuth path: apollo sets `Deprecation`, |
| 1067 | SDK emits a `ComposioDeprecationWarning` pointing callers at link().""" |
| 1068 | self._no_existing_accounts(mock_client) |
| 1069 | body = self._make_response() |
| 1070 | _set_initiate_response( |
| 1071 | mock_client, |
| 1072 | body, |
| 1073 | headers={ |
| 1074 | "Deprecation": "@1776988800", |
| 1075 | "Sunset": "Fri, 08 May 2026 00:00:00 GMT", |
| 1076 | "Link": ( |
| 1077 | "<https://docs.composio.dev/docs/changelog/2026/04/24>; " |
| 1078 | 'rel="deprecation"' |
| 1079 | ), |
| 1080 | }, |
| 1081 | ) |
| 1082 | |
| 1083 | connected_accounts = ConnectedAccounts(client=mock_client) |
| 1084 | with warnings.catch_warnings(record=True) as caught: |
| 1085 | warnings.simplefilter("always") |
| 1086 | req = connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1") |
| 1087 | |
| 1088 | assert isinstance(req, ConnectionRequest) |
| 1089 | deprecations = [ |
| 1090 | w |
| 1091 | for w in caught |
| 1092 | if issubclass(w.category, exceptions.ComposioDeprecationWarning) |
| 1093 | ] |
| 1094 | assert len(deprecations) == 1 |
| 1095 | message = str(deprecations[0].message) |
| 1096 | assert "composio.connected_accounts.link()" in message |
| 1097 | assert "2026-07-03" in message |
| 1098 | |
| 1099 | def test_does_not_warn_when_response_has_no_deprecation_header(self, mock_client): |
| 1100 | """Custom auth config / non-OAuth scheme: apollo returns a clean |
| 1101 | response, SDK must stay silent. Regression for the prior |
| 1102 | auth_scheme-only check that over-fired here.""" |
| 1103 | self._no_existing_accounts(mock_client) |
| 1104 | _set_initiate_response(mock_client, self._make_response(), headers={}) |
| 1105 | |
| 1106 | connected_accounts = ConnectedAccounts(client=mock_client) |
| 1107 | with warnings.catch_warnings(record=True) as caught: |
| 1108 | warnings.simplefilter("always") |
| 1109 | connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1") |
| 1110 | |
| 1111 | deprecations = [ |
| 1112 | w |
| 1113 | for w in caught |
| 1114 | if issubclass(w.category, exceptions.ComposioDeprecationWarning) |
| 1115 | ] |
| 1116 | assert deprecations == [] |
| 1117 | |
| 1118 | def test_warns_at_most_once_per_process_across_calls(self, mock_client): |
| 1119 | """The one-time guard must hold across multiple calls in the same |
| 1120 | process even when each response carries the Deprecation header.""" |
| 1121 | self._no_existing_accounts(mock_client) |
| 1122 | # Same headers for both calls; helper rewires the same return on |
| 1123 | # each invocation, so both calls see the Deprecation header. |
| 1124 | _set_initiate_response( |
| 1125 | mock_client, |
| 1126 | self._make_response(), |
| 1127 | headers={"Deprecation": "@1776988800"}, |
| 1128 | ) |
| 1129 | |
| 1130 | connected_accounts = ConnectedAccounts(client=mock_client) |
| 1131 | with warnings.catch_warnings(record=True) as caught: |
| 1132 | warnings.simplefilter("always") |
| 1133 | connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1") |
| 1134 | empty = Mock() |
| 1135 | empty.items = [] |
| 1136 | mock_client.connected_accounts.list.return_value = empty |
| 1137 | connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1") |
| 1138 | |
| 1139 | deprecations = [ |
| 1140 | w |
| 1141 | for w in caught |
| 1142 | if issubclass(w.category, exceptions.ComposioDeprecationWarning) |
| 1143 | ] |
| 1144 | assert len(deprecations) == 1 |