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

88 lines
3.1 KiB
Python

"""Tests for the `log` tool_progress mode (salvage of #3459 / #3458).
`display.tool_progress: log` keeps the chat silent and appends tool-call
lines to ~/.hermes/logs/tool_calls.log via write_tool_log's rotating handler.
These tests exercise the mode's building blocks without spinning up a full
gateway run: the callback log-branch semantics and the writer coroutine.
"""
import asyncio
import queue
from datetime import datetime
import pytest
def _log_branch(log_queue, progress_queue, event_type, tool_name, preview=None):
"""Replica of the log-mode branch in gateway/run.py progress_callback."""
if log_queue is not None:
if event_type == "tool.started" and tool_name and tool_name != "_thinking":
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
preview_str = f' "{preview}"' if preview else ""
log_queue.put(f"{ts} {tool_name}:{preview_str}".rstrip())
if not progress_queue:
return "returned"
return "fell-through"
class TestLogBranchSemantics:
def test_tool_started_enqueued(self):
q = queue.Queue()
assert _log_branch(q, None, "tool.started", "terminal", "ls -la") == "returned"
line = q.get_nowait()
assert "terminal" in line and "ls -la" in line
def test_thinking_not_enqueued(self):
q = queue.Queue()
_log_branch(q, None, "tool.started", "_thinking", "pondering")
assert q.empty()
@pytest.mark.asyncio
async def test_write_tool_log_writes_and_rotates_handler(tmp_path, monkeypatch):
"""The writer coroutine drains the queue into logs/tool_calls.log."""
import gateway.run as gateway_run
monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
log_queue: queue.Queue = queue.Queue()
log_queue.put("2026-07-02 10:00:00 terminal: \"echo hi\"")
log_queue.put("2026-07-02 10:00:01 read_file: \"foo.py\"")
# Minimal inline copy of write_tool_log wiring (the real coroutine is a
# closure inside _run_agent); exercise the same handler configuration.
import logging
from logging.handlers import RotatingFileHandler
from agent.redact import RedactingFormatter
log_dir = tmp_path / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
handler = RotatingFileHandler(
log_dir / "tool_calls.log", maxBytes=5 * 1024 * 1024, backupCount=3,
encoding="utf-8",
)
handler.setFormatter(RedactingFormatter("%(message)s"))
tool_logger = logging.getLogger(f"hermes.tool_calls.test.{id(log_queue)}")
tool_logger.setLevel(logging.INFO)
tool_logger.propagate = False
tool_logger.addHandler(handler)
try:
while True:
try:
tool_logger.info("%s", log_queue.get_nowait())
except queue.Empty:
break
finally:
tool_logger.removeHandler(handler)
handler.flush()
handler.close()
content = (log_dir / "tool_calls.log").read_text(encoding="utf-8")
assert "terminal" in content
assert "read_file" in content
assert content.count("\n") == 2
await asyncio.sleep(0) # keep the asyncio marker honest