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:
chengyongru authored and GitHub committed 2026-10-18 03:16:25 +08:00
1 parent c7ab7aa6da
commit 74942bd190
91 files changed
+1891 -1391

No files matched your search

@@ -1,5 +1,7 @@
"""Tests for Feishu/Lark domain configuration."""
from unittest.mock import MagicMock
from unittest.mock import ANY, AsyncMock, MagicMock
import pytest
from nanobot.bus.queue import MessageBus
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig
@@ -44,3 +46,46 @@ class TestFeishuConfigDomain:
def test_channel_persists_feishu_domain_from_config(self):
ch = _make_channel(domain="feishu")
assert ch.config.domain == "feishu"
@pytest.mark.asyncio
@pytest.mark.parametrize("domain, expected_domain", [
("feishu", "https://open.feishu.cn"),
("lark", "https://open.larksuite.com"),
])
async def test_start_selects_domain_for_http_and_websocket_sdk_clients(
domain, expected_domain, monkeypatch, tmp_path,
):
lark = pytest.importorskip("lark_oapi")
# Startup must never persist fixture credentials into the active host config.
monkeypatch.setattr("nanobot.config.loader.get_config_path", lambda: tmp_path / "config.json")
monkeypatch.setattr(
"nanobot.channels.feishu.runtime.sync_saved_feishu_identity_boundary",
lambda **_kwargs: False,
)
builder = MagicMock()
for method in ("app_id", "app_secret", "domain", "log_level"):
getattr(builder, method).return_value = builder
monkeypatch.setattr(lark.Client, "builder", lambda: builder)
ws_client = MagicMock()
monkeypatch.setattr(lark.ws, "Client", ws_client)
ch = _make_channel(domain)
async def started(*_args):
ch._running = False
# Keep production start/domain selection, but never open an SDK connection.
ch._ws_runner = MagicMock(start_client=AsyncMock(side_effect=started), stop_client=AsyncMock())
monkeypatch.setattr(ch, "_fetch_bot_open_id", lambda: None)
try:
await ch.start()
builder.domain.assert_called_once_with(expected_domain)
ws_client.assert_called_once_with(
"cli_test", "secret", domain=expected_domain,
event_handler=ANY,
log_level=lark.LogLevel.INFO,
)
assert ch._client is builder.build.return_value
ch._ws_runner.start_client.assert_awaited_once_with(ch.name, ws_client.return_value)
finally:
await ch.stop()
@@ -9,7 +9,7 @@ import pytest
pytest.importorskip("lark_oapi")
from nanobot.bus.queue import MessageBus
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig, _FeishuStreamBuf
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig
def _make_channel() -> FeishuChannel:
@@ -187,12 +187,7 @@ class TestStreamEndReactionCleanup:
@pytest.mark.asyncio
async def test_removes_reaction_on_stream_end(self):
ch = _make_channel()
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
text="Done", card_id="card_1", sequence=3, last_edit=0.0,
)
ch._reaction_ids["om_001"] = "rx_42"
ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))
ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))
ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})
ch._remove_reaction = AsyncMock()
await ch.send_delta(
@@ -201,33 +196,23 @@ class TestStreamEndReactionCleanup:
stream_end=True,
)
ch._remove_reaction.assert_called_once_with("om_001", "rx_42")
ch._remove_reaction.assert_awaited_once_with("om_001", "rx_42")
assert ch._reaction_ids == {"om_other": "rx_other"}
@pytest.mark.asyncio
async def test_no_removal_when_message_id_missing(self):
ch = _make_channel()
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
text="Done", card_id="card_1", sequence=3, last_edit=0.0,
)
ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))
ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))
ch._reaction_ids["om_001"] = "rx_42"
ch._remove_reaction = AsyncMock()
await ch.send_delta(
"oc_chat1", "",
stream_end=True,
)
await ch.send_delta("oc_chat1", "", stream_end=True)
ch._remove_reaction.assert_not_called()
ch._remove_reaction.assert_not_awaited()
assert ch._reaction_ids == {"om_001": "rx_42"}
@pytest.mark.asyncio
async def test_no_removal_when_reaction_id_missing(self):
ch = _make_channel()
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
text="Done", card_id="card_1", sequence=3, last_edit=0.0,
)
ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))
ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))
ch._remove_reaction = AsyncMock()
await ch.send_delta(
@@ -241,26 +226,29 @@ class TestStreamEndReactionCleanup:
@pytest.mark.asyncio
async def test_no_removal_when_not_stream_end(self):
ch = _make_channel()
ch._reaction_ids["om_001"] = "rx_42"
ch._create_streaming_card_sync = MagicMock(return_value=None)
ch._remove_reaction = AsyncMock()
ch._add_reaction = AsyncMock()
ch.config.done_emoji = "DONE"
await ch.send_delta(
"oc_chat1", "more text",
metadata={"message_id": "om_001", "reaction_id": "rx_42"},
metadata={"message_id": "om_001"},
)
ch._remove_reaction.assert_not_called()
ch._remove_reaction.assert_not_awaited()
ch._add_reaction.assert_not_awaited()
assert ch._reaction_ids == {"om_001": "rx_42"}
assert ch._stream_bufs["om_001"].text == "more text"
assert "oc_chat1" not in ch._stream_bufs
@pytest.mark.asyncio
async def test_no_removal_when_resuming(self):
"""resuming=True means more tool-call rounds follow; reaction must persist."""
ch = _make_channel()
ch.config.done_emoji = "DONE"
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
text="partial", card_id="card_1", sequence=3, last_edit=0.0,
)
ch._reaction_ids["om_001"] = "rx_42"
ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))
ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))
ch._remove_reaction = AsyncMock()
ch._add_reaction = AsyncMock()
@@ -281,12 +269,7 @@ class TestStreamEndReactionCleanup:
"""Across resuming rounds, done_emoji is added only on the final round."""
ch = _make_channel()
ch.config.done_emoji = "DONE"
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
text="t", card_id="card_1", sequence=3, last_edit=0.0,
)
ch._reaction_ids["om_001"] = "rx_42"
ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))
ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))
ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})
ch._remove_reaction = AsyncMock()
ch._add_reaction = AsyncMock()
@@ -300,10 +283,8 @@ class TestStreamEndReactionCleanup:
ch._remove_reaction.assert_not_called()
ch._add_reaction.assert_not_called()
# Re-prime the stream buffer for the final round (the previous stream end popped it).
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
text="t", card_id="card_1", sequence=5, last_edit=0.0,
)
assert ch._reaction_ids == {"om_001": "rx_42", "om_other": "rx_other"}
# Final stream end (resuming=False): OnIt removed, done_emoji added.
await ch.send_delta(
"oc_chat1", "",
@@ -311,5 +292,6 @@ class TestStreamEndReactionCleanup:
stream_end=True,
resuming=False,
)
ch._remove_reaction.assert_called_once_with("om_001", "rx_42")
ch._add_reaction.assert_called_once_with("om_001", "DONE")
ch._remove_reaction.assert_awaited_once_with("om_001", "rx_42")
ch._add_reaction.assert_awaited_once_with("om_001", "DONE")
assert ch._reaction_ids == {"om_other": "rx_other"}
@@ -1,3 +1,5 @@
import { vi } from "vitest";
import { channelUiContribution } from "@/channel-plugins/registry";
import { NanobotClient } from "@/lib/nanobot-client";
import type { ConnectionStatus } from "@/lib/types";
@@ -253,16 +255,21 @@ describe("Linear channel UI", () => {
requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));
renderSettingsView({ initialSection: "channels" });
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
fireEvent.change(await screen.findByRole("textbox", { name: "OAuth client ID" }), {
target: { value: "replacement-client" },
});
fireEvent.blur(screen.getByRole("textbox", { name: "OAuth client ID" }));
expect(await screen.findByText("Unable to save settings")).toBeVisible();
expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toHaveValue("replacement-client");
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
await new Promise((resolve) => setTimeout(resolve, 750));
expect(actionCalls()).toHaveLength(1);
expect(actionCalls()[0][1]).not.toHaveProperty("enable");
const input = await screen.findByRole("textbox", { name: "OAuth client ID" });
vi.useFakeTimers();
try {
fireEvent.change(input, { target: { value: "replacement-client" } });
fireEvent.blur(input);
await act(async () => { await vi.advanceTimersByTimeAsync(750); });
expect(screen.getByText("Unable to save settings")).toBeVisible();
expect(input).toHaveValue("replacement-client");
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
await act(async () => { await vi.advanceTimersByTimeAsync(750); });
expect(actionCalls()).toHaveLength(1);
expect(actionCalls()[0][1]).not.toHaveProperty("enable");
} finally {
vi.useRealTimers();
}
});
it("replaces a saved secret only on explicit save and submits just that field", async () => {
@@ -280,10 +287,15 @@ describe("Linear channel UI", () => {
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
const input = screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });
expect(input).toHaveFocus();
fireEvent.change(input, { target: { value: "replacement-secret" } });
fireEvent.blur(input);
await new Promise((resolve) => setTimeout(resolve, 750));
expect(actionCalls()).toHaveLength(0);
vi.useFakeTimers();
try {
fireEvent.change(input, { target: { value: "replacement-secret" } });
fireEvent.blur(input);
await act(async () => { await vi.advanceTimersByTimeAsync(750); });
expect(actionCalls()).toHaveLength(0);
} finally {
vi.useRealTimers();
}
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
await waitFor(() => expect(actionCalls()).toHaveLength(1));
const params = actionCalls()[0][1] as { values: Record<string, unknown> };
@@ -300,14 +312,19 @@ describe("Linear channel UI", () => {
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {
target: { value: "discarded-draft" },
});
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();
await new Promise(resolve => setTimeout(resolve, 750));
expect(actionCalls()).toHaveLength(0);
vi.useFakeTimers();
try {
fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {
target: { value: "discarded-draft" },
});
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();
await act(async () => { await vi.advanceTimersByTimeAsync(750); });
expect(actionCalls()).toHaveLength(0);
} finally {
vi.useRealTimers();
}
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("");
});
@@ -951,14 +951,30 @@ async def test_typing_keepalive_refreshes_periodically(monkeypatch) -> None:
channel._running = True
monkeypatch.setattr(matrix_module, "TYPING_KEEPALIVE_INTERVAL_MS", 10)
refreshed = asyncio.Event()
room_typing = client.room_typing
await channel._start_typing_keepalive("!room:matrix.org")
await asyncio.sleep(0.03)
await channel._stop_typing_keepalive("!room:matrix.org", clear_typing=True)
async def record_typing(**kwargs):
response = await room_typing(**kwargs)
if len([call for call in client.typing_calls if call[1] is True]) >= 2:
refreshed.set()
return response
monkeypatch.setattr(client, "room_typing", record_typing)
task = None
try:
await channel._start_typing_keepalive("!room:matrix.org")
task = channel._typing_tasks["!room:matrix.org"]
await asyncio.wait_for(refreshed.wait(), timeout=5)
finally:
channel._running = False
await channel._stop_typing_keepalive("!room:matrix.org", clear_typing=True)
true_updates = [call for call in client.typing_calls if call[1] is True]
assert len(true_updates) >= 2
assert client.typing_calls[-1] == ("!room:matrix.org", False, TYPING_NOTICE_TIMEOUT_MS)
assert task is not None and task.done()
assert not channel._typing_tasks
@pytest.mark.asyncio
@@ -1365,10 +1381,14 @@ async def test_on_media_message_sets_thread_metadata_when_threaded_event(
monkeypatch.setattr("nanobot.channels.matrix.runtime.get_data_dir", lambda: tmp_path)
channel = MatrixChannel(_make_config(), MessageBus())
client = _FakeAsyncClient("", "", "", None)
client.download_bytes = b"image"
channel.client = client
channel.client = _FakeAsyncClient("", "", "", None)
downloads: list[tuple[str, int]] = []
async def _download_media_bytes(mxc_url: str, limit_bytes: int) -> bytes:
downloads.append((mxc_url, limit_bytes))
return b"image"
monkeypatch.setattr(channel, "_download_media_bytes", _download_media_bytes)
handled: list[dict[str, object]] = []
async def _fake_handle_message(**kwargs) -> None:
@@ -1396,8 +1416,15 @@ async def test_on_media_message_sets_thread_metadata_when_threaded_event(
await channel._on_media_message(room, event)
assert len(downloads) == 1
assert downloads[0][0] == "mxc://example.org/mediaid"
assert downloads[0][1] >= len(b"image")
assert len(handled) == 1
media_paths = handled[0]["media"]
assert len(media_paths) == 1
assert Path(media_paths[0]).read_bytes() == b"image"
metadata = handled[0]["metadata"]
assert metadata["attachments"][0]["path"] == media_paths[0]
assert metadata["thread_root_event_id"] == "$root1"
assert metadata["thread_reply_to_event_id"] == "$event1"
assert metadata["event_id"] == "$event1"
@@ -2322,31 +2349,6 @@ def test_build_matrix_text_content_with_event_id_preserves_thread_relation() ->
assert result["m.new_content"]["m.relates_to"] == relates_to
def test_build_matrix_text_content_no_event_id() -> None:
"""Test that when event_id is not provided, no extra properties are added."""
result = _build_matrix_text_content("Regular message")
# Basic required properties should be present
assert "msgtype" in result
assert "body" in result
assert result["body"] == "Regular message"
# Extra properties for replacement should NOT be present
assert "m.relates_to" not in result
assert "m.new_content" not in result
assert "format" not in result
assert "formatted_body" not in result
def test_build_matrix_text_content_plain_text_no_html() -> None:
"""Test plain text that should not include HTML formatting."""
result = _build_matrix_text_content("Simple plain text")
assert "msgtype" in result
assert "body" in result
assert "format" not in result
assert "formatted_body" not in result
@pytest.mark.asyncio
async def test_send_room_content_returns_room_send_response():
"""Test that _send_room_content returns the response from client.room_send."""
+5 -2
View File
@@ -105,8 +105,11 @@ def test_guess_send_file_type_file() -> None:
def test_guess_send_file_type_by_mime() -> None:
# A filename with no known extension but whose mime type is image/*
assert _guess_send_file_type("photo.xyz_image_test") == QQ_FILE_TYPE_FILE
filename = "photo.xyz_image_test"
assert not _is_image_name(filename)
with patch.object(qq.mimetypes, "guess_type", return_value=("image/png", None)) as guess_type:
assert _guess_send_file_type(filename) == QQ_FILE_TYPE_IMAGE
guess_type.assert_called_once_with(filename)
# ── send() exception handling ───────────────────────────────────────
@@ -90,10 +90,12 @@ def test_markdown_style_mapping(markdown, expected_plain, styled_text, style):
def test_code_block():
plain, styles = _markdown_to_signal("```\nprint('hi')\n```")
assert "print('hi')" in plain
assert styles_for(plain, styles).get("print('hi')\n") == ["MONOSPACE"] or "MONOSPACE" in str(
styles_for(plain, styles)
)
assert plain.rstrip("\n") == "print('hi')"
assert {
span.rstrip("\n"): span_styles
for span, span_styles in utf16_styles_for(plain, styles).items()
} == {"print('hi')": ["MONOSPACE"]}
assert_within_utf16_bounds(plain, styles)
def test_code_block_with_lang():
@@ -167,9 +169,10 @@ def test_header_with_inline_code():
"""Header becomes BOLD; code inside becomes MONOSPACE (not double-BOLD)."""
plain, styles = _markdown_to_signal("# Use `grep`")
assert plain == "Use grep"
sd = styles_for(plain, styles)
assert "BOLD" in sd.get("Use ", []) or "BOLD" in str(styles)
assert "MONOSPACE" in sd.get("grep", [])
assert utf16_styles_for(plain, styles) == {
"Use ": ["BOLD"], "grep": ["MONOSPACE"],
}
assert_within_utf16_bounds(plain, styles)
def test_multiline_mixed():
@@ -435,20 +438,16 @@ def test_inline_code_inside_blockquote():
assert sd.get("grep") == ["MONOSPACE"]
def test_header_with_inner_bold_produces_contiguous_bold_ranges():
"""`# **wrap** me` — header forces BOLD over the whole line; the inner `**`
splits the run, yielding two contiguous BOLD ranges that together cover
"wrap me". This is intentional — Signal renders adjacent same-style ranges
as a single visual span.
"""
def test_header_with_inner_bold_covers_whole_header():
"""Header text is bold regardless of equivalent adjacent range fragmentation."""
plain, styles = _markdown_to_signal("# **wrap** me")
assert plain == "wrap me"
# Both ranges are BOLD; collectively they cover the whole "wrap me".
assert_within_utf16_bounds(plain, styles)
assert all(s.endswith(":BOLD") for s in styles)
bold_ranges = [s for s in styles if s.endswith(":BOLD")]
assert len(bold_ranges) == 2
covered = set()
for entry in bold_ranges:
start, length, _ = entry.split(":", 2)
for i in range(int(start), int(start) + int(length)):
covered.add(i)
assert covered == set(range(len(plain)))
assert covered == set(range(_utf16_len(plain)))
@@ -773,9 +773,12 @@ async def test_running_message_handler_reorders_same_session_updates() -> None:
MessageBus(),
)
seen: list[int] = []
processed = asyncio.Event()
async def fake_process(update, context) -> None:
seen.append(update.message.message_id)
if len(seen) == 2:
processed.set()
channel._process_message_update = fake_process
channel._running = True
@@ -787,12 +790,20 @@ async def test_running_message_handler_reorders_same_session_updates() -> None:
second.update_id = 101
second.message.message_id = 2
await channel._on_message(second, None)
await channel._on_message(first, None)
await asyncio.sleep(0.3)
channel._running = False
workers: set[asyncio.Task[None]] = set()
try:
await channel._on_message(second, None)
workers.update(channel._inbound_workers.values())
await channel._on_message(first, None)
await asyncio.wait_for(processed.wait(), timeout=5)
assert seen == [1, 2]
finally:
workers.update(channel._inbound_workers.values())
await channel.stop()
await asyncio.wait_for(asyncio.gather(*workers, return_exceptions=True), timeout=5)
assert seen == [1, 2]
assert workers
assert all(task.done() for task in workers)
@pytest.mark.asyncio
@@ -92,7 +92,7 @@ from .ws_test_client import http_get as _http_get
# -- Shared helpers (aligned with test_websocket_integration.py) ---------------
_PORT = 29876
_PORT = 0
async def _register_running_turn(
@@ -180,12 +180,36 @@ def _basic_handler(bus: Any, **kw: Any) -> GatewayServices:
)
async def _connect_when_ready(url: str) -> Any:
while True:
try:
return await websockets.connect(url)
except OSError:
await asyncio.sleep(0.02)
@pytest.fixture
async def start_listener():
"""Start test-owned ephemeral listeners and join them even if setup/assertions fail."""
listeners = []
async def start(channel: WebSocketChannel):
assert channel.config.port == 0
task = asyncio.create_task(channel.start())
listeners.append((channel, task))
async with asyncio.timeout(5):
while True:
if task.done():
await task
raise AssertionError("listener stopped before becoming ready")
server = channel._server
if server is not None and server.sockets and server.is_serving():
return server.sockets[0].getsockname()[1], task
await asyncio.sleep(0.01)
try:
yield start
finally:
for channel, task in reversed(listeners):
try:
await asyncio.wait_for(channel.stop(), timeout=5)
await asyncio.wait_for(asyncio.shield(task), timeout=5)
finally:
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
async def _wait_for_connection_cleanup(
@@ -875,8 +899,8 @@ def test_issue_route_secret_matches_empty_secret() -> None:
@pytest.mark.asyncio
async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock) -> None:
port = 29882
async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(
bus,
port=port,
@@ -885,8 +909,7 @@ async def test_token_issue_route_requires_secret_when_static_token_configured(bu
websocketRequiresToken=True,
)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
denied = await _http_get(f"http://127.0.0.1:{port}/custom-token")
@@ -4155,17 +4178,14 @@ async def test_stop_is_idempotent() -> None:
@pytest.mark.asyncio
async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock) -> None:
port = 29876
async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
port, server_task = await start_listener(channel)
try:
client = await asyncio.wait_for(
_connect_when_ready(f"ws://127.0.0.1:{port}/ws?client_id=tester"),
timeout=5,
)
client = await websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=tester")
async with client:
ready_raw = await client.recv()
ready = json.loads(ready_raw)
@@ -4194,12 +4214,11 @@ async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: Magi
@pytest.mark.asyncio
async def test_token_rejects_handshake_when_mismatch(bus: MagicMock) -> None:
port = 29877
async def test_token_rejects_handshake_when_mismatch(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port, path="/", token="secret")
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
@@ -4212,12 +4231,11 @@ async def test_token_rejects_handshake_when_mismatch(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_wrong_path_returns_404(bus: MagicMock) -> None:
port = 29878
async def test_wrong_path_returns_404(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
@@ -4237,8 +4255,8 @@ def test_registry_discovers_websocket_channel() -> None:
@pytest.mark.asyncio
async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock) -> None:
port = 29879
async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(
bus, port=port,
tokenIssuePath="/auth/token",
@@ -4246,8 +4264,7 @@ async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock
websocketRequiresToken=True,
)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
deny = await _http_get(f"http://127.0.0.1:{port}/auth/token")
@@ -4286,8 +4303,9 @@ async def test_settings_api_returns_safe_subset_and_updates_whitelist(
bus: MagicMock,
monkeypatch,
tmp_path,
start_listener,
) -> None:
port = 29891
port = 0
config_path = tmp_path / "config.json"
config = Config()
config.agents.defaults.model = "openai/gpt-4o"
@@ -4321,8 +4339,7 @@ async def test_settings_api_returns_safe_subset_and_updates_whitelist(
channel = _ch(bus, port=port, image_generation_reload=image_reload)
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
webui_client = None
try:
@@ -4700,6 +4717,7 @@ async def test_image_settings_hot_reload_without_restart(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
provider_name: str,
start_listener,
) -> None:
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.image_generation import (
@@ -4707,7 +4725,7 @@ async def test_image_settings_hot_reload_without_restart(
reload_image_generation_tool,
)
port = 29935
port = 0
config_path = tmp_path / "config.json"
config = Config.model_validate({"providers": {"SenseNova": {
"apiKey": "named-image-key", "apiBase": "https://images.test/v1",
@@ -4728,8 +4746,7 @@ async def test_image_settings_hot_reload_without_restart(
channel = _ch(runtime_bus, port=port, image_generation_reload=image_reload)
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
webui_client = None
try:
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
@@ -4786,8 +4803,9 @@ async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
runtime_available: bool,
start_listener,
) -> None:
port = 29936
port = 0
config_path = tmp_path / "config.json"
config = Config()
config.providers.openrouter.api_key = "image-key"
@@ -4803,8 +4821,7 @@ async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(
channel = _ch(bus, port=port, image_generation_reload=image_reload if runtime_available else None)
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
webui_client = None
try:
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
@@ -4829,13 +4846,12 @@ async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(
@pytest.mark.asyncio
async def test_commands_api_returns_slash_command_metadata(bus: MagicMock) -> None:
port = 29892
async def test_commands_api_returns_slash_command_metadata(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
denied = await _http_get(f"http://127.0.0.1:{port}/api/commands")
@@ -4863,8 +4879,8 @@ async def test_commands_api_returns_slash_command_metadata(bus: MagicMock) -> No
@pytest.mark.asyncio
async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:
port = 29893
async def test_bootstrap_exposes_native_surface(bus: MagicMock, start_listener) -> None:
port = 0
channel = WebSocketChannel(
{
"enabled": True,
@@ -4883,8 +4899,7 @@ async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:
),
)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
response = await _http_get(
@@ -4990,12 +5005,11 @@ def test_update_provider_settings_ignores_api_type_for_non_openai(monkeypatch, t
@pytest.mark.asyncio
async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock) -> None:
port = 29880
async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port, streaming=True)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=stream-tester") as client:
@@ -5043,12 +5057,11 @@ async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMoc
@pytest.mark.asyncio
async def test_token_issue_rejects_when_at_capacity(bus: MagicMock) -> None:
port = 29881
async def test_token_issue_rejects_when_at_capacity(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port, tokenIssuePath="/auth/token", tokenIssueSecret="s")
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
# Fill issued tokens to capacity
@@ -5071,12 +5084,11 @@ async def test_token_issue_rejects_when_at_capacity(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock) -> None:
port = 29882
async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port, allowFrom=["alice", "bob"])
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
@@ -5311,12 +5323,11 @@ async def test_side_channel_command_does_not_register_queued_turn(
@pytest.mark.asyncio
async def test_client_id_truncation(bus: MagicMock) -> None:
port = 29883
async def test_client_id_truncation(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
long_id = "x" * 200
@@ -5330,12 +5341,11 @@ async def test_client_id_truncation(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_non_utf8_binary_frame_ignored(bus: MagicMock) -> None:
port = 29884
async def test_non_utf8_binary_frame_ignored(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bin-test") as client:
@@ -5351,8 +5361,8 @@ async def test_non_utf8_binary_frame_ignored(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) -> None:
port = 29885
async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(
bus, port=port,
token="static-secret",
@@ -5360,8 +5370,7 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) ->
tokenIssueSecret="route-secret",
)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
# Get an issued token
@@ -5382,12 +5391,11 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) ->
@pytest.mark.asyncio
async def test_allow_from_empty_list_denies_all(bus: MagicMock) -> None:
port = 29886
async def test_allow_from_empty_list_denies_all(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port, allowFrom=[])
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
@@ -5400,13 +5408,12 @@ async def test_allow_from_empty_list_denies_all(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_websocket_requires_token_without_issue_path(bus: MagicMock) -> None:
async def test_websocket_requires_token_without_issue_path(bus: MagicMock, start_listener) -> None:
"""When websocket_requires_token is True but no token or issue path configured, all connections are rejected."""
port = 29887
port = 0
channel = _ch(bus, port=port, websocketRequiresToken=True)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
# No token at all → 401
@@ -5433,11 +5440,10 @@ async def test_websocket_requires_token_without_issue_path(bus: MagicMock) -> No
@pytest.mark.asyncio
async def test_multiplex_legacy_still_works(bus: MagicMock) -> None:
port = 29930
async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=legacy") as client:
@@ -5471,11 +5477,10 @@ async def test_multiplex_legacy_still_works(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_multiplex_new_chat_roundtrip(bus: MagicMock) -> None:
port = 29931
async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=mp") as client:
@@ -5607,11 +5612,10 @@ async def test_webui_message_envelope_appends_user_transcript(
@pytest.mark.asyncio
async def test_multiplex_two_chats_isolated(bus: MagicMock) -> None:
port = 29932
async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=two") as client:
@@ -5644,11 +5648,10 @@ async def test_multiplex_two_chats_isolated(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_multiplex_invalid_frames_return_error(bus: MagicMock) -> None:
port = 29933
async def test_multiplex_invalid_frames_return_error(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bad") as client:
@@ -5680,11 +5683,10 @@ async def test_multiplex_invalid_frames_return_error(bus: MagicMock) -> None:
@pytest.mark.asyncio
async def test_multiplex_cleanup_on_disconnect(bus: MagicMock) -> None:
port = 29934
async def test_multiplex_cleanup_on_disconnect(bus: MagicMock, start_listener) -> None:
port = 0
channel = _ch(bus, port=port)
server_task = asyncio.create_task(channel.start())
await asyncio.sleep(0.3)
port, server_task = await start_listener(channel)
try:
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=dc") as client:
@@ -101,7 +101,7 @@ def test_sanitize_filename_empty_or_dots_fallback() -> None:
@pytest.mark.asyncio
async def test_download_and_save_success() -> None:
async def test_download_and_save_success(tmp_path: Path) -> None:
"""Successful download writes file and returns sanitized path."""
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
client = _FakeWeComClient()
@@ -110,14 +110,12 @@ async def test_download_and_save_success() -> None:
fake_data = b"\x89PNG\r\nfake image"
client.download_file.return_value = (fake_data, "raw_photo.png")
with patch("nanobot.channels.wecom.runtime.get_media_dir", return_value=Path(tempfile.gettempdir())):
with patch("nanobot.channels.wecom.runtime.get_media_dir", return_value=tmp_path):
path = await channel._download_and_save_media("https://example.com/img.png", "aes_key", "image", "photo.png")
assert path is not None
assert os.path.isfile(path)
assert os.path.basename(path) == "photo.png"
# Cleanup
os.unlink(path)
assert Path(path) == tmp_path / "photo.png"
assert Path(path).read_bytes() == fake_data
@pytest.mark.asyncio
@@ -253,7 +253,10 @@ async def test_qr_fetch_does_not_retry_invalid_request_without_local_tokens(tmp_
@pytest.mark.asyncio
async def test_lifecycle_notifications_are_best_effort() -> None:
channel = _ready_channel()
channel._api_post = AsyncMock(return_value={"ret": 0})
channel._api_post = AsyncMock(side_effect=[
httpx.ReadTimeout("upstream unavailable"),
{"ret": -100, "errmsg": "upstream rejected notification"},
])
await channel._notify_lifecycle("start")
await channel._notify_lifecycle("stop")