Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions tests/test_file_mode_extra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Additional unit tests for tools/file_mode.py (probe retry, exhaustion, fallback)."""

from __future__ import annotations

import stat
import sys
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import mock

REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO / "tools"))

import file_mode # noqa: E402


class TestFileModeExtra(unittest.TestCase):
def test_new_file_mode_retries_with_a_fresh_probe_name_after_a_collision(self) -> None:
with TemporaryDirectory() as tmp:
taken = Path(tmp) / ".mode-aaaa.probe"
taken.write_bytes(b"sentinel")
# A real collision: the first name exists, the second does not. A retry that reused the
# first name would exhaust its attempts on the same file and raise.
with mock.patch.object(file_mode.secrets, "token_hex", side_effect=["aaaa", "bbbb"]) as names:
mode = file_mode.new_file_mode(tmp)
self.assertEqual(names.call_count, 2)
self.assertEqual(mode & ~0o777, 0)
self.assertEqual(taken.read_bytes(), b"sentinel")
self.assertEqual([p.name for p in Path(tmp).iterdir()], [".mode-aaaa.probe"])

def test_new_file_mode_raises_after_exhausting_retries(self) -> None:
with TemporaryDirectory() as tmp:
with mock.patch.object(file_mode.os, "open", side_effect=FileExistsError("always collides")):
with self.assertRaises(FileExistsError):
file_mode.new_file_mode(tmp)

def test_published_mode_falls_back_when_target_missing(self) -> None:
with TemporaryDirectory() as tmp:
missing = Path(tmp) / "new_output.json"
with mock.patch.object(file_mode, "new_file_mode", return_value=0o640) as new_mode:
mode = file_mode.published_mode(str(missing))
# A missing target gets a new file's mode, probed in the target's own directory.
self.assertEqual(mode, 0o640)
new_mode.assert_called_once_with(file_mode.os.path.dirname(file_mode.os.path.abspath(str(missing))))

def test_published_mode_keeps_the_mode_of_the_file_it_replaces(self) -> None:
with TemporaryDirectory() as tmp:
existing = Path(tmp) / "output.json"
existing.write_text("{}", encoding="utf-8", newline="\n")
with mock.patch.object(file_mode, "new_file_mode", side_effect=AssertionError("must not probe")):
mode = file_mode.published_mode(str(existing))
self.assertEqual(mode, stat.S_IMODE(existing.stat().st_mode))


if __name__ == "__main__":
unittest.main()