Skip to content
Merged
Show file tree
Hide file tree
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
61 changes: 27 additions & 34 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ def helper(tmp_path, monkeypatch):
return module


@pytest.fixture
def exec_envs(helper, monkeypatch):
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
return children


@pytest.mark.parametrize('provider,key', [('claude', 'CLAUDE_CODE_OAUTH_TOKEN'), ('codex', 'CODEX_HOME')])
def test_managed_credentials_rebind_and_preserve_explicit(helper, provider, key):
if provider == 'codex':
Expand Down Expand Up @@ -124,7 +131,7 @@ def test_stale_failure_requires_exact_model_evidence(helper, monkeypatch, cache,
assert helper.active('claude') == active


def test_launch_then_pin_survives_active_change(helper, monkeypatch, capsys):
def test_launch_then_pin_survives_active_change(helper, monkeypatch, capsys, exec_envs):
monkeypatch.setattr(helper, 'probe_claude_model', lambda token, model: {'ok': True, 'http': 200, 'util': {}})
assert helper.main(['launch', 'claude', '--model', 'm']) == 0
output = capsys.readouterr().out
Expand All @@ -135,26 +142,22 @@ def test_launch_then_pin_survives_active_change(helper, monkeypatch, capsys):
monkeypatch.setattr(helper, 'probe_claude_model', lambda *args: pytest.fail('cached launch probed'))
assert helper.launch('claude', 'm', {})['identity'] == launch['identity']
helper.set_active('claude', 'b')
child = []
monkeypatch.setattr(helper.os, 'execvpe', lambda executable, argv, env: child.append(env))
monkeypatch.setenv('AI_ACCOUNTS_CLAUDE_OWNER', '1')
helper.main(['exec', 'claude', '--identity', launch['identity'], '--', 'real-harness'])
assert child[0]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert child[0]['AI_ACCOUNTS_CLAUDE_IDENTITY'] == launch['identity']
assert exec_envs[0]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert exec_envs[0]['AI_ACCOUNTS_CLAUDE_IDENTITY'] == launch['identity']


def test_pin_revision_changed_or_explicit_credentials_fails_closed(helper, monkeypatch, capsys):
def test_pin_revision_changed_or_explicit_credentials_fails_closed(helper, monkeypatch, capsys, exec_envs):
revision = helper.with_accounts('claude', {})['AI_ACCOUNTS_CLAUDE_IDENTITY']
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda *args: children.append(args))
monkeypatch.setenv('CLAUDE_CODE_OAUTH_TOKEN', 'caller-explicit')
assert helper.main(['exec', 'claude', '--identity', revision, '--', 'real-harness']) == 2
assert json.loads(capsys.readouterr().out)['outcome'] == 'unmanaged'
monkeypatch.delenv('CLAUDE_CODE_OAUTH_TOKEN')
helper.write_private(helper.STATE / 'claude/tokens/a', 'synthetic-revised-secret')
assert helper.main(['exec', 'claude', '--identity', revision, '--', 'real-harness']) == 2
assert json.loads(capsys.readouterr().out)['outcome'] == 'unmanaged'
assert children == []
assert exec_envs == []


def test_launch_keeps_unknown_model_unknown(helper, monkeypatch):
Expand Down Expand Up @@ -211,7 +214,7 @@ def test_partial_or_unidentified_codex_auth_keeps_strict_revision(helper, creden
('7d', 1, 1201, 'ok', True, True), ('7d', 1, 0, 'missing', True, True)])
@pytest.mark.parametrize('schema', ['legacy', 'windows'])
@pytest.mark.parametrize('pinned', [False, True])
def test_exec_reserve_policy(helper, monkeypatch, capsys, window, used, age, cache, owner, allowed, pinned, schema):
def test_exec_reserve_policy(helper, monkeypatch, capsys, exec_envs, window, used, age, cache, owner, allowed, pinned, schema):
monkeypatch.delenv('AI_ACCOUNTS_CLAUDE_OWNER', raising=False)
if owner:
monkeypatch.setenv('AI_ACCOUNTS_CLAUDE_OWNER', '1')
Expand All @@ -224,56 +227,46 @@ def test_exec_reserve_policy(helper, monkeypatch, capsys, window, used, age, cac
status['providers']['claude']['accounts'] = {}
if cache != 'missing':
helper.write_private(helper.STATE / 'status.json', '{' if cache == 'broken' else json.dumps(status))
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda *args: children.append(args))
monkeypatch.setattr(helper, 'probe_claude_model', lambda *args: pytest.fail('exec must not probe'))
args = ['exec', 'claude']
if pinned:
args += ['--identity', helper.identity('claude', 'a')]
code = helper.main([*args, '--', 'fake-cli'])
assert code == (127 if allowed else 3)
assert bool(children) is allowed
assert bool(exec_envs) is allowed
stderr = capsys.readouterr().err
if not allowed:
assert 'account a' in stderr
if used == .85:
assert window in stderr and '85%' in stderr and helper.iso(2000) in stderr


