import sys from pathlib import Path import pytest from afk_developer.campaign_models import ClosureMetric from afk_developer.closure_metric import ( ClosureMetricError, measure_closure_metric, parse_metric_output, record_measurement, resolve_metric_command, ) from afk_developer.environment import _normalize_interpreter def _metric(command: str, **overrides) -> ClosureMetric: return ClosureMetric(name="remaining", command=command, **overrides) def _python_metric(script: str) -> ClosureMetric: return _metric(f'"{sys.executable}" -c "{script}"') def test_measure_returns_the_single_integer_the_command_prints(tmp_path: Path) -> None: assert measure_closure_metric(_python_metric("print(12)"), tmp_path) == 12 def test_measure_runs_from_the_project_root(tmp_path: Path) -> None: (tmp_path / "count.txt").write_text("5", encoding="utf-8") metric = _python_metric("import pathlib;print(pathlib.Path('count.txt').read_text())") assert measure_closure_metric(metric, tmp_path) == 5 def test_measure_fails_closed_on_a_nonzero_exit(tmp_path: Path) -> None: with pytest.raises(ClosureMetricError, match="exited 3"): measure_closure_metric(_python_metric("raise SystemExit(3)"), tmp_path) def test_measure_fails_closed_on_a_timeout(tmp_path: Path) -> None: metric = _python_metric("import time;time.sleep(5)") with pytest.raises(ClosureMetricError, match="timed out"): measure_closure_metric(metric, tmp_path, timeout=1) @pytest.mark.parametrize( ("stdout", "message"), [ ("", "exactly one integer line"), ("12\n13\n", "exactly one integer line"), ("twelve\n", "non-integer"), ("12 guards\n", "non-integer"), ], ) def test_parse_rejects_anything_but_one_integer(stdout: str, message: str) -> None: with pytest.raises(ClosureMetricError, match=message): parse_metric_output(_metric("x"), stdout) def test_parse_tolerates_surrounding_blank_lines_and_whitespace() -> None: assert parse_metric_output(_metric("x"), "\n\n -3 \n\n") == -3 def test_python_placeholder_resolves_to_the_explicit_target_interpreter(tmp_path: Path) -> None: command = resolve_metric_command( _metric('{python} -c "print(1)"'), tmp_path, target_python=sys.executable ) # Absolutised, never resolved: resolving a venv interpreter through its # symlink would run {python} outside the venv the target depends on. assert command == f'"{_normalize_interpreter(sys.executable)}" -c "print(1)"' assert measure_closure_metric(_metric('{python} -c "print(1)"'), tmp_path, target_python=sys.executable) == 1 def test_python_placeholder_falls_back_to_the_project_venv_only(tmp_path: Path) -> None: metric = _metric('{python} -c "print(1)"') with pytest.raises(ClosureMetricError, match="no target interpreter"): resolve_metric_command(metric, tmp_path) venv_python = tmp_path / ".venv" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") venv_python.parent.mkdir(parents=True) venv_python.write_bytes(b"") assert str(venv_python.resolve()) in resolve_metric_command(metric, tmp_path) def test_commands_without_the_placeholder_are_left_alone(tmp_path: Path) -> None: assert resolve_metric_command(_metric("git status"), tmp_path) == "git status" def test_record_measurement_pins_the_start_value_once() -> None: metric = _metric("x") record_measurement(metric, 78, at_start=True) record_measurement(metric, 12) assert metric.start_value == 78 assert metric.last_value == 12 assert metric.last_measured_at is not None def test_python_placeholder_keeps_a_symlinked_venv_interpreter(tmp_path) -> None: """{python} must not be resolved through a venv symlink to the base binary. This resolver serves both closure metrics and task contract commands. Live on the 6502 campaign it substituted /usr/bin/python3.14 for a project venv interpreter, so every contract test failed with "No module named pytest" even though the task's own suite had just passed, and the campaign escalated on its first task. """ base = tmp_path / "base-python" base.write_text("not executed", encoding="utf-8") venv_python = tmp_path / "project" / ".venv" / "bin" / "python" venv_python.parent.mkdir(parents=True) try: venv_python.symlink_to(base) except (OSError, NotImplementedError): # pragma: no cover - platform dependent pytest.skip("This platform cannot create symlinks without elevation.") metric = ClosureMetric(name="contract", command="{python} -m pytest -q") resolved = resolve_metric_command( metric, tmp_path / "project", target_python=venv_python ) assert str(venv_python) in resolved assert str(base) not in resolved