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