Skip to content

Commit 944d41c

Browse files
committed
Prevent race condition
1 parent f9de4c9 commit 944d41c

File tree

1 file changed

+20
-16
lines changed

1 file changed

+20
-16
lines changed

mypy/test/testutil.py

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Iterator, List, Tuple
1+
from typing import Iterator, List, Tuple, IO
22
import time
33
import os
44
import sys
@@ -13,16 +13,6 @@
1313
WIN32 = sys.platform.startswith("win")
1414

1515

16-
def lock_file(filename: str, duration: float) -> Thread:
17-
"""Open a file and keep it open in a background thread for duration sec."""
18-
def _lock_file() -> None:
19-
with open(filename):
20-
time.sleep(duration)
21-
t = Thread(target=_lock_file, daemon=True)
22-
t.start()
23-
return t
24-
25-
2616
@skipUnless(WIN32, "only relevant for Windows")
2717
class WindowsReplace(TestCase):
2818
tmpdir = tempfile.TemporaryDirectory(prefix='mypy-test-',
@@ -34,6 +24,18 @@ class WindowsReplace(TestCase):
3424

3525
threads = [] # type: List[Thread]
3626

27+
@classmethod
28+
def close_file_later(cls, file: IO, after: float) -> Thread:
29+
"""Open a file and keep it open in a background thread for duration sec."""
30+
def _close_file_later() -> None:
31+
time.sleep(after)
32+
file.close()
33+
34+
t = Thread(target=_close_file_later, daemon=True)
35+
cls.threads.append(t)
36+
t.start()
37+
return t
38+
3739
@classmethod
3840
def tearDownClass(cls) -> None:
3941
# Need to wait for threads to complete, otherwise we'll get PermissionError
@@ -52,12 +54,14 @@ def prepare_src_dest(self, src_lock_duration: float, dest_lock_duration: float
5254
src = os.path.join(self.tmpdir.name, random_string())
5355
dest = os.path.join(self.tmpdir.name, random_string())
5456

55-
for fname in (src, dest):
56-
with open(fname, 'w') as f:
57-
f.write(fname)
57+
for fname, duration in zip((src, dest), (src_lock_duration, dest_lock_duration)):
58+
f = open(fname, 'w')
59+
f.write(fname)
60+
if duration:
61+
self.close_file_later(f, duration)
62+
else:
63+
f.close()
5864

59-
self.threads.append(lock_file(src, src_lock_duration))
60-
self.threads.append(lock_file(dest, dest_lock_duration))
6165
return src, dest
6266

6367
def replace_ok(self, src_lock_duration: float, dest_lock_duration: float,

0 commit comments

Comments
 (0)