Debian Codegraph @

tests/test_async_read_write.py

raw
1 from __future__ import annotations
2
3 import gc
4 from concurrent.futures import ThreadPoolExecutor
5 from typing import TYPE_CHECKING, Literal
6
7 import pytest
8
9 from tests.capability_marks import NEEDS_COLLECTED_FINALIZATION
10
11 pytest.importorskip("sqlite3")
12
13 import sqlite3
14
15 from filelock import AsyncReadWriteLock, ReadWriteLock, Timeout
16
17 if TYPE_CHECKING:
18 from collections.abc import Generator
19 from pathlib import Path
20
21
22 @pytest.fixture(autouse=True)
23 def _clear_singleton_cache() -> Generator[None]:
24 ReadWriteLock._instances.clear()
25 yield
26 for ref in list(ReadWriteLock._instances.valuerefs()):
27 if (lock := ref()) is not None: # pragma: no cover # cache is normally emptied before teardown
28 lock.close()
29 ReadWriteLock._instances.clear()
30
31
32 @pytest.fixture
33 def lock_file(tmp_path: Path) -> str:
34 return str(tmp_path / "test_lock.db")
35
36
37 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
38 @pytest.mark.asyncio
39 async def test_acquire_release(lock_file: str, mode: Literal["read", "write"]) -> None:
40 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
41 proxy = await (lock.acquire_read() if mode == "read" else lock.acquire_write())
42 async with proxy as held:
43 assert held is lock
44 with pytest.raises(RuntimeError, match="not held"):
45 await lock.release()
46 await lock.close()
47
48
49 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
50 @pytest.mark.asyncio
51 async def test_lock_context_manager(lock_file: str, mode: Literal["read", "write"]) -> None:
52 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
53 ctx = lock.read_lock() if mode == "read" else lock.write_lock()
54 async with ctx:
55 assert_mode_held(lock_file, mode)
56 with pytest.raises(RuntimeError, match="not held"):
57 await lock.release()
58 await lock.close()
59
60
61 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
62 @pytest.mark.asyncio
63 async def test_reentrant(lock_file: str, mode: Literal["read", "write"]) -> None:
64 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
65 acquire = lock.acquire_read if mode == "read" else lock.acquire_write
66 await acquire()
67 await acquire()
68 await lock.release()
69 assert_mode_held(lock_file, mode)
70 await lock.release()
71 with pytest.raises(RuntimeError, match="not held"):
72 await lock.release()
73 await lock.close()
74
75
76 @pytest.mark.parametrize(
77 ("held", "requested", "match"),
78 [
79 pytest.param("read", "write", r"already holding a read lock.*upgrade not allowed", id="upgrade"),
80 pytest.param("write", "read", r"already holding a write lock.*downgrade not allowed", id="downgrade"),
81 ],
82 )
83 @pytest.mark.asyncio
84 async def test_mode_change_prohibited(
85 lock_file: str,
86 held: Literal["read", "write"],
87 requested: Literal["read", "write"],
88 match: str,
89 ) -> None:
90 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
91 await (lock.acquire_read() if held == "read" else lock.acquire_write())
92 with pytest.raises(RuntimeError, match=match):
93 await (lock.acquire_read() if requested == "read" else lock.acquire_write())
94 await lock.release()
95 await lock.close()
96
97
98 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
99 @pytest.mark.asyncio
100 async def test_non_blocking_conflict(lock_file: str, mode: Literal["read", "write"]) -> None:
101 holder = ReadWriteLock(lock_file, is_singleton=False)
102 (holder.acquire_write if mode == "read" else holder.acquire_read)()
103 try:
104 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
105 with pytest.raises(Timeout):
106 await (lock.acquire_read if mode == "read" else lock.acquire_write)(blocking=False)
107 await lock.close()
108 finally:
109 holder.release()
110
111
112 @pytest.mark.asyncio
113 async def test_timeout_expires(lock_file: str) -> None:
114 holder = ReadWriteLock(lock_file, is_singleton=False)
115 holder.acquire_write()
116 try:
117 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
118 with pytest.raises(Timeout):
119 await lock.acquire_read(timeout=0.2)
120 await lock.close()
121 finally:
122 holder.release()
123
124
125 @pytest.mark.asyncio
126 async def test_release_unheld_raises(lock_file: str) -> None:
127 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
128 with pytest.raises(RuntimeError, match="not held"):
129 await lock.release()
130 await lock.close()
131
132
133 @pytest.mark.asyncio
134 async def test_release_force(lock_file: str) -> None:
135 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
136 await lock.acquire_write()
137 await lock.acquire_write()
138 await lock.release(force=True)
139 with pytest.raises(RuntimeError, match="not held"):
140 await lock.release()
141 await lock.close()
142
143
144 @pytest.mark.asyncio
145 async def test_release_force_unheld_is_noop(lock_file: str) -> None:
146 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
147 await lock.release(force=True)
148 await lock.close()
149
150
151 @pytest.mark.parametrize(
152 ("held", "supplied_executor"),
153 [
154 pytest.param(False, False, id="idle-owned-executor"),
155 pytest.param(True, False, id="held-owned-executor"),
156 pytest.param(False, True, id="idle-supplied-executor"),
157 pytest.param(True, True, id="held-supplied-executor"),
158 ],
159 )
160 @pytest.mark.asyncio
161 async def test_close_rejects_later_acquisition(lock_file: str, held: bool, supplied_executor: bool) -> None:
162 executor = ThreadPoolExecutor(max_workers=1) if supplied_executor else None
163 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
164 if held:
165 await lock.acquire_write()
166 await lock.close()
167 with pytest.raises(sqlite3.ProgrammingError, match="Cannot operate on a closed database"):
168 await lock.acquire_read()
169 if executor is not None:
170 executor.shutdown(wait=False)
171
172
173 def test_properties(lock_file: str) -> None:
174 executor = ThreadPoolExecutor(max_workers=1)
175 lock = AsyncReadWriteLock(lock_file, timeout=5.0, blocking=False, is_singleton=False, executor=executor)
176 assert lock.lock_file == lock_file
177 assert lock.timeout == pytest.approx(5.0)
178 assert lock.blocking is False
179 assert lock.loop is None
180 assert lock.executor is executor
181 executor.shutdown(wait=False)
182
183
184 @pytest.mark.asyncio
185 async def test_custom_executor(lock_file: str) -> None:
186 executor = ThreadPoolExecutor(max_workers=1)
187 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
188 async with lock.read_lock():
189 assert_mode_held(lock_file, "read")
190 with pytest.raises(RuntimeError, match="not held"):
191 await lock.release()
192 executor.shutdown(wait=False)
193
194
195 @pytest.mark.asyncio
196 async def test_close_shuts_down_owned_executor(lock_file: str) -> None:
197 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
198 executor = lock.executor
199 await lock.close()
200 await lock.close()
201 with pytest.raises(RuntimeError):
202 executor.submit(int)
203
204
205 @pytest.mark.asyncio
206 async def test_close_keeps_provided_executor_open(lock_file: str) -> None:
207 executor = ThreadPoolExecutor(max_workers=1)
208 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
209 await lock.close()
210 assert executor.submit(int).result(timeout=5) == 0
211 executor.shutdown(wait=False)
212
213
214 @NEEDS_COLLECTED_FINALIZATION
215 def test_del_shuts_down_owned_executor(lock_file: str) -> None:
216 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
217 executor = lock.executor
218 del lock
219 gc.collect()
220 with pytest.raises(RuntimeError):
221 executor.submit(int)
222
223
224 def test_del_keeps_provided_executor_open(lock_file: str) -> None:
225 executor = ThreadPoolExecutor(max_workers=1)
226 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
227 del lock
228 gc.collect()
229 assert executor.submit(int).result(timeout=5) == 0
230 executor.shutdown(wait=False)
231
232
233 @pytest.mark.asyncio
234 async def test_acquire_return_proxy_context_manager(lock_file: str) -> None:
235 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
236 async with await lock.acquire_read() as ctx:
237 assert ctx is lock
238 assert_mode_held(lock_file, "read")
239 with pytest.raises(RuntimeError, match="not held"):
240 await lock.release()
241 await lock.close()
242
243
244 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
245 @pytest.mark.asyncio
246 async def test_nested_context_managers(lock_file: str, mode: Literal["read", "write"]) -> None:
247 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
248 make_ctx = lock.read_lock if mode == "read" else lock.write_lock
249 async with make_ctx():
250 assert_mode_held(lock_file, mode)
251 async with make_ctx():
252 assert_mode_held(lock_file, mode)
253 assert_mode_held(lock_file, mode)
254 with pytest.raises(RuntimeError, match="not held"):
255 await lock.release()
256 await lock.close()
257
258
259 @pytest.mark.asyncio
260 async def test_context_manager_uses_instance_defaults(lock_file: str) -> None:
261 lock = AsyncReadWriteLock(lock_file, timeout=3.0, blocking=True, is_singleton=False)
262 async with lock.read_lock():
263 assert_mode_held(lock_file, "read")
264 async with lock.write_lock():
265 assert_mode_held(lock_file, "write")
266 await lock.close()
267
268
269 @pytest.mark.asyncio
270 async def test_context_manager_overrides_defaults(lock_file: str) -> None:
271 lock = AsyncReadWriteLock(lock_file, timeout=10.0, blocking=False, is_singleton=False)
272 async with lock.read_lock(timeout=5.0, blocking=True):
273 assert_mode_held(lock_file, "read")
274 async with lock.write_lock(timeout=5.0, blocking=True):
275 assert_mode_held(lock_file, "write")
276 await lock.close()
277
278
279 @pytest.mark.asyncio
280 async def test_sequential_mode_switch(lock_file: str) -> None:
281 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
282 async with lock.read_lock():
283 pass
284 async with lock.write_lock():
285 pass
286 async with lock.read_lock():
287 pass
288 await lock.close()
289
290
291 def assert_mode_held(lock_file: str, mode: Literal["read", "write"]) -> None:
292 contender = ReadWriteLock(lock_file, is_singleton=False)
293 acquire = contender.acquire_write if mode == "read" else contender.acquire_read
294 with pytest.raises(Timeout):
295 acquire(blocking=False)
296 contender.close()