| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import sys |
| 5 |
from errno import EIO |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from filelock import AsyncFileLock, BaseAsyncFileLock |
| 11 |
from tests.capability_marks import XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 12 |
|
| 13 |
if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 14 |
from builtins import BaseExceptionGroup, ExceptionGroup # pragma: >=3.11 cover |
| 15 |
else: # pragma: no cover (<py311) |
| 16 |
from exceptiongroup import BaseExceptionGroup, ExceptionGroup |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from pathlib import Path |
| 20 |
|
| 21 |
|
| 22 |
@pytest.mark.asyncio |
| 23 |
async def test_release_serialized_skips_when_peer_already_released(tmp_path: Path) -> None: |
| 24 |
release_started = asyncio.Event() |
| 25 |
finish_release = asyncio.Event() |
| 26 |
releases = 0 |
| 27 |
|
| 28 |
class Lock(BaseAsyncFileLock): |
| 29 |
async def _acquire(self) -> None: # ty: ignore[invalid-method-override] |
| 30 |
self._context.lock_file_fd = 1 |
| 31 |
|
| 32 |
async def _release(self) -> None: # ty: ignore[invalid-method-override] |
| 33 |
nonlocal releases |
| 34 |
releases += 1 |
| 35 |
release_started.set() |
| 36 |
await finish_release.wait() |
| 37 |
self._context.lock_file_fd = None |
| 38 |
|
| 39 |
lock = Lock(tmp_path / "a", run_in_executor=False) |
| 40 |
await lock.acquire() |
| 41 |
first = asyncio.create_task(lock.release()) |
| 42 |
await release_started.wait() |
| 43 |
second = asyncio.create_task(lock.release()) |
| 44 |
await asyncio.sleep(0) # let the queued release block on the transition gate before the holder unlocks |
| 45 |
finish_release.set() |
| 46 |
await first |
| 47 |
await second |
| 48 |
|
| 49 |
assert releases == 1 # the queued release found the lock already gone and did no backend work |
| 50 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 51 |
|
| 52 |
|
| 53 |
@pytest.mark.asyncio |
| 54 |
@XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 55 |
async def test_release_cancellation_surfaces_backend_error(tmp_path: Path) -> None: |
| 56 |
backend_error = OSError(EIO, "backend release failed") |
| 57 |
release_started = asyncio.Event() |
| 58 |
finish_release = asyncio.Event() |
| 59 |
fail_release = True |
| 60 |
|
| 61 |
class Lock(BaseAsyncFileLock): |
| 62 |
async def _acquire(self) -> None: # ty: ignore[invalid-method-override] |
| 63 |
self._context.lock_file_fd = 1 |
| 64 |
|
| 65 |
async def _release(self) -> None: # ty: ignore[invalid-method-override] |
| 66 |
if fail_release: |
| 67 |
release_started.set() |
| 68 |
await finish_release.wait() |
| 69 |
raise backend_error |
| 70 |
self._context.lock_file_fd = None |
| 71 |
|
| 72 |
lock = Lock(tmp_path / "a", run_in_executor=False) |
| 73 |
await lock.acquire() |
| 74 |
task = asyncio.create_task(lock.release()) |
| 75 |
await release_started.wait() |
| 76 |
task.cancel("cancel release") |
| 77 |
finish_release.set() |
| 78 |
|
| 79 |
with pytest.raises(OSError, match="backend release failed") as info: |
| 80 |
await task |
| 81 |
assert info.value is backend_error |
| 82 |
assert isinstance(info.value.__context__, asyncio.CancelledError) |
| 83 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) # backend failed before unlocking, so state is kept |
| 84 |
|
| 85 |
fail_release = False |
| 86 |
await lock.release() |
| 87 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 88 |
|
| 89 |
|
| 90 |
@pytest.mark.asyncio |
| 91 |
@XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 92 |
async def test_acquire_cancellation_rollback_failure_surfaces_backend_error(tmp_path: Path) -> None: |
| 93 |
rollback_error = OSError(EIO, "rollback release failed") |
| 94 |
acquire_started = asyncio.Event() |
| 95 |
finish_acquire = asyncio.Event() |
| 96 |
fail_release = True |
| 97 |
|
| 98 |
class Lock(BaseAsyncFileLock): |
| 99 |
async def _acquire(self) -> None: # ty: ignore[invalid-method-override] |
| 100 |
acquire_started.set() |
| 101 |
await finish_acquire.wait() |
| 102 |
self._context.lock_file_fd = 1 |
| 103 |
|
| 104 |
async def _release(self) -> None: # ty: ignore[invalid-method-override] |
| 105 |
if fail_release: |
| 106 |
raise rollback_error |
| 107 |
self._context.lock_file_fd = None |
| 108 |
|
| 109 |
lock = Lock(tmp_path / "a", run_in_executor=False) |
| 110 |
task = asyncio.create_task(lock.acquire()) |
| 111 |
await acquire_started.wait() |
| 112 |
task.cancel("cancel acquire") |
| 113 |
finish_acquire.set() # let the backend finish acquiring, so cancellation must roll the acquired lock back |
| 114 |
|
| 115 |
with pytest.raises(OSError, match="rollback release failed") as info: |
| 116 |
await task |
| 117 |
assert info.value is rollback_error |
| 118 |
assert isinstance(info.value.__context__, asyncio.CancelledError) |
| 119 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) # rollback failed before unlocking, so state is kept |
| 120 |
|
| 121 |
fail_release = False |
| 122 |
await lock.release() |
| 123 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 124 |
|
| 125 |
|
| 126 |
@pytest.mark.asyncio |
| 127 |
async def test_registration_failure_rolls_back_and_surfaces_cleanup(tmp_path: Path) -> None: |
| 128 |
registration_error = RuntimeError("registration failed") |
| 129 |
rollback_error = OSError(EIO, "rollback release failed") |
| 130 |
fail_release = True |
| 131 |
|
| 132 |
class Lock(BaseAsyncFileLock): |
| 133 |
async def _acquire(self) -> None: # ty: ignore[invalid-method-override] |
| 134 |
self._context.lock_file_fd = 1 |
| 135 |
|
| 136 |
async def _release(self) -> None: # ty: ignore[invalid-method-override] |
| 137 |
if fail_release: |
| 138 |
raise rollback_error |
| 139 |
self._context.lock_file_fd = None |
| 140 |
|
| 141 |
def _register_context_descriptor(self) -> None: # ruff:ignore[no-self-use] # overrides a base instance method |
| 142 |
raise registration_error |
| 143 |
|
| 144 |
lock = Lock(tmp_path / "a", run_in_executor=False) |
| 145 |
with pytest.raises(ExceptionGroup) as info: |
| 146 |
await lock.acquire() |
| 147 |
assert info.value.message == "descriptor registration cleanup failed" |
| 148 |
assert info.value.exceptions == (registration_error, rollback_error) |
| 149 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) # rollback failed before unlocking, so state is kept |
| 150 |
|
| 151 |
fail_release = False |
| 152 |
await lock.release() |
| 153 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 154 |
|
| 155 |
|
| 156 |
@pytest.mark.parametrize( |
| 157 |
"rollback_fails", |
| 158 |
[pytest.param(True, id="rollback-fails"), pytest.param(False, id="rollback-succeeds")], |
| 159 |
) |
| 160 |
@pytest.mark.asyncio |
| 161 |
async def test_acquire_failure_with_registration_failure_rolls_back(tmp_path: Path, *, rollback_fails: bool) -> None: |
| 162 |
acquisition_error = RuntimeError("acquire failed") |
| 163 |
registration_error = LookupError("registration failed") |
| 164 |
rollback_error = OSError(EIO, "rollback release failed") |
| 165 |
fail_release = rollback_fails |
| 166 |
|
| 167 |
class Lock(BaseAsyncFileLock): |
| 168 |
async def _acquire(self) -> None: # ty: ignore[invalid-method-override] |
| 169 |
self._context.lock_file_fd = 1 |
| 170 |
raise acquisition_error |
| 171 |
|
| 172 |
async def _release(self) -> None: # ty: ignore[invalid-method-override] |
| 173 |
if fail_release: |
| 174 |
raise rollback_error |
| 175 |
self._context.lock_file_fd = None |
| 176 |
|
| 177 |
def _register_context_descriptor(self) -> None: # ruff:ignore[no-self-use] # overrides a base instance method |
| 178 |
raise registration_error |
| 179 |
|
| 180 |
lock = Lock(tmp_path / "a", run_in_executor=False) |
| 181 |
with pytest.raises(ExceptionGroup) as info: |
| 182 |
await lock.acquire() |
| 183 |
assert info.value.message == "lock acquisition cleanup failed" |
| 184 |
if rollback_fails: |
| 185 |
assert info.value.exceptions == (acquisition_error, registration_error, rollback_error) |
| 186 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) # rollback failed before unlocking, so state is kept |
| 187 |
fail_release = False |
| 188 |
await lock.release() |
| 189 |
else: |
| 190 |
assert info.value.exceptions == (acquisition_error, registration_error) |
| 191 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 192 |
|
| 193 |
|
| 194 |
@pytest.mark.asyncio |
| 195 |
async def test_context_group_reconciles_release_cancellation_with_backend_error(tmp_path: Path) -> None: |
| 196 |
body_error = ValueError("body failed") |
| 197 |
backend_error = OSError(EIO, "backend release failed") |
| 198 |
release_started = asyncio.Event() |
| 199 |
finish_release = asyncio.Event() |
| 200 |
fail_release = True |
| 201 |
|
| 202 |
class Lock(BaseAsyncFileLock): |
| 203 |
async def _acquire(self) -> None: # ty: ignore[invalid-method-override] |
| 204 |
self._context.lock_file_fd = 1 |
| 205 |
|
| 206 |
async def _release(self) -> None: # ty: ignore[invalid-method-override] |
| 207 |
if fail_release: |
| 208 |
release_started.set() |
| 209 |
await finish_release.wait() |
| 210 |
raise backend_error |
| 211 |
self._context.lock_file_fd = None |
| 212 |
|
| 213 |
lock = Lock(tmp_path / "a", run_in_executor=False, context_error_policy="group") |
| 214 |
|
| 215 |
async def run_context() -> None: |
| 216 |
async with lock: |
| 217 |
raise body_error |
| 218 |
|
| 219 |
task = asyncio.create_task(run_context()) |
| 220 |
await release_started.wait() |
| 221 |
task.cancel("cancel release") |
| 222 |
finish_release.set() |
| 223 |
|
| 224 |
with pytest.raises(BaseExceptionGroup) as info: |
| 225 |
await task |
| 226 |
grouped_body, grouped_cancellation, grouped_backend = info.value.exceptions |
| 227 |
assert info.value.message == "context body, release cancellation, and backend release failed" |
| 228 |
assert (grouped_body, grouped_backend) == (body_error, backend_error) |
| 229 |
assert isinstance(grouped_cancellation, asyncio.CancelledError) |
| 230 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) # backend failed before unlocking, so state is kept |
| 231 |
|
| 232 |
fail_release = False |
| 233 |
await lock.release() |
| 234 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 235 |
|
| 236 |
|
| 237 |
def test_sync_context_exit_is_unsupported(tmp_path: Path) -> None: |
| 238 |
# __enter__ already raises, so the with-statement never reaches __exit__; call the protocol method directly. |
| 239 |
lock = AsyncFileLock(str(tmp_path / "a")) |
| 240 |
with pytest.raises(NotImplementedError, match=r"async with"): |
| 241 |
lock.__exit__(None, None, None) |