Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions tests/agent/test_anthropic_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,18 @@ def test_no_expiry_but_has_token(self):


class TestResolveAnthropicToken:
@pytest.fixture(autouse=True)
def no_keychain(self, monkeypatch):
# resolve_anthropic_token() reads real macOS Keychain credentials via
# read_claude_code_credentials() before falling back to the mocked
# Path.home() cred file. Without this, these tests are not hermetic:
# on a Mac with Claude Code installed, the test reads the developer's
# real OAuth token from Keychain instead of the mocked value, making
# the test pass/fail based on local machine state.
monkeypatch.setattr(
"agent.anthropic_adapter._read_claude_code_credentials_from_keychain",
lambda: None,
)
def test_prefers_oauth_token_over_api_key(self, monkeypatch, tmp_path):
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-api03-mykey")
monkeypatch.setenv("ANTHROPIC_TOKEN", "sk-ant-oat01-mytoken")
Expand Down Expand Up @@ -450,6 +462,14 @@ def test_credentials_file_created_with_0o600(self, tmp_path, monkeypatch):


class TestResolveWithRefresh:
@pytest.fixture(autouse=True)
def no_keychain(self, monkeypatch):
# See TestResolveAnthropicToken.no_keychain — same hermeticity gap.
monkeypatch.setattr(
"agent.anthropic_adapter._read_claude_code_credentials_from_keychain",
lambda: None,
)

def test_auto_refresh_on_expired_creds(self, monkeypatch, tmp_path):
"""When cred file has expired token + refresh token, auto-refresh is attempted."""
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
Expand Down Expand Up @@ -497,6 +517,22 @@ def test_static_env_oauth_token_does_not_block_refreshable_claude_creds(self, mo


class TestRunOauthSetupToken:
@pytest.fixture(autouse=True)
def no_keychain(self, monkeypatch):
# read_claude_code_credentials() (called internally by
# run_oauth_setup_token()) checks the macOS Keychain via its own
# subprocess.run(["security", ...]) call before falling back to the
# cred file. Tests in this class patch subprocess.run globally to
# mock the `claude setup-token` invocation, which also intercepts
# the keychain lookup and returns a generic MagicMock — crashing
# json.loads() on a non-str/bytes object. Block the keychain lookup
# so these tests only exercise the credential-file/env-var paths
# they're actually testing.
monkeypatch.setattr(
"agent.anthropic_adapter._read_claude_code_credentials_from_keychain",
lambda: None,
)

def test_raises_when_claude_not_installed(self, monkeypatch):
monkeypatch.setattr("shutil.which", lambda _: None)
with pytest.raises(FileNotFoundError, match="claude.*CLI.*not installed"):
Expand Down