def test_exec_binds_approved_selection_and_preserves_explicit_auth(helper, monkeypatch):
def test_exec_binds_approved_selection_and_preserves_explicit_auth(helper, monkeypatch, exec_envs):
monkeypatch.setenv('AI_ACCOUNTS_CLAUDE_OWNER', '1')
original = helper.with_accounts
def rotate(providers, base, selected=None):
helper.set_active('claude', 'b')
return original(providers, base, selected)
monkeypatch.setattr(helper, 'with_accounts', rotate)
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
assert helper.cmd_exec('claude', ['fake']) == 127
assert children[-1]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert exec_envs[-1]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert original('claude', {}, {'claude': None}) == {}
assert original('claude', {'ANTHROPIC_API_KEY': 'explicit'}, {'claude': 'a'}) == {'ANTHROPIC_API_KEY': 'explicit'}


def test_exec_prefers_account_under_reserve(helper, monkeypatch):
@pytest.mark.parametrize('key', [None, 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'])
def test_exec_selects_under_reserve_or_preserves_caller_auth(helper, monkeypatch, exec_envs, key):
monkeypatch.delenv('AI_ACCOUNTS_CLAUDE_OWNER', raising=False)
accounts = {n: {'models': {'m': {'util': {'7d': used}}}} for n, used in (('a', .9), ('b', .5))}
status = {'checked_at': helper.now(), 'providers': {'claude': {'accounts': accounts}}}
helper.write_private(helper.STATE / 'status.json', json.dumps(status))
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
assert helper.cmd_exec('claude', ['fake']) == 127
assert children[0]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-b'


@pytest.mark.parametrize('key', ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'])
def test_exec_explicit_auth_skips_reserve_guard(helper, monkeypatch, key):
monkeypatch.delenv('AI_ACCOUNTS_CLAUDE_OWNER', raising=False)
monkeypatch.setenv(key, 'caller-owned')
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
if key is None:
accounts = {n: {'models': {'m': {'util': {'7d': used}}}} for n, used in (('a', .9), ('b', .5))}
status = {'checked_at': helper.now(), 'providers': {'claude': {'accounts': accounts}}}
helper.write_private(helper.STATE / 'status.json', json.dumps(status))
key, expected = 'CLAUDE_CODE_OAUTH_TOKEN', 'synthetic-secret-b'
else:
expected = 'caller-owned'
monkeypatch.setenv(key, expected)
assert helper.cmd_exec('claude', ['fake']) == 127
assert children[0][key] == 'caller-owned'
assert exec_envs[0][key] == expected


@pytest.mark.parametrize('code,retry_after,delay', [
Expand Down
49 changes: 16 additions & 33 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
env = { UV_CACHE_DIR = "/home/me/.cache/uv", UV_PYTHON_DOWNLOADS = "never" }
limits = { memory_mb = 1024, file_mb = 512 }

[checks.inputs]
"uv run pytest -q" = ["src/**"]
"*" = ["lock"]

[delivery]
merge = "rebase"
reviewers = ["codex"]
Expand All @@ -40,13 +44,16 @@ def write(tmp_path, text):
return path


def test_load_full_config(tmp_path):
assert config.load(write(tmp_path, FULL)) == Config(
@pytest.mark.parametrize("strategy,queue", [("rebase", None), ("mergify", "main")])
def test_load_full_config(tmp_path, strategy, queue):
workflow = FULL if queue is None else FULL.replace('merge = "rebase"', 'merge = "mergify"\nmergify_queue = "main"')
assert config.load(write(tmp_path, workflow)) == Config(
repo="owner/name",
base_branch="develop",
checks=("uv run pytest -q", "uv run ruff check ."),
required_ci=("checks",),
merge_strategy="rebase",
merge_strategy=strategy,
mergify_queue=queue,
reviewers=("codex",),
review={"codex": ReviewConfig("gpt-5.6-luna", "medium", ("low", "medium", "high"))},
reviewer_ro_paths=("/opt/claude", "/opt/codex"),
Expand All @@ -58,6 +65,7 @@ def test_load_full_config(tmp_path):
scratch=(".venv",),
env=(("UV_CACHE_DIR", "/home/me/.cache/uv"), ("UV_PYTHON_DOWNLOADS", "never")),
limits=ResourceLimits(memory_mb=1024, file_mb=512),
inputs={"uv run pytest -q": ("src/**",), "*": ("lock",)},
)

padded = FULL.replace('"uv run pytest -q"', '" uv run pytest -q "')
Expand All @@ -82,21 +90,6 @@ def test_load_applies_defaults(tmp_path):
assert loaded.limits == ResourceLimits(memory_mb=4096, file_mb=2048)


def test_mergify_delivery_requires_and_loads_queue(tmp_path):
loaded = config.load(write(tmp_path, """
[repo]
name = "o/n"
[delivery]
merge = "mergify"
mergify_queue = "main"
"""))
assert loaded.merge_strategy == "mergify"
assert loaded.mergify_queue == "main"

with pytest.raises(config.ConfigError, match="mergify_queue is required"):
config.load(write(tmp_path, '[repo]\nname = "o/n"\n[delivery]\nmerge = "mergify"\n'))


def test_missing_file(tmp_path):
with pytest.raises(config.ConfigError, match="config file not found"):
config.load(tmp_path / "nope.toml")
Expand All @@ -115,6 +108,11 @@ def test_missing_file(tmp_path):
r"workflow\.toml: checks\.commands.*nonblank command"),
('[repo]\nname = "o/n"\n[checks]\nnetwork = "yes"\n', "checks.network must be a bool"),
('[repo]\nname = "o/n"\n[delivery]\nmerge = "ff"\n', "delivery.merge must be one of"),
('[repo]\nname = "o/n"\n[delivery]\nmerge = "mergify"\n', "mergify_queue is required"),
*((f'[repo]\nname = "o/n"\n[delivery]\n{strategy}mergify_queue = "main"\n',
rf"delivery\.mergify_queue.*delivery\.merge.*{selected}")
for strategy, selected in [("", "squash"), ('merge = "squash"\n', "squash"), ('merge = "queue"\n', "queue")]),
(FULL.replace('["src/**"]', '"src"'), r"checks\.inputs"),
('[repo]\nname = "o/n"\n[delivery]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"),
('[repo]\nname = "o/n"\n[repo2]\nx = 1\n', "unknown key\\(s\\) in top level: repo2"),
('[repo]\nname = "o/n"\nnmae = "x"\n', "unknown key\\(s\\) in \\[repo\\]: nmae"),
Expand Down Expand Up @@ -174,18 +172,3 @@ def test_ro_path_boundary(tmp_path, path, allowed):
else:
with pytest.raises(config.ConfigError, match="must not expose"):
config.load(cfg)


def test_check_inputs(tmp_path):
cfg = config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = ["src/**"]\n"*" = ["lock"]\n'))
assert cfg.inputs == {"uv run pytest -q": ("src/**",), "*": ("lock",)}
with pytest.raises(config.ConfigError):
config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = "src"\n'))


@pytest.mark.parametrize("strategy", ["", 'merge = "squash"\n', 'merge = "queue"\n'])
def test_mergify_queue_rejects_other_strategies(tmp_path, strategy):
selected = "queue" if "queue" in strategy else "squash"
text = '[repo]\nname = "o/n"\n[delivery]\n' + strategy + 'mergify_queue = "main"\n'
with pytest.raises(config.ConfigError, match=rf"delivery\.mergify_queue.*delivery\.merge.*{selected}"):
config.load(write(tmp_path, text))
Loading
Loading