mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-07-30 19:09:28 +00:00
Second, deeper pass over tools/gateway/hermes_cli plus first pass over the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker, dashboard, conformance, monitoring, secret_sources, hermes_state, providers). Same rubric as wave 1 (AGENTS.md test policy); security, alternation/caching invariants, issue-number regressions, and E2E kept. Real test-quality fixes found and rooted out along the way: - tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls (DEFAULT_CONFIG smart-approval leaked in) — pinned approval mode=manual via autouse fixture: 17.4s → 0.4s. - test_model_switch_custom_providers.py / test_user_providers_model_switch.py silently probed live provider catalogs (~2s/test) — stubbed cached_provider_model_ids/provider_model_ids/fetch_api_models. - test_telegram_noise_filter.py: 15-platform copy-paste matrix over shared gateway.run logic → 3 representative platforms (55s → 3.9s). - test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on MagicMock agents — interrupt.side_effect now clears _running_agents (22s → 1.0s). - test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait 5s → 0.5s. - test_telegram_init_deadline.py: loop-block margin restored to 1.0s with rationale comment — the watchdog-dump assertion needs the loop blocked well past deadline+grace under parallel load (flaked once in the 40-worker verification run at a 0.2s margin). Verification: full hermetic suite via scripts/run_tests.sh — 2,438 files, 21,718 tests passed, 0 failed, 293.9s wall. Suite totals vs original baseline: 46,820 → 19,757 test functions (−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
161 lines
5.9 KiB
Python
161 lines
5.9 KiB
Python
"""Tests for Telegram text message aggregation.
|
|
|
|
When a user sends a long message, Telegram clients split it into multiple
|
|
updates. The TelegramAdapter should buffer rapid successive text messages
|
|
from the same session and aggregate them before dispatching.
|
|
"""
|
|
|
|
import asyncio
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
|
|
from gateway.config import Platform, PlatformConfig
|
|
from gateway.platforms.base import MessageEvent, MessageType, SessionSource
|
|
from gateway.session import build_session_key
|
|
|
|
|
|
def _make_adapter():
|
|
"""Create a minimal TelegramAdapter for testing text batching."""
|
|
from plugins.platforms.telegram.adapter import TelegramAdapter
|
|
|
|
config = PlatformConfig(enabled=True, token="test-token")
|
|
adapter = object.__new__(TelegramAdapter)
|
|
adapter._platform = Platform.TELEGRAM
|
|
adapter.platform = Platform.TELEGRAM
|
|
adapter.config = config
|
|
adapter._running = True
|
|
adapter._fatal_error_code = None
|
|
adapter._fatal_error_message = None
|
|
adapter._fatal_error_retryable = True
|
|
adapter._drop_delayed_deliveries = False
|
|
adapter._pending_text_batches = {}
|
|
adapter._pending_text_batch_tasks = {}
|
|
adapter._pending_photo_batches = {}
|
|
adapter._pending_photo_batch_tasks = {}
|
|
adapter._media_group_events = {}
|
|
adapter._media_group_tasks = {}
|
|
adapter._polling_error_task = None
|
|
adapter._polling_heartbeat_task = None
|
|
adapter._app = None
|
|
adapter._bot = None
|
|
adapter._set_status_indicator = AsyncMock()
|
|
adapter._release_platform_lock = lambda: None
|
|
adapter._text_batch_delay_seconds = 0.1 # fast for tests
|
|
adapter._active_sessions = {}
|
|
adapter._pending_messages = {}
|
|
adapter._message_handler = AsyncMock()
|
|
adapter.handle_message = AsyncMock()
|
|
return adapter
|
|
|
|
|
|
def _make_event(text: str, chat_id: str = "12345") -> MessageEvent:
|
|
return MessageEvent(
|
|
text=text,
|
|
message_type=MessageType.TEXT,
|
|
source=SessionSource(platform=Platform.TELEGRAM, chat_id=chat_id, chat_type="dm"),
|
|
)
|
|
|
|
|
|
class TestTextBatching:
|
|
@pytest.mark.asyncio
|
|
async def test_single_message_dispatched_after_delay(self):
|
|
adapter = _make_adapter()
|
|
event = _make_event("hello world")
|
|
|
|
adapter._enqueue_text_event(event)
|
|
|
|
# Not dispatched yet
|
|
adapter.handle_message.assert_not_called()
|
|
|
|
# Wait for flush
|
|
await asyncio.sleep(0.2)
|
|
|
|
adapter.handle_message.assert_called_once()
|
|
dispatched = adapter.handle_message.call_args[0][0]
|
|
assert dispatched.text == "hello world"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_split_messages_aggregated(self):
|
|
"""Two rapid messages from the same chat should be merged."""
|
|
adapter = _make_adapter()
|
|
|
|
adapter._enqueue_text_event(_make_event("This is part one of a long"))
|
|
await asyncio.sleep(0.02) # small gap, within batch window
|
|
adapter._enqueue_text_event(_make_event("message that was split by Telegram."))
|
|
|
|
# Not dispatched yet (timer restarted)
|
|
adapter.handle_message.assert_not_called()
|
|
|
|
# Wait for flush
|
|
await asyncio.sleep(0.2)
|
|
|
|
adapter.handle_message.assert_called_once()
|
|
dispatched = adapter.handle_message.call_args[0][0]
|
|
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
|
|
async def test_disconnected_adapter_drops_pending_media_group_flush_before_dispatch(self):
|
|
"""A pending media group should not dispatch after disconnect starts."""
|
|
from plugins.platforms.telegram.adapter import TelegramAdapter
|
|
|
|
adapter = _make_adapter()
|
|
event = _make_event("album caption")
|
|
event.media_urls = ["/tmp/photo.jpg"]
|
|
event.media_types = ["image/jpeg"]
|
|
|
|
with patch.object(TelegramAdapter, "MEDIA_GROUP_WAIT_SECONDS", 0.1):
|
|
await adapter._queue_media_group_event("album-1", event)
|
|
adapter._mark_disconnected()
|
|
await asyncio.sleep(0.2)
|
|
|
|
adapter.handle_message.assert_not_called()
|
|
assert adapter._media_group_events == {}
|
|
assert adapter._media_group_tasks == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_disconnect_cancels_all_pending_delivery_task_maps(self):
|
|
"""Photo/media/polling delayed tasks are awaited and queues are cleared."""
|
|
adapter = _make_adapter()
|
|
tasks = [asyncio.create_task(asyncio.sleep(0.2)) for _ in range(4)]
|
|
adapter._pending_text_batches["text"] = _make_event("text")
|
|
adapter._pending_text_batch_tasks["text"] = tasks[0]
|
|
adapter._pending_photo_batches["photo"] = _make_event("photo")
|
|
adapter._pending_photo_batch_tasks["photo"] = tasks[1]
|
|
adapter._media_group_events["media"] = _make_event("media")
|
|
adapter._media_group_tasks["media"] = tasks[2]
|
|
adapter._polling_error_task = tasks[3]
|
|
|
|
await adapter.disconnect()
|
|
|
|
assert all(task.done() for task in tasks)
|
|
assert adapter._pending_text_batches == {}
|
|
assert adapter._pending_text_batch_tasks == {}
|
|
assert adapter._pending_photo_batches == {}
|
|
assert adapter._pending_photo_batch_tasks == {}
|
|
assert adapter._media_group_events == {}
|
|
assert adapter._media_group_tasks == {}
|
|
assert adapter._polling_error_task is None
|