hermes-agent/tests/gateway/test_telegram_channel_posts.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

149 lines
4.7 KiB
Python

"""Regression tests for Telegram channel_post updates.
Telegram channel broadcasts are delivered as ``Update.channel_post`` rather than
``Update.message``. The adapter should use ``effective_message`` so channel
posts are converted into Hermes gateway events instead of being silently
ignored.
"""
import importlib
import importlib.util
import sys
import types
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from gateway.config import PlatformConfig
from gateway.platforms.base import MessageType
def _build_telegram_stubs():
telegram_mod = types.ModuleType("telegram")
telegram_mod.Update = object
telegram_mod.Bot = object
telegram_mod.Message = object
telegram_mod.InlineKeyboardButton = object
telegram_mod.InlineKeyboardMarkup = object
telegram_mod.LinkPreviewOptions = object
telegram_ext_mod = types.ModuleType("telegram.ext")
telegram_ext_mod.Application = object
telegram_ext_mod.CommandHandler = object
telegram_ext_mod.CallbackQueryHandler = object
telegram_ext_mod.MessageHandler = object
telegram_ext_mod.ContextTypes = SimpleNamespace(DEFAULT_TYPE=type(None))
telegram_ext_mod.filters = SimpleNamespace()
telegram_constants_mod = types.ModuleType("telegram.constants")
telegram_constants_mod.ParseMode = SimpleNamespace(MARKDOWN_V2="MarkdownV2")
telegram_constants_mod.ChatType = SimpleNamespace(
GROUP="group",
SUPERGROUP="supergroup",
CHANNEL="channel",
PRIVATE="private",
)
telegram_request_mod = types.ModuleType("telegram.request")
telegram_request_mod.HTTPXRequest = object
telegram_mod.ext = telegram_ext_mod
telegram_mod.constants = telegram_constants_mod
telegram_mod.request = telegram_request_mod
return {
"telegram": telegram_mod,
"telegram.ext": telegram_ext_mod,
"telegram.constants": telegram_constants_mod,
"telegram.request": telegram_request_mod,
}
@pytest.fixture
def telegram_adapter_cls(monkeypatch):
"""Import TelegramAdapter without leaking temporary telegram stubs."""
module_name = "plugins.platforms.telegram.adapter"
existing_module = sys.modules.get(module_name)
if existing_module is not None:
yield existing_module.TelegramAdapter
return
telegram_pkg = sys.modules.get("telegram")
installed = isinstance(getattr(telegram_pkg, "__file__", None), str)
if telegram_pkg is None:
try:
installed = importlib.util.find_spec("telegram") is not None
except ValueError:
installed = False
if not installed:
for name, module in _build_telegram_stubs().items():
monkeypatch.setitem(sys.modules, name, module)
module = importlib.import_module(module_name)
try:
yield module.TelegramAdapter
finally:
if not installed:
sys.modules.pop(module_name, None)
def _make_adapter(telegram_adapter_cls):
a = telegram_adapter_cls(PlatformConfig(enabled=True, token="***", extra={}))
# Channel posts have from_user=None. After PR #28494's fail-closed
# auth, the empty-allowlist adapter rejects all messages including
# channel posts. These tests focus on routing, not auth gating.
a._is_callback_user_authorized = lambda user_id, **_kw: True
return a
def _make_channel_message(text="channel id test @hermes_bot"):
chat = SimpleNamespace(
id=-1003950368353,
type="channel",
title="wzrd",
full_name=None,
is_forum=False,
)
return SimpleNamespace(
chat=chat,
from_user=None,
text=text,
caption=None,
entities=[],
caption_entities=[],
message_thread_id=None,
is_topic_message=False,
message_id=11,
reply_to_message=None,
quote=None,
date=None,
forum_topic_created=None,
)
def _make_channel_update(msg):
return SimpleNamespace(
update_id=12345,
message=None,
channel_post=msg,
effective_message=msg,
)
def test_build_message_event_uses_channel_identity_for_channel_posts(telegram_adapter_cls):
adapter = _make_adapter(telegram_adapter_cls)
msg = _make_channel_message()
event = adapter._build_message_event(msg, MessageType.TEXT, update_id=12345)
assert event.source.chat_type == "channel"
assert event.source.chat_id == "-1003950368353"
# Channel posts often have no from_user. Preserve an identity so the
# gateway authorization layer can allowlist the channel by numeric ID.
assert event.source.user_id == "-1003950368353"
assert event.source.user_name == "wzrd"
assert event.platform_update_id == 12345