Decouple bridges: ship each with its pack

The core no longer owns concrete bridge implementations. A bridge now ships
inside the pack that declares it (packs/<name>/bridge/<name>.py, plus its
package marker, optional client module, and hermetic test), and the core
registry imports it by convention from the pack's `bridges`.

Core keeps only:
- bridges/base.py: BridgeInfo + BridgeService (shared HTTP/JSON/auth layer),
  plus a new BridgeService.from_config build hook (a bridge that needs the
  scheduler's `llm` client or top-level fallback values declares that itself,
  replacing build_bridge's per-name special-casing) and checkout_root() so a
  pack-relative bridge can still anchor .runtime/ paths;
- bridges/inbox.py: the generic MessagingInbox;
- bridges/llm.py: the one shared, pack-less LLMBridge (CORE_BRIDGES);
- bridges/registry.py: discovery (discover_bridge_classes/known_infos/
  describe_bridges/derived_config_vars/build_bridge/run_bridges) scanning each
  pack's bridge/ dir, plus load_pack_bridge_module/package for tests.

Moved to their packs: simplex, nextcloud (+client), outlook (+client), browser
(+client) — each with its hermetic test. tests/test_bridges.py now covers the
core (shared LLM bridge + registry); tests/test_packs.py runs every pack's
bridge test. Docs (AGENTS.md, PACKGEN.md, README.md) updated.

Packs pushed separately to pack.<name>.
This commit is contained in:
gabby committed 2026-10-13 23:56:06 +00:00
1 parent 16e8583921
commit 41c18e6c47
21 files changed
+485 -7476

No files matched your search

+8 -636
View File
@@ -1,13 +1,13 @@
"""Pure-stdlib tests for the standalone bridge services.
"""Core bridge tests: the shared LLM bridge and the discovery registry.
The SimpleX bridge is exercised over a real loopback HTTP server (no mocking of
its HTTP transport) with a fake daemon standing in for the `simplex-chat`
connection — the decision engine and LLM are never involved. These prove the
mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
resolution, outbound routing, address lookup, and token/body validation.
Bridge implementations ship with their packs; their hermetic tests live in the
pack (see `packs/*/bridge/test_*.py`, run by `tests/test_packs.py`). This file
covers what stays in the core: the shared, pack-less LLM bridge and the registry
surface (`known_infos`/`describe_bridges`/`derived_config_vars`) that discovers
the packs' bridges and renders the catalog codegen reads. The decision engine and
a real model are never involved.
"""
import asyncio
import json
import urllib.error
import urllib.request
@@ -20,122 +20,6 @@ from semif_agent.bridges.registry import (
describe_bridges,
known_infos,
)
from semif_agent.bridges.simplex import SimplexBridge
class FakeDaemon:
"""Stands in for the bridge's own simplex-chat connection."""
def __init__(
self,
link=None,
error=None,
contacts=None,
contacts_error=None,
chats=None,
chats_error=None,
history=None,
history_error=None,
send_response=None,
send_error=None,
read_response=None,
read_error=None,
):
self.link = link
self.error = error
self.contacts_list = contacts or []
self.contacts_error = contacts_error
self.chats_list = chats or []
self.chats_error = chats_error
self.history_list = history or []
self.history_error = history_error
self.send_response = send_response
self.send_error = send_error
self.read_response = read_response
self.read_error = read_error
self.refresh_count = 0
self.chat_calls = []
self.history_calls = []
self.read_calls = []
self.sent = []
self.closed = False
self.on_message = None
def check_requirements(self):
return True, None
def run(self, on_message):
self.on_message = on_message
def enqueue(self, chat_id, text=""):
if chat_id is not None:
self.sent.append((chat_id, text))
def request_send(self, chat_id, text, timeout=20.0):
self.sent.append((chat_id, text))
if self.send_error is not None:
raise self.send_error
if self.send_response is not None:
return self.send_response
return {
"type": "newChatItems",
"chatItems": [
{"chatItem": {"meta": {"itemId": 1, "itemStatus": {"type": "sndRcvd"}}}}
],
}
def request_address(self, timeout=20.0):
if self.error is not None:
raise self.error
return self.link
def request_contacts(self, timeout=20.0):
self.refresh_count += 1
if self.contacts_error is not None:
raise self.contacts_error
return list(self.contacts_list)
async def contacts(self, timeout=20.0):
return self.request_contacts(timeout)
def request_chats(self, unread_only=True, count=20, timeout=20.0):
self.chat_calls.append((unread_only, count))
if self.chats_error is not None:
raise self.chats_error
return list(self.chats_list)
def request_chat_history(self, contact_id, count=20, timeout=20.0):
self.history_calls.append((contact_id, count))
if self.history_error is not None:
raise self.history_error
return list(self.history_list)
def request_mark_read(self, chat_id, item_ids=None, timeout=20.0):
self.read_calls.append((str(chat_id), list(item_ids or [])))
if self.read_error is not None:
raise self.read_error
if self.read_response is not None:
return self.read_response
return {"ok": True, "type": "itemsReadForChat", "error": ""}
def close(self):
self.closed = True
def start_bridge(daemon=None, **config):
daemon = daemon or FakeDaemon()
bridge = SimplexBridge(config, daemon=daemon)
port = bridge.start()
return bridge, daemon, f"http://127.0.0.1:{port}"
def inbound(text, contact_id="4", display_name="Alice", item_id=""):
return {
"text": text,
"contact_id": contact_id,
"display_name": display_name,
"item_id": item_id,
}
def get(url, token=None):
@@ -154,427 +38,6 @@ def post(url, payload, token=None):
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def test_health_and_contacts():
bridge, _, base = start_bridge()
try:
assert get(f"{base}/health") == {"ok": True, "platform": "simplex"}
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
assert get(f"{base}/contacts") == {
"contacts": [{"id": "4", "display_name": "Alice"}]
}
finally:
bridge.stop()
def test_inbox_peek_then_pop_consumes_oldest():
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("first", contact_id="4", display_name="Alice"))
bridge._on_message(inbound("second", contact_id="7", display_name="Bob"))
peeked = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in peeked] == ["first", "second"]
assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume"
popped = get(f"{base}/inbox/next")["message"]
assert popped["text"] == "first"
assert popped["contact_id"] == "4"
remaining = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in remaining] == ["second"]
finally:
bridge.stop()
def test_inbox_next_filters_by_contact():
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("first", contact_id="4", display_name="Alice"))
bridge._on_message(inbound("second", contact_id="7", display_name="Bob"))
popped = get(f"{base}/inbox/next?contact=7")["message"]
assert popped["text"] == "second"
assert get(f"{base}/inbox/next?contact=7")["message"] is None
assert [m["text"] for m in get(f"{base}/inbox")["messages"]] == ["first"]
finally:
bridge.stop()
def test_inbox_buffers_any_sender():
# No allowlist: a brand-new contact who reached the bot via its invite link
# must be visible, which is the whole point of the forwarding bridge.
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("who are you?", contact_id="99", display_name="stranger"))
messages = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in messages] == ["who are you?"]
finally:
bridge.stop()
def test_inbox_is_bounded():
bridge, _, base = start_bridge(max_inbox=2)
try:
for text in ("one", "two", "three"):
bridge._on_message(inbound(text))
messages = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped"
finally:
bridge.stop()
def test_send_routes_to_daemon():
bridge, daemon, base = start_bridge()
try:
result = post(f"{base}/send", {"recipient": "7", "text": "on my way"})
assert result["ok"] is True, result
assert result["contact_id"] == "7", result
assert result["status"] == "sndRcvd", result
assert daemon.sent == [("7", "on my way")]
finally:
bridge.stop()
def test_send_resolves_known_display_name():
bridge, daemon, base = start_bridge()
try:
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
assert result["contact_id"] == "4"
assert daemon.sent == [("4", "hello")]
finally:
bridge.stop()
def test_send_reports_a_failed_send_not_a_false_success():
# A dead connection: the daemon creates the item then marks it sndError.
# The bridge must surface ok:false with the reason, never a false success.
failed = {
"type": "newChatItems",
"chatItems": [
{
"chatItem": {
"meta": {
"itemId": 12,
"itemStatus": {
"type": "sndError",
"agentError": {"type": "auth"},
},
}
}
}
],
}
daemon = FakeDaemon(send_response=failed)
bridge, _, base = start_bridge(daemon=daemon)
try:
result = post(f"{base}/send", {"recipient": "7", "text": "hey"})
assert result["ok"] is False, result
assert result["status"] == "sndError", result
assert result["error"] == "auth", result
assert result["contact_id"] == "7"
finally:
bridge.stop()
def test_send_verifies_status_via_history():
# The daemon accepts the send (sndNew) and only later resolves it to a
# delivered status; the bridge polls history to confirm.
accepted = {
"type": "newChatItems",
"chatItems": [
{"chatItem": {"meta": {"itemId": 5, "itemStatus": {"type": "sndNew"}}}}
],
}
history = [
{"item_id": "5", "text": "hi", "status": "sndRcvd", "unread": False,
"direction": "directSnd", "sent_at": ""},
]
daemon = FakeDaemon(send_response=accepted, history=history)
bridge, _, base = start_bridge(daemon=daemon)
try:
result = post(f"{base}/send", {"recipient": "7", "text": "hi"})
assert result["ok"] is True, result
assert result["status"] == "sndRcvd", result
assert daemon.history_calls, "the bridge must poll for the real status"
finally:
bridge.stop()
def test_resolve_prefers_a_healthy_duplicate():
# Two peers share the display name "pepper"; the stale one has auth errors.
daemon = FakeDaemon(
contacts=[
{"id": "3", "display_name": "pepper", "local_name": "pepper",
"connected": True, "auth_errors": 2},
{"id": "4", "display_name": "pepper", "local_name": "pepper_1",
"connected": True, "auth_errors": 0},
]
)
bridge, _, _ = start_bridge(daemon=daemon)
try:
assert bridge.resolve("pepper") == "4", "a stale duplicate must lose"
assert bridge.resolve("pepper_1") == "4"
assert bridge.resolve("3") == "3", "an explicit id always wins"
finally:
bridge.stop()
def test_contacts_refreshed_from_daemon():
# A contact the bridge has never received from must still be visible: the
# daemon knows them, so /send can address them.
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
bridge, _, base = start_bridge(daemon=daemon)
try:
assert get(f"{base}/contacts") == {
"contacts": [{"id": "42", "display_name": "Zed"}]
}
assert daemon.refresh_count >= 1
finally:
bridge.stop()
def test_send_resolves_daemon_only_contact():
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
bridge, _, base = start_bridge(daemon=daemon)
try:
result = post(f"{base}/send", {"recipient": "Zed", "text": "hello"})
assert result["ok"] is True and result["contact_id"] == "42", result
assert daemon.sent == [("42", "hello")]
finally:
bridge.stop()
def test_refresh_on_connect_primes_contacts():
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
bridge, _, base = start_bridge(daemon=daemon)
try:
asyncio.run(bridge._refresh_on_connect())
assert get(f"{base}/contacts")["contacts"] == [
{"id": "42", "display_name": "Zed"}
]
finally:
bridge.stop()
def test_contacts_failure_keeps_cached_and_stays_available():
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
bridge.daemon.contacts_error = RuntimeError("not connected")
assert get(f"{base}/contacts") == {
"contacts": [{"id": "4", "display_name": "Alice"}]
}
finally:
bridge.stop()
def test_daemon_refresh_does_not_clobber_inbound_name():
daemon = FakeDaemon(contacts=[{"id": "4", "display_name": ""}])
bridge, _, base = start_bridge(daemon=daemon)
try:
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
assert get(f"{base}/contacts") == {
"contacts": [{"id": "4", "display_name": "Alice"}]
}
finally:
bridge.stop()
def test_send_rejects_unknown_recipient():
bridge, daemon, base = start_bridge()
try:
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/send", {"recipient": "ghost", "text": "hello"})
assert exc.value.code == 400
assert daemon.sent == [], "a rejected send must not enqueue anything"
finally:
bridge.stop()
def test_send_validates_body():
bridge, daemon, base = start_bridge()
try:
for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}):
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/send", payload)
assert exc.value.code == 400
assert daemon.sent == []
finally:
bridge.stop()
def test_token_is_required_when_configured():
bridge, _, base = start_bridge(token="sekret")
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/inbox")
assert exc.value.code == 401
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/send", {"recipient": "4", "text": "hi"})
assert exc.value.code == 401
assert get(f"{base}/inbox", token="sekret") == {"messages": []}
finally:
bridge.stop()
def test_address_returns_daemon_link():
link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False}
bridge, _, base = start_bridge(daemon=FakeDaemon(link=link))
try:
assert get(f"{base}/address") == link
finally:
bridge.stop()
def test_address_without_connection_is_unavailable():
bridge, _, base = start_bridge(
daemon=FakeDaemon(error=RuntimeError("not connected"))
)
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/address")
assert exc.value.code == 503
finally:
bridge.stop()
def test_address_lookup_failure_is_reported():
bridge, _, base = start_bridge(daemon=FakeDaemon(error=TimeoutError("slow")))
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/address")
assert exc.value.code == 502
finally:
bridge.stop()
def test_stop_closes_the_daemon():
bridge, daemon, _ = start_bridge()
bridge.stop()
assert daemon.closed is True
# ---- daemon-backed unread / history ----
def chat_summary(contact_id="4", display_name="Alice", unread_count=2):
return {
"contact_id": contact_id,
"display_name": display_name,
"unread_count": unread_count,
"min_unread_item_id": "10",
"unread": True,
"messages": [
{
"item_id": "10",
"text": "hello there",
"status": "rcvNew",
"unread": True,
"direction": "directRcv",
"sent_at": "2026-01-01T00:00:00Z",
}
],
}
def test_unread_returns_daemon_chats():
daemon = FakeDaemon(chats=[chat_summary()])
bridge, _, base = start_bridge(daemon=daemon)
try:
assert get(f"{base}/unread") == {"chats": [chat_summary()]}
assert daemon.chat_calls == [(True, 20)], "must ask the daemon for unread"
finally:
bridge.stop()
def test_unread_attaches_cached_connection_health():
daemon = FakeDaemon(chats=[chat_summary(contact_id="4", display_name="pepper")])
bridge, _, base = start_bridge(daemon=daemon)
try:
bridge.inbox.merge_contacts(
[
{"id": "4", "display_name": "pepper", "local_name": "pepper_1",
"connected": True, "auth_errors": 0},
]
)
chats = get(f"{base}/unread")["chats"]
assert chats[0]["connected"] is True
assert chats[0]["auth_errors"] == 0
finally:
bridge.stop()
def test_unread_honours_count_query():
daemon = FakeDaemon(chats=[])
bridge, _, base = start_bridge(daemon=daemon)
try:
get(f"{base}/unread?count=5")
assert daemon.chat_calls == [(True, 5)]
finally:
bridge.stop()
def test_unread_without_connection_is_unavailable():
bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=RuntimeError("not connected")))
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/unread")
assert exc.value.code == 503
finally:
bridge.stop()
def test_unread_lookup_failure_is_reported():
bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=TimeoutError("slow")))
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/unread")
assert exc.value.code == 502
finally:
bridge.stop()
def test_history_returns_messages_for_contact():
messages = [{"item_id": "11", "text": "hi", "status": "rcvRead", "unread": False,
"direction": "directRcv", "sent_at": ""}]
daemon = FakeDaemon(history=messages)
bridge, _, base = start_bridge(daemon=daemon)
try:
assert get(f"{base}/history?contact=7") == {"contact_id": "7", "messages": messages}
assert daemon.history_calls == [("7", 20)]
finally:
bridge.stop()
def test_history_requires_a_contact():
bridge, daemon, base = start_bridge()
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/history")
assert exc.value.code == 400
assert daemon.history_calls == []
finally:
bridge.stop()
def test_history_without_connection_is_unavailable():
bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=RuntimeError("not connected")))
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/history?contact=4")
assert exc.value.code == 503
finally:
bridge.stop()
def test_history_lookup_failure_is_reported():
bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=TimeoutError("slow")))
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/history?contact=4")
assert exc.value.code == 502
finally:
bridge.stop()
# ---- LLM bridge ----
class FakeLLMClient:
@@ -663,18 +126,9 @@ def test_llm_bridge_health_and_token():
bridge.stop()
# ---- catalog / codegen surface ----
def test_known_infos_include_simplex():
infos = {info.name: info for info in known_infos()}
assert "simplex" in infos
info = infos["simplex"]
assert info.service == "simplex"
assert info.url_config_var == "simplex_bridge_url"
assert info.auth_header == "X-Semif-Token"
assert info.auth_config_var == "simplex_bridge_token"
def test_known_infos_include_llm():
infos = {info.name: info for info in known_infos()}
assert "llm" in infos
@@ -729,85 +183,3 @@ def test_derived_config_vars_skip_unconfigured_bridges():
assert derived["nextcloud_bridge_token"] == ""
def test_describe_bridges_renders_service_auth_and_endpoints():
text = describe_bridges()
assert "simplex" in text
assert "service: simplex" in text
assert "simplex_bridge_url" in text
assert "X-Semif-Token" in text
assert "simplex_bridge_token" in text
assert "/inbox/next" in text
assert "/unread" in text
assert "/history" in text
assert "rather than reaching around it" in text
def test_read_marks_given_items_only():
daemon = FakeDaemon()
bridge, _, base = start_bridge(daemon=daemon)
try:
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8", "9"]})
assert result == {
"ok": True,
"contact_id": "4",
"item_ids": ["8", "9"],
"status": "read",
}
assert daemon.read_calls == [("4", ["8", "9"])], "only the listed items"
finally:
bridge.stop()
def test_read_validates_body():
bridge, daemon, base = start_bridge()
try:
payloads = (
{"item_ids": ["8"]},
{"contact": "4"},
{"contact": "4", "item_ids": []},
{"contact": " ", "item_ids": ["8"]},
)
for payload in payloads:
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/read", payload)
assert exc.value.code == 400
assert daemon.read_calls == []
finally:
bridge.stop()
def test_read_without_connection_is_unavailable():
bridge, _, base = start_bridge(
daemon=FakeDaemon(read_error=RuntimeError("not connected"))
)
try:
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
assert result["ok"] is False
assert result["status"] == "unavailable"
assert "not connected" in result["error"]
finally:
bridge.stop()
def test_read_reports_a_rejected_read():
bridge, _, base = start_bridge(
daemon=FakeDaemon(read_response={"ok": False, "error": "agent error"})
)
try:
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
assert result["ok"] is False
assert result["status"] == "rejected"
assert result["error"] == "agent error"
finally:
bridge.stop()
def test_inbox_carries_item_id_for_consumption():
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("hi", contact_id="4", item_id="33"))
popped = get(f"{base}/inbox/next")["message"]
assert popped["item_id"] == "33"
finally:
bridge.stop()
-373
View File
@@ -1,373 +0,0 @@
"""Pure-stdlib tests for the browser (Playwright) bridge.
The bridge is exercised over a real loopback HTTP server with a fake driver
standing in for the Playwright browser — the decision engine, the browser, and
Playwright itself are never involved. These prove the mechanics a skill depends
on: route wiring/validation, the token/auth surface, and the status mapping
(400 bad input, 503 unavailable, 502 real failure). Passing these proves
mechanics only; a real run against a real browser is the only proof the
integration works.
"""
import json
import urllib.error
import urllib.request
import pytest
from semif_agent.bridges.browser import BrowserBridge
from semif_agent.bridges.browser_client import (
BrowserDriver,
BrowserError,
BrowserUnavailable,
)
from semif_agent.bridges.registry import (
build_bridge,
derived_config_vars,
describe_bridges,
known_infos,
)
class FakeDriver:
"""Stands in for the Playwright browser, recording every call."""
def __init__(self, error=None, unavailable=None):
self.error = error
self.unavailable = unavailable
self.calls = []
self.closed = False
def _maybe_fail(self):
if self.unavailable is not None:
raise BrowserUnavailable(self.unavailable)
if self.error is not None:
raise BrowserError(self.error)
def state(self):
self.calls.append(("state",))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def goto(self, url, wait_until="load", timeout=None):
self.calls.append(("goto", url, wait_until, timeout))
self._maybe_fail()
return {"url": url, "title": "Example", "status": 200}
def content(self, fmt="text", max_chars=None):
self.calls.append(("content", fmt, max_chars))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example", "format": fmt, "content": "hi", "truncated": False}
def text(self, selector):
self.calls.append(("text", selector))
self._maybe_fail()
return {"url": "https://example.com/", "selector": selector, "count": 1, "matches": [{"text": "hi"}]}
def links(self, query="", limit=50):
self.calls.append(("links", query, limit))
self._maybe_fail()
return {"url": "https://example.com/", "links": [{"text": "More", "href": "/more"}]}
def screenshot(self, full_page=False, selector="", inline=False):
self.calls.append(("screenshot", full_page, selector, inline))
self._maybe_fail()
return {"ok": True, "path": "/tmp/shot.png", "bytes": 12, "url": "https://example.com/", "title": "Example"}
def click(self, selector="", text="", index=0, timeout=None):
self.calls.append(("click", selector, text, index, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def fill(self, selector, value, submit=False, timeout=None):
self.calls.append(("fill", selector, value, submit, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def press(self, key, selector="", timeout=None):
self.calls.append(("press", key, selector, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def select(self, selector, value=None, label=None, timeout=None):
self.calls.append(("select", selector, value, label, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def wait_for(self, selector="", text="", timeout=None):
self.calls.append(("wait_for", selector, text, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def back(self, timeout=None):
self.calls.append(("back", timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def forward(self, timeout=None):
self.calls.append(("forward", timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def reset(self, purge=True):
self.calls.append(("reset", purge))
self._maybe_fail()
return {"ok": True, "purged": bool(purge)}
def close(self):
self.closed = True
def start_bridge(driver=None, **config):
driver = driver or FakeDriver()
bridge = BrowserBridge(config, client=driver)
port = bridge.start()
return bridge, driver, f"http://127.0.0.1:{port}"
def get(url, token=None):
headers = {"X-Semif-Token": token} if token else {}
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def post(url, payload, token=None):
body = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
request = urllib.request.Request(url, data=body, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def http_error(url, payload=None, token=None):
if payload is None:
request = urllib.request.Request(url)
else:
body = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
request = urllib.request.Request(url, data=body, headers=headers)
with pytest.raises(urllib.error.HTTPError) as exc:
urllib.request.urlopen(request, timeout=5)
return exc.value
# ---- routes ----
def test_health_reports_engine_without_a_browser():
bridge, _driver, base = start_bridge(headless=False, engine="firefox")
try:
assert get(f"{base}/health") == {
"ok": True,
"platform": "browser",
"engine": "firefox",
"headless": False,
}
finally:
bridge.stop()
def test_read_routes_wire_to_the_driver():
bridge, driver, base = start_bridge()
try:
assert get(f"{base}/state") == {"url": "https://example.com/", "title": "Example"}
assert get(f"{base}/content?format=html&max_chars=500")["content"] == "hi"
assert get(f"{base}/text?selector=h1")["count"] == 1
assert get(f"{base}/links?query=more&limit=5")["links"][0]["href"] == "/more"
assert get(f"{base}/screenshot?full_page=true&inline=true")["path"] == "/tmp/shot.png"
assert driver.calls == [
("state",),
("content", "html", 500),
("text", "h1"),
("links", "more", 5),
("screenshot", True, "", True),
]
finally:
bridge.stop()
def test_action_routes_wire_to_the_driver():
bridge, driver, base = start_bridge()
try:
assert post(f"{base}/goto", {"url": "https://a.test/", "wait_until": "networkidle"})["status"] == 200
post(f"{base}/click", {"text": "Sign in"})
post(f"{base}/fill", {"selector": "#q", "value": "hi", "submit": True})
post(f"{base}/press", {"key": "Enter"})
post(f"{base}/select", {"selector": "select", "label": "Two"})
post(f"{base}/wait", {"text": "Done", "timeout": 5})
post(f"{base}/back", {})
post(f"{base}/forward", {})
post(f"{base}/reset", {"purge": False})
assert driver.calls == [
("goto", "https://a.test/", "networkidle", None),
("click", "", "Sign in", 0, None),
("fill", "#q", "hi", True, None),
("press", "Enter", "", None),
("select", "select", None, "Two", None),
("wait_for", "", "Done", 5.0),
("back", None),
("forward", None),
("reset", False),
]
finally:
bridge.stop()
def test_missing_url_is_400():
bridge, driver, base = start_bridge()
try:
exc = http_error(f"{base}/goto", {})
assert exc.code == 400
assert driver.calls == [], "a rejected goto must not touch the browser"
finally:
bridge.stop()
def test_bad_wait_until_and_content_format_are_400():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/goto", {"url": "https://a.test", "wait_until": "whenever"}).code == 400
assert http_error(f"{base}/content?format=pdf").code == 400
finally:
bridge.stop()
def test_click_requires_selector_or_text():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/click", {}).code == 400
finally:
bridge.stop()
def test_select_requires_value_or_label():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/select", {"selector": "s"}).code == 400
finally:
bridge.stop()
def test_real_browser_failure_is_502():
bridge, _driver, base = start_bridge(driver=FakeDriver(error="net::ERR_NAME_NOT_RESOLVED"))
try:
exc = http_error(f"{base}/goto", {"url": "https://nope.invalid"})
assert exc.code == 502
assert b"ERR_NAME_NOT_RESOLVED" in exc.read()
finally:
bridge.stop()
def test_unavailable_browser_is_503_with_install_hint():
driver = FakeDriver(unavailable="install the browser bridge stack")
bridge, _driver, base = start_bridge(driver=driver)
try:
exc = http_error(f"{base}/state")
assert exc.code == 503
assert b"install the browser bridge stack" in exc.read()
# /health still answers, so the bridge is diagnosable without a browser.
assert get(f"{base}/health")["ok"] is True
finally:
bridge.stop()
def test_unknown_route_is_404():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/nope").code == 404
finally:
bridge.stop()
def test_token_guards_the_bridge():
bridge, _driver, base = start_bridge(token="sekret")
try:
assert http_error(f"{base}/state", token=None).code == 401
assert get(f"{base}/health", token="sekret")["platform"] == "browser"
finally:
bridge.stop()
def test_stop_closes_the_driver():
bridge, driver, _base = start_bridge()
bridge.stop()
assert driver.closed is True
def test_check_requirements_never_blocks_startup():
# An optional dependency must not take down the other bridges, so the check
# is honest-but-permissive and a missing browser surfaces as a 503 on use.
assert BrowserBridge({}).check_requirements() == (True, None)
def test_bad_engine_falls_back_to_chromium():
assert BrowserBridge({"engine": "netscape"}).engine == "chromium"
assert BrowserBridge({"engine": "WebKit"}).engine == "webkit"
def test_executable_path_and_channel_are_plumbed():
bridge = BrowserBridge(
{"channel": "chrome", "executable_path": "/usr/bin/google-chrome"}
)
assert bridge.channel == "chrome"
assert bridge.executable_path == "/usr/bin/google-chrome"
# The real driver (no injected double) carries them; executable_path wins at
# launch, so the managed download is skipped entirely.
assert bridge.client.channel == "chrome"
assert bridge.client.executable_path == "/usr/bin/google-chrome"
def test_driver_defaults_to_managed_browser():
driver = BrowserDriver()
assert driver.channel == ""
assert driver.executable_path == ""
# ---- driver dependency handling ----
def test_driver_unavailable_without_playwright(monkeypatch):
import semif_agent.bridges.browser_client as browser_client
monkeypatch.setattr(browser_client.importlib.util, "find_spec", lambda name: None)
driver = BrowserDriver()
assert driver.configured is False
with pytest.raises(BrowserUnavailable):
driver.state()
# No dangling loop/thread was started.
driver.close()
# ---- catalog / codegen surface ----
def test_known_infos_include_browser():
infos = {info.name: info for info in known_infos()}
assert "browser" in infos
info = infos["browser"]
assert info.service == "browser"
assert info.url_config_var == "browser_bridge_url"
assert info.auth_header == "X-Semif-Token"
assert info.auth_config_var == "browser_bridge_token"
assert any("/goto" in endpoint for endpoint in info.endpoints)
def test_describe_bridges_covers_browser():
text = describe_bridges()
assert "browser_bridge_url" in text
assert "/screenshot" in text
assert "Playwright" in text
def test_derived_config_vars_for_browser():
config = {"bridges": {"browser": {"host": "127.0.0.1", "port": 5232, "token": "b"}}}
derived = derived_config_vars(config)
assert derived["browser_bridge_url"] == "http://127.0.0.1:5232"
assert derived["browser_bridge_token"] == "b"
def test_build_bridge_returns_browser():
bridge = build_bridge({"bridges": {"browser": {"port": 5232}}}, "browser")
assert isinstance(bridge, BrowserBridge)
File diff suppressed because it is too large. Load diff
-646
View File
@@ -1,646 +0,0 @@
"""Pure-stdlib tests for the Outlook (Microsoft Graph) bridge.
A loopback `http.server` plays Microsoft's token endpoint and Graph API so the
bridge's own client is exercised over HTTP with no mocking of the transport. The
decision engine and LLM are never involved. A few route tests inject a fake
client to check wiring/validation without a server. Passing these proves
mechanics only; a real run against the user's Microsoft account is the only proof
the integration works.
"""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
import pytest
from semif_agent.bridges.outlook import OutlookBridge
from semif_agent.bridges.outlook_client import (
OutlookAuthRequired,
OutlookClient,
OutlookError,
load_token,
run_device_code_flow,
save_token,
)
from semif_agent.bridges.registry import build_bridge, derived_config_vars, describe_bridges, known_infos
class FakeGraph:
"""A minimal but real Microsoft-shaped HTTP server (token + Graph)."""
def __init__(self):
self.calls = []
self.refresh_calls = 0
self.device_polls = 0
self.token_status = 200
self._server = None
self._thread = None
# ---- lifecycle ----
def start(self):
fake = self
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, status, payload):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _dispatch(self, method):
body = self._read()
fake.calls.append((method, self.path, dict(self.headers), body))
status, payload = fake.handle(method, self.path, body)
if status == 204:
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
return
if isinstance(payload, bytes):
self.send_response(status)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
return
self._send(status, payload)
def do_GET(self):
self._dispatch("GET")
def do_POST(self):
self._dispatch("POST")
def do_PUT(self):
self._dispatch("PUT")
def do_PATCH(self):
self._dispatch("PATCH")
def do_DELETE(self):
self._dispatch("DELETE")
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start()
return f"http://127.0.0.1:{self._server.server_address[1]}"
def stop(self):
if self._server is not None:
self._server.shutdown()
self._server.server_close()
self._server = None
# ---- routing ----
def handle(self, method, path, body):
parsed = urlparse(path)
route = parsed.path
query = parse_qs(parsed.query)
# ---- OAuth token endpoint ----
if route.endswith("/oauth2/v2.0/devicecode"):
return 200, {
"device_code": "dev-code",
"user_code": "ABCD-EFGH",
"verification_uri": "https://microsoft.com/devicelogin",
"interval": 1,
"expires_in": 900,
"message": "go to https://microsoft.com/devicelogin and enter ABCD-EFGH",
}
if route.endswith("/oauth2/v2.0/token"):
fields = parse_qs(body.decode("utf-8"))
grant = (fields.get("grant_type") or [""])[0]
if grant == "refresh_token":
self.refresh_calls += 1
return self.token_status, {
"access_token": f"refreshed-{self.refresh_calls}",
"refresh_token": f"rotated-{self.refresh_calls}",
"expires_in": 3600,
"token_type": "Bearer",
"scope": "Mail.ReadWrite",
}
# device-code poll: pending once, then success
self.device_polls += 1
if self.device_polls < 2:
return 400, {"error": "authorization_pending"}
return 200, {
"access_token": "device-access",
"refresh_token": "device-refresh",
"expires_in": 3600,
"token_type": "Bearer",
"scope": "Mail.ReadWrite",
}
# ---- Graph ----
if method == "GET" and route == "/v1.0/me":
return 200, {
"id": "user-1",
"displayName": "Jane Doe",
"mail": "jane@example.com",
"userPrincipalName": "jane@example.com",
}
if method == "GET" and route == "/v1.0/me/mailFolders":
return 200, {
"value": [
{"id": "inbox", "displayName": "Inbox", "totalItemCount": 3, "unreadItemCount": 1}
]
}
if method == "GET" and route == "/v1.0/me/mailFolders/inbox/messages":
return 200, {
"value": [
{
"id": "m1",
"subject": "Hello",
"from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}},
"toRecipients": [{"emailAddress": {"address": "jane@example.com"}}],
"ccRecipients": [],
"receivedDateTime": "2026-10-08T09:00:00Z",
"isRead": False,
"hasAttachments": False,
"bodyPreview": "Hi there",
"importance": "normal",
"webLink": "https://outlook/m1",
}
]
}
if method == "GET" and route == "/v1.0/me/messages/m1":
return 200, {
"id": "m1",
"subject": "Hello",
"from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}},
"toRecipients": [{"emailAddress": {"address": "jane@example.com"}}],
"ccRecipients": [],
"receivedDateTime": "2026-10-08T09:00:00Z",
"isRead": False,
"hasAttachments": False,
"body": {"contentType": "text", "content": "Hi there"},
"bodyPreview": "Hi there",
"importance": "normal",
"webLink": "https://outlook/m1",
}
if method == "POST" and route == "/v1.0/me/sendMail":
self.sent = json.loads(body.decode("utf-8"))
return 202, {}
if method == "POST" and route == "/v1.0/me/messages":
payload = json.loads(body.decode("utf-8"))
return 201, {"id": "draft-1", "subject": payload.get("subject", "")}
if method == "GET" and route == "/v1.0/me/calendars":
return 200, {
"value": [
{"id": "cal1", "name": "Calendar", "color": "auto", "isDefaultCalendar": True, "canEdit": True}
]
}
if method == "GET" and route == "/v1.0/me/calendarView":
return 200, {
"value": [
{
"id": "e1",
"subject": "Standup",
"start": {"dateTime": "2026-10-08T09:00:00.0000000", "timeZone": "UTC"},
"end": {"dateTime": "2026-10-08T09:30:00.0000000", "timeZone": "UTC"},
"isAllDay": False,
"location": {"displayName": "Room 1"},
"bodyPreview": "",
"showAs": "busy",
"isOnlineMeeting": False,
"webLink": "https://outlook/e1",
"organizer": {"emailAddress": {"address": "jane@example.com"}},
}
]
}
if method == "POST" and route == "/v1.0/me/events":
payload = json.loads(body.decode("utf-8"))
return 201, {
"id": "new-event",
"subject": payload.get("subject"),
"webLink": "https://outlook/new-event",
}
if method == "PATCH" and route.startswith("/v1.0/me/events/"):
payload = json.loads(body.decode("utf-8"))
return 200, {"id": route.rsplit("/", 1)[-1], "subject": payload.get("subject", "")}
if method == "DELETE" and route.startswith("/v1.0/me/events/"):
return 204, {}
if method == "GET" and route == "/v1.0/me/todo/lists":
return 200, {
"value": [
{"id": "list1", "displayName": "Tasks", "isOwner": True, "wellknownListName": "defaultList"}
]
}
if method == "GET" and route == "/v1.0/me/todo/lists/list1/tasks":
return 200, {
"value": [
{
"id": "t1",
"title": "Buy milk",
"status": "notStarted",
"importance": "normal",
"dueDateTime": {"dateTime": "2026-10-10T00:00:00", "timeZone": "UTC"},
"completedDateTime": {},
"body": {"content": ""},
}
]
}
if method == "POST" and route == "/v1.0/me/todo/lists/list1/tasks":
payload = json.loads(body.decode("utf-8"))
return 201, {"id": "t2", "title": payload.get("title")}
if method == "PATCH" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"):
payload = json.loads(body.decode("utf-8"))
return 200, {"id": route.rsplit("/", 1)[-1], "status": payload.get("status", "notStarted")}
if method == "DELETE" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"):
return 204, {}
if method == "GET" and route == "/v1.0/me/contacts":
return 200, {
"value": [
{
"id": "c1",
"displayName": "Bob Smith",
"givenName": "Bob",
"surname": "Smith",
"emailAddresses": [{"address": "bob@example.com"}],
"businessPhones": ["555-1234"],
"homePhones": [],
"mobilePhone": None,
"companyName": "Acme",
"jobTitle": "Dev",
}
]
}
if method == "GET" and route == "/v1.0/me/drive/root/children":
return 200, {
"value": [
{
"id": "f1",
"name": "notes.txt",
"size": 5,
"lastModifiedDateTime": "2026-10-08T08:00:00Z",
"file": {"mimeType": "text/plain"},
"parentReference": {"path": "/drive/root:"},
"webUrl": "https://onedrive/f1",
}
]
}
if route.startswith("/v1.0/me/drive/root:/") and route.endswith(":"):
return 200, {
"id": "f1",
"name": "notes.txt",
"size": 5,
"file": {"mimeType": "text/plain"},
"lastModifiedDateTime": "2026-10-08T08:00:00Z",
"webUrl": "https://onedrive/f1",
}
if route.startswith("/v1.0/me/drive/root:/") and route.endswith("/content"):
if method == "GET":
return 200, b"hello"
return 201, {"id": "f2", "size": 5, "webUrl": "https://onedrive/f2"}
return 404, {"error": {"code": "notFound", "message": f"no fake route for {method} {route}"}}
@pytest.fixture()
def fake():
server = FakeGraph()
base = server.start()
try:
yield server, base
finally:
server.stop()
def make_client(fake, tmp_path, *, token="tok", expires_at=None, refresh="r1", graph_suffix="/v1.0"):
server, base = fake
token_path = tmp_path / "token.json"
if token is not None:
save_token(
str(token_path),
{
"access_token": token,
"refresh_token": refresh,
"expires_at": 9999999999 if expires_at is None else expires_at,
"token_type": "Bearer",
},
)
return OutlookClient(
"client-1",
tenant="common",
token_path=str(token_path),
graph=base + graph_suffix,
login=base,
)
# ---- OAuth ----
def test_device_code_flow_polls_until_success(fake):
server, base = fake
lines = []
token = run_device_code_flow(
"client-1", "common", out=lines.append, sleep=lambda _s: None, login=base
)
assert token["access_token"] == "device-access"
assert token["refresh_token"] == "device-refresh"
assert any("ABCD-EFGH" in line for line in lines)
assert server.device_polls == 2
def test_token_refresh_on_expiry(fake, tmp_path):
server, base = fake
client = make_client(fake, tmp_path, token="stale", expires_at=0)
user = client.me()
assert user["display_name"] == "Jane Doe"
assert server.refresh_calls == 1
stored = load_token(str(tmp_path / "token.json"))
assert stored["access_token"] == "refreshed-1"
assert stored["refresh_token"] == "rotated-1"
def test_missing_token_raises_auth_required(tmp_path):
client = OutlookClient(
"client-1", token_path=str(tmp_path / "missing.json"), graph="http://127.0.0.1:1/v1.0"
)
with pytest.raises(OutlookAuthRequired):
client.me()
def test_not_configured_without_client_id(tmp_path):
client = OutlookClient("", token_path=str(tmp_path / "t.json"))
assert client.configured is False
# ---- Graph client ----
def test_me_and_mail(fake, tmp_path):
client = make_client(fake, tmp_path)
assert client.me()["mail"] == "jane@example.com"
folders = client.list_mail_folders()
assert folders[0]["name"] == "Inbox"
messages = client.list_messages("inbox")
assert messages[0]["subject"] == "Hello"
assert messages[0]["from"] == "Alice <alice@example.com>"
assert messages[0]["to"] == ["jane@example.com"]
full = client.get_message("m1")
assert full["body"] == "Hi there"
assert full["body_type"] == "text"
def test_send_mail(fake, tmp_path):
server, _base = fake
client = make_client(fake, tmp_path)
result = client.send_mail(["sam@example.com"], "Lunch", "Tomorrow?", cc=["bob@example.com"])
assert result["ok"] is True
sent = server.sent
assert sent["message"]["subject"] == "Lunch"
assert sent["message"]["toRecipients"][0]["emailAddress"]["address"] == "sam@example.com"
assert sent["message"]["ccRecipients"][0]["emailAddress"]["address"] == "bob@example.com"
assert sent["saveToSentItems"] is True
def test_create_draft(fake, tmp_path):
client = make_client(fake, tmp_path)
result = client.create_draft(["sam@example.com"], "Draft", "body")
assert result["id"] == "draft-1"
assert result["subject"] == "Draft"
def test_list_events(fake, tmp_path):
client = make_client(fake, tmp_path)
events = client.list_events()
assert events[0]["subject"] == "Standup"
assert events[0]["start"] == "2026-10-08T09:00:00.0000000"
assert events[0]["location"] == "Room 1"
assert events[0]["organizer"] == "jane@example.com"
def test_create_event_builds_graph_body(fake, tmp_path):
server, _base = fake
client = make_client(fake, tmp_path)
result = client.create_event(
subject="Dentist",
start="2026-11-10T14:00:00",
all_day=False,
location="Clinic",
timezone_name="America/Chicago",
)
assert result["ok"] is True
assert result["id"] == "new-event"
call = next(c for c in server.calls if c[0] == "POST" and c[1] == "/v1.0/me/events")
body = json.loads(call[3].decode("utf-8"))
assert body["subject"] == "Dentist"
assert body["start"] == {"dateTime": "2026-11-10T14:00:00", "timeZone": "America/Chicago"}
# end defaults to one hour after start
assert body["end"]["dateTime"] == "2026-11-10T15:00:00"
assert body["isAllDay"] is False
assert body["location"] == {"displayName": "Clinic"}
def test_create_event_all_day_defaults_end_next_day(fake, tmp_path):
server, _base = fake
client = make_client(fake, tmp_path)
client.create_event(subject="Conference", start="2026-11-10T00:00:00", all_day=True)
call = next(c for c in server.calls if c[0] == "POST" and c[1] == "/v1.0/me/events")
body = json.loads(call[3].decode("utf-8"))
assert body["isAllDay"] is True
assert body["end"]["dateTime"].startswith("2026-11-11")
def test_tasks_flow(fake, tmp_path):
client = make_client(fake, tmp_path)
lists = client.list_task_lists()
assert lists[0]["is_default"] is True
tasks = client.list_tasks()
assert tasks[0]["title"] == "Buy milk"
created = client.create_task(title="Call mom", due="2026-10-12T09:00:00")
assert created["id"] == "t2"
completed = client.complete_task("t1")
assert completed["status"] == "completed"
def test_contacts(fake, tmp_path):
client = make_client(fake, tmp_path)
contacts = client.list_contacts("bob")
assert contacts[0]["display_name"] == "Bob Smith"
assert contacts[0]["emails"] == ["bob@example.com"]
assert "555-1234" in contacts[0]["phones"]
def test_files_read_and_write(fake, tmp_path):
client = make_client(fake, tmp_path)
entries = client.list_files("/")
assert entries[0]["name"] == "notes.txt"
read = client.read_file("notes.txt")
assert read["content"] == "hello"
assert read["encoding"] == "utf-8"
written = client.write_file("notes.txt", "hello", overwrite=True)
assert written["ok"] is True
assert written["path"] == "notes.txt"
def test_unreachable_graph_is_an_outlook_error(tmp_path):
client = OutlookClient(
"client-1", token_path=str(tmp_path / "t.json"), graph="http://127.0.0.1:1/v1.0"
)
save_token(str(tmp_path / "t.json"), {"access_token": "x", "refresh_token": "r", "expires_at": 9999999999})
with pytest.raises(OutlookError):
client.me()
# ---- bridge routes ----
class StubClient:
configured = True
def __init__(self):
self.calls = []
def me(self):
return {"display_name": "Jane"}
def list_mail_folders(self):
return [{"id": "inbox", "name": "Inbox"}]
def list_messages(self, folder="", count=25, search="", unread_only=False):
self.calls.append(("list_messages", folder, count, search, unread_only))
return [{"id": "m1", "subject": "Hello"}]
def get_message(self, message_id):
return {"id": message_id, "body": "hi"}
def send_mail(self, to, subject, body, cc=(), content_type="text", save_to_sent=True):
self.calls.append(("send_mail", to, subject, body, cc))
return {"ok": True, "to": to}
def create_event(self, **kwargs):
self.calls.append(("create_event", kwargs))
return {"ok": True, "id": "e1"}
def list_events(self, calendar="", start="", end=""):
return [{"id": "e1", "subject": "Standup"}]
def create_task(self, **kwargs):
self.calls.append(("create_task", kwargs))
return {"ok": True, "id": "t1"}
def list_files(self, path="/"):
return [{"name": "notes.txt"}]
def write_file(self, path, content, encoding="utf-8", overwrite=True):
return {"ok": True, "path": path}
def list_calendars(self):
return []
def list_task_lists(self):
return []
def list_tasks(self, task_list=""):
return []
def list_contacts(self, query="", count=50):
return []
def test_bridge_routes_wire_to_client():
stub = StubClient()
bridge = OutlookBridge({"client_id": "c", "token_path": "/tmp/x"}, client=stub)
assert bridge.handle_get("/health", {}) == (200, {"ok": True, "platform": "outlook"})
status, payload = bridge.handle_get("/mail/messages", {"folder": ["inbox"], "count": ["10"]})
assert status == 200 and payload["messages"][0]["subject"] == "Hello"
assert stub.calls[-1] == ("list_messages", "inbox", 10, "", False)
status, payload = bridge.handle_post(
"/mail/send", {"to": ["sam@example.com"], "subject": "Hi", "body": "there"}
)
assert status == 200 and payload["ok"] is True
assert stub.calls[-1] == ("send_mail", ["sam@example.com"], "Hi", "there", [])
status, _payload = bridge.handle_post("/calendars/events", {"subject": "Standup", "start": "2026-01-01T09:00:00"})
assert status == 200
assert stub.calls[-1][0] == "create_event"
def test_bridge_validation_errors():
bridge = OutlookBridge({"client_id": "c"}, client=StubClient())
status, payload = bridge.handle_post("/calendars/events", {"start": "2026-01-01T09:00:00"})
assert status == 400 and "subject" in payload["error"]
status, payload = bridge.handle_post("/mail/send", {"subject": "no recipient"})
assert status == 400 and "to" in payload["error"]
status, _ = bridge.handle_post("/nope", {})
assert status == 404
def test_bridge_unconfigured_is_503():
bridge = OutlookBridge({}, client=StubClient())
bridge.client = type("C", (), {"configured": False})()
assert bridge.handle_get("/mail/messages", {})[0] == 503
assert bridge.handle_post("/mail/send", {"to": ["a@b.c"]})[0] == 503
def test_bridge_auth_required_is_503():
class Unauthorized:
configured = True
def list_messages(self, *args, **kwargs):
raise OutlookAuthRequired("run packs/outlook/scripts/outlook-auth.py")
bridge = OutlookBridge({"client_id": "c"}, client=Unauthorized())
status, payload = bridge.handle_get("/mail/messages", {})
assert status == 503
assert "outlook-auth" in payload["error"]
def test_bridge_maps_real_failure_to_502():
class Broken:
configured = True
def list_messages(self, *args, **kwargs):
raise OutlookError("boom")
bridge = OutlookBridge({"client_id": "c"}, client=Broken())
assert bridge.handle_get("/mail/messages", {})[0] == 502
def test_check_requirements_is_stdlib_only():
assert OutlookBridge({}).check_requirements() == (True, None)
# ---- catalog ----
def test_known_infos_include_outlook():
infos = {info.name: info for info in known_infos()}
assert "outlook" in infos
info = infos["outlook"]
assert info.service == "outlook"
assert info.url_config_var == "outlook_bridge_url"
assert info.auth_header == "X-Semif-Token"
assert info.auth_config_var == "outlook_bridge_token"
def test_describe_bridges_covers_outlook():
text = describe_bridges()
assert "outlook" in text
assert "outlook_bridge_url" in text
assert "Microsoft To Do" in text
def test_derived_config_vars_for_outlook():
derived = derived_config_vars(
{"bridges": {"outlook": {"host": "127.0.0.1", "port": 5231, "token": "o"}}}
)
assert derived["outlook_bridge_url"] == "http://127.0.0.1:5231"
assert derived["outlook_bridge_token"] == "o"
def test_build_bridge_returns_outlook():
bridge = build_bridge({"bridges": {"outlook": {"client_id": "c"}}}, "outlook")
assert isinstance(bridge, OutlookBridge)
assert bridge.client_id == "c"
+31
View File
@@ -10,6 +10,8 @@ user's service is (see AGENTS.md).
import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
@@ -29,6 +31,7 @@ from semif_agent.packs import (
PACKS = Path(__file__).resolve().parent.parent / "packs"
SKILL_DIRS = sorted(path.parent for path in PACKS.glob("*/skills/*/*/skill.py"))
BRIDGE_TESTS = sorted(PACKS.glob("*/bridge/test_*.py"))
def seed_id(seed: Path) -> str:
@@ -152,3 +155,31 @@ def test_seed_hermetic_test_passes(seed, monkeypatch):
monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing)
passed, output = run_skill_test(seed, timeout=30)
assert passed, output
@pytest.mark.parametrize(
"test_file", BRIDGE_TESTS, ids=[f"{p.parent.parent.name}/{p.name}" for p in BRIDGE_TESTS]
)
def test_pack_bridge_test_passes(test_file):
"""A bridge ships with its pack; its hermetic test runs from the pack.
The bridge tests are pytest modules (they use fixtures and `pytest.raises`),
so they run in a subprocess with the checkout on `PYTHONPATH` — the same
import path a real run uses. A pack that declares a bridge but ships no test
is a hole; this parametrization picks up exactly the tests that exist, and
`test_pack_manifests_are_valid` keeps the packs present.
"""
root = str(PACKS.parent)
env = {
**os.environ,
"PYTHONPATH": root + os.pathsep + os.environ.get("PYTHONPATH", ""),
}
proc = subprocess.run(
[sys.executable, "-m", "pytest", str(test_file), "-q", "-p", "no:cacheprovider"],
cwd=root,
capture_output=True,
text=True,
timeout=300,
env=env,
)
assert proc.returncode == 0, (proc.stdout or "") + (proc.stderr or "")