Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

test: raise PR coverage to 100% on changed cubepi modules

xf gong50a0c6939433
diff --git a/tests/checkpointer/test_init.py b/tests/checkpointer/test_init.py
new file mode 100644
index 0000000..dbf0b26
--- /dev/null
+++ b/tests/checkpointer/test_init.py
@@ -0,0 +1,31 @@
+"""Tests for cubepi.checkpointer public module __getattr__ lazy imports."""
+
+import pytest
+
+
+def test_postgres_checkpointer_lazy_import_via_public_module() -> None:
+ """`from cubepi.checkpointer import PostgresCheckpointer` hits the lazy path."""
+ import cubepi.checkpointer as pkg
+
+ PG = pkg.PostgresCheckpointer # triggers __getattr__
+ from cubepi.checkpointer.postgres.checkpointer import (
+ PostgresCheckpointer as Direct,
+ )
+
+ assert PG is Direct
+
+
+def test_sqlite_checkpointer_lazy_import_via_public_module() -> None:
+ import cubepi.checkpointer as pkg
+
+ SQ = pkg.SQLiteCheckpointer
+ from cubepi.checkpointer.sqlite import SQLiteCheckpointer as Direct
+
+ assert SQ is Direct
+
+
+def test_unknown_attribute_raises_attribute_error() -> None:
+ import cubepi.checkpointer as pkg
+
+ with pytest.raises(AttributeError, match="has no attribute 'NotAThing'"):
+ _ = pkg.NotAThing
diff --git a/tests/checkpointer/test_postgres.py b/tests/checkpointer/test_postgres.py
index e9b3b11..9f5ba12 100644
--- a/tests/checkpointer/test_postgres.py
+++ b/tests/checkpointer/test_postgres.py
@@ -3,6 +3,9 @@
Full E2E tests are in D1.3 once PostgresCheckpointer is implemented.
"""
+import asyncpg
+import pytest
+
def test_models_import() -> None:
from cubepi.checkpointer.postgres.models import (
@@ -106,13 +109,56 @@ def test_schema_mismatch_without_hint() -> None:
assert "actual=1" in str(err)
+def test_role_of_known_message_types() -> None:
+ """_role_of maps each concrete Message subclass to its role string."""
+ from cubepi.checkpointer.postgres.checkpointer import _role_of
+ from cubepi.providers.base import (
+ AssistantMessage,
+ TextContent,
+ ToolResultMessage,
+ Usage,
+ UserMessage,
+ )
+
+ assert _role_of(UserMessage(content=[TextContent(text="x")])) == "user"
+ assert (
+ _role_of(AssistantMessage(content=[TextContent(text="x")], usage=Usage()))
+ == "assistant"
+ )
+ tr = ToolResultMessage(
+ tool_call_id="tc-1",
+ tool_name="t",
+ content=[TextContent(text="ok")],
+ )
+ assert _role_of(tr) == "tool"
+
+
+def test_role_of_rejects_unknown_message_type() -> None:
+ """_role_of raises for anything that isn't User/Assistant/ToolResult."""
+ from cubepi.checkpointer.postgres.checkpointer import _role_of
+
+ class FakeMessage:
+ pass
+
+ with pytest.raises(TypeError, match="unknown Message type"):
+ _role_of(FakeMessage()) # type: ignore[arg-type]
+
+
+async def test_append_empty_messages_is_noop() -> None:
+ """append([]) returns early without touching the pool — no DB needed."""
+ from cubepi.checkpointer.postgres import PostgresCheckpointer
+
+ cp = PostgresCheckpointer("postgresql://unreachable-host/none")
+ # Pool intentionally never created — early return must precede the assert.
+ assert cp._pool is None
+ await cp.append("thread-x", [])
+
+
# ---------------------------------------------------------------------------
# D1.3 E2E tests — require a real Postgres instance
# ---------------------------------------------------------------------------
-import asyncpg # noqa: E402
-import pytest # noqa: E402
-
async def _setup_schema(dsn: str) -> None:
"""Build the cubepi schema (matching what host alembic would generate)."""
diff --git a/tests/checkpointer/test_sqlite.py b/tests/checkpointer/test_sqlite.py
index 7c6b71a..ffe1d37 100644
--- a/tests/checkpointer/test_sqlite.py
+++ b/tests/checkpointer/test_sqlite.py
@@ -4,7 +4,7 @@ import tempfile
import pytest
from cubepi.checkpointer.sqlite import SQLiteCheckpointer
-from cubepi.providers.base import TextContent, UserMessage
+from cubepi.providers.base import TextContent, ToolResultMessage, UserMessage
@pytest.fixture
@@ -82,6 +82,24 @@ class TestSQLiteCheckpointer:
assert data.messages == []
assert data.extra == {"key": "value"}
+ async def test_round_trip_tool_result_message(self, db_path):
+ """ToolResultMessage round-trips through the tool_result deserializer branch."""
+ async with SQLiteCheckpointer(db_path) as cp:
+ tool_msg = ToolResultMessage(
+ tool_call_id="tc-1",
+ tool_name="search",
+ content=[TextContent(text="result")],
+ )
+ await cp.append("thread-1", [tool_msg])
+
+ data = await cp.load("thread-1")
+ assert data is not None
+ assert len(data.messages) == 1
+ loaded = data.messages[0]
+ assert isinstance(loaded, ToolResultMessage)
+ assert loaded.tool_call_id == "tc-1"
+ assert loaded.content[0].text == "result"
+
async def test_deserialize_unknown_role(self, db_path):
"""A message with an unknown role should be returned as a plain dict."""
async with SQLiteCheckpointer(db_path) as cp:
diff --git a/tests/mcp/test_adapter.py b/tests/mcp/test_adapter.py
index 4833d31..5d965c4 100644
--- a/tests/mcp/test_adapter.py
+++ b/tests/mcp/test_adapter.py
@@ -51,6 +51,26 @@ def test_schema_to_model_boolean_and_number() -> None:
assert instance.rate == 1.5
+def test_schema_to_model_unknown_type_becomes_any() -> None:
+ """An unrecognized JSON Schema type falls back to typing.Any."""
+ from typing import Any
+
+ schema = {
+ "type": "object",
+ "properties": {
+ # Neither a known scalar nor array/object — must hit the Any fallback.
+ "weird": {"type": "totally-not-a-real-type"},
+ },
+ "required": [],
+ }
+ M = mcp_schema_to_pydantic_model(tool_name="x", input_schema=schema)
+ # Field accepts arbitrary values because its type is Any.
+ instance = M(weird={"anything": [1, 2, 3]})
+ assert instance.weird == {"anything": [1, 2, 3]}
+ annotations = M.model_fields["weird"].annotation
+ assert annotations is Any
+
+
def test_schema_to_model_object_field_becomes_dict() -> None:
schema = {
"type": "object",
diff --git a/tests/mcp/test_http_loader.py b/tests/mcp/test_http_loader.py
index 15e9c04..c5b8dbc 100644
--- a/tests/mcp/test_http_loader.py
+++ b/tests/mcp/test_http_loader.py
@@ -1,10 +1,14 @@
"""HTTP MCP loader tests (D2.2).
-Full E2E requires a running MCP test server. We provide a smoke import
-test always, and a skip-unless-env E2E hook (CUBEPI_TEST_MCP_HTTP_URL).
+The loader's transport (`sse_client` + `ClientSession`) is mocked so the
+test runs without a real MCP server. End-to-end against a live server is
+gated behind CUBEPI_TEST_MCP_HTTP_URL.
"""
import os
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+
import pytest
@@ -15,6 +19,162 @@ def test_import_http_loader() -> None:
assert callable(load_mcp_tools_http)
+class _FakeSession:
+ """Stand-in for mcp.ClientSession that records calls and returns canned data."""
+
+ def __init__(self, *streams, tools=None, call_response=None):
+ self._tools = tools or []
+ self._call_response = call_response
+ self.initialized = False
+ self.calls: list[tuple[str, dict]] = []
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return None
+
+ async def initialize(self):
+ self.initialized = True
+
+ async def list_tools(self):
+ return SimpleNamespace(tools=self._tools)
+
+ async def call_tool(self, name, args):
+ self.calls.append((name, args))
+ return self._call_response
+
+
+def _install_fake_transport(monkeypatch, *, tools, call_response):
+ import mcp
+ import mcp.client.sse as sse_mod
+
+ sessions: list[_FakeSession] = []
+ sse_calls: list[dict] = []
+
+ @asynccontextmanager
+ async def fake_sse_client(url, *, headers=None, timeout=None):
+ sse_calls.append({"url": url, "headers": headers, "timeout": timeout})
+ yield ("read-stream-stub", "write-stream-stub")
+
+ def fake_client_session(*streams):
+ sess = _FakeSession(*streams, tools=tools, call_response=call_response)
+ sessions.append(sess)
+ return sess
+
+ monkeypatch.setattr(sse_mod, "sse_client", fake_sse_client)
+ monkeypatch.setattr(mcp, "ClientSession", fake_client_session)
+ return sessions, sse_calls
+
+
+async def test_load_mcp_tools_http_lists_and_calls_tool(monkeypatch) -> None:
+ """Mocked transport: lists tools, then invokes one and serializes response."""
+ from cubepi.mcp import load_mcp_tools_http
+ from cubepi.providers.base import TextContent
+
+ tools_resp = [
+ SimpleNamespace(
+ name="search",
+ description="Search the web",
+ inputSchema={
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ },
+ ),
+ ]
+ call_resp = SimpleNamespace(
+ content=[
+ SimpleNamespace(type="text", text="hello"),
+ SimpleNamespace(type="image", data="ignored"), # non-text dropped
+ ],
+ isError=False,
+ )
+ sessions, sse_calls = _install_fake_transport(
+ monkeypatch, tools=tools_resp, call_response=call_resp
+ )
+
+ tools = await load_mcp_tools_http(
+ "https://mcp.example/sse",
+ headers={"x-test": "1"},
+ timeout=12.5,
+ )
+
+ assert len(tools) == 1
+ tool = tools[0]
+ assert tool.name == "search"
+ assert tool.description == "Search the web"
+ assert sse_calls[0] == {
+ "url": "https://mcp.example/sse",
+ "headers": {"x-test": "1"},
+ "timeout": 12.5,
+ }
+ assert sessions[0].initialized is True
+
+ args = tool.parameters(query="cats")
+ result = await tool.execute("tc-1", args, signal=None, on_update=None)
+
+ # transport opened a second session for the call
+ assert len(sessions) == 2
+ assert sessions[1].calls == [("search", {"query": "cats"})]
+
+ # only the text content block survives serialization
+ assert len(result.content) == 1
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "hello"
+ assert result.is_error is None
+
+
+async def test_load_mcp_tools_http_propagates_is_error(monkeypatch) -> None:
+ from cubepi.mcp import load_mcp_tools_http
+
+ tools_resp = [
+ SimpleNamespace(
+ name="boom",
+ description=None, # falsy description path → ""
+ inputSchema=None, # falsy schema path → empty object schema
+ ),
+ ]
+ call_resp = SimpleNamespace(
+ content=[SimpleNamespace(type="text", text="oops")],
+ isError=True,
+ )
+ _install_fake_transport(monkeypatch, tools=tools_resp, call_response=call_resp)
+
+ tools = await load_mcp_tools_http("https://mcp.example/sse")
+ assert len(tools) == 1
+ tool = tools[0]
+ # falsy → defaults applied
+ assert tool.description == ""
+
+ args = tool.parameters() # empty schema → no required fields
+ result = await tool.execute("tc-2", args, signal=None, on_update=None)
+ assert result.is_error is True
+
+
+async def test_load_mcp_tools_http_handles_empty_content(monkeypatch) -> None:
+ """resp.content == None should not break the serializer."""
+ from cubepi.mcp import load_mcp_tools_http
+
+ tools_resp = [
+ SimpleNamespace(
+ name="silent",
+ description="",
+ inputSchema={"type": "object", "properties": {}},
+ ),
+ ]
+ call_resp = SimpleNamespace(content=None, isError=False)
+ _install_fake_transport(monkeypatch, tools=tools_resp, call_response=call_resp)
+
+ tools = await load_mcp_tools_http("https://mcp.example/sse")
+ args = tools[0].parameters()
+ result = await tools[0].execute("tc-3", args, signal=None, on_update=None)
+ assert result.content == []
+
+
@pytest.mark.asyncio
async def test_load_mcp_tools_http_against_test_server() -> None:
"""End-to-end: connect to a real MCP test server, list + call a tool."""
diff --git a/tests/middleware/test_after_model_response.py b/tests/middleware/test_after_model_response.py
index 1792482..3e40ac9 100644
--- a/tests/middleware/test_after_model_response.py
+++ b/tests/middleware/test_after_model_response.py
@@ -181,6 +181,38 @@ async def test_agent_loops_when_middleware_returns_loop_to_model() -> None:
assert call_count == 2
+async def test_agent_direct_hook_returning_none_emits_message_end() -> None:
+ """When after_model_response is passed directly (bypassing compose) and
+ returns None, the loop still emits message_end via the dedicated branch."""
+ provider = FauxProvider()
+ provider.set_responses([faux_assistant_message("ok")])
+
+ hook_calls: list[AssistantMessage] = []
+
+ async def _hook(response, ctx, *, signal=None):
+ hook_calls.append(response)
+ return None
+
+ agent = Agent(
+ model=Model(id="test", provider="faux"),
+ provider=provider,
+ after_model_response=_hook,
+ )
+
+ events: list[str] = []
+
+ def _listener(event, signal):
+ events.append(event.type)
+
+ agent.subscribe(_listener)
+ await agent.prompt("hi")
+
+ assert len(hook_calls) == 1
+ assert events.count("message_end") >= 1
+ assert "agent_end" in events
+
+
@pytest.mark.asyncio
async def test_agent_no_middleware_natural_flow() -> None:
"""Without after_model_response middleware, natural flow proceeds."""
diff --git a/tests/middleware/test_base.py b/tests/middleware/test_base.py
index 4341e49..3c03642 100644
--- a/tests/middleware/test_base.py
+++ b/tests/middleware/test_base.py
@@ -176,3 +176,56 @@ class TestPartialMiddleware:
assert "transform_context" in hooks
assert "convert_to_llm" not in hooks
assert "before_tool_call" not in hooks
+
+
+class TestBaseMiddlewareDefaults:
+ """Each base Middleware method raises NotImplementedError if invoked directly.
+
+ These default bodies are never reached through compose_middleware (it
+ filters them out via _has_method), so we exercise them explicitly to
+ guarantee the contract: subclasses must override what they declare.
+ """
+
+ async def test_transform_context_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().transform_context([], signal=None)
+
+ async def test_convert_to_llm_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().convert_to_llm([])
+
+ async def test_before_tool_call_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().before_tool_call(None, signal=None)
+
+ async def test_after_tool_call_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().after_tool_call(None, signal=None)
+
+ async def test_transform_system_prompt_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().transform_system_prompt("hello", signal=None)
+
+ async def test_should_stop_after_turn_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().should_stop_after_turn(None)
+
+ async def test_after_model_response_raises(self):
+ import pytest
+
+ with pytest.raises(NotImplementedError):
+ await Middleware().after_model_response(
+ AssistantMessage(content=[]), None, signal=None
+ )