The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(connectors): named accounts across dispatch, managed actions and RPC
Siddharth Balyand2590382a130
diff --git a/tests/tools/test_connector_accounts.py b/tests/tools/test_connector_accounts.pynew file mode 100644index 00000000000..ad43dfcf3b8--- /dev/null+++ b/tests/tools/test_connector_accounts.py@@ -0,0 +1,134 @@+"""Several accounts of one connector, each addressed by its name (alias).++Contracts:+- the account a call ran under reaches the model on the single-call and the batch path+- connect with an alias asks the gateway for that account; reconnect with an alias repairs that+ account even when another account of the same connector is healthy+- rename resolves the name to the account; an unknown name lists the valid names+- an open operation for one account is never reused for another account of the same connector+"""++import json+from unittest.mock import patch++import pytest++from tools.connectors import live+from tools.connectors import operation as op+from tools.connectors.gateway.client import ConnectorClient+from tools.connectors.tool import manage_connections++[email protected](autouse=True)+def _clean_live():+ live.reset_for_tests()+ yield+ live.reset_for_tests()+++class _Response:+ def __init__(self, body):+ self.status_code = 200+ self._body = body++ def json(self):+ return self._body+++class _ExecuteTransport:+ """Answers every execute with one result per call, each naming the account it ran under."""++ def request(self, method, url, *, headers=None, json=None, timeout=None):+ results = [{"index": i, "connector": c["connector"], "tool": c["tool"], "data": {"ok": True},+ "account": c["arguments"].get("connector_alias")} for i, c in enumerate(json["tools"])]+ return _Response({"results": results, "successCount": len(results), "errorCount": 0,+ "totalCount": len(results)})+++def test_the_account_a_call_ran_under_reaches_the_model_on_both_dispatch_paths(monkeypatch):+ import model_tools+ from tools.connectors.gateway import bridge, config+ from tools.registry import invalidate_check_fn_cache++ monkeypatch.setattr(config, "connectors_available", lambda: True)+ monkeypatch.setattr(bridge, "connectors_available", lambda: True)+ invalidate_check_fn_cache()+ monkeypatch.setattr(bridge, "_default_client_factory", lambda: ConnectorClient(+ transport=_ExecuteTransport(), endpoint_resolver=lambda: "https://gateway.test",+ header_provider=lambda _url: {"Authorization": "Bearer t"}))+ kwargs = dict(enabled_toolsets=["connections"], session_id="s", skip_pre_tool_call_hook=True,+ skip_tool_request_middleware=True, skip_tool_execution_middleware=True)++ single = json.loads(model_tools.handle_function_call(+ "connectors__gmail__FETCH_EMAILS", {"connector_alias": "work"}, **kwargs))+ assert single["account"] == "work"++ batch = json.loads(model_tools.handle_function_call("tool_call", {"calls": [+ {"name": "connectors__gmail__FETCH_EMAILS", "arguments": {"connector_alias": "home"}},+ {"name": "connectors__gmail__FETCH_EMAILS", "arguments": {}},+ ]}, **kwargs))+ assert [entry.get("account") for entry in batch["results"]] == ["home", None]+++class _Gateway:+ """The connections and account routes, recording every mint."""++ def __init__(self, connected=()):+ self.connected = set(connected)+ self.mints = []++ def list_connectors(self, *, timeout=None):+ return [{"connector": "gmail", "enabled": True, "connected": "gmail" in self.connected}]++ def connections(self, connectors, *, reinitiate=False, alias=None, return_to=None, op=None):+ self.mints.append({"connectors": tuple(connectors), "reinitiate": reinitiate, "alias": alias})+ return {"results": [{"connector": c, "status": "initiated", "connection_id": f"ca_{c}_{len(self.mints)}",+ "connect_url": f"https://connect.example/{c}"} for c in connectors]}++ def account_status(self, connection_id, *, timeout=None):+ return {"connectionId": connection_id, "connector": "gmail", "status": "active", "label": "[email protected]",+ "active": True, "createdAt": "2026-10-08T00:00:00Z", "updatedAt": "2026-10-08T00:00:00Z"}+++def _account(alias, label, status="active"):+ return {"connectionId": f"ca_{alias or label}", "connector": "gmail", "status": status, "label": label,+ "alias": alias, "active": status == "active", "createdAt": "t", "updatedAt": "t"}+++def _run(args, gateway, accounts=()):+ with patch("tools.connectors.managed.WATCH_TICK_SECONDS", 0.0), \+ patch("tools.connectors.managed.portal_accounts", return_value=list(accounts)), \+ patch("tools.connectors.gateway.client.session_platform", return_value="desktop"):+ return json.loads(manage_connections(args, client_factory=lambda: gateway,+ connection_callback=lambda _payload: None, session_id="s1"))+++def test_connect_with_an_alias_asks_for_that_account_and_watches_the_one_it_mints():+ gateway = _Gateway()+ out = _run({"action": "connect", "connectors": [{"name": "gmail", "alias": "work"}]}, gateway)+ assert gateway.mints == [{"connectors": ("gmail",), "reinitiate": False, "alias": "work"}]+ (target,) = out["targets"]+ assert (target["alias"], target["state"]) == ("work", "connected")+++def test_reconnect_with_an_alias_repairs_it_even_when_another_account_is_healthy():+ gateway = _Gateway(connected={"gmail"})+ accounts = [_account("home", "[email protected]"), _account("work", "[email protected]", status="expired")]+ _run({"action": "reconnect", "connectors": [{"name": "gmail", "alias": "work"}]}, gateway, accounts)+ assert gateway.mints == [{"connectors": ("gmail",), "reinitiate": True, "alias": "work"}]+++def test_rename_of_an_unknown_name_lists_the_names_that_exist():+ accounts = [_account("home", "[email protected]"), _account(None, "[email protected]")]+ with patch("tools.connectors.portal.client.PortalConnectorClient.rename_account") as rename:+ out = _run({"action": "rename", "connectors": [{"name": "gmail", "alias": "wrk", "to": "office"}]},+ _Gateway(), accounts)+ rename.assert_not_called()+ assert "home" in out["error"] and "[email protected]" in out["error"]+++def test_an_open_operation_for_one_account_is_not_reused_for_another():+ plain = op.ConnectionOperation([op.Target("gmail", "connector", "connect")], session_key="s1")+ live.open(plain)+ assert live.find_target("gmail") is plain+ assert live.find_target("gmail", alias="work") is Nonediff --git a/tests/tui_gateway/test_connector_accounts_rpc.py b/tests/tui_gateway/test_connector_accounts_rpc.pynew file mode 100644index 00000000000..987dc9140fe--- /dev/null+++ b/tests/tui_gateway/test_connector_accounts_rpc.py@@ -0,0 +1,77 @@+"""Named connector accounts over the real RPC dispatch.++- ``connectors.connect`` with an alias opens an operation for that one account and mints it+- ``connectors.accounts.rename`` answers ALIAS_TAKEN when another account holds the name+"""++import threading++import pytest++from tools.connectors import live+from tools.connectors.gateway.errors import IdempotencyConflict+from tui_gateway import server++[email protected](autouse=True)+def _gate(monkeypatch):+ live.reset_for_tests()+ monkeypatch.setattr("tools.connectors.connectors_available", lambda: True)+ yield+ live.reset_for_tests()+++class _Transport:+ """Collects the frames a long handler writes back instead of returning."""++ def __init__(self):+ self.frames = []+ self.arrived = threading.Event()++ def write(self, obj):+ self.frames.append(obj)+ self.arrived.set()+ return True++ def close(self):+ pass+++def _rpc(method, **params):+ transport = _Transport()+ reply = server.dispatch({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, transport)+ if reply is not None:+ return reply+ assert transport.arrived.wait(5), "no reply"+ return next(frame for frame in transport.frames if frame.get("id") == 1)+++def test_account_connect_with_an_alias_mints_that_account(monkeypatch):+ mints = []+ minted = threading.Event()++ class Client:+ def connections(self, names, *, reinitiate=False, alias=None, **_):+ mints.append((tuple(names), reinitiate, alias))+ minted.set()+ return {"results": [{"connector": n, "status": "initiated", "connection_id": "ca_1",+ "connect_url": "https://connect.example/1"} for n in names]}++ def account_status(self, connection_id, *, timeout=None):+ return None++ monkeypatch.setattr("tools.connectors.managed.managed_client", Client)+ reply = _rpc("connectors.connect", owner={"type": "account"}, connectors=["gmail"], alias="work")+ assert "result" in reply, reply+ assert minted.wait(2)+ assert mints == [(("gmail",), False, "work")]+ assert [(t["name"], t.get("alias")) for t in reply["result"]["targets"]] == [("gmail", "work")]+++def test_rename_to_a_name_another_account_holds_is_alias_taken(monkeypatch):+ def taken(self, connection_id, alias):+ raise IdempotencyConflict("alias taken", code="alias_taken", status=409)++ monkeypatch.setattr("tools.connectors.portal.client.PortalConnectorClient.rename_account", taken)+ reply = _rpc("connectors.accounts.rename", connection_id="ca_1", alias="home")+ assert reply["error"]["data"]["reason"] == "ALIAS_TAKEN"