Files
hermes-agent/tests/plugins/test_honcho_client_concurrency.py
teknium1 d10bb2ab6f test: make tests/ mirror the source tree; drop issue numbers from filenames
`scripts/run_tests.sh tests/<dir>/` is how a change gets its regression
coverage run, so a test filed under the wrong directory is a test nobody
runs when that code changes. Two kinds of drift had accumulated.

Parallel directories for one source package, folded into the mirror:
  tests/acp        -> tests/acp_adapter   (its __init__/conftest move with it)
  tests/cli        -> tests/hermes_cli    (prompt_toolkit fixture merged into
                                           hermes_cli/conftest.py)
  tests/run_agent  -> tests/agent         (backoff fixture becomes
                                           agent/conftest.py)
  tests/relay      -> tests/gateway/relay
  tests/state      -> tests/hermes_state

246 loose files at tests/ root, routed by the package they import/patch:
hermes_cli, hermes_state, agent, gateway, tools, plugins, tui_gateway, cron.
Installer and desktop-update script tests go to tests/scripts/{install,
desktop_update}/. 43 tests of root-level modules (batch_runner, utils,
hermes_constants, packaging) stay at the root.

Filenames drop their issue numbers (95 files: test_89315_x.py -> test_x.py);
the number stays in the module docstring where it has context.

Collisions: test_cli_skin_integration.py existed in both tests/ and tests/cli
with different subsets — merged into one (10 tests, all kept);
run_agent/test_pre_compress_memory_context.py -> agent/..._handoff.py;
tests/test_account_usage.py -> agent/test_account_usage_fetch.py;
tests/test_web_server.py -> hermes_cli/test_web_server_ws_ping.py.
Deleted: test_minisweagent_path.py (empty since PR #2804),
test_model_picker_scroll.py (tested a private copy of the logic, imported
nothing), test_process_loop_event_loop_warning.py (asserted asyncio behaviour,
imported nothing from Hermes).

Repo-root path arithmetic (Path(__file__).parents[N], dirname chains) is
bumped for the 202 files that changed depth and verified by evaluating every
such expression against the new location. classify_changes' desktop-updater
lane prefix, tests-os.yml's ignore glob and every in-tree path comment follow
the moves. tests/test_tests_tree_layout.py keeps the tree from drifting back.
2026-09-13 09:18:02 -07:00

110 lines
3.0 KiB
Python

"""Concurrency test for get_honcho_client() — the TOCTOU race fix (#24759).
Proves the Honcho client is constructed exactly once even when many threads
race the first call, by stubbing the SDK constructor and counting invocations.
"""
import sys
import threading
import types
import pytest
from plugins.memory.honcho import client as honcho_client
from plugins.memory.honcho.client import (
HonchoClientConfig,
get_honcho_client,
reset_honcho_client,
)
@pytest.fixture(autouse=True)
def _reset_singleton():
reset_honcho_client()
yield
reset_honcho_client()
def _install_fake_honcho_sdk(monkeypatch, build_count, build_lock):
"""Make `from honcho import Honcho` resolve to a counting fake."""
class _FakeHoncho:
def __init__(self, **kwargs):
with build_lock:
build_count["n"] += 1
import time
time.sleep(0.01) # widen the race window
self.kwargs = kwargs
fake_mod = types.ModuleType("honcho")
fake_mod.Honcho = _FakeHoncho
monkeypatch.setitem(sys.modules, "honcho", fake_mod)
# Skip the lazy-install path entirely.
monkeypatch.setattr(
honcho_client, "_resolve_optional_float", lambda *a, **k: None, raising=False
)
def test_get_honcho_client_builds_once_under_concurrent_first_call(monkeypatch):
build_count = {"n": 0}
build_lock = threading.Lock()
_install_fake_honcho_sdk(monkeypatch, build_count, build_lock)
config = HonchoClientConfig(
api_key="test-key",
workspace_id="ws",
environment="production",
)
barrier = threading.Barrier(20)
results = []
results_lock = threading.Lock()
def worker():
barrier.wait()
c = get_honcho_client(config)
with results_lock:
results.append(c)
threads = [threading.Thread(target=worker) for _ in range(20)]
for t in threads:
t.start()
for t in threads:
t.join()
assert build_count["n"] == 1, "Honcho client must be constructed exactly once"
assert len(results) == 20
assert all(r is results[0] for r in results), "all threads share one client"
def test_reset_allows_rebuild(monkeypatch):
build_count = {"n": 0}
build_lock = threading.Lock()
_install_fake_honcho_sdk(monkeypatch, build_count, build_lock)
config = HonchoClientConfig(
api_key="test-key", workspace_id="ws", environment="production"
)
c1 = get_honcho_client(config)
assert build_count["n"] == 1
# Cached: no rebuild.
assert get_honcho_client(config) is c1
assert build_count["n"] == 1
reset_honcho_client()
c2 = get_honcho_client(config)
assert build_count["n"] == 2
assert c2 is not c1
def test_missing_credentials_still_raises_before_build(monkeypatch):
build_count = {"n": 0}
build_lock = threading.Lock()
_install_fake_honcho_sdk(monkeypatch, build_count, build_lock)
bad = HonchoClientConfig(api_key="", base_url="", workspace_id="ws")
with pytest.raises(ValueError):
get_honcho_client(bad)
assert build_count["n"] == 0