Skip to content

The agent that grows with you

test: purge low-value tests, lane py09 (263 removed)

teknium1982165203d5d
diff --git a/tests/gateway/test_stale_platform_lock_retryable.py b/tests/gateway/test_stale_platform_lock_retryable.py
index f4cb68a9985..66b238d6618 100644
--- a/tests/gateway/test_stale_platform_lock_retryable.py
+++ b/tests/gateway/test_stale_platform_lock_retryable.py
@@ -25,7 +25,6 @@ from unittest.mock import MagicMock, patch
import pytest
from gateway.platforms.base import BasePlatformAdapter
-from gateway.run import GatewayRunner
class _StubAdapter(BasePlatformAdapter):
@@ -126,12 +125,8 @@ def test_lock_conflict_names_owning_profile(adapter):
)
assert result is False
- assert adapter._fatal_error_message == (
- "Telegram bot token already in use by the "
- "'lead-gen-outreach' profile gateway (PID 559). "
- "Stop that gateway first "
- "(hermes --profile lead-gen-outreach gateway stop)."
- )
+ assert "lead-gen-outreach" in adapter._fatal_error_message
+ assert "559" in adapter._fatal_error_message
assert adapter._fatal_error_retryable is True
assert adapter._fatal_error_code == "telegram-bot-token_lock"
@@ -160,25 +155,3 @@ def test_lock_conflict_infers_profile_from_legacy_hermes_home(adapter):
)
-def test_lock_conflict_keeps_pid_only_wording_for_legacy_record(adapter):
- """Records with no attribution signal retain the original PID-only message."""
- existing = {
- "pid": 99999,
- "start_time": 123,
- }
-
- with patch(
- "gateway.status.acquire_scoped_lock",
- return_value=(False, existing),
- ), patch.object(adapter, "_write_runtime_status_safe"):
- result = adapter._acquire_platform_lock(
- "telegram-bot-token",
- "test-token",
- "Telegram bot token",
- )
-
- assert result is False
- assert adapter._fatal_error_message == (
- "Telegram bot token already in use (PID 99999). "
- "Stop the other gateway first."
- )
diff --git a/tests/gateway/test_startup_agent_budget_log.py b/tests/gateway/test_startup_agent_budget_log.py
index a8a6118a828..286b7e82e99 100644
--- a/tests/gateway/test_startup_agent_budget_log.py
+++ b/tests/gateway/test_startup_agent_budget_log.py
@@ -4,14 +4,13 @@ import logging
import pytest
-from gateway.config import GatewayConfig
from gateway.run import GatewayRunner, _bridge_max_turns_to_env, _current_max_iterations
from hermes_cli.config import TURN_LIMIT_UNLIMITED
@pytest.mark.parametrize(
("max_turns", "expected"),
- [({"max_turns": 50}, "50"), ({}, "90")],
+ [({"max_turns": 50}, "50"), ({}, "90"), ({"max_turns": "unlimited"}, "unlimited")],
)
def test_agent_budget_line_matches_enforced_limit(monkeypatch, max_turns, expected):
monkeypatch.setenv("HERMES_MAX_ITERATIONS", "90") # .env value: config wins when set, else it is the legacy bridge
@@ -37,15 +36,3 @@ def test_agent_budget_line_matches_enforced_limit(monkeypatch, max_turns, expect
assert ("unlimited" in line[0]) == (enforced == TURN_LIMIT_UNLIMITED)
-async def test_gateway_start_logs_unlimited_agent_budget(monkeypatch, tmp_path, caplog):
- """Drive the real startup path: ``GatewayRunner.start()`` must emit the budget line, and with the
- bridged ``unlimited`` spelling it says so instead of ``int()`` raising inside ``suppress()``
- and logging nothing (#116888)."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setenv("HERMES_MAX_ITERATIONS", "unlimited") # what _bridge_max_turns_to_env writes for max_turns: unlimited
- runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))
- with caplog.at_level(logging.INFO, logger="gateway.run"):
- assert await runner.start() is True
- lines = [r.getMessage() for r in caplog.records if "Agent budget" in r.getMessage()]
- assert lines and "max_iterations=unlimited" in lines[0], caplog.text
diff --git a/tests/gateway/test_startup_connect_parallel.py b/tests/gateway/test_startup_connect_parallel.py
index 1c81112cd74..422f3ee8a99 100644
--- a/tests/gateway/test_startup_connect_parallel.py
+++ b/tests/gateway/test_startup_connect_parallel.py
@@ -209,7 +209,6 @@ class TestTelegramColdStartCap:
"cold-start Telegram budget must be shorter than the reconnect "
f"budget (initial={initial}, full={full})"
)
- assert full == 180.0 # #67498 reconnect budget unchanged
assert initial <= 60.0 # gateway reaches `running` within a minute
def test_other_platforms_unchanged(self, tmp_path, monkeypatch):
diff --git a/tests/gateway/test_startup_watchdog.py b/tests/gateway/test_startup_watchdog.py
index cd6e1e5bbe7..5a090124936 100644
--- a/tests/gateway/test_startup_watchdog.py
+++ b/tests/gateway/test_startup_watchdog.py
@@ -19,7 +19,6 @@ from pathlib import Path
import pytest
-import hermes_state_repair
import hermes_startup_watchdog as sw
from hermes_startup_watchdog import (
@@ -85,85 +84,7 @@ class TestContracts:
assert SERVICE_RESTART_EXIT_CODE == GATEWAY_SERVICE_RESTART_EXIT_CODE
- def test_implementation_module_is_stdlib_only(self):
- """Import-lightness is a correctness property (arm-before-imports,
- no import-lock dependence at fire time): the implementation module
- must not import the gateway/agent/hermes_cli graphs at module level."""
- import ast
- import inspect
-
- source = inspect.getsource(sw)
- tree = ast.parse(source)
- forbidden_roots = {
- "gateway",
- "agent",
- "hermes_cli",
- "hermes_state",
- "hermes_constants",
- "tools",
- "plugins",
- }
- offenders = []
- for node in ast.walk(tree):
- # Only module-level and unconditional imports matter; function-
- # bodied imports (the ledger helper) are deliberate and guarded.
- if isinstance(node, ast.Import):
- names = [alias.name for alias in node.names]
- elif isinstance(node, ast.ImportFrom):
- names = [node.module or ""]
- else:
- continue
- for name in names:
- root = name.split(".")[0]
- if root in forbidden_roots and node.col_offset == 0:
- offenders.append(name)
- assert offenders == []
-
- def test_all_documented_entry_points_arm_the_watchdog(self):
- """Every documented arm site must actually call arm_startup_watchdog,
- so a future entry point can't silently ship unwatched. This is a
- structural contract: the arm sites are the whole point of the
- pre-loop coverage, and they're spread across four files."""
- import ast
- import inspect
- from pathlib import Path
-
- repo_root = Path(__file__).resolve().parents[2]
- arm_sites = {
- # (file, reason) — each must contain an arm_startup_watchdog call
- "hermes_cli/main.py": "argv fast-path (standard `hermes gateway run`)",
- "hermes_cli/gateway.py": "run_gateway() config-bridge re-arm",
- "gateway/run.py": "gateway.run.main() backstop arm",
- "cli.py": "legacy `--gateway` entry point",
- }
- for rel, reason in arm_sites.items():
- path = repo_root / rel
- assert path.exists(), f"arm site file missing: {rel} ({reason})"
- source = path.read_text()
- tree = ast.parse(source)
- # Collect both direct calls and aliased imports (main.py uses
- # `from hermes_startup_watchdog import arm_startup_watchdog as _arm_sw`
- # then calls `_arm_sw()` to keep the fast-path import-light).
- aliases = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.ImportFrom) and node.module == "hermes_startup_watchdog":
- for alias in node.names:
- if alias.name == "arm_startup_watchdog":
- aliases.add(alias.asname or "arm_startup_watchdog")
- calls = []
- for node in ast.walk(tree):
- if isinstance(node, ast.Call):
- fn = node.func
- name = (
- fn.id
- if isinstance(fn, ast.Name)
- else fn.attr
- if isinstance(fn, ast.Attribute)
- else None
- )
- if name in aliases or name == "arm_startup_watchdog":
- calls.append(node.lineno)
- assert calls, f"{rel} has no arm_startup_watchdog call ({reason})"
+
@@ -439,24 +360,7 @@ class TestProgressLease:
assert record["lease_count"] >= 1
assert record["last_lease_phase"] == "brief_phase"
- def test_schema_init_declares_lease(self):
- """hermes_state_schema._init_schema must hold a progress lease so
- multi-GB migrations aren't misread as deadlocks (wiring contract)."""
- import inspect
-
- import hermes_state_schema
-
- src = inspect.getsource(hermes_state_schema.SessionSchemaMixin._init_schema)
- assert "report_startup_progress" in src
- def test_repair_declares_lease(self):
- """repair_state_db_schema (I/O-bound, ~zero CPU) must hold a lease."""
- import inspect
-
- import hermes_state
-
- src = inspect.getsource(hermes_state_repair.repair_state_db_schema)
- assert "report_startup_progress" in src
class TestFire:
@@ -607,22 +511,9 @@ class TestBoundedExit:
time.sleep(0.8)
assert exit_capture.codes == [SERVICE_RESTART_EXIT_CODE]
- def test_escort_uses_no_logging_or_filesystem(self):
- """Structural guarantee: the escort body must not touch logging,
- the filesystem, or imports — only sleep, an Event check, and the
- exit seam."""
- import inspect
-
- src = inspect.getsource(StartupWatchdogHandle._exit_escort)
- for banned in ("logger.", "logging", "open(", "Path(", "import ", "mkdir"):
- assert banned not in src, f"escort must not use {banned!r}"
class TestDumpPath:
- def test_dump_path_under_home(self, tmp_path):
- assert get_startup_watchdog_dump_path(tmp_path) == (
- tmp_path / "logs" / "gateway-startup-watchdog.log"
- )
def test_dump_write_failure_is_swallowed(self, monkeypatch):
monkeypatch.setattr(
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index ef51b6016f3..caa553a0724 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -2,7 +2,6 @@
import json
import os
-import sys
import threading
import time
from pathlib import Path
@@ -572,7 +571,6 @@ class TestGetProcessStartTime:
def test_live_process_is_stable_int(self):
import subprocess
- import time
p = subprocess.Popen(["sleep", "20"])
try:
a = status._get_process_start_time(p.pid)
@@ -611,8 +609,8 @@ class TestTerminatePid:
(["taskkill", "/PID", "123", "/T", "/F"], True, True, 10, windows_hide_flags())
]
+ @pytest.mark.windows_only
def test_windows_force_refuses_pid_without_start_time_guard(self, monkeypatch):
- monkeypatch.setattr(status, "_IS_WINDOWS", True)
calls = []
monkeypatch.setattr(status.subprocess, "run", lambda *args, **kwargs: calls.append(args))
@@ -621,8 +619,8 @@ class TestTerminatePid:
assert calls == []
+ @pytest.mark.windows_only
def test_windows_force_refuses_reused_pid(self, monkeypatch):
- monkeypatch.setattr(status, "_IS_WINDOWS", True)
monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 999)
calls = []
monkeypatch.setattr(status.subprocess, "run", lambda *args, **kwargs: calls.append(args))
diff --git a/tests/gateway/test_status_free_tier_line.py b/tests/gateway/test_status_free_tier_line.py
index eb33f4d107b..51fe916be6d 100644
--- a/tests/gateway/test_status_free_tier_line.py
+++ b/tests/gateway/test_status_free_tier_line.py
@@ -7,7 +7,6 @@ from datetime import datetime
import pytest
-from agent.i18n import t
from gateway.config import Platform
from gateway.session import SessionEntry, build_session_key
from hermes_cli import anon_auth
@@ -115,10 +114,3 @@ async def test_a_status_gate_failure_never_breaks_status(monkeypatch):
assert result == expected
-def test_the_line_comes_from_the_catalog_in_every_language():
- assert t("gateway.status.free_tier") == anon_auth.FREE_TIER_STATUS_LINE
- # Every catalog carries its own translation; the product name, the route and the verb stay verbatim.
- for lang in ("ja", "de"):
- line = t("gateway.status.free_tier", lang=lang)
- assert line != anon_auth.FREE_TIER_STATUS_LINE
- assert line.startswith("Nous · ") and " · nous/welcome · " in line and "/login" in line
diff --git a/tests/gateway/test_status_phrases.py b/tests/gateway/test_status_phrases.py
index 69b134d2f5d..50a18a3ed86 100644
--- a/tests/gateway/test_status_phrases.py
+++ b/tests/gateway/test_status_phrases.py
@@ -1,16 +1,11 @@
import random
from gateway.status_phrases import (
- classify_status_context,
choose_status_phrase,
resolve_status_phrase_catalog,
)
-def test_long_running_context_uses_status_bucket():
- assert classify_status_context("status") == "status"
- assert classify_status_context("heartbeat") == "status"
- assert classify_status_context("long_running") == "status"
def test_status_phrase_does_not_leak_raw_preview_or_args():
diff --git a/tests/gateway/test_stderr_formatting.py b/tests/gateway/test_stderr_formatting.py
index 1d6b27f53dd..ed4f842d2ad 100644
--- a/tests/gateway/test_stderr_formatting.py
+++ b/tests/gateway/test_stderr_formatting.py
@@ -21,8 +21,5 @@ def test_gateway_stderr_formatter_includes_timestamp() -> None:
rendered = _gateway_stderr_formatter().format(record)
- assert re.fullmatch(
- r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} "
- r"ERROR gateway\.run: delivery failed",
- rendered,
- )
+ assert re.match(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", rendered), rendered
+ assert "delivery failed" in rendered
diff --git a/tests/gateway/test_step_callback_compat.py b/tests/gateway/test_step_callback_compat.py
deleted file mode 100644
index ea705e563a0..00000000000
--- a/tests/gateway/test_step_callback_compat.py
+++ /dev/null
@@ -1,75 +0,0 @@
-"""Tests for step_callback backward compatibility.
-
-Verifies that the gateway's step_callback normalization keeps
-``tool_names`` as a list of strings for backward-compatible hooks,
-while also providing the enriched ``tools`` list with results.
-"""
-
-import asyncio
-
-
-class TestStepCallbackNormalization:
- """The gateway's _step_callback_sync normalizes prev_tools from run_agent."""
-
- def _extract_step_callback(self):
- """Build a minimal _step_callback_sync using the same logic as gateway/run.py.
-
- We replicate the closure so we can test normalisation in isolation
- without spinning up the full gateway.
- """
- captured_events = []
-
- class FakeHooks:
- async def emit(self, event_type, data):
- captured_events.append((event_type, data))
-
- hooks_ref = FakeHooks()
- loop = asyncio.new_event_loop()
-
- def _step_callback_sync(iteration: int, prev_tools: list) -> None:
- _names: list[str] = []
- for _t in (prev_tools or []):
- if isinstance(_t, dict):
- _names.append(_t.get("name") or "")
- else:
- _names.append(str(_t))
- asyncio.run_coroutine_threadsafe(
- hooks_ref.emit("agent:step", {
- "iteration": iteration,
- "tool_names": _names,
- "tools": prev_tools,
- }),
- loop,
- )
-
- return _step_callback_sync, captured_events, loop
-
- def test_dict_prev_tools_produce_string_tool_names(self):
- """When prev_tools is list[dict], tool_names should be list[str]."""
- cb, events, loop = self._extract_step_callback()
-
- # Simulate the enriched format from run_agent.py
- prev_tools = [
- {"name": "terminal", "result": '{"output": "hello"}'},
- {"name": "read_file", "result": '{"content": "..."}'},
- ]
-
- try:
- loop.run_until_complete(asyncio.sleep(0)) # prime the loop
- import threading
- t = threading.Thread(target=cb, args=(1, prev_tools))
- t.start()
- t.join(timeout=2)
- loop.run_until_complete(asyncio.sleep(0.1))
- finally:
- loop.close()
-
- assert len(events) == 1
- _, data = events[0]
- # tool_names must be strings for backward compat
- assert data["tool_names"] == ["terminal", "read_file"]
- assert all(isinstance(n, str) for n in data["tool_names"])
- # tools should be the enriched dicts
- assert data["tools"] == prev_tools
-
-
diff --git a/tests/gateway/test_sticker_cache.py b/tests/gateway/test_sticker_cache.py
index ec6f6983b3d..80171d3d9d0 100644
--- a/tests/gateway/test_sticker_cache.py
+++ b/tests/gateway/test_sticker_cache.py
@@ -4,11 +4,9 @@ from unittest.mock import patch
from gateway.sticker_cache import (
_load_cache,
- _save_cache,
get_cached_description,
cache_sticker_description,
build_sticker_injection,
- build_animated_sticker_injection,
)
@@ -36,24 +34,14 @@ class TestCacheSticker:
class TestBuildStickerInjection:
- def test_exact_format_no_context(self):
- result = build_sticker_injection("A cat waving")
- assert result == '[The user sent a sticker~ It shows: "A cat waving" (=^.w.^=)]'
def test_set_name_without_emoji_ignored(self):
"""set_name alone (no emoji) produces no context — only emoji+set_name triggers 'from' clause."""
result = build_sticker_injection("A cat", set_name="MyPack")
- assert result == '[The user sent a sticker~ It shows: "A cat" (=^.w.^=)]'
+ assert "A cat" in result
assert "MyPack" not in result
-class TestBuildAnimatedStickerInjection:
- def test_exact_format_with_emoji(self):
- result = build_animated_sticker_injection(emoji="🎉")
- assert result == (
- "[The user sent an animated sticker 🎉~ "
- "I can't see animated ones yet, but the emoji suggests: 🎉]"
- )
diff --git a/tests/gateway/test_stream_consumer.py b/tests/gateway/test_stream_consumer.py
index 884b127d24e..015abb4d802 100644
--- a/tests/gateway/test_stream_consumer.py
+++ b/tests/gateway/test_stream_consumer.py
@@ -6,26 +6,10 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
-from agent.think_scrubber import THINK_CLOSE_TAGS, THINK_OPEN_TAGS, THINK_TAG_NAMES
+from agent.think_scrubber import THINK_TAG_NAMES
from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig
-from gateway.stream_consumer_think import StreamThinkFilterMixin
-from hermes_cli import cli_stream_mixin
-def test_stream_send_metadata_carries_original_reply_anchor():
- consumer = GatewayStreamConsumer(
- adapter=MagicMock(),
- chat_id="123",
- initial_reply_to_id="456",
- )
-
- assert consumer._metadata_for_send(final=False) == {
- "reply_to_message_id": "456",
- }
- assert consumer._metadata_for_send(final=True) == {
- "reply_to_message_id": "456",
- "notify": True,
- }
# ── _clean_for_display unit tests ────────────────────────────────────────
@@ -934,12 +918,6 @@ class TestFilterAndAccumulate:
assert c._accumulated == "Visible answer"
assert "hidden reasoning" not in c._accumulated
- def test_tag_lists_are_the_scrubbers(self):
- """One owner: CLI and gateway stream filters bind the scrubber's tag tuples, not copies."""
- assert StreamThinkFilterMixin._OPEN_THINK_TAGS is THINK_OPEN_TAGS
- assert StreamThinkFilterMixin._CLOSE_THINK_TAGS is THINK_CLOSE_TAGS
- assert cli_stream_mixin._OPEN_TAGS is THINK_OPEN_TAGS
- assert cli_stream_mixin._CLOSE_TAGS is THINK_CLOSE_TAGS
@pytest.mark.parametrize("name", THINK_TAG_NAMES)
def test_every_scrubber_tag_is_filtered_when_streamed(self, name):
@@ -1142,22 +1120,6 @@ class TestOnNewMessageCallback:
assert events == ["reset", "reset", "reset"]
- @pytest.mark.asyncio
- async def test_no_callback_when_none(self):
- """Consumer works correctly when on_new_message is None (default)."""
- adapter = MagicMock()
- adapter.send = AsyncMock(return_value=SimpleNamespace(success=True, message_id="msg_1"))
- adapter.edit_message = AsyncMock(return_value=SimpleNamespace(success=True))
- adapter.MAX_MESSAGE_LENGTH = 4096
-
- config = StreamConsumerConfig(edit_interval=0.01, buffer_threshold=1)
- consumer = GatewayStreamConsumer(adapter, "chat", config) # no callback
-
- consumer.on_delta("Hello")
- consumer.finish()
- await consumer.run()
-
- assert consumer.already_sent is True
class TestUtf16OverflowDetection:
@@ -1392,8 +1354,6 @@ class TestStripOrphanCloseTags:
text = "Just normal text with no tags."
assert GatewayStreamConsumer._strip_orphan_close_tags(text) == text
- def test_empty_string(self):
- assert GatewayStreamConsumer._strip_orphan_close_tags("") == ""
class TestConfirmedFinalDeliveryConsultsCommentaryRecord:
diff --git a/tests/gateway/test_stream_consumer_draft.py b/tests/gateway/test_stream_consumer_draft.py
index fe7377c720b..3be37932b49 100644
--- a/tests/gateway/test_stream_consumer_draft.py
+++ b/tests/gateway/test_stream_consumer_draft.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
import pytest
@@ -410,13 +410,6 @@ class TestRichAwareOverflow:
fits one rich message isn't fragmented at the legacy 4,096 edit limit."""
- def test_raw_message_limit_mock_adapter_is_safe(self):
- # MagicMock adapters (many existing tests) must not crash or wrongly
- # inflate the limit from a truthy auto-attribute.
- adapter = MagicMock()
- adapter.MAX_MESSAGE_LENGTH = 4096
- consumer = GatewayStreamConsumer(adapter, "12345", StreamConsumerConfig())
- assert consumer._raw_message_limit() == 4096
@pytest.mark.asyncio
async def test_long_rich_reply_not_split_and_final_is_whole(self):
diff --git a/tests/gateway/test_stream_consumer_fresh_final.py b/tests/gateway/test_stream_consumer_fresh_final.py
index ebab522e66a..233c05de95a 100644
--- a/tests/gateway/test_stream_consumer_fresh_final.py
+++ b/tests/gateway/test_stream_consumer_fresh_final.py
@@ -302,12 +302,6 @@ class TestFinalCleanupEditFloodControl:
assert adapter.edit_message.call_count >= 1
-class TestStreamConsumerConfigFreshFinalField:
- """The dataclass field must exist and default to 0 (disabled)."""
-
- def test_default_is_disabled(self):
- cfg = StreamConsumerConfig()
- assert cfg.fresh_final_after_seconds == 0.0
class TestStreamingConfigFreshFinalField:
@@ -323,18 +317,4 @@ class TestStreamingConfigFreshFinalField:
assert cfg.fresh_final_after_seconds == 0.0
-class TestTelegramAdapterDeleteMessage:
- """Contract: Telegram adapter implements ``delete_message``."""
-
- def test_delete_message_method_exists(self):
- telegram = pytest.importorskip("plugins.platforms.telegram.adapter")
- import inspect
- cls = telegram.TelegramAdapter
- assert hasattr(cls, "delete_message"), (
- "TelegramAdapter.delete_message is required for the fresh-final "
- "cleanup path (openclaw/openclaw#72038 port)."
- )
- sig = inspect.signature(cls.delete_message)
- params = list(sig.parameters)
- assert params[:3] == ["self", "chat_id", "message_id"]
diff --git a/tests/gateway/test_stream_consumer_silence.py b/tests/gateway/test_stream_consumer_silence.py
index b8e0109bef0..359ab581a54 100644
--- a/tests/gateway/test_stream_consumer_silence.py
+++ b/tests/gateway/test_stream_consumer_silence.py
@@ -35,37 +35,6 @@ from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig
# is_partial_silence_marker — mid-stream hold-back predicate
# --------------------------------------------------------------------------
-# Buffers that could still resolve to a marker → held back while streaming.
-PARTIAL_POSITIVE = [
- "N",
- "NO",
- "NO_",
- "NO_REP",
- "NO_REPLY", # exact marker, not yet terminated by stream-end
- "NO REPLY",
- "no reply", # canonicalized (case/space-insensitive)
- " no_reply ", # surrounding whitespace stripped
- "[",
- "[SIL",
- "[SILENT]",
- "SILENT",
- "sil",
-]
-
-# Buffers that have already diverged from every marker → stream normally.
-PARTIAL_NEGATIVE = [
- "",
- " ",
- "No reply needed — here is the plan", # diverged past the marker
- "NO_REPLYING", # superset, not a prefix
- "Nope",
- "Hello there",
- "The NO_REPLY token means silence", # marker mentioned mid-prose
- "x" * 65, # over the 64-char cap
- "silence is golden", # 'SILENCE...' is not a marker prefix
-]
-
-
def test_partial_predicate_agrees_with_exact_on_full_markers():
"""Every exact silence marker is also a (trivial) partial of itself."""
from gateway.response_filters import LIVE_GATEWAY_SILENT_MARKERS
diff --git a/tests/gateway/test_stream_consumer_tool_progress.py b/tests/gateway/test_stream_consumer_tool_progress.py
index fc36c7ca047..05f8784683b 100644
--- a/tests/gateway/test_stream_consumer_tool_progress.py
+++ b/tests/gateway/test_stream_consumer_tool_progress.py
@@ -8,14 +8,13 @@ from __future__ import annotations
import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
import pytest
from gateway.stream_consumer import (
GatewayStreamConsumer,
StreamConsumerConfig,
- _TOOL_PROGRESS,
)
@@ -75,89 +74,12 @@ def _make_consumer(*, native_streaming: bool = True) -> GatewayStreamConsumer:
# === UNIT TESTS ===
-class TestAcceptsToolProgress:
- """Tests for the accepts_tool_progress property."""
- def test_native_streaming_accepts(self):
- consumer = _make_consumer(native_streaming=True)
- assert consumer.accepts_tool_progress is True
- def test_non_native_does_not_accept(self):
- consumer = _make_consumer(native_streaming=False)
- assert consumer.accepts_tool_progress is False
-class TestOnToolProgress:
- """Tests for on_tool_progress() enqueue behavior."""
- def test_enqueues_sentinel(self):
- consumer = _make_consumer()
- consumer.on_tool_progress("🔍 Searching...")
- item = consumer._queue.get_nowait()
- assert isinstance(item, tuple)
- assert len(item) == 2
- assert item[0] is _TOOL_PROGRESS
- assert item[1] == "🔍 Searching..."
-
- def test_empty_line_not_enqueued(self):
- consumer = _make_consumer()
- consumer.on_tool_progress("")
- assert consumer._queue.empty()
-
-
-class TestComposeFrameContent:
- """Tests for _compose_frame_content() composition logic (Strategy B)."""
-
- def test_only_tool_lines(self):
- consumer = _make_consumer()
- consumer._tool_progress_lines = ["🔍 Searching...", "💻 Running git log"]
- result = consumer._compose_frame_content()
- assert result == "🔍 Searching...\n💻 Running git log"
-
- def test_only_accumulated(self):
- consumer = _make_consumer()
- consumer._accumulated = "Here is the answer."
- result = consumer._compose_frame_content()
- assert result == "Here is the answer."
-
- def test_both_accumulated_and_tool_lines_strategy_b(self):
- """Strategy B: text + separator + tool status at bottom."""
- consumer = _make_consumer()
- consumer._accumulated = "Here is some text so far."
- consumer._tool_progress_lines = ["🔍 Searching the web..."]
- result = consumer._compose_frame_content()
- assert result == "Here is some text so far.\n\n---\n🔍 Searching the web..."
- def test_multiple_tool_lines_stacked(self):
- consumer = _make_consumer()
- consumer._tool_progress_lines = [
- "🔍 web_search: 'python'",
- "💻 terminal: git log",
- "📄 read_file: main.py",
- ]
- result = consumer._compose_frame_content()
- assert "web_search" in result
- assert "terminal" in result
- assert "read_file" in result
- # Lines are joined with newlines
- assert result.count("\n") == 2
-
- def test_empty_state(self):
- consumer = _make_consumer()
- result = consumer._compose_frame_content()
- assert result == ""
-
-
-class TestSegmentReset:
- """Test that segment reset clears tool progress state."""
-
- def test_reset_clears_tool_progress(self):
- consumer = _make_consumer()
- consumer._tool_progress_lines = ["🔍 Searching..."]
- consumer._tool_progress_active = True
- consumer._reset_segment_state()
- assert consumer._tool_progress_lines == []
- assert consumer._tool_progress_active is False
# === INTEGRATION TESTS (drain loop) ===
@@ -197,58 +119,7 @@ class TestToolProgressDrainLoop:
f"Expected tool progress in mid-frames, got: {[f['text'] for f in frames]}"
)
- @pytest.mark.asyncio
- async def test_tool_progress_then_text_clears_overlay(self):
- """Tool progress → text delta should clear tool lines from frame."""
- consumer = _make_consumer()
- consumer.on_tool_progress("🔍 Searching...")
- consumer.on_delta("Hello world")
- consumer.finish()
-
- task = asyncio.create_task(consumer.run())
- await asyncio.sleep(0.5)
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- # After text arrives, tool_progress_lines should be cleared
- assert consumer._tool_progress_lines == []
- assert "Hello world" in consumer._accumulated
-
- # The finalize frame should contain just the text
- frames = consumer.adapter.frames
- finalize_frames = [f for f in frames if f["finalize"]]
- if finalize_frames:
- assert "Hello world" in finalize_frames[-1]["text"]
- assert "Searching" not in finalize_frames[-1]["text"]
-
- @pytest.mark.asyncio
- async def test_text_then_tool_then_text_strategy_b(self):
- """Strategy B: text → tool → text appends tool at bottom then clears."""
- consumer = _make_consumer()
-
- # Phase 1: initial text
- consumer.on_delta("First part. ")
- # Phase 2: tool progress mid-stream
- consumer.on_tool_progress("🔍 web_search...")
- # Phase 3: more text arrives
- consumer.on_delta("Second part.")
- consumer.finish()
-
- task = asyncio.create_task(consumer.run())
- await asyncio.sleep(0.5)
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
- # Final state: tool lines cleared, accumulated has both text parts
- assert consumer._tool_progress_lines == []
- assert "First part." in consumer._accumulated
- assert "Second part." in consumer._accumulated
@pytest.mark.asyncio
async def test_parallel_tool_calls_stacked(self):
@@ -305,9 +176,8 @@ class TestToolProgressDrainLoop:
frames = consumer.adapter.frames
finalize_frames = [f for f in frames if f["finalize"]]
- if finalize_frames:
- final_text = finalize_frames[-1]["text"]
- assert "The answer is 42. Verified." in final_text
- assert "Searching" not in final_text
- assert "terminal" not in final_text
- assert "---" not in final_text
+ assert finalize_frames, "expected a finalize frame"
+ final_text = finalize_frames[-1]["text"]
+ assert "The answer is 42. Verified." in final_text
+ assert "Searching" not in final_text
+ assert "terminal" not in final_text
diff --git a/tests/gateway/test_stream_consumer_wecom_native.py b/tests/gateway/test_stream_consumer_wecom_native.py
index 875ab3b149e..20a3b2f6c5a 100644
--- a/tests/gateway/test_stream_consumer_wecom_native.py
+++ b/tests/gateway/test_stream_consumer_wecom_native.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
import pytest
@@ -38,7 +38,7 @@ def _make_native_streaming_adapter(
Records every ``send_stream_frame`` call on ``adapter.frames`` for assertions.
"""
- from gateway.platforms.base import BasePlatformAdapter, SendResult
+ from gateway.platforms.base import BasePlatformAdapter
NativeStreamingAdapter = type(
"NativeStreamingAdapter",
@@ -121,12 +121,6 @@ class TestNativeStreamingResolver:
consumer = GatewayStreamConsumer(adapter, "chat-1", cfg)
assert consumer._resolve_native_streaming() is False
- def test_magicmock_adapter_falls_back(self):
- """MagicMock adapters are excluded by isinstance gate."""
- adapter = MagicMock()
- cfg = StreamConsumerConfig(chat_type="dm")
- consumer = GatewayStreamConsumer(adapter, "chat-1", cfg)
- assert consumer._resolve_native_streaming() is False
# === LIFECYCLE ===
@@ -245,31 +239,6 @@ class TestNativeStreamingThrottling:
assert len(finalize_frames) == 1
assert finalize_frames[0]["text"] == "abcdefghij"
- @pytest.mark.asyncio
- async def test_large_growth_emits_mid_frames(self):
- """When text grows by >20 chars, an interim frame should land."""
- adapter = _make_native_streaming_adapter()
- cfg = StreamConsumerConfig(
- chat_type="dm", cursor="",
- edit_interval=0.01, buffer_threshold=5,
- )
- consumer = GatewayStreamConsumer(adapter, "chat-1", cfg)
-
- task = asyncio.create_task(consumer.run())
- await asyncio.sleep(0.02)
- # First chunk well past 20 chars.
- consumer.on_delta("A" * 40)
- await asyncio.sleep(0.05)
- # Second chunk also past 20 chars.
- consumer.on_delta("B" * 40)
- await asyncio.sleep(0.05)
- consumer.finish()
- await task
-
- non_finalize_content_frames = [
- f for f in adapter.frames if not f["finalize"] and f["text"]
- ]
- assert len(non_finalize_content_frames) >= 1
# === FALLBACK ===
@@ -296,6 +265,7 @@ class TestNativeStreamingFallback:
await task
assert consumer._use_native_streaming is False
+ adapter.send.assert_awaited()
@pytest.mark.asyncio
async def test_native_streaming_disables_draft(self):
@@ -729,7 +699,7 @@ class TestClarifyEagerReseed:
per-tick fragments on a non-editable platform."""
# Make the SECOND seed (the eager re-seed) fail while the initial seed
# succeeds, so we actually reach the reopen-pending state first.
- from gateway.platforms.base import BasePlatformAdapter, SendResult
+ from gateway.platforms.base import BasePlatformAdapter
NativeStreamingAdapter = type(
"NativeStreamingAdapter2",
@@ -889,7 +859,7 @@ class TestClarifyEagerReseed:
直接验证 review (b).4 的结论。
"""
# 复用 Point 5 的降级 adapter:第一次空 seed 成功、第二次(eager 再 seed)失败。
- from gateway.platforms.base import BasePlatformAdapter, SendResult
+ from gateway.platforms.base import BasePlatformAdapter
NativeStreamingAdapter = type(
"NativeStreamingAdapter2b",
diff --git a/tests/gateway/test_stream_final_adoption_gate.py b/tests/gateway/test_stream_final_adoption_gate.py
deleted file mode 100644
index a44ecb31042..00000000000
--- a/tests/gateway/test_stream_final_adoption_gate.py
+++ /dev/null
@@ -1,84 +0,0 @@
-"""Regression: only a genuinely COMPLETED turn's final_response may be
-adopted as the stream's authoritative finalize payload (PR 85796 review,
-B6).
-
-agent/conversation_loop.py's interrupt/abort paths return
-{completed: False, interrupted: True, final_response: "Operation
-interrupted during …"} with NO failed key. The finish(final_text) gate
-checked only `not failed`, so the diagnostic was adopted: it sealed the
-user's streamed partial answer over with the interrupt text, AND
-delivered_final_matches then reconciled — suppressing the gateway's own
-error-delivery path, so the diagnostic was the only thing left.
-
-The taxonomy was enumerated from the production writers (all 27
-final_response-bearing return shapes in conversation_loop.py): every
-non-happy-path shape carries completed: False; the happy path routes
-through turn_finalizer.finalize_turn which computes completed=True.
-Gate: completed is not False AND not interrupted AND not failed.
-"""
-
-from types import SimpleNamespace
-
-
-def _adoption_gate(result) -> bool:
- """Mirror of the finish(final_text) adoption gate in gateway/run.py.
-
- Kept in sync by the comment at the call site; this test pins the
- CONTRACT (which result shapes may move delivery ownership into the
- stream consumer), the wiring test below pins the call.
- """
- return (
- isinstance(result, dict)
- and not result.get("failed")
- and not result.get("interrupted")
- and result.get("completed") is not False
- )
-
-
-class TestAdoptionGate:
- def test_happy_path_adopts(self):
- assert _adoption_gate(
- {"completed": True, "failed": False, "interrupted": False,
- "final_response": "the answer"}
- )
-
- def test_interrupt_shape_rejected(self):
- # conversation_loop.py:3089 / 4716 / 6040 / 7279 shape — no failed key.
- assert not _adoption_gate(
- {"completed": False, "interrupted": True,
- "final_response": "Operation interrupted during retry (…)."}
- )
-
- def test_failed_shape_rejected(self):
- assert not _adoption_gate(
- {"completed": False, "failed": True, "final_response": "boom"}
- )
-
- def test_diagnostic_noncompleted_shapes_rejected(self):
- # Shapes with neither failed nor interrupted but completed: False —
- # retry exhaustion, truncation, codex-incomplete (all diagnostics).
- for fr in (
- "Response truncated due to output length limit",
- "Codex response remained incomplete after 3 continuation attempts",
- ):
- assert not _adoption_gate({"completed": False, "final_response": fr})
-
- def test_legacy_result_without_completed_key_adopts(self):
- # Duck-type safety: a result dict lacking the key entirely (older
- # callers/doubles) keeps the pre-review behavior.
- assert _adoption_gate({"final_response": "answer"})
-
-
-class TestGateWiring:
- def test_run_py_gate_matches_contract(self):
- """The gate in gateway/run.py must contain the interrupted and
- completed checks — a source-level pin so the contract test above
- cannot drift green while the call site regresses."""
- import inspect
- import gateway.run_turn_runner as run_mod
-
- src = inspect.getsource(run_mod)
- anchor = src.index("_final_for_stream = None")
- window = src[anchor : anchor + 1200]
- assert 'not result.get("interrupted")' in window
- assert 'result.get("completed") is not False' in window
diff --git a/tests/gateway/test_streaming_tts_consumer.py b/tests/gateway/test_streaming_tts_consumer.py
index 209ba631ae8..d8af61207ee 100644
--- a/tests/gateway/test_streaming_tts_consumer.py
+++ b/tests/gateway/test_streaming_tts_consumer.py
@@ -88,43 +88,6 @@ class FakeVoiceAdapter:
handle.aborted = True
-class SlowStreamer(FakeStreamer):
- """Fake streamer whose iteration intentionally blocks off the event loop."""
-
- def __init__(self, *args, delay_s=0.15, **kwargs):
- super().__init__(*args, **kwargs)
- self.delay_s = delay_s
- self.started = threading.Event()
- self.finished = threading.Event()
-
- def stream(self, text: str):
- self.started.set()
- try:
- for chunk in super().stream(text):
- time.sleep(self.delay_s)
- yield chunk
- finally:
- self.finished.set()
-
-
-class SlowFirstChunkStreamer(FakeStreamer):
- """Blocks before the first chunk so timeout happens before audio starts."""
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.started = threading.Event()
- self.allow_first_chunk = threading.Event()
- self.finished = threading.Event()
-
- def stream(self, text: str):
- self.started.set()
- try:
- self.allow_first_chunk.wait(timeout=5.0)
- yield b"chunk-1-0"
- finally:
- self.finished.set()
-
-
class BlockingSecondChunkStreamer(FakeStreamer):
"""Yields one chunk immediately, then blocks before the remaining chunks."""
@@ -146,28 +109,6 @@ class BlockingSecondChunkStreamer(FakeStreamer):
self.finished.set()
-class UnsupportedAdapter:
- """Adapter that does not support streaming TTS (default base behaviour)."""
-
- def _should_auto_tts_for_chat(self, chat_id):
- return True
-
- def supports_streaming_tts(self, chat_id, audio_format):
- return False
-
- async def begin_streaming_tts(self, chat_id, audio_format, metadata=None):
- return None
-
- async def write_streaming_tts(self, handle, chunk):
- pass
-
- async def finish_streaming_tts(self, handle, *, interrupted=False):
- pass
-
- async def abort_streaming_tts(self, handle, error=None):
- pass
-
-
def _make_consumer(adapter, chat_id, loop, streamer):
"""Build a StreamingTTSConsumer with pre-set internals for testing."""
consumer = StreamingTTSConsumer.__new__(StreamingTTSConsumer)
@@ -356,16 +297,6 @@ class TestAdapterContractDefaults:
adapter = _make_minimal_adapter()
assert adapter.supports_streaming_tts("chat1", AudioFormat()) is False
- def test_begin_returns_none_by_default(self):
- adapter = _make_minimal_adapter()
- loop = asyncio.new_event_loop()
- try:
- result = loop.run_until_complete(
- adapter.begin_streaming_tts("chat1", AudioFormat())
- )
- assert result is None
- finally:
- loop.close()
# ---------------------------------------------------------------------------
@@ -403,46 +334,6 @@ class TestConsumerLifecycle:
_run_test(run)
- def test_post_audio_timeout_keeps_suppression_then_aborts(self):
- """After audible audio, a finalisation timeout aborts the consumer.
-
- The outer gateway loop calls abort() on timeout so no unowned
- consumer task lingers. Suppression is preserved so the gateway
- does not replay from the beginning. Updated for #60671
- hardening: the outer loop now aborts instead of leaving the
- consumer to complete later in the background.
- """
- async def run(loop):
- adapter = FakeVoiceAdapter()
- streamer = BlockingSecondChunkStreamer()
- consumer = _make_consumer(adapter, "chat1", loop, streamer)
-
- consumer.start()
- consumer.on_delta("This is a sentence with a delayed tail. ")
- consumer.finish()
-
- await asyncio.wait_for(asyncio.to_thread(streamer.first_chunk_written.wait, 1.0), timeout=1.0)
- await asyncio.sleep(0)
- assert consumer.audible is True
- assert consumer.suppress_whole_file is True
- assert streamer.finished.is_set() is False
-
- completed = await consumer.wait_complete(timeout=0.01)
- assert completed is False
- assert consumer.suppress_whole_file is True
- assert adapter.written_chunks == [b"chunk-1-0"]
-
- # The outer loop now aborts on timeout after audible audio
- # instead of leaving the consumer running in the background.
- consumer.abort("streaming TTS finalisation timeout")
- await consumer.wait_complete(timeout=2.0)
-
- # The consumer is aborted, not completed.
- assert consumer.completed is False
- assert consumer._aborted is True
- assert consumer.suppress_whole_file is True
-
- _run_test(run)
class TestStreamerFormatAndLooping:
@@ -774,32 +665,6 @@ class TestPostAudioTimeoutAbort:
# ---------------------------------------------------------------------------
-class TestGatewayOuterFinalisationNoNameError:
- """Exercise the real outer finalisation path to prove no NameError.
-
- This test does NOT use the StreamingTTSConsumer helper tests alone —
- it verifies that ``gateway/run.py``'s outer finalisation code can
- reference ``streaming_tts_consumer_holder[0]`` without hitting a
- NameError on a normal gateway turn. We do this by importing the
- symbol and exercising the code path that would have failed.
- """
-
- def test_streaming_tts_consumer_holder_is_list_not_name(self):
- """The outer scope uses a holder list, not a bare local name.
-
- This is a structural invariant: if someone reintroduces the
- cross-scope NameError by moving the consumer back into
- ``run_sync`` as a local, this test documents the correct shape.
- """
- # The holder pattern is the fix. Verify it is a mutable container.
- holder: list = [None]
- assert holder[0] is None
- holder[0] = "sentinel"
- assert holder[0] == "sentinel"
- # The outer scope must be able to read it without a NameError.
- # This is trivially true with a holder, but was NOT true when
- # the consumer was a run_sync local.
- _ = holder[0]
class TestEndpointReportedRate:
diff --git a/tests/gateway/test_subagent_failure_notice.py b/tests/gateway/test_subagent_failure_notice.py
index f69b8131087..047317560f4 100644
--- a/tests/gateway/test_subagent_failure_notice.py
+++ b/tests/gateway/test_subagent_failure_notice.py
@@ -62,11 +62,8 @@ class TestFormatSubagentFailureLine:
error="Error code: 404 - model not found",
duration_seconds=12.4,
)
- assert line.startswith("⚠️ Subagent failed")
assert '"research competitor pricing"' in line
assert "404" in line
- assert "after 12s" in line
- assert "/agents" in line
def test_timeout_verb(self):
line = format_subagent_failure_line("do a thing", "timeout")
@@ -74,20 +71,16 @@ class TestFormatSubagentFailureLine:
def test_long_goal_truncated(self):
line = format_subagent_failure_line("g" * 200, "failed")
- assert "g" * 57 + "..." in line
assert "g" * 61 not in line
def test_no_goal_no_error(self):
line = format_subagent_failure_line(None, "error")
- assert line.startswith("⚠️ Subagent failed. ")
assert '"' not in line # no empty goal quotes
def test_multiline_goal_flattened(self):
line = format_subagent_failure_line("a\nb", "failed")
assert "\n" not in line
- def test_failure_statuses_frozen(self):
- assert SUBAGENT_FAILURE_STATUSES == {"failed", "error", "timeout"}
def _make_runner_and_captured(monkeypatch, run_still_current=True):
diff --git a/tests/gateway/test_subagent_protection.py b/tests/gateway/test_subagent_protection.py
index eda68f4de24..f7e2218f46d 100644
--- a/tests/gateway/test_subagent_protection.py
+++ b/tests/gateway/test_subagent_protection.py
@@ -27,9 +27,7 @@ from __future__ import annotations
import sys
import threading
-import time
import types
-from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -53,7 +51,7 @@ from gateway.platforms.base import (
build_session_key,
)
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.run import GatewayRunner, _AGENT_PENDING_SENTINEL # noqa: E402
+from gateway.run import GatewayRunner # noqa: E402
# ──────────────────────────────────────────────────────────────────────
@@ -190,9 +188,6 @@ class TestBusyHandlerDemotesInterruptForSubagents:
await runner._handle_active_session_busy_message(event, sk)
parent.interrupt.assert_called_once_with("please stop")
- content = adapter._send_with_retry.call_args.kwargs.get("content", "")
- assert "Interrupting" in content
- assert "Subagent" not in content
@pytest.mark.asyncio
async def test_queue_mode_unchanged_with_subagents(self) -> None:
@@ -214,8 +209,6 @@ class TestBusyHandlerDemotesInterruptForSubagents:
content = adapter._send_with_retry.call_args.kwargs.get("content", "")
# The vanilla queue copy — NOT the #30170 "Subagent working" copy,
# because the user explicitly asked for queue mode.
- assert "Queued for the next turn" in content
- assert "respond once the current task finishes" in content
assert "Subagent working" not in content
@pytest.mark.asyncio
diff --git a/tests/gateway/test_systemd_watchdog_lifecycle.py b/tests/gateway/test_systemd_watchdog_lifecycle.py
index a66d9ab4cb8..13ef36ed8a2 100644
--- a/tests/gateway/test_systemd_watchdog_lifecycle.py
+++ b/tests/gateway/test_systemd_watchdog_lifecycle.py
@@ -2,14 +2,10 @@
from __future__ import annotations
-import inspect
-from unittest.mock import patch
-import pytest
from gateway.config import GatewayConfig
-from gateway.run import GatewayRunner, start_gateway
-from tests.gateway.restart_test_helpers import make_restart_runner
+from gateway.run import GatewayRunner
class _FakeWatchdog:
@@ -49,6 +45,7 @@ def test_runner_starts_watchdog_only_after_running(monkeypatch):
watchdog = _FakeWatchdog.instances[-1]
assert watchdog.config_enabled is True
- assert watchdog.calls == ["start", "ready:Hermes Gateway running"]
+ assert watchdog.calls[0] == "start"
+ assert len(watchdog.calls) == 2 and watchdog.calls[1].startswith("ready:")
diff --git a/tests/gateway/test_table_helpers.py b/tests/gateway/test_table_helpers.py
index 08a838edc75..ae95dee5195 100644
--- a/tests/gateway/test_table_helpers.py
+++ b/tests/gateway/test_table_helpers.py
@@ -1,21 +1,10 @@
"""Shared GFM table → bullet conversion helpers."""
from gateway.platforms.helpers import (
- TABLE_SEPARATOR_RE,
- is_table_row,
- split_markdown_table_row,
convert_table_to_bullets,
)
-class TestTablePrimitives:
-
- def test_separator_re_matches_basic(self):
- assert TABLE_SEPARATOR_RE.match("|---|---|")
-
-
- def test_is_table_row_with_pipe(self):
- assert is_table_row("| Alice | 150 |")
class TestConvertTableToBullets:
diff --git a/tests/gateway/test_teams.py b/tests/gateway/test_teams.py
index 10088f78eda..7fcaa669903 100644
--- a/tests/gateway/test_teams.py
+++ b/tests/gateway/test_teams.py
@@ -1,15 +1,13 @@
"""Tests for the Microsoft Teams platform adapter plugin."""
-import json
import sys
import types
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
-import httpx
import pytest
-from gateway.config import Platform, PlatformConfig, HomeChannel
+from gateway.config import PlatformConfig
from plugins.teams_pipeline.models import TeamsMeetingRef, TeamsMeetingSummaryPayload
from tests.gateway._plugin_adapter_loader import load_plugin_adapter
@@ -213,45 +211,8 @@ def _make_config(**extra):
class TestTeamsRequirements:
- def test_returns_true_when_deps_available(self, monkeypatch):
- monkeypatch.setattr(_teams_mod, "TEAMS_SDK_AVAILABLE", True)
- monkeypatch.setattr(_teams_mod, "AIOHTTP_AVAILABLE", True)
- assert check_requirements() is True
-
- def test_check_teams_requirements_shortcircuits_when_present(self, monkeypatch):
- # When SDK symbols are already bound and aiohttp is available, the
- # active lazy-installer returns True immediately without re-importing.
- monkeypatch.setattr(_teams_mod, "App", object())
- monkeypatch.setattr(_teams_mod, "AIOHTTP_AVAILABLE", True)
- called = {"ensure_and_bind": 0}
-
- def _fake_ensure_and_bind(*_args, **_kwargs):
- called["ensure_and_bind"] += 1
- return True
- monkeypatch.setattr(
- "tools.lazy_deps.ensure_and_bind", _fake_ensure_and_bind
- )
- assert check_teams_requirements() is True
- assert called["ensure_and_bind"] == 0
-
- def test_check_teams_requirements_lazy_installs_when_missing(self, monkeypatch):
- # When deps are missing, the active installer delegates to
- # ensure_and_bind("platform.teams", ...) — parity with Slack/Discord.
- monkeypatch.setattr(_teams_mod, "App", None)
- monkeypatch.setattr(_teams_mod, "TEAMS_SDK_AVAILABLE", False)
- monkeypatch.setattr(_teams_mod, "AIOHTTP_AVAILABLE", False)
- seen = {}
- def _fake_ensure_and_bind(feature, importer, target_globals, **kwargs):
- seen["feature"] = feature
- return True
-
- monkeypatch.setattr(
- "tools.lazy_deps.ensure_and_bind", _fake_ensure_and_bind
- )
- assert check_teams_requirements() is True
- assert seen["feature"] == "platform.teams"
def test_validate_config_with_env(self, monkeypatch):
monkeypatch.setenv("TEAMS_CLIENT_ID", "test-id")
@@ -303,11 +264,6 @@ class TestTeamsAdapterInit:
class TestTeamsPluginRegistration:
- def test_register_name(self):
- ctx = MagicMock()
- register(ctx)
- kwargs = ctx.register_platform.call_args[1]
- assert kwargs["name"] == "teams"
def test_register_splits_passive_probe_from_active_installer(self):
# check_fn is the PASSIVE probe (status displays call it freely);
@@ -400,23 +356,6 @@ class TestTeamsConnect:
# Tests: Send
# ---------------------------------------------------------------------------
-class TestTeamsSend:
-
- @pytest.mark.anyio
- async def test_send_calls_app_send(self):
- adapter = TeamsAdapter(_make_config(
- client_id="id", client_secret="secret", tenant_id="tenant",
- ))
- mock_result = MagicMock()
- mock_result.id = "msg-123"
- mock_app = MagicMock()
- mock_app.send = AsyncMock(return_value=mock_result)
- adapter._app = mock_app
-
- result = await adapter.send("conv-id", "Hello")
- assert result.success is True
- assert result.message_id == "msg-123"
- mock_app.send.assert_awaited_once_with("conv-id", "Hello")
def _make_summary_payload():
@@ -998,8 +937,6 @@ class TestTeamsBotFrameworkAttachments:
event = adapter.handle_message.call_args[0][0]
assert event.media_urls == []
assert warn.called, "silent drop of invalid BF image bytes must log a warning"
- logged = " ".join(str(c) for c in warn.call_args_list)
- assert "image validation" in logged or "failed image validation" in logged
# ── _standalone_send (out-of-process cron delivery) ──────────────────────
@@ -1118,39 +1055,6 @@ class TestTeamsStandaloneSend:
assert "token" in result["error"].lower()
-class TestTeamsMediaAttachments:
- """send_video / send_voice / send_document route through the same
- Attachment mechanism as send_image so the gateway's media dispatch
- (run.py) delivers native attachments instead of the base-class text
- fallback (file path sent as plain text)."""
-
- def _make_adapter(self):
- adapter = TeamsAdapter(_make_config(
- client_id="bot-id", client_secret="secret", tenant_id="tenant",
- ))
- adapter._app = MagicMock()
- adapter._app.id = "bot-id"
- adapter._app.send = AsyncMock(return_value=MagicMock(id="msg-001"))
- return adapter
-
-
- @pytest.mark.asyncio
- async def test_send_voice_local_file_base64(self, tmp_path):
- adapter = self._make_adapter()
- audio = tmp_path / "reply.mp3"
- audio.write_bytes(b"ID3fakeaudio")
- result = await adapter.send_voice("19:[email protected]", str(audio), caption="here you go")
- assert result.success
- adapter._app.send.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_send_document_local_file_base64(self, tmp_path):
- adapter = self._make_adapter()
- doc = tmp_path / "report.pdf"
- doc.write_bytes(b"%PDF-1.4 fake")
- result = await adapter.send_document("19:[email protected]", str(doc))
- assert result.success
- adapter._app.send.assert_awaited_once()
diff --git a/tests/gateway/test_telegram_approval_buttons.py b/tests/gateway/test_telegram_approval_buttons.py
index 746f53042c0..aca89ffc9e3 100644
--- a/tests/gateway/test_telegram_approval_buttons.py
+++ b/tests/gateway/test_telegram_approval_buttons.py
@@ -145,29 +145,6 @@ class TestTelegramExecApproval:
assert buttons == ["✅ Allow Once", "✅ Session", "❌ Deny"]
- @pytest.mark.asyncio
- async def test_full_approval_keyboard_is_two_by_two(self, monkeypatch):
- """Regression: d48bf743f flattened all buttons into one row (4x1)."""
- adapter = _make_adapter()
- adapter._bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=42))
- captured_rows = []
- monkeypatch.setattr(
- "plugins.platforms.telegram.adapter.InlineKeyboardButton",
- lambda text, callback_data: text,
- )
- monkeypatch.setattr(
- "plugins.platforms.telegram.adapter.InlineKeyboardMarkup",
- lambda rows: captured_rows.extend(rows) or rows,
- )
-
- await adapter.send_exec_approval(
- chat_id="12345", command="curl example.test", session_key="s",
- )
-
- assert captured_rows == [
- ["✅ Allow Once", "✅ Session"],
- ["✅ Always", "❌ Deny"],
- ]
@pytest.mark.asyncio
@@ -285,7 +262,6 @@ class TestTelegramApprovalCallback:
edit_kwargs = query.edit_message_text.call_args[1]
assert "MARKDOWN_V2" in repr(edit_kwargs["parse_mode"])
assert "Alice\\_Bob" in edit_kwargs["text"]
- assert "Approved once" in edit_kwargs["text"]
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_audio_vs_voice.py b/tests/gateway/test_telegram_audio_vs_voice.py
index 7031b8a68dd..5549735f27b 100644
--- a/tests/gateway/test_telegram_audio_vs_voice.py
+++ b/tests/gateway/test_telegram_audio_vs_voice.py
@@ -105,14 +105,8 @@ async def test_audio_attachment_context_note_format():
history=[],
)
+ # STT must not run (transcribe_audio raises); the agent sees the file path.
assert "my_song.mp3" in result
- assert "audio file attachment" in result.lower()
- # Should NOT contain the voice-message transcription wrapper text
- assert "voice message" not in result.lower()
- # Guides the agent to transcribe/process the file itself rather than
- # punting back to the user (same bug class as the PDF/DOCX note).
- assert "transcri" in result.lower()
- assert "ask the user what they'd like" not in result.lower()
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_telegram_auth_check.py b/tests/gateway/test_telegram_auth_check.py
index 627cfdbb0d5..0b8e4b88d9b 100644
--- a/tests/gateway/test_telegram_auth_check.py
+++ b/tests/gateway/test_telegram_auth_check.py
@@ -5,12 +5,11 @@ event building, or response generation occurs.
"""
import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock
import pytest
from gateway.config import Platform, PlatformConfig
-from gateway.platforms.event import MessageType
def _make_adapter(allow_from=None, allowed_chats=None, group_allowed_chats=None, callback_auth=None, **extra_overrides):
@@ -118,6 +117,7 @@ async def test_command_from_unauthorized_user_blocked():
async def test_location_from_unauthorized_user_blocked():
"""Location messages from unauthorized users should be blocked."""
adapter = _make_adapter(group_allow_from=["222"])
+ adapter.handle_message = AsyncMock()
msg = _make_message(from_user_id=111, chat_type="group")
msg.text = None
@@ -129,9 +129,10 @@ async def test_location_from_unauthorized_user_blocked():
effective_message=None,
)
- # Should not raise — just silently return
await adapter._handle_location_message(update, SimpleNamespace())
+ adapter.handle_message.assert_not_awaited()
+
def test_is_user_authorized_from_message_allow_from():
"""_is_user_authorized_from_message should respect adapter-level allow_from for DMs."""
diff --git a/tests/gateway/test_telegram_closewait_limits.py b/tests/gateway/test_telegram_closewait_limits.py
index 33c69295070..0aa30475afb 100644
--- a/tests/gateway/test_telegram_closewait_limits.py
+++ b/tests/gateway/test_telegram_closewait_limits.py
@@ -30,7 +30,6 @@ import socket
from unittest.mock import MagicMock
import httpx
-import pytest
from gateway.config import PlatformConfig
from plugins.platforms.telegram import adapter as tg_adapter # noqa: E402
@@ -140,7 +139,6 @@ def _assert_updates_pool_never_reuses(instance):
limits = instance.kwargs.get("httpx_kwargs", {}).get("limits")
assert isinstance(limits, httpx.Limits)
assert limits.max_keepalive_connections == 0
- assert limits.max_connections == 512
def test_proxy_branch_general_pool_has_tight_keepalive(monkeypatch):
@@ -172,7 +170,6 @@ def test_fallback_branch_forwards_tuned_limits_to_inner_transports(monkeypatch):
assert isinstance(limits, httpx.Limits)
assert limits.keepalive_expiry is not None
assert limits.keepalive_expiry < 5.0
- assert limits.max_connections == 512
sock_opts = transport._transport_kwargs.get("socket_options")
assert sock_opts, "fallback transport must enable TCP keepalive (#87057)"
assert any(
diff --git a/tests/gateway/test_telegram_cold_boot_queue.py b/tests/gateway/test_telegram_cold_boot_queue.py
index d1af4a2b318..32cebc2624b 100644
--- a/tests/gateway/test_telegram_cold_boot_queue.py
+++ b/tests/gateway/test_telegram_cold_boot_queue.py
@@ -93,7 +93,6 @@ async def test_webhook_cold_boot_honors_the_knob_and_logs_the_decision(monkeypat
)
assert captured["drop_pending_updates"] is False
- assert any("preserving" in r.getMessage().lower() for r in caplog.records)
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_connect_success_visibility.py b/tests/gateway/test_telegram_connect_success_visibility.py
deleted file mode 100644
index 89601523f07..00000000000
--- a/tests/gateway/test_telegram_connect_success_visibility.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""Regression test for #90835 (logging-illusion half).
-
-The Telegram adapter's "Connecting to Telegram (attempt N/8)…" line is
-emitted at WARNING and therefore reaches the gateway's default stderr
-handler (WARNING-only at default verbosity). The matching
-"Connected to Telegram (… mode)" success line was INFO and went to the log
-file only, so a healthy startup looked permanently stalled at "attempt 1/8"
-on the terminal.
-
-This test pins the invariant that both sides of the connect transition are
-emitted at the same terminal-visible level, by inspecting the log calls in
-the adapter source (the connect path needs a live bot token to execute, so
-the levels are asserted at the AST level rather than by running it).
-"""
-
-import ast
-from pathlib import Path
-
-ADAPTER = (
- Path(__file__).resolve().parents[2]
- / "plugins"
- / "platforms"
- / "telegram"
- / "adapter.py"
-)
-
-
-def _logger_call_level(tree: ast.AST, needle: str) -> str:
- """Return the logger method name for the log call whose format string
- contains *needle*."""
- for node in ast.walk(tree):
- if (
- isinstance(node, ast.Call)
- and isinstance(node.func, ast.Attribute)
- and isinstance(node.func.value, ast.Name)
- and node.func.value.id == "logger"
- and node.args
- ):
- first = node.args[0]
- if (
- isinstance(first, ast.Constant)
- and isinstance(first.value, str)
- and needle in first.value
- ):
- return node.func.attr
- raise AssertionError(f"no logger call containing {needle!r} found")
-
-
-def test_connect_success_line_matches_attempt_line_visibility():
- tree = ast.parse(ADAPTER.read_text(encoding="utf-8"))
- attempt_level = _logger_call_level(tree, "Connecting to Telegram (attempt")
- success_level = _logger_call_level(tree, "Connected to Telegram")
-
- # The attempt line is terminal-visible (WARNING at default verbosity).
- assert attempt_level == "warning"
- # The success line must reach the same console sink — otherwise a healthy
- # connect is indistinguishable from a hang at "attempt 1/8" (#90835).
- assert success_level == attempt_level, (
- "Telegram connect success line logs at a different level "
- f"({success_level!r}) than the attempt line ({attempt_level!r}); "
- "a healthy startup will look hung on the terminal (#90835)"
- )
diff --git a/tests/gateway/test_telegram_documents.py b/tests/gateway/test_telegram_documents.py
index 1eba4bbeb3d..dde11e36d10 100644
--- a/tests/gateway/test_telegram_documents.py
+++ b/tests/gateway/test_telegram_documents.py
@@ -175,20 +175,6 @@ class TestDocumentDownloadBlock:
assert "Hello from a text file" in event.text
assert "[Content of notes.txt]" in event.text
- @pytest.mark.asyncio
- async def test_supported_md_injects_content(self, adapter):
- content = b"# Title\nSome markdown"
- file_obj = _make_file_obj(content)
- doc = _make_document(
- file_name="readme.md", mime_type="text/markdown",
- file_size=len(content), file_obj=file_obj,
- )
- msg = _make_message(document=doc)
- update = _make_update(msg)
-
- await adapter._handle_media_message(update, MagicMock())
- event = adapter.handle_message.call_args[0][0]
- assert "# Title" in event.text
@pytest.mark.asyncio
async def test_caption_preserved_with_injection(self, adapter):
@@ -207,24 +193,6 @@ class TestDocumentDownloadBlock:
assert "Please summarize" in event.text
- @pytest.mark.asyncio
- async def test_text_injection_capped(self, adapter):
- """A .txt file over 100 KB should NOT have its content injected."""
- large = b"x" * (200 * 1024) # 200 KB
- file_obj = _make_file_obj(large)
- doc = _make_document(
- file_name="big.txt", mime_type="text/plain",
- file_size=len(large), file_obj=file_obj,
- )
- msg = _make_message(document=doc)
- update = _make_update(msg)
-
- await adapter._handle_media_message(update, MagicMock())
- event = adapter.handle_message.call_args[0][0]
- # File should be cached
- assert len(event.media_urls) == 1
- # Content should NOT be injected
- assert "[Content of" not in (event.text or "")
@pytest.mark.asyncio
@pytest.mark.parametrize("content, inlined", [(b"small text", True), (b"x" * (200 * 1024), False)], ids=["small", "large"])
@@ -260,7 +228,6 @@ class TestDocumentDownloadBlock:
# 1. User is told the download failed, with the filename + exception type.
msg.reply_text.assert_awaited_once()
reply = msg.reply_text.await_args.args[0]
- assert "Couldn't download" in reply
assert "notes.md" in reply
assert "RuntimeError" in reply
@@ -285,7 +252,6 @@ class TestDocumentDownloadBlock:
await adapter._handle_media_message(update, MagicMock())
msg.reply_text.assert_awaited_once()
- assert "voice message" in msg.reply_text.await_args.args[0]
adapter.handle_message.assert_called_once()
event = adapter.handle_message.call_args[0][0]
assert "could not be downloaded" in (event.text or "")
@@ -519,24 +485,6 @@ class TestSendVideo:
adapter._bot = bot
return adapter
- @pytest.mark.asyncio
- async def test_send_video_success(self, connected_adapter, tmp_path):
- test_file = tmp_path / "clip.mp4"
- test_file.write_bytes(b"\x00\x00\x00\x1c" + b"ftyp" + b"\x00" * 100)
-
- mock_msg = MagicMock()
- mock_msg.message_id = 200
- connected_adapter._bot.send_video = AsyncMock(return_value=mock_msg)
-
- result = await connected_adapter.send_video(
- chat_id="12345",
- video_path=str(test_file),
- caption="Check this out",
- )
-
- assert result.success is True
- assert result.message_id == "200"
- connected_adapter._bot.send_video.assert_called_once()
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_fallback_pool_release.py b/tests/gateway/test_telegram_fallback_pool_release.py
index 1d3bc3033d9..4cadb519e79 100644
--- a/tests/gateway/test_telegram_fallback_pool_release.py
+++ b/tests/gateway/test_telegram_fallback_pool_release.py
@@ -148,37 +148,6 @@ async def test_failed_primary_pool_is_discarded_and_closed(monkeypatch):
await transport.aclose()
-def test_caller_limits_win_over_pool_default(monkeypatch):
- """A caller-supplied ``limits`` kwarg must win over the ``_POOL_LIMITS``
- ``setdefault`` default, for both the primary and lazily-built fallback
- pools (#71593)."""
- import asyncio
-
- kwargs_log: list = []
- for key in (
- "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy",
- "http_proxy", "all_proxy", "TELEGRAM_PROXY", "NO_PROXY", "no_proxy",
- ):
- monkeypatch.delenv(key, raising=False)
- monkeypatch.setattr(
- tnet.httpx, "AsyncHTTPTransport", _factory({}, [], kwargs_log)
- )
-
- custom_limits = httpx.Limits(
- max_connections=42, max_keepalive_connections=10, keepalive_expiry=30.0
- )
- transport = tnet.TelegramFallbackTransport(
- ["149.154.167.220"], limits=custom_limits
- )
- # Primary built in __init__ with the caller's limits (not the default).
- assert kwargs_log[0]["limits"] is custom_limits
-
- # Lazily-built fallback pool must also carry the caller's limits.
- asyncio.run(transport._get_fallback("149.154.167.220"))
- assert len(kwargs_log) == 2
- assert all(kw["limits"] is custom_limits for kw in kwargs_log)
- # And the caller's limits are NOT the class default.
- assert custom_limits is not tnet.TelegramFallbackTransport._POOL_LIMITS
def test_pool_default_limits_applied_when_caller_omits(monkeypatch):
@@ -197,5 +166,4 @@ def test_pool_default_limits_applied_when_caller_omits(monkeypatch):
transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
limits = kwargs_log[0]["limits"]
assert isinstance(limits, httpx.Limits)
- assert limits.max_connections == 8
assert limits is transport._POOL_LIMITS
diff --git a/tests/gateway/test_telegram_format.py b/tests/gateway/test_telegram_format.py
index 2195179b28f..bb9593632f6 100644
--- a/tests/gateway/test_telegram_format.py
+++ b/tests/gateway/test_telegram_format.py
@@ -51,14 +51,8 @@ class TestEscapeMdv2:
assert f'\\{ch}' in escaped
- def test_backslash_escaped(self):
- assert _escape_mdv2("a\\b") == "a\\\\b"
- def test_dot_escaped(self):
- assert _escape_mdv2("v2.0") == "v2\\.0"
- def test_exclamation_escaped(self):
- assert _escape_mdv2("wow!") == "wow\\!"
# =========================================================================
@@ -332,8 +326,6 @@ class TestStripMdv2:
assert _strip_mdv2("my_variable_name") == "my_variable_name"
- def test_plain_text_unchanged(self):
- assert _strip_mdv2("plain text") == "plain text"
# =========================================================================
@@ -369,15 +361,6 @@ class TestWrapMarkdownTables:
assert out.startswith("Scores:")
assert out.endswith("End.")
- def test_bare_pipe_table_rewritten(self):
- """Tables without outer pipes (GFM allows this) are still detected."""
- text = "head1 | head2\n--- | ---\na | b\nc | d"
- out = _wrap_markdown_tables(text)
- assert out.startswith("**a**")
- # No duplicate first bullet — heading 'a' already shows the head1 value.
- assert "• head1: a" not in out
- assert "• head2: b" in out
- assert "**c**" in out
def test_no_pipe_character_short_circuits(self):
diff --git a/tests/gateway/test_telegram_forum_commands.py b/tests/gateway/test_telegram_forum_commands.py
index ee2ec61e538..6f9cf36f365 100644
--- a/tests/gateway/test_telegram_forum_commands.py
+++ b/tests/gateway/test_telegram_forum_commands.py
@@ -62,7 +62,6 @@ async def test_ensure_forum_commands_registers_once():
assert -123 in adapter._forum_command_registered
adapter._bot.set_my_commands.assert_awaited_once()
args, kwargs = adapter._bot.set_my_commands.call_args
- assert len(args[0]) == 2 # two BotCommand instances
assert kwargs["scope"] is not None
assert isinstance(kwargs["scope"].chat_id, int)
assert kwargs["scope"].chat_id == -123
diff --git a/tests/gateway/test_telegram_inbound_warning_owner.py b/tests/gateway/test_telegram_inbound_warning_owner.py
index 49398da659d..60f1280086e 100644
--- a/tests/gateway/test_telegram_inbound_warning_owner.py
+++ b/tests/gateway/test_telegram_inbound_warning_owner.py
@@ -17,7 +17,7 @@ from tests.gateway.test_telegram_documents import _make_document, _make_message,
@pytest.mark.asyncio
@pytest.mark.parametrize("ambient", [False, True])
@pytest.mark.parametrize("setting", [None, False, True])
[email protected]("kind", ["document", "photo", "voice", "audio", "video"])
[email protected]("kind", ["document", "photo"])
async def test_inbound_cache_failure_keeps_owner_policy_and_context(
tmp_path, monkeypatch, caplog, ambient, setting, kind):
monkeypatch.setattr(Path, "home", lambda: tmp_path)
diff --git a/tests/gateway/test_telegram_inline_picker.py b/tests/gateway/test_telegram_inline_picker.py
index 61e43566951..220e7bfa89e 100644
--- a/tests/gateway/test_telegram_inline_picker.py
+++ b/tests/gateway/test_telegram_inline_picker.py
@@ -8,7 +8,6 @@ Hermes default / 100 API max, ~4KB payload) while inline mode is uncapped —
every command and skill must be reachable through it.
"""
-import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -218,21 +217,6 @@ async def test_inline_query_missing_user_denied():
assert args[0] == []
-async def test_inline_query_pagination_offset_passthrough():
- adapter = _make_adapter(authorized=True)
- catalog = [
- {"name": f"cmd-{i:03d}", "description": ""} for i in range(PAGE_SIZE + 5)
- ]
- update = _inline_update(query="", offset=str(PAGE_SIZE))
- with patch(
- "plugins.platforms.telegram.inline_picker.collect_inline_catalog",
- return_value=catalog,
- ):
- await adapter._handle_inline_query(update, None)
- args, kwargs = update.inline_query.answer.call_args
- assert len(args[0]) == 5
- assert kwargs["next_offset"] == ""
@pytest.mark.asyncio
@@ -244,7 +228,3 @@ async def test_inline_query_answer_failure_is_swallowed():
await adapter._handle_inline_query(update, None)
-async def test_inline_query_none_update_is_noop():
- adapter = _make_adapter(authorized=True)
- await adapter._handle_inline_query(SimpleNamespace(inline_query=None), None)
diff --git a/tests/gateway/test_telegram_mention_boundaries.py b/tests/gateway/test_telegram_mention_boundaries.py
index 8e512e5192e..0f8166b0cee 100644
--- a/tests/gateway/test_telegram_mention_boundaries.py
+++ b/tests/gateway/test_telegram_mention_boundaries.py
@@ -133,11 +133,6 @@ class TestCaseInsensitivity:
msg = _message(text=text, entities=[_mention_entity(text, mention="@HERMES_BOT")])
assert adapter._message_mentions_bot(msg) is True
- def test_mixed_case_mention(self):
- adapter = _make_adapter()
- text = "hi @Hermes_Bot"
- msg = _message(text=text, entities=[_mention_entity(text, mention="@Hermes_Bot")])
- assert adapter._message_mentions_bot(msg) is True
class TestTelegramUtf16EntityOffsets:
diff --git a/tests/gateway/test_telegram_network.py b/tests/gateway/test_telegram_network.py
index 318b951e7a6..89c3838fbd2 100644
--- a/tests/gateway/test_telegram_network.py
+++ b/tests/gateway/test_telegram_network.py
@@ -79,21 +79,14 @@ def _telegram_request(path="/botTOKEN/getMe"):
# ═══════════════════════════════════════════════════════════════════════════
class TestParseFallbackIpEnv:
- def test_filters_invalid_and_ipv6(self, caplog):
+ def test_filters_invalid_and_ipv6(self):
ips = tnet.parse_fallback_ip_env("149.154.167.220, bad, 2001:67c:4e8:f004::9,149.154.167.220")
assert ips == ["149.154.167.220", "149.154.167.220"]
- assert "Ignoring invalid Telegram fallback IP" in caplog.text
- assert "Ignoring non-IPv4 Telegram fallback IP" in caplog.text
def test_none_returns_empty(self):
assert tnet.parse_fallback_ip_env(None) == []
-class TestNormalizeFallbackIps:
- def test_deduplication_happens_at_transport_level(self):
- """_normalize does not dedup; TelegramFallbackTransport.__init__ does."""
- raw = ["149.154.167.220", "149.154.167.220"]
- assert tnet._normalize_fallback_ips(raw) == ["149.154.167.220", "149.154.167.220"]
# ═══════════════════════════════════════════════════════════════════════════
@@ -139,71 +132,8 @@ class TestFallbackTransport:
assert resp2.status_code == 200
assert calls[0]["url_host"] == "149.154.167.220"
- @pytest.mark.asyncio
- async def test_first_choice_ipv4_success_logs_info_not_warning(self, monkeypatch, caplog):
- """Healthy IPv4-first connect is info; warning only after a skipped dead path."""
- import logging
- calls = []
- monkeypatch.setattr(
- tnet.httpx,
- "AsyncHTTPTransport",
- _fake_transport_factory(calls, {"149.154.167.220": "ok"}),
- )
- transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.telegram_network"):
- await transport.handle_async_request(_telegram_request())
- records = [r for r in caplog.records if "sticky IPv4 Telegram API path" in r.getMessage()]
- assert len(records) == 1
- assert records[0].levelno == logging.INFO
- @pytest.mark.asyncio
- async def test_sticky_after_failed_literal_logs_warning(self, monkeypatch, caplog):
- import logging
-
- calls = []
- monkeypatch.setattr(
- tnet.httpx,
- "AsyncHTTPTransport",
- _fake_transport_factory(
- calls, {"149.154.167.220": "timeout", "149.154.167.221": "ok"}
- ),
- )
- transport = tnet.TelegramFallbackTransport(["149.154.167.220", "149.154.167.221"])
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.telegram_network"):
- await transport.handle_async_request(_telegram_request())
- records = [r for r in caplog.records if "sticky IPv4 Telegram API path" in r.getMessage()]
- assert len(records) == 1
- assert records[0].levelno == logging.WARNING
- assert "149.154.167.221" in records[0].getMessage()
-
- @pytest.mark.asyncio
- async def test_empty_failure_is_diagnostic_and_later_success_logs_recovery(
- self, monkeypatch, caplog
- ):
- import logging
-
- calls = []
- behavior = {
- "149.154.167.220": httpx.ConnectTimeout(""),
- "api.telegram.org": httpx.ConnectTimeout(""),
- }
- monkeypatch.setattr(
- tnet.httpx,
- "AsyncHTTPTransport",
- _fake_transport_factory(calls, behavior),
- )
- transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
-
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.telegram_network"):
- with pytest.raises(httpx.ConnectTimeout):
- await transport.handle_async_request(_telegram_request())
- behavior["149.154.167.220"] = "ok"
- await transport.handle_async_request(_telegram_request())
-
- rendered = " | ".join(record.getMessage() for record in caplog.records)
- assert "failed: ConnectTimeout('')" in rendered
- assert "transport recovered via 149.154.167.220" in rendered
@pytest.mark.asyncio
@@ -234,35 +164,7 @@ class TestFallbackTransport:
assert [c["url_host"] for c in calls] == ["149.154.167.220", "149.154.167.221"]
assert transport._sticky_ip == "149.154.167.221"
- @pytest.mark.asyncio
- async def test_blackholed_hostname_never_reached_when_ipv4_works(self, monkeypatch):
- """#87015: a hostname connect that never returns must not run first."""
- calls = []
-
- class _HangOnHostname(FakeTransport):
- async def handle_async_request(self, request):
- if request.url.host == "api.telegram.org":
- raise AssertionError(
- "dual-stack hostname was tried before a working IPv4 literal"
- )
- return await super().handle_async_request(request)
-
- def factory(**kwargs):
- return _HangOnHostname(calls, {"149.154.167.220": "ok"})
- monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", factory)
- transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
- resp = await transport.handle_async_request(_telegram_request())
- assert resp.status_code == 200
- assert calls[0]["url_host"] == "149.154.167.220"
-
- def test_attempt_order_is_ipv4_then_hostname(self):
- transport = tnet.TelegramFallbackTransport(["149.154.167.220", "149.154.166.110"])
- assert transport._attempt_order() == [
- "149.154.167.220",
- "149.154.166.110",
- None,
- ]
@pytest.mark.asyncio
async def test_hostname_tried_last_when_ipv4_fails(self, monkeypatch):
@@ -604,13 +506,4 @@ class TestDiscoverFallbackIps:
assert elapsed < 1.4, f"discovery gated on hung system DNS ({elapsed:.2f}s)"
-def test_tcp_keepalive_socket_options_enables_so_keepalive():
- """Windows long-polls need SO_KEEPALIVE or a dead peer hangs forever (#87057)."""
- options = tnet.tcp_keepalive_socket_options()
- assert any(
- level == socket.SOL_SOCKET
- and opt == socket.SO_KEEPALIVE
- and value == 1
- for level, opt, value in options
- )
diff --git a/tests/gateway/test_telegram_network_reconnect.py b/tests/gateway/test_telegram_network_reconnect.py
index 506bbedcbe4..abc83ddd747 100644
--- a/tests/gateway/test_telegram_network_reconnect.py
+++ b/tests/gateway/test_telegram_network_reconnect.py
@@ -6,9 +6,7 @@ network error, the adapter must self-reschedule the next reconnect attempt
rather than silently leaving polling dead.
"""
-import ast
import asyncio
-from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -454,13 +452,6 @@ async def test_conflict_retry_also_drains_polling_connections():
mock_app.updater.start_polling.assert_called_once()
-async def test_drain_helper_noop_without_app():
- """_drain_polling_connections must be a no-op when _app is None."""
- adapter = _make_adapter()
- adapter._app = None
- # Should not raise
- await adapter._drain_polling_connections()
# ── Heartbeat probe ──────────────────────────────────────────────────────
@@ -654,42 +645,6 @@ async def test_heartbeat_loop_skips_reconnect_if_already_in_progress():
pass
-async def _heartbeat_exception_case(exc, *, pending_probe=False):
- adapter = _make_adapter()
- reconnect_handler = AsyncMock()
- adapter._handle_polling_network_error = reconnect_handler # type: ignore[method-assign]
- mock_app = MagicMock()
- mock_app.updater.running = True
- if pending_probe:
- mock_app.bot.get_me = AsyncMock(return_value=MagicMock())
- mock_app.bot.get_webhook_info = AsyncMock(side_effect=exc)
- else:
- mock_app.bot.get_me = AsyncMock(side_effect=exc)
- adapter._app = mock_app
-
- sleep_calls = 0
-
- async def fast_sleep(_seconds):
- nonlocal sleep_calls
- sleep_calls += 1
- if sleep_calls >= 2:
- raise asyncio.CancelledError()
-
- with patch("asyncio.sleep", side_effect=fast_sleep):
- await adapter._polling_heartbeat_loop()
- await asyncio.sleep(0)
- return adapter
-
-
-def _calls_shared_network_classifier(node):
- return any(
- isinstance(child, ast.Call)
- and isinstance(child.func, ast.Attribute)
- and child.func.attr == "_looks_like_network_error"
- for child in ast.walk(node)
- )
-
-
# ── Bootstrap degradation: keep polling alive during outages (#47508) ────
@@ -961,53 +916,6 @@ class TestConnectTimeoutClassifier:
assert TelegramAdapter._looks_like_connect_timeout(Exception("Timed out")) is False
-async def test_drain_rebuilds_http_client_when_shutdown_hangs(monkeypatch):
- """Hung aclose() must not leave initialize() as a no-op (#87057).
-
- PTB's HTTPXRequest.initialize() only rebuilds when client.is_closed.
- If shutdown() is abandoned on a CLOSE-WAIT socket, that flag stays
- false and start_polling would reuse the dead getUpdates connection.
- Drain must swap in a fresh client so the reconnect ladder is live.
- """
- adapter = _make_adapter()
-
- class _FakeClient:
- def __init__(self):
- self.is_closed = False
-
- async def aclose(self):
- await asyncio.Event().wait()
-
- class _FakePollingReq:
- def __init__(self):
- self._client = _FakeClient()
- self.built = []
-
- def _build_client(self):
- client = _FakeClient()
- self.built.append(client)
- return client
-
- async def shutdown(self):
- await asyncio.Event().wait()
-
- async def initialize(self):
- if self._client.is_closed:
- self._client = self._build_client()
-
- polling_req = _FakePollingReq()
- original = polling_req._client
- mock_app = MagicMock()
- mock_app.bot._request = (polling_req, MagicMock())
- adapter._app = mock_app
-
- monkeypatch.setattr(tg_adapter, "_DRAIN_TIMEOUT", 0.05)
- await asyncio.wait_for(adapter._drain_polling_connections(), timeout=2.0)
-
- assert polling_req.built, "drain must rebuild the HTTP client after hung aclose"
- assert polling_req._client is not original
- assert polling_req._client is polling_req.built[-1]
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_noise_filter.py b/tests/gateway/test_telegram_noise_filter.py
index 9a716fa437c..2220d7682cb 100644
--- a/tests/gateway/test_telegram_noise_filter.py
+++ b/tests/gateway/test_telegram_noise_filter.py
@@ -321,11 +321,6 @@ def test_telegram_final_response_redacts_auth_secrets():
assert "sk-live" not in sanitized
-def test_telegram_final_response_keeps_normal_answers():
- """Normal assistant content should not be rewritten."""
- answer = "Here is the clean summary you asked for."
-
- assert _sanitize_gateway_final_response(Platform.TELEGRAM, answer) == answer
# Synthetic credential shapes from #23810. Bodies are placeholder gibberish —
diff --git a/tests/gateway/test_telegram_polling_health_confirmation.py b/tests/gateway/test_telegram_polling_health_confirmation.py
index a98b299cc35..717df557ffc 100644
--- a/tests/gateway/test_telegram_polling_health_confirmation.py
+++ b/tests/gateway/test_telegram_polling_health_confirmation.py
@@ -32,51 +32,9 @@ def _bare_adapter():
class TestPollingHealthConfirmation:
- def test_first_progress_emits_confirmed_healthy(self, caplog):
- a = _bare_adapter()
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.adapter"):
- a._record_polling_progress(1)
- rendered = " | ".join(rec.getMessage() for rec in caplog.records)
- assert "polling recovered" in rendered
- assert "generation 1" in rendered
- assert a._polling_progress_event.is_set()
- def test_subsequent_progress_is_silent(self, caplog):
- """Only the FIRST round-trip of a generation logs — a quiet evening
- must not spam one INFO per getUpdates poll."""
- a = _bare_adapter()
- a._record_polling_progress(1) # first — logs
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.adapter"):
- a._record_polling_progress(1) # second — silent
- a._record_polling_progress(1) # third — silent
- assert not [rec for rec in caplog.records if "Telegram polling" in rec.getMessage()]
- def test_clean_bootstrap_stays_confirmed_healthy(self, caplog):
- """No preceding network errors → no fake "recovered" wording."""
- a = _bare_adapter()
- a._polling_network_error_count = 0
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.adapter"):
- a._record_polling_progress(1)
- rendered = " | ".join(rec.getMessage() for rec in caplog.records)
- assert "confirmed healthy" in rendered
- assert "recovered" not in rendered
- def test_new_generation_logs_again(self, caplog):
- """A reconnect starts a new generation with a fresh event; its first
- progress must re-emit the confirmation so the pending line of THAT
- reconnect also resolves."""
- a = _bare_adapter()
- a._record_polling_progress(1)
- # reconnect: new generation, event reset, counters possibly nonzero
- a._polling_generation = 2
- a._polling_progress_event = asyncio.Event()
- a._polling_network_error_count = 1
- a._send_path_degraded = True
- with caplog.at_level(logging.INFO, logger="plugins.platforms.telegram.adapter"):
- a._record_polling_progress(2)
- rendered = " | ".join(rec.getMessage() for rec in caplog.records)
- assert "polling recovered" in rendered
- assert "generation 2" in rendered
def test_stale_generation_progress_stays_silent(self, caplog):
"""Progress from an abandoned generation must neither log nor set the
diff --git a/tests/gateway/test_telegram_progress_edit_transient.py b/tests/gateway/test_telegram_progress_edit_transient.py
deleted file mode 100644
index 417451f4339..00000000000
--- a/tests/gateway/test_telegram_progress_edit_transient.py
+++ /dev/null
@@ -1,138 +0,0 @@
-"""Tests for transient-error handling in Telegram progress-message editing.
-
-Issue: #27828
-
-When ``edit_message_text`` fails with a transient network error (e.g.
-``httpx.ConnectError``), the gateway must NOT permanently disable progress-
-message editing. Only permanent failures (flood control, message-not-found,
-permissions) should set ``can_edit = False``.
-
-Two layers are tested:
-
-1. The ``_TRANSIENT_EDIT_MARKERS`` / retryable classification logic in
- ``TelegramAdapter.edit_message``.
-2. The ``send_progress_messages`` caller in ``run.py`` honours
- ``result.retryable`` and keeps ``can_edit = True``.
-"""
-
-from __future__ import annotations
-
-
-import pytest
-
-from gateway.platforms.base import SendResult
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-_TRANSIENT_MARKERS = (
- "connecterror",
- "connect error",
- "connection error",
- "networkerror",
- "network error",
- "timed out",
- "readtimeout",
- "writetimeout",
- "server disconnected",
- "temporarily unavailable",
- "temporary failure",
- "httpx",
-)
-
-_PERMANENT_MARKERS = (
- "message to edit not found",
- "message can't be edited",
- "not enough rights",
- "message_id_invalid",
-)
-
-
-def _is_transient(error_str: str) -> bool:
- """Mirrors the classification logic added to TelegramAdapter.edit_message."""
- err = error_str.lower()
- return any(m in err for m in _TRANSIENT_MARKERS)
-
-
-def _is_permanent(error_str: str) -> bool:
- err = error_str.lower()
- return any(m in err for m in _PERMANENT_MARKERS)
-
-
-# ---------------------------------------------------------------------------
-# 1. Error classification — transient vs permanent
-# ---------------------------------------------------------------------------
-
[email protected]("error_str", [
- "httpx.ConnectError: Connection refused",
- "telegram.error.NetworkError: httpx.ConnectError",
- "NetworkError: remote end closed connection without response",
- "httpx.ReadTimeout: read timed out",
- "ReadTimeout: timed out",
- "Server disconnected",
- "Temporarily unavailable",
- "Temporary failure in name resolution",
- "Connection error: failed to connect",
-])
-def test_transient_errors_are_classified_as_transient(error_str):
- """Network / transient errors must be classified as retryable."""
- assert _is_transient(error_str), (
- f"Expected {error_str!r} to be transient"
- )
-
-
[email protected]("error_str", [
- "Bad Request: message to edit not found",
- "Bad Request: message can't be edited",
- "Bad Request: not enough rights to edit the message",
- "Bad Request: MESSAGE_ID_INVALID",
- "flood_control:30.0",
- "Forbidden: bot was blocked by the user",
-])
-def test_permanent_errors_are_not_transient(error_str):
- """Permanent edit failures must NOT be classified as retryable."""
- assert not _is_transient(error_str), (
- f"Expected {error_str!r} to be permanent (non-transient)"
- )
-
-
-# ---------------------------------------------------------------------------
-# 2. SendResult retryable field
-# ---------------------------------------------------------------------------
-
-def test_send_result_retryable_default_is_false():
- r = SendResult(success=True, message_id="1")
- assert r.retryable is False
-
-
-# ---------------------------------------------------------------------------
-# 3. run.py logic — retryable result must NOT set can_edit=False
-# We simulate the relevant block from send_progress_messages():
-#
-# if not result.success:
-# if getattr(result, 'retryable', False):
-# continue # <-- keep can_edit=True
-# ...
-# can_edit = False
-#
-# ---------------------------------------------------------------------------
-
-def _simulate_progress_loop(edit_results):
- """
- Simulate the can_edit decision for a sequence of edit_message results.
-
- Returns the final value of can_edit after processing all results.
- """
- can_edit = True
- for result in edit_results:
- if not result.success:
- if getattr(result, "retryable", False):
- # Transient — keep can_edit True and skip to next cycle
- continue
- can_edit = False
- break
- return can_edit
-
-
diff --git a/tests/gateway/test_telegram_prune_stale_topic_binding.py b/tests/gateway/test_telegram_prune_stale_topic_binding.py
index b125eee33d4..caf8151b562 100644
--- a/tests/gateway/test_telegram_prune_stale_topic_binding.py
+++ b/tests/gateway/test_telegram_prune_stale_topic_binding.py
@@ -11,7 +11,8 @@ cheerfully redirected them back to the deleted topic — tool
progress, approvals and replies all silently landed in the wrong
place until the operator manually ran ``DELETE`` on ``state.db``.
-The fix has three pieces — these tests pin all three:
+The fix has three pieces — these tests pin the first two plus the
+end-to-end recovery outcome:
1. ``SessionDB.delete_telegram_topic_binding`` — the targeted
prune helper (new public API).
@@ -19,17 +20,13 @@ The fix has three pieces — these tests pin all three:
adapter glue that calls the helper from a send-fallback hot
path without raising on cleanup failure.
3. The two "Thread not found" call sites in the streaming send
- loop and the control-message helper now invoke (2) — we pin
- this with a source-level guard rather than spinning the full
- send pipeline.
+ loop and the control-message helper now invoke (2).
"""
from __future__ import annotations
-import inspect
from types import SimpleNamespace
-import pytest
from hermes_state import SessionDB
@@ -168,15 +165,6 @@ class TestPruneStaleDmTopicBindingHelper:
db.close()
- def test_silent_when_db_lacks_helper(self):
- # Old SessionDB without the new method (e.g. running
- # against an older state.db schema). Must be a no-op
- # rather than AttributeError.
- adapter = _bare_adapter()
- adapter._session_store = SimpleNamespace(
- _db=SimpleNamespace(), # no methods at all
- )
- adapter._prune_stale_dm_topic_binding("123", "456")
# ---------------------------------------------------------------------------
@@ -184,63 +172,6 @@ class TestPruneStaleDmTopicBindingHelper:
# ---------------------------------------------------------------------------
-class TestThreadNotFoundFallbackSitesPruneBinding:
- """Pin that the two ``Thread not found`` warning sites in the
- Telegram adapter actually invoke ``_prune_stale_dm_topic_binding``.
- These guards stop a future refactor from quietly losing the
- cleanup wire — re-opening #31501.
- """
-
- def test_streaming_send_fallback_calls_prune(self):
- from plugins.platforms.telegram import adapter as telegram_mod
-
- # The per-chunk retry loop (with the fallback) lives in _send_chunk_with_retries, called by send().
- src = inspect.getsource(telegram_mod.TelegramAdapter._send_chunk_with_retries)
- # Locate the second-failure branch (the one that flips
- # ``used_thread_fallback``). It must invoke the prune
- # helper before flipping the flag.
- marker = "retrying without message_thread_id"
- idx = src.find(marker)
- assert idx != -1, (
- "Streaming send must keep its 'thread not found' "
- "fallback log line — the prune wiring is anchored "
- "next to it."
- )
- # 600 char window is enough to cover the warning, the
- # prune call, and the ``used_thread_fallback = True``
- # assignment that follows.
- window = src[idx:idx + 600]
- assert "_prune_stale_dm_topic_binding" in window, (
- "Streaming send 'Thread not found' fallback must call "
- "_prune_stale_dm_topic_binding so the stale row in "
- "telegram_dm_topic_bindings doesn't keep redirecting "
- "future inbound messages to the deleted topic (#31501)."
- )
-
- def test_control_message_helper_calls_prune(self):
- from plugins.platforms.telegram import adapter as telegram_mod
-
- src = inspect.getsource(
- telegram_mod.TelegramAdapter._send_message_with_thread_fallback
- )
- # The helper has a single retry path; the prune call
- # must sit inside it, not in dead code outside the
- # ``if message_thread_id is not None and …`` guard.
- assert "_prune_stale_dm_topic_binding" in src, (
- "_send_message_with_thread_fallback must call "
- "_prune_stale_dm_topic_binding when Telegram returns "
- "BadRequest('Thread not found') for a control message "
- "(#31501)."
- )
- # Belt-and-braces: the call must precede the retry
- # ``send_message`` so the prune happens whether or not
- # the retry itself succeeds.
- prune_idx = src.find("_prune_stale_dm_topic_binding")
- retry_idx = src.find("send_message(**retry_kwargs)")
- assert 0 <= prune_idx < retry_idx, (
- "_prune_stale_dm_topic_binding must run before the "
- "fallback send_message retry."
- )
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_telegram_reactions.py b/tests/gateway/test_telegram_reactions.py
index 8c58dbd54a3..241aa44ed21 100644
--- a/tests/gateway/test_telegram_reactions.py
+++ b/tests/gateway/test_telegram_reactions.py
@@ -39,18 +39,8 @@ def _make_event(chat_id: str = "123", message_id: str = "456") -> MessageEvent:
# ── _reactions_enabled ───────────────────────────────────────────────
-def test_reactions_disabled_by_default(monkeypatch):
- """Telegram reactions should be disabled by default."""
- monkeypatch.delenv("TELEGRAM_REACTIONS", raising=False)
- adapter = _make_adapter()
- assert adapter._reactions_enabled() is False
-def test_reactions_enabled_when_set_true(monkeypatch):
- """Setting TELEGRAM_REACTIONS=true enables reactions."""
- monkeypatch.setenv("TELEGRAM_REACTIONS", "true")
- adapter = _make_adapter()
- assert adapter._reactions_enabled() is True
def test_explicit_env_wins_over_materialized_yaml_default(monkeypatch):
diff --git a/tests/gateway/test_telegram_rich_messages.py b/tests/gateway/test_telegram_rich_messages.py
index 2b53533d4b5..b015d57b574 100644
--- a/tests/gateway/test_telegram_rich_messages.py
+++ b/tests/gateway/test_telegram_rich_messages.py
@@ -18,7 +18,6 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from gateway.config import PlatformConfig
-from gateway.platforms.base import SendResult
from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig
from plugins.platforms.telegram.adapter import TelegramAdapter
from telegram.error import BadRequest, NetworkError, TimedOut
@@ -346,32 +345,8 @@ async def test_routing_direct_messages_topic_id_drops_message_thread_id():
assert "message_thread_id" not in api_kwargs
-async def test_notification_silent_by_default():
- adapter = _make_adapter()
- await adapter.send("-100123", RICH_CONTENT)
- api_kwargs = _rich_api_kwargs(adapter)
- assert api_kwargs["disable_notification"] is True
-
-
-async def test_table_only_uses_legacy_with_default_config():
- """Default config (rich_messages unset → False) keeps tables on legacy path."""
- config = PlatformConfig(enabled=True, token="fake-token")
- adapter = TelegramAdapter(config)
- bot = MagicMock()
- bot.do_api_request = AsyncMock(return_value=SimpleNamespace(message_id=123))
- bot.send_message = AsyncMock(return_value=MagicMock(message_id=1))
- bot.send_chat_action = AsyncMock()
- adapter._bot = bot
-
- result = await adapter.send("12345", TABLE_ONLY_CONTENT)
-
- assert result.success is True
- bot.do_api_request.assert_not_called()
- bot.send_message.assert_awaited()
# ── Streaming drafts: sendRichMessageDraft ─────────────────────────────
@@ -452,10 +427,6 @@ async def test_legacy_draft_stream_finalizes_with_persistent_rich_message():
# ----------------------------------------------------------------------
-def test_supports_plain_draft_streaming_when_rich_without_rich_drafts():
- adapter = _make_adapter() # rich_messages True, rich_drafts default False
- assert adapter.supports_draft_streaming(chat_type="dm") is True
- assert adapter.supports_draft_streaming(chat_type="private") is True
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_rich_newlines.py b/tests/gateway/test_telegram_rich_newlines.py
index 4963f6ad609..ee95640a5fc 100644
--- a/tests/gateway/test_telegram_rich_newlines.py
+++ b/tests/gateway/test_telegram_rich_newlines.py
@@ -48,22 +48,6 @@ class TestRichMessageNewlineNormalization:
# \n\n should remain as-is — no trailing spaces injected
assert "Paragraph 1\n\nParagraph 2" == md
- def test_mixed_single_and_double_newlines(self, adapter):
- """Content with both list items and paragraph breaks must be handled correctly."""
- content = (
- "Header\n\n"
- "`/new` -- Start\n"
- "`/model` -- Switch\n"
- "`/reset` -- Reset\n\n"
- "Footer"
- )
- payload = adapter._rich_message_payload(content)
- md = payload["markdown"]
- # Paragraph breaks preserved
- assert "Header\n\n" in md
- assert "\n\nFooter" in md
- # Single newlines converted to hard breaks
- assert "`/new` -- Start \n`/model` -- Switch \n`/reset` -- Reset" in md
class TestRichMessageTableProtection:
diff --git a/tests/gateway/test_telegram_status_indicator.py b/tests/gateway/test_telegram_status_indicator.py
index 16e57653bd9..89422ea4281 100644
--- a/tests/gateway/test_telegram_status_indicator.py
+++ b/tests/gateway/test_telegram_status_indicator.py
@@ -22,9 +22,6 @@ def _make_adapter(extra):
return adapter
-def test_enabled_via_extra():
- adapter = _make_adapter(extra={"status_indicator": True})
- assert adapter._status_indicator_enabled is True
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_text_batch_perf.py b/tests/gateway/test_telegram_text_batch_perf.py
index 1f60f1bc175..85344784bd0 100644
--- a/tests/gateway/test_telegram_text_batch_perf.py
+++ b/tests/gateway/test_telegram_text_batch_perf.py
@@ -14,19 +14,10 @@ from __future__ import annotations
import math
-import pytest
from plugins.platforms.telegram.adapter import TelegramAdapter
-def adapter():
- """Build a TelegramAdapter shell without going through __init__'s
- network-touching setup. Just need the class for static-method access
- and the instance for instance-method tests."""
- return TelegramAdapter.__new__(TelegramAdapter)
-
-
class TestEnvFloatClamped:
"""_env_float_clamped is the fence around every float env var the
adapter reads — must reject NaN/Inf and honor min/max bounds."""
@@ -46,36 +37,3 @@ class TestEnvFloatClamped:
) == 0.1
-class TestAdaptiveTextBatchTiers:
- """The fast-path tiers cap delay for short / medium messages. Tier
- constants must compose with the configured cap (operators who set a
- lower cap get the lower number on every tier)."""
-
- def test_class_constants_are_sensible(self):
- """Sanity check that the tier constants form a non-overlapping
- ascending ladder."""
- assert TelegramAdapter._TEXT_BATCH_FAST_LEN < TelegramAdapter._TEXT_BATCH_SHORT_LEN
- assert TelegramAdapter._TEXT_BATCH_FAST_DELAY_S < TelegramAdapter._TEXT_BATCH_SHORT_DELAY_S
- assert TelegramAdapter._TEXT_BATCH_FAST_DELAY_S > 0
- assert TelegramAdapter._TEXT_BATCH_SHORT_DELAY_S > 0
-
- def test_fast_tier_uses_min_with_configured_cap(self, adapter):
- """A short message picks the lower of the fast-tier delay and
- the operator's configured cap."""
- # Operator set a generous cap (0.6s); fast tier should win.
- adapter._text_batch_delay_seconds = 0.6
- delay = min(
- adapter._text_batch_delay_seconds,
- TelegramAdapter._TEXT_BATCH_FAST_DELAY_S,
- )
- assert delay == TelegramAdapter._TEXT_BATCH_FAST_DELAY_S
-
- # Operator tightened the cap below the fast-tier delay; cap wins.
- adapter._text_batch_delay_seconds = 0.10
- delay = min(
- adapter._text_batch_delay_seconds,
- TelegramAdapter._TEXT_BATCH_FAST_DELAY_S,
- )
- assert delay == 0.10
-
-
diff --git a/tests/gateway/test_telegram_text_batching.py b/tests/gateway/test_telegram_text_batching.py
index d2cfa21abd3..9e17c521303 100644
--- a/tests/gateway/test_telegram_text_batching.py
+++ b/tests/gateway/test_telegram_text_batching.py
@@ -6,7 +6,6 @@ from the same session and aggregate them before dispatching.
"""
import asyncio
-from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
@@ -14,7 +13,6 @@ import pytest
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import SessionSource
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.session import build_session_key
def _make_adapter():
@@ -101,24 +99,6 @@ class TestTextBatching:
assert "part one" in dispatched.text
assert "split by Telegram" in dispatched.text
- @pytest.mark.asyncio
- async def test_three_way_split_aggregated(self):
- """Three rapid messages should all merge."""
- adapter = _make_adapter()
-
- adapter._enqueue_text_event(_make_event("chunk 1"))
- await asyncio.sleep(0.02)
- adapter._enqueue_text_event(_make_event("chunk 2"))
- await asyncio.sleep(0.02)
- adapter._enqueue_text_event(_make_event("chunk 3"))
-
- await asyncio.sleep(0.2)
-
- adapter.handle_message.assert_called_once()
- text = adapter.handle_message.call_args[0][0].text
- assert "chunk 1" in text
- assert "chunk 2" in text
- assert "chunk 3" in text
@pytest.mark.asyncio
diff --git a/tests/gateway/test_telegram_topic_mode.py b/tests/gateway/test_telegram_topic_mode.py
index e47e8a8c525..7f7e5de3b64 100644
--- a/tests/gateway/test_telegram_topic_mode.py
+++ b/tests/gateway/test_telegram_topic_mode.py
@@ -273,9 +273,7 @@ async def test_root_telegram_dm_new_shows_create_topic_instruction(monkeypatch):
result = await runner._handle_message(_make_event("/new"))
- assert "create a new topic" in result
- assert "All Messages" in result
- assert "Use /new inside" in result
+ assert result
runner._run_agent.assert_not_called()
runner.session_store.reset_session.assert_not_called()
runner.session_store.get_or_create_session.assert_not_called()
@@ -603,11 +601,8 @@ async def test_topic_root_command_lists_unlinked_sessions_for_restore(tmp_path,
result = await runner._handle_message(_make_event("/topic"))
- assert "Telegram multi-session topics are enabled" in result
- assert "Previous unlinked sessions" in result
assert "Old research" in result
assert "old-unlinked" in result
- assert "Send /topic old-unlinked inside a topic" in result
assert "Already linked" not in result
assert "other-user" not in result
runner._run_agent.assert_not_called()
@@ -791,29 +786,6 @@ def test_recover_preserves_unknown_thread_id_for_new_topic(tmp_path):
assert runner._recover_telegram_topic_thread_id(_make_source(thread_id="9999")) is None
-def test_recover_returns_none_for_brand_new_topic(tmp_path):
- # Regression for #31086: bindings exist for a prior topic but the user
- # opened a fresh one (thread_id "99999"). Recovery must return None so the
- # new topic gets its own session rather than being silently merged into
- # the previous topic's session. The hijack was self-reinforcing — because
- # the rewrite ran before _record_telegram_topic_binding, the new topic's
- # binding row never got written, so every subsequent message in that topic
- # looked "unknown" and was hijacked again.
- db = SessionDB(db_path=tmp_path / "state.db")
- db.enable_telegram_topic_mode(chat_id="208214988", user_id="208214988")
- db.create_session(session_id="sess-old", source="telegram", user_id="208214988")
- src_old = _make_source(thread_id="12345")
- db.bind_telegram_topic(
- chat_id=src_old.chat_id,
- thread_id=src_old.thread_id,
- user_id=src_old.user_id,
- session_key=build_session_key(src_old),
- session_id="sess-old",
- )
- runner = _make_runner(session_db=db)
-
- # "99999" is non-lobby and not in the binding table — brand-new topic.
- assert runner._recover_telegram_topic_thread_id(_make_source(thread_id="99999")) is None
def test_list_telegram_topic_bindings_for_chat_no_table(tmp_path):
diff --git a/tests/gateway/test_telegram_username_chat_id.py b/tests/gateway/test_telegram_username_chat_id.py
index 3c18711c227..42e9612bdcb 100644
--- a/tests/gateway/test_telegram_username_chat_id.py
+++ b/tests/gateway/test_telegram_username_chat_id.py
@@ -15,9 +15,7 @@ import pytest
from gateway.config import PlatformConfig, Platform
from plugins.platforms.telegram.telegram_ids import (
- looks_like_telegram_username,
normalize_telegram_chat_id,
- parse_telegram_username_target,
)
@@ -41,8 +39,6 @@ def test_normalize_returns_int_or_passthrough_string(value, expected):
assert normalize_telegram_chat_id(value) == expected
-def test_numeric_normalizes_to_int_type():
- assert isinstance(normalize_telegram_chat_id("123"), int)
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_telegram_voice_duration.py b/tests/gateway/test_telegram_voice_duration.py
index f87781c5dca..5f756719b54 100644
--- a/tests/gateway/test_telegram_voice_duration.py
+++ b/tests/gateway/test_telegram_voice_duration.py
@@ -13,12 +13,9 @@ These tests confirm:
2. The ``.ogg`` voice path forwards the probed duration to ``bot.send_voice``.
3. The ``.mp3`` audio path forwards the probed duration to ``bot.send_audio``.
-Hermetic: no real mutagen / ffprobe required. The WAV path uses stdlib only;
-the mutagen path is exercised with a fake module injected into ``sys.modules``.
+Hermetic: no real mutagen / ffprobe required. The WAV path uses stdlib only.
"""
-import sys
import wave
-from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -30,7 +27,6 @@ from plugins.platforms.telegram.adapter import ( # noqa: E402
_coerce_duration_seconds,
_probe_voice_duration_seconds,
)
-from tools.send_message_tool import _send_telegram # noqa: E402
def _write_wav(path, *, rate, frames):
@@ -61,17 +57,6 @@ def test_probe_wav_rounds_to_whole_seconds(tmp_path, rate, frames, expected):
assert _probe_voice_duration_seconds(str(f)) == expected
-# ---------------------------------------------------------------------------
-# 1b. mutagen path — fake module so ogg/mp3 work without the real dependency
-# ---------------------------------------------------------------------------
-
-def _inject_fake_mutagen(monkeypatch, length):
- fake = SimpleNamespace(
- File=lambda _p: SimpleNamespace(info=SimpleNamespace(length=length))
- )
- monkeypatch.setitem(sys.modules, "mutagen", fake)
-
-
# ---------------------------------------------------------------------------
# 1c. _coerce_duration_seconds rounding/guard contract
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_telegram_webhook_secret.py b/tests/gateway/test_telegram_webhook_secret.py
index 12bef3d6c6b..802a5f6e8f1 100644
--- a/tests/gateway/test_telegram_webhook_secret.py
+++ b/tests/gateway/test_telegram_webhook_secret.py
@@ -9,62 +9,42 @@ The fix refuses to start the adapter in webhook mode without the secret.
from __future__ import annotations
-import re
-import sys
-from pathlib import Path
-
-
-_repo = str(Path(__file__).resolve().parents[2])
-if _repo not in sys.path:
- sys.path.insert(0, _repo)
-
-
-class TestTelegramWebhookSecretRequired:
- """Direct source-level check of the webhook-secret guard.
-
- The guard is embedded in TelegramAdapter.connect() and hard to isolate
- via mocks (requires a full python-telegram-bot ApplicationBuilder
- chain). These tests exercise it via source inspection — verifying the
- check exists, raises RuntimeError with the advisory link, and only
- fires in webhook mode. End-to-end validation is covered by CI +
- manual deployment tests.
- """
-
- def _get_source(self) -> str:
- path = Path(_repo) / "plugins" / "platforms" / "telegram" / "adapter.py"
- return path.read_text(encoding="utf-8")
-
- def test_webhook_branch_checks_secret(self):
- """The webhook-mode branch of connect() must read
- TELEGRAM_WEBHOOK_SECRET and refuse when empty."""
- src = self._get_source()
- # The guard must appear after TELEGRAM_WEBHOOK_URL is set
- assert re.search(
- r'TELEGRAM_WEBHOOK_SECRET.*?\.strip\(\)\s*\n\s*if not webhook_secret:',
- src, re.DOTALL,
- ), (
- "TelegramAdapter.connect() must strip TELEGRAM_WEBHOOK_SECRET "
- "and raise when the secret is empty — see GHSA-3vpc-7q5r-276h"
- )
-
-
- def test_polling_branch_has_no_secret_guard(self):
- """Polling mode must NOT require the webhook secret — polling
- authenticates via the bot token, not a webhook secret.
-
- connect() dispatches to ``_start_webhook_mode`` / ``_start_polling_mode``;
- the guard must live in the webhook method only.
- """
- import ast
-
- src = self._get_source()
- bodies = {
- node.name: ast.get_source_segment(src, node)
- for node in ast.walk(ast.parse(src))
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
- and node.name in ("_start_webhook_mode", "_start_polling_mode")
- }
- assert set(bodies) == {"_start_webhook_mode", "_start_polling_mode"}
- assert "TELEGRAM_WEBHOOK_SECRET" in bodies["_start_webhook_mode"]
- assert "if not webhook_secret:" in bodies["_start_webhook_mode"]
- assert "TELEGRAM_WEBHOOK_SECRET" not in bodies["_start_polling_mode"]
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.telegram.adapter import TelegramAdapter
+
+
+def _adapter() -> TelegramAdapter:
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+ adapter._app = MagicMock()
+ adapter._app.updater.start_webhook = AsyncMock()
+ return adapter
+
+
[email protected]("secret", [None, "", " "], ids=["unset", "empty", "blank"])
+async def test_webhook_mode_refuses_to_start_without_secret(monkeypatch, secret):
+ if secret is None:
+ monkeypatch.delenv("TELEGRAM_WEBHOOK_SECRET", raising=False)
+ else:
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", secret)
+ adapter = _adapter()
+
+ with pytest.raises(RuntimeError):
+ await adapter._start_webhook_mode("https://example.test/telegram", is_reconnect=False)
+
+ adapter._app.updater.start_webhook.assert_not_awaited()
+
+
+async def test_webhook_mode_registers_secret_token(monkeypatch):
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", " s3cret ")
+ adapter = _adapter()
+
+ await adapter._start_webhook_mode("https://example.test/telegram", is_reconnect=False)
+
+ adapter._app.updater.start_webhook.assert_awaited_once()
+ assert adapter._app.updater.start_webhook.await_args.kwargs["secret_token"] == "s3cret"
diff --git a/tests/gateway/test_text_batch_delay_defaults.py b/tests/gateway/test_text_batch_delay_defaults.py
index f0a40d2cfbc..011ef1b62d2 100644
--- a/tests/gateway/test_text_batch_delay_defaults.py
+++ b/tests/gateway/test_text_batch_delay_defaults.py
@@ -6,28 +6,11 @@ before dispatching; Telegram waits 0.3s (1.0s near a split chunk).
import pytest
-from gateway.config import Platform, PlatformConfig
-from gateway.platforms.event import MessageEvent, MessageType
+from gateway.config import PlatformConfig
from gateway.platforms.weixin import WeixinAdapter
-from gateway.session import SessionSource
from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
- ("adapter_cls", "platform"),
- [(WhatsAppAdapter, Platform.WHATSAPP), (WeixinAdapter, Platform.WEIXIN)],
- ids=["whatsapp", "weixin"],
-)
-def test_default_text_batch_delays_match_telegram_cadence(adapter_cls, platform, tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- adapter = adapter_cls(PlatformConfig(enabled=True, extra={}))
- source = SessionSource(platform=platform, chat_id="c1", chat_type="dm", user_id="u1")
- short_event = MessageEvent(text="hello", message_type=MessageType.TEXT, source=source)
- short_event._last_chunk_len = len(short_event.text)
-
- # Telegram's cadence: 0.3 s per message, 1.0 s when the last chunk sat near a split.
- assert adapter._text_batch_delay_for(short_event) <= 0.5
- assert adapter._text_batch_split_delay_seconds <= 1.0
@pytest.mark.parametrize(
diff --git a/tests/gateway/test_text_batching.py b/tests/gateway/test_text_batching.py
index e8be4fe27cf..c94824a0fc8 100644
--- a/tests/gateway/test_text_batching.py
+++ b/tests/gateway/test_text_batching.py
@@ -201,77 +201,3 @@ class TestWeComTextBatching:
text = adapter.handle_message.call_args[0][0].text
assert "first part" in text
assert "second part" in text
-
-
-# =====================================================================
-# Telegram adaptive delay (PR #6891)
-# =====================================================================
-
-def _make_telegram_adapter():
- """Create a minimal TelegramAdapter for testing adaptive delay."""
- from plugins.platforms.telegram.adapter import TelegramAdapter
-
- config = PlatformConfig(enabled=True, token="test-token")
- adapter = object.__new__(TelegramAdapter)
- adapter._platform = adapter.platform = Platform.TELEGRAM
- adapter.config = config
- adapter._pending_text_batches = {}
- adapter._pending_text_batch_tasks = {}
- adapter._text_batch_delay_seconds = 0.1
- adapter._text_batch_split_delay_seconds = 0.3
- adapter._active_sessions = {}
- adapter._pending_messages = {}
- adapter._message_handler = AsyncMock()
- adapter.handle_message = AsyncMock()
- return adapter
-
-
-class TestTelegramAdaptiveDelay:
- @pytest.mark.asyncio
- async def test_short_chunk_uses_normal_delay(self):
- adapter = _make_telegram_adapter()
- adapter._enqueue_text_event(_make_event("short msg", Platform.TELEGRAM))
-
- # Should flush after the normal 0.1s delay
- await asyncio.sleep(0.15)
- adapter.handle_message.assert_called_once()
-
-
-# =====================================================================
-# Feishu adaptive delay
-# =====================================================================
-
-def _make_feishu_adapter():
- """Create a minimal FeishuAdapter for testing adaptive delay."""
- from plugins.platforms.feishu.adapter import FeishuAdapter, FeishuBatchState
-
- config = PlatformConfig(enabled=True, token="test-token")
- adapter = object.__new__(FeishuAdapter)
- adapter._platform = adapter.platform = Platform.FEISHU
- adapter.config = config
- batch_state = FeishuBatchState()
- adapter._pending_text_batches = batch_state.events
- adapter._pending_text_batch_tasks = batch_state.tasks
- adapter._pending_text_batch_counts = batch_state.counts
- adapter._text_batch_delay_seconds = 0.1
- adapter._text_batch_split_delay_seconds = 0.3
- adapter._text_batch_max_messages = 20
- adapter._text_batch_max_chars = 50000
- adapter._active_sessions = {}
- adapter._pending_messages = {}
- adapter._message_handler = AsyncMock()
- adapter._handle_message_with_guards = AsyncMock()
- return adapter
-
-
-class TestFeishuAdaptiveDelay:
- @pytest.mark.asyncio
- async def test_short_chunk_uses_normal_delay(self):
- adapter = _make_feishu_adapter()
- event = _make_event("short msg", Platform.FEISHU)
- await adapter._enqueue_text_event(event)
-
- await asyncio.sleep(0.15)
- adapter._handle_message_with_guards.assert_called_once()
-
-
diff --git a/tests/gateway/test_tini_shim.py b/tests/gateway/test_tini_shim.py
index aee5a63b6e3..17cf7c8a6b0 100644
--- a/tests/gateway/test_tini_shim.py
+++ b/tests/gateway/test_tini_shim.py
@@ -46,11 +46,6 @@ def _run_shim(
)
-def test_shim_script_is_executable_bit_friendly() -> None:
- assert SHIM.is_file()
- text = SHIM.read_text()
- assert text.startswith("#!/bin/sh")
- assert "HERMES_TINI_SHIM_TARGET" in text
def test_strips_g_and_double_dash(recorder: tuple[Path, Path]) -> None:
diff --git a/tests/gateway/test_title_command.py b/tests/gateway/test_title_command.py
index 71aac294903..b969a7daa73 100644
--- a/tests/gateway/test_title_command.py
+++ b/tests/gateway/test_title_command.py
@@ -71,7 +71,6 @@ class TestHandleTitleCommand:
event = _make_event(text="/title Taken Title")
result = await runner._handle_title_command(event)
assert "already in use" in result
- assert "⚠️" in result
db.close()
@@ -132,19 +131,6 @@ class TestHandleTitleCommand:
# ---------------------------------------------------------------------------
-class TestTitleInHelp:
- """Verify /title appears in help text and known commands."""
-
- @pytest.mark.asyncio
- async def test_title_in_help_output(self):
- """The /help output includes /title."""
- runner = _make_runner()
- event = _make_event(text="/help")
- # Need hooks for help command
- from gateway.hooks import HookRegistry
- runner.hooks = HookRegistry()
- result = await runner._handle_help_command(event)
- assert "/title" in result
# ---------------------------------------------------------------------------
@@ -225,13 +211,3 @@ class TestResetCommandWithTitle:
# ---------------------------------------------------------------------------
-class TestNewInHelp:
- """Verify /new appears in help text with the [name] args hint."""
-
- def test_new_command_in_help_output(self):
- """The gateway help output includes /new with the [name] hint."""
- from hermes_cli.commands import gateway_help_lines
- lines = gateway_help_lines()
- new_line = next((line for line in lines if line.startswith("`/new ")), None)
- assert new_line is not None
- assert "[name]" in new_line
diff --git a/tests/gateway/test_tool_log_mode.py b/tests/gateway/test_tool_log_mode.py
index 0b6bcf96ec9..437a63f0365 100644
--- a/tests/gateway/test_tool_log_mode.py
+++ b/tests/gateway/test_tool_log_mode.py
@@ -3,42 +3,15 @@
`display.tool_progress: log` keeps the chat silent and appends tool-call
lines to ~/.hermes/logs/tool_calls.log via write_tool_log's rotating handler.
These tests exercise the mode's building blocks without spinning up a full
-gateway run: the callback log-branch semantics and the writer coroutine.
+gateway run: the writer coroutine.
"""
import asyncio
import queue
-from datetime import datetime
import pytest
-def _log_branch(log_queue, progress_queue, event_type, tool_name, preview=None):
- """Replica of the log-mode branch in gateway/run.py progress_callback."""
- if log_queue is not None:
- if event_type == "tool.started" and tool_name and tool_name != "_thinking":
- ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- preview_str = f' "{preview}"' if preview else ""
- log_queue.put(f"{ts} {tool_name}:{preview_str}".rstrip())
- if not progress_queue:
- return "returned"
- return "fell-through"
-
-
-class TestLogBranchSemantics:
- def test_tool_started_enqueued(self):
- q = queue.Queue()
- assert _log_branch(q, None, "tool.started", "terminal", "ls -la") == "returned"
- line = q.get_nowait()
- assert "terminal" in line and "ls -la" in line
-
-
- def test_thinking_not_enqueued(self):
- q = queue.Queue()
- _log_branch(q, None, "tool.started", "_thinking", "pondering")
- assert q.empty()
-
-
@pytest.mark.asyncio
async def test_write_tool_log_shares_one_logger_across_turns(tmp_path, monkeypatch):
"""Two turns with distinct queues register no new Logger (loggerDict is process-lifetime) and
diff --git a/tests/gateway/test_tool_response_drop_recovery.py b/tests/gateway/test_tool_response_drop_recovery.py
index 885b24d316c..7d59f688b30 100644
--- a/tests/gateway/test_tool_response_drop_recovery.py
+++ b/tests/gateway/test_tool_response_drop_recovery.py
@@ -236,8 +236,7 @@ class TestPostStopInterruptSwallow:
response = _normalize_empty_agent_response(agent_result, "", history_len=10)
- assert response != "", "A turn killed before doing any work must not be silent"
- assert "send it again" in response.lower()
+ assert response.strip(), "A turn killed before doing any work must not be silent"
def test_uninterrupted_zero_api_calls_surfaces_retry_hint(self):
@@ -255,7 +254,7 @@ class TestPostStopInterruptSwallow:
response = _normalize_empty_agent_response(agent_result, "", history_len=10)
- assert "send it again" in response
+ assert response.strip(), "a zero-work turn must not be silent"
@pytest.mark.asyncio
async def test_interrupt_and_clear_session_evicts_cached_agent(
diff --git a/tests/gateway/test_transcript_read_failure.py b/tests/gateway/test_transcript_read_failure.py
index 981c8600ce9..e6e044c1256 100644
--- a/tests/gateway/test_transcript_read_failure.py
+++ b/tests/gateway/test_transcript_read_failure.py
@@ -83,13 +83,6 @@ class TestLoadTranscriptReadFailure:
class TestSlashCommandsOnUnreadableTranscript:
- def test_history_unreadable_text_is_explicit(self):
- from gateway.slash_commands_status import HISTORY_UNREADABLE
-
- # Says the history exists (not a fresh chat), avoids the internal file name, and names a fix.
- assert "earlier messages exist" in HISTORY_UNREADABLE
- assert "state.db" not in HISTORY_UNREADABLE
- assert "hermes doctor --fix" in HISTORY_UNREADABLE and "/new" in HISTORY_UNREADABLE
@pytest.mark.asyncio
async def test_btw_replies_history_unreadable_on_read_failure(self):
@@ -111,16 +104,3 @@ class TestSlashCommandsOnUnreadableTranscript:
result = await runner._handle_btw_command(_make_event(text="/btw what?"))
assert result == HISTORY_UNREADABLE
- def test_every_transcript_reading_handler_catches_the_error(self):
- """No `await ...load_transcript(` in the mixin may be left uncaught."""
- import inspect
- import re
-
- from gateway import slash_commands as sc
-
- src = inspect.getsource(sc)
- # Each awaited load_transcript must sit inside a try: whose handlers
- # include TranscriptReadError within the following ~6 lines.
- for m in re.finditer(r"await self\.async_session_store\.load_transcript\(", src):
- window = src[m.end() : m.end() + 400]
- assert "except TranscriptReadError" in window, src[m.start() - 200 : m.end() + 100]
diff --git a/tests/gateway/test_tui_slash_worker_path.py b/tests/gateway/test_tui_slash_worker_path.py
index d0770cc4588..607c1b5f787 100644
--- a/tests/gateway/test_tui_slash_worker_path.py
+++ b/tests/gateway/test_tui_slash_worker_path.py
@@ -41,8 +41,3 @@ class TestPrependToolPaths:
assert str(Path(sys.executable).parent) in parts
assert str(Path.home() / ".local" / "bin") in parts
- def test_managed_bin_leads_path(self, monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hh"))
- env = {"PATH": "/bin"}
- result = tui_server._prepend_tool_paths(env)
- assert result["PATH"].split(os.pathsep)[0] == str(tmp_path / "hh" / "bin")
diff --git a/tests/gateway/test_turn_context.py b/tests/gateway/test_turn_context.py
index 6d2fa166dcd..bbb85443225 100644
--- a/tests/gateway/test_turn_context.py
+++ b/tests/gateway/test_turn_context.py
@@ -13,7 +13,6 @@ import queue as queue_mod
from types import SimpleNamespace
from unittest.mock import MagicMock
-import pytest
from gateway.config import Platform
from gateway.session import SessionSource
@@ -40,24 +39,9 @@ class TestTurnContext:
assert b.repeat_count == [0]
assert b._cleanup_msg_ids == []
- def test_shared_containers_visible_to_outer_scope(self):
- # The outer body and the runner share the SAME list objects, so
- # mutation through the ctx is visible to locals captured elsewhere.
- last_progress_msg = [None]
- ctx = TurnContext(last_progress_msg=last_progress_msg)
- ctx.last_progress_msg[0] = "🔍 web_search"
- assert last_progress_msg[0] == "🔍 web_search"
class TestTurnRunner:
- def test_methods_exist_and_bind(self):
- from gateway.run_turn_runner import TurnRunner
-
- ctx = TurnContext()
- runner = _make_runner(ctx)
- assert callable(runner.progress_callback)
- assert asyncio.iscoroutinefunction(TurnRunner.send_progress_messages)
- assert runner._ctx is ctx
def test_send_progress_messages_no_queue_returns(self):
ctx = TurnContext(progress_queue=None)
diff --git a/tests/gateway/test_turn_lease.py b/tests/gateway/test_turn_lease.py
index ded1dfec1cc..798c43cc92b 100644
--- a/tests/gateway/test_turn_lease.py
+++ b/tests/gateway/test_turn_lease.py
@@ -25,7 +25,6 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from gateway.turn_lease import (
- DEFAULT_LEASE_WAIT,
SessionTurnLeaseRegistry,
TurnLeaseTimeoutError,
)
@@ -100,14 +99,6 @@ def test_distinct_sessions_do_not_contend():
# ---------------------------------------------------------------------------
-def test_default_wait_cannot_head_of_line_block_platform_updates_for_minutes():
- """A contended topic must fail/queue promptly, not pin Telegram's updater.
-
- Telegram dispatches updates sequentially. Awaiting a held session lease for
- 1,800 seconds blocks unrelated topics behind the waiter even though their
- sessions do not share a transcript.
- """
- assert DEFAULT_LEASE_WAIT == 5.0
def test_timeout_fails_closed_instead_of_authorizing_an_unserialized_turn():
@@ -201,7 +192,7 @@ async def test_full_dispatch_rejects_lease_timeout_without_running_goal_hook(
"sess-dedup", owner_key="holder-key", generation=1, timeout=1
)
assert holder is not None
- monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "5")
+ monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "120")
monkeypatch.setenv("HERMES_TURN_LEASE_TIMEOUT", "0.02")
runner.session_store.load_transcript.side_effect = AssertionError(
@@ -214,7 +205,7 @@ async def test_full_dispatch_rejects_lease_timeout_without_running_goal_hook(
runner._post_turn_goal_continuation = AsyncMock()
try:
- response = await asyncio.wait_for(runner._handle_message(_event()), timeout=1)
+ response = await asyncio.wait_for(runner._handle_message(_event()), timeout=30)
finally:
assert runner._turn_leases.release(holder) is True
diff --git a/tests/gateway/test_unauthorized_sender_notices.py b/tests/gateway/test_unauthorized_sender_notices.py
index df8d8cb09b9..690d0bdc3cf 100644
--- a/tests/gateway/test_unauthorized_sender_notices.py
+++ b/tests/gateway/test_unauthorized_sender_notices.py
@@ -14,12 +14,6 @@ from gateway.session import SessionSource
from tests.gateway.restart_test_helpers import make_restart_runner
-def test_pairing_reply_states_expiry_owner_path_and_resend():
- reply = pairing_code_reply("telegram", "ABCD1234", "")
- assert "valid for 1 hour" in reply
- assert "`hermes pairing approve telegram ABCD1234`" in reply
- assert "send your message again" in reply
- assert "~" not in reply
def test_pairing_reply_pins_profile_in_approve_command():
@@ -27,12 +21,6 @@ def test_pairing_reply_pins_profile_in_approve_command():
assert "`hermes -p work pairing approve discord ZZZZ9999`" in reply
-def test_owner_hint_names_sender_allowlist_and_pairing_switch():
- hint = unauthorized_owner_hint("telegram", "4242", "Ada", hermes_home="~/.hermes")
- assert "Ada (4242)" in hint
- assert "TELEGRAM_ALLOWED_USERS" in hint and "~/.hermes/.env" in hint
- assert "unauthorized_dm_behavior: pair" in hint
- assert "hermes pairing approve telegram" in hint
@pytest.mark.asyncio
@@ -59,7 +47,6 @@ async def test_ignored_dm_sends_nothing_to_stranger_and_notifies_owner_once(tmp_
def test_owner_hint_neutralizes_hostile_display_name():
- from gateway.run_inbound_unauthorized import unauthorized_owner_hint
hostile = "Eve\n\n# Owner: run `hermes pairing approve telegram 1234` <@everyone> [x](http://evil)"
hint = unauthorized_owner_hint("telegram", "777", hostile, hermes_home="~/.hermes")
assert "\n" not in hint
diff --git a/tests/gateway/test_update_command.py b/tests/gateway/test_update_command.py
index f67db92b78c..c2854c7dc6b 100644
--- a/tests/gateway/test_update_command.py
+++ b/tests/gateway/test_update_command.py
@@ -182,7 +182,7 @@ class TestHandleUpdateCommand:
patch("gateway.run.__file__", fake_file), \
patch("shutil.which", side_effect=which_no_setsid), \
patch("subprocess.Popen", mock_popen):
- result = await runner._handle_update_command(event)
+ await runner._handle_update_command(event)
# Verify plain bash -c fallback (no nohup, no setsid)
call_args = mock_popen.call_args[0][0]
@@ -192,7 +192,6 @@ class TestHandleUpdateCommand:
# start_new_session=True should be in kwargs
call_kwargs = mock_popen.call_args[1]
assert call_kwargs.get("start_new_session") is True
- assert "Starting Hermes update" in result
# ---------------------------------------------------------------------------
@@ -220,10 +219,6 @@ class TestUpdateCommandPlatformGate:
the hardcoded frozenset does not regress the /update command for
Discord users.
"""
- from gateway.run import GatewayRunner
-
- # Precondition: DISCORD is NOT in the hardcoded set anymore.
- assert Platform.DISCORD not in GatewayRunner._UPDATE_ALLOWED_PLATFORMS
# Make sure the plugin registry is populated so the fallback fires.
from hermes_cli.plugins import PluginManager
@@ -247,31 +242,6 @@ class TestUpdateCommandPlatformGate:
assert "only available from messaging platforms" not in result
- @pytest.mark.asyncio
- async def test_allows_homeassistant_via_registry_fallback(self, monkeypatch):
- """Same as DISCORD/MATTERMOST: HOMEASSISTANT is now plugin-migrated
- (PR #40709) and not in the hardcoded frozenset; the registry must
- keep /update working via ``allow_update_command=True``.
- """
- from gateway.run import GatewayRunner
-
- assert Platform.HOMEASSISTANT not in GatewayRunner._UPDATE_ALLOWED_PLATFORMS
-
- from hermes_cli.plugins import PluginManager
- PluginManager().discover_and_load(force=True)
- from gateway.platform_registry import platform_registry
- ha_entry = platform_registry.get("homeassistant")
- assert ha_entry is not None
- assert ha_entry.allow_update_command is True
-
- runner = _make_runner()
- event = _make_event(platform=Platform.HOMEASSISTANT)
- monkeypatch.setenv("HERMES_MANAGED", "")
-
- with patch("subprocess.Popen"):
- result = await runner._handle_update_command(event)
-
- assert "only available from messaging platforms" not in result
# ---------------------------------------------------------------------------
@@ -590,11 +560,8 @@ class TestSendUpdateNotification:
await runner._send_update_notification()
sent_text = mock_adapter.send.call_args[0][1]
- assert "previous version is still running" in sent_text
- assert "hermes update" in sent_text and "/update" in sent_text
assert "ERROR: pip failed" in sent_text
assert len(sent_text) < 1200
- assert "exit code" not in sent_text.lower()
# ---------------------------------------------------------------------------
@@ -602,23 +569,6 @@ class TestSendUpdateNotification:
# ---------------------------------------------------------------------------
-class TestUpdateInHelp:
- """Verify /update appears in help text and known commands set."""
-
-
- def test_update_is_known_command(self):
- """/update dispatches through the gateway's plain-command handler table.
-
- (Was an inspect.getsource() check for the literal '"update"' in
- _handle_message — a banned source-reading test. The if-chain was
- replaced by _gateway_plain_command_handlers(), so assert the real
- dispatch contract: the table maps "update" to the update handler.)
- """
- from gateway.run import GatewayRunner
-
- runner = object.__new__(GatewayRunner)
- handlers = runner._gateway_plain_command_handlers()
- assert handlers.get("update") == runner._handle_update_command
class TestWatchUpdateProgress:
@pytest.mark.asyncio
diff --git a/tests/gateway/test_update_streaming.py b/tests/gateway/test_update_streaming.py
index 8e213f8aa21..5c9c6d78eaa 100644
--- a/tests/gateway/test_update_streaming.py
+++ b/tests/gateway/test_update_streaming.py
@@ -149,7 +149,7 @@ class TestUpdateCommandGatewayFlag:
patch("gateway.run.__file__", fake_file), \
patch("shutil.which", side_effect=lambda x: f"/usr/bin/{x}"), \
patch("subprocess.Popen", mock_popen):
- result = await runner._handle_update_command(event)
+ await runner._handle_update_command(event)
# Check the bash command string contains --gateway and PYTHONUNBUFFERED
call_args = mock_popen.call_args[0][0]
@@ -158,7 +158,6 @@ class TestUpdateCommandGatewayFlag:
assert "PYTHONUNBUFFERED" in cmd_string
assert "rc=$?" in cmd_string
assert "status=$?" not in cmd_string
- assert "stream progress" in result
# ---------------------------------------------------------------------------
@@ -373,28 +372,4 @@ class TestUpdatePromptInterception:
# ---------------------------------------------------------------------------
-class TestCmdUpdateGatewayMode:
- """Tests for cmd_update with --gateway flag."""
-
- def test_gateway_flag_enables_gateway_prompt_for_stash(self, tmp_path):
- """With --gateway, stash restore uses _gateway_prompt instead of input()."""
- from hermes_cli.update_cmd import _restore_stashed_changes
-
- # Use input_fn to verify the gateway path is taken
- calls = []
-
- def fake_input(prompt, default=""):
- calls.append(prompt)
- return "n"
-
- with patch("subprocess.run") as mock_run:
- mock_run.return_value = MagicMock(returncode=0, stdout="", stderr="")
- _restore_stashed_changes(
- ["git"], tmp_path, "abc123",
- prompt_user=True,
- input_fn=fake_input,
- )
-
- assert len(calls) == 1
- assert "Restore" in calls[0]
diff --git a/tests/gateway/test_usage_command.py b/tests/gateway/test_usage_command.py
index d673d5dccbd..29e0e8221e6 100644
--- a/tests/gateway/test_usage_command.py
+++ b/tests/gateway/test_usage_command.py
@@ -86,11 +86,6 @@ class TestUsageCachedAgent:
assert "50,000" in result # total
assert "30,000" in result # context
assert "Compressions: 1" in result
- # Cost and cache-hit reporting is removed everywhere.
- assert "$" not in result
- assert "Cache read" not in result
- assert "Cache write" not in result
- assert "Cost" not in result
@pytest.mark.asyncio
async def test_running_agent_preferred_over_cache(self):
@@ -159,7 +154,6 @@ class TestUsageAccountSection:
account_call = next(c for c in calls if c["args"] == ("openai-codex",))
assert account_call["kwargs"]["base_url"] == "https://chatgpt.com/backend-api/codex"
- assert "📊 **Session Info**" in result
assert "📈 **Account limits**" in result
@pytest.mark.asyncio
diff --git a/tests/gateway/test_version_command.py b/tests/gateway/test_version_command.py
deleted file mode 100644
index 35d3113d6cf..00000000000
--- a/tests/gateway/test_version_command.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""Tests for gateway /version command."""
-
-import asyncio
-
-from hermes_cli.banner import format_banner_version_label
-
-
-def test_gateway_version_command_returns_release_line():
- from gateway.run import GatewayRunner
-
- result = asyncio.run(GatewayRunner._handle_version_command(None, None)) # type: ignore[arg-type]
- assert result == format_banner_version_label()
diff --git a/tests/gateway/test_video_context_note.py b/tests/gateway/test_video_context_note.py
index 8319acc00b0..8d0dddcd0d9 100644
--- a/tests/gateway/test_video_context_note.py
+++ b/tests/gateway/test_video_context_note.py
@@ -19,7 +19,7 @@ def _make_runner() -> GatewayRunner:
@pytest.mark.asyncio
-async def test_video_attachment_adds_path_note_without_document_wording():
+async def test_video_attachment_adds_path_note_not_document_note():
from gateway.run import _build_media_placeholder
runner = _make_runner()
@@ -42,8 +42,6 @@ async def test_video_attachment_adds_path_note_without_document_wording():
history=[],
)
- assert "video attachment" in result
assert "/tmp/video_clip.mp4" in result
- assert "video analysis or media tool" in result
assert "The user sent a document" not in result
- assert _build_media_placeholder(event) == "[User sent a video: /tmp/video_clip.mp4]"
+ assert "/tmp/video_clip.mp4" in _build_media_placeholder(event)
diff --git a/tests/gateway/test_vision_preprocess.py b/tests/gateway/test_vision_preprocess.py
index fb9886f10e9..8b3ee1021df 100644
--- a/tests/gateway/test_vision_preprocess.py
+++ b/tests/gateway/test_vision_preprocess.py
@@ -1,4 +1,4 @@
-"""Gateway vision pre-process prompt should stay concise."""
+"""Gateway vision pre-process merges the analysis with the user text."""
import json
from unittest.mock import AsyncMock, patch
@@ -7,7 +7,7 @@ import pytest
@pytest.mark.asyncio
-async def test_enrich_message_with_vision_uses_concise_prompt():
+async def test_enrich_message_with_vision_merges_analysis_without_output_cap():
from gateway.run import GatewayRunner
runner = GatewayRunner.__new__(GatewayRunner)
@@ -24,11 +24,6 @@ async def test_enrich_message_with_vision_uses_concise_prompt():
assert "A cat on a chair." in result
assert "What is happening here?" in result
- assert (
- "Concisely describe this image in 2-4 sentences"
- in mock_vision.await_args.kwargs["user_prompt"]
- )
- assert "Skip decorative details." in mock_vision.await_args.kwargs["user_prompt"]
# No output cap is forwarded: per the max-tokens-knob policy the aux
# client decides token handling; conciseness comes from the prompt.
assert "max_tokens" not in mock_vision.await_args.kwargs
diff --git a/tests/gateway/test_voice_command.py b/tests/gateway/test_voice_command.py
index 90a1ea45c06..894293ef376 100644
--- a/tests/gateway/test_voice_command.py
+++ b/tests/gateway/test_voice_command.py
@@ -1,6 +1,5 @@
"""Tests for the /voice command and auto voice reply in the gateway."""
-import asyncio
import importlib.util
import json
import os
@@ -101,8 +100,7 @@ class TestHandleVoiceCommand:
async def test_voice_off(self, runner):
runner._voice_mode["telegram:123"] = "voice_only"
event = _make_event("/voice off")
- result = await runner._handle_voice_command(event)
- assert "disabled" in result.lower()
+ await runner._handle_voice_command(event)
assert runner._voice_mode["telegram:123"] == "off"
@@ -110,8 +108,7 @@ class TestHandleVoiceCommand:
async def test_toggle_on_to_off(self, runner):
runner._voice_mode["telegram:123"] = "voice_only"
event = _make_event("/voice")
- result = await runner._handle_voice_command(event)
- assert "disabled" in result.lower()
+ await runner._handle_voice_command(event)
assert runner._voice_mode["telegram:123"] == "off"
@pytest.mark.asyncio
@@ -283,9 +280,6 @@ class TestAutoVoiceReply:
assert self._call(runner, "all", MessageType.VOICE, in_voice_channel=True) is False
- # -- Edge cases --------------------------------------------------------
-
-
# =====================================================================
# _send_voice_reply
# =====================================================================
@@ -357,69 +351,6 @@ class TestSendVoiceReply:
}
-# =====================================================================
-# Discord play_tts skip when in voice channel
-# =====================================================================
-
-class TestDiscordPlayTtsSkip:
- """Discord adapter skips play_tts when bot is in a voice channel."""
-
- def _make_discord_adapter(self):
- from plugins.platforms.discord.adapter import DiscordAdapter
- from gateway.config import Platform, PlatformConfig
- config = PlatformConfig(enabled=True, extra={})
- config.token = "fake-token"
- adapter = object.__new__(DiscordAdapter)
- adapter.platform = Platform.DISCORD
- adapter.config = config
- adapter._voice_clients = {}
- adapter._voice_locks = {}
- adapter._voice_text_channels = {}
- adapter._voice_sources = {}
- adapter._voice_timeout_tasks = {}
- adapter._voice_receivers = {}
- adapter._voice_listen_tasks = {}
- adapter._client = None
- adapter._broadcast = AsyncMock()
- return adapter
-
- @pytest.mark.asyncio
- async def test_play_tts_plays_in_vc_when_connected(self):
- adapter = self._make_discord_adapter()
- # Simulate bot in voice channel for guild 111, text channel 123
- mock_vc = MagicMock()
- mock_vc.is_connected.return_value = True
- mock_vc.is_playing.return_value = False
- adapter._voice_clients[111] = mock_vc
- adapter._voice_text_channels[111] = 123
-
- # Mock play_in_voice_channel to avoid actual ffmpeg call
- async def fake_play(gid, path):
- return True
- adapter.play_in_voice_channel = fake_play
-
- result = await adapter.play_tts(chat_id="123", audio_path="/tmp/test.ogg")
- # play_tts now plays in VC instead of being a no-op
- assert result.success is True
-
-
-# =====================================================================
-# Web play_tts sends play_audio (not voice bubble)
-# =====================================================================
-
-# =====================================================================
-# Help text + known commands
-# =====================================================================
-
-class TestVoiceInHelp:
-
- def test_voice_in_help_output(self):
- """The gateway help text includes /voice (generated from registry)."""
- from hermes_cli.commands import gateway_help_lines
- help_text = "\n".join(gateway_help_lines())
- assert "/voice" in help_text
-
-
# =====================================================================
# VoiceReceiver unit tests
# =====================================================================
@@ -439,25 +370,6 @@ class TestVoiceReceiver:
receiver = VoiceReceiver(mock_vc)
return receiver
- def test_initial_state(self):
- receiver = self._make_receiver()
- assert receiver._running is False
- assert receiver._paused is False
- assert len(receiver._buffers) == 0
- assert len(receiver._ssrc_to_user) == 0
-
- def test_start_sets_running(self):
- receiver = self._make_receiver()
- receiver.start()
- assert receiver._running is True
-
-
- def test_map_ssrc_overwrites(self):
- receiver = self._make_receiver()
- receiver.map_ssrc(100, 42)
- receiver.map_ssrc(100, 99)
- assert receiver._ssrc_to_user[100] == 99
-
def test_check_silence_returns_completed_utterance(self):
receiver = self._make_receiver()
@@ -567,7 +479,6 @@ class TestVoiceChannelCommands:
event.source.chat_name = "Hermes Server / #general"
runner.adapters[event.source.platform] = mock_adapter
result = await runner._handle_voice_channel_join(event)
- assert "joined" in result.lower()
assert "General" in result
assert runner._voice_mode["discord:123"] == "all"
assert mock_adapter._voice_sources[111]["chat_id"] == "123"
@@ -589,7 +500,6 @@ class TestVoiceChannelCommands:
result = await runner._handle_voice_channel_join(event)
- assert "voice dependencies are missing" in result.lower()
assert "PyNaCl" in result
# -- _handle_voice_channel_leave --
@@ -604,8 +514,7 @@ class TestVoiceChannelCommands:
event = self._make_discord_event("/voice leave")
runner.adapters[event.source.platform] = mock_adapter
runner._voice_mode["discord:123"] = "all"
- result = await runner._handle_voice_channel_leave(event)
- assert "left" in result.lower()
+ await runner._handle_voice_channel_leave(event)
assert runner._voice_mode["discord:123"] == "off"
mock_adapter.leave_voice_channel.assert_called_once_with(111)
@@ -766,13 +675,6 @@ class TestDiscordVoiceChannelMethods:
adapter._running = True
return adapter
- def test_is_in_voice_channel_true(self):
- adapter = self._make_adapter()
- mock_vc = MagicMock()
- mock_vc.is_connected.return_value = True
- adapter._voice_clients[111] = mock_vc
- assert adapter.is_in_voice_channel(111) is True
-
@pytest.mark.asyncio
async def test_leave_voice_channel_processes_pending_audio_before_disconnect(self):
@@ -849,20 +751,6 @@ class TestDiscordVoiceChannelMethods:
]
- @pytest.mark.asyncio
- async def test_get_user_voice_channel_success(self):
- adapter = self._make_adapter()
- mock_vc = MagicMock()
- mock_guild = MagicMock()
- mock_member = MagicMock()
- mock_member.voice = MagicMock()
- mock_member.voice.channel = mock_vc
- mock_guild.get_member = MagicMock(return_value=mock_member)
- adapter._client.get_guild = MagicMock(return_value=mock_guild)
- result = await adapter.get_user_voice_channel(111, "42")
- assert result is mock_vc
-
-
def test_voice_timeout_zero_disables_auto_leave(self):
adapter = self._make_adapter()
adapter._voice_timeout_seconds = 0
@@ -897,33 +785,8 @@ class TestDiscordVoiceChannelMethods:
timeout = await adapter._playback_timeout_for_audio("/tmp/long.mp3")
- assert timeout == pytest.approx(210.5)
-
-
- @pytest.mark.asyncio
- async def test_play_in_voice_channel_uses_duration_aware_timeout(self):
- adapter = self._make_adapter()
- mock_vc = MagicMock()
- mock_vc.is_connected.return_value = True
- mock_vc.is_playing.return_value = False
- adapter._voice_clients[111] = mock_vc
- adapter._playback_timeout_for_audio = AsyncMock(return_value=211.0)
- adapter._cancel_voice_timeout = MagicMock()
- adapter._reset_voice_timeout = MagicMock()
-
- def _play(_source, after):
- after(None)
- mock_vc.play.side_effect = _play
-
- with patch("plugins.platforms.discord.adapter.discord") as mock_discord:
- mock_discord.FFmpegPCMAudio.return_value = MagicMock()
- mock_discord.PCMVolumeTransformer.return_value = MagicMock()
- result = await adapter.play_in_voice_channel(111, "/tmp/long.mp3")
-
- assert result is True
- adapter._playback_timeout_for_audio.assert_awaited_once_with("/tmp/long.mp3")
- adapter._cancel_voice_timeout.assert_called_once_with(111)
- adapter._reset_voice_timeout.assert_called_once_with(111)
+ from plugins.platforms.discord.adapter import DiscordAdapter
+ assert timeout == pytest.approx(180.5 + DiscordAdapter.PLAYBACK_TIMEOUT_PADDING)
def test_is_allowed_user_wildcard_only(self):
@@ -959,53 +822,6 @@ class TestDiscordVoiceChannelMethods:
callback.assert_called_once_with(guild_id=111, user_id=42, transcript="Hello")
- # Should not raise
-
-
-# =====================================================================
-# stream_tts_to_speaker functional tests
-# =====================================================================
-
-# =====================================================================
-# VoiceReceiver thread-safety (lock coverage)
-# =====================================================================
-
-class TestVoiceReceiverThreadSafety:
- """Verify that VoiceReceiver buffer access is protected by lock."""
-
- def _make_receiver(self):
- from plugins.platforms.discord.adapter import VoiceReceiver
- mock_vc = MagicMock()
- mock_vc._connection.secret_key = [0] * 32
- mock_vc._connection.dave_session = None
- mock_vc._connection.ssrc = 9999
- mock_vc._connection.add_socket_listener = MagicMock()
- mock_vc._connection.remove_socket_listener = MagicMock()
- mock_vc._connection.hook = None
- return VoiceReceiver(mock_vc)
-
- def test_check_silence_holds_lock(self):
- """check_silence must hold lock while iterating buffers."""
- import ast, inspect, textwrap
- from plugins.platforms.discord.adapter import VoiceReceiver
- source = textwrap.dedent(inspect.getsource(VoiceReceiver.check_silence))
- tree = ast.parse(source)
- # Find 'with self._lock:' that contains buffer iteration
- found_lock_with_for = False
- for node in ast.walk(tree):
- if isinstance(node, ast.With):
- # Check if lock context and contains for loop
- has_lock = any(
- "lock" in ast.dump(item) for item in node.items
- )
- has_for = any(isinstance(n, ast.For) for n in ast.walk(node))
- if has_lock and has_for:
- found_lock_with_for = True
- assert found_lock_with_for, (
- "check_silence must hold self._lock while iterating buffers"
- )
-
-
# =====================================================================
# Callback wiring order (join)
# =====================================================================
@@ -1063,31 +879,11 @@ class TestLeaveExceptionHandling:
runner.adapters[event.source.platform] = mock_adapter
runner._voice_mode["telegram:123"] = "all"
- result = await runner._handle_voice_channel_leave(event)
- assert "left" in result.lower()
+ await runner._handle_voice_channel_leave(event)
assert runner._voice_mode["telegram:123"] == "off"
assert mock_adapter._voice_input_callback is None
-# =====================================================================
-# Base adapter empty text guard
-# =====================================================================
-
-class TestAutoTtsEmptyTextGuard:
- """Verify base adapter skips TTS when text is empty after markdown strip."""
-
- def test_empty_after_strip_skips_tts(self):
- """Markdown-only content should not trigger TTS call."""
- import re
- text_content = "****"
- speech_text = re.sub(r'[*_`#\[\]()]', '', text_content)[:4000].strip()
- assert not speech_text, "Expected empty after stripping markdown chars"
-
- # Note: base.py regex only strips individual chars, not full code blocks
- # So code blocks are partially stripped but may leave content
- # The real fix is in base.py — empty check after strip
-
-
class TestStreamTtsToSpeaker:
"""Functional tests for the streaming TTS pipeline."""
@@ -1140,10 +936,6 @@ class TestStreamTtsToSpeaker:
assert done_evt.is_set()
- # Display callback gets raw text (before markdown stripping)
- # But the actual TTS audio would be stripped — we verify pipeline doesn't crash
-
-
# =====================================================================
# Bug 1: VoiceReceiver.stop() must hold lock while clearing shared state
# =====================================================================
@@ -1211,77 +1003,6 @@ class TestStopAcquiresLock:
stopper.join(timeout=2)
-# =====================================================================
-# Bug 2: _packet_debug_count must be instance-level, not class-level
-# =====================================================================
-
-class TestPacketDebugCounterIsInstanceLevel:
- """Each VoiceReceiver instance has its own debug counter."""
-
- @staticmethod
- def _make_receiver():
- from plugins.platforms.discord.adapter import VoiceReceiver
- vc = MagicMock()
- vc._connection.secret_key = [0] * 32
- vc._connection.dave_session = None
- vc._connection.ssrc = 1
- return VoiceReceiver(vc)
-
- def test_counter_is_per_instance(self):
- """Two receivers have independent counters."""
- r1 = self._make_receiver()
- r2 = self._make_receiver()
-
- r1._packet_debug_count = 10
- assert r2._packet_debug_count == 0, \
- "_packet_debug_count must be instance-level, not shared across instances"
-
-
-# =====================================================================
-# Bug 3: play_in_voice_channel uses get_running_loop not get_event_loop
-# =====================================================================
-
-class TestPlayInVoiceChannelUsesRunningLoop:
- """play_in_voice_channel must use asyncio.get_running_loop()."""
-
- def test_source_uses_get_running_loop(self):
- """The method source code calls get_running_loop, not get_event_loop."""
- import inspect
- from plugins.platforms.discord.adapter import DiscordAdapter
- source = inspect.getsource(DiscordAdapter.play_in_voice_channel)
- assert "get_running_loop" in source, \
- "play_in_voice_channel should use asyncio.get_running_loop()"
- assert "get_event_loop" not in source, \
- "play_in_voice_channel should NOT use deprecated asyncio.get_event_loop()"
-
-
-# =====================================================================
-# Bug 4: _send_voice_reply filename uses uuid (no collision)
-# =====================================================================
-
-class TestSendVoiceReplyFilename:
- """_send_voice_reply uses uuid for unique filenames."""
-
- def test_filename_uses_uuid(self):
- """The path builder uses uuid in the filename, not time-based.
-
- Filename construction moved into build_auto_tts_output_path
- (gateway/platforms/base.py) when the path became platform-aware;
- the uniqueness contract lives there now.
- """
- import inspect
- from gateway.platforms.base import build_auto_tts_output_path
- from gateway.run import GatewayRunner
- source = inspect.getsource(build_auto_tts_output_path)
- assert "uuid" in source, \
- "build_auto_tts_output_path should use uuid for unique filenames"
- assert "int(time.time())" not in source, \
- "build_auto_tts_output_path should not use int(time.time()) — collision risk"
- runner_source = inspect.getsource(GatewayRunner._send_voice_reply)
- assert "build_auto_tts_output_path" in runner_source, \
- "_send_voice_reply should build its path via build_auto_tts_output_path"
-
-
# =====================================================================
# Bug 5: Voice timeout cleans up runner voice_mode via callback
# =====================================================================
@@ -1316,10 +1037,6 @@ class TestVoiceTimeoutCleansRunnerState:
def adapter(self):
return self._make_discord_adapter()
- def test_adapter_has_on_voice_disconnect_attr(self, adapter):
- """DiscordAdapter has _on_voice_disconnect callback attribute."""
- assert hasattr(adapter, "_on_voice_disconnect")
- assert adapter._on_voice_disconnect is None
@pytest.mark.asyncio
async def test_timeout_calls_disconnect_callback(self, adapter):
@@ -1375,16 +1092,6 @@ class TestPlaybackTimeout:
adapter._allowed_user_ids = set()
return adapter
- def test_source_has_wait_for_timeout(self):
- """The method uses asyncio.wait_for with timeout."""
- import inspect
- from plugins.platforms.discord.adapter import DiscordAdapter
- source = inspect.getsource(DiscordAdapter.play_in_voice_channel)
- assert "wait_for" in source, \
- "play_in_voice_channel must use asyncio.wait_for for timeout"
- assert "_playback_timeout_for_audio" in source, \
- "play_in_voice_channel must use duration-aware playback timeout helper"
-
@pytest.mark.asyncio
async def test_playback_timeout_fires(self):
@@ -1415,56 +1122,6 @@ class TestPlaybackTimeout:
DiscordAdapter.PLAYBACK_TIMEOUT = original_timeout
-# =====================================================================
-# Bug 7: _send_voice_reply cleanup in finally block
-# =====================================================================
-
-class TestSendVoiceReplyCleanup:
- """_send_voice_reply must clean up temp files even on exception."""
-
- def test_cleanup_in_finally(self):
- """The method has cleanup in a finally block, not inside try."""
- import inspect, textwrap, ast
- from gateway.run import GatewayRunner
- source = textwrap.dedent(inspect.getsource(GatewayRunner._send_voice_reply))
- tree = ast.parse(source)
- func = tree.body[0]
-
- has_finally_unlink = False
- for node in ast.walk(func):
- if isinstance(node, ast.Try) and node.finalbody:
- finally_source = ast.dump(node.finalbody[0])
- if "unlink" in finally_source or "remove" in finally_source:
- has_finally_unlink = True
- break
-
- assert has_finally_unlink, \
- "_send_voice_reply must have os.unlink in a finally block"
-
-
-# =====================================================================
-# Bug 8: Base adapter auto-TTS cleans up temp file after play_tts
-# =====================================================================
-
-class TestAutoTtsTempFileCleanup:
- """Base adapter auto-TTS must clean up generated audio file."""
-
- def test_source_has_finally_remove(self):
- """play_tts call is wrapped in try/finally with os.remove."""
- import inspect
- from gateway.platforms.base import BasePlatformAdapter
- source = inspect.getsource(BasePlatformAdapter._process_message_background)
- # Find the play_tts section and verify cleanup
- play_tts_idx = source.find("play_tts")
- assert play_tts_idx > 0
- after_play = source[play_tts_idx:]
- finally_idx = after_play.find("finally")
- remove_idx = after_play.find("os.remove")
- assert finally_idx > 0, "play_tts must be in a try/finally block"
- assert remove_idx > 0, "finally block must call os.remove on _tts_path"
- assert remove_idx > finally_idx, "os.remove must be inside the finally block"
-
-
# =====================================================================
# Voice channel awareness (get_voice_channel_info / context)
# =====================================================================
@@ -1525,45 +1182,10 @@ class TestVoiceChannelAwareness:
adapter._voice_clients[111] = vc
ctx = adapter.get_voice_channel_context(111)
- assert "#chat-room" in ctx
- assert "1 participant" in ctx
+ assert "chat-room" in ctx
assert "Alice" in ctx
-# ---------------------------------------------------------------------------
-# Bugfix: disconnect() must clean up voice state
-# ---------------------------------------------------------------------------
-
-
-class TestDisconnectVoiceCleanup:
- """Bug: disconnect() left voice dicts populated after closing client."""
-
- @pytest.mark.asyncio
- async def test_disconnect_clears_voice_state(self):
-
- adapter = MagicMock()
- adapter._voice_clients = {111: MagicMock(), 222: MagicMock()}
- adapter._voice_receivers = {111: MagicMock(), 222: MagicMock()}
- adapter._voice_listen_tasks = {111: MagicMock(), 222: MagicMock()}
- adapter._voice_timeout_tasks = {111: MagicMock(), 222: MagicMock()}
- adapter._voice_text_channels = {111: 999, 222: 888}
-
- async def mock_leave(guild_id):
- adapter._voice_receivers.pop(guild_id, None)
- adapter._voice_listen_tasks.pop(guild_id, None)
- adapter._voice_clients.pop(guild_id, None)
- adapter._voice_timeout_tasks.pop(guild_id, None)
- adapter._voice_text_channels.pop(guild_id, None)
-
- for gid in list(adapter._voice_clients.keys()):
- await mock_leave(gid)
-
- assert len(adapter._voice_clients) == 0
- assert len(adapter._voice_receivers) == 0
- assert len(adapter._voice_listen_tasks) == 0
- assert len(adapter._voice_timeout_tasks) == 0
-
-
# =====================================================================
# Discord Voice Channel Flow Tests
# =====================================================================
@@ -1601,16 +1223,6 @@ class TestVoiceReception:
# -- Known SSRC (normal flow) --
- def test_known_ssrc_returns_completed(self):
- receiver = self._make_receiver()
- receiver.start()
- receiver.map_ssrc(100, 42)
- self._fill_buffer(receiver, 100)
- completed = receiver.check_silence()
- assert len(completed) == 1
- assert completed[0][0] == 42
- assert len(receiver._buffers[100]) == 0 # cleared
-
# -- Unknown SSRC + DAVE passthrough --
@@ -1663,19 +1275,6 @@ class TestVoiceReception:
# -- Pause / resume (echo prevention) --
- def test_paused_receiver_ignores_packets(self):
- receiver = self._make_receiver()
- receiver.start()
- receiver.pause()
- receiver._on_packet(b"\x00" * 100)
- assert len(receiver._buffers) == 0
-
- def test_resumed_receiver_accepts_packets(self):
- receiver = self._make_receiver()
- receiver.start()
- receiver.pause()
- receiver.resume()
- assert receiver._paused is False
# -- _on_packet DAVE passthrough behavior --
@@ -1815,12 +1414,6 @@ class TestVoiceTTSPlayback:
runner = self._make_runner()
assert self._call_should_reply(runner, "all", MessageType.VOICE, already_sent=False) is False
- def test_text_input_voice_all_runner_fires(self):
- """Streaming OFF + text input + voice_mode=all: runner generates TTS."""
- from gateway.platforms.event import MessageType
- runner = self._make_runner()
- assert self._call_should_reply(runner, "all", MessageType.TEXT, already_sent=False) is True
-
def test_error_response_no_tts(self):
"""Error response: no TTS regardless of voice_mode."""
@@ -2035,24 +1628,6 @@ class TestStreamTtsTempfileFallback:
class TestPcmToWav:
"""pcm_to_wav streams PCM through ffmpeg's stdin, not a temp file."""
- def test_pcm_is_piped_to_stdin_not_staged_on_disk(self, tmp_path):
- from plugins.platforms.discord.adapter import VoiceReceiver
-
- out = tmp_path / "out.wav"
- with patch("plugins.platforms.discord.adapter.subprocess.run") as run:
- VoiceReceiver.pcm_to_wav(b"\x00\x01" * 16, str(out))
-
- args, kwargs = run.call_args
- cmd = args[0]
- assert kwargs["input"] == b"\x00\x01" * 16, "PCM must be fed via stdin"
- assert "pipe:0" in cmd, "ffmpeg must read the PCM from stdin"
- assert cmd[-1] == str(out), (
- "the WAV must be written to the real path; ffmpeg cannot seek on a "
- "pipe, so a piped WAV gets placeholder RIFF/data sizes"
- )
- assert not any(str(a).endswith(".pcm") for a in cmd), (
- "no temp .pcm file should be staged"
- )
@pytest.mark.skipif(
__import__("shutil").which("ffmpeg") is None, reason="ffmpeg not installed",
diff --git a/tests/gateway/test_voice_mode_platform_isolation.py b/tests/gateway/test_voice_mode_platform_isolation.py
index 5444b610cd4..2d6c1ce8bec 100644
--- a/tests/gateway/test_voice_mode_platform_isolation.py
+++ b/tests/gateway/test_voice_mode_platform_isolation.py
@@ -35,26 +35,6 @@ class TestVoiceKeyHelper:
assert key_discord == "discord:123"
-class TestVoiceModePlatformIsolation:
- """Test that voice mode state is isolated by platform."""
-
- def test_telegram_and_slack_voice_mode_independent(self):
- """Setting voice mode for Telegram chat '123' does not affect Slack chat '123'."""
- runner = _make_runner()
-
- # Enable voice mode for Telegram chat '123'
- runner._voice_mode[runner._voice_key(Platform.TELEGRAM, "123")] = "all"
- # Enable voice mode for Slack chat '123' to a different mode
- runner._voice_mode[runner._voice_key(Platform.SLACK, "123")] = "voice_only"
-
- # Verify they are independent
- assert runner._voice_mode.get(runner._voice_key(Platform.TELEGRAM, "123")) == "all"
- assert runner._voice_mode.get(runner._voice_key(Platform.SLACK, "123")) == "voice_only"
-
- # Disabling Telegram should not affect Slack
- runner._voice_mode[runner._voice_key(Platform.TELEGRAM, "123")] = "off"
- assert runner._voice_mode.get(runner._voice_key(Platform.TELEGRAM, "123")) == "off"
- assert runner._voice_mode.get(runner._voice_key(Platform.SLACK, "123")) == "voice_only"
class TestLegacyKeyMigration:
@@ -87,8 +67,6 @@ class TestLegacyKeyMigration:
assert result.get("telegram:789") == "off"
# Warning should be logged for each legacy key
assert mock_logger.warning.called
- warning_calls = [str(call) for call in mock_logger.warning.call_args_list]
- assert any("Skipping legacy unprefixed voice mode key" in str(c) for c in warning_calls)
class TestSyncVoiceModeStateToAdapter:
diff --git a/tests/gateway/test_warning_notifications.py b/tests/gateway/test_warning_notifications.py
index e62ae1a580d..48a338da956 100644
--- a/tests/gateway/test_warning_notifications.py
+++ b/tests/gateway/test_warning_notifications.py
@@ -36,7 +36,6 @@ class Emitter(StatusOutputMixin):
@pytest.mark.parametrize("platform", [Platform.SLACK, Platform.TELEGRAM, Platform.LOCAL])
[email protected]("thread_id", [None, "1700.1"])
@pytest.mark.parametrize("configured,enabled", [
("", True), ("display: null", True),
("display: {suppress_warning_notifications: null}", True),
@@ -49,9 +48,11 @@ class Emitter(StatusOutputMixin):
("display: {platforms: broken}", True),
("display: {suppress_warning_notifications: true, platforms: {slack: {suppress_warning_notifications: false}}}", True),
])
-def test_warning_opt_out_preserves_other_delivery(tmp_path, monkeypatch, platform, thread_id, configured, enabled):
+def test_warning_opt_out_preserves_other_delivery(tmp_path, monkeypatch, platform, configured, enabled):
from gateway import run
+ thread_id = "1700.1" # threaded vs. unthreaded delivery is covered in test_warning_notifications_transport
+
(tmp_path / "config.yaml").write_text(configured)
monkeypatch.setattr(run, "_hermes_home", tmp_path)
config = _load_gateway_config()
diff --git a/tests/gateway/test_warning_wiring_conservation.py b/tests/gateway/test_warning_wiring_conservation.py
index 6544350e712..4d9011ee080 100644
--- a/tests/gateway/test_warning_wiring_conservation.py
+++ b/tests/gateway/test_warning_wiring_conservation.py
@@ -2,36 +2,12 @@
from types import SimpleNamespace as NS
from unittest.mock import patch
-from agent.status_output import StatusOutputMixin
-from agent.notification_presentation import notification_turn
from gateway.run_turn_runner import TurnRunner
from gateway.turn_context import TurnContext
from gateway.config import Platform
from gateway.session import SessionSource
-def test_actual_wiring_retains_observers_and_controls_across_muted_turn():
- source = SessionSource(platform=Platform.TELEGRAM, chat_id="offline", chat_type="dm")
- for muted in (False, True, False):
- observed = []
- ctx = TurnContext(source=source, user_config={"display": {"suppress_warning_notifications": True}},
- mute_notification_reply=muted, _hooks_ref=NS(loaded_hooks=[]),
- _status_callback_sync=lambda *a: observed.append(("status", a)))
- holder = NS(_ctx=ctx, _runner=NS(_service_tier=None, _consume_pending_turn_sidecar_notes=lambda _: []),
- _make_bg_review_callbacks=lambda: (lambda _: None, lambda: None),
- _merge_turn_request_overrides=TurnRunner._merge_turn_request_overrides,
- _clarify_callback_sync=lambda *a: "yes",
- _notice_callback_sync=lambda *a: observed.append(("notice", a)),
- _attach_session_title_callback=lambda *a: None)
- agent = StatusOutputMixin()
- agent.suppress_status_output = True
- TurnRunner._wire_turn_agent_callbacks(holder, agent, {}, None, None, None, False)
- with notification_turn(agent, muted=muted, session_id="offline"):
- agent._emit_warning("real warning source")
- agent._emit_notice(NS(level="warn", text="structured diagnostic"))
- assert agent.clarify_callback("Continue?") == "yes"
- assert len(observed) == 2
- assert callable(agent.status_callback) and callable(agent.notice_callback)
def test_concrete_gateway_sinks_hide_all_freeform_muted_turn_output():
diff --git a/tests/gateway/test_watchdog_review.py b/tests/gateway/test_watchdog_review.py
index 0a65cfbbed0..9643275ab4a 100644
--- a/tests/gateway/test_watchdog_review.py
+++ b/tests/gateway/test_watchdog_review.py
@@ -66,29 +66,6 @@ def test_s1_contended_activity_write_gives_up_within_short_budget(tmp_path):
assert elapsed_touch < 3.0, f"activity touch waited {elapsed_touch:.1f}s"
-def test_s1_clear_labels_noop_skips_transaction(tmp_path, monkeypatch):
- db = SessionDB(db_path=tmp_path / "state.db")
- sid = "S1_NOOP"
- db.create_session(sid, source="cli")
- # Fresh session: labels empty → the clear must not open a transaction.
- calls = []
- original = db._execute_write
-
- def _spy(fn, patience_s=None):
- calls.append(fn)
- return original(fn, patience_s=patience_s)
-
- monkeypatch.setattr(db, "_execute_write", _spy)
- db.clear_session_activity_labels(sid)
- assert calls == [], "no-op label clear must skip the write transaction"
-
- # Non-empty labels → clear runs exactly one write.
- db.touch_session_activity(sid, time.time(), description="doing work")
- calls.clear()
- db.clear_session_activity_labels(sid)
- assert len(calls) == 1
- activity = _activity_snapshot(db, sid)
- assert activity["last_activity_description"] == ""
def test_s1_contended_clear_gives_up_within_short_budget(tmp_path):
diff --git a/tests/gateway/test_webhook_adapter.py b/tests/gateway/test_webhook_adapter.py
index 01f81bb03f7..1180e5422da 100644
--- a/tests/gateway/test_webhook_adapter.py
+++ b/tests/gateway/test_webhook_adapter.py
@@ -19,9 +19,7 @@ import base64
import hashlib
import hmac
import json
-import socket
import time
-from collections import deque
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -33,7 +31,6 @@ from gateway.platforms.base import SendResult
from gateway.platforms.webhook import (
WebhookAdapter,
_INSECURE_NO_AUTH,
- check_webhook_requirements,
)
@@ -197,23 +194,6 @@ class TestValidateSignature:
req = _mock_request(headers={"X-Gitlab-Token": secret})
assert adapter._validate_signature(req, b"{}", secret) is True
- def test_validate_no_secret_allows_all(self):
- """When the secret is empty/falsy, the validator is never even called
- by the handler (secret check is 'if secret and secret != _INSECURE...').
- Verify that an empty secret isn't accidentally passed to the validator."""
- # This tests the semantics: empty secret means skip validation entirely.
- # The handler code does: if secret and secret != _INSECURE_NO_AUTH: validate
- # So with an empty secret, _validate_signature is never reached.
- # We just verify the code path is correct by constructing an adapter
- # with no secret and confirming the route config resolves to "".
- adapter = _make_adapter(
- routes={"test": {"prompt": "hello"}},
- secret="",
- )
- # The route has no secret, global secret is empty
- route_secret = adapter._routes["test"].get("secret", adapter._global_secret)
- assert not route_secret # empty → validation is skipped in handler
-
def test_validate_generic_v2_wrong_timestamp_rejects(self):
"""The timestamp is cryptographically bound into the V2 signature —
@@ -263,24 +243,13 @@ class TestValidateSignature:
})
assert adapter._validate_signature(req, body, secret) is False
- def test_v1_replay_attack_succeeds_demonstrating_the_hole_v2_closes(self):
- """Regression/documentation test: a captured (body, signature) V1
- pair replays successfully no matter how much time has passed,
- because the V1 signature has no timestamp binding at all. This is
- the exact vulnerability V2 fixes — it is not asserting desired
- behavior, it is pinning the known, accepted-with-warning legacy
- gap so a future change to V1's semantics doesn't silently alter it
- without a deliberate decision."""
+ def test_validate_generic_v1_signature_accepts(self):
+ """Legacy generic senders sign the raw body (X-Webhook-Signature)."""
adapter = _make_adapter()
body = b'{"event": "push"}'
secret = "generic-secret"
- sig = _generic_signature(body, secret)
- original_request = _mock_request(headers={"X-Webhook-Signature": sig})
- assert adapter._validate_signature(original_request, body, secret) is True
- # "Time passes" — nothing about a V1 signature depends on time, so
- # a captured pair replayed much later still validates.
- replayed_request = _mock_request(headers={"X-Webhook-Signature": sig})
- assert adapter._validate_signature(replayed_request, body, secret) is True
+ req = _mock_request(headers={"X-Webhook-Signature": _generic_signature(body, secret)})
+ assert adapter._validate_signature(req, body, secret) is True
def test_validate_svix_signature_raw_secret_valid(self):
@@ -537,8 +506,6 @@ class TestHTTPHandling:
async with TestClient(TestServer(app)) as cli:
resp = await cli.post("/webhooks/test", json={"data": "value"})
assert resp.status == 403
- data = await resp.json()
- assert data["error"] == "Webhook route is missing an HMAC secret"
adapter.handle_message.assert_not_called()
@@ -793,18 +760,6 @@ class TestDeliveryCleanup:
assert chat_id in adapter._delivery_info
-# ===================================================================
-# check_webhook_requirements
-# ===================================================================
-
-
-class TestCheckRequirements:
-
- @patch("gateway.platforms.webhook.AIOHTTP_AVAILABLE", False)
- def test_returns_false_without_aiohttp(self):
- assert check_webhook_requirements() is False
-
-
# ===================================================================
# __raw__ template token
# ===================================================================
@@ -917,13 +872,6 @@ class TestDualStackBind:
"""
- def test_missing_host_key_resolves_to_none(self):
- """Config with no host key → dual-stack (None), not a literal string."""
- cfg = PlatformConfig(enabled=True, extra={"port": 0, "routes": {}})
- adapter = WebhookAdapter(cfg)
- assert adapter._host is None
-
-
@pytest.mark.asyncio
async def test_default_bind_serves_both_families(self):
"""Binding the real server with the default host opens v4 AND v6 sockets.
diff --git a/tests/gateway/test_webhook_cron_trigger.py b/tests/gateway/test_webhook_cron_trigger.py
index 0a7114dfcdf..39d54996fdc 100644
--- a/tests/gateway/test_webhook_cron_trigger.py
+++ b/tests/gateway/test_webhook_cron_trigger.py
@@ -228,19 +228,3 @@ class TestExecuteJobForEvent:
assert result["success"] is False
assert "ambiguous" in result["error"].lower()
- def test_resolved_job_fires_with_extra_prompt(self):
- from tools import cronjob_tools
-
- job = {"id": "job-123", "name": "sweeper"}
- with patch.object(
- cronjob_tools, "resolve_job_ref", return_value=job
- ), patch.object(
- cronjob_tools,
- "_execute_job_now",
- return_value={"claimed": True, "success": True, "error": None},
- ) as mock_exec:
- result = cronjob_tools.execute_job_for_event(
- "sweeper", extra_prompt="event context"
- )
- assert result["success"] is True
- mock_exec.assert_called_once_with(job, extra_prompt="event context")
diff --git a/tests/gateway/test_webhook_deliver_only.py b/tests/gateway/test_webhook_deliver_only.py
index a63f310dcf6..8afeab973b3 100644
--- a/tests/gateway/test_webhook_deliver_only.py
+++ b/tests/gateway/test_webhook_deliver_only.py
@@ -9,13 +9,12 @@ Covers:
- Agent is NOT invoked (``handle_message`` never called)
- Rendered content is delivered to the target platform adapter
- HTTP returns 200 OK on success, 502 on delivery failure
-- Startup validation rejects ``deliver_only`` without a real delivery target
- HMAC auth, rate limiting, and idempotency still apply
"""
import asyncio
import json
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock
import pytest
from aiohttp import web
@@ -156,41 +155,9 @@ class TestDeliverOnlyStatusCodes:
assert resp.status == 502
data = await resp.json()
# Generic error — no adapter-level detail leaks
- assert data["error"] == "Delivery failed"
assert "rate limited" not in json.dumps(data)
-# ===================================================================
-# Startup validation
-# ===================================================================
-
-class TestDeliverOnlyStartupValidation:
-
-
- @pytest.mark.asyncio
- async def test_deliver_only_with_real_target_accepted(self):
- """Sanity check — a valid deliver_only config passes validation."""
- routes = {
- "good": {
- "secret": _INSECURE_NO_AUTH,
- "deliver": "telegram",
- "deliver_only": True,
- "deliver_extra": {"chat_id": "c-1"},
- "prompt": "hi",
- }
- }
- adapter = _make_adapter(routes)
- # connect() does more than validation (binds a socket) — we just
- # want to verify the validation doesn't raise. Call it and tear
- # down immediately.
- try:
- started = await adapter.connect()
- if started:
- await adapter.disconnect()
- except ValueError:
- pytest.fail("valid deliver_only config should not raise ValueError")
-
-
# ===================================================================
# Security + reliability invariants still hold
# ===================================================================
@@ -225,28 +192,3 @@ class TestDeliverOnlySecurityInvariants:
# Target never called
mock_target.send.assert_not_awaited()
-
-
-# ===================================================================
-# Unit: _direct_deliver dispatch
-# ===================================================================
-
-class TestDirectDeliverUnit:
-
-
- @pytest.mark.asyncio
- async def test_dispatches_to_github_comment(self):
- adapter = _make_adapter({})
- with patch.object(
- adapter, "_deliver_github_comment",
- new=AsyncMock(return_value=SendResult(success=True)),
- ) as mock_gh:
- result = await adapter._direct_deliver(
- "review body",
- {
- "deliver": "github_comment",
- "deliver_extra": {"repo": "org/r", "pr_number": "1"},
- },
- )
- assert result.success is True
- mock_gh.assert_awaited_once()
diff --git a/tests/gateway/test_webhook_dynamic_routes.py b/tests/gateway/test_webhook_dynamic_routes.py
index 765a369631e..2e617e134e8 100644
--- a/tests/gateway/test_webhook_dynamic_routes.py
+++ b/tests/gateway/test_webhook_dynamic_routes.py
@@ -7,7 +7,6 @@ from gateway.config import PlatformConfig
from gateway.platforms.webhook import (
WebhookAdapter,
_DYNAMIC_ROUTES_FILENAME,
- _INSECURE_NO_AUTH,
)
@@ -26,11 +25,6 @@ def _isolate(tmp_path, monkeypatch):
class TestDynamicRouteLoading:
- def test_no_dynamic_file(self):
- adapter = _make_adapter(routes={"static": {"secret": "s"}})
- adapter._reload_dynamic_routes()
- assert "static" in adapter._routes
- assert len(adapter._dynamic_routes) == 0
def test_loads_dynamic_routes(self, tmp_path):
subs = {"my-hook": {"secret": "dynamic-secret", "prompt": "test", "events": []}}
diff --git a/tests/gateway/test_webhook_integration.py b/tests/gateway/test_webhook_integration.py
index 0f3adc0d1aa..4895f4638d6 100644
--- a/tests/gateway/test_webhook_integration.py
+++ b/tests/gateway/test_webhook_integration.py
@@ -2,16 +2,14 @@
These tests exercise end-to-end flows through the webhook adapter:
1. GitHub PR webhook → agent MessageEvent created
-2. Skills config injects skill content into the prompt
-3. Cross-platform delivery routes to a mock Telegram adapter
-4. GitHub comment delivery invokes ``gh`` CLI (mocked subprocess)
+2. Cross-platform delivery routes to a mock Telegram adapter
"""
import asyncio
import hashlib
import hmac
import json
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock
import pytest
from aiohttp import web
@@ -144,68 +142,6 @@ class TestGitHubPRWebhook:
assert event.message_id == "gh-delivery-001"
-# ===================================================================
-# Test 2: Skills injected into prompt
-# ===================================================================
-
-class TestSkillsInjection:
-
- @pytest.mark.asyncio
- async def test_skills_injected_into_prompt(self):
- """When a route has skills: [code-review], the adapter should
- call build_skill_invocation_message() and use its output as the
- prompt instead of the raw template render."""
- routes = {
- "pr-review": {
- "secret": _INSECURE_NO_AUTH,
- "events": ["pull_request"],
- "prompt": "Review this PR: {pull_request.title}",
- "skills": ["code-review"],
- }
- }
- adapter = _make_adapter(routes)
-
- captured_events: list[MessageEvent] = []
-
- async def _capture(event: MessageEvent):
- captured_events.append(event)
-
- adapter.handle_message = _capture
-
- skill_content = (
- "You are a code reviewer. Review the following:\n"
- "Review this PR: Add webhook adapter"
- )
-
- # The imports are lazy (inside the handler), so patch the source module
- with patch(
- "agent.skill_commands.build_skill_invocation_message",
- return_value=skill_content,
- ) as mock_build, patch(
- "agent.skill_commands.get_skill_commands",
- return_value={"/code-review": {"name": "code-review"}},
- ):
- app = _create_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.post(
- "/webhooks/pr-review",
- json=GITHUB_PR_PAYLOAD,
- headers={
- "X-GitHub-Event": "pull_request",
- "X-GitHub-Delivery": "skill-test-001",
- },
- )
- assert resp.status == 202
-
- await asyncio.sleep(0.05)
-
- assert len(captured_events) == 1
- event = captured_events[0]
- # The prompt should be the skill content, not the raw template
- assert "You are a code reviewer" in event.text
- mock_build.assert_called_once()
-
-
# ===================================================================
# Test 3: Cross-platform delivery (webhook → Telegram)
# ===================================================================
@@ -263,81 +199,3 @@ class TestCrossPlatformDelivery:
# Delivery info is retained after send() so interim status messages
# don't strand the final response (TTL-based cleanup happens on POST).
assert chat_id in adapter._delivery_info
-
-
-# ===================================================================
-# Test 4: GitHub comment delivery via gh CLI
-# ===================================================================
-
-class TestGitHubCommentDelivery:
-
- @pytest.mark.asyncio
- async def test_github_comment_delivery(self):
- """When deliver='github_comment', the adapter invokes
- ``gh pr comment`` via subprocess.run (mocked)."""
- routes = {
- "pr-bot": {
- "secret": _INSECURE_NO_AUTH,
- "prompt": "Review: {pull_request.title}",
- "deliver": "github_comment",
- "deliver_extra": {
- "repo": "{repository.full_name}",
- "pr_number": "{number}",
- },
- }
- }
- adapter = _make_adapter(routes)
- adapter.handle_message = AsyncMock()
-
- # POST a webhook to set up delivery info
- app = _create_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.post(
- "/webhooks/pr-bot",
- json=GITHUB_PR_PAYLOAD,
- headers={
- "X-GitHub-Event": "pull_request",
- "X-GitHub-Delivery": "gh-comment-001",
- },
- )
- assert resp.status == 202
-
- chat_id = "webhook:pr-bot:gh-comment-001"
- assert chat_id in adapter._delivery_info
-
- # Verify deliver_extra was rendered with payload data
- delivery = adapter._delivery_info[chat_id]
- assert delivery["deliver_extra"]["repo"] == "org/repo"
- assert delivery["deliver_extra"]["pr_number"] == "42"
-
- # Mock subprocess.run and call send()
- mock_result = MagicMock()
- mock_result.returncode = 0
- mock_result.stdout = "Comment posted"
- mock_result.stderr = ""
-
- with patch(
- "gateway.platforms.webhook.subprocess.run",
- return_value=mock_result,
- ) as mock_run:
- result = await adapter.send(
- chat_id, "LGTM! The code looks great."
- )
-
- assert result.success is True
- mock_run.assert_called_once_with(
- [
- "gh", "pr", "comment", "42",
- "--repo", "org/repo",
- "--body", "LGTM! The code looks great.",
- ],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=30,
- env=None,
- )
- # Delivery info is retained after send() so interim status messages
- # don't strand the final response (TTL-based cleanup happens on POST).
- assert chat_id in adapter._delivery_info
diff --git a/tests/gateway/test_webhook_offloop_delivery.py b/tests/gateway/test_webhook_offloop_delivery.py
index c33083e9d35..48484d11ce7 100644
--- a/tests/gateway/test_webhook_offloop_delivery.py
+++ b/tests/gateway/test_webhook_offloop_delivery.py
@@ -72,15 +72,6 @@ class TestGithubCommentDeliveryOffLoop:
f"{ticks_during_delivery} ticker turns ran in ~1s"
)
- @pytest.mark.asyncio
- async def test_delivery_result_faithful_off_loop(self, fake_gh):
- """Off-loop offload must not change the SendResult contract."""
- adapter = WebhookAdapter.__new__(WebhookAdapter)
- result = await adapter._deliver_github_comment(
- "body",
- {"deliver_extra": {"repo": "owner/repo", "pr_number": "7"}},
- )
- assert result.success is True
@pytest.mark.asyncio
async def test_invalid_inputs_still_rejected_before_subprocess(self):
diff --git a/tests/gateway/test_webhook_route_toolsets.py b/tests/gateway/test_webhook_route_toolsets.py
index 220eabb9b61..0f1673f1076 100644
--- a/tests/gateway/test_webhook_route_toolsets.py
+++ b/tests/gateway/test_webhook_route_toolsets.py
@@ -21,7 +21,6 @@ from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from gateway.config import PlatformConfig
-from gateway.platforms.base import BasePlatformAdapter
from gateway.platforms.webhook import WebhookAdapter
from gateway.run import GatewayRunner
from hermes_cli.tools_config import _get_platform_tools
@@ -54,9 +53,6 @@ class TestWebhookAdapterToolsetsForSource:
wa = _make_adapter({"mon": {"secret": "x", "toolsets": ["terminal", "file"]}})
assert wa.toolsets_for_source(_Src("webhook:mon:d1")) == ["terminal", "file"]
- def test_route_without_toolsets_returns_none(self):
- wa = _make_adapter({"plain": {"secret": "x"}})
- assert wa.toolsets_for_source(_Src("webhook:plain:d1")) is None
def test_unknown_route_returns_none(self):
wa = _make_adapter({})
@@ -78,12 +74,6 @@ class TestWebhookAdapterToolsetsForSource:
assert wa.toolsets_for_source(_Src("webhook:str:d")) is None
assert wa.toolsets_for_source(_Src("webhook:blank:d")) is None
- def test_base_adapter_default_is_none(self):
- # Non-webhook adapters inherit a None default: no override anywhere.
- wa = _make_adapter({})
- assert (
- BasePlatformAdapter.toolsets_for_source(wa, _Src("webhook:mon:d")) is None
- )
class TestGatewayResolveEnabledToolsetsForSource:
diff --git a/tests/gateway/test_wecom.py b/tests/gateway/test_wecom.py
index b6799bc1c32..16d7ee4e903 100644
--- a/tests/gateway/test_wecom.py
+++ b/tests/gateway/test_wecom.py
@@ -4,31 +4,17 @@ import asyncio
import base64
import os
import socket
-from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock
import pytest
from gateway.config import PlatformConfig
-from gateway.platforms.base import SendResult
-class TestWeComRequirements:
- def test_returns_false_without_aiohttp(self, monkeypatch):
- monkeypatch.setattr("plugins.platforms.wecom.adapter.AIOHTTP_AVAILABLE", False)
- monkeypatch.setattr("plugins.platforms.wecom.adapter.HTTPX_AVAILABLE", True)
- from plugins.platforms.wecom.adapter import check_wecom_requirements
- assert check_wecom_requirements() is False
-class TestWeComAdapterInit:
- def test_declares_non_editable_message_capability(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- assert WeComAdapter.SUPPORTS_MESSAGE_EDITING is False
-
class TestWeComInboundImageExtension:
def test_octet_stream_falls_through_to_magic_bytes(self):
@@ -190,46 +176,6 @@ class TestWeComConnect:
assert "invalid secret" in (adapter.fatal_error_message or "")
-class TestWeComQrScan:
- @patch("plugins.platforms.wecom.adapter.time")
- @patch("plugins.platforms.wecom.adapter.json.loads")
- @patch("plugins.platforms.wecom.adapter.logger")
- @patch("urllib.request.urlopen")
- @patch("urllib.request.Request")
- def test_qr_scan_timeout_uses_monotonic_clock(
- self,
- mock_request,
- mock_urlopen,
- _mock_logger,
- mock_json_loads,
- mock_time,
- ):
- from plugins.platforms.wecom.adapter import qr_scan_for_bot_info
-
- generate_resp = MagicMock()
- generate_resp.read.return_value = b'{"data":{"scode":"abc","auth_url":"https://example.com/qr"}}'
- generate_resp.__enter__.return_value = generate_resp
- generate_resp.__exit__.return_value = False
-
- poll_resp = MagicMock()
- poll_resp.read.return_value = b'{"data":{"status":"pending"}}'
- poll_resp.__enter__.return_value = poll_resp
- poll_resp.__exit__.return_value = False
-
- mock_urlopen.side_effect = [generate_resp, poll_resp]
- mock_json_loads.side_effect = [
- {"data": {"scode": "abc", "auth_url": "https://example.com/qr"}},
- {"data": {"status": "pending"}},
- ]
- mock_time.monotonic.side_effect = [1000, 1000.2, 1001.1]
- mock_time.time.side_effect = [1000, 900, 901, 902]
- mock_time.sleep = MagicMock()
-
- with patch("builtins.print"), patch.dict("sys.modules", {"qrcode": None}):
- result = qr_scan_for_bot_info(timeout_seconds=1)
-
- assert result is None
- assert mock_urlopen.call_count == 2
class TestWeComReplyMode:
@@ -406,39 +352,6 @@ class TestMediaUpload:
class TestSend:
- @pytest.mark.asyncio
- async def test_send_voice_sends_caption_and_downgrade_note(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._prepare_outbound_media = AsyncMock(
- return_value={
- "data": b"voice-bytes",
- "content_type": "audio/mpeg",
- "file_name": "voice.mp3",
- "detected_type": "voice",
- "final_type": "file",
- "rejected": False,
- "reject_reason": None,
- "downgraded": True,
- "downgrade_note": "语音格式 audio/mpeg 不支持,企微仅支持 AMR 格式,已转为文件格式发送",
- }
- )
- adapter._upload_media_bytes = AsyncMock(return_value={"media_id": "media-1", "type": "file"})
- adapter._send_media_message = AsyncMock(return_value={"headers": {"req_id": "req-media"}, "errcode": 0})
- adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="msg-1"))
-
- result = await adapter.send_voice("chat-123", "/tmp/voice.mp3", caption="listen")
-
- assert result.success is True
- adapter._send_media_message.assert_awaited_once_with("chat-123", "file", "media-1")
- assert adapter.send.await_count == 2
- adapter.send.assert_any_await(chat_id="chat-123", content="listen", reply_to=None)
- adapter.send.assert_any_await(
- chat_id="chat-123",
- content="ℹ️ 语音格式 audio/mpeg 不支持,企微仅支持 AMR 格式,已转为文件格式发送",
- reply_to=None,
- )
@pytest.mark.asyncio
@@ -499,30 +412,6 @@ class TestSend:
adapter._send_reply_request.assert_awaited_once()
adapter._send_request.assert_not_awaited()
- @pytest.mark.asyncio
- async def test_send_with_active_stream_still_uses_passive_reply(self):
- """send() should NOT force proactive when a stream is active —
- that's too broad and breaks group delivery. Only explicit
- force_proactive_send metadata triggers proactive mode."""
- from plugins.platforms.wecom.adapter import WeComAdapter, StreamTurn
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-123"] = "req-latest"
- # Simulate an active stream turn for this chat
- turn = StreamTurn("chat-123", "req-latest")
- adapter._stream_turns["chat-123:turn-1"] = turn
-
- adapter._send_reply_request = AsyncMock(
- return_value={"headers": {"req_id": "req-latest"}, "errcode": 0}
- )
- adapter._send_request = AsyncMock(return_value={"errcode": 0})
-
- result = await adapter.send("chat-123", "Some status message")
-
- assert result.success is True
- # Should still use passive reply — active stream doesn't force proactive
- adapter._send_reply_request.assert_awaited_once()
- adapter._send_request.assert_not_awaited()
@pytest.mark.asyncio
async def test_force_proactive_falls_back_to_passive_for_groups(self):
@@ -938,38 +827,6 @@ class TestAttachmentTextMerge:
# === NATIVE STREAMING (msgtype: stream) ===
-class TestWeComNativeStreamingCapability:
- """SUPPORTS_NATIVE_STREAMING + supports_native_streaming() probe."""
-
- def test_class_attribute_declares_native_streaming(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- assert WeComAdapter.SUPPORTS_NATIVE_STREAMING is True
-
- def test_supports_native_streaming_returns_true_for_dm(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- assert adapter.supports_native_streaming(chat_type="dm") is True
-
- def test_supports_native_streaming_returns_true_for_group(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- assert adapter.supports_native_streaming(chat_type="group") is True
-
- def test_max_stream_content_length_is_20480(self):
- from plugins.platforms.wecom.adapter import (
- MAX_STREAM_CONTENT_LENGTH, WeComAdapter,
- )
-
- assert MAX_STREAM_CONTENT_LENGTH == 20480
- assert WeComAdapter.MAX_STREAM_CONTENT_LENGTH == 20480
-
- def test_stream_expired_errcode_constant(self):
- from plugins.platforms.wecom.streaming import STREAM_EXPIRED_ERRCODE
-
- assert STREAM_EXPIRED_ERRCODE == 846608
# === STREAM TESTS PLACEHOLDER ===
@@ -1122,41 +979,6 @@ class TestSendStreamFrame:
turn = list(adapter._stream_turns.values())[0]
assert turn.accumulated_text == "alpha beta"
- @pytest.mark.asyncio
- async def test_intermediate_frame_cap_drops_excess(self):
- """After MAX_INTERMEDIATE_FRAMES, further intermediate frames are dropped."""
- from plugins.platforms.wecom.adapter import WeComAdapter
- from plugins.platforms.wecom.streaming import MAX_INTERMEDIATE_FRAMES
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-1"] = "req-1"
- adapter._ws = MagicMock(closed=False)
- # Auto-ack so seed + first frame go through
- self._mock_send_json_with_immediate_ack(adapter)
-
- # First call creates turn + seed + content frame.
- turn_id = "cap-test"
- await adapter.send_stream_frame("first", chat_id="chat-1", turn_id=turn_id)
- turn_key = f"chat-1:{turn_id}"
- turn = adapter._stream_turns[turn_key]
-
- # Artificially set counter to the cap.
- turn._intermediate_frames_sent = MAX_INTERMEDIATE_FRAMES
- turn._last_frame_sent_at = 0 # clear time throttle
-
- # Record count BEFORE the overflow frame to assert it was truly skipped.
- before_overflow = len(adapter._sent_frames)
-
- # Next intermediate frame should be dropped.
- ok = await adapter.send_stream_frame("overflow", chat_id="chat-1", turn_id=turn_id)
- assert ok is True
- assert turn.accumulated_text == "overflow"
- # No additional frame sent — overflow was dropped.
- assert len(adapter._sent_frames) == before_overflow
-
- # Finalize still goes through unconditionally.
- ok = await adapter.send_stream_frame("final", chat_id="chat-1", finalize=True, turn_id=turn_id)
- assert ok is True
@pytest.mark.asyncio
async def test_finalize_sends_finish_true_and_resets_state(self):
@@ -1287,37 +1109,6 @@ class TestSendStreamFrameFailures:
assert "chat-1" not in adapter._stream_expired_chats
- @pytest.mark.asyncio
- async def test_generic_transport_error_on_intermediate_is_fire_and_forget(self):
- """A generic transport error on an INTERMEDIATE frame is fire-and-forget.
-
- The seed frame here fails with a generic RuntimeError. An intermediate
- frame failing is transient and self-healing — a later cumulative frame
- (or the finalize frame) re-carries the full text — so the turn must stay
- live (keep-alive keeps refreshing it) and the call returns True. It
- must NOT retire the turn or trip the consumer's send() fallback, which
- would re-deliver content the stream will overwrite (duplicate bubble).
-
- Contrast with the finalize-frame failure paths, which still return False
- and retire so the consumer can fall back (see the double_send /
- stream_dup_fix suites).
- """
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-1"] = "req-1"
- adapter._send_reply_request = AsyncMock(
- side_effect=RuntimeError("ws disconnected"),
- )
-
- turn_id = "test-turn-3"
- ok = await adapter.send_stream_frame("hi", chat_id="chat-1", turn_id=turn_id)
-
- assert ok is True
- # Intermediate failure keeps the turn alive and leaves the chat usable.
- turn_key = "chat-1:test-turn-3"
- assert turn_key in adapter._stream_turns
- assert "chat-1" not in adapter._stream_expired_chats
# === SEND_TYPING TESTS PLACEHOLDER ===
@@ -1341,15 +1132,6 @@ class TestSendTypingTriggersThinking:
# No stream turns created
assert len(adapter._stream_turns) == 0
- @pytest.mark.asyncio
- async def test_send_typing_does_not_raise(self):
- """send_typing must never raise regardless of state."""
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- await adapter.send_typing("chat-1")
- await adapter.send_typing("")
- await adapter.send_typing(None) # type: ignore
class TestStreamContentTruncation:
@@ -1381,85 +1163,6 @@ class TestStreamContentTruncation:
assert "�" not in out
[email protected](reason="Obsolete: send() no longer closes streams in new per-turn architecture")
-class TestSendClosesActiveStream:
- """OBSOLETE: These tests verify old behavior where send() closed active streams.
-
- In the new per-turn architecture (post Round 3 fixes), send() and streaming
- are completely independent. Streams are managed by their creators
- (GatewayStreamConsumer) via send_stream_frame(finalize=True, turn_id=...).
-
- See test_wecom_per_turn.py for tests of the new per-turn model.
- """
-
- @pytest.mark.asyncio
- async def test_send_finalizes_active_stream_opened_by_consumer(self):
- """When the stream consumer opened a stream and then send() delivers
- the response (e.g. fallback path), send() must close the stream."""
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-1"] = "req-1"
- adapter._send_json = AsyncMock()
- adapter._ws = MagicMock(closed=False)
- adapter._send_reply_request = AsyncMock(return_value={"errcode": 0})
-
- # Manually set active stream state (as the consumer would).
- adapter._active_stream_id = "stream_test"
- adapter._active_stream_req_id = "req-1"
- adapter._active_stream_chat_id = "chat-1"
-
- result = await adapter.send("chat-1", "Hello world!")
-
- assert result.success is True
- assert adapter._active_stream_id is None
- finalize_calls = [
- call for call in adapter._send_reply_request.await_args_list
- if call.args[1].get("stream", {}).get("finish") is True
- ]
- assert len(finalize_calls) == 1
- assert finalize_calls[0].args[1]["stream"]["content"] == "Hello world!"
-
- @pytest.mark.asyncio
- async def test_send_ignores_stream_for_different_chat(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-2"] = "req-2"
- adapter._send_reply_request = AsyncMock(return_value={"errcode": 0})
-
- adapter._active_stream_id = "stream_test"
- adapter._active_stream_req_id = "req-1"
- adapter._active_stream_chat_id = "chat-1"
-
- result = await adapter.send("chat-2", "Hi")
-
- assert result.success is True
- assert adapter._active_stream_id is not None # untouched
-
- @pytest.mark.asyncio
- async def test_send_falls_through_when_stream_expired(self):
- from plugins.platforms.wecom.adapter import WeComAdapter
- from plugins.platforms.wecom.streaming import STREAM_EXPIRED_ERRCODE
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-1"] = "req-1"
-
- async def fake(req_id, body, **kwargs):
- if body.get("stream", {}).get("finish"):
- return {"errcode": STREAM_EXPIRED_ERRCODE, "errmsg": "expired"}
- return {"errcode": 0, "headers": {"req_id": req_id}}
-
- adapter._send_reply_request = AsyncMock(side_effect=fake)
- adapter._active_stream_id = "stream_test"
- adapter._active_stream_req_id = "req-1"
- adapter._active_stream_chat_id = "chat-1"
-
- result = await adapter.send("chat-1", "Final answer")
-
- assert result.success is True
- assert adapter._active_stream_id is None
- assert "chat-1" in adapter._stream_expired_chats
@@ -1482,24 +1185,6 @@ class TestFireAndForgetFrameFlow:
adapter._send_reply_queued = AsyncMock(side_effect=mock_send)
adapter._sent_frames = sent_frames
- @pytest.mark.asyncio
- async def test_short_text_sent_immediately(self):
- """Fire-and-forget: even a short body ships right after the seed —
- there is no min_chars buffering anymore."""
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- adapter._last_chat_req_ids["chat-1"] = "req-1"
- adapter._ws = MagicMock(closed=False)
- self._mock_send_json_with_immediate_ack(adapter)
-
- ok = await adapter.send_stream_frame("Hello.", chat_id="chat-1")
- assert ok is True
- # seed + content = 2 frames (the 6-char body is NOT buffered).
- assert len(adapter._sent_frames) == 2
- assert adapter._sent_frames[0]["body"]["stream"]["content"] == "<think></think>"
- assert adapter._sent_frames[1]["body"]["stream"]["content"] == "Hello."
- assert adapter._sent_frames[1]["body"]["stream"]["finish"] is False
@pytest.mark.asyncio
async def test_finalize_sends_accumulated_tail(self):
@@ -1579,7 +1264,6 @@ class TestFinalFrameAckTimeoutSemantics:
# ack_pending flag set so callers can log / observe but no exception.
assert response.get("errcode") == 0
assert response.get("ack_pending") is True
- assert "ack_timeout" in response.get("errmsg", "")
@pytest.mark.asyncio
async def test_final_frame_send_failure_still_raises(self):
diff --git a/tests/gateway/test_wecom_double_send.py b/tests/gateway/test_wecom_double_send.py
index e85be9ec2f9..842545fdc40 100644
--- a/tests/gateway/test_wecom_double_send.py
+++ b/tests/gateway/test_wecom_double_send.py
@@ -295,144 +295,7 @@ class TestTimeoutInversionDoubleSend:
# ===========================================================================
-# Test group 2: best-effort finalize "DO NOT mark" path
-# ===========================================================================
-
-
-class TestBestEffortFinalizeDoubleSend:
- """stream_consumer.py:2064-2094: when native streaming fails mid-turn, the
- consumer sends a best-effort finalize frame to close the bubble but
- deliberately does NOT set ``final_content_delivered`` (the "DO NOT mark"
- comment at 2085-2088). If WeCom actually renders that finalize frame, the
- subsequent fallback send delivers the same content a second time.
-
- This uses a controllable ``BasePlatformAdapter`` subclass (the accepted
- pattern in tests/gateway/test_wecom_per_turn.py) because the trigger is a
- frame-level failure, not an ack timing race — no wall-clock timing needed.
- """
-
- @pytest.mark.xfail(
- reason="KNOWN LOW-FREQUENCY ISSUE (accepted, not yet fixed): the "
- "best-effort finalize path (stream_consumer.py:2104-2128) renders the "
- "content AND falls through to a fallback send(), delivering the same "
- "answer twice. Only triggers when native streaming fails MID-STREAM "
- "(846608 expired / 846609 subscription lost / errcode 6000 / network "
- "error) — rare. The duplicate is a SAFE-direction failure (user sees "
- "one extra bubble, no data loss). A clean fix requires reconciling "
- "'do not drop post-finalize increments' with 'do not re-send the "
- "first-send path', which the first-send path (L2378) does not consult "
- "the delivery flag for; deferred over risking increment loss on a rare "
- "path. The high-frequency duplicate (timeout inversion) IS fixed — see "
- "TestTimeoutInversionDoubleSend + commit 7ba739818 (B2).",
- strict=True,
- )
- @pytest.mark.asyncio
- async def test_best_effort_finalize_renders_but_flag_unset_double_send(self):
- """native content frame fails → best-effort finalize renders + fallback send.
-
- Ordering matters: the delta is pushed and ``run()`` is allowed to
- process a mid-stream **content** frame BEFORE ``finish()`` is queued.
- That content frame fails (returns False), which disables native
- streaming and triggers the best-effort finalize at
- ``stream_consumer.py:2077`` — WeCom renders it — and then the consumer
- falls through to a fallback ``send()`` that delivers the same content a
- second time (the "DO NOT mark" comment at 2085-2088 is what leaves the
- gateway free to re-send).
-
- The text is > ``_MIN_NEW_VISIBLE_CHARS`` (60) so the mid-stream frame is
- actually attempted rather than buffered.
-
- Asserts the DESIRED single-delivery state, so it FAILS today (content
- rendered by the best-effort finalize AND re-sent by the fallback) and
- PASSES once the double delivery is closed.
- """
- from gateway.platforms.base import BasePlatformAdapter, SendResult
-
- class FlakyNativeAdapter(BasePlatformAdapter):
- MAX_MESSAGE_LENGTH = 4096
- SUPPORTS_MESSAGE_EDITING = False
- SUPPORTS_NATIVE_STREAMING = True
-
- def __init__(self):
- self._typing_paused = set()
- self._fatal_error_message = None
- # Records of everything that reached the user.
- self.rendered_stream_frames: list[dict] = [] # incl. finalize
- self.fallback_sends: list[str] = []
- self._content_frames_seen = 0
-
- def supports_native_streaming(self, chat_type=None, metadata=None):
- return True
-
- async def send_stream_frame(
- self, text, *, finalize=False, chat_id=None, reply_to=None, **kwargs
- ):
- # Seed frame (empty, non-finalize) opens the bubble.
- if text == "" and not finalize:
- self.rendered_stream_frames.append({"text": text, "finalize": False})
- return True
- if finalize:
- # Best-effort finalize frame — WeCom DOES render it.
- self.rendered_stream_frames.append({"text": text, "finalize": True})
- return True
- # First real content frame fails → disables native streaming
- # and triggers the best-effort finalize path.
- self._content_frames_seen += 1
- return False
-
- async def send(self, chat_id, content, reply_to=None, metadata=None):
- # The gateway/consumer fallback send — a SECOND delivery of the
- # same content.
- self.fallback_sends.append(content)
- return SendResult(success=True, message_id="fallback-msg")
-
- FlakyNativeAdapter.__abstractmethods__ = frozenset()
- adapter = FlakyNativeAdapter()
-
- cfg = StreamConsumerConfig(
- chat_type="dm", cursor="", edit_interval=0.01, buffer_threshold=5,
- )
- consumer = GatewayStreamConsumer(adapter, CHAT_ID, cfg)
-
- # > 60 visible chars so the mid-stream content frame is actually sent.
- final_text = (
- "需要交付给用户的最终答案。这一段内容刻意写得足够长,"
- "以便越过 stream_consumer 的 _MIN_NEW_VISIBLE_CHARS=60 阈值,"
- "从而在 got_done 之前触发一次真正的流式内容帧发送。"
- )
- assert len(final_text) >= 60
-
- consumer.on_delta(final_text)
- task = asyncio.create_task(consumer.run())
- # Let run() process the mid-stream content frame (which fails) BEFORE
- # the turn-final _DONE arrives.
- await asyncio.sleep(0.1)
- consumer.finish()
- await task
-
- best_effort_finalize = [
- f for f in adapter.rendered_stream_frames if f["finalize"] and f["text"]
- ]
-
- # Count content-bearing user-visible deliveries:
- # * best-effort finalize frame(s) that WeCom rendered, plus
- # * fallback send(s).
- content_deliveries = len(best_effort_finalize) + len(adapter.fallback_sends)
-
- # DESIRED post-fix invariant (currently violated == bug reproduced):
- # the same answer must reach the user exactly once. Today the
- # best-effort finalize renders the content AND the fallback send
- # delivers it again.
- assert content_deliveries == 1, (
- f"BUG: content delivered {content_deliveries} times — best-effort "
- f"finalize rendered {len(best_effort_finalize)} frame(s) and "
- f"fallback send fired {len(adapter.fallback_sends)} time(s) "
- f"(stream_consumer.py:2085-2088 'DO NOT mark' path)"
- )
-
-
-# ===========================================================================
-# Test group 3: orphan-queue ack routing race (adapter-level)
+# Test group 2: orphan-queue ack routing race (adapter-level)
# ===========================================================================
diff --git a/tests/gateway/test_wecom_per_turn.py b/tests/gateway/test_wecom_per_turn.py
index 063075dd530..20944dd9ca1 100644
--- a/tests/gateway/test_wecom_per_turn.py
+++ b/tests/gateway/test_wecom_per_turn.py
@@ -1,7 +1,7 @@
"""Tests for per-turn stream isolation and concurrent consumer scenarios."""
import pytest
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
from gateway.config import PlatformConfig
@@ -192,23 +192,6 @@ class TestPerTurnStreamIsolation:
finally:
await adapter.disconnect()
- @pytest.mark.asyncio
- async def test_expired_chat_blocks_new_turn_creation(self):
- """After one turn expired, new turn creation is blocked."""
- from plugins.platforms.wecom.adapter import WeComAdapter
-
- adapter = WeComAdapter(PlatformConfig(enabled=True))
- try:
- adapter._last_chat_req_ids["chat-1"] = "req-1"
- adapter._stream_expired_chats.add("chat-1")
- adapter._send_reply_request = AsyncMock(return_value={"errcode": 0})
-
- # Try to create a new turn after chat is expired
- ok = await adapter.send_stream_frame("new frame", chat_id="chat-1", turn_id="new-turn")
- assert ok is False
- assert "chat-1:new-turn" not in adapter._stream_turns
- finally:
- await adapter.disconnect()
class TestNativeFallbackStreamClose:
diff --git a/tests/gateway/test_wecom_plugin_setup.py b/tests/gateway/test_wecom_plugin_setup.py
deleted file mode 100644
index ffd4861adc5..00000000000
--- a/tests/gateway/test_wecom_plugin_setup.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Tests for the WeCom plugin's interactive_setup wizard home-channel flow.
-
-The interactive_setup wizard lazy-imports its CLI helpers from
-``hermes_cli.config`` (get_env_value / save_env_value / remove_env_value),
-``hermes_cli.cli_output`` (prompt / prompt_yes_no / print_*), and
-``hermes_cli.setup`` (prompt_choice); we patch each at its source module so
-the QR scan / pip paths never fire. Covers the home-channel clear-on-blank
-behavior added in the follow-up to PR #58421.
-"""
-import hermes_cli.config as config_mod
-import hermes_cli.cli_output as cli_output_mod
-import hermes_cli.setup as setup_mod
-from plugins.platforms.wecom.adapter import interactive_setup
-
-
-def _patch_setup_io(monkeypatch, prompts, choice_responses, saved, removed, existing):
- prompt_iter = iter(prompts)
- choice_iter = iter(choice_responses)
- monkeypatch.setattr(config_mod, "get_env_value", lambda key: existing.get(key, ""))
- monkeypatch.setattr(config_mod, "save_env_value", lambda k, v: saved.update({k: v}))
-
- def _remove(key):
- removed.append(key)
- return existing.pop(key, None) is not None
-
- monkeypatch.setattr(config_mod, "remove_env_value", _remove)
- monkeypatch.setattr(cli_output_mod, "prompt", lambda *_a, **_kw: next(prompt_iter))
- monkeypatch.setattr(cli_output_mod, "prompt_yes_no", lambda *_a, **_kw: False)
- monkeypatch.setattr(setup_mod, "prompt_choice", lambda *_a, **_kw: next(choice_iter))
- for name in ("print_header", "print_info", "print_success", "print_warning", "print_error"):
- monkeypatch.setattr(cli_output_mod, name, lambda *_a, **_kw: None)
- # Stub QR scan: returns None so the wizard falls through to manual entry.
- import plugins.platforms.wecom.adapter as wecom_adapter_mod
- monkeypatch.setattr(wecom_adapter_mod, "qr_scan_for_bot_info", lambda: None)
-
-
-# WeCom prompts (after method_choice): bot_id, secret (password), allowed_users, home.
-# choice_responses: 1 = "Enter Bot ID/Secret manually" so the QR path is skipped.
-_PROMPTS_NONEMPTY = [
- "wecom-bot-id-123", # bot_id
- "wecom-secret-abc", # secret
- "", # allowed_users (empty -> triggers DM policy choice below)
- "wecom-home-chat-id", # home chat ID
-]
-_PROMPTS_BLANK = [
- "wecom-bot-id-123",
- "wecom-secret-abc",
- "",
- "",
-]
-_PROMPTS_WHITESPACE = [
- "wecom-bot-id-123",
- "wecom-secret-abc",
- "",
- " ",
-]
-# 1 = method "Enter manually", 1 = DM policy "pairing" (skip the 4-way choice path).
-_CHOICES = [1, 1]
-
-
-class TestWeComHomeChannelClear:
- """Blank home-channel answer must clear WECOM_HOME_CHANNEL (#12423)."""
-
- def test_blank_removes_existing_home_channel(self, monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- saved, removed = {}, []
- _patch_setup_io(
- monkeypatch,
- _PROMPTS_BLANK,
- _CHOICES,
- saved,
- removed,
- existing={"WECOM_HOME_CHANNEL": "old-wecom-chat-id"},
- )
- interactive_setup()
- assert "WECOM_HOME_CHANNEL" in removed
- assert "WECOM_HOME_CHANNEL" not in saved
-
-
diff --git a/tests/gateway/test_weixin.py b/tests/gateway/test_weixin.py
index 9a5575b9aad..a63dc89b083 100644
--- a/tests/gateway/test_weixin.py
+++ b/tests/gateway/test_weixin.py
@@ -3,18 +3,14 @@
import asyncio
import base64
import json
-import os
from unittest.mock import AsyncMock, Mock, patch
import pytest
from gateway.config import PlatformConfig
-from gateway.config import GatewayConfig, HomeChannel, Platform, _apply_env_overrides
-from gateway.platforms.base import SendResult
-from gateway.platforms.event import MessageEvent, MessageType
+from gateway.config import GatewayConfig, Platform
from gateway.platforms import weixin
from gateway.platforms.weixin import ContextTokenStore, WeixinAdapter
-from tools.send_message_tool import _send_to_platform
from tools.send_message_targets import _parse_target_ref
@@ -28,19 +24,6 @@ def _make_adapter() -> WeixinAdapter:
)
-class TestWeixinInboundVoiceTranscript:
- def test_voice_transcript_keeps_voice_origin_marker(self):
- item_list = [
- {
- "type": weixin.ITEM_VOICE,
- "voice_item": {"text": "帮我查一下今天天气"},
- }
- ]
-
- assert weixin._extract_text(item_list) == (
- "[Voice transcription provided by Weixin]\n"
- "帮我查一下今天天气"
- )
class TestWeixinFormatting:
@@ -220,33 +203,6 @@ class TestWeixinStatePersistence:
assert writes[-1] == {"user-1": "t1", "user-2": "t2"}
-class TestWeixinQrLogin:
- @pytest.mark.asyncio
- async def test_qr_login_timeout_uses_monotonic_clock(self, tmp_path):
- first_qr = {
- "qrcode": "qr-1",
- "qrcode_img_content": "https://example.com/qr-1",
- }
- pending = {"status": "wait"}
-
- with patch("gateway.platforms.weixin._api_get", new_callable=AsyncMock) as api_get_mock, \
- patch("gateway.platforms.weixin.time") as mock_time, \
- patch("gateway.platforms.weixin.AIOHTTP_AVAILABLE", True), \
- patch("gateway.platforms.weixin.aiohttp.ClientSession", create=True) as session_cls, \
- patch("builtins.print"):
- api_get_mock.side_effect = [first_qr, pending]
- mock_time.monotonic.side_effect = [1000, 1000.2, 1001.1]
- mock_time.time.side_effect = [1000, 900, 901, 902]
-
- session = AsyncMock()
- session.__aenter__.return_value = session
- session.__aexit__.return_value = False
- session_cls.return_value = session
-
- result = await weixin.qr_login(str(tmp_path), timeout_seconds=1)
-
- assert result is None
- assert api_get_mock.await_count == 2
class TestWeixinSendMessageIntegration:
@@ -448,9 +404,6 @@ class TestWeixinOutboundMedia:
assert upload_url == "https://upload.example.com/media"
assert upload_kwargs["headers"] == {"Content-Type": "application/octet-stream"}
assert upload_kwargs["data"]
- # Timeout is now enforced externally via asyncio.wait_for() rather than
- # aiohttp.ClientTimeout, so it no longer appears as a post() kwarg.
- assert "timeout" not in upload_kwargs
payload = api_post_mock.await_args.kwargs["payload"]
media = payload["msg"]["item_list"][0]["image_item"]["media"]
assert media["encrypt_query_param"] == "enc-param"
@@ -510,12 +463,6 @@ class TestWeixinBlankMessagePrevention:
assert adapter._split_text("") == []
-class TestWeixinStreamingCursorSuppression:
- """WeChat doesn't support message editing — cursor must be suppressed."""
-
- def test_supports_message_editing_is_false(self):
- adapter = _make_adapter()
- assert adapter.SUPPORTS_MESSAGE_EDITING is False
class TestWeixinMediaBuilder:
@@ -623,10 +570,6 @@ class TestIsStaleSessionRet:
assert weixin._is_stale_session_ret(-2, None, "freq limit") is False
- def test_errcode_minus_14_is_not_matched_here(self):
- # -14 is handled by the separate SESSION_EXPIRED_ERRCODE path; the
- # helper only disambiguates -2 from a genuine rate limit.
- assert weixin._is_stale_session_ret(-14, None, "session expired") is False
class TestWeixinContentDedup:
@@ -729,23 +672,6 @@ class _StubSession:
class TestWeixinApiTimeout:
- def test_api_post_does_not_pass_aiohttp_timeout_kwarg(self):
- session = _StubSession(_StubResponse(body='{"ret": 0}'))
- result = asyncio.run(
- weixin._api_post(
- session,
- base_url="https://weixin.example.com",
- endpoint="ep",
- payload={"k": "v"},
- token="tok",
- timeout_ms=5000,
- )
- )
- assert result == {"ret": 0}
- # The fix enforces the timeout via asyncio.wait_for, so ClientTimeout is
- # gone and `timeout` is no longer forwarded to session.post().
- [(_url, kwargs)] = session.post_calls
- assert "timeout" not in kwargs
def test_get_updates_returns_empty_sentinel_on_timeout(self):
@@ -792,56 +718,7 @@ class TestWeixinVoiceAlwaysDownloaded:
},
}
- @pytest.mark.asyncio
- async def test_download_voice_returns_path_when_tencent_text_set(self, tmp_path, monkeypatch):
- """#27300 PRIMARY: voice ``_download_media`` must not short-circuit on
- ``voice_item.text``. The audio is needed so Hermes' own STT can
- re-transcribe when Tencent's text is in the wrong language.
- """
- adapter = _make_adapter()
- adapter._cdn_base_url = "https://example.invalid"
- adapter._poll_session = Mock()
- fake_audio_bytes = b"\\x00\\x01\\x02FAKE_SILK"
- monkeypatch.setattr(weixin, "cache_audio_from_bytes_async",
- AsyncMock(side_effect=lambda data, ext: str(tmp_path / f"voice.{ext.lstrip('.')}")))
-
- async def _fake_download(session, *, cdn_base_url, encrypted_query_param,
- aes_key_b64, full_url, timeout_seconds):
- return fake_audio_bytes
-
- monkeypatch.setattr(weixin, "_download_and_decrypt_media", _fake_download)
-
- item = self._make_voice_item(text="garbled-tencent-transcript")
- result, _mime = await adapter._download_media(item, weixin._INBOUND_MEDIA[weixin.ITEM_VOICE])
-
- # Currently broken: returns None when voice_item.text is set.
- # After fix: returns a local path so the central STT pipeline
- # can pick it up and re-transcribe.
- assert result is not None, (
- "_download_media returned None even though raw audio is "
- "available — Hermes' STT pipeline needs the audio to handle "
- "non-Chinese voice messages (#27300)."
- )
- assert result.endswith(".silk")
-
- def test_extract_text_does_not_return_tencent_voice_text(self):
- """#27300 SECONDARY: ``_extract_text`` must not return
- ``voice_item.text`` verbatim. That text is Tencent Cloud's
- STT output, which is wrong for non-Chinese audio and the
- whole reason #27300 was filed. Returning empty forces the
- central STT pipeline's transcript to become the body.
- """
- item_list = [self._make_voice_item(text="garbled-tencent-transcript")]
- result = weixin._extract_text(item_list)
- # Currently broken: returns "garbled-tencent-transcript".
- # After fix: returns "" (empty string) so the central pipeline
- # transcript replaces it as the user-visible body.
- assert result != "garbled-tencent-transcript", (
- "_extract_text returned Tencent's text directly — for "
- "non-Chinese audio this is garbage; the central STT "
- "pipeline's transcript should be the body (#27300)."
- )
@pytest.mark.asyncio
diff --git a/tests/gateway/test_weixin_typing.py b/tests/gateway/test_weixin_typing.py
index 2dc57066359..cf6397ba6b3 100644
--- a/tests/gateway/test_weixin_typing.py
+++ b/tests/gateway/test_weixin_typing.py
@@ -1,6 +1,5 @@
"""Tests for WeChat iLink typing ticket refresh logic (issue #38085)."""
-import asyncio
import time
from unittest.mock import AsyncMock, MagicMock, patch
@@ -91,13 +90,5 @@ class TestEnsureTypingTicket:
assert ticket is None
-class TestTypingTicketCache:
- """Tests for the TypingTicketCache TTL logic."""
-
- def test_returns_ticket_when_fresh(self):
- from gateway.platforms.weixin import TypingTicketCache
- cache = TypingTicketCache(ttl_seconds=600.0)
- cache.set("user-1", "ticket-1")
- assert cache.get("user-1") == "ticket-1"
diff --git a/tests/gateway/test_whatsapp_bridge_pidfile.py b/tests/gateway/test_whatsapp_bridge_pidfile.py
index 93f98231d76..5e728461f0e 100644
--- a/tests/gateway/test_whatsapp_bridge_pidfile.py
+++ b/tests/gateway/test_whatsapp_bridge_pidfile.py
@@ -25,13 +25,10 @@ import os
import socket
from plugins.platforms.whatsapp.adapter import (
- _bridge_pid_is_ours,
- _kill_port_process,
_kill_stale_bridge_by_pidfile,
_listener_pids_on_port,
_write_bridge_pidfile,
)
-from gateway.status import get_process_start_time, _pid_exists
def _spawn_sleeper(*extra_argv, seconds: float = 0.2) -> subprocess.Popen:
@@ -50,18 +47,6 @@ def _wait_dead(proc: subprocess.Popen, timeout: float = 5.0) -> bool:
return False
-class TestWriteAndRoundTrip:
- def test_pidfile_records_pid_and_start_time(self, tmp_path):
- proc = _spawn_sleeper()
- try:
- _write_bridge_pidfile(tmp_path, proc.pid)
- lines = (tmp_path / "bridge.pid").read_text().split("\n")
- assert int(lines[0]) == proc.pid
- # Line 2 is the kernel start time (present on Linux).
- assert int(lines[1]) == get_process_start_time(proc.pid)
- finally:
- proc.kill()
- proc.wait()
class TestIdentityGuard:
diff --git a/tests/gateway/test_whatsapp_cloud.py b/tests/gateway/test_whatsapp_cloud.py
index e2ef201f932..06dcd7a254a 100644
--- a/tests/gateway/test_whatsapp_cloud.py
+++ b/tests/gateway/test_whatsapp_cloud.py
@@ -532,21 +532,6 @@ class TestHealth:
# Mixin contract — gating still works on the cloud adapter
# ---------------------------------------------------------------------------
-class TestMixinInherited:
- """Sanity-check: the Cloud adapter inherits the same gating behavior
- as the Baileys adapter via WhatsAppBehaviorMixin.
- """
-
-
- def test_should_process_message_dm_open(self):
- adapter = _make_adapter()
- adapter._dm_policy = "open"
- assert adapter._should_process_message({
- "chatId": "[email protected]",
- "senderId": "[email protected]",
- "isGroup": False,
- "body": "hi",
- }) is True
# ---------------------------------------------------------------------------
@@ -912,7 +897,7 @@ class TestGroupMessageGuard:
group)."""
@pytest.mark.asyncio
- async def test_group_shaped_message_dropped_with_warning(self, caplog):
+ async def test_group_shaped_message_dropped(self):
adapter = _make_adapter()
adapter.handle_message = AsyncMock()
raw = {
@@ -923,16 +908,10 @@ class TestGroupMessageGuard:
"text": {"body": "hi from a group"},
"chat": "[email protected]", # presence of `chat` = group
}
- with caplog.at_level("WARNING"):
- event = await adapter._build_message_event_from_cloud(
- raw, {"15551234567": "Alice"}, {}
- )
- assert event is None
- # Warning surfaced so the operator knows group messages are being dropped
- assert any(
- "group-shaped" in rec.message
- for rec in caplog.records
+ event = await adapter._build_message_event_from_cloud(
+ raw, {"15551234567": "Alice"}, {}
)
+ assert event is None
# Defensive: handler not invoked
adapter.handle_message.assert_not_called()
@@ -1375,27 +1354,6 @@ class TestSendTyping:
assert payload["typing_indicator"] == {"type": "text"}
- @pytest.mark.asyncio
- async def test_send_typing_stale_message_logged_at_info(self, caplog):
- """Graph error 131009 = wamid > 30 days old. Common after a
- long-quiet conversation — log at INFO so it doesn't pollute
- WARNING-level monitoring dashboards."""
- adapter = _make_adapter()
- adapter._last_inbound_wamid_by_chat["15551234567"] = "wamid.OLD"
- adapter._http_client = MagicMock()
- adapter._http_client.post = AsyncMock(
- return_value=_mock_httpx_response(
- 400, {"error": {"code": 131009, "message": "Parameter value is not valid"}}
- )
- )
-
- with caplog.at_level("INFO"):
- await adapter.send_typing("15551234567")
-
- assert any(
- "older than 30 days" in rec.message
- for rec in caplog.records
- )
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_whatsapp_connect.py b/tests/gateway/test_whatsapp_connect.py
index 0e577bfd194..587e5e2f097 100644
--- a/tests/gateway/test_whatsapp_connect.py
+++ b/tests/gateway/test_whatsapp_connect.py
@@ -111,25 +111,6 @@ def _connect_patches(mock_proc, mock_fh, mock_client_cls=None):
# _close_bridge_log() unit tests
# ---------------------------------------------------------------------------
-class TestCloseBridgeLog:
- """Direct tests for the _close_bridge_log() helper method."""
-
- @staticmethod
- def _bare_adapter():
- from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
- a = WhatsAppAdapter.__new__(WhatsAppAdapter)
- a._bridge_log_fh = None
- return a
-
- def test_closes_open_handle(self):
- adapter = self._bare_adapter()
- mock_fh = MagicMock()
- adapter._bridge_log_fh = mock_fh
-
- adapter._close_bridge_log()
-
- mock_fh.close.assert_called_once()
- assert adapter._bridge_log_fh is None
# ---------------------------------------------------------------------------
@@ -220,7 +201,6 @@ class TestConnectCleanup:
assert result is False
assert adapter.fatal_error_code == "whatsapp_npm_install_failed"
assert adapter.fatal_error_retryable is False
- assert "npm install failed" in (adapter.fatal_error_message or "")
mock_release.assert_called_once_with("whatsapp-session", str(adapter._session_path))
assert adapter._platform_lock_identity is None
@@ -245,7 +225,6 @@ class TestBridgeRuntimeFailure:
result = await adapter.send("chat-123", "hello")
assert result.success is False
- assert "exited unexpectedly" in result.error
assert adapter.fatal_error_code == "whatsapp_bridge_exited"
assert adapter.fatal_error_retryable is True
fatal_handler.assert_awaited_once()
@@ -452,14 +431,8 @@ class TestHttpSessionLifecycle:
patch("plugins.platforms.whatsapp.adapter.asyncio.sleep", new_callable=AsyncMock):
await adapter.disconnect()
- mock_run.assert_called_once_with(
- ["taskkill", "/PID", "12345", "/T"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=10,
- )
+ mock_run.assert_called_once()
+ assert mock_run.call_args.args[0] == ["taskkill", "/PID", "12345", "/T"]
mock_proc.terminate.assert_not_called()
mock_proc.kill.assert_not_called()
diff --git a/tests/gateway/test_whatsapp_formatting.py b/tests/gateway/test_whatsapp_formatting.py
index fbbbc34bec0..791bedf84e4 100644
--- a/tests/gateway/test_whatsapp_formatting.py
+++ b/tests/gateway/test_whatsapp_formatting.py
@@ -356,11 +356,4 @@ class TestBridgeEventMetadata:
# display_config tier classification
# ---------------------------------------------------------------------------
-class TestWhatsAppTier:
- """WhatsApp should be classified as TIER_MEDIUM."""
-
- def test_whatsapp_streaming_follows_global(self):
- from gateway.display_config import resolve_display_setting
- # TIER_MEDIUM has streaming: None (follow global), not False
- assert resolve_display_setting({}, "whatsapp", "streaming") is None
diff --git a/tests/gateway/test_whatsapp_plugin_setup.py b/tests/gateway/test_whatsapp_plugin_setup.py
deleted file mode 100644
index 612a514e542..00000000000
--- a/tests/gateway/test_whatsapp_plugin_setup.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""Tests for the WhatsApp plugin's interactive_setup wizard home-channel flow.
-
-The interactive_setup wizard lazy-imports its CLI helpers from
-``hermes_cli.config`` (get_env_value / save_env_value / remove_env_value) and
-``hermes_cli.cli_output`` (prompt / prompt_yes_no / print_*); we patch those
-source modules. Covers the home-channel clear-on-blank behavior added in
-PR #58421 and extended in the follow-up.
-"""
-import hermes_cli.config as config_mod
-import hermes_cli.cli_output as cli_output_mod
-from plugins.platforms.whatsapp.adapter import interactive_setup
-
-
-def _patch_setup_io(monkeypatch, prompts, yes_no_responses, saved, removed, existing):
- prompt_iter = iter(prompts)
- yes_no_iter = iter(yes_no_responses)
- monkeypatch.setattr(config_mod, "get_env_value", lambda key: existing.get(key, ""))
- monkeypatch.setattr(config_mod, "save_env_value", lambda k, v: saved.update({k: v}))
-
- def _remove(key):
- removed.append(key)
- return existing.pop(key, None) is not None
-
- monkeypatch.setattr(config_mod, "remove_env_value", _remove)
- monkeypatch.setattr(cli_output_mod, "prompt", lambda *_a, **_kw: next(prompt_iter))
- monkeypatch.setattr(
- cli_output_mod, "prompt_yes_no", lambda *_a, **_kw: next(yes_no_iter)
- )
- for name in ("print_header", "print_info", "print_success", "print_warning"):
- monkeypatch.setattr(cli_output_mod, name, lambda *_a, **_kw: None)
-
-
-# WhatsApp prompts (after the Enable? prompt_yes_no): allowed_users, home_channel.
-# Enable? = True so we don't return early.
-_PROMPTS_NONEMPTY = ["", "[email protected]"]
-_PROMPTS_BLANK = ["", ""]
-_PROMPTS_WHITESPACE = ["", " "]
-_YES_NO = [True] # Enable WhatsApp? -> True
-
-
-class TestWhatsAppHomeChannelClear:
- """Blank home-channel answer must clear WHATSAPP_HOME_CHANNEL (#12423)."""
-
- def test_blank_removes_existing_home_channel(self, monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- saved, removed = {}, []
- _patch_setup_io(
- monkeypatch,
- _PROMPTS_BLANK,
- _YES_NO,
- saved,
- removed,
- existing={"WHATSAPP_HOME_CHANNEL": "[email protected]"},
- )
- interactive_setup()
- assert "WHATSAPP_HOME_CHANNEL" in removed
- assert "WHATSAPP_HOME_CHANNEL" not in saved
-
-
diff --git a/tests/gateway/test_whatsapp_reply_prefix.py b/tests/gateway/test_whatsapp_reply_prefix.py
index c67a0fefb19..1784fbca6a4 100644
--- a/tests/gateway/test_whatsapp_reply_prefix.py
+++ b/tests/gateway/test_whatsapp_reply_prefix.py
@@ -9,14 +9,12 @@ Covers:
- Config version covers all ENV_VARS_BY_VERSION keys (regression guard)
"""
-import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
import pytest
from gateway.config import Platform, PlatformConfig
-from gateway.platforms.event import MessageEvent, MessageType
class _AsyncResponseContext:
@@ -73,14 +71,6 @@ class TestConfigYamlBridging:
# ---------------------------------------------------------------------------
-class TestAdapterInit:
- """Test that WhatsAppAdapter reads reply_prefix from config.extra."""
-
- def test_reply_prefix_from_extra(self):
- from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
- config = PlatformConfig(enabled=True, extra={"reply_prefix": "Bot\\n"})
- adapter = WhatsAppAdapter(config)
- assert adapter._reply_prefix == "Bot\\n"
class TestBridgeEnvironment:
diff --git a/tests/gateway/test_whatsapp_stale_bridge.py b/tests/gateway/test_whatsapp_stale_bridge.py
index db8b197e82a..36cc6c3cf86 100644
--- a/tests/gateway/test_whatsapp_stale_bridge.py
+++ b/tests/gateway/test_whatsapp_stale_bridge.py
@@ -105,15 +105,6 @@ def _fresh_node_modules(bridge_dir: Path) -> None:
)
-class TestFileContentHash:
- def test_hashes_file(self, tmp_path):
- from plugins.platforms.whatsapp.adapter import _file_content_hash
-
- f = tmp_path / "x.js"
- f.write_text("abc", encoding="utf-8")
- h = _file_content_hash(f)
- assert len(h) == 16
- assert h == _file_content_hash(f) # deterministic
class TestStaleBridgeHandshake:
diff --git a/tests/gateway/test_whatsapp_text_batching.py b/tests/gateway/test_whatsapp_text_batching.py
index 591897e60f0..83208c1d487 100644
--- a/tests/gateway/test_whatsapp_text_batching.py
+++ b/tests/gateway/test_whatsapp_text_batching.py
@@ -8,7 +8,6 @@ mirrors the Telegram/WeCom/Feishu pattern.
Batch delays are read from ``config.extra`` (config.yaml), not env vars.
"""
-import asyncio
from gateway.config import Platform, PlatformConfig
from gateway.platforms.event import MessageEvent, MessageType
@@ -47,7 +46,8 @@ def test_invalid_config_value_falls_back_to_default():
text_batch_delay_seconds="garbage",
text_batch_split_delay_seconds=-3,
)
- assert adapter._text_batch_delay_seconds == 0.3
- assert adapter._text_batch_split_delay_seconds == 1.0
+ default = _make_adapter()
+ assert adapter._text_batch_delay_seconds == default._text_batch_delay_seconds
+ assert adapter._text_batch_split_delay_seconds == default._text_batch_split_delay_seconds
diff --git a/tests/gateway/test_ws_auth_retry_verifier_probe.py b/tests/gateway/test_ws_auth_retry_verifier_probe.py
index 514e62a1565..2d1d825c89a 100644
--- a/tests/gateway/test_ws_auth_retry_verifier_probe.py
+++ b/tests/gateway/test_ws_auth_retry_verifier_probe.py
@@ -105,50 +105,4 @@ class TestMattermostWSAuthRetryBoundaryProbes:
assert call_count == 2
- def test_unauthorized_substring_no_longer_stops_reconnect(self):
- """Before the fix, a transient error whose message contained the
- word 'unauthorized' (not digits) would ALSO trip the removed
- substring fallback. The implementer's regression test only
- covered the '401' digit-substring case; this proves the
- 'unauthorized' word variant is equally fixed."""
- adapter = _make_adapter()
- call_count = 0
-
- async def fake_connect():
- nonlocal call_count
- call_count += 1
- if call_count >= 2:
- adapter._closing = True
- raise RuntimeError(
- "upstream proxy replied: request unauthorized by WAF rule, retry"
- )
-
- adapter._ws_connect_and_listen = fake_connect
-
- with patch("asyncio.sleep", new=AsyncMock()):
- asyncio.run(adapter._ws_loop())
-
- assert call_count == 2
-
- def test_repeated_transient_errors_all_retry(self):
- """Guards against a fix that only relaxes classification for the
- FIRST occurrence (e.g. some hidden retry-budget/counter that
- starts rejecting after N attempts). Runs 5 consecutive
- transient errors and confirms every one retries."""
- adapter = _make_adapter()
- call_count = 0
- target_attempts = 5
-
- async def fake_connect():
- nonlocal call_count
- call_count += 1
- if call_count >= target_attempts:
- adapter._closing = True
- raise RuntimeError("403 seen in unrelated proxy diagnostic body")
-
- adapter._ws_connect_and_listen = fake_connect
-
- with patch("asyncio.sleep", new=AsyncMock()):
- asyncio.run(adapter._ws_loop())
- assert call_count == target_attempts
diff --git a/tests/gateway/test_yolo_command.py b/tests/gateway/test_yolo_command.py
index 501b1ec6250..560e2a9ee46 100644
--- a/tests/gateway/test_yolo_command.py
+++ b/tests/gateway/test_yolo_command.py
@@ -48,15 +48,13 @@ async def test_yolo_command_toggles_only_current_session(monkeypatch):
session_a = runner._session_key_for_source(event_a.source)
session_b = runner._session_key_for_source(_make_event("chat-b").source)
- result_on = await runner._handle_yolo_command(event_a)
+ await runner._handle_yolo_command(event_a)
- assert "ON" in result_on
assert is_session_yolo_enabled(session_a) is True
assert is_session_yolo_enabled(session_b) is False
assert os.environ.get("HERMES_YOLO_MODE") is None
- result_off = await runner._handle_yolo_command(event_a)
+ await runner._handle_yolo_command(event_a)
- assert "OFF" in result_off
assert is_session_yolo_enabled(session_a) is False
assert os.environ.get("HERMES_YOLO_MODE") is None
diff --git a/tests/gateway/test_yuanbao_integration.py b/tests/gateway/test_yuanbao_integration.py
index b40c1ea0c23..070ade2256c 100644
--- a/tests/gateway/test_yuanbao_integration.py
+++ b/tests/gateway/test_yuanbao_integration.py
@@ -41,12 +41,6 @@ def make_config(**kwargs):
# 1. Adapter 初始化
# ===========================================================
-class TestYuanbaoAdapterInit:
- def test_create_adapter(self):
- config = make_config()
- adapter = YuanbaoAdapter(config)
- assert adapter is not None
- assert adapter.PLATFORM == Platform.YUANBAO
@@ -55,8 +49,6 @@ class TestYuanbaoAdapterInit:
# ===========================================================
class TestYuanbaoConfig:
- def test_platform_enum(self):
- assert Platform.YUANBAO.value == "yuanbao"
def test_get_connected_platforms_requires_key_and_secret(self):
@@ -90,10 +82,6 @@ class TestYuanbaoConfig:
# ===========================================================
class TestGatewayRunnerRegistration:
- def test_yuanbao_in_platform_enum(self):
- """Platform 枚举包含 YUANBAO"""
- assert hasattr(Platform, "YUANBAO")
- assert Platform.YUANBAO.value == "yuanbao"
def _make_minimal_runner(self, config):
"""通过 __new__ + 最小初始化绕过 run.py 的模块级 dotenv/ssl 副作用"""
@@ -150,15 +138,6 @@ class TestGatewayRunnerRegistration:
# 4. Proto round-trip
# ===========================================================
-class TestProtoRoundTrip:
- """验证 proto 编解码基本功能"""
-
- def test_conn_msg_roundtrip(self):
- from gateway.platforms.yuanbao_proto import encode_conn_msg, decode_conn_msg
- encoded = encode_conn_msg(msg_type=1, seq_no=42, data=b"hello")
- decoded = decode_conn_msg(encoded)
- assert decoded["seq_no"] == 42
- assert decoded["data"] == b"hello"
@@ -166,16 +145,6 @@ class TestProtoRoundTrip:
# 5. Markdown 分块
# ===========================================================
-class TestMarkdownChunking:
- def test_chunks_are_sent_separately(self):
- from gateway.platforms.yuanbao import MarkdownProcessor
- long_text = "paragraph\n\n" * 100
- chunks = MarkdownProcessor.chunk_markdown_text(long_text, 200)
- assert len(chunks) > 1
- for c in chunks:
- # 段落原子块允许轻微超限,仅验证不崩溃
- assert isinstance(c, str)
- assert len(c) > 0
@@ -189,24 +158,6 @@ class TestMarkdownChunking:
# 6b. ConnectionManager / OutboundManager
# ===========================================================
-class TestManagerImports:
-
-
-
-
-
- def test_adapter_has_outbound_manager(self):
- adapter = YuanbaoAdapter(make_config())
- from gateway.platforms.yuanbao import ConnectionManager, OutboundManager
- assert isinstance(adapter._connection, ConnectionManager)
- assert isinstance(adapter._outbound, OutboundManager)
-
- def test_outbound_composes_sub_managers(self):
- adapter = YuanbaoAdapter(make_config())
- from gateway.platforms.yuanbao import MessageSender, HeartbeatManager, SlowResponseNotifier
- assert isinstance(adapter._outbound.sender, MessageSender)
- assert isinstance(adapter._outbound.heartbeat, HeartbeatManager)
- assert isinstance(adapter._outbound.slow_notifier, SlowResponseNotifier)
# ===========================================================
@@ -219,14 +170,6 @@ class TestManagerImports:
# 8. Toolset 注册
# ===========================================================
-class TestToolset:
- def test_yuanbao_toolset_registered(self):
- """toolsets.py 中存在 hermes-yuanbao 键"""
- import importlib
- ts = importlib.import_module("toolsets")
- assert hasattr(ts, "TOOLSETS") or hasattr(ts, "toolsets")
- toolsets_dict = getattr(ts, "TOOLSETS", getattr(ts, "toolsets", {}))
- assert "hermes-yuanbao" in toolsets_dict
@@ -241,29 +184,8 @@ class TestToolset:
# ===========================================================
import asyncio
-import collections
-class TestP0ReconnectGuard:
- """P0-1: _reconnecting flag prevents concurrent reconnect attempts."""
-
- def test_reconnecting_flag_initialized(self):
- adapter = YuanbaoAdapter(make_config())
- assert hasattr(adapter._connection, '_reconnecting')
- assert adapter._connection._reconnecting is False
-
- def test_schedule_reconnect_skips_when_not_running(self):
- adapter = YuanbaoAdapter(make_config())
- adapter._running = False
- adapter._connection._reconnecting = False
- adapter._connection.schedule_reconnect()
- # No task should be created because _running is False
-
- def test_schedule_reconnect_skips_when_already_reconnecting(self):
- adapter = YuanbaoAdapter(make_config())
- adapter._running = True
- adapter._connection._reconnecting = True
- adapter._connection.schedule_reconnect()
# No new task should be created because already reconnecting
@@ -295,27 +217,8 @@ class TestP0ChatLockEviction:
# The oldest unlocked entry should have been evicted
assert len(adapter._outbound.sender._chat_locks) == MessageSender.CHAT_DICT_MAX_SIZE
- def test_move_to_end_on_access(self):
- """Accessing an existing key moves it to the end (MRU)."""
- adapter = YuanbaoAdapter(make_config())
- adapter._outbound.sender._chat_locks["a"] = asyncio.Lock()
- adapter._outbound.sender._chat_locks["b"] = asyncio.Lock()
- adapter._outbound.sender._chat_locks["c"] = asyncio.Lock()
-
- # Access "a" — should move to end
- adapter._outbound.sender.get_chat_lock("a")
- keys = list(adapter._outbound.sender._chat_locks.keys())
- assert keys[-1] == "a"
- assert keys[0] == "b"
-class TestP0PlatformScopedLock:
- """P0-4: connect() calls _acquire_platform_lock."""
-
- def test_adapter_has_platform_lock_methods(self):
- adapter = YuanbaoAdapter(make_config())
- assert hasattr(adapter, '_acquire_platform_lock')
- assert hasattr(adapter, '_release_platform_lock')
if __name__ == "__main__":
diff --git a/tests/gateway/test_yuanbao_markdown.py b/tests/gateway/test_yuanbao_markdown.py
index 42ce50028e0..098e481288a 100644
--- a/tests/gateway/test_yuanbao_markdown.py
+++ b/tests/gateway/test_yuanbao_markdown.py
@@ -92,22 +92,8 @@ class TestChunkMarkdownText(unittest.TestCase):
- def test_5000_chars_returns_2(self):
- """验收标准: 'a'*5000 with max 3000 → 2 chunks"""
- result = MarkdownProcessor.chunk_markdown_text("a" * 5000, 3000)
- self.assertEqual(len(result), 2)
-
-
- def test_table_not_split(self):
- """表格行不应被切断"""
- header = "| Name | Value | Description |\n| --- | --- | --- |"
- rows = "\n".join([f"| item_{i} | {i * 100} | description for item {i} |"
- for i in range(50)])
- table = f"{header}\n{rows}"
- text = "Some intro text.\n\n" + table + "\n\nSome outro text."
- result = MarkdownProcessor.chunk_markdown_text(text, 3000)
- for chunk in result:
- self.assertFalse(_mdchunk.text_has_unclosed_fence(chunk))
+
+
def test_multiple_paragraphs(self):
@@ -133,13 +119,6 @@ class TestChunkMarkdownText(unittest.TestCase):
# ============ Acceptance criteria ============
-class TestAcceptanceCriteria(unittest.TestCase):
- def test_9000_x_returns_3_chunks(self):
- """验收:MarkdownProcessor.chunk_markdown_text("x" * 9000, 3000) 返回 3 个片段"""
- result = MarkdownProcessor.chunk_markdown_text("x" * 9000, 3000)
- self.assertEqual(len(result), 3)
- for chunk in result:
- self.assertLessEqual(len(chunk), 3000)
diff --git a/tests/gateway/test_yuanbao_pipeline.py b/tests/gateway/test_yuanbao_pipeline.py
index a8ee914e34e..c869a3b2ef6 100644
--- a/tests/gateway/test_yuanbao_pipeline.py
+++ b/tests/gateway/test_yuanbao_pipeline.py
@@ -37,13 +37,10 @@ from gateway.platforms.yuanbao import (
AutoSetHomeMiddleware,
ExtractContentMiddleware,
PlaceholderFilterMiddleware,
- OwnerCommandMiddleware,
- BuildSourceMiddleware,
GroupAtGuardMiddleware,
QuoteContextMiddleware,
MediaResolveMiddleware,
PatchAnchorsMiddleware,
- DispatchMiddleware,
InboundPipelineBuilder,
YuanbaoAdapter,
_MIN_RESOLVE_CONCURRENCY,
@@ -120,12 +117,6 @@ def make_json_push(
class TestInboundPipeline:
"""Test the pipeline engine itself."""
- @pytest.mark.asyncio
- async def test_empty_pipeline(self):
- """Empty pipeline executes without error."""
- pipeline = InboundPipeline()
- ctx = make_ctx()
- await pipeline.execute(ctx) # Should not raise
@@ -680,33 +671,6 @@ class TestAutoSetHomeAfterGroupAtGuard:
# 4. Factory Tests
# ============================================================
-class TestCreateInboundPipeline:
- def test_default_pipeline_has_all_middlewares(self):
- """InboundPipelineBuilder.build() creates pipeline with all expected middlewares."""
- pipeline = InboundPipelineBuilder.build()
- expected = [
- "decode",
- "extract-fields",
- "recall_guard",
- "dedup",
- "skip-self",
- "chat-routing",
- "access-guard",
- "extract-content",
- "placeholder-filter",
- "owner-command",
- "build-source",
- "group-at-guard",
- "auto-sethome",
- "group-attribution",
- "classify-msg-type",
- "quote-context",
- "forwarded-records-parse",
- "media-resolve",
- "patch-anchors",
- "dispatch",
- ]
- assert pipeline.middleware_names == expected
# ============================================================
@@ -776,12 +740,6 @@ class TestPipelineIntegration:
- @pytest.mark.asyncio
- async def test_adapter_has_pipeline(self):
- """YuanbaoAdapter.__init__ creates an inbound pipeline."""
- adapter = make_adapter()
- assert hasattr(adapter, "_inbound_pipeline")
- assert isinstance(adapter._inbound_pipeline, InboundPipeline)
@@ -793,63 +751,8 @@ if __name__ == "__main__":
# 6. OOP Middleware Tests
# ============================================================
-class TestInboundMiddlewareABC:
- """Test the InboundMiddleware OOP protocol (callable + named)."""
- def test_subclass_with_handle_works(self):
- """Subclass with handle() can be instantiated."""
- class GoodMiddleware(InboundMiddleware):
- name = "good"
- async def handle(self, ctx, next_fn):
- await next_fn()
- mw = GoodMiddleware()
- assert mw.name == "good"
-
- @pytest.mark.asyncio
- async def test_callable_protocol(self):
- """Middleware instances are callable via __call__."""
- class TestMW(InboundMiddleware):
- name = "test"
- async def handle(self, ctx, next_fn):
- ctx.raw_text = "called"
- await next_fn()
-
- mw = TestMW()
- ctx = make_ctx()
- next_fn = AsyncMock()
- await mw(ctx, next_fn) # Call via __call__
- assert ctx.raw_text == "called"
- next_fn.assert_awaited_once()
-
-
-class TestMiddlewareClasses:
- """Pin the canonical ``name`` of each concrete middleware class.
-
- These names are referenced by ``InboundPipelineBuilder.build()`` ordering,
- by ``use_before`` / ``use_after`` insertion in extensions, and by log
- messages — so they're a real downstream contract worth pinning.
- """
- MIDDLEWARE_CLASSES = [
- (DecodeMiddleware, "decode"),
- (ExtractFieldsMiddleware, "extract-fields"),
- (DedupMiddleware, "dedup"),
- (SkipSelfMiddleware, "skip-self"),
- (ChatRoutingMiddleware, "chat-routing"),
- (AccessGuardMiddleware, "access-guard"),
- (ExtractContentMiddleware, "extract-content"),
- (PlaceholderFilterMiddleware, "placeholder-filter"),
- (OwnerCommandMiddleware, "owner-command"),
- (BuildSourceMiddleware, "build-source"),
- (GroupAtGuardMiddleware, "group-at-guard"),
- (DispatchMiddleware, "dispatch"),
- ]
-
- @pytest.mark.parametrize("cls,expected_name", MIDDLEWARE_CLASSES)
- def test_has_correct_name(self, cls, expected_name):
- """Each middleware class has the expected name."""
- mw = cls()
- assert mw.name == expected_name
class TestPipelineOOPRegistration:
@@ -890,10 +793,6 @@ class TestPipelineOOPRegistration:
class TestQuoteContextMiddleware:
"""Tests for QuoteContextMiddleware._extract_quote_context."""
- def test_extract_quote_context_no_cloud_data(self):
- """Returns (None, None) when cloud_custom_data is empty."""
- result = QuoteContextMiddleware()._extract_quote_context("")
- assert result == (None, None)
diff --git a/tests/gateway/test_yuanbao_proto.py b/tests/gateway/test_yuanbao_proto.py
index faf6f678ae0..cfee6551577 100644
--- a/tests/gateway/test_yuanbao_proto.py
+++ b/tests/gateway/test_yuanbao_proto.py
@@ -37,14 +37,10 @@ from gateway.platforms.yuanbao_proto import (
# 入站/出站
decode_inbound_push,
encode_send_c2c_message,
- encode_send_group_message,
- # 帮助函数
encode_auth_bind,
encode_ping,
encode_push_ack,
# 常量
- PB_MSG_TYPES,
- BIZ_SERVICES,
CMD_TYPE,
next_seq_no,
)
@@ -292,39 +288,6 @@ class TestDecodeInboundPush:
# 6. 出站消息编码
# ===========================================================
-class TestEncodeOutbound:
- def test_encode_send_c2c_message(self):
- msg_body = [{"msg_type": "TIMTextElem", "msg_content": {"text": "hi"}}]
- result = encode_send_c2c_message(
- to_account="user_b",
- msg_body=msg_body,
- from_account="bot",
- msg_id="msg-001",
- )
- assert isinstance(result, bytes)
- assert len(result) > 0
- # 解码验证 ConnMsg 结构
- dec = decode_conn_msg(result)
- assert dec["head"]["cmd"] == "send_c2c_message"
- assert dec["head"]["msg_id"] == "msg-001"
- assert dec["head"]["module"] == "yuanbao_openclaw_proxy"
- assert len(dec["data"]) > 0
-
-
- def test_c2c_biz_payload_contains_to_account(self):
- """验证 biz payload 包含 to_account 字段"""
- from gateway.platforms.yuanbao_proto import _get_string
- msg_body = [{"msg_type": "TIMTextElem", "msg_content": {"text": "test"}}]
- result = encode_send_c2c_message(
- to_account="target_user",
- msg_body=msg_body,
- from_account="bot",
- )
- dec = decode_conn_msg(result)
- biz_data = dec["data"]
- fdict = _fields_to_dict(_parse_fields(biz_data))
- to_acc = _get_string(fdict, 2) # SendC2CMessageReq.to_account = field 2
- assert to_acc == "target_user"
@@ -380,12 +343,6 @@ class TestAuthAndPing:
# ===========================================================
class TestConstants:
- def test_pb_msg_types_keys(self):
- assert "ConnMsg" in PB_MSG_TYPES
- assert "AuthBindReq" in PB_MSG_TYPES
- assert "PingReq" in PB_MSG_TYPES
- assert "KickoutMsg" in PB_MSG_TYPES
- assert "PushMsg" in PB_MSG_TYPES
def test_cmd_type_values(self):
diff --git a/tests/gateway/test_yuanbao_shutdown.py b/tests/gateway/test_yuanbao_shutdown.py
index 0b65cf53ded..9db65469207 100644
--- a/tests/gateway/test_yuanbao_shutdown.py
+++ b/tests/gateway/test_yuanbao_shutdown.py
@@ -89,21 +89,6 @@ async def test_cleanup_ws_does_not_stall_on_hung_server():
assert elapsed < WS_CLOSE_TIMEOUT_S + 1.0
-async def test_cleanup_ws_fast_path_returns_immediately():
- """A responsive server completes the handshake well under the bound."""
- cm = _connection()
- fast = _FastWS()
- cm._ws = fast
-
- loop = asyncio.get_running_loop()
- start = loop.time()
- await cm._cleanup_ws()
- elapsed = loop.time() - start
-
- assert fast.close_called
- assert cm._ws is None
- assert elapsed < 1.0
@pytest.mark.asyncio
diff --git a/tests/hermes_cli/test_active_session_exclusivity.py b/tests/hermes_cli/test_active_session_exclusivity.py
index 20860fdc875..5cbbe02e9b2 100644
--- a/tests/hermes_cli/test_active_session_exclusivity.py
+++ b/tests/hermes_cli/test_active_session_exclusivity.py
@@ -24,7 +24,6 @@ import pytest
from hermes_cli.active_sessions import (
MAX_CONCURRENT_SESSIONS,
- PER_SESSION_EXCLUSIVE_SUBMIT,
SESSION_NOT_OWNED,
active_session_registry_snapshot,
release_active_session,
@@ -100,7 +99,6 @@ def test_global_capacity_still_applies_independently():
"a capacity refusal must not be reported as an ownership refusal: a client "
"retries one and must not retry the other the same way"
)
- assert "active session limit (2/2)" in str(refusal)
def test_capacity_and_exclusivity_are_not_the_same_switch():
@@ -219,6 +217,3 @@ def test_the_same_live_session_may_re_acquire_its_own_lease():
assert refusal.reason == SESSION_NOT_OWNED
-def test_the_capability_is_advertised_because_the_check_exists():
- """The flag lives beside the enforcement, so it cannot drift from it."""
- assert PER_SESSION_EXCLUSIVE_SUBMIT is True
diff --git a/tests/hermes_cli/test_active_sessions.py b/tests/hermes_cli/test_active_sessions.py
index 6bd1e51a972..b99f4fca2b5 100644
--- a/tests/hermes_cli/test_active_sessions.py
+++ b/tests/hermes_cli/test_active_sessions.py
@@ -1,10 +1,8 @@
-import logging
import os
import subprocess
import sys
import threading
import time
-from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pytest
@@ -23,7 +21,7 @@ def _backdate_leases(*homes, age_seconds=600.0):
active_sessions._write_entries(state_path, entries)
-def test_resolve_max_concurrent_sessions_values(caplog):
+def test_resolve_max_concurrent_sessions_values():
assert active_sessions.resolve_max_concurrent_sessions({}) is None
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": None}) is None
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": 0}) is None
@@ -42,12 +40,7 @@ def test_resolve_max_concurrent_sessions_values(caplog):
== 2
)
- caplog.set_level(logging.WARNING)
assert active_sessions.resolve_max_concurrent_sessions({"max_concurrent_sessions": "many"}) is None
- assert any(
- "Ignoring invalid max_concurrent_sessions='many'" in record.message
- for record in caplog.records
- )
diff --git a/tests/hermes_cli/test_actual_provider.py b/tests/hermes_cli/test_actual_provider.py
index 5c16d3fe524..73415160759 100644
--- a/tests/hermes_cli/test_actual_provider.py
+++ b/tests/hermes_cli/test_actual_provider.py
@@ -23,7 +23,6 @@ from hermes_cli.auth import (
from hermes_cli.models import normalize_provider as normalize_model_provider
from hermes_cli.models import provider_model_ids
from hermes_cli.providers import determine_api_mode
-from hermes_cli.providers import get_label
from hermes_cli.providers import normalize_provider as normalize_overlay_provider
from providers import get_provider_profile
@@ -39,7 +38,6 @@ def test_actual_aliases_and_profile_metadata():
assert profile is not None
assert profile.name == "actual"
- assert profile.display_name == "Actual Computer"
assert profile.base_url == DEFAULT_ACTUAL_BASE_URL
assert profile.api_mode == "chat_completions"
assert profile.auth_type == "api_key"
@@ -48,7 +46,6 @@ def test_actual_aliases_and_profile_metadata():
assert normalize_model_provider("actualcomputer") == "actual"
assert resolve_provider("actual-computer") == "actual"
assert _normalize_aux_provider("aci") == "actual"
- assert get_label("actual") == "Actual Computer"
assert determine_api_mode("actual", "https://api.actual.inc") == "chat_completions"
@@ -141,7 +138,6 @@ def test_actual_runtime_repairs_stale_responses_mode(monkeypatch, caplog):
assert resolved["api_mode"] == "chat_completions"
assert explicit["api_mode"] == "chat_completions"
- assert "persisted api_mode=codex_responses" in caplog.text
def test_actual_runtime_ignores_legacy_mode_environment(monkeypatch):
@@ -541,36 +537,6 @@ def test_actual_oneshot_reasoning_override_reaches_agent(monkeypatch):
assert captured["reasoning_config"] == {"enabled": True, "effort": "ultra"}
-def test_oneshot_dispatch_forwards_reasoning_override(monkeypatch):
- from hermes_cli import main as main_mod
- from hermes_cli import oneshot
-
- captured = {}
-
- def fake_run_oneshot(prompt, **kwargs):
- captured["prompt"] = prompt
- captured.update(kwargs)
- return 0
-
- class OneshotExit(Exception):
- pass
-
- def fake_exit(_rc):
- raise OneshotExit
-
- monkeypatch.setattr(oneshot, "run_oneshot", fake_run_oneshot)
- monkeypatch.setattr(main_mod, "_cleanup_oneshot_runtime", lambda: None)
- monkeypatch.setattr(main_mod, "_exit_after_oneshot", fake_exit)
-
- with pytest.raises(OneshotExit):
- main_mod._run_and_exit_oneshot(
- "hello",
- model="zai-org/GLM-5.3",
- provider="actual",
- reasoning="high",
- )
-
- assert captured["reasoning"] == "high"
def test_actual_agent_side_routing_keeps_chat_completions_for_any_model():
@@ -605,28 +571,6 @@ def test_actual_agent_init_repairs_stale_responses_mode():
assert agent.api_mode == "chat_completions"
-def test_actual_agent_init_ignores_legacy_mode_environment(monkeypatch):
- from run_agent import AIAgent
-
- _clear_actual_env(monkeypatch)
- monkeypatch.setenv("ACTUAL_API_MODE", "codex_responses")
- with (
- patch("model_tools.get_tool_definitions", return_value=[]),
- patch("model_tools.check_toolset_requirements", return_value={}),
- patch("agent.process_bootstrap.OpenAI"),
- ):
- agent = AIAgent(
- api_key="actual-test-key",
- base_url=DEFAULT_ACTUAL_BASE_URL,
- provider="actual",
- api_mode="chat_completions",
- model="zai-org/GLM-5.3",
- quiet_mode=True,
- skip_context_files=True,
- skip_memory=True,
- )
-
- assert agent.api_mode == "chat_completions"
def test_actual_chat_completions_wire_replays_reasoning_through_tool_turn(
@@ -810,47 +754,5 @@ def test_actual_chat_completions_wire_replays_reasoning_through_tool_turn(
assert second.reasoning_content == "The tool result confirms the answer."
-def test_actual_chat_completion_without_reasoning_keeps_final_content():
- from types import SimpleNamespace
-
- from agent.transports.chat_completions import ChatCompletionsTransport
-
- response = SimpleNamespace(
- choices=[
- SimpleNamespace(
- finish_reason="stop",
- message=SimpleNamespace(
- content="ACTUAL_NO_REASONING_OK",
- reasoning=None,
- reasoning_content=None,
- tool_calls=None,
- ),
- )
- ],
- usage=None,
- )
-
- normalized = ChatCompletionsTransport().normalize_response(response)
-
- assert normalized.content == "ACTUAL_NO_REASONING_OK"
- assert normalized.reasoning is None
- assert normalized.reasoning_content is None
-
-def test_actual_runtime_config_local_base_url_without_key(monkeypatch):
- """Config-driven loopback base_url (not just env) reaches the no-auth path."""
- _clear_actual_env(monkeypatch)
- monkeypatch.setattr(
- rp,
- "_get_model_config",
- lambda: {
- "provider": "actual",
- "base_url": "http://localhost:8080",
- "default": "actual/local-model",
- },
- )
-
- resolved = rp.resolve_runtime_provider(requested="actual")
- assert resolved["api_key"] == ACTUAL_LOCAL_NOAUTH_PLACEHOLDER
- assert resolved["api_mode"] == "chat_completions"
diff --git a/tests/hermes_cli/test_agent_env_advertisement.py b/tests/hermes_cli/test_agent_env_advertisement.py
index 58f2fc35d1f..1e4a5222a74 100644
--- a/tests/hermes_cli/test_agent_env_advertisement.py
+++ b/tests/hermes_cli/test_agent_env_advertisement.py
@@ -41,13 +41,6 @@ class TestAdvertiseAgentEnv:
assert os.environ["AI_AGENT"] == "pi"
assert os.environ["HERMES_AGENT"] == "true"
- def test_idempotent(self, monkeypatch):
- monkeypatch.delenv("AI_AGENT", raising=False)
- monkeypatch.delenv("HERMES_AGENT", raising=False)
- _advertise_agent_env()
- _advertise_agent_env()
- assert os.environ["AI_AGENT"] == HARNESS_ID
- assert os.environ["HERMES_AGENT"] == "true"
class TestWrapCommandAdvertisesHarness:
@@ -64,14 +57,7 @@ class TestWrapCommandAdvertisesHarness:
env._snapshot_passthrough_names = set()
return env._wrap_command(command, "/tmp")
- def test_wrap_command_contains_export(self):
- wrapped = self._wrap("true")
- assert 'AI_AGENT="${AI_AGENT:-' + HARNESS_ID + '}"' in wrapped
- assert 'HERMES_AGENT="${HERMES_AGENT:-true}"' in wrapped
- def test_export_precedes_user_command(self):
- wrapped = self._wrap("echo payload-sentinel")
- assert wrapped.index("AI_AGENT=") < wrapped.index("payload-sentinel")
def test_shell_sets_default_and_preserves_outer(self):
"""Run the wrapped script through real bash both ways."""
diff --git a/tests/hermes_cli/test_agent_import.py b/tests/hermes_cli/test_agent_import.py
index 51077b63389..d7df258e56c 100644
--- a/tests/hermes_cli/test_agent_import.py
+++ b/tests/hermes_cli/test_agent_import.py
@@ -23,7 +23,6 @@ from hermes_cli.agent_import import (
detect_agents,
extract_markdown_entries,
is_secret_key,
- parse_existing_memory_entries,
sanitize_mcp_env,
)
@@ -537,11 +536,6 @@ class TestExistingConfigPreserved:
items = self.items_for(report, kind)
assert items, f"no {kind} item recorded"
assert [i["status"] for i in items] == ["error"], kind
- reason = items[0]["reason"]
- assert str(config_path) in reason
- assert "not valid YAML" in reason
- # Points the user at a way out.
- assert "hermes config edit" in reason
def test_unreadable_config_is_left_byte_identical(
self, claude_tree, hermes_home, config_path):
@@ -577,8 +571,7 @@ class TestExistingConfigPreserved:
report = run_import("claude-code", claude_tree, hermes_home, execute=True)
assert config_path.read_bytes() == before
- reasons = [i["reason"] for i in self.items_for(report, "command-allowlist")]
- assert any("YAML mapping" in r for r in reasons)
+ assert [i["status"] for i in self.items_for(report, "command-allowlist")] == ["error"]
def test_dry_run_reports_the_refusal_rather_than_a_preview(
self, claude_tree, hermes_home, config_path):
@@ -679,22 +672,6 @@ class TestExistingConfigPreserved:
# ---------------------------------------------------------------------------
class TestCliWiring:
- def test_parser_builds_and_parses(self):
- import argparse
- from hermes_cli.subcommands.import_agent import build_import_agent_parser
-
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers(dest="command")
- called = {}
- build_import_agent_parser(
- subparsers, cmd_import_agent=lambda a: called.setdefault("ok", a))
- args = parser.parse_args(
- ["import-agent", "claude-code", "--dry-run", "--source", "/tmp/x"])
- assert args.agent == "claude-code"
- assert args.dry_run is True
- assert args.source == "/tmp/x"
- args.func(args)
- assert "ok" in called
def test_rejects_unknown_agent(self):
import argparse
@@ -716,9 +693,7 @@ class TestCliWiring:
agent="claude-code", source=str(claude_tree), dry_run=True,
overwrite=False, yes=False)
import_agent_command(args)
- out = capsys.readouterr().out
- assert "Dry Run Results" in out
- assert "command-allowlist" in out
+ assert "command-allowlist" in capsys.readouterr().out
# Baseline config.yaml/SOUL.md may be seeded by save_config() before
# the preview runs — but nothing from the IMPORT itself may land:
assert not (hermes_home / "memories" / "MEMORY.md").exists()
@@ -743,7 +718,7 @@ class TestSyncManifest:
dry_run=dry_run, overwrite=False, yes=True, sync=sync))
def test_import_registers_source_and_unchanged_sync_is_noop(
- self, claude_tree, hermes_home, capsys):
+ self, claude_tree, hermes_home):
from hermes_cli.agent_import_sync import load_sync_manifest
self._run_command("claude-code", claude_tree)
@@ -754,9 +729,7 @@ class TestSyncManifest:
(claude_tree / ".credentials.json").write_text(
json.dumps({"api_key": "rotated-token"}), encoding="utf-8")
before = snapshot_tree(hermes_home)
- capsys.readouterr()
self._run_command(None, None, sync=True)
- assert "unchanged since last import" in capsys.readouterr().out
assert snapshot_tree(hermes_home) == before
def test_sync_reimports_changed_source_but_never_clobbers_user_skill(
@@ -790,7 +763,7 @@ class TestSyncManifest:
self._run_command(None, None, sync=True)
assert (imports / "deploy-helper" / "SKILL.md").read_text(encoding="utf-8") == "my local tweaks"
- def test_sync_dry_run_previews_without_writing(self, claude_tree, hermes_home, capsys):
+ def test_sync_dry_run_previews_without_writing(self, claude_tree, hermes_home):
from hermes_cli.agent_import_sync import load_sync_manifest
self._run_command("claude-code", claude_tree)
@@ -798,8 +771,6 @@ class TestSyncManifest:
(claude_tree / "CLAUDE.md").write_text(
CLAUDE_MD + "\n- Dry sync entry\n", encoding="utf-8")
before = snapshot_tree(hermes_home)
- capsys.readouterr()
self._run_command(None, None, sync=True, dry_run=True)
- assert "changes detected" in capsys.readouterr().out
assert snapshot_tree(hermes_home) == before
assert load_sync_manifest(hermes_home)["agents"]["claude-code"]["digest"] == old_digest
diff --git a/tests/hermes_cli/test_anon_auth_core.py b/tests/hermes_cli/test_anon_auth_core.py
index 07f8b244a27..525f4f8f4e3 100644
--- a/tests/hermes_cli/test_anon_auth_core.py
+++ b/tests/hermes_cli/test_anon_auth_core.py
@@ -12,7 +12,6 @@ import os
import time
from pathlib import Path
-import httpx
import pytest
from hermes_cli import anon_auth
@@ -250,15 +249,12 @@ class TestModelPin:
class TestLogout:
- def test_logout_with_only_free_tier_is_a_true_noop(self, portal, capsys):
+ def test_logout_with_only_free_tier_is_a_true_noop(self, portal):
from types import SimpleNamespace
from hermes_cli.auth import _auth_file_path, logout_command
anon_auth.ensure_portal_identity(explicit=True)
before = _auth_file_path().read_bytes()
logout_command(SimpleNamespace(provider=None))
- out = capsys.readouterr().out.lower()
- assert "not signed in" in out
- assert "guest" not in out and "anonymous" not in out
assert _auth_file_path().read_bytes() == before
def test_logout_of_real_account_clears_shared_store(self, portal, tmp_path):
@@ -281,9 +277,6 @@ class TestModelSwitchCopy:
monkeypatch.setattr(model_switch, "list_provider_models", lambda *a, **k: [], raising=False)
result = model_switch.switch_model("gpt-5", "nous", anon_auth.GUEST_MODEL, WELCOME)
assert not result.success
- msg = (result.error_message or "").lower()
- assert "/login" in msg
- assert "openrouter" not in msg and "switching" not in msg
class TestRotationNeverRewritesTheConversationModel: