Debian Codegraph @

tests/soft_rw/test_soft_rw_async.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import os
5 import threading
6 from concurrent.futures import ThreadPoolExecutor
7 from typing import TYPE_CHECKING, Literal
8
9 import pytest
10
11 from filelock import Timeout
12 from filelock._soft_rw import AsyncSoftReadWriteLock, SoftReadWriteLock
13 from filelock._soft_rw._protocol import GenerationLog
14 from filelock._soft_rw._storage import OsFiles
15 from tests.capability_marks import XFAIL_WITHOUT_COROUTINE_CANCELLATION
16
17 if TYPE_CHECKING:
18 from collections.abc import Callable, Generator
19 from concurrent.futures import Executor
20 from pathlib import Path
21
22 from pytest_mock import MockerFixture
23
24 pytestmark = pytest.mark.requires_hard_links
25
26
27 @pytest.fixture(autouse=True)
28 def _clear_singletons() -> Generator[None]:
29 SoftReadWriteLock._instances.clear()
30 yield
31 for lock in filter(None, (ref() for ref in list(SoftReadWriteLock._instances.valuerefs()))):
32 lock.close()
33 SoftReadWriteLock._instances.clear()
34
35
36 def _make(
37 tmp_path: Path,
38 name: str = "foo.lock",
39 *,
40 timeout: float = -1,
41 blocking: bool = True,
42 heartbeat_interval: float = 0.1,
43 stale_threshold: float = 0.5,
44 poll_interval: float = 0.02,
45 loop: asyncio.AbstractEventLoop | None = None,
46 executor: Executor | None = None,
47 ) -> AsyncSoftReadWriteLock:
48 return AsyncSoftReadWriteLock(
49 str(tmp_path / name),
50 timeout=timeout,
51 blocking=blocking,
52 is_singleton=False,
53 heartbeat_interval=heartbeat_interval,
54 stale_threshold=stale_threshold,
55 poll_interval=poll_interval,
56 loop=loop,
57 executor=executor,
58 )
59
60
61 class _Gate:
62 """Pause one call inside the executor thread so a cancellation lands after the backend work started."""
63
64 def __init__(self, mocker: MockerFixture, name: str, *, fail_with: BaseException | None = None) -> None:
65 self.started = asyncio.Event()
66 # Set once the gated call returns, letting a test distinguish the executor finishing from the caller giving up.
67 self.finished = threading.Event()
68 self._resume = threading.Event()
69 self._loop = asyncio.get_running_loop()
70 self._real: Callable[..., object] = getattr(SoftReadWriteLock, name)
71 self._pending = True
72 mocker.patch.object(SoftReadWriteLock, name, autospec=True, side_effect=self._call(fail_with))
73
74 def _call(self, fail_with: BaseException | None) -> Callable[..., object]:
75 def call(lock: SoftReadWriteLock, *args: object, **kwargs: object) -> object:
76 if not self._pending:
77 return self._real(lock, *args, **kwargs)
78 self._pending = False
79 self._loop.call_soon_threadsafe(self.started.set)
80 assert self._resume.wait(timeout=5)
81 try:
82 if fail_with is not None:
83 raise fail_with
84 return self._real(lock, *args, **kwargs)
85 finally:
86 self.finished.set()
87
88 return call
89
90 def resume(self) -> None:
91 self._resume.set()
92
93
94 def _members(tmp_path: Path, name: str = "foo.lock") -> list[str]:
95 lock_file = str(tmp_path / name)
96 latest = GenerationLog(OsFiles(lock_file), lock_file, f"{lock_file}.rw").latest()
97 holders = tmp_path / f"{name}.rw" / "holders"
98 return sorted(latest.members) + (sorted(entry.name for entry in holders.iterdir()) if holders.is_dir() else [])
99
100
101 @pytest.mark.asyncio
102 @pytest.mark.parametrize("mode", [pytest.param("write", id="write"), pytest.param("read", id="read")])
103 async def test_async_lock_context_manager(tmp_path: Path, mode: Literal["read", "write"]) -> None:
104 lock = _make(tmp_path)
105 try:
106 context = lock.write_lock if mode == "write" else lock.read_lock
107 async with context(timeout=2):
108 pass
109 finally:
110 await lock.close()
111
112
113 @pytest.mark.asyncio
114 async def test_async_exposes_configuration(tmp_path: Path) -> None:
115 lock = _make(tmp_path, timeout=5, blocking=False)
116 try:
117 assert lock.lock_file.endswith("foo.lock")
118 assert lock.timeout == 5
119 assert lock.blocking is False
120 assert lock.loop is None
121 assert lock.executor is None
122 assert lock.generation is None
123 assert lock.compromise is None
124 finally:
125 await lock.close()
126
127
128 @pytest.mark.asyncio
129 async def test_async_raw_acquire_release_round_trip(tmp_path: Path) -> None:
130 lock = _make(tmp_path)
131 try:
132 proxy = await lock.acquire_write(timeout=2)
133 async with proxy:
134 assert lock.generation is not None
135 proxy = await lock.acquire_read(timeout=2)
136 async with proxy:
137 pass
138 finally:
139 await lock.close()
140
141
142 @pytest.mark.asyncio
143 async def test_async_custom_loop_and_executor(tmp_path: Path) -> None:
144 with ThreadPoolExecutor(max_workers=1) as executor:
145 loop = asyncio.get_running_loop()
146 lock = _make(tmp_path, loop=loop, executor=executor)
147 try:
148 assert lock.loop is loop
149 assert lock.executor is executor
150 async with lock.write_lock(timeout=2):
151 pass
152 finally:
153 await lock.close()
154
155
156 @pytest.mark.asyncio
157 async def test_async_release_force(tmp_path: Path) -> None:
158 lock = _make(tmp_path)
159 try:
160 await lock.acquire_read(timeout=2)
161 await lock.release(force=True)
162 finally:
163 await lock.close()
164
165
166 @pytest.mark.asyncio
167 async def test_async_release_and_close_skip_when_pid_differs(tmp_path: Path, mocker: MockerFixture) -> None:
168 # A pid that no longer matches the creator's must leave the parent's still-held lock untouched.
169 lock = _make(tmp_path)
170 await lock.acquire_write(timeout=2)
171 try:
172 mocker.patch("filelock._soft_rw._async.os.getpid", return_value=os.getpid() + 1)
173 await lock.release(force=True)
174 await lock.close()
175 mocker.stopall()
176 await lock.release()
177 finally:
178 mocker.stopall()
179 await lock.close()
180
181
182 @pytest.mark.asyncio
183 async def test_async_leaked_singleton_is_closed_on_teardown(tmp_path: Path) -> None:
184 # A live heartbeat thread keeps the singleton reachable, so the autouse teardown finds and closes it.
185 path = tmp_path / "singleton.lock"
186 lock = AsyncSoftReadWriteLock(str(path), heartbeat_interval=0.5, stale_threshold=1.5, poll_interval=0.02)
187 await lock.acquire_write(timeout=2)
188 assert len(_members(tmp_path, "singleton.lock")) == 2
189
190
191 @pytest.mark.asyncio
192 async def test_async_writer_times_out_behind_reader(tmp_path: Path) -> None:
193 reader = _make(tmp_path)
194 await reader.acquire_read(timeout=2)
195 try:
196 writer = _make(tmp_path)
197 try:
198 with pytest.raises(Timeout):
199 await writer.acquire_write(timeout=0.3)
200 finally:
201 await writer.close()
202 finally:
203 await reader.release()
204 await reader.close()
205
206
207 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
208 @pytest.mark.asyncio
209 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
210 async def test_async_acquire_cancellation_hands_the_claim_back(
211 tmp_path: Path, mocker: MockerFixture, mode: Literal["read", "write"]
212 ) -> None:
213 gate = _Gate(mocker, f"acquire_{mode}")
214 lock = _make(tmp_path)
215 acquire = lock.acquire_read if mode == "read" else lock.acquire_write
216 task = asyncio.create_task(acquire(timeout=5))
217 await gate.started.wait()
218 task.cancel("cancel acquire")
219 gate.resume()
220 with pytest.raises(asyncio.CancelledError):
221 await task
222 assert gate.finished.wait(timeout=5), "the executor never finished the acquire it was already running"
223
224 assert lock._lock._hold is None
225 assert _members(tmp_path) == []
226 contender = SoftReadWriteLock(str(tmp_path / "foo.lock"), is_singleton=False, poll_interval=0.02)
227 try:
228 with contender.write_lock(timeout=5):
229 pass
230 finally:
231 contender.close()
232 await lock.close()
233
234
235 @pytest.mark.asyncio
236 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
237 async def test_async_acquire_cancellation_surfaces_a_failed_acquire(tmp_path: Path, mocker: MockerFixture) -> None:
238 acquire_error = Timeout(str(tmp_path / "foo.lock"))
239 gate = _Gate(mocker, "acquire_write", fail_with=acquire_error)
240 lock = _make(tmp_path)
241 task = asyncio.create_task(lock.acquire_write(timeout=5))
242 await gate.started.wait()
243 task.cancel("cancel acquire")
244 gate.resume()
245 with pytest.raises(Timeout) as info:
246 await task
247
248 assert info.value is acquire_error
249 assert isinstance(acquire_error.__context__, asyncio.CancelledError)
250 assert lock._lock._hold is None
251 assert _members(tmp_path) == []
252 await lock.close()
253
254
255 @pytest.mark.asyncio
256 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
257 async def test_async_acquire_cancellation_surfaces_a_failed_release(tmp_path: Path, mocker: MockerFixture) -> None:
258 gate = _Gate(mocker, "acquire_write")
259 release_error = RuntimeError("release failed")
260 mocker.patch.object(SoftReadWriteLock, "release", side_effect=release_error)
261 lock = _make(tmp_path)
262 task = asyncio.create_task(lock.acquire_write(timeout=5))
263 await gate.started.wait()
264 task.cancel("cancel acquire")
265 gate.resume()
266 with pytest.raises(RuntimeError, match="release failed") as info:
267 await task
268
269 assert info.value is release_error
270 assert isinstance(release_error.__context__, asyncio.CancelledError)
271 mocker.stopall()
272 await lock.close()
273
274
275 @pytest.mark.asyncio
276 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
277 async def test_async_release_cancellation_drains_the_release(tmp_path: Path, mocker: MockerFixture) -> None:
278 lock = _make(tmp_path)
279 await lock.acquire_write(timeout=5)
280 gate = _Gate(mocker, "release")
281 task = asyncio.create_task(lock.release())
282 await gate.started.wait()
283 task.cancel("cancel release")
284 # Resume only after the cancellation has had a chance to propagate, so the cancellation reaching the caller
285 # before the release finished is a failure rather than a coin flip.
286 asyncio.get_running_loop().call_later(0.05, gate.resume)
287 with pytest.raises(asyncio.CancelledError):
288 await task
289
290 assert gate.finished.is_set(), "the cancellation surfaced while the release was still running"
291 assert lock._lock._hold is None
292 assert _members(tmp_path) == []
293 await lock.close()
294
295
296 @pytest.mark.asyncio
297 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
298 async def test_async_release_cancellation_surfaces_a_failed_release(tmp_path: Path, mocker: MockerFixture) -> None:
299 lock = _make(tmp_path)
300 await lock.acquire_write(timeout=5)
301 release_error = RuntimeError("release failed")
302 gate = _Gate(mocker, "release", fail_with=release_error)
303 task = asyncio.create_task(lock.release())
304 await gate.started.wait()
305 task.cancel("cancel release")
306 gate.resume()
307 with pytest.raises(RuntimeError, match="release failed") as info:
308 await task
309
310 assert info.value is release_error
311 assert isinstance(release_error.__context__, asyncio.CancelledError)
312 mocker.stopall()
313 await lock.close()