"""Tests for the shared atomic-write utility (afk_developer/fsutil.py). Session 2 dedup (docs/refactor-handoffs/02-dedup.md Task 3.1): this consolidates three hand-duplicated NamedTemporaryFile-then-replace implementations (cli.py::_save_plan, campaign_store.py::CampaignStore.save, config.py::save_user_config). Only cli.py's had the Windows PermissionError retry/backoff before; campaign_store.py and config.py deliberately gain it now. """ from pathlib import Path from afk_developer import fsutil def test_atomic_write_text_creates_parent_directories(tmp_path: Path) -> None: target = tmp_path / "nested" / "dir" / "file.json" fsutil.atomic_write_text(target, '{"a": 1}') assert target.read_text(encoding="utf-8") == '{"a": 1}' def test_atomic_write_text_leaves_prior_contents_untouched_on_a_crash_mid_write( tmp_path: Path, monkeypatch ) -> None: target = tmp_path / "state.json" fsutil.atomic_write_text(target, "original") def _boom(*_args, **_kwargs): raise RuntimeError("simulated crash mid-write") monkeypatch.setattr(fsutil, "NamedTemporaryFile", _boom) try: fsutil.atomic_write_text(target, "should never land") except RuntimeError: pass assert target.read_text(encoding="utf-8") == "original" assert not list(tmp_path.glob("tmp*")) def test_atomic_write_text_retries_through_a_transient_windows_permission_error( tmp_path: Path, monkeypatch ) -> None: target = tmp_path / "state.json" real_replace = Path.replace calls = {"count": 0} def _flaky_replace(self, dest): calls["count"] += 1 if calls["count"] == 1: raise PermissionError("[WinError 5] Access is denied (simulated)") return real_replace(self, dest) monkeypatch.setattr(Path, "replace", _flaky_replace) monkeypatch.setattr(fsutil.time, "sleep", lambda _seconds: None) fsutil.atomic_write_text(target, "written after one retry") assert target.read_text(encoding="utf-8") == "written after one retry" assert calls["count"] == 2 def test_atomic_write_text_reraises_after_exhausting_retry_attempts( tmp_path: Path, monkeypatch ) -> None: target = tmp_path / "state.json" def _always_denied(self, dest): raise PermissionError("[WinError 5] Access is denied (simulated)") monkeypatch.setattr(Path, "replace", _always_denied) monkeypatch.setattr(fsutil.time, "sleep", lambda _seconds: None) try: fsutil.atomic_write_text(target, "never lands") raised = False except PermissionError: raised = True assert raised def test_campaign_store_save_now_retries_through_a_transient_permission_error( tmp_path: Path, monkeypatch ) -> None: """Deliberate behavior gain (Task 3.1): CampaignStore.save previously used a bare .replace() with no Windows PermissionError retry -- it now shares fsutil's retry-hardened atomic write.""" from afk_developer.campaign_models import CampaignState from afk_developer.campaign_store import CampaignStore store = CampaignStore(tmp_path / "state") state = CampaignState( name="example", project_dir=tmp_path, root_goal="Improve the target project through small verified batches.", ) real_replace = Path.replace calls = {"count": 0} def _flaky_replace(self, dest): calls["count"] += 1 if calls["count"] == 1: raise PermissionError("[WinError 5] Access is denied (simulated)") return real_replace(self, dest) monkeypatch.setattr(Path, "replace", _flaky_replace) monkeypatch.setattr(fsutil.time, "sleep", lambda _seconds: None) saved_path = store.save(state) assert saved_path.exists() assert calls["count"] == 2 def test_save_user_config_now_retries_through_a_transient_permission_error( tmp_path: Path, monkeypatch ) -> None: """Deliberate behavior gain (Task 3.1): save_user_config previously used a bare .replace() with no Windows PermissionError retry -- it now shares fsutil's retry-hardened atomic write.""" from afk_developer.config import save_user_config target = tmp_path / "config.yml" monkeypatch.setenv("AFK_CONFIG_PATH", str(target)) real_replace = Path.replace calls = {"count": 0} def _flaky_replace(self, dest): calls["count"] += 1 if calls["count"] == 1: raise PermissionError("[WinError 5] Access is denied (simulated)") return real_replace(self, dest) monkeypatch.setattr(Path, "replace", _flaky_replace) monkeypatch.setattr(fsutil.time, "sleep", lambda _seconds: None) result_path = save_user_config({"endpoints": {"copilot": {"type": "copilot"}}}) assert result_path == target assert calls["count"] == 2