test: replace false-green checks with behavioral coverage (#6282)
* test: replace false-green checks with behavioral coverage * test: complete behavior-focused audit coverage
This commit is contained in:
1 parent
c7ab7aa6da
commit
74942bd190
91 files changed
+1891
-1391
No files matched your search
@@ -3,10 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
ProgressEvent,
|
||||
@@ -33,84 +35,77 @@ class _MockChannel(BaseChannel):
|
||||
pass
|
||||
|
||||
async def send(self, msg):
|
||||
if isinstance(msg.event, ContextCompactionEvent) and not (
|
||||
msg.event.notify or self.show_compaction_notices
|
||||
):
|
||||
return
|
||||
return await self._send_mock(msg)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager() -> ChannelManager:
|
||||
def manager(tmp_path) -> ChannelManager:
|
||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
||||
mgr = ChannelManager(config, MessageBus())
|
||||
mgr = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
|
||||
mgr.channels["mock"] = _MockChannel({}, mgr.bus)
|
||||
return mgr
|
||||
|
||||
|
||||
async def _dispatch_until(manager: ChannelManager, expected: int) -> None:
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for _ in range(40):
|
||||
if manager.channels["mock"]._send_mock.await_count >= expected:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
finally:
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
def _sent_contents(manager: ChannelManager) -> list[str]:
|
||||
return [call.args[0].content for call in manager.channels["mock"]._send_mock.await_args_list]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_receives_automatic_compaction_but_does_not_render_it(
|
||||
async def test_dispatch_forwards_all_compaction_phases_before_adapter_filtering(
|
||||
manager: ChannelManager,
|
||||
) -> None:
|
||||
manager.channels["mock"].send_progress = False
|
||||
for event in (
|
||||
ProgressEvent(content="ordinary progress"),
|
||||
channel = manager.channels["mock"]
|
||||
channel.send_progress = False
|
||||
channel.show_compaction_notices = False
|
||||
events = [
|
||||
ContextCompactionEvent(compaction_id="auto", phase="started"),
|
||||
ContextCompactionEvent(compaction_id="auto", phase="succeeded"),
|
||||
ContextCompactionEvent(compaction_id="auto-failed", phase="failed"),
|
||||
ContextCompactionEvent(compaction_id="auto-cancelled", phase="cancelled"),
|
||||
ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),
|
||||
ContextCompactionEvent(compaction_id="c1", phase="succeeded", notify=True),
|
||||
):
|
||||
await manager.bus.publish_outbound(
|
||||
outbound_message_for_event(channel="mock", chat_id="chat", event=event)
|
||||
)
|
||||
]
|
||||
await manager.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="mock", chat_id="chat", event=ProgressEvent(content="ordinary progress"),
|
||||
))
|
||||
messages = [
|
||||
outbound_message_for_event(channel="mock", chat_id="chat", event=event)
|
||||
for event in events
|
||||
]
|
||||
for msg in messages:
|
||||
await manager.bus.publish_outbound(msg)
|
||||
final = OutboundMessage(channel="mock", chat_id="chat", content="Final")
|
||||
await manager.bus.publish_outbound(final)
|
||||
delivered = asyncio.Event()
|
||||
|
||||
await _dispatch_until(manager, 2)
|
||||
def record_send(msg):
|
||||
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat", "Final", None):
|
||||
delivered.set()
|
||||
|
||||
contents = _sent_contents(manager)
|
||||
assert "ordinary progress" not in contents
|
||||
assert contents == ["Compressing context…", "Context compacted."]
|
||||
channel._send_mock.side_effect = record_send
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||
finally:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
|
||||
# The recorder sees the manager -> adapter boundary, not a fake presentation rule.
|
||||
received = [call.args[0] for call in channel._send_mock.await_args_list]
|
||||
assert received == [*messages, final]
|
||||
assert [msg.event for msg in received] == [*events, None]
|
||||
assert [msg.content for msg in received[-3:]] == [
|
||||
"Compressing context…", "Context compacted.", "Final",
|
||||
]
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
|
||||
|
||||
@pytest.mark.parametrize("global_value", [False, True])
|
||||
@pytest.mark.parametrize("override", [None, False, True])
|
||||
@pytest.mark.parametrize("key", ["show_compaction_notices", "showCompactionNotices"])
|
||||
async def test_global_notice_policy_and_channel_override(manager, global_value, override, key):
|
||||
def test_global_notice_policy_and_channel_override(manager, global_value, override, key):
|
||||
manager.config.channels.show_compaction_notices = global_value
|
||||
section = {} if override is None else {key: override}
|
||||
channel = manager._build_channel("mock", _MockChannel, section)
|
||||
assert channel.show_compaction_notices is (global_value if override is None else override)
|
||||
channel.send_progress = False # Ordinary progress and compaction are independent policies.
|
||||
manager.channels["mock"] = channel
|
||||
|
||||
for phase in ("started", "succeeded", "failed", "cancelled"):
|
||||
for notify in (False, True):
|
||||
await channel.send(outbound_message_for_event(
|
||||
channel="mock", chat_id="chat",
|
||||
event=ContextCompactionEvent("compact", phase, notify=notify),
|
||||
))
|
||||
|
||||
assert channel._send_mock.await_count == (8 if channel.show_compaction_notices else 4)
|
||||
|
||||
|
||||
def test_global_notice_config_round_trip_and_rebuild(manager):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for ChannelManager delta coalescing to reduce streaming latency."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
@@ -74,8 +75,8 @@ def bus():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(config, bus):
|
||||
manager = ChannelManager(config, bus)
|
||||
def manager(config, bus, tmp_path):
|
||||
manager = ChannelManager(config, bus, config_path=tmp_path / "config.json")
|
||||
manager.channels["mock"] = manager._build_channel("mock", MockChannel, {})
|
||||
return manager
|
||||
|
||||
@@ -121,43 +122,6 @@ class TestDeltaCoalescing:
|
||||
assert merged.metadata == first.metadata
|
||||
assert pending == [second]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_delta_not_coalesced(self, manager, bus):
|
||||
msg = _delta("Hello")
|
||||
await bus.publish_outbound(msg)
|
||||
|
||||
async def process_one():
|
||||
try:
|
||||
m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)
|
||||
event = m.event
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
m, pending = manager._coalesce_stream_deltas(m)
|
||||
for p in pending:
|
||||
await bus.publish_outbound(p)
|
||||
channel = manager.channels.get(m.channel)
|
||||
event = m.event
|
||||
if channel and isinstance(event, StreamDeltaEvent):
|
||||
await channel.send_delta(
|
||||
m.chat_id,
|
||||
m.content,
|
||||
m.metadata,
|
||||
stream_id=event.stream_id,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
await process_one()
|
||||
|
||||
manager.channels["mock"]._send_delta_mock.assert_called_once_with(
|
||||
"chat1",
|
||||
"Hello",
|
||||
{},
|
||||
stream_id=None,
|
||||
stream_end=False,
|
||||
resuming=False,
|
||||
merge_next=False,
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multiple_deltas_coalesced(self, manager, bus):
|
||||
for text in ["Hello", " ", "world", "!"]:
|
||||
@@ -270,38 +234,49 @@ class TestDispatchOutboundWithCoalescing:
|
||||
"""Tests for the full _dispatch_outbound flow with coalescing."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dispatch_coalesces_and_processes_pending(self, manager, bus):
|
||||
await bus.publish_outbound(_delta("A"))
|
||||
await bus.publish_outbound(_delta("B"))
|
||||
await bus.publish_outbound(OutboundMessage(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
content="Final",
|
||||
))
|
||||
@pytest.mark.parametrize("end_stream", [False, True])
|
||||
async def test_dispatch_coalesces_and_delivers_final(self, manager, bus, end_stream):
|
||||
await bus.publish_outbound(_delta("A", stream_id="seg-1"))
|
||||
await bus.publish_outbound(_delta("B", stream_id="seg-1"))
|
||||
if end_stream:
|
||||
await bus.publish_outbound(_end(
|
||||
"C", stream_id="seg-1", resuming=True, merge_next=True,
|
||||
))
|
||||
final = OutboundMessage(channel="mock", chat_id="chat1", content="Final")
|
||||
await bus.publish_outbound(final)
|
||||
delivered = asyncio.Event()
|
||||
received = []
|
||||
|
||||
pending = []
|
||||
processed = []
|
||||
def record_delta(chat_id, delta, metadata, **flags):
|
||||
received.append(("delta", chat_id, delta, metadata, flags))
|
||||
|
||||
msg = pending.pop(0) if pending else await bus.consume_outbound()
|
||||
event = msg.event
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
msg, extra_pending = manager._coalesce_stream_deltas(msg)
|
||||
pending.extend(extra_pending)
|
||||
def record_send(msg):
|
||||
received.append(("send", msg.channel, msg.chat_id, msg.content, msg.event))
|
||||
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat1", "Final", None):
|
||||
delivered.set()
|
||||
|
||||
channel = manager.channels.get(msg.channel)
|
||||
event = msg.event
|
||||
if channel and isinstance(event, StreamDeltaEvent):
|
||||
await channel.send_delta(
|
||||
msg.chat_id,
|
||||
msg.content,
|
||||
msg.metadata,
|
||||
stream_id=event.stream_id,
|
||||
)
|
||||
processed.append(("delta", msg.content))
|
||||
channel = manager.channels["mock"]
|
||||
channel._send_delta_mock.side_effect = record_delta
|
||||
channel._send_mock.side_effect = record_send
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||
finally:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
|
||||
assert processed == [("delta", "AB")]
|
||||
assert len(pending) == 1
|
||||
assert pending[0].content == "Final"
|
||||
assert received == [
|
||||
("delta", "chat1", "ABC" if end_stream else "AB", {}, {
|
||||
"stream_id": "seg-1",
|
||||
"stream_end": end_stream,
|
||||
"resuming": end_stream,
|
||||
"merge_next": end_stream,
|
||||
}),
|
||||
("send", "mock", "chat1", "Final", None),
|
||||
]
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
|
||||
|
||||
class TestProgressFiltering:
|
||||
|
||||
@@ -16,6 +16,7 @@ plugins only implement the streaming primitives.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
@@ -41,6 +42,7 @@ class _MockChannel(BaseChannel):
|
||||
self._delta_mock = AsyncMock()
|
||||
self._end_mock = AsyncMock()
|
||||
self._file_edit_mock = AsyncMock()
|
||||
self.received = []
|
||||
|
||||
async def start(self): # pragma: no cover - not exercised
|
||||
pass
|
||||
@@ -49,27 +51,31 @@ class _MockChannel(BaseChannel):
|
||||
pass
|
||||
|
||||
async def send(self, msg):
|
||||
return await self._send_mock(msg)
|
||||
await self._send_mock(msg)
|
||||
self.received.append(("send", msg))
|
||||
|
||||
async def send_reasoning_delta(self, chat_id, delta, metadata=None, *, stream_id=None):
|
||||
return await self._delta_mock(chat_id, delta, metadata, stream_id=stream_id)
|
||||
await self._delta_mock(chat_id, delta, metadata, stream_id=stream_id)
|
||||
self.received.append(("delta", chat_id, delta, metadata, stream_id))
|
||||
|
||||
async def send_reasoning_end(self, chat_id, metadata=None, *, stream_id=None):
|
||||
return await self._end_mock(chat_id, metadata, stream_id=stream_id)
|
||||
await self._end_mock(chat_id, metadata, stream_id=stream_id)
|
||||
self.received.append(("end", chat_id, metadata, stream_id))
|
||||
|
||||
async def send_file_edit_events(self, chat_id, edits, metadata=None):
|
||||
return await self._file_edit_mock(chat_id, edits, metadata)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager() -> ChannelManager:
|
||||
def manager(tmp_path) -> ChannelManager:
|
||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
||||
mgr = ChannelManager(config, MessageBus())
|
||||
mgr = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
|
||||
mgr.channels["mock"] = _MockChannel({}, mgr.bus)
|
||||
return mgr
|
||||
|
||||
|
||||
def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.workspaces.read_webui_default_access_mode",
|
||||
lambda: "default",
|
||||
@@ -87,7 +93,9 @@ def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monke
|
||||
}
|
||||
)
|
||||
|
||||
mgr = ChannelManager(config, MessageBus(), webui_static_dist=False)
|
||||
mgr = ChannelManager(
|
||||
config, MessageBus(), webui_static_dist=False, config_path=tmp_path / "config.json",
|
||||
)
|
||||
channel = mgr.channels["websocket"]
|
||||
|
||||
scope = channel.gateway.workspaces.default_scope()
|
||||
@@ -142,58 +150,58 @@ async def test_one_shot_reasoning_expands_to_delta_plus_end(manager):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dispatch_drops_reasoning_when_channel_opts_out(manager):
|
||||
@pytest.mark.parametrize("show_reasoning", [False, True])
|
||||
@pytest.mark.parametrize("send_progress", [False, True])
|
||||
async def test_dispatch_reasoning_visibility_is_independent_of_progress(
|
||||
manager, show_reasoning, send_progress,
|
||||
):
|
||||
channel = manager.channels["mock"]
|
||||
channel.show_reasoning = False
|
||||
msg = outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="c1",
|
||||
event=ProgressEvent(content="hidden thinking", reasoning_delta=True),
|
||||
)
|
||||
await manager.bus.publish_outbound(msg)
|
||||
channel.show_reasoning = show_reasoning
|
||||
channel.send_progress = send_progress
|
||||
events = [
|
||||
ProgressEvent(content="first ", reasoning_delta=True, stream_id="r1"),
|
||||
ProgressEvent(content="second", reasoning_delta=True, stream_id="r1"),
|
||||
ProgressEvent(reasoning_end=True, stream_id="r1"),
|
||||
ProgressEvent(content="one-shot reasoning", reasoning=True, stream_id="r2"),
|
||||
ProgressEvent(content="ordinary progress"),
|
||||
]
|
||||
messages = [
|
||||
outbound_message_for_event(channel="mock", chat_id="c1", event=event)
|
||||
for event in events
|
||||
]
|
||||
for msg in messages:
|
||||
await manager.bus.publish_outbound(msg)
|
||||
|
||||
await _pump_one(manager)
|
||||
final = await _dispatch_through_final(manager)
|
||||
|
||||
channel._delta_mock.assert_not_awaited()
|
||||
channel._end_mock.assert_not_awaited()
|
||||
channel._send_mock.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dispatch_delivers_reasoning_when_channel_opts_in(manager):
|
||||
channel = manager.channels["mock"]
|
||||
channel.show_reasoning = True
|
||||
for chunk in ("first ", "second"):
|
||||
await manager.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="c1",
|
||||
event=ProgressEvent(content=chunk, reasoning_delta=True, stream_id="r1"),
|
||||
))
|
||||
await manager.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="c1",
|
||||
event=ProgressEvent(reasoning_end=True, stream_id="r1"),
|
||||
))
|
||||
|
||||
await _pump_one(manager)
|
||||
|
||||
assert channel._delta_mock.await_count == 2
|
||||
channel._end_mock.assert_awaited_once()
|
||||
expected = []
|
||||
if show_reasoning:
|
||||
expected.extend([
|
||||
("delta", "c1", "first ", messages[0].metadata, "r1"),
|
||||
("delta", "c1", "second", messages[1].metadata, "r1"),
|
||||
("end", "c1", messages[2].metadata, "r1"),
|
||||
("delta", "c1", "one-shot reasoning", messages[3].metadata, "r2"),
|
||||
("end", "c1", messages[3].metadata, "r2"),
|
||||
])
|
||||
if send_progress:
|
||||
expected.append(("send", messages[-1]))
|
||||
assert channel.received == [*expected, ("send", final)]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dispatch_silently_drops_reasoning_for_unknown_channel(manager):
|
||||
msg = outbound_message_for_event(
|
||||
await manager.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="ghost",
|
||||
chat_id="c1",
|
||||
event=ProgressEvent(content="nobody home", reasoning_delta=True),
|
||||
)
|
||||
await manager.bus.publish_outbound(msg)
|
||||
event=ProgressEvent(content="nobody home", reasoning_delta=True, stream_id="ghost-r1"),
|
||||
))
|
||||
|
||||
await _pump_one(manager)
|
||||
final = await _dispatch_through_final(manager)
|
||||
|
||||
manager.channels["mock"]._delta_mock.assert_not_awaited()
|
||||
manager.channels["mock"]._send_mock.assert_not_awaited()
|
||||
channel = manager.channels["mock"]
|
||||
assert channel.received == [("send", final)]
|
||||
channel._delta_mock.assert_not_awaited()
|
||||
channel._end_mock.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -259,41 +267,24 @@ async def test_base_channel_file_edit_events_are_noop_safe():
|
||||
assert await channel.send_file_edit_events("c", [{"path": "a.py"}]) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reasoning_routing_does_not_consult_send_progress(manager):
|
||||
"""`show_reasoning` is orthogonal to `send_progress` — turning off
|
||||
progress streaming must not silence reasoning."""
|
||||
channel = manager.channels["mock"]
|
||||
channel.send_progress = False
|
||||
channel.show_reasoning = True
|
||||
await manager.bus.publish_outbound(outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="c1",
|
||||
event=ProgressEvent(content="still surfaces", reasoning_delta=True),
|
||||
))
|
||||
async def _dispatch_through_final(manager: ChannelManager) -> OutboundMessage:
|
||||
"""A same-destination send acknowledges completion of earlier callbacks."""
|
||||
final = OutboundMessage(channel="mock", chat_id="c1", content="Final")
|
||||
delivered = asyncio.Event()
|
||||
|
||||
await _pump_one(manager)
|
||||
def record_send(msg):
|
||||
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "c1", "Final", None):
|
||||
delivered.set()
|
||||
|
||||
channel._delta_mock.assert_awaited_once()
|
||||
|
||||
|
||||
async def _pump_one(manager: ChannelManager) -> None:
|
||||
"""Process currently queued messages through the reasoning dispatch branch."""
|
||||
|
||||
async def dispatch_one(msg: OutboundMessage) -> None:
|
||||
event = msg.event
|
||||
if isinstance(event, ProgressEvent) and (
|
||||
event.reasoning_delta
|
||||
or event.reasoning_end
|
||||
or event.reasoning
|
||||
):
|
||||
channel = manager.channels.get(msg.channel)
|
||||
if channel is not None and channel.show_reasoning:
|
||||
await manager._send_with_retry(channel, msg)
|
||||
|
||||
await dispatch_one(await asyncio.wait_for(manager.bus.consume_outbound(), timeout=1.0))
|
||||
while True:
|
||||
try:
|
||||
await dispatch_one(manager.bus.outbound.get_nowait())
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
manager.channels["mock"]._send_mock.side_effect = record_send
|
||||
await manager.bus.publish_outbound(final)
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||
finally:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
return final
|
||||
@@ -1,67 +1,150 @@
|
||||
"""Executable architecture constraints for the WebSocket transport adapter."""
|
||||
"""Behavioral delegation and executable ownership boundaries for WebSocket."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request, Response
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket import runtime
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
_REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
|
||||
_RUNTIME_PATH = _REPOSITORY_ROOT / "nanobot" / "channels" / "websocket" / "runtime.py"
|
||||
_SESSION_IDENTITY_PATH = _REPOSITORY_ROOT / "nanobot" / "webui" / "session_identity.py"
|
||||
|
||||
|
||||
def _channel_method(name: str) -> ast.AsyncFunctionDef:
|
||||
tree = ast.parse(_RUNTIME_PATH.read_text(encoding="utf-8"))
|
||||
channel = next(
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.ClassDef) and node.name == "WebSocketChannel"
|
||||
@pytest.fixture
|
||||
async def channel(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
config = runtime.WebSocketConfig(allow_from=["client-1"], websocket_requires_token=False)
|
||||
bus = MessageBus()
|
||||
gateway = build_gateway_services(
|
||||
config=config,
|
||||
bus=bus,
|
||||
session_manager=None,
|
||||
static_dist_path=None,
|
||||
workspace_path=tmp_path,
|
||||
default_restrict_to_workspace=True,
|
||||
config_path=tmp_path / "config.json",
|
||||
runtime_model_name=None,
|
||||
runtime_surface="browser",
|
||||
runtime_capabilities_overrides=None,
|
||||
)
|
||||
return next(
|
||||
node
|
||||
for node in channel.body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == name
|
||||
channel = runtime.WebSocketChannel(config, bus, gateway=gateway)
|
||||
try:
|
||||
yield channel
|
||||
finally:
|
||||
async with asyncio.timeout(2):
|
||||
await channel.stop()
|
||||
assert channel._server_task is None
|
||||
assert not channel._connection_outbound
|
||||
assert not channel._outbound_retire_tasks
|
||||
assert not channel._commands.request_tasks
|
||||
|
||||
|
||||
async def test_send_delegates_the_outbound_message_to_the_projector(channel, monkeypatch):
|
||||
send = AsyncMock()
|
||||
hydrate = AsyncMock()
|
||||
monkeypatch.setattr(channel._outbound, "send", send)
|
||||
monkeypatch.setattr(channel._outbound, "hydrate", hydrate)
|
||||
msg = OutboundMessage(
|
||||
channel="websocket", chat_id="chat-1", content="hello", reply_to="m1",
|
||||
media=["/example/image.png"], metadata={"turn_id": "turn-1"},
|
||||
)
|
||||
|
||||
await channel.send(msg)
|
||||
|
||||
def _statements_without_docstring(node: ast.AsyncFunctionDef) -> list[ast.stmt]:
|
||||
body = list(node.body)
|
||||
if (
|
||||
body
|
||||
and isinstance(body[0], ast.Expr)
|
||||
and isinstance(body[0].value, ast.Constant)
|
||||
and isinstance(body[0].value.value, str)
|
||||
):
|
||||
body.pop(0)
|
||||
return body
|
||||
send.assert_awaited_once_with(msg)
|
||||
hydrate.assert_not_awaited()
|
||||
|
||||
|
||||
def test_business_entrypoints_are_thin_transport_delegations() -> None:
|
||||
for method_name in ("_dispatch_envelope", "_hydrate_after_subscribe", "send"):
|
||||
statements = _statements_without_docstring(_channel_method(method_name))
|
||||
assert len(statements) == 1, method_name
|
||||
assert isinstance(statements[0], ast.Expr), method_name
|
||||
assert isinstance(statements[0].value, ast.Await), method_name
|
||||
async def test_subscribe_hydration_delegates_the_requested_chat(channel, monkeypatch):
|
||||
hydrate = AsyncMock()
|
||||
send = AsyncMock()
|
||||
monkeypatch.setattr(channel._outbound, "hydrate", hydrate)
|
||||
monkeypatch.setattr(channel._outbound, "send", send)
|
||||
|
||||
statements = _statements_without_docstring(_channel_method("_dispatch_http"))
|
||||
assert len(statements) == 1
|
||||
assert isinstance(statements[0], ast.Return)
|
||||
assert isinstance(statements[0].value, ast.Await)
|
||||
await channel._hydrate_after_subscribe("chat-2")
|
||||
|
||||
hydrate.assert_awaited_once_with("chat-2")
|
||||
send.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_envelope_delegates_connection_client_and_payload_to_application(channel, monkeypatch):
|
||||
dispatch = AsyncMock()
|
||||
monkeypatch.setattr(channel._commands, "dispatch", dispatch)
|
||||
connection = AsyncMock()
|
||||
envelope = {"type": "subscribe", "chat_id": "chat-2"}
|
||||
|
||||
await channel._dispatch_envelope(connection, "client-1", envelope)
|
||||
|
||||
dispatch.assert_awaited_once_with(connection, "client-1", envelope)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("allow_upgrade", [False, True])
|
||||
async def test_http_delegates_authorization_and_preserves_endpoint_result(
|
||||
channel, monkeypatch, allow_upgrade,
|
||||
):
|
||||
response = None if allow_upgrade else Response(
|
||||
403, "Forbidden", Headers({"Content-Type": "text/plain"}), b"access denied",
|
||||
)
|
||||
process_request = AsyncMock(return_value=response)
|
||||
monkeypatch.setattr(channel.gateway.endpoint, "process_request", process_request)
|
||||
connection = AsyncMock()
|
||||
request = Request("/webui/thread?chat_id=chat-2", Headers())
|
||||
|
||||
result = await channel._dispatch_http(connection, request)
|
||||
|
||||
assert result is response
|
||||
process_request.assert_awaited_once_with(connection, request, is_allowed=channel.is_allowed)
|
||||
authorize = process_request.await_args.kwargs["is_allowed"]
|
||||
assert authorize("client-1") is True
|
||||
assert authorize("other-client") is False
|
||||
|
||||
|
||||
def _session_namespace_literal_lines(source: str) -> list[int]:
|
||||
"""Locate executable namespace literals, not prose or type annotations."""
|
||||
tree = ast.parse(source)
|
||||
ignored = set()
|
||||
for node in ast.walk(tree):
|
||||
annotation = None
|
||||
if isinstance(node, ast.AnnAssign | ast.arg):
|
||||
annotation = node.annotation
|
||||
elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
|
||||
annotation = node.returns
|
||||
if annotation is not None:
|
||||
ignored.update(ast.walk(annotation))
|
||||
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
|
||||
# A standalone string (including a docstring) does not define runtime policy.
|
||||
ignored.add(node.value)
|
||||
return [
|
||||
node.lineno
|
||||
for node in ast.walk(tree)
|
||||
if isinstance(node, ast.Constant)
|
||||
and isinstance(node.value, str)
|
||||
and node.value.startswith("websocket:")
|
||||
and node not in ignored
|
||||
]
|
||||
|
||||
|
||||
def test_persisted_webui_session_prefix_has_one_production_owner() -> None:
|
||||
owners = []
|
||||
# Consumers import session_identity; independent literal keys/prefixes fork its policy.
|
||||
# Exact persisted values and mapping round trips live in test_session_identity.py.
|
||||
owners = {}
|
||||
for path in (_REPOSITORY_ROOT / "nanobot").rglob("*.py"):
|
||||
if "tests" in path.parts or path == _SESSION_IDENTITY_PATH:
|
||||
if "tests" in path.parts:
|
||||
continue
|
||||
if "websocket:" in path.read_text(encoding="utf-8"):
|
||||
owners.append(path.relative_to(_REPOSITORY_ROOT).as_posix())
|
||||
assert owners == []
|
||||
assert 'WEBUI_SESSION_STORAGE_PREFIX = "websocket:"' in _SESSION_IDENTITY_PATH.read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
lines = _session_namespace_literal_lines(path.read_text(encoding="utf-8"))
|
||||
if lines:
|
||||
owners[path.relative_to(_REPOSITORY_ROOT).as_posix()] = lines
|
||||
assert set(owners) == {_SESSION_IDENTITY_PATH.relative_to(_REPOSITORY_ROOT).as_posix()}, owners
|
||||
|
||||
|
||||
def test_runtime_exports_compatibility_protocol_helpers() -> None:
|
||||
|
||||
Reference in new issue
Block a user