diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 2d3037a6..9eaea5cb 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -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': @@ -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 @@ -135,18 +142,14 @@ 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' @@ -154,7 +157,7 @@ def test_pin_revision_changed_or_explicit_credentials_fails_closed(helper, monke 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): @@ -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') @@ -224,15 +227,13 @@ 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 @@ -240,40 +241,32 @@ def test_exec_reserve_policy(helper, monkeypatch, capsys, window, used, age, cac 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', [ diff --git a/tests/test_config.py b/tests/test_config.py index 2ed48a21..4ab54b06 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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"] @@ -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"), @@ -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 "') @@ -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") @@ -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"), @@ -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)) diff --git a/tests/test_github.py b/tests/test_github.py index 98e0e410..2fb26235 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -262,12 +262,13 @@ def test_auth_failure_is_gh_auth(gh: FakeGh) -> None: assert "required token scope: repo" in info.value.tail -def test_generic_failure_carries_command_and_tail(gh: FakeGh) -> None: - gh.fail("pr ready", "HTTP 422: boom\n") +@pytest.mark.parametrize("stdout", ["", '{"message": "detail on stdout"}']) +def test_generic_failure_carries_command_and_tail(gh: FakeGh, stdout: str) -> None: + gh.respond("pr ready", {"stdout": stdout, "stderr": "gh: HTTP 422\n", "exit": 1}) with pytest.raises(github.GhError) as info: github.mark_ready(REPO, 7) assert info.value.command == ("gh", "pr", "ready", "7", "--repo", REPO) - assert "HTTP 422" in info.value.tail + assert info.value.tail == "gh: HTTP 422" + ("\n\n" + stdout if stdout else "\n") # --- PR lookup / creation ----------------------------------------------------------- @@ -571,14 +572,6 @@ def test_post_review_falls_back_to_comment_for_own_pr(gh: FakeGh, verdict: str, assert first["comments"] == second["comments"] and first["body"] == second["body"] -def test_gh_error_tail_joins_stderr_and_stdout(gh: FakeGh) -> None: - gh.respond("pr ready", {"stdout": '{"message": "detail on stdout"}', "stderr": "gh: HTTP 422\n", - "exit": 1}) - with pytest.raises(github.GhError) as info: - github.mark_ready(REPO, 7) - assert info.value.tail == 'gh: HTTP 422\n\n{"message": "detail on stdout"}' - - @pytest.mark.parametrize(("failure", "remedy"), [ ("not logged in", github.GH_AUTH_REMEDY), ("HTTP 429 rate limit", "retry after GitHub's reset or Retry-After"), @@ -639,23 +632,16 @@ def timeout(*args, **kwargs): assert info.value.__suppress_context__ -@pytest.mark.parametrize("verdict", ["approve", "request_changes"]) -def test_post_review_posts_comment_directly_for_own_pr(gh: FakeGh, verdict: str) -> None: - arm_review(gh, author="bot-user") - github.post_review(REPO, 7, HEAD, review(verdict=verdict, findings=FINDINGS[:1])) +@pytest.mark.parametrize("verdict,supplied", [("approve", False), ("request_changes", False), ("approve", True)]) +def test_post_review_posts_comment_directly_for_own_pr(gh: FakeGh, verdict: str, supplied: bool) -> None: + details = f"api repos/{REPO}/pulls/7" + arm_review(gh, author="someone-else" if supplied else "bot-user") + pr = github._pr_from_rest(rest_pr_json(pr_json(author={"login": "bot-user"}))) if supplied else None + github.post_review(REPO, 7, HEAD, review(verdict=verdict, findings=FINDINGS[:1]), pr=pr) (payload,) = review_payloads(gh) assert payload["event"] == "COMMENT" - assert [c["argv"][:2] for c in gh.calls[:2]] == [["api", f"repos/{REPO}/pulls/7"], - ["api", "graphql"]] - assert gh.argv(0) == ["api", f"repos/{REPO}/pulls/7", "--include"] - - -def test_post_review_uses_given_pr_without_lookup(gh: FakeGh) -> None: - arm_review(gh) - pr = github._pr_from_rest(rest_pr_json(pr_json(author={"login": "bot-user"}))) - github.post_review(REPO, 7, HEAD, review(verdict="approve"), pr=pr) - assert calls_for(gh, "pr view") == [] - assert review_payloads(gh)[0]["event"] == "COMMENT" + assert [c["argv"] for c in calls_for(gh, details)] == ([] if supplied else [[*details.split(), "--include"]]) + assert gh.argv(int(not supplied))[:2] == ["api", "graphql"] def test_post_review_other_errors_propagate(gh: FakeGh) -> None: @@ -676,9 +662,9 @@ def test_open_blocking_findings_filters_and_parses(gh: FakeGh) -> None: app = thread(f"{marker('important')}\n**important: From the App**", path="src/c.py") app["comments"]["nodes"][0]["author"] = {"__typename": "Bot", "login": "loopzero-app"} gh.respond("api graphql", threads_json( - thread(f"{versioned}\n**critical: Null deref**\n\nx may be None"), + thread(f"{versioned}\n**critical: Null deref**\n\nx may be None", edited="2026-09-18T01:00:00Z"), thread(f"{marker('important')}\nplain title", resolved=True), - thread(f"{marker('suggestion')}\n**suggestion: Rename**"), + thread(f"{marker('suggestion')}\n**suggestion: Rename**", edited="2026-09-18T01:00:00Z"), thread(f"{marker('important')}\n**important: Missing check**\n\nvalidate", path="src/b.py", line=2), app, @@ -690,7 +676,8 @@ def test_open_blocking_findings_filters_and_parses(gh: FakeGh) -> None: "**important: Missing check**\n\nvalidate"), Finding("important", "src/c.py", 3, "From the App", "**important: From the App**"), ] - argv = gh.argv(0) + (call,) = gh.calls + argv = call["argv"] assert argv[:2] == ["api", "graphql"] assert "-F" in argv and "owner=acme" in argv and "name=widgets" in argv and "number=7" in argv assert any(a.startswith("query=") and "author { __typename login }" in a for a in argv) @@ -711,6 +698,9 @@ def test_open_blocking_findings_filters_and_parses(gh: FakeGh) -> None: (marker("critical").replace(" head=", "\nhead=") + "\n**critical: Split**", "bot-user"), (marker("critical") + " trailing prose\n**critical: Trailed**", "bot-user"), (marker("critical", head=HEAD[:7]) + "\n**critical: Short head**", "bot-user"), + ("stripped loopzero marker\n**critical: X**", "bot-user"), + ("mentions loopzero but a human wrote it", "human"), + ("bot-user wrote this but it is unrelated", "bot-user"), ]) def test_open_findings_ignore_untrusted_or_quoted_markers(gh: FakeGh, body: str, author: str) -> None: gh.respond("api graphql", threads_json({**thread(body, author=author), "id": "T_1"})) @@ -838,29 +828,6 @@ def test_finding_id_is_deterministic_and_uses_location_and_title() -> None: assert github.finding_id(HEAD, "src/a.py", 11, "Null deref") != expected -def test_open_blocking_findings_counts_only_explicit_blocking_markers(gh: FakeGh) -> None: - gh.respond("api graphql", threads_json( - thread(f"{marker('suggestion')}\n**suggestion: nit**", edited="2026-09-18T01:00:00Z"), - thread(f"{marker('critical')}\nX", edited="2026-09-18T01:00:00Z", path="e.py", line=4), - )) - found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) - assert [(f.severity, f.path, f.line, f.title) for f in found] == [ - ("critical", "e.py", 4, "X"), - ] - assert all(c["argv"][:2] == ["api", "graphql"] for c in gh.calls), "no login lookup needed" - - -def test_open_blocking_findings_does_not_guess_from_body_or_author(gh: FakeGh) -> None: - gh.respond("api graphql", threads_json( - thread("stripped loopzero marker\n**critical: X**", author="bot-user"), - thread("mentions loopzero but a human wrote it", author="human"), - thread("bot-user wrote this but it is unrelated", author="bot-user"), - )) - found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) - assert found == [] - assert all(c["argv"] != ["api", "user"] for c in gh.calls) - - def test_open_blocking_findings_paginates(gh: FakeGh) -> None: gh.respond("api graphql", threads_json(thread(f"{marker('critical')}\nA"), has_next=True, cursor="C1"), @@ -1007,24 +974,18 @@ def arm_workflow_runs(gh, *runs): gh.respond(f"api repos/{REPO}/actions/runs?head_sha={HEAD}", *pages) -def test_readiness_ready(gh: FakeGh) -> None: - arm_readiness(gh) - assert readiness() == github.Readiness(True, ()) +@pytest.mark.parametrize("reviewed,reasons", [ + (HEAD, ()), + ("b" * 40, (f"head {HEAD[:12]} differs from reviewed {'b' * 12}",)), + (None, ("no review recorded for the current head",)), +]) +def test_readiness_requires_current_review(gh: FakeGh, reviewed, reasons) -> None: + arm_readiness(gh, threads=(thread(f"{marker('critical')}\nX", resolved=True), + thread(f"{marker('suggestion')}\nY"))) + assert readiness(reviewed=reviewed) == github.Readiness(not reasons, reasons) assert not any("actions/runs" in " ".join(c["argv"]) for c in gh.calls) -def test_readiness_head_moved(gh: FakeGh) -> None: - arm_readiness(gh) - r = readiness(reviewed="b" * 40) - assert not r.ready and any("differs from reviewed" in x for x in r.reasons) - - -def test_readiness_no_review(gh: FakeGh) -> None: - arm_readiness(gh) - r = readiness(reviewed=None) - assert r.reasons == ("no review recorded for the current head",) - - @pytest.mark.parametrize("finding,reason", [ pytest.param( thread(f"{marker('important')}\n**important: Oops**"), @@ -1042,12 +1003,6 @@ def test_readiness_blocking_finding(gh: FakeGh, finding: dict, reason: str) -> N assert not result.ready and result.reasons == (reason,) -def test_readiness_resolved_or_suggestion_threads_do_not_block(gh: FakeGh) -> None: - arm_readiness(gh, threads=(thread(f"{marker('critical')}\nX", resolved=True), - thread(f"{marker('suggestion')}\nY"))) - assert readiness().ready - - def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks( gh: FakeGh, ) -> None: @@ -1112,13 +1067,7 @@ def test_readiness_defers_only_replaceable_failure(gh: FakeGh, created_at, statu def test_readiness_looks_up_only_required_failed_checks(gh: FakeGh) -> None: - gh.respond("api graphql", threads_json()) - gh.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs", {"check_runs": [ - {"name": "checks", "status": "completed", "conclusion": "success"}, - {"name": "optional", "status": "completed", "conclusion": "failure", - "check_suite": {"id": 10}}, - ]}) - gh.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", []) + arm_workflow_check(gh, check_run("success"), failed_check(name="optional")) result = readiness(workflow_wait=True) assert result.ready assert not any("actions/runs" in " ".join(c["argv"]) for c in gh.calls) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 88ce09f8..89018879 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -39,38 +39,39 @@ def reject_network(_connection): assert fake_key not in "".join(traceback.format_exception(failure.value)) -def test_membership_uses_bearer_and_validates_queue(monkeypatch): +@pytest.fixture +def request_log(monkeypatch): monkeypatch.setenv("MERGIFY_API_KEY", "secret") seen = [] - def open_(request): - seen.append(request) - return response({ - "number": 7, "queue_rule_name": "main", "queued_at": "now", "position": 2, - }) + def install(payload=None, *, status=None): + def open_(request): + seen.append(request) + if status: + raise urllib.error.HTTPError(request.full_url, status, "test response", {}, None) + return response(payload) + monkeypatch.setattr(mergify, "_open", open_) + return seen + + return install + - monkeypatch.setattr(mergify, "_open", open_) +def test_membership_uses_bearer_and_validates_queue(request_log): + seen = request_log({"number": 7, "queue_rule_name": "main", "queued_at": "now", "position": 2}) assert mergify.membership("acme/widgets", 7, "main") == mergify.Membership() assert seen[0].full_url == "https://api.mergify.com/v1/repos/acme/widgets/merge-queue/pull/7" assert seen[0].headers["Authorization"] == "Bearer secret" assert seen[0].headers["User-agent"] == "loopzero" -def test_membership_maps_404_only_to_absent(monkeypatch): - monkeypatch.setenv("MERGIFY_API_KEY", "secret") - - def missing(request): - raise urllib.error.HTTPError(request.full_url, 404, "missing", {}, None) - - monkeypatch.setattr(mergify, "_open", missing) - assert mergify.membership("acme/widgets", 7, "main") is None - - def forbidden(request): - raise urllib.error.HTTPError(request.full_url, 403, "forbidden", {}, None) - - monkeypatch.setattr(mergify, "_open", forbidden) - with pytest.raises(mergify.MergifyError, match="HTTP 403"): - mergify.membership("acme/widgets", 7, "main") +@pytest.mark.parametrize("status", [404, 403]) +def test_membership_maps_404_only_to_absent(request_log, status): + request_log(status=status) + if status == 404: + assert mergify.membership("acme/widgets", 7, "main") is None + else: + with pytest.raises(mergify.MergifyError, match="HTTP 403"): + mergify.membership("acme/widgets", 7, "main") def test_api_get_rejects_paths_outside_repository(): @@ -80,15 +81,8 @@ def test_api_get_rejects_paths_outside_repository(): mergify.api_get("acme/widgets", "/../other") -def test_dequeue_posts_to_documented_endpoint(monkeypatch): - monkeypatch.setenv("MERGIFY_API_KEY", "secret") - seen = [] - - def open_(request): # a transient failure must not repeat the write - seen.append(request) - raise urllib.error.HTTPError(request.full_url, 503, "x", {}, None) - - monkeypatch.setattr(mergify, "_open", open_) +def test_dequeue_posts_to_documented_endpoint(request_log): + seen = request_log(status=503) # a transient failure must not repeat the write with pytest.raises(mergify.MergifyError): mergify.dequeue("acme/widgets", 7) assert (len(seen), seen[0].method, seen[0].full_url.endswith("/pull/7/dequeue")) == (1, "POST", True) @@ -96,11 +90,12 @@ def open_(request): # a transient failure must not repeat the write @pytest.fixture def queue_api(monkeypatch): - monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( - {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else - {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} - )) - def github_config(text, *, default="main", changed=False, file_overrides=None): + def github_config(text, *, default="main", changed=False, file_overrides=None, queues=True, inplace=True): + rows = [{"name": "main", "config": {"allow_inplace_checks": inplace}}] if queues else [] + monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( + {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") + else {"configuration": rows} + )) reads = 0 def get(path): nonlocal reads @@ -137,6 +132,8 @@ def get(path): *((text, {}, False) for text in UNSAFE_CONFIGS), (SAFE_CONFIG, {"default": "other"}, False), (SAFE_CONFIG, {"changed": True}, False), + (SAFE_CONFIG, {"queues": False}, False), + (ONE_CHECK, {"inplace": False}, False), *((SAFE_CONFIG, {"file_overrides": {key: value}}, False) for key, value in (("encoding", "none"), ("type", "symlink"), ("sha", None), ("sha", "z" * 40), ("content", None), ("content", "!"))), @@ -146,21 +143,6 @@ def test_configured_validates_canonical_github_config(queue_api, text, options, assert mergify.configured("acme/widgets", "main", "main") == accepted -def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch): - queue_api(SAFE_CONFIG) - monkeypatch.setattr(mergify, "api_get", lambda *_: {"batches": [], "mode": "serial", "configuration": []}) - assert not mergify.configured("acme/widgets", "main", "main") - - -def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): - queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) - monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( - {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else - {"configuration": [{"name": "main", "config": {"allow_inplace_checks": False}}]} - )) - assert not mergify.configured("acme/widgets", "main", "main") - - def test_markers_only_accept_exact_lines_from_current_login(monkeypatch): head, marker = "a" * 40, f"" rows = [("trusted", "@mergifyio queue main"), ("attacker", marker), # early queue: no request diff --git a/tests/test_runners.py b/tests/test_runners.py index e14ccdba..23e2e3c3 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -853,8 +853,6 @@ def test_reviewer_ro_paths_replace_binary_default(fake_bin: Path, tmp_path: Path @pytest.mark.parametrize("family,override", [("codex", "CODEX_HOME"), ("claude", "CLAUDE_CONFIG_DIR")]) def test_blank_reviewer_home_matches_unset(repo, family, override, tmp_path, fake_bwrap, monkeypatch): - from loopzero import runners - git(repo, "init", "-q") host = tmp_path / "host" state = host / f".{family}" @@ -862,9 +860,6 @@ def test_blank_reviewer_home_matches_unset(repo, family, override, tmp_path, fak (state / "auth.json").touch() monkeypatch.setenv("HOME", str(host)) monkeypatch.chdir(repo) - for name in ("CODEX_HOME", "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR", - *runners.CLAUDE_AUTH_ENV): - monkeypatch.delenv(name, raising=False) monkeypatch.setattr(runners, "_review_binary", lambda _: Path("/usr/bin/true")) monkeypatch.setattr(runners.sandbox, "probe", lambda *_: None) @@ -880,22 +875,8 @@ def test_blank_reviewer_home_matches_unset(repo, family, override, tmp_path, fak assert runners._auth_binds(family, blank_home) == unset_binds -def test_empty_secure_storage_override_preserves_native_default(repo, - fake_bin, tmp_path, fake_bwrap, monkeypatch, -) -> None: - host = tmp_path / "host" - host.mkdir() - monkeypatch.setenv("HOME", str(host)) - monkeypatch.chdir(repo) - monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", "") - _fake_review(fake_bin, "claude") - assert _review("claude", repo).verdict == "approve" - with pytest.raises(SandboxUnavailable, match="protected reviewer state"): - _review("claude", repo, reviewer_ro_paths=(str(Path.home() / ".claude"),)) - - @pytest.mark.parametrize("state", [ - ".claude", ".codex", ".claude.json", "custom-claude", "custom-codex", "secure-storage", + ".claude", ".codex", ".claude.json", "custom-claude", "custom-codex", "secure-storage", "blank-secure-storage", ]) @pytest.mark.parametrize("exposure", ["exact", "ancestor", "descendant", "alias", "repository"]) def test_review_refuses_additional_host_state_exposure( @@ -907,8 +888,9 @@ def test_review_refuses_additional_host_state_exposure( monkeypatch.setenv("HOME", str(host)) monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(host / "custom-claude")) monkeypatch.setenv("CODEX_HOME", str(host / "custom-codex")) - monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", str(host / "secure-storage")) - protected = host / state + blank = state == "blank-secure-storage" + monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", "" if blank else str(host / "secure-storage")) + protected = host / (".claude" if blank else state) protected.mkdir() (protected / "history.txt").write_text("private host history") child = protected / "child" @@ -920,6 +902,11 @@ def test_review_refuses_additional_host_state_exposure( repo = protected if exposure == "repository" else tmp_path / "repo" repo.mkdir(exist_ok=True) _fake_review(fake_bin, "claude") + if blank and exposure == "exact": + monkeypatch.delenv("CLAUDE_CONFIG_DIR") + monkeypatch.chdir(repo) + assert _review("claude", repo).verdict == "approve" + (fake_bin / "claude.stdin").unlink() with pytest.raises(SandboxUnavailable, match="protected reviewer state"): _review("claude", repo, reviewer_ro_paths=() if exposure == "repository" else (str(exposed),)) assert not (fake_bin / "claude.stdin").exists() @@ -1004,25 +991,13 @@ def test_review_denies_state_exposure_from_non_runtime_mounts(repo, assert not (fake_bin / "claude.stdin").exists() -@pytest.mark.parametrize("family", ["claude", "codex"]) @pytest.mark.parametrize("reported", [True, False]) -def test_native_settings_keep_requests_and_bounded_claims_separate(fake_bin, tmp_path, family, reported): - if family == "claude": - envelope = _claude_envelope(APPROVE, modelUsage={"reported-model": {}} if reported else {}) - _fake_claude(fake_bin, envelope) - else: - _fake_codex(fake_bin, json.dumps(APPROVE), stderr=( - "model: reported-model\nreasoning effort: high\nSECRET-NOT-PERSISTED" if reported else "" - )) - result = _review(family, tmp_path, model="requested-model", effort="medium") +def test_claude_keeps_native_settings_separate_from_requested_settings(fake_bin, tmp_path, reported): + envelope = _claude_envelope(APPROVE, modelUsage={"reported-model": {}} if reported else {}) + _fake_claude(fake_bin, envelope) + result = _review("claude", tmp_path, model="requested-model", effort="medium") assert result.provenance["requested_settings"] == [{"model": "requested-model", "effort": "medium"}] - if family == "claude": - assert json.loads(result.raw) == envelope, "native Claude evidence must remain unchanged" - else: - assert json.loads(result.raw)["reported_settings"] == { - "model": "reported-model" if reported else None, "effort": "high" if reported else None, - } - assert "SECRET-NOT-PERSISTED" not in result.raw + assert json.loads(result.raw) == envelope def test_merge_preserves_native_call_order_and_pads_legacy_requests(fake_bin, tmp_path): @@ -1042,6 +1017,8 @@ def test_merge_preserves_native_call_order_and_pads_legacy_requests(fake_bin, tm @pytest.mark.parametrize("stderr,expected", [ + ("", {"model": None, "effort": None}), + ("model: reported-model\nreasoning effort: high\nSECRET-NOT-PERSISTED", {"model": "reported-model", "effort": "high"}), ("model: " + "x" * 129 + "\nreasoning effort: high extra", {"model": None, "effort": None}), ("diagnostic model: ignored\neffort: high", {"model": None, "effort": None}), ("model:\nSECRET-NOT-PERSISTED", {"model": None, "effort": None}), @@ -1049,7 +1026,8 @@ def test_merge_preserves_native_call_order_and_pads_legacy_requests(fake_bin, tm ]) def test_codex_retains_only_recognized_bounded_cli_claims(fake_bin, tmp_path, stderr, expected): _fake_codex(fake_bin, json.dumps(APPROVE), stderr=stderr) - result = _review("codex", tmp_path) + result = _review("codex", tmp_path, model="requested-model", effort="medium") + assert result.provenance["requested_settings"] == [{"model": "requested-model", "effort": "medium"}] assert json.loads(result.raw)["reported_settings"] == expected assert "SECRET-NOT-PERSISTED" not in result.raw @@ -1244,20 +1222,10 @@ def test_inspection_accepts_the_reviewer_patch_command() -> None: assert runners._inspection_commands(command, "/repo") == [("diff", "a" * 40, "b" * 40)] -def test_split_diff_respects_budget_and_summarizes_deleted_file() -> None: - deleted = ( - "diff --git a/gone.py b/gone.py\n" - "deleted file mode 100644\n--- a/gone.py\n+++ /dev/null\n" - "@@ -1,3 +0,0 @@\n-one\n-two\n-three\n" - ) - added = "diff --git a/new.py b/new.py\n" + "+x\n" * 60 - chunks = split_diff(deleted + added, 100) - assert all(len(chunk.encode()) <= 100 for chunk in chunks) - assert any("gone.py: deleted, 3 lines" in chunk for chunk in chunks) - - -@pytest.mark.parametrize("name", ["zażółć gęślą.txt", "gone with spaces.txt", "gone.txt"]) -def test_split_diff_summarizes_real_git_deletion(git_repo: Path, name: str) -> None: +@pytest.mark.parametrize("name,budget", [ + ("zażółć gęślą.txt", 4096), ("gone with spaces.txt", 4096), ("gone.txt", 4096), ("gone.py", 100), +]) +def test_split_diff_summarizes_real_git_deletion(git_repo: Path, name: str, budget: int) -> None: git(git_repo, "config", "core.quotePath", "true") path = git_repo / name path.write_text("deleted line\n" * 600) @@ -1268,9 +1236,8 @@ def test_split_diff_summarizes_real_git_deletion(git_repo: Path, name: str) -> N git(git_repo, "commit", "-qm", "delete file") diff = render_patch(worktree.diff_since(git_repo, base)) - chunks = split_diff(diff, 4096) - - assert all(len(chunk.encode()) <= 4096 for chunk in chunks) + chunks = split_diff(diff, budget) + assert all(len(chunk.encode()) <= budget for chunk in chunks) assert any(f"{name}: deleted, 600 lines" in chunk for chunk in chunks) assert chunks[0].split("\n", 1)[0] == diff.split("\n", 1)[0] diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 674e4d8a..b8ea47f6 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -186,16 +186,13 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", "echo hello"] -def test_probe_uses_real_flags(git_repo, bwrap_log): - sandbox.run_checks(make_config(checks=(), network=True), git_repo) - argv = argv_of(bwrap_log) # only the probe ran - assert argv[argv.index("--") + 1 :] == ["true"] - assert argv.index("--unshare-all") < argv.index("--share-net") < argv.index("--clearenv") - - -def test_network_binds_resolv_conf_after_run_tmpfs(git_repo, bwrap_log): - sandbox.run_checks(make_config(network=True), git_repo) +@pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) +def test_network_binds_resolv_conf_after_run_tmpfs(git_repo, bwrap_log, checks): + sandbox.run_checks(make_config(checks=checks, network=True), git_repo) argv = argv_of(bwrap_log) + if not checks: + assert argv[argv.index("--") + 1 :] == ["true"] + assert argv.index("--unshare-all") < argv.index("--share-net") < argv.index("--clearenv") resolv_conf = Path("/etc/resolv.conf") resolved = resolv_conf.resolve() if resolv_conf.is_symlink() and any( @@ -204,14 +201,8 @@ def test_network_binds_resolv_conf_after_run_tmpfs(git_repo, bwrap_log): source = destination = str(resolved.parent) else: source, destination = str(resolved), str(resolv_conf) - bind_at = next( - i - for i in range(len(argv) - 2) - if argv[i : i + 3] == ["--ro-bind", source, destination] - ) - run_tmpfs_at = next( - i for i in range(len(argv) - 1) if argv[i : i + 2] == ["--tmpfs", "/run"] - ) + bind_at = next(i for i, flag in enumerate(argv) if flag == "--ro-bind" and argv[i + 1:i + 3] == [source, destination]) + run_tmpfs_at = next(i for i, pair in enumerate(itertools.pairwise(argv)) if pair == ("--tmpfs", "/run")) assert bind_at > run_tmpfs_at @@ -729,11 +720,14 @@ def fetched_base(git_repo): @pytest.fixture -def cache_check(git_repo): - exclude = git_repo / ".git/info/exclude" - with exclude.open("a") as stream: +def receipt_path(git_repo): + with (git_repo / ".git/info/exclude").open("a") as stream: stream.write("\n.loopzero/\n") + return git_repo / ".loopzero/checks.json" + +@pytest.fixture +def cache_check(git_repo, receipt_path): def cache(config, *, clean=False, verify_reuse=False): report = sandbox.run_checks(config, git_repo) assert report.ok @@ -750,7 +744,7 @@ def cache(config, *, clean=False, verify_reuse=False): @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', 'dirty_tree', 'legacy', 'grant']) -def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): +def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change, cache_check, receipt_path): cfg = make_config(checks=('echo one', 'echo two'), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) if change == 'grant': @@ -761,11 +755,7 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch whole = replace(cfg, inputs={'*': ('.',)}) key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base) assert key is not None - _save_report(git_repo, sandbox.run_checks(cfg, git_repo)) - receipt = git_repo / '.loopzero/checks.json' - git(git_repo, 'config', 'core.excludesFile', str(git_repo / '.git/info/exclude')) - with (git_repo / '.git/info/exclude').open('a') as stream: - stream.write('\n.loopzero/\n') + cache_check(cfg, clean=True) if change in {'other', 'input', 'shared', 'dirty_tree'}: path = 'README.md' if change in {'input', 'dirty_tree'} else 'src.py' if change == 'other' else change (git_repo / path).write_text('new content') @@ -788,7 +778,7 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch elif change == 'version': monkeypatch.setattr(sandbox, '__version__', 'new') else: - data = json.loads(receipt.read_text()) + data = json.loads(receipt_path.read_text()) if change in {'failed', 'boolean_exit_code'}: for row in data['results']: row['exit_code'] = False if change == 'boolean_exit_code' else 1 @@ -799,7 +789,7 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch else: for row in data['results']: row.pop('input_key') - receipt.write_text(json.dumps(data)) + receipt_path.write_text(json.dumps(data)) report = sandbox.run_checks(cfg, git_repo, status=(messages := []).append) assert [r.command for r in report.results] == list(cfg.checks) assert all(bool(r.reused_from) == (change == 'other') for r in report.results) @@ -859,21 +849,23 @@ def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_ba assert report.results[0].reused_from is None -@pytest.mark.parametrize("recorded_base", [False, True]) -def test_local_check_reuse_tracks_base_at_same_head(git_repo, bwrap_log, recorded_base): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +@pytest.mark.parametrize("base", ["tracked", "recorded", "absent"]) +def test_local_check_reuse_tracks_base_at_same_head(git_repo, bwrap_log, base, cache_check): head = git(git_repo, "rev-parse", "HEAD").strip() base_ref = "refs/remotes/origin/main" - if recorded_base: + if base == "recorded": (git_repo / ".loopzero").mkdir() (git_repo / ".loopzero/task.md").write_text(f"Base: {head}\n") - else: + elif base == "tracked": git(git_repo, "update-ref", base_ref, head) config = make_config(inputs={"*": (".",)}) - _save_report(git_repo, sandbox.run_checks(config, git_repo)) + cache_check(config, clean=True, verify_reuse=base != "absent") + if base == "absent": + [result] = sandbox.run_checks(config, git_repo).results + assert (result.exit_code, result.input_key, result.reused_from) == (0, None, None) + return assert _current_check_report(git_repo, config, head) is not None - assert sandbox.run_checks(config, git_repo).results[0].reused_from == head tree = git(git_repo, "rev-parse", "HEAD^{tree}").strip() new_base = git(git_repo, "commit-tree", tree, "-p", head, "-m", "advance base").strip() @@ -883,12 +875,10 @@ def test_local_check_reuse_tracks_base_at_same_head(git_repo, bwrap_log, recorde assert (report.results[0].reused_from, _current_check_report(git_repo, config, head)) == (None, None) -def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fetched_base): +def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fetched_base, receipt_path): marker = "CHECK_INTEGRATION_SHARD []" command = f"echo '{marker}'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) - with (git_repo / ".git/info/exclude").open("a") as stream: - stream.write("\n.loopzero/\n") original = sandbox.run_checks(config, git_repo) assert original.ok legacy = replace(original.results[0], tail=f"{'x' * 20_000}\n{marker}") @@ -897,7 +887,7 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe git(git_repo, "commit", "--allow-empty", "-m", "advance head") _save_report(git_repo, sandbox.run_checks(config, git_repo)) - receipt = json.loads((git_repo / ".loopzero/checks.json").read_text()) + receipt = json.loads(receipt_path.read_text()) assert receipt["head"] == git(git_repo, "rev-parse", "HEAD").strip() [result] = receipt["results"] assert result["reused_from"] == original.head @@ -938,16 +928,6 @@ def fail_fingerprint(argv, **kwargs): assert saved.get("input_key") is None and saved.get("reused_from") is None -def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log, cache_check): - config = make_config(inputs={"*": (".",)}) - cache_check(config) - - second = sandbox.run_checks(config, git_repo) - assert second.ok - assert second.results[0].input_key is None - assert second.results[0].reused_from is None - - @pytest.mark.parametrize('symlink', [False, True]) def test_tracked_forged_receipt_runs_failing_stage(git_repo, bwrap_log, fetched_base, symlink): from loopzero.types import CheckReport, CheckResult diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 838ea563..3b65536d 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -41,11 +41,12 @@ def test_git_fixture_ignores_inherited_directory(tmp_path, monkeypatch): assert (checkout / ".git").is_dir() and not ambient.exists() -def test_branch_preserves_unicode_whitespace(repo: Path) -> None: - name = worktree.branch_name(repo, "zażółć\u00a0") +@pytest.mark.parametrize("slug", ["zażółć\u00a0", "ok-1.2_x"]) +def test_branch_round_trips_valid_names(repo: Path, slug: str) -> None: + name = worktree.branch_name(repo, slug) git(repo, "switch", "-c", name) - assert worktree.branch(repo) == "lz/zażółć\u00a0" + assert worktree.branch(repo) == f"lz/{slug}" def test_branch_refuses_detached_head(repo: Path) -> None: @@ -175,32 +176,25 @@ def interleave(fd, rules): assert exclude.read_text().count(".worktrees/") == 1 -def test_start_refuses_existing_branch(repo: Path) -> None: - git(repo, "branch", "lz/dup") - with pytest.raises(worktree.WorktreeError, match="branch already exists"): +@pytest.mark.parametrize("collision", ["branch", "directory"]) +def test_start_refuses_an_existing_task_destination(repo: Path, collision: str) -> None: + path = repo / ".worktrees" / "dup" + if collision == "branch": + git(repo, "branch", "lz/dup") + else: + path.mkdir(parents=True) + with pytest.raises(worktree.WorktreeError, match=f"{collision} already exists"): worktree.start(repo, "dup", "main") - assert not (repo / ".worktrees" / "dup").exists() + assert path.exists() == (collision == "directory") -def test_start_refuses_existing_directory(repo: Path) -> None: - (repo / ".worktrees" / "dup").mkdir(parents=True) - with pytest.raises(worktree.WorktreeError, match="directory already exists"): - worktree.start(repo, "dup", "main") - - -@pytest.mark.parametrize("slug", ["../escape", "a/b", "bad..name", "trail.lock", "sp ace", ""]) +@pytest.mark.parametrize("slug", ["../escape", "a/b", "bad..name", "trail.lock", "sp ace", "has~tilde", ""]) def test_start_rejects_bad_slug(repo: Path, slug: str) -> None: with pytest.raises(worktree.WorktreeError, match="invalid slug"): worktree.start(repo, slug, "main") assert not (repo / ".worktrees").exists(), "rejected before fetch or worktree add" -def test_branch_name_uses_git_check_ref_format(repo: Path) -> None: - assert worktree.branch_name(repo, "ok-1.2_x") == "lz/ok-1.2_x" - with pytest.raises(worktree.WorktreeError): - worktree.branch_name(repo, "has~tilde") - - @pytest.mark.parametrize("change", [("remove", "origin"), ("rename", "origin", "upstream")]) def test_start_explains_missing_origin(repo: Path, change: tuple[str, ...]) -> None: git(repo, "remote", *change)