| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import logging |
| 5 |
import sys |
| 6 |
import threading |
| 7 |
from errno import EIO |
| 8 |
from typing import TYPE_CHECKING |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from filelock import AsyncFileLock, BaseAsyncFileLock, ContextErrorPolicy |
| 13 |
from tests.async_filelock_cancellation_helpers import ( |
| 14 |
assert_cancellation_message, |
| 15 |
assert_file_lock_state, |
| 16 |
get_fcntl, |
| 17 |
start_file_lock_holder, |
| 18 |
) |
| 19 |
from tests.capability_marks import NEEDS_FCNTL, XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 20 |
|
| 21 |
if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 22 |
from builtins import BaseExceptionGroup, ExceptionGroup # pragma: >=3.11 cover |
| 23 |
else: # pragma: no cover (<py311) |
| 24 |
from exceptiongroup import BaseExceptionGroup, ExceptionGroup |
| 25 |
|
| 26 |
if TYPE_CHECKING: |
| 27 |
from pathlib import Path |
| 28 |
|
| 29 |
from pytest_mock import MockerFixture |
| 30 |
|
| 31 |
|
| 32 |
@NEEDS_FCNTL |
| 33 |
@pytest.mark.asyncio # pragma: needs fcntl |
| 34 |
async def test_release_completes_despite_cancellation(tmp_path: Path, mocker: MockerFixture) -> None: |
| 35 |
lock = AsyncFileLock(str(tmp_path / "a")) |
| 36 |
await lock.acquire() |
| 37 |
release_started = asyncio.Event() |
| 38 |
finish_release = threading.Event() |
| 39 |
loop = asyncio.get_running_loop() |
| 40 |
|
| 41 |
def block_unlock(_fd: int, _operation: int) -> None: |
| 42 |
loop.call_soon_threadsafe(release_started.set) |
| 43 |
assert finish_release.wait(timeout=5) |
| 44 |
|
| 45 |
mocker.patch("filelock._unix.fcntl.flock", side_effect=block_unlock) |
| 46 |
task = asyncio.create_task(lock.release()) |
| 47 |
await release_started.wait() |
| 48 |
task.cancel("cancel release") |
| 49 |
finish_release.set() |
| 50 |
with pytest.raises(asyncio.CancelledError): |
| 51 |
await task |
| 52 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 53 |
assert_file_lock_state(str(tmp_path / "a"), available=True) |
| 54 |
|
| 55 |
|
| 56 |
@NEEDS_FCNTL |
| 57 |
@pytest.mark.asyncio # pragma: needs fcntl |
| 58 |
@XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 59 |
async def test_acquire_proceeds_after_queued_release_is_canceled(tmp_path: Path, mocker: MockerFixture) -> None: |
| 60 |
lock = AsyncFileLock(tmp_path / "a") |
| 61 |
await lock.acquire() |
| 62 |
release_started = asyncio.Event() |
| 63 |
finish_release = threading.Event() |
| 64 |
loop = asyncio.get_running_loop() |
| 65 |
fcntl = get_fcntl() |
| 66 |
real_flock = fcntl.flock |
| 67 |
blocked = False |
| 68 |
|
| 69 |
def block_first_unlock(fd: int, operation: int) -> None: |
| 70 |
nonlocal blocked |
| 71 |
if operation & fcntl.LOCK_UN and not blocked: |
| 72 |
blocked = True |
| 73 |
loop.call_soon_threadsafe(release_started.set) |
| 74 |
assert finish_release.wait(timeout=5) |
| 75 |
real_flock(fd, operation) |
| 76 |
|
| 77 |
mocker.patch("filelock._unix.fcntl.flock", side_effect=block_first_unlock) |
| 78 |
first_release = asyncio.create_task(lock.release()) |
| 79 |
await release_started.wait() |
| 80 |
second_release = asyncio.create_task(lock.release()) |
| 81 |
await asyncio.sleep(0) |
| 82 |
second_release.cancel("abandon queued release") |
| 83 |
try: |
| 84 |
with pytest.raises(asyncio.CancelledError) as info: |
| 85 |
await second_release |
| 86 |
assert_cancellation_message(info.value, "abandon queued release") |
| 87 |
acquire = asyncio.create_task(lock.acquire()) |
| 88 |
finally: |
| 89 |
finish_release.set() |
| 90 |
|
| 91 |
await first_release |
| 92 |
await acquire |
| 93 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) |
| 94 |
await lock.release() |
| 95 |
assert_file_lock_state(str(tmp_path / "a"), available=True) |
| 96 |
|
| 97 |
|
| 98 |
@NEEDS_FCNTL |
| 99 |
@pytest.mark.asyncio |
| 100 |
async def test_release_waits_for_provisional_acquire(tmp_path: Path) -> None: # pragma: needs fcntl |
| 101 |
hook_started = asyncio.Event() |
| 102 |
finish_hook = threading.Event() |
| 103 |
loop = asyncio.get_running_loop() |
| 104 |
|
| 105 |
def block_hook(_fd: int) -> None: |
| 106 |
loop.call_soon_threadsafe(hook_started.set) |
| 107 |
assert finish_hook.wait(timeout=5) |
| 108 |
|
| 109 |
lock = AsyncFileLock(tmp_path / "a", on_acquired=block_hook) |
| 110 |
acquire_task = asyncio.create_task(lock.acquire()) |
| 111 |
await hook_started.wait() |
| 112 |
release_started = asyncio.Event() |
| 113 |
|
| 114 |
async def release() -> None: |
| 115 |
release_started.set() |
| 116 |
await lock.release() |
| 117 |
|
| 118 |
release_task = asyncio.create_task(release()) |
| 119 |
await release_started.wait() |
| 120 |
finish_hook.set() |
| 121 |
await acquire_task |
| 122 |
await release_task |
| 123 |
|
| 124 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 125 |
assert_file_lock_state(str(tmp_path / "a"), available=True) |
| 126 |
|
| 127 |
|
| 128 |
@pytest.mark.asyncio |
| 129 |
async def test_release_returns_while_acquire_waits_for_external_holder(tmp_path: Path) -> None: |
| 130 |
holder, holder_started, finish_holder = start_file_lock_holder(str(tmp_path / "a")) |
| 131 |
assert await asyncio.to_thread(holder_started.wait, 5) |
| 132 |
first_polled = asyncio.Event() |
| 133 |
|
| 134 |
def observe_first_poll() -> bool: |
| 135 |
first_polled.set() |
| 136 |
return False |
| 137 |
|
| 138 |
lock = AsyncFileLock(tmp_path / "a") |
| 139 |
acquire_task = asyncio.create_task(lock.acquire(cancel_check=observe_first_poll, poll_interval=0.001)) |
| 140 |
try: |
| 141 |
await first_polled.wait() |
| 142 |
await lock.release() |
| 143 |
assert (acquire_task.done(), lock.is_locked) == (False, False) |
| 144 |
finally: |
| 145 |
finish_holder.set() |
| 146 |
await asyncio.to_thread(holder.join, 5) |
| 147 |
|
| 148 |
assert not holder.is_alive() |
| 149 |
await acquire_task |
| 150 |
await lock.release() |
| 151 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 152 |
assert_file_lock_state(str(tmp_path / "a"), available=True) |
| 153 |
|
| 154 |
|
| 155 |
@NEEDS_FCNTL |
| 156 |
@pytest.mark.parametrize("policy", [pytest.param("chain", id="chain"), pytest.param("group", id="group")]) |
| 157 |
@pytest.mark.asyncio |
| 158 |
@XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 159 |
async def test_release_cancellation_surfaces_backend_error( # pragma: needs fcntl |
| 160 |
tmp_path: Path, mocker: MockerFixture, caplog: pytest.LogCaptureFixture, policy: ContextErrorPolicy |
| 161 |
) -> None: |
| 162 |
lock = AsyncFileLock(tmp_path / "a", context_error_policy=policy) |
| 163 |
await lock.acquire() |
| 164 |
release_started = asyncio.Event() |
| 165 |
finish_release = threading.Event() |
| 166 |
loop = asyncio.get_running_loop() |
| 167 |
release_error = OSError(EIO, "release failed") |
| 168 |
release_count = 0 |
| 169 |
|
| 170 |
def fail_first_unlock(_fd: int, _operation: int) -> None: |
| 171 |
nonlocal release_count |
| 172 |
release_count += 1 |
| 173 |
if release_count == 1: |
| 174 |
loop.call_soon_threadsafe(release_started.set) |
| 175 |
assert finish_release.wait(timeout=5) |
| 176 |
raise release_error |
| 177 |
|
| 178 |
mocker.patch("filelock._unix.fcntl.flock", side_effect=fail_first_unlock) |
| 179 |
task = asyncio.create_task(lock.release()) |
| 180 |
await release_started.wait() |
| 181 |
task.cancel("cancel release") |
| 182 |
finish_release.set() |
| 183 |
|
| 184 |
if policy == "chain": |
| 185 |
with pytest.raises(OSError, match="release failed") as info: |
| 186 |
await task |
| 187 |
cancellation = info.value.__context__ |
| 188 |
assert info.value is release_error |
| 189 |
else: |
| 190 |
with pytest.raises(BaseExceptionGroup) as info: |
| 191 |
await task |
| 192 |
cancellation, grouped_release_error = info.value.exceptions |
| 193 |
assert grouped_release_error is release_error |
| 194 |
assert (info.value.__cause__, info.value.__suppress_context__) == (None, True) |
| 195 |
assert isinstance(cancellation, asyncio.CancelledError) |
| 196 |
assert (cancellation.args, release_error.__cause__, release_error.__context__) == ( |
| 197 |
("cancel release",), |
| 198 |
None, |
| 199 |
cancellation if policy == "chain" else None, |
| 200 |
) |
| 201 |
assert (cancellation.__traceback__ is not None, release_error.__traceback__ is not None) == (True, True) |
| 202 |
assert not any(record.name == "asyncio" and record.levelno >= logging.ERROR for record in caplog.records) |
| 203 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) |
| 204 |
assert_file_lock_state(str(tmp_path / "a"), available=False) |
| 205 |
await lock.release() |
| 206 |
|
| 207 |
|
| 208 |
@pytest.mark.asyncio |
| 209 |
async def test_context_chain_does_not_duplicate_body_already_in_release_group(tmp_path: Path) -> None: |
| 210 |
body_error = ValueError("body failed") |
| 211 |
release_group = ExceptionGroup("release failed", (body_error,)) |
| 212 |
fail_release = True |
| 213 |
|
| 214 |
class GroupReleaseLock(BaseAsyncFileLock): |
| 215 |
def _acquire(self) -> None: |
| 216 |
self._context.lock_file_fd = 1 |
| 217 |
|
| 218 |
def _release(self) -> None: |
| 219 |
nonlocal fail_release |
| 220 |
if fail_release: |
| 221 |
fail_release = False |
| 222 |
raise release_group |
| 223 |
self._context.lock_file_fd = None |
| 224 |
|
| 225 |
lock = GroupReleaseLock(tmp_path / "a", run_in_executor=False, context_error_policy="chain") |
| 226 |
with pytest.raises(ExceptionGroup) as info: |
| 227 |
async with lock: |
| 228 |
raise body_error |
| 229 |
assert (info.value, release_group.__context__, release_group.exceptions) == ( |
| 230 |
release_group, |
| 231 |
body_error, |
| 232 |
(body_error,), |
| 233 |
) |
| 234 |
await lock.release() |