hermes-agent/tests/hermes_cli/test_telegram_managed_bot.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

237 lines
7.8 KiB
Python

"""Tests for hermes_cli.telegram_managed_bot — QR codes, deep links, pairing."""
from __future__ import annotations
from pathlib import PureWindowsPath
from unittest.mock import MagicMock, patch
from hermes_cli.telegram_managed_bot import (
DEFAULT_MANAGER_BOT,
TELEGRAM_ONBOARDING_URL_ENV,
TelegramBotSetupResult,
TelegramPairing,
create_pairing,
generate_bot_username,
generate_deep_link,
generate_pairing_nonce,
poll_for_setup_result,
poll_for_token,
print_qr_code,
render_qr_terminal,
)
VALID_TOKEN = "123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"
SECOND_VALID_TOKEN = "987654321:abcdefghijklmnopqrstuvwxyzABCDEF"
class TestGenerateBotUsername:
def test_secure_default_format(self):
name = generate_bot_username()
assert name.startswith("hermes_")
assert name.endswith("_bot")
assert len(name) == len("hermes_") + 16 + len("_bot")
assert len(name) <= 32
def test_uniqueness(self):
names = {generate_bot_username() for _ in range(20)}
assert len(names) == 20
class TestGenerateDeepLink:
def test_basic_format(self):
link = generate_deep_link(
manager_bot="TestBot",
suggested_username="my_bot",
)
assert link == "https://t.me/newbot/TestBot/my_bot"
def test_name_url_encoded(self):
link = generate_deep_link(
manager_bot="Bot",
suggested_username="test_bot",
suggested_name="Hermes & Friends",
)
assert "Hermes+%26+Friends" in link
class TestPairingNonce:
def test_hex_chars(self):
nonce = generate_pairing_nonce()
assert all(c in "0123456789abcdef" for c in nonce)
class TestQRCode:
def test_render_returns_string(self):
result = render_qr_terminal("https://example.com")
if result:
assert isinstance(result, str)
assert len(result) > 10
def test_render_graceful_without_qrcode(self):
with patch.dict("sys.modules", {"qrcode": None}):
render_qr_terminal("https://example.com")
def test_print_qr_code_with_url(self, capsys):
print_qr_code("https://t.me/newbot/Bot/test_bot")
captured = capsys.readouterr()
assert "https://t.me/newbot/Bot/test_bot" in captured.out
class TestCreatePairing:
def test_success(self):
mock_resp = MagicMock()
mock_resp.status_code = 201
mock_resp.json.return_value = {
"pairing_id": "abcdefghijklmnop",
"poll_token": "secret-token",
"suggested_username": "hermes_abcdefghijklmnop_bot",
"deep_link": "https://t.me/newbot/HermesSetupBot/hermes_abcdefghijklmnop_bot?name=Hermes+Agent",
"qr_payload": "https://t.me/newbot/HermesSetupBot/hermes_abcdefghijklmnop_bot?name=Hermes+Agent",
"expires_at": "2026-05-18T00:00:00.000Z",
}
with patch(
"hermes_cli.telegram_managed_bot.httpx.post", return_value=mock_resp
) as post:
pairing = create_pairing("https://api.example.com", bot_name="Hermes Agent")
assert pairing == TelegramPairing(
pairing_id="abcdefghijklmnop",
poll_token="secret-token",
suggested_username="hermes_abcdefghijklmnop_bot",
deep_link="https://t.me/newbot/HermesSetupBot/hermes_abcdefghijklmnop_bot?name=Hermes+Agent",
qr_payload="https://t.me/newbot/HermesSetupBot/hermes_abcdefghijklmnop_bot?name=Hermes+Agent",
expires_at="2026-05-18T00:00:00.000Z",
)
post.assert_called_once_with(
"https://api.example.com/v1/telegram/pairings",
json={"bot_name": "Hermes Agent"},
timeout=10.0,
)
def test_failure_status(self):
mock_resp = MagicMock()
mock_resp.status_code = 500
with patch(
"hermes_cli.telegram_managed_bot.httpx.post", return_value=mock_resp
):
assert create_pairing("https://api.example.com") is None
def test_uses_env_override(self, monkeypatch):
monkeypatch.setenv(TELEGRAM_ONBOARDING_URL_ENV, "https://worker.example")
mock_resp = MagicMock()
mock_resp.status_code = 500
with patch(
"hermes_cli.telegram_managed_bot.httpx.post", return_value=mock_resp
) as post:
create_pairing()
assert post.call_args.args[0] == "https://worker.example/v1/telegram/pairings"
class TestPollForToken:
def pairing(self):
return TelegramPairing(
pairing_id="abcdefghijklmnop",
poll_token="secret-token",
suggested_username="hermes_abcdefghijklmnop_bot",
deep_link="https://t.me/newbot/HermesSetupBot/hermes_abcdefghijklmnop_bot",
qr_payload="https://t.me/newbot/HermesSetupBot/hermes_abcdefghijklmnop_bot",
)
def test_immediate_success(self):
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.json.return_value = {
"bot_username": "hermes_abcdefghijklmnop_bot",
"owner_user_id": 42,
"status": "ready",
"token": VALID_TOKEN,
}
with patch(
"hermes_cli.telegram_managed_bot.httpx.get", return_value=mock_resp
) as get:
with patch("hermes_cli.telegram_managed_bot.time.sleep"):
token = poll_for_token(
"https://api.example.com", self.pairing(), timeout=5
)
assert token == VALID_TOKEN
assert (
get.call_args.args[0]
== "https://api.example.com/v1/telegram/pairings/abcdefghijklmnop"
)
assert get.call_args.kwargs["headers"] == {
"Authorization": "Bearer secret-token"
}
def test_eventual_success(self):
not_ready = MagicMock()
not_ready.status_code = 200
not_ready.json.return_value = {"status": "waiting"}
ready = MagicMock()
ready.status_code = 200
ready.json.return_value = {"status": "ready", "token": SECOND_VALID_TOKEN}
call_count = 0
def fake_get(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count < 3:
return not_ready
return ready
with patch("hermes_cli.telegram_managed_bot.httpx.get", side_effect=fake_get):
with patch("hermes_cli.telegram_managed_bot.time.sleep"):
token = poll_for_token(
"https://api.example.com", self.pairing(), timeout=30
)
assert token == SECOND_VALID_TOKEN
class TestSetupTelegramAuto:
def test_setup_helper_exists(self):
from hermes_cli.setup import _setup_telegram_auto
assert callable(_setup_telegram_auto)
def test_setup_result_passes_profile_name_for_profile_home(self, monkeypatch, tmp_path):
from hermes_cli import setup
seen = {}
profile_home = tmp_path / ".hermes" / "profiles" / "oracle"
profile_home.mkdir(parents=True)
monkeypatch.setattr(setup, "get_hermes_home", lambda: profile_home)
def fake_auto_setup_telegram_bot_result(*, profile_name=None):
seen["profile_name"] = profile_name
return None
monkeypatch.setattr(
"hermes_cli.telegram_managed_bot.auto_setup_telegram_bot_result",
fake_auto_setup_telegram_bot_result,
)
assert setup._setup_telegram_auto_result() is None
assert seen["profile_name"] == "oracle"
def test_profile_name_from_home_path_handles_windows_separators(self):
from hermes_cli.setup import _profile_name_from_hermes_home
assert (
_profile_name_from_hermes_home(
PureWindowsPath(r"C:\Users\test\AppData\Local\hermes\profiles\oracle")
)
== "oracle"
)