hermes-agent/tests/hermes_state/test_get_messages_around.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

106 lines
3.9 KiB
Python

"""Tests for SessionDB.get_messages_around (anchored-window primitive).
Used by session_search both for the discovery shape (FTS5 match as anchor)
and the scroll shape (user-supplied anchor). Returns a window of messages
around the anchor plus before/after counts so callers can detect session
boundaries.
"""
import pytest
from hermes_state import SessionDB
@pytest.fixture
def db(tmp_path):
return SessionDB(tmp_path / "state.db")
def _seed(db, sid="s1", n=10):
"""Create session with n alternating user/assistant messages, return ids ascending."""
db.create_session(sid, source="cli")
ids = []
for i in range(n):
role = "user" if i % 2 == 0 else "assistant"
# append_message returns the new id
mid = db.append_message(sid, role=role, content=f"msg {i}")
ids.append(mid)
return ids
class TestBasicWindow:
def test_returns_window_around_anchor(self, db):
ids = _seed(db, n=10)
anchor = ids[5]
view = db.get_messages_around("s1", anchor, window=2)
# Expected: 2 before + anchor + 2 after = 5 messages
msgs = view["window"]
assert len(msgs) == 5
assert [m["id"] for m in msgs] == [ids[3], ids[4], ids[5], ids[6], ids[7]]
assert view["messages_before"] == 2
assert view["messages_after"] == 2
def test_window_zero_returns_only_anchor(self, db):
ids = _seed(db, n=5)
view = db.get_messages_around("s1", ids[2], window=0)
assert len(view["window"]) == 1
assert view["window"][0]["id"] == ids[2]
assert view["messages_before"] == 0
assert view["messages_after"] == 0
class TestBoundaryDetection:
"""messages_before / messages_after tell the agent it's at start/end."""
def test_at_session_start_messages_before_is_short(self, db):
ids = _seed(db, n=10)
# Anchor on first message; ask for window=5
view = db.get_messages_around("s1", ids[0], window=5)
assert view["messages_before"] == 0 # nothing before the first msg
assert view["messages_after"] == 5
# window contains anchor + 5 after = 6 messages
assert len(view["window"]) == 6
class TestScrollPattern:
"""The forward/backward scroll loop the agent will run."""
def test_scroll_forward_re_anchored_on_last_id(self, db):
ids = _seed(db, n=20)
anchor = ids[5]
v1 = db.get_messages_around("s1", anchor, window=3)
last_id = v1["window"][-1]["id"]
v2 = db.get_messages_around("s1", last_id, window=3)
# Boundary id (last_id) appears in both windows (in v2 it's the anchor)
assert last_id in [m["id"] for m in v1["window"]]
assert last_id in [m["id"] for m in v2["window"]]
# v2's window extends beyond v1
assert max(m["id"] for m in v2["window"]) > max(m["id"] for m in v1["window"])
class TestContentHydration:
def test_content_is_decoded(self, db):
ids = _seed(db, n=3)
view = db.get_messages_around("s1", ids[1], window=1)
for m in view["window"]:
assert isinstance(m.get("content"), str)
assert m["content"].startswith("msg ")
def test_tool_calls_deserialized(self, db):
db.create_session("s1", source="cli")
# Message with tool_calls (pass list — append_message JSON-encodes it)
tc_payload = [{"id": "t1", "function": {"name": "x", "arguments": "{}"}}]
db.append_message("s1", role="assistant", content="", tool_calls=tc_payload)
mid = db.append_message("s1", role="tool", content="result", tool_name="x")
view = db.get_messages_around("s1", mid, window=2)
# Find the assistant message with tool_calls
asst = [m for m in view["window"] if m.get("role") == "assistant"]
assert asst, "expected an assistant message"
# tool_calls should be a list after hydration, not a string
assert isinstance(asst[0].get("tool_calls"), list)