okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f9bfe8bc1
main
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 ): 18def setUp (self )-> None : 19self .tmp = Path (tempfile .mkdtemp (prefix = "strata-atomic-" )) 20 21def test_plain_replace (self ): 22 (self .tmp / "a.tmp" ).write_text ("new" ) 23 (self .tmp / "a" ).write_text ("old" ) 24atomic .replace (self .tmp / "a.tmp" ,self .tmp / "a" ) 25self .assertEqual ((self .tmp / "a" ).read_text (),"new" ) 26 27def test_a_held_file_is_waited_for_on_windows_and_the_error_is_kept_elsewhere (self ): 28real = os .replace 29calls = {"n" :0 } 30 31def held (src ,dst ): 32calls ["n" ]+= 1 33if calls ["n" ]< 4 : 34raise PermissionError (5 ,"Access is denied" ) 35return real (src ,dst ) 36 37 (self .tmp / "b.tmp" ).write_text ("new" ) 38slept = [] 39with mock .patch ("os.replace" ,held ),mock .patch .object (atomic .os ,"name" ,"nt" ): 40atomic .replace (self .tmp / "b.tmp" ,self .tmp / "b" ,sleep = slept .append ) 41self .assertEqual (calls ["n" ],4 ) 42self .assertEqual (len (slept ),3 ) 43self .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" ) 46with mock .patch ("os.replace" ,side_effect = PermissionError (13 ,"denied" )),mock .patch .object (atomic .os ,"name" ,"posix" ): 47with self .assertRaises (PermissionError ): 48atomic .replace (self .tmp / "c.tmp" ,self .tmp / "c" ) 49 50def test_a_file_that_stays_held_is_given_up_on_after_the_patience (self ): 51now = [0.0 ] 52with mock .patch ("os.replace" ,side_effect = PermissionError (5 ,"Access is denied" )),mock .patch .object (atomic .os ,"name" ,"nt" ): 53with self .assertRaises (PermissionError ): 54atomic .replace ("x" ,"y" ,patience = 1.0 ,sleep = lambda s :now .__setitem__ (0 ,now [0 ]+ 0.5 ),clock = lambda :now [0 ]) 55 56def test_write_text_leaves_no_temporary_file (self ): 57atomic .write_text (self .tmp / "run.json" ,"{}" ) 58self .assertEqual (sorted (p .name for p in self .tmp .iterdir ()), ["run.json" ]) 59 60 61if __name__ == "__main__" : 62unittest .main ()