import importlib.util from pathlib import Path from types import ModuleType, SimpleNamespace from unittest.mock import Mock import pytest @pytest.fixture def track(monkeypatch: pytest.MonkeyPatch) -> ModuleType: script = Path(__file__).resolve().parents[2] / "scripts/reconcile_track.py" spec = importlib.util.spec_from_file_location("reconcile_measurements", script) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module @pytest.mark.parametrize( ("disturbed", "quiet", "accepted", "discarded"), [ ([False], True, True, 0), ([True, False], True, True, 1), ([True, True], True, False, 2), ([True], False, False, 1), ], ) def test_only_clean_measurements_are_accepted( track: ModuleType, monkeypatch: pytest.MonkeyPatch, *, disturbed: list[bool], quiet: bool, accepted: bool, discarded: int, ) -> None: reports = [{"cost": {"cpu_seconds": 1}, "attempt": i} for i in range(len(disturbed))] monkeypatch.setattr(track, "sample", lambda: None) monkeypatch.setattr(track, "reconcile", Mock(side_effect=reports)) monkeypatch.setattr(track, "screen", Mock(side_effect=[{"disturbed": d} for d in disturbed])) monkeypatch.setattr(track, "wait_quiet", lambda *_: quiet) chosen, rejected = track.measure([], {}, SimpleNamespace(retries=1), set()) assert (chosen is not None) == accepted assert len(rejected) == discarded assert all(r["screen"]["disturbed"] for r in rejected) if chosen is not None: assert not chosen["screen"]["disturbed"] assert chosen not in rejected def test_existing_series_is_preserved_before_docker_access( track: ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: monkeypatch.setenv("RECONCILE_EVIDENCE_DIR", str(tmp_path)) folder = tmp_path / "cost" folder.mkdir() raw = folder / "n1000-shallow-1.json" raw.write_text("previous evidence") query = Mock(side_effect=AssertionError("must not access the stand")) monkeypatch.setattr(track, "psql", query) with pytest.raises(FileExistsError): track.cost(SimpleNamespace(sizes=[1000])) assert raw.read_text() == "previous evidence" query.assert_not_called() def test_quiet_deadline_is_not_success(track: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(track.time, "monotonic", lambda: 10) assert not track.wait_quiet(SimpleNamespace(quiet_timeout=0), set())