mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-07-31 19:16:29 +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.
231 lines
8.3 KiB
Python
231 lines
8.3 KiB
Python
"""Tests for WhatsApp message formatting and chunking.
|
|
|
|
Covers:
|
|
- format_message(): markdown → WhatsApp syntax conversion
|
|
- send(): message chunking for long responses
|
|
- MAX_MESSAGE_LENGTH: practical UX limit
|
|
"""
|
|
|
|
import asyncio
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
|
|
from gateway.config import Platform
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _whatsapp_open_optin(monkeypatch):
|
|
"""Opt into WhatsApp allow-all so ``dm_policy: open`` dispatch tests run.
|
|
|
|
The adapter fails closed on ``open`` without an allow-all opt-in
|
|
(SECURITY.md 2.6); these formatting/dispatch-mechanics tests set
|
|
``_dm_policy = "open"`` as a stand-in for "process this DM".
|
|
"""
|
|
monkeypatch.setenv("WHATSAPP_ALLOW_ALL_USERS", "true")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _make_adapter():
|
|
"""Create a WhatsAppAdapter with test attributes (bypass __init__)."""
|
|
from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
|
|
|
|
adapter = WhatsAppAdapter.__new__(WhatsAppAdapter)
|
|
adapter.platform = Platform.WHATSAPP
|
|
adapter.config = MagicMock()
|
|
adapter.config.extra = {}
|
|
adapter._bridge_port = 3000
|
|
adapter._bridge_script = "/tmp/test-bridge.js"
|
|
adapter._session_path = MagicMock()
|
|
adapter._bridge_log_fh = None
|
|
adapter._bridge_log = None
|
|
adapter._bridge_process = None
|
|
adapter._reply_prefix = None
|
|
adapter._running = True
|
|
adapter._message_handler = None
|
|
adapter._fatal_error_code = None
|
|
adapter._fatal_error_message = None
|
|
adapter._fatal_error_retryable = True
|
|
adapter._fatal_error_handler = None
|
|
adapter._active_sessions = {}
|
|
adapter._pending_messages = {}
|
|
adapter._background_tasks = set()
|
|
adapter._auto_tts_disabled_chats = set()
|
|
adapter._message_queue = asyncio.Queue()
|
|
adapter._http_session = MagicMock()
|
|
adapter._mention_patterns = []
|
|
adapter._dm_policy = "open"
|
|
adapter._allow_from = set()
|
|
adapter._group_policy = "open"
|
|
adapter._group_allow_from = set()
|
|
return adapter
|
|
|
|
|
|
class _AsyncCM:
|
|
"""Minimal async context manager returning a fixed value."""
|
|
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
async def __aenter__(self):
|
|
return self.value
|
|
|
|
async def __aexit__(self, *exc):
|
|
return False
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# format_message tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestFormatMessage:
|
|
"""WhatsApp markdown conversion."""
|
|
|
|
|
|
def test_strikethrough(self):
|
|
adapter = _make_adapter()
|
|
assert adapter.format_message("~~deleted~~") == "~deleted~"
|
|
|
|
def test_headers_converted_to_bold(self):
|
|
adapter = _make_adapter()
|
|
assert adapter.format_message("# Title") == "*Title*"
|
|
assert adapter.format_message("## Subtitle") == "*Subtitle*"
|
|
assert adapter.format_message("### Deep") == "*Deep*"
|
|
|
|
def test_bold_header_does_not_double_wrap(self):
|
|
""""# **Title**" must become *Title*, not **Title** (WhatsApp would
|
|
render the doubled asterisks literally)."""
|
|
adapter = _make_adapter()
|
|
assert adapter.format_message("# **Title**") == "*Title*"
|
|
assert adapter.format_message("## __Strong__") == "*Strong*"
|
|
|
|
|
|
def test_already_whatsapp_italic(self):
|
|
"""Markdown *italic* converts to WhatsApp _italic_ (PR #58704)."""
|
|
adapter = _make_adapter()
|
|
assert adapter.format_message("*italic*") == "_italic_"
|
|
# Already-WhatsApp _italic_ passes through unchanged
|
|
assert adapter.format_message("_italic_") == "_italic_"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# MAX_MESSAGE_LENGTH tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestMessageLimits:
|
|
"""WhatsApp message length limits."""
|
|
|
|
|
|
def test_chunk_limit_reserves_default_self_chat_prefix(self, monkeypatch):
|
|
adapter = _make_adapter()
|
|
monkeypatch.delenv("WHATSAPP_REPLY_PREFIX", raising=False)
|
|
monkeypatch.setenv("WHATSAPP_MODE", "self-chat")
|
|
|
|
assert adapter._outgoing_chunk_limit() == (
|
|
adapter.MAX_MESSAGE_LENGTH - len(adapter.DEFAULT_REPLY_PREFIX)
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# send() chunking tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestSendChunking:
|
|
"""WhatsApp send() splits long messages into chunks."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_short_message_single_send(self):
|
|
adapter = _make_adapter()
|
|
resp = MagicMock(status=200)
|
|
resp.json = AsyncMock(return_value={"messageId": "msg1"})
|
|
adapter._http_session.post = MagicMock(return_value=_AsyncCM(resp))
|
|
|
|
result = await adapter.send("chat1", "short message")
|
|
assert result.success
|
|
# Only one call to bridge /send
|
|
assert adapter._http_session.post.call_count == 1
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_long_message_chunked(self):
|
|
adapter = _make_adapter()
|
|
resp = MagicMock(status=200)
|
|
resp.json = AsyncMock(return_value={"messageId": "msg1"})
|
|
adapter._http_session.post = MagicMock(return_value=_AsyncCM(resp))
|
|
|
|
# Create a message longer than MAX_MESSAGE_LENGTH (4096)
|
|
long_msg = "a " * 3000 # ~6000 chars
|
|
|
|
result = await adapter.send("chat1", long_msg)
|
|
assert result.success
|
|
# Should have made multiple calls
|
|
assert adapter._http_session.post.call_count > 1
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_chunks_leave_room_for_bridge_prefix(self, monkeypatch):
|
|
adapter = _make_adapter()
|
|
monkeypatch.delenv("WHATSAPP_REPLY_PREFIX", raising=False)
|
|
monkeypatch.setenv("WHATSAPP_MODE", "self-chat")
|
|
resp = MagicMock(status=200)
|
|
resp.json = AsyncMock(return_value={"messageId": "msg1"})
|
|
adapter._http_session.post = MagicMock(return_value=_AsyncCM(resp))
|
|
|
|
long_msg = "a " * 3000
|
|
|
|
await adapter.send("chat1", long_msg)
|
|
|
|
for call in adapter._http_session.post.call_args_list:
|
|
payload = call.kwargs.get("json") or call[1].get("json")
|
|
final_text = adapter.DEFAULT_REPLY_PREFIX + payload["message"]
|
|
assert len(final_text) <= adapter.MAX_MESSAGE_LENGTH
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# bridge event metadata
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestBridgeEventMetadata:
|
|
"""WhatsApp bridge metadata is preserved for downstream consumers."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_quoted_reply_metadata_is_preserved_in_raw_message(self):
|
|
adapter = _make_adapter()
|
|
data = {
|
|
"messageId": "incoming-msg",
|
|
"chatId": "15551234567@s.whatsapp.net",
|
|
"senderId": "15551234567@s.whatsapp.net",
|
|
"senderName": "Tester",
|
|
"chatName": "Tester",
|
|
"isGroup": False,
|
|
"body": "approved",
|
|
"hasMedia": False,
|
|
"mediaUrls": [],
|
|
"quotedMessageId": "outbound-msg",
|
|
"quotedParticipant": "99999999999@s.whatsapp.net",
|
|
"quotedRemoteJid": "15551234567@s.whatsapp.net",
|
|
"hasQuotedMessage": True,
|
|
}
|
|
|
|
event = await adapter._build_message_event(data)
|
|
|
|
assert event is not None
|
|
assert event.raw_message["quotedMessageId"] == "outbound-msg"
|
|
assert event.raw_message["quotedParticipant"] == "99999999999@s.whatsapp.net"
|
|
assert event.raw_message["quotedRemoteJid"] == "15551234567@s.whatsapp.net"
|
|
assert event.raw_message["hasQuotedMessage"] is True
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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
|
|
|