okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-agent3 c99896ae6 (status, goal and time-skip events and backend, time-skip keepalive and stop, atomic.py) into f-split-intf9bfe8bc1

main
2.4 KiB62 linesraw
1"""atomic.replace: a file another program is reading is waited for, not failed on (Windows "Access is denied")."""
2
3from __future__ import annotations
4
5import os
6import sys
7import tempfile
8import unittest
9from pathlib import Path
10from unittest import mock
11
12sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
13
14from strata_control import atomic  # noqa: E402
15
16
17class TestReplace(unittest.TestCase):
18    def setUp(self) -> None:
19        self.tmp = Path(tempfile.mkdtemp(prefix="strata-atomic-"))
20
21    def test_plain_replace(self):
22        (self.tmp / "a.tmp").write_text("new")
23        (self.tmp / "a").write_text("old")
24        atomic.replace(self.tmp / "a.tmp", self.tmp / "a")
25        self.assertEqual((self.tmp / "a").read_text(), "new")
26
27    def test_a_held_file_is_waited_for_on_windows_and_the_error_is_kept_elsewhere(self):
28        real = os.replace
29        calls = {"n": 0}
30
31        def held(src, dst):
32            calls["n"] += 1
33            if calls["n"] < 4:
34                raise PermissionError(5, "Access is denied")
35            return real(src, dst)
36
37        (self.tmp / "b.tmp").write_text("new")
38        slept = []
39        with mock.patch("os.replace", held), mock.patch.object(atomic.os, "name", "nt"):
40            atomic.replace(self.tmp / "b.tmp", self.tmp / "b", sleep=slept.append)
41        self.assertEqual(calls["n"], 4)
42        self.assertEqual(len(slept), 3)
43        self.assertEqual((self.tmp / "b").read_text(), "new")
44        # on a system without this behaviour a PermissionError is a real error
45        (self.tmp / "c.tmp").write_text("x")
46        with mock.patch("os.replace", side_effect=PermissionError(13, "denied")), mock.patch.object(atomic.os, "name", "posix"):
47            with self.assertRaises(PermissionError):
48                atomic.replace(self.tmp / "c.tmp", self.tmp / "c")
49
50    def test_a_file_that_stays_held_is_given_up_on_after_the_patience(self):
51        now = [0.0]
52        with mock.patch("os.replace", side_effect=PermissionError(5, "Access is denied")), mock.patch.object(atomic.os, "name", "nt"):
53            with self.assertRaises(PermissionError):
54                atomic.replace("x", "y", patience=1.0, sleep=lambda s: now.__setitem__(0, now[0] + 0.5), clock=lambda: now[0])
55
56    def test_write_text_leaves_no_temporary_file(self):
57        atomic.write_text(self.tmp / "run.json", "{}")
58        self.assertEqual(sorted(p.name for p in self.tmp.iterdir()), ["run.json"])
59
60
61if __name__ == "__main__":
62    unittest.main()