hermes-agent/tests/tools/test_send_message_slack.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
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.
2026-07-29 13:39:40 -07:00

139 lines
4.5 KiB
Python

"""Slack-specific send_message delivery regressions.
Salvaged from #47547 and adapted to the post-#41112 plugin layout: the legacy
``_send_slack`` helper moved to ``plugins/platforms/slack/adapter.py::
_standalone_send`` and text sends now route through ``_send_via_adapter``
(live adapter first, registry standalone fallback).
"""
import asyncio
import sys
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from gateway.config import Platform
from tools.send_message_tool import _send_to_platform
def _ensure_slack_mock(monkeypatch):
"""Install lightweight Slack modules when optional Slack deps are absent."""
if "slack_bolt" in sys.modules and hasattr(sys.modules["slack_bolt"], "__file__"):
return
slack_bolt = MagicMock()
slack_bolt.async_app.AsyncApp = MagicMock
slack_bolt.adapter.socket_mode.async_handler.AsyncSocketModeHandler = MagicMock
slack_sdk = MagicMock()
slack_sdk.web.async_client.AsyncWebClient = MagicMock
for name, mod in [
("slack_bolt", slack_bolt),
("slack_bolt.async_app", slack_bolt.async_app),
("slack_bolt.adapter", slack_bolt.adapter),
("slack_bolt.adapter.socket_mode", slack_bolt.adapter.socket_mode),
("slack_bolt.adapter.socket_mode.async_handler", slack_bolt.adapter.socket_mode.async_handler),
("slack_sdk", slack_sdk),
("slack_sdk.web", slack_sdk.web),
("slack_sdk.web.async_client", slack_sdk.web.async_client),
]:
monkeypatch.setitem(sys.modules, name, mod)
def test_slack_send_to_platform_routes_through_send_via_adapter(monkeypatch):
"""Slack text sends go through _send_via_adapter (live adapter first)."""
_ensure_slack_mock(monkeypatch)
live_send = AsyncMock(return_value={"success": True, "message_id": "live-ts"})
with patch("tools.send_message_tool._send_via_adapter", live_send):
result = asyncio.run(
_send_to_platform(
Platform.SLACK,
SimpleNamespace(enabled=True, token="bad-token,good-token", extra={}),
"C123",
"**hello** from Hermes",
thread_id="171.1",
)
)
assert result == {"success": True, "message_id": "live-ts"}
live_send.assert_awaited_once()
call = live_send.await_args
assert call.args[0] == Platform.SLACK
assert call.args[2] == "C123"
assert call.kwargs["thread_id"] == "171.1"
class _SlackResponse:
def __init__(self, payload):
self._payload = payload
async def json(self):
return self._payload
class _SlackPostContext:
def __init__(self, response):
self._response = response
async def __aenter__(self):
return self._response
async def __aexit__(self, exc_type, exc, tb):
return False
class _SlackSession:
"""Fake aiohttp session whose good-token posts succeed."""
def __init__(self):
self.calls = []
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
return False
def post(self, url, *, headers, json, **kwargs):
token = headers["Authorization"].removeprefix("Bearer ")
self.calls.append((token, json))
if token == "good-token":
payload = {"ok": True, "ts": "171.123"}
else:
payload = {"ok": False, "error": "invalid_auth"}
return _SlackPostContext(_SlackResponse(payload))
@pytest.fixture
def _standalone_send(monkeypatch):
_ensure_slack_mock(monkeypatch)
from plugins.platforms.slack import adapter as slack_adapter
return slack_adapter._standalone_send
def test_standalone_send_stops_on_non_token_error(monkeypatch, _standalone_send):
"""Terminal errors (not token-scoped) must not burn the remaining tokens."""
class _FatalSession(_SlackSession):
def post(self, url, *, headers, json, **kwargs):
token = headers["Authorization"].removeprefix("Bearer ")
self.calls.append((token, json))
return _SlackPostContext(
_SlackResponse({"ok": False, "error": "msg_too_long"})
)
fake_session = _FatalSession()
monkeypatch.setattr(
"aiohttp.ClientSession", lambda *args, **kwargs: fake_session
)
pconfig = SimpleNamespace(enabled=True, token="tok-a,tok-b", extra={})
result = asyncio.run(_standalone_send(pconfig, "C123", "hello"))
assert result == {"error": "Slack API error: msg_too_long"}
assert len(fake_session.calls) == 1