Coverage for tests/core/test_secrets.py: 100%
64 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
1"""Tests the secrets module."""
3from __future__ import annotations
5import pathlib
6import types
8import pytest
10import courtpy
11from courtpy import secrets
14class FakeKeyring:
15 """A keyring that keeps passwords in a `dict`."""
17 def __init__(self) -> None:
18 self.passwords: dict[tuple[str, str], str] = {}
20 def get_password(self, service: str, username: str) -> str | None:
21 return self.passwords.get((service, username))
23 def set_password(self, service: str, username: str, password: str) -> None:
24 self.passwords[(service, username)] = password
26 def delete_password(self, service: str, username: str) -> None:
27 del self.passwords[(service, username)]
30def test_missing_key() -> None:
31 assert secrets.find_api_key() is None
32 assert secrets.get_api_key(required = False) is None
33 with pytest.raises(secrets.MissingAPIKeyError, match = 'courtpy key set'):
34 secrets.get_api_key()
37def test_file_store_outside_project(tmp_path: pathlib.Path) -> None:
38 place = secrets.set_api_key(' Token abcdef0123456789 ')
39 path = secrets.secrets_path()
40 assert place == str(path)
41 assert path.is_relative_to(tmp_path / 'config')
42 assert secrets.get_api_key() == 'abcdef0123456789'
43 assert 'abcdef0123456789' in path.read_text(encoding = 'utf-8')
44 assert secrets.find_api_key() == ('abcdef0123456789', str(path))
45 assert secrets.delete_api_key() == [str(path)]
46 assert secrets.find_api_key() is None
49def test_environment_variable_comes_first(monkeypatch: pytest.MonkeyPatch) -> None:
50 secrets.set_api_key('from-the-file')
51 monkeypatch.setenv(courtpy.options._ENV_API_KEY, 'from-the-environment')
52 key, place = secrets.find_api_key()
53 assert key == 'from-the-environment'
54 assert courtpy.options._ENV_API_KEY in place
57def test_dotenv_in_current_folder(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None:
58 project = tmp_path / 'project'
59 project.mkdir()
60 (project / '.env').write_text(
61 '# my settings\nexport COURTLISTENER_API_KEY="from-dotenv"\nOTHER=1\n',
62 encoding = 'utf-8')
63 monkeypatch.chdir(project)
64 assert secrets.find_api_key() == ('from-dotenv', str(project / '.env'))
67def test_keyring_store(monkeypatch: pytest.MonkeyPatch) -> None:
68 keyring = FakeKeyring()
69 monkeypatch.setattr(secrets, '_keyring', lambda: keyring)
70 assert secrets.set_api_key('in-the-keyring') == 'the system keyring'
71 assert not secrets.secrets_path().exists()
72 assert secrets.find_api_key() == ('in-the-keyring', 'the system keyring')
73 assert secrets.delete_api_key() == ['the system keyring']
74 assert secrets.find_api_key() is None
77def test_keyring_failure_falls_back_to_file(monkeypatch: pytest.MonkeyPatch) -> None:
78 broken = types.SimpleNamespace(
79 set_password = lambda *args: (_ for _ in ()).throw(RuntimeError('locked')),
80 get_password = lambda *args: None)
81 monkeypatch.setattr(secrets, '_keyring', lambda: broken)
82 assert secrets.set_api_key('fallback') == str(secrets.secrets_path())
83 with pytest.raises(RuntimeError, match = 'could not be stored'):
84 secrets.set_api_key('fallback', store = 'keyring')
87def test_invalid_input() -> None:
88 with pytest.raises(ValueError, match = 'blank'):
89 secrets.set_api_key(' ')
90 with pytest.raises(ValueError, match = 'store must be'):
91 secrets.set_api_key('key', store = 'cloud')
94def test_mask() -> None:
95 assert secrets.mask('0123456789abcdef') == '0123••••••••cdef'
96 assert secrets.mask('short') == '•' * 5