11import json
2- import threading
2+ import os
3+ from concurrent .futures import ThreadPoolExecutor
34import time
45from unittest .mock import patch
56
@@ -64,11 +65,8 @@ def add_item(number):
6465 items .append (Item (id = str (number ), name = f"item { number } " ))
6566 repo ._save_all (items )
6667
67- threads = [threading .Thread (target = add_item , args = (n ,)) for n in range (8 )]
68- for thread in threads :
69- thread .start ()
70- for thread in threads :
71- thread .join ()
68+ with ThreadPoolExecutor (max_workers = 8 ) as executor :
69+ list (executor .map (add_item , range (8 ))) # list() re-raises any error from a thread
7270
7371 assert len (JsonRepository (file_path , Item )._load_all ()) == 8
7472
@@ -94,3 +92,37 @@ def test_save_that_fails_while_writing_json_leaves_no_temp_file(tmp_path, error)
9492
9593 assert repo ._load_all () == [Item (id = "1" , name = "original" )]
9694 assert list (tmp_path .glob ("*.tmp" )) == []
95+
96+
97+ def test_save_retries_when_the_file_is_briefly_locked (tmp_path ):
98+ # Windows refuses os.replace while another program has the file open for a moment
99+ repo = JsonRepository (tmp_path / "items.json" , Item )
100+ real_replace = os .replace
101+ calls = []
102+
103+ def locked_twice (src , dst ):
104+ calls .append (src )
105+ if len (calls ) <= 2 :
106+ raise PermissionError ("file is in use" )
107+ real_replace (src , dst )
108+
109+ with patch ("backend.app.repositories.json_repository.os.replace" , side_effect = locked_twice ), \
110+ patch ("backend.app.repositories.json_repository.time.sleep" ):
111+ repo ._save_all ([Item (id = "1" , name = "saved" )])
112+
113+ assert len (calls ) == 3
114+ assert repo ._load_all () == [Item (id = "1" , name = "saved" )]
115+
116+
117+ def test_save_gives_up_after_too_many_attempts (tmp_path ):
118+ repo = JsonRepository (tmp_path / "items.json" , Item )
119+ repo ._save_all ([Item (id = "1" , name = "original" )])
120+
121+ with patch ("backend.app.repositories.json_repository.os.replace" , side_effect = PermissionError ("file is in use" )) as replace , \
122+ patch ("backend.app.repositories.json_repository.time.sleep" ):
123+ with pytest .raises (OSError , match = "Failed to save" ):
124+ repo ._save_all ([Item (id = "2" , name = "new" )])
125+
126+ assert replace .call_count == 5
127+ assert repo ._load_all () == [Item (id = "1" , name = "original" )]
128+ assert list (tmp_path .glob ("*.tmp" )) == []
0 commit comments