Debian Codegraph @

tests/test_async_filelock.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import gc
5 import logging
6 import os
7 import sys
8 import threading
9 import traceback
10 from concurrent.futures import ThreadPoolExecutor
11 from contextlib import contextmanager
12 from errno import EINTR, EIO, ENOSYS
13 from pathlib import Path, PurePath
14 from typing import TYPE_CHECKING, Literal
15
16 import pytest
17
18 from filelock import (
19 AsyncFileLock,
20 AsyncSoftFileLock,
21 BaseAsyncFileLock,
22 CloseErrorPolicy,
23 ContextErrorPolicy,
24 Timeout,
25 )
26 from tests.capability_marks import NEEDS_FCNTL, NEEDS_PARENT_SYMLINK_COLLAPSE
27
28 if sys.version_info >= (3, 11): # pragma: no cover (py311+)
29 from builtins import BaseExceptionGroup, ExceptionGroup # pragma: >=3.11 cover
30 else: # pragma: no cover (<py311)
31 from exceptiongroup import BaseExceptionGroup, ExceptionGroup
32
33 if TYPE_CHECKING:
34 from collections.abc import Callable, Iterator
35
36 from pytest_mock import MockerFixture
37
38
39 # Windows resolves a lock's parent with abspath, so a symlinked parent stays a distinct key and never collapses.
40
41
42 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
43 @pytest.mark.parametrize("path_type", [str, PurePath, Path])
44 @pytest.mark.parametrize("filename", ["a", "new/b", "new2/new3/c"])
45 @pytest.mark.asyncio
46 async def test_simple(
47 lock_type: type[BaseAsyncFileLock],
48 path_type: type[str | Path],
49 filename: str,
50 tmp_path: Path,
51 caplog: pytest.LogCaptureFixture,
52 ) -> None:
53 caplog.set_level(logging.DEBUG)
54
55 lock_path = tmp_path / filename
56 lock = lock_type(path_type(lock_path))
57 async with lock as locked:
58 assert lock.is_locked
59 assert lock is locked
60 assert not lock.is_locked
61
62 assert caplog.messages == [
63 f"Attempting to acquire lock {id(lock)} on {lock_path}",
64 f"Lock {id(lock)} acquired on {lock_path}",
65 f"Attempting to release lock {id(lock)} on {lock_path}",
66 f"Lock {id(lock)} released on {lock_path}",
67 ]
68 assert [r.levelno for r in caplog.records] == [logging.DEBUG, logging.DEBUG, logging.DEBUG, logging.DEBUG]
69 assert [r.name for r in caplog.records] == ["filelock", "filelock", "filelock", "filelock"]
70 assert logging.getLogger("filelock").level == logging.NOTSET
71
72
73 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
74 @pytest.mark.parametrize("path_type", [str, PurePath, Path])
75 @pytest.mark.parametrize("filename", ["a", "new/b", "new2/new3/c"])
76 @pytest.mark.asyncio
77 async def test_acquire(
78 lock_type: type[BaseAsyncFileLock],
79 path_type: type[str | Path],
80 filename: str,
81 tmp_path: Path,
82 caplog: pytest.LogCaptureFixture,
83 ) -> None:
84 caplog.set_level(logging.DEBUG)
85
86 lock_path = tmp_path / filename
87 lock = lock_type(path_type(lock_path))
88 async with await lock.acquire() as locked:
89 assert lock.is_locked
90 assert lock is locked
91 assert not lock.is_locked
92
93 assert caplog.messages == [
94 f"Attempting to acquire lock {id(lock)} on {lock_path}",
95 f"Lock {id(lock)} acquired on {lock_path}",
96 f"Attempting to release lock {id(lock)} on {lock_path}",
97 f"Lock {id(lock)} released on {lock_path}",
98 ]
99 assert [r.levelno for r in caplog.records] == [logging.DEBUG, logging.DEBUG, logging.DEBUG, logging.DEBUG]
100 assert [r.name for r in caplog.records] == ["filelock", "filelock", "filelock", "filelock"]
101 assert logging.getLogger("filelock").level == logging.NOTSET
102
103
104 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
105 @pytest.mark.asyncio
106 async def test_non_blocking(lock_type: type[BaseAsyncFileLock], tmp_path: Path) -> None:
107 lock_path = tmp_path / "a"
108 lock_1, lock_2 = lock_type(str(lock_path)), lock_type(str(lock_path))
109 lock_3 = lock_type(str(lock_path), blocking=False)
110 lock_4 = lock_type(str(lock_path), timeout=0)
111 lock_5 = lock_type(str(lock_path), blocking=False, timeout=-1)
112
113 await lock_1.acquire()
114 assert lock_1.is_locked
115 assert not lock_2.is_locked
116 assert not lock_3.is_locked
117 assert not lock_4.is_locked
118 assert not lock_5.is_locked
119
120 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
121 await lock_2.acquire(blocking=False)
122 assert not lock_2.is_locked
123 assert lock_1.is_locked
124
125 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
126 await lock_3.acquire()
127 assert not lock_3.is_locked
128 assert lock_1.is_locked
129
130 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
131 async with lock_3:
132 pass # pragma: no cover # __aenter__ raises Timeout, so the body never runs
133 assert not lock_3.is_locked
134 assert lock_1.is_locked
135
136 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
137 await lock_4.acquire()
138 assert not lock_4.is_locked
139 assert lock_1.is_locked
140
141 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
142 async with lock_4:
143 pass # pragma: no cover # __aenter__ raises Timeout, so the body never runs
144 assert not lock_4.is_locked
145 assert lock_1.is_locked
146
147 # blocking precedence over timeout
148 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
149 await lock_5.acquire()
150 assert not lock_5.is_locked
151 assert lock_1.is_locked
152
153 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
154 async with lock_5:
155 pass # pragma: no cover # __aenter__ raises Timeout, so the body never runs
156 assert not lock_5.is_locked
157 assert lock_1.is_locked
158
159 await lock_1.release()
160 assert not lock_1.is_locked
161 assert not lock_2.is_locked
162 assert not lock_3.is_locked
163 assert not lock_4.is_locked
164 assert not lock_5.is_locked
165
166
167 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
168 @pytest.mark.parametrize("thread_local", [True, False])
169 @pytest.mark.asyncio
170 async def test_non_executor(lock_type: type[BaseAsyncFileLock], thread_local: bool, tmp_path: Path) -> None:
171 lock = lock_type(str(tmp_path / "a"), thread_local=thread_local, run_in_executor=False)
172 async with lock as locked:
173 assert lock.is_locked
174 assert lock is locked
175 assert not lock.is_locked
176
177
178 @pytest.mark.asyncio
179 async def test_coroutine_function(tmp_path: Path) -> None:
180 acquired = released = False
181
182 class AioFileLock(BaseAsyncFileLock):
183 async def _acquire(self) -> None: # ty: ignore[invalid-method-override]
184 nonlocal acquired
185 acquired = True
186 self._context.lock_file_fd = 1
187
188 async def _release(self) -> None: # ty: ignore[invalid-method-override]
189 nonlocal released
190 released = True
191 self._context.lock_file_fd = None
192
193 lock = AioFileLock(str(tmp_path / "a"))
194 await lock.acquire()
195 assert acquired
196 assert not released
197 await lock.release()
198 assert acquired
199 assert released
200
201
202 @pytest.mark.asyncio
203 async def test_coroutine_acquire_without_holding_polls_and_skips_on_acquired(tmp_path: Path) -> None:
204 attempts: list[str] = []
205
206 class NeverHoldsLock(BaseAsyncFileLock):
207 async def _acquire(self) -> None: # ty: ignore[invalid-method-override]
208 attempts.append(self.lock_file) # returns without setting the fd, so is_locked stays False
209
210 async def _release(self) -> None: # ty: ignore[invalid-method-override]
211 self._context.lock_file_fd = None # pragma: no cover # never held, so release never runs
212
213 lock = NeverHoldsLock(str(tmp_path / "a"), timeout=0.1)
214 with pytest.raises(Timeout):
215 await lock.acquire()
216
217 # The coroutine backend returned without acquiring, so the tracker skipped on_acquired and the poll loop retried.
218 assert len(attempts) >= 2
219 assert not lock.is_locked
220
221
222 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
223 @pytest.mark.asyncio
224 async def test_wait_message_logged(
225 lock_type: type[BaseAsyncFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
226 ) -> None:
227 caplog.set_level(logging.DEBUG)
228 lock_path = tmp_path / "a"
229 first_lock = lock_type(str(lock_path))
230 second_lock = lock_type(str(lock_path), timeout=0.2)
231
232 # Hold the lock so second_lock has to wait
233 await first_lock.acquire()
234 with pytest.raises(Timeout):
235 await second_lock.acquire()
236 assert any("waiting" in msg for msg in caplog.messages)
237
238
239 @pytest.mark.parametrize("lock_type", [AsyncSoftFileLock, AsyncFileLock])
240 @pytest.mark.asyncio
241 async def test_attempting_to_acquire_branch(
242 lock_type: type[BaseAsyncFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
243 ) -> None:
244 caplog.set_level(logging.DEBUG)
245
246 lock = lock_type(str(tmp_path / "a"))
247 await lock.acquire()
248 assert any("Attempting to acquire lock" in m for m in caplog.messages)
249 await lock.release()
250
251
252 @pytest.mark.asyncio
253 async def test_thread_local_run_in_executor(tmp_path: Path) -> None: # ruff:ignore[unused-async] # the asyncio marker requires a coroutine though the body awaits nothing
254 with pytest.raises(ValueError, match="run_in_executor is not supported when thread_local is True"):
255 AsyncSoftFileLock(str(tmp_path / "a"), thread_local=True, run_in_executor=True)
256
257
258 @pytest.mark.parametrize("lock_type", [AsyncSoftFileLock, AsyncFileLock])
259 @pytest.mark.asyncio
260 async def test_attempting_to_acquire(
261 lock_type: type[BaseAsyncFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
262 ) -> None:
263 caplog.set_level(logging.DEBUG)
264 lock = lock_type(str(tmp_path / "a.lock"), run_in_executor=False)
265 await lock.acquire(timeout=0.1)
266 assert any("Attempting to acquire lock" in m for m in caplog.messages)
267 await lock.release()
268
269
270 @pytest.mark.parametrize("lock_type", [AsyncSoftFileLock, AsyncFileLock])
271 @pytest.mark.asyncio
272 async def test_attempting_to_release(
273 lock_type: type[BaseAsyncFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
274 ) -> None:
275 caplog.set_level(logging.DEBUG)
276 lock = lock_type(str(tmp_path / "a.lock"), run_in_executor=False)
277
278 await lock.acquire(timeout=0.1)
279 await lock.acquire(timeout=0.1) # reentrant acquire
280 await lock.release(force=True)
281
282 assert any("Attempting to release lock" in m for m in caplog.messages)
283 assert any("released" in m for m in caplog.messages)
284
285
286 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
287 @pytest.mark.asyncio
288 async def test_release_early_exit_when_unlocked(lock_type: type[BaseAsyncFileLock], tmp_path: Path) -> None:
289 lock = lock_type(str(tmp_path / "a.lock"), run_in_executor=False)
290 assert not lock.is_locked
291 await lock.release()
292 assert not lock.is_locked
293
294
295 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
296 @pytest.mark.asyncio
297 async def test_release_nonzero_counter_exit(
298 lock_type: type[BaseAsyncFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
299 ) -> None:
300 caplog.set_level(logging.DEBUG)
301 lock = lock_type(str(tmp_path / "a.lock"), run_in_executor=False)
302 await lock.acquire()
303 await lock.acquire()
304 await lock.release()
305 assert lock.lock_counter == 1
306 assert lock.is_locked
307 assert not any("Attempting to release" in m for m in caplog.messages)
308 await lock.release()
309
310
311 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
312 @pytest.mark.asyncio
313 async def test_cancel_check_triggers(lock_type: type[BaseAsyncFileLock], tmp_path: Path) -> None:
314 lock_path = tmp_path / "a"
315 lock_1 = lock_type(str(lock_path))
316 lock_2 = lock_type(str(lock_path))
317
318 await lock_1.acquire()
319
320 with pytest.raises(Timeout, match=r"The file lock '.*' could not be acquired."):
321 await lock_2.acquire(timeout=1, cancel_check=lambda: True)
322 assert not lock_2.is_locked
323 await lock_1.release()
324
325
326 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
327 @pytest.mark.asyncio
328 async def test_cancel_check_not_called_when_lock_available(lock_type: type[BaseAsyncFileLock], tmp_path: Path) -> None:
329 lock = lock_type(str(tmp_path / "a"))
330
331 called = False
332
333 def should_not_be_called() -> bool: # pragma: no cover # a free lock never consults cancel_check
334 nonlocal called
335 called = True
336 return True
337
338 await lock.acquire(cancel_check=should_not_be_called)
339 assert lock.is_locked
340 assert not called
341 await lock.release()
342
343
344 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
345 @pytest.mark.asyncio
346 async def test_cancel_check_log_message(
347 lock_type: type[BaseAsyncFileLock], tmp_path: Path, caplog: pytest.LogCaptureFixture
348 ) -> None:
349 caplog.set_level(logging.DEBUG)
350 lock_path = tmp_path / "a"
351 lock_1 = lock_type(str(lock_path))
352 lock_2 = lock_type(str(lock_path))
353
354 await lock_1.acquire()
355 with pytest.raises(Timeout):
356 await lock_2.acquire(timeout=1, cancel_check=lambda: True)
357 assert any("Cancellation requested" in msg for msg in caplog.messages)
358 await lock_1.release()
359
360
361 @pytest.mark.parametrize(
362 "lock_type",
363 [pytest.param(AsyncFileLock, id="async"), pytest.param(AsyncSoftFileLock, id="soft")],
364 )
365 def test_sync_with_raises_not_implemented_error(lock_type: type[BaseAsyncFileLock], tmp_path: Path) -> None:
366 # __exit__ must exist so Python can call it after __enter__ raises; without it AttributeError hides the real error
367 with pytest.raises(NotImplementedError, match=r"async with"), lock_type(str(tmp_path / "test.lock")):
368 pass # pragma: no cover # __enter__ raises NotImplementedError, so the body never runs
369
370
371 @pytest.mark.parametrize(
372 "lock_type",
373 [pytest.param(AsyncFileLock, id="async"), pytest.param(AsyncSoftFileLock, id="soft")],
374 )
375 def test_del_after_loop_close_does_not_raise(lock_type: type[BaseAsyncFileLock], tmp_path: Path) -> None:
376 # __del__ must not call get_running_loop(); it raises RuntimeError when no loop is running
377 def _run() -> None:
378 lock = lock_type(str(tmp_path / "test.lock"))
379 loop = asyncio.new_event_loop()
380 asyncio.set_event_loop(loop)
381 try:
382 loop.run_until_complete(lock.acquire())
383 loop.run_until_complete(lock.release(force=True))
384 finally:
385 loop.close()
386 asyncio.set_event_loop(None)
387 del lock
388 gc.collect()
389
390 with ThreadPoolExecutor(max_workers=1) as pool:
391 pool.submit(_run).result(timeout=10)
392
393
394 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
395 @pytest.mark.asyncio
396 async def test_same_task_different_instances_raises(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
397 lock_path = tmp_path / "test.lock"
398 lock1 = lock_type(lock_path)
399 async with lock1:
400 lock2 = lock_type(lock_path)
401 with pytest.raises(RuntimeError, match="Deadlock"):
402 await lock2.acquire()
403
404
405 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
406 @pytest.mark.asyncio
407 async def test_finite_timeout_gives_timeout_not_deadlock(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
408 lock_path = tmp_path / "test.lock"
409 lock1 = lock_type(lock_path)
410 async with lock1:
411 lock2 = lock_type(lock_path, timeout=0.1)
412 with pytest.raises(Timeout):
413 await lock2.acquire()
414
415
416 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
417 @pytest.mark.asyncio
418 async def test_non_blocking_gives_timeout_not_deadlock(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
419 lock_path = tmp_path / "test.lock"
420 lock1 = lock_type(lock_path)
421 async with lock1:
422 lock2 = lock_type(lock_path, blocking=False)
423 with pytest.raises(Timeout):
424 await lock2.acquire()
425
426
427 @pytest.mark.parametrize(
428 "mode",
429 [pytest.param("finite", id="finite"), pytest.param("nonblocking", id="nonblocking")],
430 )
431 @pytest.mark.asyncio
432 async def test_failed_acquire_keeps_holder_registered(tmp_path: Path, mode: Literal["finite", "nonblocking"]) -> None:
433 lock_path = tmp_path / "test.lock"
434 async with AsyncFileLock(lock_path, run_in_executor=False):
435 with pytest.raises(Timeout):
436 await _acquire_for_mode(AsyncFileLock(lock_path, run_in_executor=False), mode)
437 with pytest.raises(RuntimeError, match="Deadlock"):
438 await AsyncFileLock(lock_path, run_in_executor=False).acquire(cancel_check=lambda: True)
439
440
441 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
442 @pytest.mark.asyncio
443 async def test_different_paths_no_conflict(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
444 lock1 = lock_type(tmp_path / "a.lock")
445 lock2 = lock_type(tmp_path / "b.lock")
446 async with lock1, lock2:
447 assert lock1.is_locked
448 assert lock2.is_locked
449
450
451 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
452 @pytest.mark.asyncio
453 async def test_same_instance_reentrant_works(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
454 lock = lock_type(tmp_path / "test.lock")
455 async with lock:
456 async with lock:
457 assert lock.is_locked
458 assert lock.is_locked
459 assert not lock.is_locked
460
461
462 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
463 @pytest.mark.asyncio
464 async def test_singleton_avoids_deadlock(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
465 lock_path = tmp_path / "test.lock"
466 lock1 = lock_type(lock_path, is_singleton=True)
467 async with lock1:
468 lock2 = lock_type(lock_path, is_singleton=True)
469 assert lock1 is lock2
470 async with lock2:
471 assert lock2.is_locked
472
473
474 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
475 @pytest.mark.asyncio
476 async def test_different_tasks_no_false_positive(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
477 # The registry is per-thread, so a second acquire from a different task must not look like a reentrant deadlock.
478 lock_path = tmp_path / "test.lock"
479 lock1 = lock_type(lock_path, timeout=0)
480 await lock1.acquire()
481
482 error: BaseException | None = None
483
484 async def acquire_other() -> None:
485 nonlocal error
486 lock2 = lock_type(lock_path, timeout=0)
487 try:
488 await lock2.acquire()
489 except BaseException as exc:
490 error = exc
491
492 await asyncio.create_task(acquire_other())
493 await lock1.release()
494
495 assert not isinstance(error, RuntimeError), "Should not raise RuntimeError in a different task"
496
497
498 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
499 @pytest.mark.asyncio
500 async def test_cross_task_blocking_acquire_queues(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
501 # A blocking acquire from a different task must queue behind the holder, not raise. Polling yields the event
502 # loop on every iteration, so the holder keeps running and releases; only a same-task reentry can deadlock.
503 # The waiter starts on an event the holder sets once it holds: yielding with sleep(0) instead would let the
504 # waiter run its check before the holder registers, so an empty registry would pass even with the bug.
505 lock_path = tmp_path / "test.lock"
506 events: list[str] = []
507 holding = asyncio.Event()
508
509 async def holder() -> None:
510 async with lock_type(lock_path):
511 events.append("holder:acquired")
512 holding.set()
513 await asyncio.sleep(0.05) # the waiter polls while the lock is held
514 events.append("holder:released")
515
516 async def waiter() -> None:
517 await holding.wait()
518 async with lock_type(lock_path):
519 events.append("waiter:acquired")
520
521 await asyncio.gather(holder(), waiter()) # propagates a false-positive Deadlock
522
523 assert events == ["holder:acquired", "holder:released", "waiter:acquired"]
524
525
526 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
527 @pytest.mark.asyncio
528 async def test_release_from_different_task_clears_registry(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
529 # The holder scope is pinned at commit time, so releasing from a different task still drops the registry entry.
530 lock_path = tmp_path / "test.lock"
531 lock = lock_type(lock_path)
532 await lock.acquire()
533
534 async def release() -> None:
535 await lock.release()
536
537 await asyncio.create_task(release())
538
539 async with lock_type(lock_path): # would raise Deadlock if the scoped entry had leaked
540 pass
541
542
543 @NEEDS_PARENT_SYMLINK_COLLAPSE
544 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
545 @pytest.mark.asyncio # pragma: win32 no cover
546 async def test_symlink_same_canonical_path(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
547 # A symlinked parent directory resolves to the same canonical key; the final component stays literal.
548 real_dir = tmp_path / "real"
549 real_dir.mkdir()
550 (tmp_path / "link").symlink_to(real_dir)
551
552 lock1 = lock_type(str(real_dir / "test.lock"))
553 async with lock1:
554 lock2 = lock_type(str(tmp_path / "link" / "test.lock"))
555 with pytest.raises(RuntimeError, match="Deadlock"):
556 await lock2.acquire()
557
558
559 @NEEDS_FCNTL
560 @pytest.mark.parametrize(
561 ("depth", "force"),
562 [
563 pytest.param(1, False, id="direct"),
564 pytest.param(2, False, id="nested"),
565 pytest.param(2, True, id="forced"),
566 ],
567 )
568 @pytest.mark.asyncio # pragma: needs fcntl
569 async def test_release_drops_acquisition_key_after_parent_retarget(tmp_path: Path, depth: int, force: bool) -> None:
570 lock_path, original_path, replacement_path = _symlinked_lock_paths(tmp_path)
571 lock = AsyncFileLock(lock_path, run_in_executor=False)
572 for _depth in range(depth):
573 await lock.acquire()
574 _retarget_parent(lock_path, replacement_path)
575
576 if force:
577 await lock.release(force=True)
578 else:
579 for _depth in range(depth):
580 await lock.release()
581
582 async with AsyncFileLock(original_path, run_in_executor=False) as successor:
583 assert successor.is_locked
584
585
586 @NEEDS_FCNTL
587 @pytest.mark.asyncio
588 async def test_release_keeps_retargeted_parent_holder_registered(tmp_path: Path) -> None: # pragma: needs fcntl
589 lock_path, _original_path, replacement_path = _symlinked_lock_paths(tmp_path)
590 original = AsyncFileLock(lock_path, run_in_executor=False)
591 await original.acquire()
592 _retarget_parent(lock_path, replacement_path)
593 async with AsyncFileLock(replacement_path, run_in_executor=False):
594 await original.release()
595 with pytest.raises(RuntimeError, match="Deadlock"):
596 await AsyncFileLock(replacement_path, run_in_executor=False).acquire(cancel_check=lambda: True)
597
598
599 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
600 @pytest.mark.asyncio
601 async def test_deadlock_registry_cleanup_on_release(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
602 lock_path = tmp_path / "test.lock"
603 lock1 = lock_type(lock_path)
604 await lock1.acquire()
605 await lock1.release()
606
607 lock2 = lock_type(lock_path)
608 async with lock2:
609 assert lock2.is_locked
610
611
612 @pytest.mark.parametrize("lock_type", [AsyncFileLock, AsyncSoftFileLock])
613 @pytest.mark.asyncio
614 async def test_force_release_clears_registry(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
615 lock_path = tmp_path / "test.lock"
616 lock1 = lock_type(lock_path)
617 async with lock1:
618 await lock1.acquire()
619 assert lock1.lock_counter == 2
620 await lock1.release(force=True)
621
622 lock2 = lock_type(lock_path)
623 async with lock2:
624 assert lock2.is_locked
625
626
627 def _symlinked_lock_paths(tmp_path: Path) -> tuple[Path, Path, Path]: # pragma: needs fcntl
628 original = tmp_path / "original"
629 replacement = tmp_path / "replacement"
630 original.mkdir()
631 replacement.mkdir()
632 link = tmp_path / "link"
633 link.symlink_to(original, target_is_directory=True)
634 return link / "test.lock", original / "test.lock", replacement / "test.lock"
635
636
637 def _retarget_parent(lock_path: Path, replacement_path: Path) -> None: # pragma: needs fcntl
638 link = lock_path.parent
639 link.unlink()
640 link.symlink_to(replacement_path.parent, target_is_directory=True)
641
642
643 async def _acquire_for_mode(lock: BaseAsyncFileLock, mode: Literal["finite", "nonblocking"]) -> None:
644 if mode == "finite":
645 await lock.acquire(timeout=0)
646 else:
647 await lock.acquire(blocking=False)
648
649
650 @NEEDS_FCNTL
651 @pytest.mark.asyncio # pragma: needs fcntl
652 async def test_release_keeps_lock_held_when_unlock_fails(tmp_path: Path, mocker: MockerFixture) -> None:
653 lock = AsyncFileLock(str(tmp_path / "a"))
654 await lock.acquire()
655 mocker.patch("filelock._unix.fcntl.flock", side_effect=[OSError(EIO, "unlock failed"), None])
656 with pytest.raises(OSError, match="unlock failed"):
657 await lock.release()
658 assert lock.is_locked
659 assert lock.lock_counter == 1
660 await lock.release()
661 assert not lock.is_locked
662
663
664 @pytest.mark.asyncio
665 async def test_async_zero_write_rolls_back_acquire(tmp_path: Path, mocker: MockerFixture) -> None:
666 mocker.patch("filelock._util.os.write", return_value=0)
667
668 lock = AsyncSoftFileLock(str(tmp_path / "a"))
669 with pytest.raises(OSError, match="0 bytes"):
670 await lock.acquire()
671 assert not lock.is_locked
672
673
674 @pytest.mark.parametrize(
675 ("policy", "surfaces"),
676 [pytest.param("default", True, id="default"), pytest.param("suppress", False, id="suppress")],
677 )
678 @pytest.mark.asyncio
679 async def test_soft_close_error_policy_cleans_marker(
680 tmp_path: Path,
681 mocker: MockerFixture,
682 policy: CloseErrorPolicy,
683 *,
684 surfaces: bool,
685 ) -> None:
686 lock_path = tmp_path / "a"
687 lock = AsyncSoftFileLock(lock_path, close_error_policy=policy, run_in_executor=False)
688 await lock.acquire()
689 with _close_after_commit(mocker, lock) as (close_error, attempts):
690 if surfaces:
691 with pytest.raises(OSError, match="close failed") as info:
692 await lock.release()
693 assert info.value is close_error
694 else:
695 await lock.release()
696 assert (len(attempts), lock.is_locked, lock.lock_counter, lock_path.exists()) == (1, False, 0, False)
697
698
699 @pytest.mark.parametrize(
700 ("depth", "force"),
701 [pytest.param(2, False, id="nested"), pytest.param(2, True, id="forced")],
702 )
703 @pytest.mark.asyncio
704 async def test_soft_close_error_suppression_releases_once(
705 tmp_path: Path,
706 mocker: MockerFixture,
707 depth: int,
708 *,
709 force: bool,
710 ) -> None:
711 lock_path = tmp_path / "a"
712 lock = AsyncSoftFileLock(lock_path, close_error_policy="suppress", run_in_executor=False)
713 for _acquisition in range(depth):
714 await lock.acquire()
715 with _close_after_commit(mocker, lock) as (_, attempts):
716 if force:
717 await lock.release(force=True)
718 else:
719 for _release in range(depth):
720 await lock.release()
721 assert (len(attempts), lock.is_locked, lock.lock_counter, lock_path.exists()) == (1, False, 0, False)
722
723
724 @pytest.mark.parametrize(
725 "use_proxy",
726 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
727 )
728 @pytest.mark.asyncio
729 async def test_soft_context_surfaces_close_error_after_cleanup(
730 tmp_path: Path,
731 mocker: MockerFixture,
732 *,
733 use_proxy: bool,
734 ) -> None:
735 lock_path = tmp_path / "a"
736 lock = AsyncSoftFileLock(lock_path, run_in_executor=False)
737 with (
738 _close_after_commit(mocker, lock) as (close_error, attempts),
739 pytest.raises(OSError, match="close failed") as info,
740 ):
741 async with await lock.acquire() if use_proxy else lock:
742 pass
743 assert (info.value, len(attempts), lock.is_locked, lock_path.exists()) == (close_error, 1, False, False)
744
745
746 @pytest.mark.asyncio
747 async def test_soft_second_release_does_not_close_reused_descriptor(
748 tmp_path: Path,
749 mocker: MockerFixture,
750 ) -> None:
751 lock = AsyncSoftFileLock(tmp_path / "a", run_in_executor=False)
752 await lock.acquire()
753 with (
754 _close_after_commit(mocker, lock) as (close_error, attempts),
755 pytest.raises(OSError, match="close failed") as info,
756 ):
757 await lock.release()
758 assert info.value is close_error
759 reused_fd = os.open(tmp_path / "reused", os.O_CREAT | os.O_WRONLY)
760 assert reused_fd == attempts[0]
761 try:
762 await lock.release()
763 os.fstat(reused_fd)
764 finally:
765 os.close(reused_fd)
766
767
768 @contextmanager
769 def _close_after_commit(mocker: MockerFixture, lock: AsyncSoftFileLock) -> Iterator[tuple[OSError, list[int]]]:
770 real_close = os.close
771 close_error = OSError(EINTR, "close failed")
772 attempts: list[int] = []
773 # close is an attribute of the shared os module, so this patch binds for every close in the process while the
774 # window is open, including one a GC-run finalizer (a multiprocessing pipe from an earlier test, say) makes on this
775 # very thread. Fail only the descriptor this lock lets go of: it clears its bookkeeping right before the one close
776 # attempt, so record the descriptor as it does.
777 released: list[int | None] = []
778 real_mark_released = lock._mark_descriptor_released
779
780 def mark_released() -> None:
781 released.append(lock._context.lock_file_fd)
782 real_mark_released()
783
784 def close(fd: int) -> None:
785 real_close(fd)
786 if fd not in released:
787 return
788 attempts.append(fd)
789 raise close_error
790
791 mocker.patch.object(lock, "_mark_descriptor_released", side_effect=mark_released)
792 close_mock = mocker.patch("filelock._soft.os.close", side_effect=close)
793 try:
794 yield close_error, attempts
795 finally:
796 mocker.stop(close_mock)
797
798
799 @pytest.mark.asyncio
800 async def test_close_after_commit_ignores_other_descriptors(tmp_path: Path, mocker: MockerFixture) -> None:
801 # The patch binds os.close process-wide, so a descriptor that is not the lock's, whether closed on another thread
802 # or by a finalizer the collector happens to run on this one, must pass through cleanly and stay out of the
803 # recorded attempts.
804 lock = AsyncSoftFileLock(tmp_path / "a", run_in_executor=False)
805 await lock.acquire()
806 closed: list[int] = []
807
808 def close_a_pipe() -> None:
809 read_fd, write_fd = os.pipe()
810 os.close(read_fd)
811 os.close(write_fd)
812 closed.extend((read_fd, write_fd))
813
814 with _close_after_commit(mocker, lock) as (_close_error, attempts):
815 close_a_pipe()
816 worker = threading.Thread(target=close_a_pipe)
817 worker.start()
818 worker.join()
819 with pytest.raises(OSError, match="close failed"):
820 await lock.release()
821
822 assert (len(closed), len(attempts), attempts[0] in closed) == (4, 1, False)
823
824
825 @pytest.mark.parametrize(
826 "use_proxy",
827 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
828 )
829 @pytest.mark.asyncio
830 async def test_context_group_detaches_release_context(
831 tmp_path: Path,
832 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
833 *,
834 use_proxy: bool,
835 ) -> None:
836 capture, release_error, release_cause = close_failure
837 body_error = ValueError("body failed")
838 body_cause = LookupError("body cause")
839 lock = AsyncFileLock(
840 str(tmp_path / "a"),
841 thread_local=False,
842 context_error_policy="group",
843 close_error_policy="raise",
844 on_acquired=capture,
845 )
846 with pytest.raises(ExceptionGroup) as info:
847 async with await lock.acquire() if use_proxy else lock:
848 raise body_error from body_cause
849 assert (
850 info.value.exceptions,
851 body_error.__context__,
852 release_error.__context__,
853 body_error.__cause__,
854 release_error.__cause__,
855 body_error.__traceback__ is not None,
856 release_error.__traceback__ is not None,
857 ) == ((body_error, release_error), None, None, body_cause, release_cause, True, True)
858
859
860 @pytest.mark.skipif(
861 sys.version_info < (3, 11), reason="standard exception-group rendering requires Python 3.11"
862 ) # pragma: >=3.11 cover
863 @pytest.mark.parametrize(
864 "use_proxy",
865 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
866 )
867 @pytest.mark.asyncio
868 async def test_context_group_renders_independent_leaves(
869 tmp_path: Path,
870 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
871 *,
872 use_proxy: bool,
873 ) -> None:
874 capture, release_error, _ = close_failure
875 release_error.__cause__ = None
876 release_error.__suppress_context__ = False
877 body_error = ValueError("body failed")
878 lock = AsyncFileLock(
879 str(tmp_path / "a"),
880 thread_local=False,
881 context_error_policy="group",
882 close_error_policy="raise",
883 on_acquired=capture,
884 )
885 with pytest.raises(ExceptionGroup) as info:
886 async with await lock.acquire() if use_proxy else lock:
887 raise body_error
888 group_rendering = "".join(traceback.format_exception(info.value))
889 release_rendering = "".join(traceback.format_exception(release_error))
890 assert (
891 group_rendering.count("ValueError: body failed"),
892 release_rendering.count("ValueError: body failed"),
893 release_rendering.count("RuntimeError: release cause"),
894 release_rendering.count("OSError: release failed"),
895 ) == (1, 0, 0, 1)
896
897
898 @pytest.mark.parametrize(
899 "use_proxy",
900 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
901 )
902 @pytest.mark.asyncio
903 async def test_context_chain_keeps_release_error_with_body_in_context(
904 tmp_path: Path,
905 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
906 *,
907 use_proxy: bool,
908 ) -> None:
909 capture, release_error, _ = close_failure
910 body_error = ValueError("body failed")
911 lock = AsyncFileLock(
912 str(tmp_path / "a"),
913 thread_local=False,
914 context_error_policy="chain",
915 close_error_policy="raise",
916 on_acquired=capture,
917 )
918 with pytest.raises(OSError, match="release failed") as info:
919 async with await lock.acquire() if use_proxy else lock:
920 raise body_error
921 assert (info.value, release_error.__context__) == (release_error, body_error)
922
923
924 @pytest.mark.parametrize(
925 "policy",
926 [pytest.param("chain", id="chain"), pytest.param("group", id="group")],
927 )
928 @pytest.mark.parametrize(
929 "use_proxy",
930 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
931 )
932 @pytest.mark.asyncio
933 async def test_context_body_only_failure_propagates_body(
934 tmp_path: Path, policy: ContextErrorPolicy, *, use_proxy: bool
935 ) -> None:
936 lock = AsyncSoftFileLock(str(tmp_path / "a"), context_error_policy=policy)
937 body = ValueError("body failed")
938 with pytest.raises(ValueError, match="body failed") as info:
939 async with await lock.acquire() if use_proxy else lock:
940 raise body
941 assert info.value is body
942
943
944 @pytest.mark.parametrize(
945 "policy",
946 [pytest.param("chain", id="chain"), pytest.param("group", id="group")],
947 )
948 @pytest.mark.parametrize(
949 "use_proxy",
950 [pytest.param(False, id="direct"), pytest.param(True, id="proxy")],
951 )
952 @pytest.mark.asyncio
953 async def test_context_release_only_failure_propagates_release(
954 tmp_path: Path,
955 close_failure: tuple[Callable[[int], None], OSError, RuntimeError],
956 policy: ContextErrorPolicy,
957 *,
958 use_proxy: bool,
959 ) -> None:
960 capture, release_error, release_cause = close_failure
961 lock = AsyncFileLock(
962 str(tmp_path / "a"),
963 thread_local=False,
964 context_error_policy=policy,
965 close_error_policy="raise",
966 on_acquired=capture,
967 )
968 with pytest.raises(OSError, match="release failed") as info:
969 async with await lock.acquire() if use_proxy else lock:
970 pass
971 assert (info.value, release_error.__context__, release_error.__cause__) == (release_error, None, release_cause)
972
973
974 @pytest.mark.asyncio
975 async def test_context_group_base_exception_leaf_is_base_group(
976 tmp_path: Path, close_failure: tuple[Callable[[int], None], OSError, RuntimeError]
977 ) -> None:
978 capture, _, _ = close_failure
979 lock = AsyncFileLock(
980 str(tmp_path / "a"),
981 thread_local=False,
982 context_error_policy="group",
983 close_error_policy="raise",
984 on_acquired=capture,
985 )
986 with pytest.raises(BaseExceptionGroup) as info:
987 async with lock:
988 raise KeyboardInterrupt
989 assert not isinstance(info.value, ExceptionGroup)
990 assert [type(leaf) for leaf in info.value.exceptions] == [KeyboardInterrupt, OSError]
991
992
993 @pytest.mark.asyncio
994 async def test_context_group_preserves_user_release_cancellation_group(tmp_path: Path) -> None:
995 body_error = ValueError("body failed")
996 backend_cancellation = asyncio.CancelledError("backend canceled")
997 backend_error = OSError(EIO, "backend failed")
998 release_group = BaseExceptionGroup(
999 "lock release cancellation and backend release both failed",
1000 (backend_cancellation, backend_error),
1001 )
1002 fail_release = True
1003
1004 class GroupReleaseLock(BaseAsyncFileLock):
1005 def _acquire(self) -> None:
1006 self._context.lock_file_fd = 1
1007
1008 def _release(self) -> None:
1009 nonlocal fail_release
1010 if fail_release:
1011 fail_release = False
1012 raise release_group
1013 self._context.lock_file_fd = None
1014
1015 lock = GroupReleaseLock(tmp_path / "a", run_in_executor=False, context_error_policy="group")
1016 with pytest.raises(BaseExceptionGroup) as info:
1017 async with lock:
1018 raise body_error
1019
1020 assert info.value.exceptions == (body_error, release_group)
1021 assert info.value.exceptions[1] is release_group
1022 assert release_group.exceptions == (backend_cancellation, backend_error)
1023 await lock.release()
1024
1025
1026 def _fail_close_of(mocker: MockerFixture, lock: BaseAsyncFileLock, error: OSError) -> None: # pragma: needs fcntl
1027 # Fail os.close only for this lock's descriptor, so an unrelated lock's __del__ close during the test is untouched.
1028 fd = lock._context.lock_file_fd
1029 real_close = os.close
1030
1031 def close(target: int) -> None:
1032 if target == fd:
1033 raise error
1034 real_close(target) # pragma: no cover # only an unrelated __del__ close during the mock window reaches here
1035
1036 mocker.patch("filelock._api.os.close", side_effect=close)
1037
1038
1039 @NEEDS_FCNTL
1040 @pytest.mark.asyncio
1041 async def test_close_error_raise_propagates(tmp_path: Path, mocker: MockerFixture) -> None: # pragma: needs fcntl
1042 lock = AsyncFileLock(str(tmp_path / "a"), close_error_policy="raise")
1043 await lock.acquire()
1044 _fail_close_of(mocker, lock, OSError(EIO, "close failed"))
1045 with pytest.raises(OSError, match="close failed"):
1046 await lock.release()
1047 assert not lock.is_locked
1048
1049
1050 @NEEDS_FCNTL
1051 @pytest.mark.asyncio # pragma: needs fcntl
1052 async def test_close_error_default_suppressed_on_unix(tmp_path: Path, mocker: MockerFixture) -> None:
1053 lock = AsyncFileLock(str(tmp_path / "a")) # default policy
1054 await lock.acquire()
1055 _fail_close_of(mocker, lock, OSError(EIO, "close failed"))
1056 await lock.release()
1057 assert not lock.is_locked
1058
1059
1060 @NEEDS_FCNTL
1061 @pytest.mark.asyncio # pragma: needs fcntl
1062 async def test_fallback_to_soft_disabled_raises_enosys(tmp_path: Path, mocker: MockerFixture) -> None:
1063 mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "no flock"))
1064 lock = AsyncFileLock(str(tmp_path / "a"), fallback_to_soft=False)
1065 with pytest.raises(OSError, match="no flock"):
1066 await lock.acquire()
1067 assert not lock.is_locked
1068 assert type(lock).__name__ == "AsyncUnixFileLock" # not swapped to the soft class
1069
1070
1071 def test_preserve_lock_file_async_soft_rejects(tmp_path: Path) -> None:
1072 with pytest.raises(ValueError, match="preserve_lock_file"):
1073 AsyncSoftFileLock(str(tmp_path / "a"), preserve_lock_file=True)
1074
1075
1076 @NEEDS_FCNTL
1077 @pytest.mark.asyncio
1078 async def test_preserve_lock_file_async_release_keeps_pathname(tmp_path: Path) -> None: # pragma: needs fcntl
1079 path = tmp_path / "a"
1080 lock = AsyncFileLock(str(path), preserve_lock_file=True)
1081 await lock.acquire()
1082 await lock.release()
1083 assert path.exists() # the native pathname survives an async release
1084 assert type(lock).__name__ == "AsyncUnixFileLock"
1085
1086
1087 def _failing_on_acquired(_fd: int) -> None: # pragma: needs fcntl
1088 msg = "hook failed"
1089 raise RuntimeError(msg)
1090
1091
1092 def test_on_acquired_async_soft_rejects(tmp_path: Path) -> None:
1093 with pytest.raises(ValueError, match="on_acquired"):
1094 AsyncSoftFileLock(str(tmp_path / "a"), on_acquired=lambda _fd: None)
1095
1096
1097 @NEEDS_FCNTL
1098 @pytest.mark.asyncio
1099 async def test_on_acquired_runs_in_backend_executor(tmp_path: Path) -> None: # pragma: needs fcntl
1100 hook_thread = -1
1101 fd_while_held = -1
1102
1103 def hook(fd: int) -> None:
1104 nonlocal hook_thread, fd_while_held
1105 hook_thread = threading.get_ident()
1106 if lock.is_locked: # pragma: no branch # on_acquired only ever runs while the lock is held
1107 fd_while_held = fd
1108
1109 lock = AsyncFileLock(str(tmp_path / "a"), thread_local=False, on_acquired=hook)
1110 await lock.acquire()
1111 try:
1112 assert fd_while_held >= 0 # the hook ran while the lock was held, with a real descriptor
1113 assert hook_thread != threading.get_ident() # in the backend executor, not the event-loop thread
1114 finally:
1115 await lock.release()
1116
1117
1118 @NEEDS_FCNTL
1119 @pytest.mark.asyncio
1120 async def test_on_acquired_async_failure_releases(tmp_path: Path) -> None: # pragma: needs fcntl
1121 lock = AsyncFileLock(str(tmp_path / "a"), thread_local=False, on_acquired=_failing_on_acquired)
1122 with pytest.raises(RuntimeError, match="hook failed"):
1123 await lock.acquire()
1124 assert not lock.is_locked
1125 assert lock.lock_counter == 0
1126
1127
1128 @pytest.mark.asyncio
1129 async def test_on_acquired_rollback_group_detaches_release_context(
1130 tmp_path: Path, close_failure: tuple[Callable[[int], None], OSError, RuntimeError]
1131 ) -> None:
1132 capture, release_error, release_cause = close_failure
1133 callback_error = RuntimeError("hook failed")
1134 callback_cause = LookupError("hook cause")
1135
1136 def fail(fd: int) -> None:
1137 capture(fd)
1138 raise callback_error from callback_cause
1139
1140 lock = AsyncFileLock(str(tmp_path / "a"), thread_local=False, close_error_policy="raise", on_acquired=fail)
1141 with pytest.raises(ExceptionGroup) as info:
1142 await lock.acquire()
1143 assert (
1144 info.value.exceptions,
1145 callback_error.__context__,
1146 release_error.__context__,
1147 callback_error.__cause__,
1148 release_error.__cause__,
1149 callback_error.__traceback__ is not None,
1150 release_error.__traceback__ is not None,
1151 ) == ((callback_error, release_error), None, None, callback_cause, release_cause, True, True)
1152
1153
1154 def test_async_del_without_any_loop_returns(tmp_path: Path, mocker: MockerFixture) -> None:
1155 # GC can finalize a lock with no loop running and none remembered, where releasing is impossible. Raise the lookup
1156 # rather than rely on no loop running here, which the surrounding tests decide.
1157 get_running_loop = mocker.patch("filelock.asyncio.asyncio.get_running_loop", side_effect=RuntimeError)
1158 lock = AsyncSoftFileLock(str(tmp_path / "a"))
1159 release = mocker.patch.object(lock, "release", autospec=True)
1160 # Any lock another test dropped reaches the same patched lookup, so only calls from here on count.
1161 get_running_loop.reset_mock()
1162
1163 lock.__del__() # ruff:ignore[unnecessary-dunder-call] # a finalizer test cannot ride on collection timing
1164
1165 # An unlocked finalizer asserts nothing on its own; the lookup and the absent release pin the path it took.
1166 assert (get_running_loop.called, release.called, lock.is_locked) == (True, False, False)