Debian Codegraph @

tests/test_filelock.py

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