Debian Codegraph @

tests/test_filelock.py

raw
1 from __future__ import annotations
2
3 import errno
4 import inspect
5 import logging
6 import os
7 import subprocess # ruff:ignore[suspicious-subprocess-import] # only the fixed-argument, no-shell run below
8 import sys
9 import threading
10 import time
11 import traceback
12 from concurrent.futures import ThreadPoolExecutor
13 from contextlib import contextmanager
14 from errno import EAGAIN, EINTR, EIO, ENOSPC, ENOSYS, EWOULDBLOCK
15 from inspect import getframeinfo, stack
16 from pathlib import Path, PurePath
17 from stat import S_IMODE, S_IWGRP, S_IWOTH, S_IWUSR, filemode
18 from types import TracebackType
19 from typing import TYPE_CHECKING, Any, Final, Literal, cast
20 from uuid import uuid4
21 from weakref import WeakValueDictionary
22
23 import pytest
24 from capabilities import CAPABILITIES
25
26 from filelock import (
27 BaseFileLock,
28 ContextErrorPolicy,
29 FileLock,
30 SoftFileLock,
31 SoftFileLockProtocolError,
32 StrictSoftFileLock,
33 Timeout,
34 UnixFileLock,
35 WindowsFileLock,
36 lock_descriptor,
37 unlock_descriptor,
38 )
39 from filelock._api import _append_exception_context, _raise_grouped_errors, _registry
40 from tests.capability_marks import (
41 NEEDS_FCNTL,
42 NEEDS_FILE_MODE,
43 NEEDS_PARENT_SYMLINK_COLLAPSE,
44 NEEDS_PROMPT_FINALIZATION,
45 NEEDS_SYMLINK,
46 )
47
48 if sys.version_info >= (3, 11): # pragma: >=3.11 cover
49 from builtins import BaseExceptionGroup, ExceptionGroup # pragma: >=3.11 cover
50 else: # pragma: <3.11 cover
51 from exceptiongroup import BaseExceptionGroup, ExceptionGroup
52
53 if TYPE_CHECKING:
54 from collections.abc import Callable, Iterator
55
56 from pytest_mock import MockerFixture
57
58
59 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
60 @pytest.mark.parametrize("path_type", [str, PurePath, Path])
61 @pytest.mark.parametrize("filename", ["a", "new/b", "new2/new3/c"])
62 def test_simple(
63 lock_type: type[BaseFileLock],
64 path_type: type[str | Path],
65 filename: str,
66 tmp_path: Path,
67 caplog: pytest.LogCaptureFixture,
68 ) -> None:
69 caplog.set_level(logging.DEBUG)
70
71 lock_path = tmp_path / filename
72 lock = lock_type(path_type(lock_path))
73 with lock as locked:
74 assert lock.is_locked
75 assert lock is locked
76 assert not lock.is_locked
77
78 assert caplog.messages == [
79 f"Attempting to acquire lock {id(lock)} on {lock_path}",
80 f"Lock {id(lock)} acquired on {lock_path}",
81 f"Attempting to release lock {id(lock)} on {lock_path}",
82 f"Lock {id(lock)} released on {lock_path}",
83 ]
84 assert [r.levelno for r in caplog.records] == [logging.DEBUG, logging.DEBUG, logging.DEBUG, logging.DEBUG]
85 assert [r.name for r in caplog.records] == ["filelock", "filelock", "filelock", "filelock"]
86 assert logging.getLogger("filelock").level == logging.NOTSET
87
88
89 @contextmanager
90 def make_ro(path: Path) -> Iterator[None]:
91 write = S_IWUSR | S_IWGRP | S_IWOTH
92 path.chmod(path.stat().st_mode & ~write)
93 try:
94 yield
95 finally:
96 path.chmod(path.stat().st_mode | write)
97
98
99 @pytest.fixture
100 def tmp_path_ro(tmp_path: Path) -> Iterator[Path]: # pragma: needs file-mode
101 with make_ro(tmp_path):
102 yield tmp_path
103
104
105 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
106 @NEEDS_FILE_MODE # pragma: needs file-mode
107 @pytest.mark.skipif(
108 sys.platform != "win32" and os.geteuid() == 0,
109 reason="Cannot make a read only file (that the current user: root can't read)",
110 )
111 def test_ro_folder(lock_type: type[BaseFileLock], tmp_path_ro: Path) -> None:
112 lock = lock_type(str(tmp_path_ro / "a"))
113 with pytest.raises(PermissionError, match="Permission denied"):
114 lock.acquire()
115
116
117 @pytest.fixture
118 def tmp_file_ro(tmp_path: Path) -> Iterator[Path]:
119 filename = tmp_path / "a"
120 filename.write_text("")
121 with make_ro(filename):
122 yield filename
123
124
125 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
126 @pytest.mark.skipif(
127 sys.platform != "win32" and os.geteuid() == 0,
128 reason="Cannot make a read only file (that the current user: root can't read)",
129 )
130 def test_ro_file(lock_type: type[BaseFileLock], tmp_file_ro: Path) -> None:
131 lock = lock_type(str(tmp_file_ro))
132 with pytest.raises(PermissionError, match="Permission denied"):
133 lock.acquire()
134
135
136 _WINDOWS_ONLY: Final[pytest.MarkDecorator] = pytest.mark.skipif(sys.platform != "win32", reason="Windows only")
137 _INVALID_DESCRIPTOR_POLL_INTERVALS: Final = (
138 pytest.param(0.0, id="zero"),
139 pytest.param(-0.01, id="negative"),
140 pytest.param(float("nan"), id="nan"),
141 pytest.param(float("inf"), id="positive-infinity"),
142 pytest.param(float("-inf"), id="negative-infinity"),
143 )
144
145
146 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
147 @pytest.mark.parametrize(
148 ("expected_error", "match", "bad_lock_file"),
149 [
150 # WindowsFileLock raises the real Win32 error the NTSTATUS maps to, so accept its wording alongside os.open's.
151 pytest.param(
152 OSError,
153 "No such file or directory:|cannot find the (path|file)|syntax is incorrect|Access is denied",
154 "",
155 id="blank_filename",
156 ),
157 pytest.param(ValueError, "embedded null (byte|character)", "\0", id="null_byte"),
158 # Should be PermissionError on Windows
159 (
160 pytest.param(PermissionError, "Permission denied:", ".", id="current_directory")
161 if sys.platform == "win32"
162 # Should be IsADirectoryError on MacOS and Linux
163 else (
164 pytest.param(IsADirectoryError, "Is a directory", ".", id="current_directory")
165 if sys.platform in {"darwin", "linux"}
166 # Should be some type of OSError at least on other operating systems
167 else pytest.param(OSError, None, ".", id="current_directory")
168 )
169 ),
170 ]
171 + [
172 pytest.param(OSError, "Invalid argument|syntax is incorrect", i, id=f"invalid_{i}", marks=_WINDOWS_ONLY)
173 for i in '<>:"|?*\a'
174 ]
175 + [
176 pytest.param(PermissionError, "Permission denied:", i, id=f"permission_{i}", marks=_WINDOWS_ONLY) for i in "/\\"
177 ],
178 )
179 @pytest.mark.timeout(5) # timeout in case of infinite loop
180 def test_bad_lock_file(
181 lock_type: type[BaseFileLock],
182 expected_error: type[Exception],
183 match: str,
184 bad_lock_file: str,
185 ) -> None:
186 lock = lock_type(bad_lock_file)
187
188 with pytest.raises(expected_error, match=match):
189 lock.acquire()
190
191
192 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
193 def test_nested_context_manager(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
194 lock_path = tmp_path / "a"
195 lock = lock_type(str(lock_path))
196
197 with lock as lock_1:
198 assert lock.is_locked
199 assert lock is lock_1
200
201 with lock as lock_2:
202 assert lock.is_locked
203 assert lock is lock_2
204
205 with lock as lock_3:
206 assert lock.is_locked
207 assert lock is lock_3
208
209 assert lock.is_locked
210 assert lock.is_locked
211 assert not lock.is_locked
212
213
214 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
215 def test_nested_acquire(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
216 lock_path = tmp_path / "a"
217 lock = lock_type(str(lock_path))
218
219 with lock.acquire() as lock_1:
220 assert lock.is_locked
221 assert lock is lock_1
222
223 with lock.acquire() as lock_2:
224 assert lock.is_locked
225 assert lock is lock_2
226
227 with lock.acquire() as lock_3:
228 assert lock.is_locked
229 assert lock is lock_3
230
231 assert lock.is_locked
232 assert lock.is_locked
233 assert not lock.is_locked
234
235
236 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
237 def test_nested_forced_release(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
238 lock_path = tmp_path / "a"
239 lock = lock_type(str(lock_path))
240
241 with lock:
242 assert lock.is_locked
243
244 lock.acquire()
245 assert lock.is_locked
246
247 lock.release(force=True)
248 assert not lock.is_locked
249 assert not lock.is_locked
250
251
252 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
253 def test_nested_contruct(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
254 lock_path = tmp_path / "a"
255
256 with lock_type(str(lock_path), is_singleton=True, timeout=2) as lock_1:
257 assert lock_1.is_locked
258
259 with lock_type(str(lock_path), is_singleton=True, timeout=2) as lock_2:
260 assert lock_2 is lock_1
261 assert lock_2.is_locked
262
263 assert lock_1.is_locked
264
265 assert not lock_1.is_locked
266
267
268 _ExcInfoType = tuple[type[BaseException], BaseException, TracebackType] | tuple[None, None, None]
269
270
271 class ExThread(threading.Thread):
272 def __init__(self, target: Callable[[], None], name: str) -> None:
273 super().__init__(target=target, name=name)
274 self.ex: _ExcInfoType | None = None
275
276 def run(self) -> None:
277 try:
278 super().run()
279 except Exception: # pragma: no cover # a worker that raises fails the test; a healthy run never lands here
280 self.ex = sys.exc_info()
281
282 def join(self, timeout: float | None = None) -> None:
283 super().join(timeout=timeout)
284 if self.ex is not None:
285 raise RuntimeError from self.ex[1] # pragma: no cover # only a worker that raised gets re-raised here
286
287
288 # 100 threads x 100 acquisitions is thousands of lock cycles; the 20s default is tight on a loaded Windows runner.
289 @pytest.mark.timeout(60)
290 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
291 def test_threaded_shared_lock_obj(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
292 if sys.platform == "win32" and lock_type.__name__ == "SoftFileLock": # pragma: win32 cover
293 pytest.skip(
294 "SoftFileLock uses file-existence locking — on Windows, unlink can silently fail under heavy "
295 "thread contention (EACCES from antivirus/indexer), orphaning the lock file with no recovery path"
296 )
297
298 lock_path = tmp_path / "a"
299 lock = lock_type(str(lock_path))
300
301 def thread_work() -> None:
302 for _ in range(100):
303 with lock:
304 assert lock.is_locked
305
306 threads = [ExThread(target=thread_work, name=f"t{i}") for i in range(100)]
307 for thread in threads:
308 thread.start()
309 for thread in threads:
310 thread.join()
311
312 assert not lock.is_locked
313
314
315 @pytest.mark.timeout(60)
316 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
317 def test_threaded_lock_different_lock_obj(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
318 if sys.platform == "win32" and (hasattr(sys, "pypy_version_info") or lock_type.__name__ == "SoftFileLock"):
319 pytest.skip("SoftFileLock on Windows has race conditions under heavy threading") # pragma: win32 cover
320
321 def t_1() -> None:
322 for _ in range(1000):
323 with lock_1:
324 assert lock_1.is_locked
325 assert not lock_2.is_locked
326
327 def t_2() -> None:
328 for _ in range(1000):
329 with lock_2:
330 assert not lock_1.is_locked
331 assert lock_2.is_locked
332
333 lock_path = tmp_path / "a"
334 lock_1, lock_2 = lock_type(str(lock_path)), lock_type(str(lock_path))
335 threads = [(ExThread(t_1, f"t1_{i}"), ExThread(t_2, f"t2_{i}")) for i in range(10)]
336
337 for thread_1, thread_2 in threads:
338 thread_1.start()
339 thread_2.start()
340 for thread_1, thread_2 in threads:
341 thread_1.join()
342 thread_2.join()
343
344 assert not lock_1.is_locked
345 assert not lock_2.is_locked
346
347
348 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
349 def test_timeout(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
350 lock_path = tmp_path / "a"
351 lock_1, lock_2 = lock_type(str(lock_path)), lock_type(str(lock_path))
352
353 lock_1.acquire()
354 assert lock_1.is_locked
355 assert not lock_2.is_locked
356
357 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
358 lock_2.acquire(timeout=0.1)
359 assert not lock_2.is_locked
360 assert lock_1.is_locked
361
362 lock_1.release()
363 assert not lock_1.is_locked
364 assert not lock_2.is_locked
365
366
367 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
368 def test_non_blocking(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
369 lock_path = tmp_path / "a"
370 lock_1, lock_2 = lock_type(str(lock_path)), lock_type(str(lock_path))
371 lock_3 = lock_type(str(lock_path), blocking=False)
372 lock_4 = lock_type(str(lock_path), timeout=0)
373 lock_5 = lock_type(str(lock_path), blocking=False, timeout=-1)
374
375 lock_1.acquire()
376 assert lock_1.is_locked
377 assert not lock_2.is_locked
378 assert not lock_3.is_locked
379 assert not lock_4.is_locked
380 assert not lock_5.is_locked
381
382 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
383 lock_2.acquire(blocking=False)
384 assert not lock_2.is_locked
385 assert lock_1.is_locked
386
387 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
388 lock_3.acquire()
389 assert not lock_3.is_locked
390 assert lock_1.is_locked
391
392 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."), lock_3:
393 pass # pragma: no cover # __enter__ raises Timeout, so the body never runs
394 assert not lock_3.is_locked
395 assert lock_1.is_locked
396
397 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
398 lock_4.acquire()
399 assert not lock_4.is_locked
400 assert lock_1.is_locked
401
402 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."), lock_4:
403 pass # pragma: no cover # __enter__ raises Timeout, so the body never runs
404 assert not lock_4.is_locked
405 assert lock_1.is_locked
406
407 # blocking precedence over timeout
408 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
409 lock_5.acquire()
410 assert not lock_5.is_locked
411 assert lock_1.is_locked
412
413 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."), lock_5:
414 pass # pragma: no cover # __enter__ raises Timeout, so the body never runs
415 assert not lock_5.is_locked
416 assert lock_1.is_locked
417
418 lock_1.release()
419 assert not lock_1.is_locked
420 assert not lock_2.is_locked
421 assert not lock_3.is_locked
422 assert not lock_4.is_locked
423 assert not lock_5.is_locked
424
425
426 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
427 def test_default_timeout(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
428 lock_path = tmp_path / "a"
429 lock_1, lock_2 = lock_type(str(lock_path)), lock_type(str(lock_path), timeout=0.1)
430 assert lock_2.timeout == pytest.approx(0.1)
431
432 lock_1.acquire()
433 assert lock_1.is_locked
434 assert not lock_2.is_locked
435
436 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
437 lock_2.acquire()
438 assert not lock_2.is_locked
439 assert lock_1.is_locked
440
441 lock_2.timeout = 0
442 assert lock_2.timeout == 0
443
444 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
445 lock_2.acquire()
446 assert not lock_2.is_locked
447 assert lock_1.is_locked
448
449 lock_1.release()
450 assert not lock_1.is_locked
451 assert not lock_2.is_locked
452
453
454 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
455 def test_context_release_on_exc(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
456 lock_path = tmp_path / "a"
457 lock = lock_type(str(lock_path))
458
459 try:
460 with lock as lock_1:
461 assert lock is lock_1
462 assert lock.is_locked
463 raise ValueError # ruff:ignore[raise-within-try] # raises inside the block to assert release on exception
464 except ValueError:
465 assert not lock.is_locked
466
467
468 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
469 def test_acquire_release_on_exc(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
470 lock_path = tmp_path / "a"
471 lock = lock_type(str(lock_path))
472
473 try:
474 with lock.acquire() as lock_1:
475 assert lock is lock_1
476 assert lock.is_locked
477 raise ValueError # ruff:ignore[raise-within-try] # raises inside the block to assert release on exception
478 except ValueError:
479 assert not lock.is_locked
480
481
482 @NEEDS_PROMPT_FINALIZATION
483 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
484 def test_del(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
485 lock_path = tmp_path / "a"
486 lock_1, lock_2 = lock_type(str(lock_path)), lock_type(str(lock_path))
487
488 lock_1.acquire()
489 assert lock_1.is_locked
490 assert not lock_2.is_locked
491
492 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
493 lock_2.acquire(timeout=0.1)
494
495 del lock_1
496
497 lock_2.acquire()
498 assert lock_2.is_locked
499
500 lock_2.release()
501
502
503 def test_cleanup_soft_lock(tmp_path: Path) -> None:
504 lock_path = tmp_path / "a"
505
506 with SoftFileLock(lock_path):
507 assert lock_path.exists()
508 assert not lock_path.exists()
509
510
511 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
512 def test_poll_intervall_deprecated(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
513 lock_path = tmp_path / "a"
514 lock = lock_type(str(lock_path))
515
516 with pytest.deprecated_call(match="use poll_interval instead of poll_intervall") as checker:
517 lock.acquire(poll_intervall=0.05)
518 frame_info = getframeinfo(stack()[0][0]) # lineno here is one past the acquire() call above
519 for warning in checker:
520 if warning.filename == frame_info.filename and warning.lineno + 1 == frame_info.lineno: # pragma: no branch
521 break
522 else: # pragma: no cover # the stacklevel=2 warning is always found, so the failure arm never runs
523 pytest.fail("No warnings of stacklevel=2 matching.")
524 # A held lock left to the garbage collector releases at an arbitrary later point on a deferred collector, and its
525 # release logs then land in whichever test is running.
526 lock.release()
527
528
529 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
530 def test_default_poll_interval(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
531 lock_path = tmp_path / "a"
532 lock = lock_type(str(lock_path))
533 assert lock.poll_interval == pytest.approx(0.05)
534
535 lock_2 = lock_type(str(lock_path), poll_interval=0.1)
536 assert lock_2.poll_interval == pytest.approx(0.1)
537
538 lock_2.poll_interval = 0.2
539 assert lock_2.poll_interval == pytest.approx(0.2)
540
541 lock_3 = lock_type(str(lock_path), poll_interval=0)
542 assert lock_3.poll_interval == 0
543 lock_3.poll_interval = 0.0
544 assert lock_3.poll_interval == pytest.approx(0.0)
545
546
547 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
548 def test_poll_interval_used_by_context_manager(
549 lock_type: type[BaseFileLock], tmp_path: Path, mocker: MockerFixture
550 ) -> None:
551 lock_path = tmp_path / "a"
552 lock_1 = lock_type(str(lock_path))
553 lock_2 = lock_type(str(lock_path), timeout=0.2, poll_interval=0.05)
554
555 lock_1.acquire()
556 sleep_mock = mocker.patch("filelock._api.time.sleep")
557 with pytest.raises(Timeout):
558 lock_2.acquire()
559 sleep_mock.assert_called_with(0.05)
560
561 sleep_mock.reset_mock()
562 lock_2.poll_interval = 0.1
563 with pytest.raises(Timeout):
564 lock_2.acquire()
565 sleep_mock.assert_called_with(0.1)
566 lock_1.release()
567
568
569 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
570 def test_poll_interval_acquire_override(lock_type: type[BaseFileLock], tmp_path: Path, mocker: MockerFixture) -> None:
571 lock_path = tmp_path / "a"
572 lock_1 = lock_type(str(lock_path))
573 lock_2 = lock_type(str(lock_path), timeout=0.2, poll_interval=0.05)
574
575 lock_1.acquire()
576 sleep_mock = mocker.patch("filelock._api.time.sleep")
577 with pytest.raises(Timeout):
578 lock_2.acquire(poll_interval=0.15)
579 sleep_mock.assert_called_with(0.15)
580 lock_1.release()
581
582
583 def _set_poll_interval(
584 lock_type: type[BaseFileLock],
585 entry_point: Literal["constructor", "setter", "acquire"],
586 lock: BaseFileLock,
587 value: object,
588 ) -> None:
589 value = cast("float", value)
590 if entry_point == "constructor":
591 lock_type(lock.lock_file, poll_interval=value)
592 elif entry_point == "setter":
593 lock.poll_interval = value
594 else:
595 lock.acquire(poll_interval=value, timeout=0)
596
597
598 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
599 @pytest.mark.parametrize("entry_point", ["constructor", "setter", "acquire"])
600 @pytest.mark.parametrize(
601 ("bad_value", "error_type", "message"),
602 [
603 pytest.param(-1, ValueError, "finite and non-negative", id="negative-int"),
604 pytest.param(-0.5, ValueError, "finite and non-negative", id="negative-float"),
605 pytest.param(float("nan"), ValueError, "finite and non-negative", id="nan"),
606 pytest.param(float("inf"), ValueError, "finite and non-negative", id="positive-infinity"),
607 pytest.param(float("-inf"), ValueError, "finite and non-negative", id="negative-infinity"),
608 pytest.param(True, TypeError, "poll_interval must be", id="true"),
609 pytest.param(False, TypeError, "poll_interval must be", id="false"),
610 pytest.param("5", TypeError, "poll_interval must be", id="string"),
611 ],
612 )
613 def test_poll_interval_rejects_invalid_value(
614 lock_type: type[BaseFileLock],
615 entry_point: Literal["constructor", "setter", "acquire"],
616 bad_value: object,
617 error_type: type[ValueError | TypeError],
618 message: str,
619 tmp_path: Path,
620 ) -> None:
621 lock = lock_type(str(tmp_path / "a"))
622 with pytest.raises(error_type, match=message):
623 _set_poll_interval(lock_type, entry_point, lock, bad_value)
624
625
626 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
627 def test_context_decorator(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
628 lock_path = tmp_path / "a"
629 lock = lock_type(str(lock_path))
630
631 @lock
632 def decorated_method() -> None:
633 assert lock.is_locked
634
635 assert not lock.is_locked
636 decorated_method()
637 assert not lock.is_locked
638
639
640 def test_lock_mode(tmp_path: Path) -> None:
641 lock_path = tmp_path / "a.lock"
642 lock = FileLock(str(lock_path), mode=0o666)
643
644 initial_umask = os.umask(0o022) # pin umask so the resulting permissions are predictable
645 try:
646 lock.acquire()
647 assert lock.is_locked
648
649 assert filemode(lock_path.stat().st_mode) == "-rw-rw-rw-"
650 finally:
651 os.umask(initial_umask)
652
653 lock.release()
654
655
656 def test_lock_mode_soft(tmp_path: Path) -> None:
657 lock_path = tmp_path / "a.lock"
658 lock = SoftFileLock(str(lock_path), mode=0o666)
659
660 initial_umask = os.umask(0o022) # pin umask so the resulting permissions are predictable
661 try:
662 lock.acquire()
663 assert lock.is_locked
664
665 assert filemode(lock_path.stat().st_mode) == ("-rw-rw-rw-" if sys.platform == "win32" else "-rw-r--r--")
666 finally:
667 os.umask(initial_umask)
668
669 lock.release()
670
671
672 def test_umask(tmp_path: Path) -> None:
673 lock_path = tmp_path / "a.lock"
674 lock = FileLock(str(lock_path), mode=0o666)
675
676 initial_umask = os.umask(0)
677 os.umask(initial_umask)
678
679 lock.acquire()
680 assert lock.is_locked
681
682 current_umask = os.umask(0)
683 os.umask(current_umask)
684 assert initial_umask == current_umask
685
686 lock.release()
687
688
689 def test_umask_soft(tmp_path: Path) -> None:
690 lock_path = tmp_path / "a.lock"
691 lock = SoftFileLock(str(lock_path), mode=0o666)
692
693 initial_umask = os.umask(0)
694 os.umask(initial_umask)
695
696 lock.acquire()
697 assert lock.is_locked
698
699 current_umask = os.umask(0)
700 os.umask(current_umask)
701 assert initial_umask == current_umask
702
703 lock.release()
704
705
706 def test_wrong_platform(tmp_path: Path) -> None:
707 assert not inspect.isabstract(UnixFileLock)
708 assert not inspect.isabstract(WindowsFileLock)
709 assert inspect.isabstract(BaseFileLock)
710
711 lock_type = UnixFileLock if sys.platform == "win32" else WindowsFileLock
712 lock = lock_type(tmp_path / "lockfile")
713
714 with pytest.raises(NotImplementedError):
715 lock.acquire()
716 with pytest.raises(NotImplementedError):
717 lock._release()
718
719
720 @NEEDS_FCNTL # pragma: needs fcntl
721 @pytest.mark.filterwarnings("ignore:flock not supported on this filesystem:UserWarning")
722 def test_flock_not_implemented_unix(tmp_path: Path, mocker: MockerFixture) -> None:
723 mocker.patch("fcntl.flock", side_effect=OSError(ENOSYS, "mock error"))
724 lock = FileLock(tmp_path / "a.lock")
725 with lock:
726 assert lock.is_locked
727 assert isinstance(lock, SoftFileLock)
728
729
730 def test_soft_errors(tmp_path: Path, mocker: MockerFixture) -> None:
731 mocker.patch("os.open", side_effect=OSError(ENOSYS, "mock error"))
732 with pytest.raises(OSError, match="mock error"):
733 SoftFileLock(tmp_path / "a.lock").acquire()
734
735
736 def _check_file_read_write(txt_file: Path) -> None:
737 for _ in range(3):
738 uuid = str(uuid4())
739 txt_file.write_text(uuid, encoding="utf-8")
740 assert txt_file.read_text(encoding="utf-8") == uuid
741
742
743 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
744 def test_thrashing_with_thread_pool_passing_lock_to_threads(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
745 def mess_with_file(lock_: BaseFileLock) -> None:
746 with lock_:
747 _check_file_read_write(txt_file)
748
749 lock_file, txt_file = tmp_path / "test.txt.lock", tmp_path / "test.txt"
750 lock = lock_type(lock_file)
751 with ThreadPoolExecutor() as executor:
752 results = [executor.submit(mess_with_file, lock) for _ in range(100)]
753 assert all(r.result() is None for r in results)
754
755
756 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
757 def test_thrashing_with_thread_pool_global_lock(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
758 def mess_with_file() -> None:
759 with lock:
760 _check_file_read_write(txt_file)
761
762 lock_file, txt_file = tmp_path / "test.txt.lock", tmp_path / "test.txt"
763 lock = lock_type(lock_file)
764 with ThreadPoolExecutor() as executor:
765 results = [executor.submit(mess_with_file) for _ in range(100)]
766
767 assert all(r.result() is None for r in results)
768
769
770 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
771 def test_thrashing_with_thread_pool_lock_recreated_in_each_thread(
772 tmp_path: Path,
773 lock_type: type[BaseFileLock],
774 ) -> None:
775 def mess_with_file() -> None:
776 with lock_type(lock_file):
777 _check_file_read_write(txt_file)
778
779 lock_file, txt_file = tmp_path / "test.txt.lock", tmp_path / "test.txt"
780 with ThreadPoolExecutor() as executor:
781 results = [executor.submit(mess_with_file) for _ in range(100)]
782
783 assert all(r.result() is None for r in results)
784
785
786 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
787 def test_lock_can_be_non_thread_local(
788 tmp_path: Path,
789 lock_type: type[BaseFileLock],
790 ) -> None:
791 lock = lock_type(tmp_path / "test.lock", thread_local=False)
792
793 for _ in range(2):
794 thread = threading.Thread(target=lock.acquire, kwargs={"timeout": 2})
795 thread.start()
796 thread.join()
797
798 assert lock.lock_counter == 2
799
800 lock.release(force=True)
801
802
803 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
804 def test_thread_local_setter_visibility(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
805 """Property setters stay per-thread when thread_local=True.
806
807 A ``poll_interval`` set on the constructing thread stays invisible to other threads: ``threading.local`` re-applies
808 the constructor arguments the first time each new thread touches the context, so the reader sees the default.
809 """
810 lock = lock_type(tmp_path / "x.lock", thread_local=True, poll_interval=0.05)
811 lock.poll_interval = 0.5
812
813 observed: list[float] = []
814
815 def read_from_thread() -> None:
816 observed.append(lock.poll_interval)
817
818 t = threading.Thread(target=read_from_thread)
819 t.start()
820 t.join()
821
822 assert observed == [pytest.approx(0.05)]
823
824
825 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
826 def test_non_thread_local_setter_visibility(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
827 """With thread_local=False, property setters are visible across threads."""
828 lock = lock_type(tmp_path / "x.lock", thread_local=False, poll_interval=0.05)
829 lock.poll_interval = 0.5
830
831 observed: list[float] = []
832 t = threading.Thread(target=lambda: observed.append(lock.poll_interval))
833 t.start()
834 t.join()
835
836 assert observed == [pytest.approx(0.5)]
837
838
839 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
840 def test_mode_is_read_only(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
841 """``mode`` has no setter, unlike the other per-thread configuration values.
842
843 Reading it back afterwards separates a missing setter from a missing attribute; no ``match`` because the message
844 differs across interpreters.
845 """
846 lock = lock_type(tmp_path / "x.lock", mode=0o644)
847
848 with pytest.raises(AttributeError):
849 lock.mode = 0o600 # ty: ignore[invalid-assignment] # the absent setter is the contract under test
850
851 assert lock.mode == 0o644
852
853
854 def test_subclass_compatibility(tmp_path: Path) -> None:
855 class MyFileLock(FileLock):
856 def __init__(
857 self,
858 lock_file: str | os.PathLike[str],
859 timeout: float = -1,
860 mode: int = 0o644,
861 thread_local: bool = True,
862 my_param: int = 0,
863 **kwargs: dict[str, Any], # ruff:ignore[unused-method-argument] # matches the base constructor signature; extras are dropped
864 ) -> None:
865 super().__init__(lock_file, timeout, mode, thread_local, is_singleton=True)
866 self.blocking = True
867 self.my_param = my_param
868
869 lock_path = tmp_path / "a"
870 MyFileLock(str(lock_path), my_param=1)
871
872 class MySoftFileLock(SoftFileLock):
873 def __init__(
874 self,
875 lock_file: str | os.PathLike[str],
876 timeout: float = -1,
877 mode: int = 0o644,
878 thread_local: bool = True,
879 my_param: int = 0,
880 **kwargs: dict[str, Any], # ruff:ignore[unused-method-argument] # matches the base constructor signature; extras are dropped
881 ) -> None:
882 super().__init__(lock_file, timeout, mode, thread_local, blocking=True, is_singleton=True)
883 self.my_param = my_param
884
885 MySoftFileLock(str(lock_path), my_param=1)
886
887
888 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
889 def test_singleton_and_non_singleton_locks_are_distinct(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
890 lock_path = tmp_path / "a"
891 lock_1 = lock_type(str(lock_path), is_singleton=False)
892 assert lock_1.is_singleton is False
893
894 lock_2 = lock_type(str(lock_path), is_singleton=True)
895 assert lock_2.is_singleton is True
896 assert lock_2 is not lock_1
897
898
899 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
900 def test_singleton_locks_are_the_same(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
901 lock_path = tmp_path / "a"
902 lock_1 = lock_type(str(lock_path), is_singleton=True)
903
904 lock_2 = lock_type(str(lock_path), is_singleton=True)
905 assert lock_2 is lock_1
906
907
908 def test_singleton_locks_survive_concurrent_first_construction(tmp_path: Path) -> None:
909 # Two threads constructing the same is_singleton=True lock at once must still share one instance. A slow
910 # __init__ widens the window between the cache miss and the store so the race is hit deterministically.
911 lock_path = tmp_path / "a"
912
913 class _SlowLock(SoftFileLock):
914 def __init__(self, lock_file: str, *, is_singleton: bool = True) -> None:
915 time.sleep(0.05)
916 super().__init__(lock_file, is_singleton=is_singleton)
917
918 results: list[BaseFileLock] = []
919 barrier = threading.Barrier(2)
920
921 def build() -> None:
922 barrier.wait()
923 results.append(_SlowLock(str(lock_path), is_singleton=True))
924
925 threads = [threading.Thread(target=build) for _ in range(2)]
926 for thread in threads:
927 thread.start()
928 for thread in threads:
929 thread.join()
930
931 assert results[0] is results[1]
932
933
934 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
935 def test_singleton_locks_are_distinct_per_lock_file(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
936 lock_path_1 = tmp_path / "a"
937 lock_1 = lock_type(str(lock_path_1), is_singleton=True)
938
939 lock_path_2 = tmp_path / "b"
940 lock_2 = lock_type(str(lock_path_2), is_singleton=True)
941 assert lock_1 is not lock_2
942
943
944 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
945 def test_singleton_locks_must_be_initialized_with_the_same_args(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
946 lock_path = tmp_path / "a"
947 args: dict[str, Any] = {"timeout": -1, "mode": 0o644, "thread_local": True, "blocking": True, "poll_interval": 0.05}
948 alternate_args: dict[str, Any] = {
949 "timeout": 10,
950 "mode": 0,
951 "thread_local": False,
952 "blocking": False,
953 "poll_interval": 0.1,
954 }
955
956 lock = lock_type(str(lock_path), is_singleton=True, **args)
957
958 general_msg = "Singleton lock instances cannot be initialized with differing arguments"
959 for arg_name in args:
960 altered_args = args.copy()
961 altered_args[arg_name] = alternate_args[arg_name]
962 with pytest.raises(ValueError, match=general_msg) as exc_info:
963 lock_type(str(lock_path), is_singleton=True, **altered_args)
964 exc_info.match(arg_name) # ensure specific non-matching argument is included in exception text
965 del lock, exc_info
966
967
968 @NEEDS_PROMPT_FINALIZATION
969 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
970 def test_singleton_locks_are_deleted_when_no_external_references_exist(
971 lock_type: type[BaseFileLock],
972 tmp_path: Path,
973 ) -> None:
974 lock_path = tmp_path / "a"
975 lock = lock_type(str(lock_path), is_singleton=True)
976
977 assert lock_type._instances == {str(lock_path): lock}
978 del lock
979 assert lock_type._instances == {}
980
981
982 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
983 def test_singleton_instance_tracking_is_unique_per_subclass(lock_type: type[BaseFileLock]) -> None:
984 class Lock1(lock_type): # ty: ignore[unsupported-base]
985 pass
986
987 class Lock2(lock_type): # ty: ignore[unsupported-base]
988 pass
989
990 assert isinstance(Lock1._instances, WeakValueDictionary)
991 assert isinstance(Lock2._instances, WeakValueDictionary)
992 assert Lock1._instances is not Lock2._instances
993
994
995 def test_singleton_locks_when_inheriting_init_is_called_once(tmp_path: Path) -> None:
996 init_calls = 0
997
998 class MyFileLock(FileLock):
999 def __init__(self, *args: Any, **kwargs: Any) -> None: # ruff:ignore[any-type] # forwards arbitrary constructor arguments to super().__init__
1000 super().__init__(*args, **kwargs)
1001 nonlocal init_calls
1002 init_calls += 1
1003
1004 lock_path = tmp_path / "a"
1005 lock1 = MyFileLock(str(lock_path), is_singleton=True)
1006 lock2 = MyFileLock(str(lock_path), is_singleton=True)
1007
1008 assert lock1 is lock2
1009 assert init_calls == 1
1010
1011
1012 def test_file_lock_positional_argument(tmp_path: Path) -> None:
1013 class FilePathLock(FileLock):
1014 def __init__(self, file_path: str) -> None:
1015 super().__init__(file_path + ".lock")
1016
1017 lock_path = tmp_path / "a"
1018 lock = FilePathLock(str(lock_path))
1019 assert lock.lock_file == str(lock_path) + ".lock"
1020
1021
1022 @pytest.mark.skipif(sys.platform != "win32" and os.geteuid() == 0, reason="root can open a 0o444 file for writing")
1023 @pytest.mark.parametrize("lock_type", [SoftFileLock, FileLock])
1024 def test_readonly_lock_file_with_mtime_zero_raises(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
1025 # acquire() no longer short-circuits the writability check on mtime 0, so a read-only lock file is still rejected.
1026 lock_path = tmp_path / "z.lock"
1027 lock_path.touch()
1028 lock_path.chmod(0o444)
1029 os.utime(lock_path, (0, 0))
1030 try:
1031 with pytest.raises(PermissionError):
1032 lock_type(str(lock_path)).acquire(timeout=0)
1033 finally:
1034 lock_path.chmod(0o644)
1035
1036
1037 @pytest.mark.parametrize("lock_type", [SoftFileLock])
1038 def test_lock_file_removed_after_release(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1039 lock_path = tmp_path / "test.lock"
1040 lock = lock_type(str(lock_path))
1041 with lock:
1042 assert lock_path.exists()
1043 assert not lock_path.exists()
1044
1045
1046 @NEEDS_FCNTL # pragma: needs fcntl
1047 def test_concurrent_acquire_release_keeps_lock_file(tmp_path: Path) -> None:
1048 lock_path = tmp_path / "test.lock"
1049 errors: list[Exception] = []
1050
1051 def worker() -> None:
1052 try:
1053 for _ in range(20):
1054 lock = FileLock(str(lock_path), is_singleton=False)
1055 with lock:
1056 pass
1057 except Exception as exc: # pragma: no cover # a healthy run never raises here
1058 errors.append(exc)
1059
1060 threads = [threading.Thread(target=worker) for _ in range(4)]
1061 for thread in threads:
1062 thread.start()
1063 for thread in threads:
1064 thread.join(timeout=30)
1065 assert not errors, errors
1066 assert lock_path.exists()
1067
1068
1069 @NEEDS_FCNTL # pragma: needs fcntl
1070 def test_lock_acquired_after_release_keeps_path(tmp_path: Path) -> None:
1071 lock_path = tmp_path / "test.lock"
1072 first = FileLock(str(lock_path), is_singleton=False)
1073 second = FileLock(str(lock_path), is_singleton=False)
1074
1075 first.acquire()
1076 assert lock_path.exists()
1077 first.release()
1078 assert lock_path.exists()
1079
1080 second.acquire()
1081 assert lock_path.exists()
1082 second.release()
1083 assert lock_path.exists()
1084
1085
1086 @NEEDS_FCNTL # pragma: needs fcntl
1087 def test_waiter_fd_cannot_split_lock_after_release(tmp_path: Path) -> None:
1088 # typeshed hides fcntl's members off POSIX, so state the invariant the capability gate already enforces.
1089 assert sys.platform != "win32"
1090 import fcntl
1091
1092 lock_path = tmp_path / "test.lock"
1093 first = FileLock(str(lock_path), is_singleton=False)
1094 replacement = FileLock(str(lock_path), is_singleton=False)
1095
1096 first.acquire()
1097 waiter_fd = os.open(lock_path, os.O_RDWR)
1098
1099 try:
1100 first.release()
1101 assert lock_path.exists()
1102
1103 replacement.acquire()
1104 try:
1105 with pytest.raises(BlockingIOError) as exc_info:
1106 fcntl.flock(waiter_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1107 assert exc_info.value.errno in {EAGAIN, EWOULDBLOCK}
1108 finally:
1109 replacement.release()
1110 finally:
1111 os.close(waiter_fd)
1112
1113
1114 @NEEDS_FCNTL # pragma: needs fcntl
1115 def test_stale_inode_retry_on_unlinked_lock(tmp_path: Path, mocker: MockerFixture) -> None:
1116 lock_path = tmp_path / "test.lock"
1117 lock = FileLock(str(lock_path), is_singleton=False)
1118
1119 real_fstat = os.fstat
1120 call_count = 0
1121
1122 def fstat_unlinked_once(fd: int) -> os.stat_result:
1123 nonlocal call_count
1124 call_count += 1
1125 if call_count == 1:
1126 Path(lock_path).unlink()
1127 return real_fstat(fd)
1128 return real_fstat(fd)
1129
1130 mocker.patch("os.fstat", side_effect=fstat_unlinked_once)
1131 lock.acquire()
1132 assert lock.is_locked
1133 assert call_count == 2
1134 lock.release()
1135
1136
1137 @NEEDS_FCNTL # pragma: needs fcntl
1138 def test_permission_error_fallback_without_o_creat(tmp_path: Path, mocker: MockerFixture) -> None:
1139 lock_path = tmp_path / "test.lock"
1140 lock_path.touch()
1141 lock = FileLock(str(lock_path), is_singleton=False)
1142
1143 real_open = os.open
1144 call_count = 0
1145
1146 def open_no_creat(path: str, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int:
1147 nonlocal call_count
1148 call_count += 1
1149 if call_count == 1 and flags & os.O_CREAT:
1150 raise PermissionError(13, "Permission denied", path)
1151 return real_open(path, flags, mode) if dir_fd is None else real_open(path, flags, mode, dir_fd=dir_fd)
1152
1153 mocker.patch("os.open", side_effect=open_no_creat)
1154 lock.acquire()
1155 assert lock.is_locked
1156 assert call_count == 2
1157 lock.release()
1158
1159
1160 @NEEDS_FCNTL # pragma: needs fcntl
1161 def test_permission_error_propagates_when_file_missing(tmp_path: Path, mocker: MockerFixture) -> None:
1162 lock_path = tmp_path / "test.lock"
1163 lock = FileLock(str(lock_path), is_singleton=False)
1164
1165 real_open = os.open
1166
1167 def open_always_permission_error(path: str, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int:
1168 if "test.lock" in path:
1169 raise PermissionError(13, "Permission denied", path)
1170 return ( # pragma: no cover # every os.open during this acquire targets the lock path
1171 real_open(path, flags, mode) if dir_fd is None else real_open(path, flags, mode, dir_fd=dir_fd)
1172 )
1173
1174 mocker.patch("os.open", side_effect=open_always_permission_error)
1175 with pytest.raises(PermissionError, match="Permission denied"):
1176 lock.acquire(timeout=0)
1177
1178
1179 @NEEDS_FCNTL # pragma: needs fcntl
1180 def test_sticky_bit_fallback_handles_concurrent_unlink(tmp_path: Path, mocker: MockerFixture) -> None:
1181 lock_path = tmp_path / "test.lock"
1182 lock_path.touch()
1183 lock = FileLock(str(lock_path), is_singleton=False)
1184
1185 real_open = os.open
1186 denied_create = False
1187 unlinked_open = False
1188
1189 # Key the injections off each open's signature rather than a global call count: GraalPy opens unrelated paths
1190 # mid-acquire, which would shift a counter and land the errors on the wrong opens. Deny the first create, then
1191 # unlink under the first no-create open, so the sticky-bit fallback must retry once more to succeed.
1192 def open_permission_then_unlink(path: str, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int:
1193 nonlocal denied_create, unlinked_open
1194 if not denied_create and flags & os.O_CREAT and "test.lock" in path:
1195 denied_create = True
1196 raise PermissionError(13, "Permission denied", path)
1197 if not unlinked_open and not flags & os.O_CREAT and "test.lock" in path:
1198 unlinked_open = True
1199 lock_path.unlink(missing_ok=True)
1200 raise FileNotFoundError(2, "No such file or directory", path)
1201 return real_open(path, flags, mode) if dir_fd is None else real_open(path, flags, mode, dir_fd=dir_fd)
1202
1203 mocker.patch("os.open", side_effect=open_permission_then_unlink)
1204 lock.acquire()
1205 assert lock.is_locked
1206 assert (denied_create, unlinked_open) == (True, True)
1207 lock.release()
1208
1209
1210 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1211 def test_cancel_check_triggers(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
1212 lock_path = tmp_path / "a"
1213 lock_1 = lock_type(str(lock_path))
1214 lock_2 = lock_type(str(lock_path))
1215
1216 lock_1.acquire()
1217
1218 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
1219 lock_2.acquire(timeout=1, cancel_check=lambda: True)
1220 assert not lock_2.is_locked
1221 lock_1.release()
1222
1223
1224 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1225 def test_cancel_check_after_n_polls(lock_type: type[BaseFileLock], tmp_path: Path, mocker: MockerFixture) -> None:
1226 lock_path = tmp_path / "a"
1227 lock_1 = lock_type(str(lock_path))
1228 lock_2 = lock_type(str(lock_path))
1229
1230 lock_1.acquire()
1231
1232 call_count = 0
1233
1234 def cancel_after_two() -> bool:
1235 nonlocal call_count
1236 call_count += 1
1237 return call_count >= 2
1238
1239 mocker.patch("filelock._api.time.sleep")
1240 with pytest.raises(Timeout):
1241 lock_2.acquire(timeout=10, cancel_check=cancel_after_two)
1242 assert call_count == 2
1243 assert not lock_2.is_locked
1244 lock_1.release()
1245
1246
1247 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1248 def test_cancel_check_not_called_when_lock_available(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
1249 lock_path = tmp_path / "a"
1250 lock = lock_type(str(lock_path))
1251
1252 called = False
1253
1254 def should_not_be_called() -> bool: # pragma: no cover # a free lock never consults cancel_check
1255 nonlocal called
1256 called = True
1257 return True
1258
1259 lock.acquire(cancel_check=should_not_be_called)
1260 assert lock.is_locked
1261 assert not called
1262 lock.release()
1263
1264
1265 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1266 def test_cancel_check_false_allows_acquisition(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
1267 lock_path = tmp_path / "a"
1268 lock = lock_type(str(lock_path))
1269
1270 lock.acquire(cancel_check=lambda: False)
1271 assert lock.is_locked
1272 lock.release()
1273
1274
1275 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1276 def test_cancel_check_log_message(
1277 lock_type: type[BaseFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
1278 ) -> None:
1279 caplog.set_level(logging.DEBUG)
1280 lock_path = tmp_path / "a"
1281 lock_1 = lock_type(str(lock_path))
1282 lock_2 = lock_type(str(lock_path))
1283
1284 lock_1.acquire()
1285 with pytest.raises(Timeout):
1286 lock_2.acquire(timeout=1, cancel_check=lambda: True)
1287 assert any("Cancellation requested" in msg for msg in caplog.messages)
1288 lock_1.release()
1289
1290
1291 @NEEDS_FCNTL # pragma: needs fcntl
1292 def test_filenotfound_on_fuse_nfs_retries(tmp_path: Path, mocker: MockerFixture) -> None:
1293 """Retry recovers from the FUSE/NFS os.open(O_CREAT) race that raises FileNotFoundError."""
1294 lock_path = tmp_path / "test.lock"
1295 lock = FileLock(str(lock_path), is_singleton=False)
1296
1297 real_open = os.open
1298 call_count = 0
1299
1300 def open_enoent_then_succeed(path: str, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int:
1301 nonlocal call_count
1302 call_count += 1
1303 if call_count == 1 and flags & os.O_CREAT and "test.lock" in path: # first O_CREAT hits the FUSE/NFS ENOENT
1304 raise FileNotFoundError(2, "No such file or directory", path)
1305 return real_open(path, flags, mode) if dir_fd is None else real_open(path, flags, mode, dir_fd=dir_fd)
1306
1307 mocker.patch("os.open", side_effect=open_enoent_then_succeed)
1308 lock.acquire()
1309 assert lock.is_locked
1310 assert call_count >= 2
1311 lock.release()
1312
1313
1314 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1315 def test_same_thread_different_instances_raises(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1316 lock_path = tmp_path / "test.lock"
1317 lock1 = lock_type(lock_path)
1318 with lock1:
1319 lock2 = lock_type(lock_path)
1320 with pytest.raises(RuntimeError, match="Deadlock"):
1321 lock2.acquire()
1322
1323
1324 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1325 def test_finite_timeout_gives_timeout_not_deadlock(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1326 lock_path = tmp_path / "test.lock"
1327 lock1 = lock_type(lock_path)
1328 with lock1:
1329 lock2 = lock_type(lock_path, timeout=0.1)
1330 with pytest.raises(Timeout):
1331 lock2.acquire()
1332
1333
1334 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1335 def test_non_blocking_gives_timeout_not_deadlock(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1336 lock_path = tmp_path / "test.lock"
1337 lock1 = lock_type(lock_path)
1338 with lock1:
1339 lock2 = lock_type(lock_path, blocking=False)
1340 with pytest.raises(Timeout):
1341 lock2.acquire()
1342
1343
1344 @pytest.mark.parametrize(
1345 "mode",
1346 [pytest.param("finite", id="finite"), pytest.param("nonblocking", id="nonblocking")],
1347 )
1348 def test_failed_acquire_keeps_holder_registered(tmp_path: Path, mode: Literal["finite", "nonblocking"]) -> None:
1349 lock_path = tmp_path / "test.lock"
1350 with FileLock(lock_path):
1351 with pytest.raises(Timeout):
1352 _acquire_for_mode(FileLock(lock_path), mode)
1353 with pytest.raises(RuntimeError, match="Deadlock"):
1354 FileLock(lock_path).acquire(cancel_check=lambda: True)
1355
1356
1357 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1358 def test_different_paths_no_conflict(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1359 lock1 = lock_type(tmp_path / "a.lock")
1360 lock2 = lock_type(tmp_path / "b.lock")
1361 with lock1, lock2:
1362 assert lock1.is_locked
1363 assert lock2.is_locked
1364
1365
1366 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1367 def test_same_instance_reentrant_works(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1368 lock = lock_type(tmp_path / "test.lock")
1369 with lock:
1370 with lock:
1371 assert lock.is_locked
1372 assert lock.is_locked
1373 assert not lock.is_locked
1374
1375
1376 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1377 def test_singleton_avoids_deadlock(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1378 lock_path = tmp_path / "test.lock"
1379 lock1 = lock_type(lock_path, is_singleton=True)
1380 with lock1:
1381 lock2 = lock_type(lock_path, is_singleton=True)
1382 assert lock1 is lock2
1383 with lock2:
1384 assert lock2.is_locked
1385
1386
1387 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1388 def test_different_threads_no_false_positive(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1389 lock_path = tmp_path / "test.lock"
1390 lock1 = lock_type(lock_path, timeout=0)
1391 lock1.acquire()
1392
1393 error: BaseException | None = None
1394
1395 def acquire_in_thread() -> None:
1396 nonlocal error
1397 lock2 = lock_type(lock_path, timeout=0)
1398 try:
1399 lock2.acquire()
1400 except BaseException as exc:
1401 error = exc
1402
1403 thread = threading.Thread(target=acquire_in_thread)
1404 thread.start()
1405 thread.join()
1406 lock1.release()
1407
1408 assert not isinstance(error, RuntimeError), "Should not raise RuntimeError in different thread"
1409
1410
1411 _NEEDS_O_NOFOLLOW: Final[pytest.MarkDecorator] = pytest.mark.skipif(
1412 not CAPABILITIES["o-nofollow"], reason="refusing to open through a final symlink needs a honored O_NOFOLLOW"
1413 )
1414
1415
1416 @NEEDS_PARENT_SYMLINK_COLLAPSE # pragma: win32 no cover
1417 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1418 def test_symlink_same_canonical_path(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1419 # A symlinked parent directory resolves to the same canonical key (the final component is kept literal, so a final
1420 # symlink stays distinct — see test_final_symlink_stays_a_distinct_key).
1421 real_dir = tmp_path / "real"
1422 real_dir.mkdir()
1423 (tmp_path / "link").symlink_to(real_dir)
1424
1425 lock1 = lock_type(str(real_dir / "test.lock"))
1426 with lock1:
1427 lock2 = lock_type(str(tmp_path / "link" / "test.lock"))
1428 with pytest.raises(RuntimeError, match="Deadlock"):
1429 lock2.acquire()
1430
1431
1432 @NEEDS_PARENT_SYMLINK_COLLAPSE # pragma: win32 no cover
1433 @pytest.mark.parametrize(
1434 ("depth", "force"),
1435 [
1436 pytest.param(1, False, id="direct"),
1437 pytest.param(2, False, id="nested"),
1438 pytest.param(2, True, id="forced"),
1439 ],
1440 )
1441 def test_release_drops_acquisition_key_after_parent_retarget(tmp_path: Path, depth: int, force: bool) -> None:
1442 lock_path, original_path, replacement_path = _symlinked_lock_paths(tmp_path)
1443 lock = FileLock(lock_path)
1444 for _depth in range(depth):
1445 lock.acquire()
1446 _retarget_parent(lock_path, replacement_path)
1447
1448 if force:
1449 lock.release(force=True)
1450 else:
1451 for _depth in range(depth):
1452 lock.release()
1453
1454 with FileLock(original_path) as successor:
1455 assert successor.is_locked
1456
1457
1458 @NEEDS_PARENT_SYMLINK_COLLAPSE # pragma: win32 no cover
1459 def test_release_keeps_retargeted_parent_holder_registered(tmp_path: Path) -> None:
1460 lock_path, _original_path, replacement_path = _symlinked_lock_paths(tmp_path)
1461 original = FileLock(lock_path)
1462 original.acquire()
1463 _retarget_parent(lock_path, replacement_path)
1464 with FileLock(replacement_path):
1465 original.release()
1466 with pytest.raises(RuntimeError, match="Deadlock"):
1467 FileLock(replacement_path).acquire(cancel_check=lambda: True)
1468
1469
1470 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1471 def test_deadlock_registry_cleanup_on_release(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1472 lock_path = tmp_path / "test.lock"
1473 lock1 = lock_type(lock_path)
1474 lock1.acquire()
1475 lock1.release()
1476
1477 lock2 = lock_type(lock_path)
1478 with lock2:
1479 assert lock2.is_locked
1480
1481
1482 @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
1483 def test_force_release_cleans_registry(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
1484 lock_path = tmp_path / "test.lock"
1485 lock1 = lock_type(lock_path)
1486 with lock1:
1487 lock1.acquire()
1488 assert lock1.lock_counter == 2
1489 lock1.release(force=True)
1490
1491 lock2 = lock_type(lock_path)
1492 with lock2:
1493 assert lock2.is_locked
1494
1495
1496 def _symlinked_lock_paths(tmp_path: Path) -> tuple[Path, Path, Path]: # pragma: win32 no cover
1497 original = tmp_path / "original"
1498 replacement = tmp_path / "replacement"
1499 original.mkdir()
1500 replacement.mkdir()
1501 link = tmp_path / "link"
1502 link.symlink_to(original, target_is_directory=True)
1503 return link / "test.lock", original / "test.lock", replacement / "test.lock"
1504
1505
1506 def _retarget_parent(lock_path: Path, replacement_path: Path) -> None: # pragma: win32 no cover
1507 link = lock_path.parent
1508 link.unlink()
1509 link.symlink_to(replacement_path.parent, target_is_directory=True)
1510
1511
1512 def _acquire_for_mode(lock: BaseFileLock, mode: Literal["finite", "nonblocking"]) -> None:
1513 if mode == "finite":
1514 lock.acquire(timeout=0)
1515 else:
1516 lock.acquire(blocking=False)
1517
1518
1519 @pytest.fixture
1520 def held_lock_path(tmp_path: Path) -> Iterator[Path]: # pragma: needs fcntl
1521 path = tmp_path / "resource.lock"
1522 with FileLock(path, timeout=0):
1523 yield path
1524
1525
1526 @NEEDS_FCNTL # pragma: needs fcntl
1527 def test_winner_truncates_stale_content(tmp_path: Path) -> None:
1528 lock_path = tmp_path / "resource.lock"
1529 lock_path.write_text("stale from a previous holder", encoding="utf-8")
1530
1531 with FileLock(lock_path, timeout=0):
1532 assert lock_path.stat().st_size == 0
1533
1534
1535 @NEEDS_FCNTL # pragma: needs fcntl
1536 def test_contender_preserves_holder_contents(held_lock_path: Path) -> None:
1537 held_lock_path.write_text("holder metadata", encoding="utf-8")
1538
1539 with pytest.raises(Timeout):
1540 FileLock(held_lock_path, timeout=0).acquire()
1541
1542 assert held_lock_path.read_text(encoding="utf-8") == "holder metadata"
1543
1544
1545 @NEEDS_FCNTL # pragma: needs fcntl
1546 def test_contender_preserves_holder_mode(held_lock_path: Path) -> None:
1547 held_lock_path.chmod(0o600)
1548
1549 with pytest.raises(Timeout):
1550 FileLock(held_lock_path, timeout=0, mode=0o644).acquire()
1551
1552 assert S_IMODE(held_lock_path.stat().st_mode) == 0o600
1553
1554
1555 @NEEDS_FCNTL # pragma: needs fcntl
1556 def test_contender_does_not_fchmod(held_lock_path: Path, mocker: MockerFixture) -> None:
1557 fchmod_spy = mocker.spy(os, "fchmod")
1558
1559 with pytest.raises(Timeout):
1560 FileLock(held_lock_path, timeout=0, mode=0o644).acquire()
1561
1562 fchmod_spy.assert_not_called()
1563
1564
1565 @NEEDS_FCNTL # pragma: needs fcntl
1566 def test_post_lock_truncate_failure_closes_fd(tmp_path: Path, mocker: MockerFixture) -> None:
1567 mocker.patch("os.ftruncate", side_effect=OSError(ENOSPC, "No space left on device"))
1568 open_spy = mocker.spy(os, "open")
1569 close_spy = mocker.spy(os, "close")
1570
1571 with pytest.raises(OSError, match="No space left on device"):
1572 FileLock(tmp_path / "resource.lock", timeout=0).acquire()
1573
1574 assert any(call.args and call.args[0] == open_spy.spy_return for call in close_spy.call_args_list)
1575
1576
1577 # Only a Windows run that also holds the symlink privilege reaches this body, so both exclusions apply.
1578 @_WINDOWS_ONLY # pragma: win32 cover # pragma: needs symlink
1579 @NEEDS_SYMLINK
1580 def test_windows_reparse_point_lock_file_rejected(tmp_path: Path) -> None:
1581 target = tmp_path / "target.txt"
1582 target.write_text("sensitive", encoding="utf-8")
1583 link = tmp_path / "resource.lock"
1584 link.symlink_to(target)
1585
1586 with pytest.raises(OSError, match="reparse point"):
1587 FileLock(link).acquire()
1588
1589 assert target.read_text(encoding="utf-8") == "sensitive"
1590
1591
1592 def test_release_keeps_lock_until_final_hold(tmp_path: Path) -> None:
1593 lock = FileLock(str(tmp_path / "a"))
1594 lock.acquire()
1595 lock.acquire()
1596 lock.release()
1597 assert lock.is_locked
1598 assert lock.lock_counter == 1
1599 lock.release()
1600 assert not lock.is_locked
1601 assert lock.lock_counter == 0
1602
1603
1604 def test_forced_release_drops_all_holds(tmp_path: Path) -> None:
1605 lock = FileLock(str(tmp_path / "a"))
1606 lock.acquire()
1607 lock.acquire()
1608 lock.release(force=True)
1609 assert not lock.is_locked
1610 assert lock.lock_counter == 0
1611
1612
1613 @NEEDS_FCNTL # pragma: needs fcntl
1614 def test_unix_release_keeps_lock_held_when_unlock_fails(tmp_path: Path, mocker: MockerFixture) -> None:
1615 lock = FileLock(str(tmp_path / "a"))
1616 lock.acquire()
1617 mocker.patch("filelock._unix.fcntl.flock", side_effect=[OSError(EIO, "unlock failed"), None])
1618 with pytest.raises(OSError, match="unlock failed"):
1619 lock.release()
1620 assert lock.is_locked
1621 assert lock.lock_counter == 1
1622 lock.release()
1623 assert not lock.is_locked
1624
1625
1626 @NEEDS_FCNTL # pragma: needs fcntl
1627 def test_unix_context_exit_propagates_unlock_failure(tmp_path: Path, mocker: MockerFixture) -> None:
1628 # One LOCK_EX for acquire, then one LOCK_UN per release; fail only the first unlock so __exit__ propagates it.
1629 mocker.patch("filelock._unix.fcntl.flock", side_effect=[None, OSError(EIO, "unlock failed"), None])
1630 lock = FileLock(str(tmp_path / "a"))
1631 with pytest.raises(OSError, match="unlock failed"), lock:
1632 assert lock.is_locked
1633 assert lock.is_locked
1634 lock.release()
1635 assert not lock.is_locked
1636
1637
1638 @_WINDOWS_ONLY # pragma: win32 cover
1639 def test_windows_release_keeps_lock_held_when_unlock_fails(tmp_path: Path, mocker: MockerFixture) -> None:
1640 lock = FileLock(str(tmp_path / "a"))
1641 lock.acquire()
1642 mocker.patch("filelock._windows._unlock_fd", side_effect=[OSError(EIO, "unlock failed"), None])
1643 with pytest.raises(OSError, match="unlock failed"):
1644 lock.release()
1645 assert lock.is_locked
1646 assert lock.lock_counter == 1
1647 lock.release()
1648 assert not lock.is_locked
1649
1650
1651 @_WINDOWS_ONLY # pragma: win32 cover
1652 def test_windows_close_failure_still_commits_release(tmp_path: Path, mocker: MockerFixture) -> None:
1653 lock = FileLock(str(tmp_path / "a"))
1654 lock.acquire()
1655 # The OS unlock succeeds, so the lock is released; the later close failure propagates but must not leave the
1656 # counter or registry believing the lock is still held.
1657 mocker.patch("filelock._windows.os.close", side_effect=OSError(EIO, "close failed"))
1658 with pytest.raises(OSError, match="close failed"):
1659 lock.release()
1660 assert not lock.is_locked
1661 assert lock.lock_counter == 0
1662
1663
1664 @_WINDOWS_ONLY # pragma: win32 cover
1665 def test_windows_delete_pending_is_treated_as_contention(tmp_path: Path, mocker: MockerFixture) -> None:
1666 mocker.patch("filelock._windows._nt_open", return_value=(0, 0xC0000056)) # STATUS_DELETE_PENDING
1667 with pytest.raises(Timeout):
1668 FileLock(str(tmp_path / "a"), timeout=0.2).acquire()
1669
1670
1671 @_WINDOWS_ONLY # pragma: win32 cover
1672 def test_windows_permanent_denial_raises_without_timeout(tmp_path: Path, mocker: MockerFixture) -> None:
1673 mocker.patch("filelock._windows._ACCESS_DENIED_GRACE", 0.02)
1674 nt_open = mocker.patch("filelock._windows._nt_open", return_value=(0, 0xC0000022)) # STATUS_ACCESS_DENIED
1675 started = time.monotonic()
1676 with pytest.raises(PermissionError):
1677 FileLock(str(tmp_path / "a"), timeout=5).acquire()
1678 # The denial outlasted its grace, so it surfaced after a bounded wait rather than the caller's timeout.
1679 assert 0.02 <= time.monotonic() - started < 5
1680 assert nt_open.call_count > 1
1681
1682
1683 @_WINDOWS_ONLY # pragma: win32 cover
1684 def test_windows_transient_denial_is_retried_within_grace(tmp_path: Path, mocker: MockerFixture) -> None:
1685 # A peer unlinking the lock file as it releases can make NtCreateFile answer STATUS_ACCESS_DENIED for a moment,
1686 # which the open must wait out instead of raising a PermissionError. timeout=0 leaves the acquire loop one attempt,
1687 # so the retry has to come from the open itself. The marker skips the run; the guard only narrows the import for
1688 # ty, so it goes one way.
1689 if sys.platform == "win32": # pragma: no branch
1690 from filelock._windows import _nt_open as real_nt_open
1691
1692 statuses = [0xC0000022]
1693
1694 def deny_once(path: str, *, read_only: bool) -> tuple[int, int]:
1695 if statuses:
1696 return 0, statuses.pop()
1697 return real_nt_open(path, read_only=read_only)
1698
1699 nt_open = mocker.patch("filelock._windows._nt_open", side_effect=deny_once)
1700 lock = FileLock(str(tmp_path / "a"), timeout=0)
1701 lock.acquire()
1702 assert (lock.is_locked, nt_open.call_count) == (True, 2)
1703 lock.release()
1704
1705
1706 @_WINDOWS_ONLY # pragma: win32 cover
1707 def test_windows_delete_in_progress_is_contention_not_denial(tmp_path: Path) -> None:
1708 # The marker skips the run; this only narrows ctypes.windll for ty, so it goes one way.
1709 if sys.platform == "win32": # pragma: no branch
1710 import ctypes
1711
1712 target = str(tmp_path / "dp.lock")
1713 kernel32 = ctypes.windll.kernel32
1714 delete_access, generic_read, share_all, create_always, delete_on_close = (
1715 0x10000,
1716 0x80000000,
1717 0x1 | 0x2 | 0x4,
1718 2,
1719 0x04000000,
1720 )
1721 # Open with delete-on-close so the name is marked for deletion but the live handle keeps it around: a fresh
1722 # open sees the deletion in progress (delete-pending or a sharing violation), which acquire must retry rather
1723 # than mistake for a permanent PermissionError.
1724 handle = kernel32.CreateFileW(
1725 target, delete_access | generic_read, share_all, None, create_always, delete_on_close, None
1726 )
1727 assert handle not in {0, ctypes.c_void_p(-1).value}
1728 try:
1729 with pytest.raises(Timeout):
1730 FileLock(target, timeout=0.3).acquire()
1731 finally:
1732 kernel32.CloseHandle(handle)
1733
1734
1735 @pytest.mark.parametrize(
1736 "use_proxy",
1737 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
1738 )
1739 def test_context_group_detaches_release_context(
1740 tmp_path: Path,
1741 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1742 *,
1743 use_proxy: bool,
1744 ) -> None:
1745 capture, release_error, release_cause = close_failure
1746 body_error = ValueError("body failed")
1747 body_cause = LookupError("body cause")
1748 lock = FileLock(str(tmp_path / "a"), context_error_policy="group", close_error_policy="raise", on_acquired=capture)
1749 with pytest.raises(ExceptionGroup) as info, lock.acquire() if use_proxy else lock:
1750 raise body_error from body_cause
1751 assert (
1752 info.value.exceptions,
1753 body_error.__context__,
1754 release_error.__context__,
1755 body_error.__cause__,
1756 release_error.__cause__,
1757 body_error.__traceback__ is not None,
1758 release_error.__traceback__ is not None,
1759 ) == ((body_error, release_error), None, None, body_cause, release_cause, True, True)
1760
1761
1762 def test_context_group_handles_deep_body_context(
1763 tmp_path: Path,
1764 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1765 ) -> None:
1766 capture, release_error, _ = close_failure
1767 body_error = ValueError("body failed")
1768 context: BaseException = body_error
1769 for index in range(2_000):
1770 next_context = RuntimeError(str(index))
1771 context.__context__ = next_context
1772 context = next_context
1773 lock = FileLock(str(tmp_path / "a"), context_error_policy="group", close_error_policy="raise", on_acquired=capture)
1774
1775 with pytest.raises(ExceptionGroup) as info, lock:
1776 raise body_error
1777
1778 assert (info.value.exceptions, release_error.__context__) == ((body_error, release_error), None)
1779
1780
1781 def test_context_group_detaches_equivalent_shared_exception_dag(
1782 tmp_path: Path,
1783 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1784 ) -> None:
1785 capture, release_error, _ = close_failure
1786 body_error: BaseException = ValueError("shared leaf")
1787 context_error = body_error
1788 for depth in range(25):
1789 body_error = ExceptionGroup(str(depth), (body_error, body_error))
1790 context_error = ExceptionGroup(str(depth), (context_error, context_error))
1791 lock = FileLock(str(tmp_path / "a"), context_error_policy="group", close_error_policy="raise", on_acquired=capture)
1792
1793 try:
1794 raise context_error
1795 except ExceptionGroup:
1796 with pytest.raises(ExceptionGroup) as info, lock:
1797 raise body_error # ruff:ignore[raise-without-from-inside-except] # build the caller-controlled implicit context graph
1798
1799 assert (info.value.exceptions, body_error.__context__, release_error.__context__) == (
1800 (body_error, release_error),
1801 None,
1802 None,
1803 )
1804
1805
1806 def test_context_group_preserves_distinct_shared_exception_dag(
1807 tmp_path: Path,
1808 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1809 ) -> None:
1810 capture, release_error, _ = close_failure
1811 body_error: BaseException = ValueError("body leaf")
1812 context_error: BaseException = TypeError("context leaf")
1813 for depth in range(25):
1814 body_error = ExceptionGroup(str(depth), (body_error, body_error))
1815 context_error = ExceptionGroup(str(depth), (context_error, context_error))
1816 lock = FileLock(str(tmp_path / "a"), context_error_policy="group", close_error_policy="raise", on_acquired=capture)
1817
1818 try:
1819 raise context_error
1820 except ExceptionGroup:
1821 with pytest.raises(ExceptionGroup) as info, lock:
1822 raise body_error # ruff:ignore[raise-without-from-inside-except] # build the caller-controlled implicit context graph
1823
1824 assert (info.value.exceptions, body_error.__context__, release_error.__context__) == (
1825 (body_error, release_error),
1826 context_error,
1827 None,
1828 )
1829
1830
1831 @pytest.mark.skipif(
1832 sys.version_info < (3, 11), reason="standard exception-group rendering requires Python 3.11"
1833 ) # pragma: >=3.11 cover
1834 @pytest.mark.parametrize(
1835 "use_proxy",
1836 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
1837 )
1838 def test_context_group_renders_independent_leaves(
1839 tmp_path: Path,
1840 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1841 *,
1842 use_proxy: bool,
1843 ) -> None:
1844 capture, release_error, _ = close_failure
1845 release_error.__cause__ = None
1846 release_error.__suppress_context__ = False
1847 body_error = ValueError("body failed")
1848 lock = FileLock(str(tmp_path / "a"), context_error_policy="group", close_error_policy="raise", on_acquired=capture)
1849 with pytest.raises(ExceptionGroup) as info, lock.acquire() if use_proxy else lock:
1850 raise body_error
1851 group_rendering = "".join(traceback.format_exception(info.value))
1852 release_rendering = "".join(traceback.format_exception(release_error))
1853 assert (
1854 group_rendering.count("ValueError: body failed"),
1855 release_rendering.count("ValueError: body failed"),
1856 release_rendering.count("RuntimeError: release cause"),
1857 release_rendering.count("OSError: release failed"),
1858 ) == (1, 0, 0, 1)
1859
1860
1861 @pytest.mark.parametrize(
1862 "use_proxy",
1863 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
1864 )
1865 def test_context_chain_keeps_release_error_with_body_in_context(
1866 tmp_path: Path,
1867 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1868 *,
1869 use_proxy: bool,
1870 ) -> None:
1871 capture, release_error, _ = close_failure
1872 body_error = ValueError("body failed")
1873 lock = FileLock(str(tmp_path / "a"), context_error_policy="chain", close_error_policy="raise", on_acquired=capture)
1874 with pytest.raises(OSError, match="release failed") as info, lock.acquire() if use_proxy else lock:
1875 raise body_error
1876 assert (info.value, release_error.__context__) == (release_error, body_error)
1877
1878
1879 @pytest.mark.parametrize(
1880 "policy",
1881 [pytest.param("chain", id="chain"), pytest.param("group", id="group")],
1882 )
1883 @pytest.mark.parametrize(
1884 "use_proxy",
1885 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
1886 )
1887 def test_context_body_only_failure_propagates_body(
1888 tmp_path: Path, policy: ContextErrorPolicy, *, use_proxy: bool
1889 ) -> None:
1890 lock = SoftFileLock(str(tmp_path / "a"), context_error_policy=policy)
1891 body = ValueError("body failed")
1892 with pytest.raises(ValueError, match="body failed") as info, lock.acquire() if use_proxy else lock:
1893 raise body
1894 assert info.value is body
1895
1896
1897 @pytest.mark.parametrize(
1898 "policy",
1899 [pytest.param("chain", id="chain"), pytest.param("group", id="group")],
1900 )
1901 @pytest.mark.parametrize(
1902 "use_proxy",
1903 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
1904 )
1905 def test_context_release_only_failure_propagates_release(
1906 tmp_path: Path,
1907 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
1908 policy: ContextErrorPolicy,
1909 *,
1910 use_proxy: bool,
1911 ) -> None:
1912 capture, release_error, release_cause = close_failure
1913 lock = FileLock(str(tmp_path / "a"), context_error_policy=policy, close_error_policy="raise", on_acquired=capture)
1914 with pytest.raises(OSError, match="release failed") as info, lock.acquire() if use_proxy else lock:
1915 pass
1916 assert (info.value, release_error.__context__, release_error.__cause__) == (release_error, None, release_cause)
1917
1918
1919 def test_context_group_base_exception_leaf_is_base_group(
1920 tmp_path: Path, close_failure: tuple[Callable[[int], None], OSError, RuntimeError]
1921 ) -> None:
1922 capture, _, _ = close_failure
1923 lock = FileLock(str(tmp_path / "a"), context_error_policy="group", close_error_policy="raise", on_acquired=capture)
1924 with pytest.raises(BaseExceptionGroup) as info, lock:
1925 raise KeyboardInterrupt
1926 assert not isinstance(info.value, ExceptionGroup) # a BaseException leaf stays outside except Exception
1927 assert [type(leaf) for leaf in info.value.exceptions] == [KeyboardInterrupt, OSError]
1928
1929
1930 def test_invalid_context_error_policy_rejected(tmp_path: Path) -> None:
1931 with pytest.raises(ValueError, match="context_error_policy must be"):
1932 SoftFileLock(str(tmp_path / "a"), context_error_policy="explode") # ty: ignore[invalid-argument-type]
1933
1934
1935 def test_singleton_rejects_different_context_policy(tmp_path: Path) -> None:
1936 path = str(tmp_path / "a")
1937 first = SoftFileLock(path, is_singleton=True, context_error_policy="chain")
1938 try:
1939 with pytest.raises(ValueError, match="context_error_policy"):
1940 SoftFileLock(path, is_singleton=True, context_error_policy="group")
1941 finally:
1942 first.release(force=True)
1943
1944
1945 def _fail_close_of(mocker: MockerFixture, lock: BaseFileLock, error: OSError) -> list[int]:
1946 # Fail os.close only for this lock's own descriptor, and record each attempt on it. A blanket patch would also hit
1947 # the close another test's lock runs from __del__ during this test, turning an unrelated garbage collection into a
1948 # spurious failure. Returns the list of attempts so a caller can assert close is not retried.
1949 fd = lock._context.lock_file_fd
1950 real_close = os.close
1951 attempts: list[int] = []
1952
1953 def close(target: int) -> None:
1954 if target == fd:
1955 attempts.append(target)
1956 raise error
1957 real_close(target) # pragma: no cover # only an unrelated __del__ close during the mock window reaches here
1958
1959 mocker.patch("filelock._api.os.close", side_effect=close)
1960 return attempts
1961
1962
1963 @NEEDS_FCNTL # pragma: needs fcntl
1964 def test_close_error_default_suppressed_on_unix(tmp_path: Path, mocker: MockerFixture) -> None:
1965 lock = FileLock(str(tmp_path / "a")) # default policy
1966 lock.acquire()
1967 _fail_close_of(mocker, lock, OSError(EIO, "close failed"))
1968 lock.release() # Unix default drops a FUSE/Docker EIO
1969 assert not lock.is_locked
1970
1971
1972 @_WINDOWS_ONLY # pragma: win32 cover
1973 def test_close_error_default_raises_on_windows(tmp_path: Path, mocker: MockerFixture) -> None:
1974 lock = FileLock(str(tmp_path / "a")) # default policy
1975 lock.acquire()
1976 _fail_close_of(mocker, lock, OSError(EIO, "close failed"))
1977 with pytest.raises(OSError, match="close failed"):
1978 lock.release()
1979 assert not lock.is_locked
1980
1981
1982 def test_close_error_suppress(tmp_path: Path, mocker: MockerFixture) -> None:
1983 lock = FileLock(str(tmp_path / "a"), close_error_policy="suppress")
1984 lock.acquire()
1985 _fail_close_of(mocker, lock, OSError(EIO, "close failed"))
1986 lock.release()
1987 assert not lock.is_locked
1988
1989
1990 @pytest.mark.parametrize("errno", [EINTR, EIO, ENOSPC])
1991 def test_close_error_raise_is_exact_and_committed(tmp_path: Path, mocker: MockerFixture, errno: int) -> None:
1992 lock = FileLock(str(tmp_path / "a"), close_error_policy="raise")
1993 lock.acquire()
1994 injected = OSError(errno, "close failed")
1995 attempts = _fail_close_of(mocker, lock, injected)
1996 with pytest.raises(OSError, match="close failed") as info:
1997 lock.release()
1998 assert info.value is injected # the original error, no wrapper
1999 assert len(attempts) == 1 # os.close is never retried, even after EINTR
2000 assert not lock.is_locked # the unlock committed even though close failed
2001 assert lock.lock_counter == 0
2002
2003
2004 @NEEDS_FCNTL # pragma: needs fcntl
2005 def test_close_not_reached_when_unlock_fails(tmp_path: Path, mocker: MockerFixture) -> None:
2006 lock = FileLock(str(tmp_path / "a"), close_error_policy="raise")
2007 lock.acquire()
2008 fd = lock._context.lock_file_fd
2009 mocker.patch("filelock._unix.fcntl.flock", side_effect=[OSError(EIO, "unlock failed"), None])
2010 real_close = os.close
2011 closed: list[int] = []
2012 mocker.patch("filelock._api.os.close", side_effect=lambda target: closed.append(target) or real_close(target))
2013 with pytest.raises(OSError, match="unlock failed"):
2014 lock.release()
2015 assert lock.is_locked # the kernel unlock failed, so the lock is still held
2016 assert fd not in closed # close is not reached while the lock is still held
2017 lock.release() # retry: unlock succeeds and close runs
2018 assert not lock.is_locked
2019 assert fd in closed
2020
2021
2022 def test_dual_body_and_close_failure_grouped(tmp_path: Path, mocker: MockerFixture) -> None:
2023 lock = FileLock(str(tmp_path / "a"), close_error_policy="raise", context_error_policy="group")
2024 lock.acquire()
2025 _fail_close_of(mocker, lock, OSError("close failed"))
2026 body = ValueError("body failed")
2027 with pytest.raises(ExceptionGroup) as info:
2028 lock._release_in_context(body) # what __exit__ runs; the close failure joins the body failure
2029 leaf_body, close = info.value.exceptions
2030 assert isinstance(leaf_body, ValueError)
2031 assert isinstance(close, OSError)
2032
2033
2034 def test_invalid_close_error_policy_rejected(tmp_path: Path) -> None:
2035 with pytest.raises(ValueError, match="close_error_policy must be"):
2036 FileLock(str(tmp_path / "a"), close_error_policy="explode") # ty: ignore[invalid-argument-type]
2037
2038
2039 def test_singleton_rejects_different_close_policy(tmp_path: Path) -> None:
2040 path = str(tmp_path / "a")
2041 first = FileLock(path, is_singleton=True, close_error_policy="raise")
2042 try:
2043 with pytest.raises(ValueError, match="close_error_policy"):
2044 FileLock(path, is_singleton=True, close_error_policy="suppress")
2045 finally:
2046 first.release(force=True)
2047
2048
2049 def test_singleton_shares_across_equivalent_spellings(tmp_path: Path) -> None:
2050 (tmp_path / "sub").mkdir()
2051 absolute = FileLock(str(tmp_path / "a"), is_singleton=True)
2052 dot = FileLock(str(tmp_path) + "/./a", is_singleton=True)
2053 dotdot = FileLock(str(tmp_path / "sub") + "/../a", is_singleton=True)
2054 try:
2055 assert absolute is dot is dotdot # one instance for equivalent spellings of one path
2056 finally:
2057 absolute.release(force=True)
2058
2059
2060 @NEEDS_PARENT_SYMLINK_COLLAPSE # pragma: win32 no cover
2061 def test_singleton_shares_through_symlinked_parent(tmp_path: Path) -> None:
2062 real = tmp_path / "real"
2063 real.mkdir()
2064 (tmp_path / "link").symlink_to(real)
2065 via_real = FileLock(str(real / "a"), is_singleton=True)
2066 via_link = FileLock(str(tmp_path / "link" / "a"), is_singleton=True)
2067 try:
2068 assert via_real is via_link # a symlinked parent directory resolves to the same key
2069 finally:
2070 via_real.release(force=True)
2071
2072
2073 @NEEDS_SYMLINK # pragma: needs symlink
2074 def test_final_symlink_stays_a_distinct_key(tmp_path: Path) -> None:
2075 target = tmp_path / "target"
2076 target.write_text("")
2077 (tmp_path / "link").symlink_to(target)
2078 on_link = FileLock(str(tmp_path / "link"), is_singleton=True)
2079 on_target = FileLock(str(target), is_singleton=True)
2080 try:
2081 assert on_link is not on_target # the final component is not resolved, so the symlink is its own key
2082 finally:
2083 on_link.release(force=True)
2084 on_target.release(force=True)
2085
2086
2087 @NEEDS_FCNTL # pragma: needs fcntl
2088 @_NEEDS_O_NOFOLLOW # pragma: needs o-nofollow
2089 def test_final_symlink_backend_refuses_to_lock(tmp_path: Path) -> None:
2090 (tmp_path / "target").write_text("")
2091 (tmp_path / "link").symlink_to(tmp_path / "target")
2092 # Keeping the final symlink a distinct key is safe because the backend still refuses to lock through it. O_NOFOLLOW
2093 # reports the refusal as ELOOP on Linux and macOS, and as EFTYPE ("inappropriate file type") on NetBSD.
2094 with pytest.raises(OSError, check=lambda error: error.errno in {errno.ELOOP, getattr(errno, "EFTYPE", None)}):
2095 FileLock(str(tmp_path / "link")).acquire()
2096
2097
2098 def test_separate_lock_classes_keep_separate_registries(tmp_path: Path) -> None:
2099 path = str(tmp_path / "a")
2100 native = FileLock(path, is_singleton=True)
2101 soft = SoftFileLock(path, is_singleton=True)
2102 try:
2103 assert native is not soft # each class caches its own singletons
2104 finally:
2105 native.release(force=True)
2106 soft.release(force=True)
2107
2108
2109 @NEEDS_FCNTL # pragma: needs fcntl
2110 def test_fallback_to_soft_disabled_raises_enosys(tmp_path: Path, mocker: MockerFixture) -> None:
2111 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
2112 lock = FileLock(str(tmp_path / "a"), fallback_to_soft=False)
2113 with pytest.raises(OSError, match="no flock") as info:
2114 lock.acquire()
2115 assert info.value.errno == ENOSYS # the original error, not a soft-lock timeout
2116 assert not lock.is_locked
2117 assert type(lock).__name__ == "UnixFileLock" # the class is not swapped to SoftFileLock
2118 assert lock.lock_counter == 0 # the failed acquire left no holder count
2119
2120
2121 @NEEDS_FCNTL # pragma: needs fcntl
2122 def test_fallback_to_soft_default_switches_to_soft(tmp_path: Path, mocker: MockerFixture) -> None:
2123 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
2124 lock = FileLock(str(tmp_path / "a")) # default fallback_to_soft=True
2125 with pytest.warns(UserWarning, match="falling back to SoftFileLock"):
2126 lock.acquire()
2127 try:
2128 assert lock.is_locked
2129 assert isinstance(lock, SoftFileLock) # switched to existence-lock semantics
2130 finally:
2131 lock.release()
2132
2133
2134 @NEEDS_FCNTL # pragma: needs fcntl
2135 def test_fallback_disabled_recursive_reraises(tmp_path: Path, mocker: MockerFixture) -> None:
2136 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
2137 lock = FileLock(str(tmp_path / "a"), fallback_to_soft=False)
2138 for _ in range(2): # a repeat acquire keeps failing the same way, never a soft downgrade
2139 with pytest.raises(OSError, match="no flock"):
2140 lock.acquire()
2141 assert not lock.is_locked
2142
2143
2144 @NEEDS_FCNTL # pragma: needs fcntl
2145 def test_singleton_rejects_different_fallback_to_soft(tmp_path: Path) -> None:
2146 path = str(tmp_path / "a")
2147 first = FileLock(path, is_singleton=True, fallback_to_soft=True)
2148 try:
2149 with pytest.raises(ValueError, match="fallback_to_soft"):
2150 FileLock(path, is_singleton=True, fallback_to_soft=False)
2151 finally:
2152 first.release(force=True)
2153
2154
2155 def test_lock_descriptor_roundtrip(tmp_path: Path) -> None:
2156 fd = os.open(str(tmp_path / "a"), os.O_RDWR | os.O_CREAT)
2157 try:
2158 assert lock_descriptor(fd, blocking=False) is True
2159 os.write(fd, b"held") # the descriptor stays usable while locked
2160 unlock_descriptor(fd)
2161 os.lseek(fd, 0, os.SEEK_SET)
2162 assert os.read(fd, 4) == b"held" # and after unlock
2163 finally:
2164 os.close(fd)
2165
2166
2167 def test_lock_descriptor_nonblocking_contention(tmp_path: Path) -> None:
2168 path = str(tmp_path / "a")
2169 holder = os.open(path, os.O_RDWR | os.O_CREAT)
2170 contender = os.open(path, os.O_RDWR | os.O_CREAT)
2171 try:
2172 assert lock_descriptor(holder, blocking=False) is True
2173 assert lock_descriptor(contender, blocking=False) is False # a second descriptor sees the lock
2174 unlock_descriptor(holder)
2175 assert lock_descriptor(contender, blocking=False) is True # free once the holder releases
2176 unlock_descriptor(contender)
2177 finally:
2178 os.close(holder)
2179 os.close(contender)
2180
2181
2182 def test_lock_descriptor_invalid_fd_raises(tmp_path: Path) -> None:
2183 fd = os.open(str(tmp_path / "a"), os.O_RDWR | os.O_CREAT)
2184 os.close(fd) # a closed descriptor is invalid; the native lock must raise, not silently succeed or contend
2185 with pytest.raises(OSError, match=r"Bad file descriptor|not open|invalid"):
2186 lock_descriptor(fd, blocking=False)
2187
2188
2189 @pytest.mark.parametrize(
2190 "poll_interval",
2191 _INVALID_DESCRIPTOR_POLL_INTERVALS,
2192 )
2193 def test_lock_descriptor_rejects_invalid_blocking_poll_interval(poll_interval: float) -> None:
2194 with pytest.raises(ValueError, match="poll_interval must be finite and greater than 0"):
2195 lock_descriptor(-1, poll_interval=poll_interval)
2196
2197
2198 @pytest.mark.parametrize(
2199 "poll_interval",
2200 _INVALID_DESCRIPTOR_POLL_INTERVALS,
2201 )
2202 def test_lock_descriptor_nonblocking_ignores_poll_interval(tmp_path: Path, poll_interval: float) -> None:
2203 fd = os.open(str(tmp_path / "a"), os.O_RDWR | os.O_CREAT)
2204 try:
2205 assert lock_descriptor(fd, blocking=False, poll_interval=poll_interval) is True
2206 unlock_descriptor(fd)
2207 finally:
2208 os.close(fd)
2209
2210
2211 @pytest.mark.parametrize("direction", ["filelock_first", "descriptor_first"])
2212 def test_filelock_and_descriptor_contend(tmp_path: Path, direction: str) -> None:
2213 path = str(tmp_path / "a")
2214 lock = FileLock(path)
2215 fd = os.open(path, os.O_RDWR | os.O_CREAT)
2216 try:
2217 if direction == "filelock_first":
2218 lock.acquire()
2219 assert lock_descriptor(fd, blocking=False) is False # the path lock blocks the descriptor lock
2220 lock.release()
2221 assert lock_descriptor(fd, blocking=False) is True
2222 unlock_descriptor(fd)
2223 else:
2224 assert lock_descriptor(fd, blocking=False) is True
2225 with pytest.raises(Timeout):
2226 lock.acquire(timeout=0.2) # the descriptor lock blocks the path lock
2227 unlock_descriptor(fd)
2228 lock.acquire()
2229 lock.release()
2230 finally:
2231 os.close(fd)
2232
2233
2234 @NEEDS_FCNTL # pragma: needs fcntl
2235 def test_lock_descriptor_touches_no_paths(tmp_path: Path) -> None:
2236 path = tmp_path / "a"
2237 fd = os.open(str(path), os.O_RDWR | os.O_CREAT)
2238 try:
2239 os.write(fd, b"payload")
2240 before = os.fstat(fd)
2241 assert lock_descriptor(fd, blocking=False) is True
2242 unlock_descriptor(fd)
2243 after = os.fstat(fd)
2244 # The adapter works purely on the descriptor: our fd stays open on the same inode with its size and mode
2245 # intact, and the file keeps its contents. That rules out any open, close, unlink, truncate or chmod on our
2246 # behalf without spying on hot global os functions, which unrelated tempfile cleanup would race and pollute.
2247 assert (after.st_ino, after.st_dev, after.st_size, after.st_mode) == (
2248 before.st_ino,
2249 before.st_dev,
2250 before.st_size,
2251 before.st_mode,
2252 )
2253 assert path.read_bytes() == b"payload"
2254 finally:
2255 os.close(fd)
2256
2257
2258 @NEEDS_FCNTL # pragma: needs fcntl
2259 def test_unlock_descriptor_failure_allows_retry(tmp_path: Path, mocker: MockerFixture) -> None:
2260 fd = os.open(str(tmp_path / "a"), os.O_RDWR | os.O_CREAT)
2261 try:
2262 assert lock_descriptor(fd, blocking=False) is True
2263 mocker.patch("filelock._unix.fcntl.flock", side_effect=[OSError(EIO, "unlock failed"), None])
2264 with pytest.raises(OSError, match="unlock failed"):
2265 unlock_descriptor(fd)
2266 unlock_descriptor(fd) # the same descriptor can retry
2267 finally:
2268 os.close(fd)
2269
2270
2271 def test_lock_descriptor_blocking_retries_until_free(tmp_path: Path, mocker: MockerFixture) -> None:
2272 path = str(tmp_path / "a")
2273 holder = os.open(path, os.O_RDWR | os.O_CREAT)
2274 fd = os.open(path, os.O_RDWR | os.O_CREAT)
2275 assert lock_descriptor(holder, blocking=False) is True
2276 # Drive the real blocking loop: the first attempt sees contention, the mocked sleep frees the holder, and the
2277 # second attempt wins. Only the clock is mocked, so a single sleep call proves exactly one retry happened.
2278 sleep = mocker.patch("filelock._descriptor.time.sleep", side_effect=lambda _: unlock_descriptor(holder))
2279 try:
2280 assert lock_descriptor(fd, blocking=True, poll_interval=0.01) is True
2281 sleep.assert_called_once_with(0.01)
2282 unlock_descriptor(fd)
2283 finally:
2284 os.close(holder)
2285 os.close(fd)
2286
2287
2288 #: NetBSD has no CLOCK_THREAD_CPUTIME_ID, so time.thread_time is absent; process CPU time proves "not spinning" too.
2289 _CPU_TIME: Final[Callable[[], float]] = getattr(time, "thread_time", time.process_time)
2290
2291
2292 def test_lock_descriptor_blocking_wait_does_not_spin(tmp_path: Path) -> None:
2293 path = str(tmp_path / "a")
2294 holder = os.open(path, os.O_RDWR | os.O_CREAT)
2295 contender = os.open(path, os.O_RDWR | os.O_CREAT)
2296 assert lock_descriptor(holder, blocking=False) is True
2297 started = threading.Event()
2298
2299 def acquire() -> float:
2300 started.set()
2301 before = _CPU_TIME()
2302 lock_descriptor(contender, poll_interval=0.01)
2303 return _CPU_TIME() - before
2304
2305 try:
2306 with ThreadPoolExecutor(max_workers=1) as executor:
2307 future = executor.submit(acquire)
2308 try:
2309 assert started.wait(timeout=1)
2310 time.sleep(0.2)
2311 finally:
2312 unlock_descriptor(holder)
2313 assert future.result(timeout=2) < 0.05
2314 unlock_descriptor(contender)
2315 finally:
2316 os.close(holder)
2317 os.close(contender)
2318
2319
2320 def test_preserve_lock_file_defaults_off(tmp_path: Path) -> None:
2321 assert FileLock(str(tmp_path / "a")).preserve_lock_file is False
2322
2323
2324 def test_preserve_lock_file_property_reflects_argument(tmp_path: Path) -> None:
2325 assert FileLock(str(tmp_path / "a"), preserve_lock_file=True).preserve_lock_file is True
2326
2327
2328 def test_preserve_lock_file_rejected_by_soft_lock(tmp_path: Path) -> None:
2329 with pytest.raises(ValueError, match="preserve_lock_file"):
2330 SoftFileLock(str(tmp_path / "a"), preserve_lock_file=True)
2331
2332
2333 def test_singleton_rejects_different_preserve_lock_file(tmp_path: Path) -> None:
2334 path = str(tmp_path / "a")
2335 first = FileLock(path, is_singleton=True, preserve_lock_file=False)
2336 try:
2337 with pytest.raises(ValueError, match="preserve_lock_file"):
2338 FileLock(path, is_singleton=True, preserve_lock_file=True)
2339 finally:
2340 first.release(force=True)
2341
2342
2343 @NEEDS_FCNTL # pragma: needs fcntl
2344 def test_preserve_lock_file_unix_keeps_pathname(tmp_path: Path) -> None:
2345 path = tmp_path / "a"
2346 lock = FileLock(str(path), preserve_lock_file=True)
2347 lock.acquire()
2348 lock.release()
2349 assert path.exists() # Unix leaves the native pathname in place
2350 assert type(lock).__name__ == "UnixFileLock"
2351
2352
2353 @NEEDS_FCNTL # pragma: needs fcntl
2354 def test_preserve_lock_file_fails_closed_on_enosys(tmp_path: Path, mocker: MockerFixture) -> None:
2355 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
2356 lock = FileLock(str(tmp_path / "a"), preserve_lock_file=True) # fallback_to_soft still defaults to True
2357 with pytest.raises(OSError, match="no flock"):
2358 lock.acquire()
2359 assert not lock.is_locked
2360 assert type(lock).__name__ == "UnixFileLock" # preserve overrides the soft fallback that would unlink to release
2361
2362
2363 @_WINDOWS_ONLY # pragma: win32 cover
2364 def test_preserve_lock_file_windows_default_removes_file(tmp_path: Path) -> None:
2365 path = tmp_path / "a"
2366 lock = FileLock(str(path))
2367 lock.acquire()
2368 lock.release()
2369 assert not path.exists() # the default Windows cleanup unlinks the lock file
2370
2371
2372 @_WINDOWS_ONLY # pragma: win32 cover
2373 def test_preserve_lock_file_windows_keeps_file(tmp_path: Path) -> None:
2374 path = tmp_path / "a"
2375 lock = FileLock(str(path), preserve_lock_file=True)
2376 lock.acquire()
2377 lock.release()
2378 assert path.exists() # preserve_lock_file skips the post-release unlink
2379
2380
2381 @_WINDOWS_ONLY # pragma: win32 cover
2382 def test_preserve_lock_file_windows_reacquires_same_identity(tmp_path: Path) -> None:
2383 path = tmp_path / "a"
2384 lock = FileLock(str(path), preserve_lock_file=True)
2385 lock.acquire()
2386 lock.release()
2387 kept = path.stat()
2388 lock.acquire()
2389 try:
2390 current = path.stat()
2391 assert (current.st_dev, current.st_ino) == (kept.st_dev, kept.st_ino) # same file across acquisitions
2392 finally:
2393 lock.release()
2394
2395
2396 @_WINDOWS_ONLY # pragma: win32 cover
2397 def test_preserve_lock_file_windows_kept_after_forced_release(tmp_path: Path) -> None:
2398 path = tmp_path / "a"
2399 lock = FileLock(str(path), preserve_lock_file=True)
2400 lock.acquire()
2401 lock.acquire() # reentrant second level
2402 lock.release(force=True) # drop every level and run the release path once
2403 assert not lock.is_locked
2404 assert path.exists() # preserved even through a forced release
2405
2406
2407 def _noop_on_acquired(_fd: int) -> None:
2408 pass
2409
2410
2411 def _failing_on_acquired(_fd: int) -> None:
2412 msg = "hook failed"
2413 raise RuntimeError(msg)
2414
2415
2416 def test_on_acquired_defaults_none(tmp_path: Path) -> None:
2417 assert FileLock(str(tmp_path / "a")).on_acquired is None
2418
2419
2420 def test_on_acquired_property_reflects_argument(tmp_path: Path) -> None:
2421 assert FileLock(str(tmp_path / "a"), on_acquired=_noop_on_acquired).on_acquired is _noop_on_acquired
2422
2423
2424 def test_on_acquired_noop_hook_allows_acquire(tmp_path: Path) -> None:
2425 lock = FileLock(str(tmp_path / "a"), on_acquired=_noop_on_acquired)
2426 lock.acquire() # the no-op hook runs during acquisition
2427 try:
2428 assert lock.is_locked
2429 finally:
2430 lock.release()
2431
2432
2433 def test_on_acquired_runs_before_acquire_returns(tmp_path: Path) -> None:
2434 fd_while_held = -1
2435 locked_during_hook = False
2436
2437 def hook(fd: int) -> None:
2438 nonlocal fd_while_held, locked_during_hook
2439 locked_during_hook = lock.is_locked
2440 fd_while_held = fd
2441
2442 lock = FileLock(str(tmp_path / "a"), on_acquired=hook)
2443 lock.acquire()
2444 try:
2445 assert locked_during_hook # the hook ran while the lock was held ...
2446 assert fd_while_held >= 0 # ... and got a real descriptor, all before acquire() returned
2447 finally:
2448 lock.release()
2449
2450
2451 def test_on_acquired_fires_once_per_physical_acquire(tmp_path: Path) -> None:
2452 calls: list[int] = []
2453 lock = FileLock(str(tmp_path / "a"), on_acquired=calls.append)
2454 lock.acquire()
2455 lock.acquire() # recursive: the poll loop skips _acquire, so the hook does not run again
2456 try:
2457 assert len(calls) == 1
2458 finally:
2459 lock.release()
2460 lock.release()
2461
2462
2463 def test_on_acquired_not_called_for_contender(tmp_path: Path) -> None:
2464 path = str(tmp_path / "a")
2465 holder = FileLock(path)
2466 holder.acquire()
2467 calls: list[int] = []
2468 contender = FileLock(path, on_acquired=calls.append)
2469 try:
2470 with pytest.raises(Timeout):
2471 contender.acquire(timeout=0.1)
2472 assert calls == [] # a contender that never acquires never runs the hook
2473 finally:
2474 holder.release()
2475
2476
2477 @NEEDS_FCNTL # pragma: needs fcntl
2478 def test_on_acquired_runs_after_truncation_and_mode(tmp_path: Path) -> None:
2479 path = tmp_path / "a"
2480 path.write_bytes(b"stale content")
2481 seen: dict[str, int] = {}
2482
2483 def hook(fd: int) -> None:
2484 stat_result = os.fstat(fd)
2485 seen["size"] = stat_result.st_size
2486 seen["mode"] = S_IMODE(stat_result.st_mode)
2487
2488 lock = FileLock(str(path), mode=0o600, on_acquired=hook)
2489 lock.acquire()
2490 try:
2491 assert seen == {"size": 0, "mode": 0o600} # backend truncation and mode setup finished before the hook
2492 finally:
2493 lock.release()
2494
2495
2496 @NEEDS_FCNTL # pragma: needs fcntl
2497 def test_on_acquired_writes_survive_contention(tmp_path: Path) -> None:
2498 path = str(tmp_path / "a")
2499
2500 def write_metadata(fd: int) -> None:
2501 os.write(fd, b"holder-metadata")
2502
2503 writer = FileLock(path, on_acquired=write_metadata)
2504 writer.acquire()
2505 try:
2506 contender = FileLock(path)
2507 with pytest.raises(Timeout):
2508 contender.acquire(timeout=0.1) # a losing contender must not truncate the holder's file
2509 assert Path(path).read_bytes() == b"holder-metadata"
2510 finally:
2511 writer.release()
2512
2513
2514 def test_on_acquired_failure_releases_lock(tmp_path: Path) -> None:
2515 path = str(tmp_path / "a")
2516 lock = FileLock(path, on_acquired=_failing_on_acquired)
2517 with pytest.raises(RuntimeError, match="hook failed"):
2518 lock.acquire()
2519 assert not lock.is_locked
2520 assert lock.lock_counter == 0
2521 other = FileLock(path)
2522 other.acquire() # the native lock was released, so a fresh acquire succeeds at once
2523 other.release()
2524
2525
2526 @NEEDS_FCNTL # pragma: needs fcntl
2527 def test_on_acquired_and_release_failure_group(tmp_path: Path, mocker: MockerFixture) -> None:
2528 path = str(tmp_path / "a")
2529 lock = FileLock(path, on_acquired=_failing_on_acquired)
2530 mocker.patch("filelock._unix._unlock_fd", side_effect=[OSError(EIO, "unlock failed"), None])
2531 with pytest.raises(BaseExceptionGroup) as info:
2532 lock.acquire()
2533 assert {type(error) for error in info.value.exceptions} == {RuntimeError, OSError}
2534 assert lock.is_locked # the OS unlock failed, so the lock stays held for a retry
2535 assert lock.lock_counter == 1
2536 lock.release() # the second unlock succeeds
2537
2538
2539 def test_on_acquired_rollback_group_detaches_release_context(
2540 tmp_path: Path, close_failure: tuple[Callable[[int], None], OSError, RuntimeError]
2541 ) -> None:
2542 capture, release_error, release_cause = close_failure
2543 callback_error = RuntimeError("hook failed")
2544 callback_cause = LookupError("hook cause")
2545
2546 def fail(fd: int) -> None:
2547 capture(fd)
2548 raise callback_error from callback_cause
2549
2550 lock = FileLock(str(tmp_path / "a"), close_error_policy="raise", on_acquired=fail)
2551 with pytest.raises(ExceptionGroup) as info:
2552 lock.acquire()
2553 assert (
2554 info.value.exceptions,
2555 callback_error.__context__,
2556 release_error.__context__,
2557 callback_error.__cause__,
2558 release_error.__cause__,
2559 callback_error.__traceback__ is not None,
2560 release_error.__traceback__ is not None,
2561 ) == ((callback_error, release_error), None, None, callback_cause, release_cause, True, True)
2562
2563
2564 def test_grouped_errors_keep_a_context_that_is_a_distinct_group() -> None:
2565 # A genuinely distinct group-valued __context__ must survive the detach rather than read as a duplicate.
2566 context = ExceptionGroup("context group", [ValueError("a")])
2567 member = ExceptionGroup("member group", [KeyError("b"), KeyError("c")])
2568 member.__context__ = context
2569
2570 with pytest.raises(BaseExceptionGroup) as info:
2571 _raise_grouped_errors("grouped", member, RuntimeError("other"))
2572
2573 assert member.__context__ is context
2574 assert member in info.value.exceptions
2575
2576
2577 def test_grouped_errors_detach_a_context_already_nested_in_a_sibling() -> None:
2578 # A context already present in a sibling's tree is dropped so the group never carries the same leaf twice.
2579 shared = ValueError("shared leaf")
2580 sibling = ExceptionGroup("sibling", [shared])
2581 member = RuntimeError("boom")
2582 member.__context__ = shared
2583
2584 with pytest.raises(BaseExceptionGroup) as info:
2585 _raise_grouped_errors("grouped", sibling, member)
2586
2587 assert member.__context__ is None
2588 assert set(info.value.exceptions) == {sibling, member}
2589
2590
2591 def test_rollback_failed_acquire_groups_registration_and_release_failures(
2592 tmp_path: Path, mocker: MockerFixture
2593 ) -> None:
2594 # An acquire that raised while still holding the lock re-registers the descriptor and releases; when both that
2595 # re-registration and the release then fail, every failure survives as a sibling of the group raised.
2596 lock = SoftFileLock(str(tmp_path / "a"))
2597 lock.acquire()
2598 registration_error = OSError("registration failed")
2599 release_error = OSError("release failed")
2600 mocker.patch.object(lock, "_register_context_descriptor", side_effect=registration_error)
2601 mocker.patch.object(lock, "_release_with_fork_tracking", side_effect=release_error)
2602 acquisition_error = RuntimeError("acquire failed")
2603
2604 try:
2605 with pytest.raises(BaseExceptionGroup) as info:
2606 lock._rollback_failed_acquire(acquisition_error)
2607 assert set(info.value.exceptions) == {acquisition_error, registration_error, release_error}
2608 finally:
2609 mocker.stopall()
2610 lock.release(force=True)
2611
2612
2613 @NEEDS_FCNTL # pragma: needs fcntl
2614 def test_on_acquired_fails_closed_on_enosys(tmp_path: Path, mocker: MockerFixture) -> None:
2615 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
2616 calls: list[int] = []
2617 lock = FileLock(str(tmp_path / "a"), on_acquired=calls.append)
2618 with pytest.raises(OSError, match="no flock"):
2619 lock.acquire()
2620 assert not lock.is_locked
2621 assert type(lock).__name__ == "UnixFileLock" # a soft lock cannot run the hook, so no fallback
2622 assert calls == []
2623
2624
2625 def test_on_acquired_rejected_by_soft_lock(tmp_path: Path) -> None:
2626 with pytest.raises(ValueError, match="on_acquired"):
2627 SoftFileLock(str(tmp_path / "a"), on_acquired=_noop_on_acquired)
2628
2629
2630 def test_singleton_shares_same_on_acquired(tmp_path: Path) -> None:
2631 path = str(tmp_path / "a")
2632 first = FileLock(path, is_singleton=True, on_acquired=_noop_on_acquired)
2633 try:
2634 assert FileLock(path, is_singleton=True, on_acquired=_noop_on_acquired) is first
2635 finally:
2636 first.release(force=True)
2637
2638
2639 def test_singleton_rejects_different_on_acquired(tmp_path: Path) -> None:
2640 path = str(tmp_path / "a")
2641 first = FileLock(path, is_singleton=True, on_acquired=_noop_on_acquired)
2642 try:
2643 with pytest.raises(ValueError, match="on_acquired"):
2644 FileLock(path, is_singleton=True, on_acquired=_failing_on_acquired)
2645 finally:
2646 first.release(force=True)
2647
2648
2649 def test_import_succeeds_without_os_link() -> None:
2650 # Termux/Android CPython has no os.link, and the strict backend touched it at import, so `from filelock import
2651 # FileLock` crashed with AttributeError there (discussion #677). Importing in a fresh interpreter with os.link
2652 # removed must still succeed.
2653 script = (
2654 "import os\n"
2655 "if hasattr(os, 'link'):\n"
2656 " del os.link\n"
2657 "from filelock import FileLock, StrictSoftFileLock\n"
2658 "print('ok')\n"
2659 )
2660 run = [sys.executable, "-c", script]
2661 result = subprocess.run(run, capture_output=True, text=True, check=False)
2662 assert (result.returncode, result.stdout.strip()) == (0, "ok"), result.stderr
2663
2664
2665 def test_strict_lock_reports_unsupported_without_os_link(tmp_path: Path, mocker: MockerFixture) -> None:
2666 # With os.link absent the strict backend cannot publish a hard-link claim, so acquire must raise the same
2667 # unsupported-filesystem error a hard-link-refusing filesystem gets, not a bare AttributeError.
2668 mocker.patch("filelock._strict._HAS_LINK", False)
2669 lock = StrictSoftFileLock(str(tmp_path / "resource.lock"))
2670 with pytest.raises(SoftFileLockProtocolError, match="hard-link publication"):
2671 lock.acquire()
2672 assert (lock.claims, lock.is_locked) == ((), False)
2673
2674
2675 def test_soft_release_groups_close_and_cleanup_failures(tmp_path: Path, mocker: MockerFixture) -> None:
2676 lock = SoftFileLock(str(tmp_path / "grouped.lock"))
2677 lock.acquire()
2678 mocker.patch.object(lock, "_close_released_fd", side_effect=OSError("close boom"))
2679 mocker.patch.object(lock, "_unlink_held_marker", side_effect=OSError("cleanup boom"))
2680
2681 with pytest.raises(BaseExceptionGroup, match="both failed") as excinfo:
2682 lock._release()
2683
2684 messages = {str(exc) for exc in excinfo.value.exceptions}
2685 assert any("close boom" in message for message in messages)
2686 assert any("cleanup boom" in message for message in messages)
2687
2688
2689 def test_soft_windows_unlink_stops_on_non_permission_error(tmp_path: Path, mocker: MockerFixture) -> None:
2690 path = tmp_path / "windows.lock"
2691 path.write_bytes(b"x")
2692 lock = SoftFileLock(str(path))
2693 st = os.lstat(path)
2694 mocker.patch.object(Path, "unlink", side_effect=OSError(ENOSYS, "boom"))
2695
2696 lock._windows_unlink_if_ours((st.st_dev, st.st_ino))
2697
2698 assert path.exists()
2699
2700
2701 @pytest.mark.timeout(5)
2702 def test_append_exception_context_terminates_on_a_cycle() -> None:
2703 first = RuntimeError("first")
2704 second = RuntimeError("second")
2705 first.__context__ = second
2706 second.__context__ = first # a cycle that never reaches the context below
2707 context = ValueError("context")
2708
2709 _append_exception_context(first, context)
2710
2711 # The walk hit the already-seen tail and stopped instead of looping forever or threading context into the ring.
2712 assert first.__context__ is second
2713 assert second.__context__ is first
2714
2715
2716 def test_undo_acquire_keeps_registry_entry_while_still_held(tmp_path: Path, mocker: MockerFixture) -> None:
2717 lock = FileLock(str(tmp_path / "a"), is_singleton=False)
2718 lock.acquire()
2719 key = lock._context.lock_file_key
2720 assert _registry.held.get(key) == id(lock)
2721
2722 # A reentrant acquire that fails while the lock reports unheld routes through _undo_acquire with the counter
2723 # still above zero, so the registry entry the outer hold owns must survive.
2724 held_fd = lock._context.lock_file_fd
2725 lock._context.lock_file_fd = None # is_locked now reports False
2726 mocker.patch.object(lock, "_poll_until_acquired", side_effect=Timeout(lock.lock_file))
2727 with pytest.raises(Timeout):
2728 lock.acquire(timeout=0)
2729
2730 assert lock._context.lock_counter == 1 # decremented from 2, the deeper hold remains
2731 assert _registry.held.get(key) == id(lock) # entry preserved because the counter did not reach zero
2732
2733 lock._context.lock_file_fd = held_fd
2734 lock.release()
2735
2736
2737 def test_soft_marker_omits_start_line_without_a_start_token(tmp_path: Path, mocker: MockerFixture) -> None:
2738 mocker.patch("filelock._soft.process_start_token", return_value=None)
2739 lock = SoftFileLock(str(tmp_path / "a"))
2740 with lock:
2741 lines = Path(lock.lock_file).read_text(encoding="utf-8").splitlines()
2742
2743 assert len(lines) == 2 # pid and hostname only; the optional start-token line is omitted
2744 assert lines[0] == str(os.getpid())
2745
2746
2747 def test_soft_is_lock_held_by_us_false_for_unparseable_marker(tmp_path: Path) -> None:
2748 lock_path = tmp_path / "a"
2749 lock_path.write_text("garbage-not-a-marker", encoding="utf-8")
2750 lock = SoftFileLock(str(lock_path))
2751
2752 assert lock.is_lock_held_by_us is False # an unreadable holder is nobody, so certainly not us
2753
2754
2755 @NEEDS_FCNTL # pragma: needs fcntl
2756 def test_unix_acquire_without_o_nofollow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
2757 monkeypatch.delattr(os, "O_NOFOLLOW", raising=False)
2758 lock = FileLock(str(tmp_path / "a"), is_singleton=False)
2759 lock.acquire()
2760 try:
2761 assert lock.is_locked # acquisition still works on a platform without O_NOFOLLOW
2762 finally:
2763 lock.release()
2764
2765
2766 @NEEDS_FCNTL # pragma: needs fcntl
2767 def test_unix_soft_fallback_keeps_a_replaced_file(tmp_path: Path, mocker: MockerFixture) -> None:
2768 lock_path = tmp_path / "a"
2769 lock = FileLock(str(lock_path), is_singleton=False)
2770 target = lock.lock_file
2771 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
2772
2773 real_lstat = os.lstat
2774
2775 def lstat_swapped_identity(path: str) -> os.stat_result:
2776 st = real_lstat(path)
2777 if str(path) != target:
2778 return st
2779 fields = list(st)
2780 fields[1] += 1 # bump st_ino so the on-disk identity no longer matches the opened fd
2781 return os.stat_result(fields)
2782
2783 mocker.patch("filelock._unix.os.lstat", side_effect=lstat_swapped_identity)
2784
2785 with pytest.raises(Timeout), pytest.warns(UserWarning, match="falling back to SoftFileLock"):
2786 lock.acquire(timeout=0.2)
2787
2788 assert isinstance(lock, SoftFileLock) # fell back after refusing to unlink the mismatched file
2789 assert lock_path.exists() # the replacement file was left in place