Skip to content

The agent that grows with you

test(honcho): trim the strict-reader tests to one case per behavior

kshitijk4poorb0d3ec62dadd
diff --git a/tests/honcho_plugin/test_cli.py b/tests/honcho_plugin/test_cli.py
index 201bbf28850..89e633a8d63 100644
--- a/tests/honcho_plugin/test_cli.py
+++ b/tests/honcho_plugin/test_cli.py
@@ -960,12 +960,3 @@ class TestWriteConfigMergesOntoDisk:
self._rotate_on_disk(cfg_path)
honcho_cli._write_config(cfg)
assert json.loads(cfg_path.read_text()) == cfg
-
- def test_write_holds_the_refresh_file_lock_and_bootstraps_a_missing_file(self, monkeypatch, tmp_path):
- import contextlib
- import plugins.memory.honcho.oauth as oauth
- cfg_path = tmp_path / "honcho.json"
- honcho_cli, locked = _point_cli_at(monkeypatch, cfg_path), []
- monkeypatch.setattr(oauth, "_config_refresh_lock", lambda path: locked.append(path) or contextlib.nullcontext())
- honcho_cli._write_config({"apiKey": "k"})
- assert locked == [cfg_path] and json.loads(cfg_path.read_text(encoding="utf-8")) == {"apiKey": "k"}
diff --git a/tests/honcho_plugin/test_oauth.py b/tests/honcho_plugin/test_oauth.py
index fa7967aab28..87f0d0ee9f8 100644
--- a/tests/honcho_plugin/test_oauth.py
+++ b/tests/honcho_plugin/test_oauth.py
@@ -1,7 +1,6 @@
"""Tests for plugins/memory/honcho/oauth.py — OAuth grant storage + refresh."""
import json
-from contextlib import nullcontext
from pathlib import Path
import pytest
@@ -185,29 +184,6 @@ class TestInstallGrant:
client_id="c", token_endpoint="e",
)
- def test_reads_and_writes_under_the_refresh_locks(self, tmp_path, monkeypatch):
- path = tmp_path / "honcho.json"
- _write(path, {"hosts": {"other": _host_block()}})
- seen, locked_paths = {}, []
-
- def spy(name, real):
- def wrapped(*a, **k):
- seen[name] = oauth._refresh_lock.locked()
- return real(*a, **k)
- return wrapped
-
- monkeypatch.setattr(oauth, "_config_refresh_lock", lambda p: locked_paths.append(p) or nullcontext())
- monkeypatch.setattr(oauth, "_read_config_strict", spy("read", oauth._read_config_strict))
- monkeypatch.setattr(oauth, "_persist_credential", spy("persist", oauth._persist_credential))
- oauth.install_grant(
- path, "hermes", {"access_token": "hch-at-new", "refresh_token": "hch-rt-new", "expires_in": 60},
- client_id="c", token_endpoint="e",
- )
- assert seen == {"read": True, "persist": True}
- assert locked_paths == [path]
- assert not oauth._refresh_lock.locked()
- assert "other" in json.loads(path.read_text())["hosts"]
-
class TestApplyTokenToClient:
def test_mutates_live_bearer(self):
@@ -226,14 +202,8 @@ class TestApplyTokenToClient:
class TestPersistReadFailure:
- """One unreadable honcho.json must never become a single-host store.
-
- ``_persist_credential`` promises "leaving all else intact", but it seeded
- the write from a reader that returned ``{}`` on ANY read failure, and
- ``_atomic_write_config`` replaces the whole file via ``os.replace`` —
- which needs only a writable parent, so a present-but-unreadable store did
- not stop the overwrite. Same class as the auth-store fix in #75206.
- """
+ """One unreadable or corrupt honcho.json must never become a single-host store, and a refresh must
+ fail BEFORE the single-use exchange when the result could not be persisted."""
@staticmethod
def _seed_two_hosts(path: Path) -> bytes:
@@ -246,120 +216,54 @@ class TestPersistReadFailure:
})
return path.read_bytes()
- def _unreadable(self, monkeypatch, target: Path):
+ def _break(self, monkeypatch, path: Path, how: str) -> type:
+ """Make ``path`` unreadable (PermissionError) or corrupt (truncated JSON); returns the expected error."""
+ if how == "corrupt":
+ path.write_text(path.read_text(encoding="utf-8")[:-5], encoding="utf-8")
+ return ValueError
real = Path.read_text
def boom(self, *a, **kw):
- if self.name == target.name:
+ if self.name == path.name:
raise PermissionError(13, "Permission denied")
return real(self, *a, **kw)
monkeypatch.setattr(Path, "read_text", boom)
+ return OSError
- def test_persist_raises_and_preserves_store_when_unreadable(
- self, tmp_path, monkeypatch
- ):
+ @pytest.mark.parametrize("how", ["unreadable", "corrupt"])
+ def test_writers_raise_and_leave_the_store_untouched(self, tmp_path, monkeypatch, how):
path = tmp_path / "honcho.json"
- before = self._seed_two_hosts(path)
+ self._seed_two_hosts(path)
+ exc = self._break(monkeypatch, path, how)
+ before = path.read_bytes()
cred = OAuthCredential.from_host_block(_host_block(refresh="hch-rt-new"))
-
- with monkeypatch.context() as m:
- self._unreadable(m, path)
- with pytest.raises(OSError):
- oauth._persist_credential(path, "rotate.example", cred)
-
+ grant = {"access_token": "hch-at-new", "refresh_token": "hch-rt-new", "expires_in": 3600}
+ with pytest.raises(exc):
+ oauth._persist_credential(path, "rotate.example", cred)
+ with pytest.raises(exc):
+ oauth.install_grant(path, "new.example", grant, client_id="c", token_endpoint="e")
assert path.read_bytes() == before
- def test_rotate_refuses_before_spending_the_refresh_token(
- self, tmp_path, monkeypatch
- ):
- # Rotation is single-use: an exchange whose result cannot be persisted
- # loses the grant, so an unreadable store must fail the refresh BEFORE
- # the exchange, not after.
+ @pytest.mark.parametrize("how", ["unreadable", "corrupt"])
+ def test_rotate_refuses_before_spending_the_refresh_token(self, tmp_path, monkeypatch, how):
path = tmp_path / "honcho.json"
- before = self._seed_two_hosts(path)
+ self._seed_two_hosts(path)
+ self._break(monkeypatch, path, how)
+ before = path.read_bytes()
cred = OAuthCredential.from_host_block(_host_block(refresh="hch-rt-rot"))
key = (str(path), "rotate.example")
oauth._refresh_failure_at.pop(key, None)
-
- def no_exchange(*a, **kw): # pragma: no cover - must not run
- raise AssertionError("exchange ran against an unreadable store")
-
- with monkeypatch.context() as m:
- m.setattr(oauth, "_exchange_with_retry", no_exchange)
- self._unreadable(m, path)
- assert oauth._rotate_and_persist(
- path, "rotate.example", key, cred, now=1.0
- ) is None
-
- assert key in oauth._refresh_failure_at
- oauth._refresh_failure_at.pop(key, None)
- assert path.read_bytes() == before
-
- def test_corrupt_store_refuses_to_persist(self, tmp_path):
- path = tmp_path / "honcho.json"
- truncated = json.dumps(
- {"hosts": {"keep.example": _host_block(refresh="hch-rt-keep")}}
- )[:-5]
- path.write_text(truncated, encoding="utf-8")
- cred = OAuthCredential.from_host_block(_host_block(refresh="hch-rt-new"))
-
- with pytest.raises(ValueError):
- oauth._read_config_strict(path)
- with pytest.raises(ValueError):
- oauth._persist_credential(path, "keep.example", cred)
- with pytest.raises(ValueError):
- oauth.install_grant(
- path, "new.example",
- {"access_token": "hch-at-new", "refresh_token": "hch-rt-new", "expires_in": 3600},
- client_id="hermes-desktop", token_endpoint="http://localhost:8000/oauth/token",
- )
- assert path.read_text(encoding="utf-8") == truncated
- assert not path.with_name(path.name + ".corrupt").exists()
-
- def test_corrupt_store_fails_the_refresh_before_the_exchange(self, tmp_path, monkeypatch):
- path = tmp_path / "honcho.json"
- path.write_text("{not json", encoding="utf-8")
- cred = OAuthCredential.from_host_block(_host_block(refresh="hch-rt-rot"))
- key = (str(path), "rotate.example")
- oauth._refresh_failure_at.pop(key, None)
-
- def no_exchange(*a, **kw): # pragma: no cover - must not run
- raise AssertionError("exchange ran against a corrupt store")
-
- monkeypatch.setattr(oauth, "_exchange_with_retry", no_exchange)
+ monkeypatch.setattr(oauth, "_exchange_with_retry",
+ lambda *a, **k: pytest.fail("exchange ran against a store that cannot be persisted"))
assert oauth._rotate_and_persist(path, "rotate.example", key, cred, now=1.0) is None
assert key in oauth._refresh_failure_at
oauth._refresh_failure_at.pop(key, None)
- assert path.read_text(encoding="utf-8") == "{not json"
+ assert path.read_bytes() == before
- def test_missing_store_still_bootstraps_empty(self, tmp_path):
+ def test_missing_store_bootstraps_empty_and_a_bom_is_not_corruption(self, tmp_path):
assert oauth._read_config_strict(tmp_path / "honcho.json") == {}
-
- def test_bom_prefixed_store_is_not_corruption(self, tmp_path):
path = tmp_path / "honcho.json"
- path.write_text(
- json.dumps({"hosts": {"keep.example": _host_block()}}),
- encoding="utf-8-sig",
- )
+ path.write_text(json.dumps({"hosts": {"keep.example": _host_block()}}), encoding="utf-8-sig")
assert "keep.example" in oauth._read_config(path).get("hosts", {})
assert "keep.example" in oauth._read_config_strict(path).get("hosts", {})
-
- def test_install_grant_raises_and_preserves_store_when_unreadable(
- self, tmp_path, monkeypatch
- ):
- path = tmp_path / "honcho.json"
- before = self._seed_two_hosts(path)
-
- with monkeypatch.context() as m:
- self._unreadable(m, path)
- with pytest.raises(OSError):
- oauth.install_grant(
- path, "new.example",
- {"access_token": "hch-at-new", "refresh_token": "hch-rt-new",
- "expires_in": 3600},
- client_id="hermes-desktop",
- token_endpoint="http://localhost:8000/oauth/token",
- )
-
- assert path.read_bytes() == before