|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from prime_rl.trainer.rl import token_export |
| 6 | +from prime_rl.trainer.rl.token_export import _mkdir_existing_dir_ok |
| 7 | + |
| 8 | + |
| 9 | +def test_mkdir_existing_dir_ok_retries_transient_file_exists( |
| 10 | + tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 11 | +) -> None: |
| 12 | + target = tmp_path / "token_exports" / "step_31" |
| 13 | + original_mkdir = Path.mkdir |
| 14 | + calls = 0 |
| 15 | + |
| 16 | + def flaky_mkdir( |
| 17 | + self: Path, |
| 18 | + mode: int = 0o777, |
| 19 | + parents: bool = False, |
| 20 | + exist_ok: bool = False, |
| 21 | + ) -> None: |
| 22 | + nonlocal calls |
| 23 | + if self == target and calls == 0: |
| 24 | + calls += 1 |
| 25 | + raise FileExistsError(str(self)) |
| 26 | + original_mkdir(self, mode=mode, parents=parents, exist_ok=exist_ok) |
| 27 | + |
| 28 | + def create_dir_during_retry(_: float) -> None: |
| 29 | + original_mkdir(target, parents=True, exist_ok=True) |
| 30 | + |
| 31 | + monkeypatch.setattr(Path, "mkdir", flaky_mkdir) |
| 32 | + monkeypatch.setattr(token_export.time, "sleep", create_dir_during_retry) |
| 33 | + |
| 34 | + _mkdir_existing_dir_ok(target) |
| 35 | + |
| 36 | + assert target.is_dir() |
| 37 | + assert calls == 1 |
| 38 | + |
| 39 | + |
| 40 | +def test_mkdir_existing_dir_ok_raises_when_path_is_file( |
| 41 | + tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 42 | +) -> None: |
| 43 | + target = tmp_path / "token_exports" / "step_31" |
| 44 | + target.parent.mkdir(parents=True) |
| 45 | + target.write_text("not a directory", encoding="utf-8") |
| 46 | + monkeypatch.setattr(token_export.time, "sleep", lambda _: None) |
| 47 | + |
| 48 | + with pytest.raises(FileExistsError): |
| 49 | + _mkdir_existing_dir_ok(target) |
0 commit comments