hermes-agent/tests/agent/test_vertex_adapter.py
Teknium 6b81590c55
test: prune low-value tests suite-wide (wave 1) — 46,820 → 28,106 test functions
Systematic prune per AGENTS.md test policy, one pass over every major
test tree (gateway, hermes_cli, tools, agent, run_agent, plugins, cli,
cron, tui_gateway, honcho/openviking, root-level):

- DELETE: source-reading tests (read_text/getsource on prod files),
  change-detector tests (exact catalog counts, model-name snapshots,
  config version literals), mock-echo tests (assert a mock returns what
  it was told), assertion-free/trivial tests, near-duplicate
  parametrizations (boundaries + one representative kept), async/sync
  twin duplicates, cosmetic within-file variations.
- KEEP (mandatory): security/redaction/approval guards, message-role
  alternation invariants, prompt-caching/deterministic-call-id
  invariants, issue-number regression tests (deduped), E2E tests.
- 6 test files deleted outright (script-style/no-assert or fully
  redundant); conftest.py, fakes/, fixtures/ untouched.
- tests/acp/conftest.py added: autouse fixture stubs the live
  models.dev/GitHub/Copilot/Anthropic inventory fetches that ACP server
  tests performed on every session create — test_server.py 147s → 3.4s,
  and the tests are now genuinely hermetic.
- Sleep-based slowness shrunk where safe (codex_ttfb_watchdog,
  compression_concurrent_fork, etc.); no wall-clock assertion tightened.

Verification: full hermetic suite via scripts/run_tests.sh —
2439 files, 31,130 tests passed, 0 failed, 0 flaky retries, 315s wall
(baseline: 583s wall, 13,564s subprocess CPU).
2026-07-29 13:10:23 -07:00

161 lines
5.3 KiB
Python

"""Tests for the Vertex AI adapter (agent/vertex_adapter.py).
Vertex uses OAuth2 (short-lived access tokens from a service-account JSON or
ADC), NOT a static API key. These tests mock google-auth entirely — no network
calls — and cover token minting, the config.yaml→env precedence bridge, the
global vs regional base-URL shapes, and the ADC→service-account fallback.
"""
from __future__ import annotations
import importlib
import sys
import types
import pytest
def _install_fake_google_auth(monkeypatch, *, adc_ok=True, adc_project="adc-project",
sa_project="sa-project", token="ya29.FAKE"):
"""Register a fake google-auth tree in sys.modules and return the module set."""
ga = types.ModuleType("google.auth")
gt = types.ModuleType("google.auth.transport")
gtr = types.ModuleType("google.auth.transport.requests")
go = types.ModuleType("google.oauth2")
gsa = types.ModuleType("google.oauth2.service_account")
gp = types.ModuleType("google")
gtr.Request = type("Request", (), {})
class _Creds:
def __init__(self):
self.token = None
self.expiry = None
self.expired = False
def refresh(self, req):
self.token = token
def _default(scopes=None):
if not adc_ok:
raise RuntimeError("Could not automatically determine credentials")
return _Creds(), adc_project
ga.default = _default
ga.transport = gt
gt.requests = gtr
class _SA:
@staticmethod
def from_service_account_file(path, scopes=None):
c = _Creds()
c.project_id = sa_project
return c
gsa.Credentials = _SA
go.service_account = gsa
gp.auth = ga
gp.oauth2 = go
for name, mod in [
("google", gp), ("google.auth", ga), ("google.auth.transport", gt),
("google.auth.transport.requests", gtr), ("google.oauth2", go),
("google.oauth2.service_account", gsa),
]:
monkeypatch.setitem(sys.modules, name, mod)
return gp
@pytest.fixture
def vertex_adapter(monkeypatch):
"""Fresh vertex_adapter with a fake google-auth and clean caches/env."""
for var in ("VERTEX_CREDENTIALS_PATH", "GOOGLE_APPLICATION_CREDENTIALS",
"VERTEX_PROJECT_ID", "VERTEX_REGION", "GOOGLE_CLOUD_PROJECT"):
monkeypatch.delenv(var, raising=False)
_install_fake_google_auth(monkeypatch)
import agent.vertex_adapter as va
va = importlib.reload(va)
va._creds_cache.clear()
# Neutralize config.yaml by default; individual tests re-patch _vertex_config.
monkeypatch.setattr(va, "_vertex_config", lambda: {})
return va
def test_has_vertex_credentials_via_config_project(vertex_adapter, monkeypatch):
monkeypatch.setattr(vertex_adapter, "_vertex_config", lambda: {"project_id": "p"})
assert vertex_adapter.has_vertex_credentials() is True
def test_has_vertex_credentials_false_when_nothing_set(vertex_adapter):
assert vertex_adapter.has_vertex_credentials() is False
def test_multiplex_scope_takes_precedence_over_raw_environ(vertex_adapter, monkeypatch):
"""In a multiplex gateway, a profile's own secret scope must win over a
stale value in process os.environ left behind by another profile's
dotenv load at boot — otherwise Profile B's turn could resolve Profile
A's Vertex project (or worse, its credentials file path)."""
from agent import secret_scope
monkeypatch.setenv("VERTEX_PROJECT_ID", "other-profile-project")
secret_scope.set_multiplex_active(True)
token = secret_scope.set_secret_scope({"VERTEX_PROJECT_ID": "this-profile-project"})
try:
assert vertex_adapter._resolve_project_override() == "this-profile-project"
finally:
secret_scope.reset_secret_scope(token)
secret_scope.set_multiplex_active(False)
def test_multiplex_unscoped_read_fails_closed(vertex_adapter, monkeypatch):
"""A credential read with no profile scope installed while multiplexing
is active must raise rather than silently fall back to (possibly another
profile's) raw os.environ value."""
from agent import secret_scope
monkeypatch.setenv("VERTEX_PROJECT_ID", "leaked-project")
secret_scope.set_multiplex_active(True)
try:
with pytest.raises(secret_scope.UnscopedSecretError):
vertex_adapter._resolve_project_override()
finally:
secret_scope.set_multiplex_active(False)
def test_adc_refuses_foreign_profile_google_application_credentials(
vertex_adapter, monkeypatch, tmp_path
):
"""When this profile's scope defines no Vertex credentials, but os.environ
still carries a *different* profile's GOOGLE_APPLICATION_CREDENTIALS (left
there by python-dotenv at gateway boot), ADC must not silently mint a
token under that foreign service account."""
from agent import secret_scope
sa_file = tmp_path / "other_profile_sa.json"
sa_file.write_text('{"project_id": "other-profile"}')
monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", str(sa_file))
secret_scope.set_multiplex_active(True)
token = secret_scope.set_secret_scope({}) # this profile defines nothing
try:
assert vertex_adapter.get_vertex_credentials() == (None, None)
finally:
secret_scope.reset_secret_scope(token)
secret_scope.set_multiplex_active(False)