Files
notebook-ai-extension/opencode_bridge/tests/test_client.py
T
tao.chen c919c95842 Initial commit: opencode_bridge JupyterLab extension (Slices 1-3.5)
A JupyterLab extension that bridges the cell UI to a local OpenCode Serve
process. The extension is a dual package: a Python server extension
exposed under /opencode-bridge/*, plus a TypeScript frontend that
registers per-cell toolbars.

Backend (Python, tornado)
- Slice 1: config + auth + OpenCode HTTP client (tornado.httpclient,
  no aiohttp). 4 settings in schema/plugin.json (url, user, password,
  request timeout).
- Slice 2: handlers for /hello, /health, /providers, /edit.
- Slice 2.1 (correction): SessionManager with 1 notebook = 1 session
  mapping, async-safe via per-path locks, 404 recovery via invalidate().
  Two new endpoints: GET /sessions, DELETE /session?notebook=<path>.
- 32 pytest tests pass.

Frontend (TypeScript, JupyterLab 4.6)
- src/types.ts: CellContext, OpenCodeRequest/Response, OpenCodeSettings.
- src/context/cell_context.ts: extract CellContext from a CodeCell +
  its parent NotebookPanel, structured error collection.
- src/api/opencode_client.ts: callOpenCodeEdit, callOpenCodeProviders.
- src/components/opencode_cell_footer.ts: OpenCodeCellFooter Widget
  implementing ICellFooter with 3 buttons (optimize / fix / edit),
  resolved via this.parent instanceof CodeCell. NOT cellToolbar
  (does not exist in JL 4.6) and NOT Widget.findParent (removed in
  @lumino/widgets 2.x).
- src/components/opencode_cell_factory.ts: Cell.ContentFactory
  subclass returning the OpenCodeCellFooter.
- src/components/opencode_installer.ts: installOpenCodeEverywhere
  patches every notebook (existing + new) to use the custom factory.
- src/index.ts: registers the factory, loads settings, fetches
  /providers on activation and logs the list to the console.
- 23 jest tests pass (mocked JupyterLab boundary, pnpm path safe).

Settings
- 6 fields: 3 auth (url/user/password) + 1 timeout + 2 model selection
  (provider/model). Provider list is fetched at startup from
  /opencode-bridge/providers and printed to the browser console so
  users can copy values into Settings Editor.

Docs
- design.md: 6 sections covering architecture, UI flow, API contract,
  TS skeletons, session management (v0.2.1 correction), and
  provider/model selection (v0.2.2 addition).
- CLAUDE.md: agent guidance for working in this repo.
- TODO.md: remaining work for Slices 4-7 + v0.4+ backlog.

CI
- Gitea release workflow at .github/workflows/build.yml.
- Bark notification helper (non-fatal on failure).

Generated artefacts ignored: opencode_bridge/labextension/, _version.py,
*.tsbuildinfo, junit.xml, test.ipynb scratch notebook.
2026-07-22 19:07:58 +08:00

150 lines
5.4 KiB
Python

"""Tests for opencode_bridge.opencode_client."""
import json
from io import BytesIO
import pytest
import tornado.httpclient
import tornado.httputil
from opencode_bridge.config import OpenCodeConfig
from opencode_bridge.opencode_client import OpenCodeClient, OpenCodeError
class MockHTTPClient:
def __init__(self) -> None:
self.calls: list[dict] = []
self.responses: list[tuple[int, object]] = []
async def fetch(self, request, **kwargs) -> tornado.httpclient.HTTPResponse:
self.calls.append({"request": request, "kwargs": kwargs})
status, body = self.responses.pop(0)
buffer = BytesIO(json.dumps(body).encode("utf-8"))
return tornado.httpclient.HTTPResponse(
request=request,
code=status,
headers=tornado.httputil.HTTPHeaders(),
buffer=buffer,
)
@pytest.fixture
def base_config() -> OpenCodeConfig:
return OpenCodeConfig(
url="http://127.0.0.1:4096",
user="opencode",
password="",
request_timeout_seconds=120,
)
def _make_client(config: OpenCodeConfig, responses: list[tuple[int, object]]) -> tuple[OpenCodeClient, MockHTTPClient]:
mock = MockHTTPClient()
mock.responses = responses
return OpenCodeClient(config, http_client=mock), mock
@pytest.mark.asyncio
async def test_health_gets_global_health(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, {"status": "ok"})])
result = await client.health()
assert result == {"status": "ok"}
assert len(mock.calls) == 1
call = mock.calls[0]
assert call["request"].url == "http://127.0.0.1:4096/global/health"
assert call["request"].method == "GET"
@pytest.mark.asyncio
async def test_create_session_posts_title(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, {"id": "s1"})])
result = await client.create_session("foo")
assert result == {"id": "s1"}
call = mock.calls[0]
assert call["request"].url == "http://127.0.0.1:4096/session"
assert call["request"].method == "POST"
body = json.loads(call["request"].body.decode("utf-8"))
assert body == {"title": "foo"}
@pytest.mark.asyncio
async def test_auth_in_fetch_kwargs_when_password_set(base_config: OpenCodeConfig) -> None:
config = base_config._replace(password="secret")
client, mock = _make_client(config, [(200, {"status": "ok"})])
await client.health()
call = mock.calls[0]
assert call["kwargs"].get("auth_username") == "opencode"
assert call["kwargs"].get("auth_password") == "secret"
@pytest.mark.asyncio
async def test_auth_not_in_fetch_kwargs_when_password_empty(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, {"status": "ok"})])
await client.health()
call = mock.calls[0]
assert "auth_username" not in call["kwargs"]
assert "auth_password" not in call["kwargs"]
@pytest.mark.asyncio
async def test_send_message_sync_includes_model_when_provider_and_model_given(
base_config: OpenCodeConfig,
) -> None:
client, mock = _make_client(base_config, [(200, {"done": True})])
parts = [{"type": "text", "text": "hello"}]
result = await client.send_message_sync("s1", parts, provider_id="p1", model_id="m1")
assert result == {"done": True}
call = mock.calls[0]
assert call["request"].url == "http://127.0.0.1:4096/session/s1/message"
body = json.loads(call["request"].body.decode("utf-8"))
assert body["parts"] == parts
assert body["model"] == {"providerID": "p1", "modelID": "m1"}
@pytest.mark.asyncio
async def test_send_message_sync_omits_model_when_provider_or_model_missing(
base_config: OpenCodeConfig,
) -> None:
client, mock = _make_client(base_config, [(200, {"done": True})])
parts = [{"type": "text", "text": "hello"}]
result = await client.send_message_sync("s1", parts)
assert result == {"done": True}
call = mock.calls[0]
body = json.loads(call["request"].body.decode("utf-8"))
assert body["parts"] == parts
assert "model" not in body
@pytest.mark.asyncio
async def test_send_message_sync_includes_system_when_provided() -> None:
"""system param is forwarded into the request body when not None."""
config = OpenCodeConfig(url="http://x:1", user="u", password="")
mock = MockHTTPClient()
mock.responses.append((200, {"info": {}, "parts": []}))
client = OpenCodeClient(config, http_client=mock)
await client.send_message_sync("sid", [{"type": "text", "text": "hi"}], system="be brief")
assert len(mock.calls) == 1
body = json.loads(mock.calls[0]["request"].body.decode("utf-8"))
assert body["system"] == "be brief"
assert body["parts"] == [{"type": "text", "text": "hi"}]
@pytest.mark.asyncio
async def test_delete_session_returns_bool_by_status(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, True), (404, False)])
assert await client.delete_session("s1") is True
assert await client.delete_session("s1") is False
assert len(mock.calls) == 2
assert mock.calls[0]["request"].method == "DELETE"
assert mock.calls[0]["request"].url == "http://127.0.0.1:4096/session/s1"
@pytest.mark.asyncio
async def test_non_2xx_response_raises_with_body(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(500, {"error": "boom"})])
with pytest.raises(OpenCodeError) as exc_info:
await client.health()
assert "boom" in str(exc_info.value)