hermes-agent/tests/tools/test_slack_send_message_media.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

176 lines
5.4 KiB
Python

"""Slack media delivery for send_message.
Covers ``plugins/platforms/slack/adapter.py::_standalone_send`` media path:
text+file, media-only, caption-on-upload, missing-file warnings.
``slack_sdk`` is optional in CI, so tests inject a fake module into
``sys.modules`` (same pattern as ``tests/gateway/test_slack.py``).
"""
from __future__ import annotations
import asyncio
import contextlib
import os
import sys
import tempfile
from types import ModuleType, SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from plugins.platforms.slack.adapter import _standalone_send
def _pconfig(token: str = "xoxb-test"):
return SimpleNamespace(token=token, extra={})
def _tmpfile(suffix: str) -> str:
f = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
f.write(b"%PDF-1.4 test")
f.close()
return f.name
def _mock_client(*, post_ok=True, upload_ok=True):
client = MagicMock()
client.chat_postMessage = AsyncMock(
return_value={
"ok": post_ok,
"ts": "111.222",
"error": None if post_ok else "channel_not_found",
}
)
if upload_ok:
client.files_upload_v2 = AsyncMock(
return_value={
"ok": True,
"file": {
"id": "F123",
"timestamp": 1234567890,
"shares": {"public": {"C012AB3CD": [{"ts": "333.444"}]}},
},
}
)
else:
client.files_upload_v2 = AsyncMock(
return_value={"ok": False, "error": "not_in_channel"}
)
return client
@contextlib.contextmanager
def _fake_slack_sdk(client):
"""Make ``from slack_sdk.web.async_client import AsyncWebClient`` resolve to a factory."""
sdk = ModuleType("slack_sdk")
web = ModuleType("slack_sdk.web")
async_client = ModuleType("slack_sdk.web.async_client")
async_client.AsyncWebClient = MagicMock(return_value=client)
sdk.web = web
web.async_client = async_client
modules = {
"slack_sdk": sdk,
"slack_sdk.web": web,
"slack_sdk.web.async_client": async_client,
}
old = {name: sys.modules.get(name) for name in modules}
sys.modules.update(modules)
try:
yield
finally:
for name, prev in old.items():
if prev is None:
sys.modules.pop(name, None)
else:
sys.modules[name] = prev
def test_text_plus_pdf_uploads_via_files_upload_v2():
pdf = _tmpfile(".pdf")
client = _mock_client()
try:
with _fake_slack_sdk(client):
result = asyncio.run(
_standalone_send(
_pconfig(),
"C012AB3CD",
"Here is the report",
media_files=[(pdf, False)],
)
)
assert result["success"] is True
assert result["platform"] == "slack"
client.chat_postMessage.assert_awaited_once()
client.files_upload_v2.assert_awaited_once()
upload_kwargs = client.files_upload_v2.await_args.kwargs
assert upload_kwargs["channel"] == "C012AB3CD"
assert upload_kwargs["file"] == pdf
assert upload_kwargs["filename"] == os.path.basename(pdf)
assert upload_kwargs["initial_comment"] == ""
finally:
os.unlink(pdf)
def test_media_only_skips_text_post():
pdf = _tmpfile(".pdf")
client = _mock_client()
try:
with _fake_slack_sdk(client):
result = asyncio.run(
_standalone_send(
_pconfig(),
"C012AB3CD",
"",
media_files=[(pdf, False)],
)
)
assert result["success"] is True
client.chat_postMessage.assert_not_awaited()
client.files_upload_v2.assert_awaited_once()
finally:
os.unlink(pdf)
def test_send_to_platform_routes_slack_media():
"""_send_to_platform must call Slack standalone_sender with media_files."""
import httpx
if not hasattr(httpx, "Proxy") or not hasattr(httpx, "URL"):
pytest.skip("httpx type annotations incompatible with telegram library")
from gateway.config import Platform
from hermes_cli.plugins import discover_plugins
from gateway.platform_registry import platform_registry
from tools.send_message_tool import _send_to_platform
pdf = _tmpfile(".pdf")
discover_plugins()
entry = platform_registry.get("slack")
assert entry is not None and entry.standalone_sender_fn is not None
original = entry.standalone_sender_fn
mock_sender = AsyncMock(
return_value={"success": True, "platform": "slack", "message_id": "1.2"}
)
entry.standalone_sender_fn = mock_sender
try:
result = asyncio.run(
_send_to_platform(
Platform.SLACK,
_pconfig(),
"C012AB3CD",
"Here is the report",
media_files=[(pdf, False)],
)
)
assert result["success"] is True
mock_sender.assert_awaited()
call_kwargs = mock_sender.await_args.kwargs
assert call_kwargs.get("media_files") == [(pdf, False)]
# Single captionable file + short text → caption rides the upload.
assert call_kwargs.get("caption") == "Here is the report"
assert not result.get("warnings")
finally:
entry.standalone_sender_fn = original
os.unlink(pdf)