fix(tests): isolate credential tests from macOS Keychain#22692
Closed
wesleysimplicio wants to merge 1 commit into
Closed
Conversation
Problem: read_claude_code_credentials() checks the macOS Keychain first on Darwin (via _read_claude_code_credentials_from_keychain). On a developer machine that has authenticated with Claude Code, the Keychain holds a real OAuth token. Tests that only mocked Path.home() never suppressed the Keychain lookup, so the real token silently won the precedence race. Five tests in TestReadClaudeCodeCredentials and one each in TestResolveAnthropicToken / TestRunOauthSetupToken were affected: - Tests expecting None received real Keychain credentials. - test_falls_back_to_claude_code_credentials received the (possibly expired) Keychain token and resolve_anthropic_token() returned None after a failed refresh rather than "cc-auto-token" from the file. - test_returns_token_from_credential_files: globally-patched subprocess.run was also intercepted by the Keychain reader, causing json.loads to fail with TypeError: MagicMock is not str. Root cause: Missing test isolation for _read_claude_code_credentials_from_keychain. Fix: Add an autouse=True _no_keychain fixture to the three affected test classes. The fixture uses monkeypatch to replace _read_claude_code_credentials_from_keychain with a no-op lambda so every test in those classes sees None from the Keychain path. Add TestReadClaudeCodeCredentialsFromKeychain with two new tests that explicitly exercise the Keychain-first priority by mocking the function to return a controlled token dict. Tests: - All 152 tests in test_anthropic_adapter.py pass (was 147 pass + 5 fail). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR makes Anthropic adapter tests deterministic on macOS by preventing accidental reads from a developer’s real macOS Keychain (which can contain live Claude Code OAuth credentials), while adding targeted tests for the Keychain-precedence behavior under controlled mocks.
Changes:
- Add
autouse=Truefixtures to suppress_read_claude_code_credentials_from_keychain()in three existing test classes so file-based and subprocess-mocking tests don’t race against real Keychain state. - Add a new test class that explicitly verifies “Keychain wins over file” and “fallback to file when Keychain empty” behaviors via controlled mocking.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+222
to
+274
| class TestReadClaudeCodeCredentialsFromKeychain: | ||
| """Verify that a populated Keychain entry takes priority over the JSON file.""" | ||
|
|
||
| def test_keychain_creds_take_priority_over_file(self, tmp_path, monkeypatch): | ||
| """When Keychain returns credentials, the JSON file is never consulted.""" | ||
| kc_token = { | ||
| "accessToken": "sk-ant-oat01-keychain", | ||
| "refreshToken": "kc-refresh", | ||
| "expiresAt": int(time.time() * 1000) + 3600_000, | ||
| "source": "macos_keychain", | ||
| } | ||
| monkeypatch.setattr( | ||
| "agent.anthropic_adapter._read_claude_code_credentials_from_keychain", | ||
| lambda: kc_token, | ||
| ) | ||
| # Even if a JSON file with different data exists, Keychain wins. | ||
| cred_file = tmp_path / ".claude" / ".credentials.json" | ||
| cred_file.parent.mkdir(parents=True) | ||
| cred_file.write_text(json.dumps({ | ||
| "claudeAiOauth": { | ||
| "accessToken": "sk-ant-oat01-from-file", | ||
| "refreshToken": "file-refresh", | ||
| "expiresAt": int(time.time() * 1000) + 3600_000, | ||
| } | ||
| })) | ||
| monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path) | ||
| creds = read_claude_code_credentials() | ||
| assert creds is not None | ||
| assert creds["accessToken"] == "sk-ant-oat01-keychain" | ||
| assert creds["source"] == "macos_keychain" | ||
|
|
||
| def test_falls_back_to_file_when_keychain_empty(self, tmp_path, monkeypatch): | ||
| """When Keychain returns None, the JSON file is used.""" | ||
| monkeypatch.setattr( | ||
| "agent.anthropic_adapter._read_claude_code_credentials_from_keychain", | ||
| lambda: None, | ||
| ) | ||
| cred_file = tmp_path / ".claude" / ".credentials.json" | ||
| cred_file.parent.mkdir(parents=True) | ||
| cred_file.write_text(json.dumps({ | ||
| "claudeAiOauth": { | ||
| "accessToken": "sk-ant-oat01-file-token", | ||
| "refreshToken": "file-refresh", | ||
| "expiresAt": int(time.time() * 1000) + 3600_000, | ||
| } | ||
| })) | ||
| monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path) | ||
| creds = read_claude_code_credentials() | ||
| assert creds is not None | ||
| assert creds["accessToken"] == "sk-ant-oat01-file-token" | ||
| assert creds["source"] == "claude_code_credentials_file" | ||
|
|
||
|
|
Collaborator
|
Duplicate of #15958 which covers the same Keychain stubbing fix with broader scope (also covers botocore skip tests). |
Closed
2 tasks
Contributor
Author
|
Fechando como duplicado — @alt-glitch confirmou que #15958 cobre o mesmo fix de Keychain stubbing com escopo maior (inclui botocore skip tests). Obrigado pela revisão! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Problem
`read_claude_code_credentials()` checks the macOS Keychain before falling back to `~/.claude/.credentials.json`. On a developer machine that has run `claude login`, the Keychain holds a live OAuth token. Three test classes patched `Path.home()` but never suppressed `_read_claude_code_credentials_from_keychain`, so the real token silently won the precedence race:
Fix
Add an `autouse=True` `_no_keychain` fixture to each affected class that uses `monkeypatch` to replace `_read_claude_code_credentials_from_keychain` with `lambda: None`.
Add `TestReadClaudeCodeCredentialsFromKeychain` with two dedicated tests that exercise the Keychain-first priority with a controlled mock token dict.
Tests
All 152 tests in `tests/agent/test_anthropic_adapter.py` pass (was 147 pass + 5 fail before this patch).
Reproduces on any macOS machine where `claude login` has been run.
🤖 Generated with Claude Code
Solution Sketch
Related Issue
N/A
Type of Change
Changes Made
.github/PULL_REQUEST_TEMPLATE.mdHow to Test
Checklist
Code
fix(scope):,feat(scope):, etc.)pytest tests/ -qand all tests passDocumentation & Housekeeping
docs/, docstrings) — or N/Acli-config.yaml.exampleif I added/changed config keys — or N/ACONTRIBUTING.mdorAGENTS.mdif I changed architecture or workflows — or N/AScreenshots / Logs