Skip to content

The agent that grows with you

test: fold private-predicate and replayed-contract tests into their keepers

kshitijk4poor93a7267b101f
diff --git a/tests/agent/test_credential_pool_interrupt.py b/tests/agent/test_credential_pool_interrupt.py
index 1a14bc54cfc..5a3b169d2b6 100644
--- a/tests/agent/test_credential_pool_interrupt.py
+++ b/tests/agent/test_credential_pool_interrupt.py
@@ -56,28 +56,3 @@ def test_rotate_immediately_when_credential_already_exhausted():
assert retried is False
pool.mark_exhausted_and_rotate.assert_called_once()
agent._swap_credential.assert_called_once_with(entries[1])
-
-
-
-
-def test_rotate_on_second_429_when_not_exhausted():
- """When credential is active and this is the second 429, rotate (existing behavior)."""
- entries = [_make_entry(0, last_status=None), _make_entry(1)]
- pool = _make_pool(entries)
- pool.mark_exhausted_and_rotate.return_value = entries[1]
-
- from run_agent import AIAgent
- with patch("model_tools.get_tool_definitions", return_value=[]), patch("model_tools.check_toolset_requirements", return_value={}), patch("agent.process_bootstrap.OpenAI"):
- agent = MagicMock(spec=AIAgent)
- agent._credential_pool = pool
- agent._swap_credential = MagicMock()
- recovered, retried = AIAgent._recover_with_credential_pool(
- agent,
- status_code=429,
- has_retried_429=True, # Second 429
- classified_reason=FailoverReason.rate_limit,
- )
-
- assert recovered is True
- assert retried is False
- pool.mark_exhausted_and_rotate.assert_called_once()
diff --git a/tests/agent/test_credential_pool_unmatched_rotation_bound.py b/tests/agent/test_credential_pool_unmatched_rotation_bound.py
index db92e7ee8c5..a443f26de37 100644
--- a/tests/agent/test_credential_pool_unmatched_rotation_bound.py
+++ b/tests/agent/test_credential_pool_unmatched_rotation_bound.py
@@ -85,26 +85,3 @@ class TestUnmatchedHintRotationIsBounded:
assert all(status != "exhausted" for status in statuses.values()), (
f"innocent keys were quarantined: {statuses}"
)
-
-
-
- def test_matched_hint_path_unaffected(self, tmp_path, monkeypatch):
- """Regression guard: the normal matched-hint path still marks the
- failing entry and rotates to the healthy one."""
- pool = _seed_pool(
- tmp_path, monkeypatch,
- [_entry(0, "key-healthy"), _entry(1, "key-failed")],
- )
- assert pool.select().access_token == "key-healthy"
-
- nxt = pool.mark_exhausted_and_rotate(
- status_code=401,
- error_context={"reason": "unauthorized"},
- api_key_hint="key-failed",
- )
-
- statuses = {e.id: e.last_status for e in pool._entries}
- assert statuses["cred-1"] == "exhausted"
- assert statuses["cred-0"] != "exhausted"
- assert nxt is not None
- assert nxt.access_token == "key-healthy"
diff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.py
index 15fa8a5225e..16c3f8d268a 100644
--- a/tests/gateway/test_api_server.py
+++ b/tests/gateway/test_api_server.py
@@ -2286,13 +2286,6 @@ class TestChatCompletionsAgentIncomplete:
class TestCORS:
- def test_origin_allowed_for_non_browser_client(self, adapter):
- assert adapter._origin_allowed("") is True
-
-
- def test_origin_allowed_for_allowlist_match(self):
- adapter = _make_adapter(cors_origins=["http://localhost:3000"])
- assert adapter._origin_allowed("http://localhost:3000") is True
@pytest.mark.asyncio
@@ -2305,23 +2298,6 @@ class TestCORS:
assert resp.headers.get("Access-Control-Allow-Origin") is None
- @pytest.mark.asyncio
- async def test_cors_allows_idempotency_key_header(self):
- adapter = _make_adapter(cors_origins=["http://localhost:3000"])
- app = _create_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.options(
- "/v1/chat/completions",
- headers={
- "Origin": "http://localhost:3000",
- "Access-Control-Request-Method": "POST",
- "Access-Control-Request-Headers": "Idempotency-Key",
- },
- )
- assert resp.status == 200
- assert "Idempotency-Key" in resp.headers.get("Access-Control-Allow-Headers", "")
-
-
@pytest.mark.asyncio
async def test_cors_options_preflight_allowed_for_configured_origin(self):
"""Configured origins can complete browser preflight."""
@@ -2333,12 +2309,14 @@ class TestCORS:
headers={
"Origin": "http://localhost:3000",
"Access-Control-Request-Method": "POST",
- "Access-Control-Request-Headers": "Authorization, Content-Type",
+ "Access-Control-Request-Headers": "Authorization, Content-Type, Idempotency-Key",
},
)
assert resp.status == 200
assert resp.headers.get("Access-Control-Allow-Origin") == "http://localhost:3000"
- assert "Authorization" in resp.headers.get("Access-Control-Allow-Headers", "")
+ allowed = resp.headers.get("Access-Control-Allow-Headers", "")
+ assert "Authorization" in allowed
+ assert "Idempotency-Key" in allowed
@pytest.mark.asyncio
diff --git a/tests/gateway/test_api_server_multimodal.py b/tests/gateway/test_api_server_multimodal.py
index 1fa85d31a35..13968dd9000 100644
--- a/tests/gateway/test_api_server_multimodal.py
+++ b/tests/gateway/test_api_server_multimodal.py
@@ -44,18 +44,6 @@ class TestNormalizeMultimodalContent:
assert _normalize_multimodal_content(content) == "hello"
- def test_input_image_converted_to_canonical_shape(self):
- content = [
- {"type": "input_text", "text": "hi"},
- {"type": "input_image", "image_url": "https://example.com/cat.png"},
- ]
- out = _normalize_multimodal_content(content)
- assert out == [
- {"type": "text", "text": "hi"},
- {"type": "image_url", "image_url": {"url": "https://example.com/cat.png"}},
- ]
-
-
class TestContentHasVisiblePayload:
diff --git a/tests/gateway/test_api_server_room_grants.py b/tests/gateway/test_api_server_room_grants.py
index 83345eff19d..8ea75e022f9 100644
--- a/tests/gateway/test_api_server_room_grants.py
+++ b/tests/gateway/test_api_server_room_grants.py
@@ -6,30 +6,6 @@ from unittest.mock import MagicMock
import pytest
from gateway.platforms import api_server
-from gateway.platforms import api_server_room_grants as room_grants
-
-def test_grant_refresh_rejects_execution_policy_drift():
- claims = {"execution_policy_digest": "a" * 64}
-
- with pytest.raises(
- room_grants.RoomGrantReauthorizationRequired,
- match="execution policy changed",
- ):
- room_grants._require_unchanged_execution_policy(
- claims,
- {"policy_digest": "b" * 64},
- )
-
-def test_grant_refresh_accepts_the_authorized_execution_policy():
- claims = {"execution_policy_digest": "a" * 64}
-
- assert (
- room_grants._require_unchanged_execution_policy(
- claims,
- {"policy_digest": "a" * 64},
- )
- is None
- )
def test_room_grant_secret_stays_gateway_owned_on_named_profile(
tmp_path, monkeypatch
diff --git a/tests/gateway/test_startup_watchdog.py b/tests/gateway/test_startup_watchdog.py
index 5a090124936..76c74d31473 100644
--- a/tests/gateway/test_startup_watchdog.py
+++ b/tests/gateway/test_startup_watchdog.py
@@ -143,9 +143,6 @@ class TestArmDisarm:
assert not exit_capture.fired.is_set()
assert exit_capture.codes == []
- def test_disarm_without_arm_is_safe(self):
- disarm_startup_watchdog() # must not raise
-
def test_disarm_is_idempotent(self):
arm_startup_watchdog(timeout_s=60)
disarm_startup_watchdog()
diff --git a/tests/hermes_cli/test_shared_metrics_send_wiring.py b/tests/hermes_cli/test_shared_metrics_send_wiring.py
index 29f572c6977..293da0da71d 100644
--- a/tests/hermes_cli/test_shared_metrics_send_wiring.py
+++ b/tests/hermes_cli/test_shared_metrics_send_wiring.py
@@ -109,20 +109,6 @@ class TestOptIn:
runtime._join_send_thread(timeout=1)
assert capture_sender["passes"] == []
- def test_no_send_when_only_collection_is_on(self, runtime, monkeypatch, capture_sender):
- _set_config(monkeypatch, _config(enabled=True))
- runtime._export()
- runtime._join_send_thread(timeout=1)
- assert capture_sender["passes"] == []
-
- def test_no_send_when_send_is_on_without_collection(
- self, runtime, monkeypatch, capture_sender
- ):
- _set_config(monkeypatch, _config(enabled=False, send=True))
- runtime._export()
- runtime._join_send_thread(timeout=1)
- assert capture_sender["passes"] == []
-
def test_sends_when_both_are_on(self, runtime, monkeypatch, capture_sender):
_set_config(monkeypatch, _config(enabled=True, send=True))
runtime._export()
diff --git a/tests/hermes_cli/test_shared_metrics_sender_e2e.py b/tests/hermes_cli/test_shared_metrics_sender_e2e.py
index d0a0ccd8ea1..6287574e1e7 100644
--- a/tests/hermes_cli/test_shared_metrics_sender_e2e.py
+++ b/tests/hermes_cli/test_shared_metrics_sender_e2e.py
@@ -225,16 +225,6 @@ class TestRealTransport:
assert outcome.sent == 1
assert len(Ingest.received) == 2
-
- def test_a_gzipped_retry_is_byte_identical_on_the_wire(self, store, server):
- """gzip embeds an mtime by default, which would break this."""
- _add(store, "pkg-1", metrics=200)
- Ingest.script = [(503, {}, {}), (202, {}, {})]
- _sender(store, server).send_pending()
- first, second = Ingest.received
- assert first["headers"].get("content-encoding") == "gzip"
- assert first["raw"] == second["raw"]
-
def test_several_packages_in_one_pass(self, store, server):
for i in range(5):
_add(store, f"pkg-{i}")
@@ -242,14 +232,6 @@ class TestRealTransport:
assert outcome.sent == 5
assert len(Ingest.received) == 5
- def test_the_outbox_directory_is_untouched(self, store, server, tmp_path):
- _add(store, "pkg-1")
- marker = store.outbox_directory / "pkg-1.json"
- marker.write_text('{"kept": true}')
- _sender(store, server).send_pending()
- assert marker.exists()
- assert json.loads(marker.read_text()) == {"kept": True}
-
def test_a_dead_server_defers_without_raising(self, store, server):
_add(store, "pkg-1")
host, port = server.server_address
diff --git a/tests/tools/test_mcp_oauth_integration.py b/tests/tools/test_mcp_oauth_integration.py
index d5ac922c080..cc890c09912 100644
--- a/tests/tools/test_mcp_oauth_integration.py
+++ b/tests/tools/test_mcp_oauth_integration.py
@@ -80,6 +80,7 @@ async def test_external_refresh_picked_up_without_restart(tmp_path, monkeypatch)
baseline_changed = await mgr.invalidate_if_disk_changed("srv")
assert baseline_changed is False
assert provider._initialized is True
+ assert await mgr.invalidate_if_disk_changed("srv") is False # unchanged file
# EXTERNAL PROCESS: cron rewrites the tokens file with fresh creds.
# The old refresh_token has been consumed by this external exchange.
@@ -152,26 +153,3 @@ async def test_handle_401_deduplicates_concurrent_callers(tmp_path, monkeypatch)
assert all(r == results[0] for r in results), "dedup must return identical result"
# Exactly ONE recovery ran — the rest awaited the same pending future.
assert call_count == 1, f"expected 1 recovery attempt, got {call_count}"
-
-
-async def test_provider_is_reused_across_reconnects(tmp_path, monkeypatch):
- """The manager caches providers; multiple reconnects reuse the same instance.
-
- This is what makes the disk-watch stick across reconnects: tearing down
- the MCP session and rebuilding it (Task 5's _reconnect_event path) must
- not create a new provider, otherwise ``last_mtime_ns`` resets and the
- first post-reconnect auth flow would spuriously "detect" a change.
- """
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- _set_interactive_stdin(monkeypatch)
- from tools.mcp_oauth_manager import MCPOAuthManager, reset_manager_for_tests
- reset_manager_for_tests()
-
- mgr = MCPOAuthManager()
- p1 = mgr.get_or_build_provider("srv", "https://example.com/mcp", None)
-
- # Simulate a reconnect: _run_http calls get_or_build_provider again
- p2 = mgr.get_or_build_provider("srv", "https://example.com/mcp", None)
-
- assert p1 is p2, "manager must cache the provider across reconnects"
diff --git a/tests/tools/test_mcp_oauth_manager.py b/tests/tools/test_mcp_oauth_manager.py
index d3e3fcc87ea..d4dbd1ae2e5 100644
--- a/tests/tools/test_mcp_oauth_manager.py
+++ b/tests/tools/test_mcp_oauth_manager.py
@@ -5,7 +5,6 @@ single object with disk-mtime watch, dedup'd 401 handling, and a provider
cache. See `tools/mcp_oauth_manager.py` for design rationale.
"""
import json
-import os
import time
from unittest.mock import MagicMock
@@ -75,55 +74,6 @@ def _set_interactive_stdin(monkeypatch, *, is_tty: bool = True) -> None:
-async def test_disk_watch_invalidates_on_mtime_change(tmp_path, monkeypatch):
- """When the tokens file mtime changes after baseline, provider reloads.
-
- This is the behaviour Claude Code ships as
- invalidateOAuthCacheIfDiskChanged (CC-1096 / GH#24317) and is the core
- fix for Cthulhu's external-cron refresh workflow.
- """
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- from tools.mcp_oauth_manager import MCPOAuthManager, reset_manager_for_tests
-
- reset_manager_for_tests()
-
- token_dir = tmp_path / "mcp-tokens"
- token_dir.mkdir(parents=True)
- tokens_file = token_dir / "srv.json"
- tokens_file.write_text(json.dumps({
- "access_token": "OLD",
- "token_type": "Bearer",
- }), encoding="utf-8")
-
- mgr = MCPOAuthManager()
- provider = mgr.get_or_build_provider("srv", "https://example.com/mcp", None)
- assert provider is not None
- await provider._initialize()
- assert provider._initialized is True
-
- # First call only records the baseline mtime. Reloading here would reset
- # the provider during its first auth handshake.
- changed1 = await mgr.invalidate_if_disk_changed("srv")
- assert changed1 is False
- assert provider._initialized is True
-
- # No file change -> False
- changed2 = await mgr.invalidate_if_disk_changed("srv")
- assert changed2 is False
-
- # Touch file with a newer mtime
- future_mtime = time.time() + 10
- os.utime(tokens_file, (future_mtime, future_mtime))
-
- changed3 = await mgr.invalidate_if_disk_changed("srv")
- assert changed3 is True
- # _initialized flipped — next async_auth_flow will re-read from disk
- assert provider._initialized is False
-
-
-
-
@pytest.mark.asyncio
async def test_first_observation_401_still_allows_in_place_refresh(tmp_path, monkeypatch):
"""A 401 on the first disk observation seeds the baseline but must still
diff --git a/tests/tools/test_mcp_oauth_stdin_console.py b/tests/tools/test_mcp_oauth_stdin_console.py
index 1a5a97badc3..42d2f575dcc 100644
--- a/tests/tools/test_mcp_oauth_stdin_console.py
+++ b/tests/tools/test_mcp_oauth_stdin_console.py
@@ -17,11 +17,3 @@ def test_devnull_stdin_is_not_a_console_on_windows():
console, isatty = proc.stdout.split()
assert isatty == "True", "premise: the Windows CRT calls DEVNULL a tty (else this guard is moot)"
assert console == "False"
-
-
-def test_non_tty_stdin_is_not_interactive(monkeypatch):
- import io
- from tools import mcp_oauth
- monkeypatch.setattr(mcp_oauth.sys, "stdin", io.StringIO())
- assert mcp_oauth._stdin_is_console() is False
- assert mcp_oauth._is_interactive() is False