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