Debian Codegraph @

tests/test_subclass_options.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import gc
5 from concurrent.futures import ThreadPoolExecutor
6 from typing import TYPE_CHECKING, Literal, Protocol, TypedDict, cast
7 from weakref import ref
8
9 import pytest
10
11 from filelock import BaseAsyncFileLock, BaseFileLock, CloseErrorPolicy, ContextErrorPolicy
12 from tests.capability_marks import NEEDS_CLASS_COLLECTION
13
14 if TYPE_CHECKING:
15 from collections.abc import Callable
16 from concurrent.futures import Executor
17 from pathlib import Path
18
19 from typing_extensions import Unpack
20
21
22 @pytest.mark.parametrize(
23 ("option", "value"),
24 [
25 pytest.param("timeout", 1, id="timeout"),
26 pytest.param("mode", 0o600, id="mode"),
27 pytest.param("thread_local", False, id="thread-local"),
28 pytest.param("blocking", False, id="blocking"),
29 pytest.param("is_singleton", True, id="singleton"),
30 pytest.param("poll_interval", 0.1, id="poll-interval"),
31 pytest.param("lifetime", 1, id="lifetime"),
32 pytest.param("context_error_policy", "group", id="context-error-policy"),
33 pytest.param("close_error_policy", "raise", id="close-error-policy"),
34 pytest.param("fallback_to_soft", False, id="fallback-to-soft"),
35 pytest.param("preserve_lock_file", True, id="preserve-lock-file"),
36 pytest.param("on_acquired", list[int]().append, id="on-acquired"),
37 ],
38 )
39 def test_narrow_sync_subclass_rejects_non_default_option(
40 option: str,
41 value: float | str | Callable[[int], None],
42 tmp_path: Path,
43 ) -> None:
44 with pytest.raises(TypeError, match=option):
45 _sync_constructor()(
46 str(tmp_path / "lock"),
47 **cast("_FileLockOptions", {option: value}),
48 )
49
50
51 def test_narrow_sync_subclass_rejects_unknown_option(tmp_path: Path) -> None:
52 with pytest.raises(TypeError, match="unknown"):
53 _unknown_constructor()(str(tmp_path / "lock"), unknown=True)
54
55
56 @pytest.mark.parametrize(
57 "option",
58 [
59 pytest.param("thread_local", id="thread-local"),
60 pytest.param("loop", id="loop"),
61 pytest.param("run_in_executor", id="run-in-executor"),
62 pytest.param("executor", id="executor"),
63 ],
64 )
65 def test_narrow_async_subclass_rejects_non_default_option(
66 option: Literal["thread_local", "loop", "run_in_executor", "executor"],
67 tmp_path: Path,
68 ) -> None:
69 loop = asyncio.new_event_loop()
70 try:
71 with ThreadPoolExecutor(max_workers=1) as executor, pytest.raises(TypeError, match=option):
72 _async_constructor()(
73 str(tmp_path / "lock"),
74 **_unsupported_async_options(option, loop, executor),
75 )
76 finally:
77 loop.close()
78
79
80 @pytest.mark.parametrize(
81 "kind",
82 [pytest.param("sync", id="sync"), pytest.param("async", id="async")],
83 )
84 def test_narrow_subclass_accepts_explicit_base_defaults(
85 kind: Literal["sync", "async"],
86 tmp_path: Path,
87 ) -> None:
88 lock_path = str(tmp_path / "lock")
89 assert _build_with_explicit_defaults(kind, lock_path).lock_file == lock_path
90
91
92 def test_narrow_subclass_accepts_named_option(tmp_path: Path) -> None:
93 assert _NamedFileLock(str(tmp_path / "lock"), marker=7).marker == 7
94
95
96 def test_sync_subclass_forwards_kwargs(tmp_path: Path) -> None:
97 hook: Callable[[int], None] = list[int]().append
98 lock = _ForwardingFileLock(
99 str(tmp_path / "lock"),
100 timeout=2,
101 mode=0o600,
102 thread_local=False,
103 blocking=False,
104 is_singleton=True,
105 poll_interval=0.1,
106 lifetime=3,
107 context_error_policy="group",
108 close_error_policy="suppress",
109 fallback_to_soft=False,
110 preserve_lock_file=True,
111 on_acquired=hook,
112 )
113
114 assert {
115 "timeout": lock.timeout,
116 "mode": lock.mode,
117 "thread_local": lock.is_thread_local(),
118 "blocking": lock.blocking,
119 "is_singleton": lock.is_singleton,
120 "poll_interval": lock.poll_interval,
121 "lifetime": lock.lifetime,
122 "context_error_policy": lock.context_error_policy,
123 "close_error_policy": lock.close_error_policy,
124 "fallback_to_soft": lock.fallback_to_soft,
125 "preserve_lock_file": lock.preserve_lock_file,
126 "on_acquired": lock.on_acquired,
127 } == {
128 "timeout": 2,
129 "mode": 0o600,
130 "thread_local": False,
131 "blocking": False,
132 "is_singleton": True,
133 "poll_interval": 0.1,
134 "lifetime": 3,
135 "context_error_policy": "group",
136 "close_error_policy": "suppress",
137 "fallback_to_soft": False,
138 "preserve_lock_file": True,
139 "on_acquired": hook,
140 }
141
142
143 def test_async_subclass_forwards_kwargs(tmp_path: Path) -> None:
144 hook: Callable[[int], None] = list[int]().append
145 loop = asyncio.new_event_loop()
146 try:
147 with ThreadPoolExecutor(max_workers=1) as executor:
148 lock = _ForwardingAsyncFileLock(
149 str(tmp_path / "lock"),
150 timeout=2,
151 mode=0o600,
152 thread_local=True,
153 blocking=False,
154 is_singleton=True,
155 poll_interval=0.1,
156 lifetime=3,
157 context_error_policy="group",
158 close_error_policy="suppress",
159 fallback_to_soft=False,
160 preserve_lock_file=True,
161 on_acquired=hook,
162 loop=loop,
163 run_in_executor=False,
164 executor=executor,
165 )
166
167 assert {
168 "timeout": lock.timeout,
169 "mode": lock.mode,
170 "thread_local": lock.is_thread_local(),
171 "blocking": lock.blocking,
172 "is_singleton": lock.is_singleton,
173 "poll_interval": lock.poll_interval,
174 "lifetime": lock.lifetime,
175 "context_error_policy": lock.context_error_policy,
176 "close_error_policy": lock.close_error_policy,
177 "fallback_to_soft": lock.fallback_to_soft,
178 "preserve_lock_file": lock.preserve_lock_file,
179 "on_acquired": lock.on_acquired,
180 "loop": lock.loop,
181 "run_in_executor": lock.run_in_executor,
182 "executor": lock.executor,
183 } == {
184 "timeout": 2,
185 "mode": 0o600,
186 "thread_local": True,
187 "blocking": False,
188 "is_singleton": True,
189 "poll_interval": 0.1,
190 "lifetime": 3,
191 "context_error_policy": "group",
192 "close_error_policy": "suppress",
193 "fallback_to_soft": False,
194 "preserve_lock_file": True,
195 "on_acquired": hook,
196 "loop": loop,
197 "run_in_executor": False,
198 "executor": executor,
199 }
200 finally:
201 loop.close()
202
203
204 @pytest.mark.parametrize(
205 "option",
206 [pytest.param("hook", id="hook"), pytest.param("policy", id="policy")],
207 )
208 def test_forwarding_subclass_singleton_rejects_changed_option(
209 option: Literal["hook", "policy"],
210 tmp_path: Path,
211 ) -> None:
212 hook: Callable[[int], None] = list[int]().append
213 lock_path = str(tmp_path / "lock")
214 first = _ForwardingFileLock(lock_path, is_singleton=True, on_acquired=hook)
215
216 with pytest.raises(ValueError, match="on_acquired" if option == "hook" else "context_error_policy"):
217 _change_singleton_option(option, lock_path, hook)
218 assert first.on_acquired is hook
219
220
221 @NEEDS_CLASS_COLLECTION
222 def test_constructor_model_does_not_retain_dynamic_subclass(tmp_path: Path) -> None:
223 lock_type = _dynamic_constructor()
224 class_ref = ref(lock_type)
225 lock_type(str(tmp_path / "lock"))
226 del lock_type
227 gc.collect()
228 assert class_ref() is None
229
230
231 def _sync_constructor() -> type[BaseFileLock]:
232 return cast("type[BaseFileLock]", _NarrowFileLock)
233
234
235 def _async_constructor() -> type[BaseAsyncFileLock]:
236 return cast("type[BaseAsyncFileLock]", _NarrowAsyncFileLock)
237
238
239 def _unknown_constructor() -> _UnknownFileLockConstructor:
240 return cast("_UnknownFileLockConstructor", _NarrowFileLock)
241
242
243 def _unsupported_async_options(
244 option: Literal["thread_local", "loop", "run_in_executor", "executor"],
245 loop: asyncio.AbstractEventLoop,
246 executor: Executor,
247 ) -> _AsyncFileLockOptions:
248 if option == "thread_local":
249 return {"thread_local": True, "run_in_executor": False}
250 if option == "loop":
251 return {"loop": loop}
252 if option == "run_in_executor":
253 return {"run_in_executor": False}
254 return {"executor": executor}
255
256
257 def _build_with_explicit_defaults(kind: Literal["sync", "async"], lock_path: str) -> BaseFileLock:
258 if kind == "sync":
259 return _sync_constructor()(
260 lock_path,
261 timeout=-1,
262 mode=-1,
263 thread_local=True,
264 blocking=True,
265 is_singleton=False,
266 poll_interval=0.05,
267 lifetime=None,
268 context_error_policy="chain",
269 close_error_policy="default",
270 fallback_to_soft=True,
271 preserve_lock_file=False,
272 on_acquired=None,
273 )
274 return _async_constructor()(
275 lock_path,
276 timeout=-1,
277 mode=-1,
278 thread_local=False,
279 blocking=True,
280 is_singleton=False,
281 poll_interval=0.05,
282 lifetime=None,
283 context_error_policy="chain",
284 close_error_policy="default",
285 fallback_to_soft=True,
286 preserve_lock_file=False,
287 on_acquired=None,
288 loop=None,
289 run_in_executor=True,
290 executor=None,
291 )
292
293
294 def _change_singleton_option(
295 option: Literal["hook", "policy"],
296 lock_path: str,
297 hook: Callable[[int], None],
298 ) -> BaseFileLock:
299 if option == "hook":
300 return _ForwardingFileLock(lock_path, is_singleton=True, on_acquired=list[int]().append)
301 return _ForwardingFileLock(
302 lock_path,
303 is_singleton=True,
304 context_error_policy="group",
305 on_acquired=hook,
306 )
307
308
309 def _dynamic_constructor() -> type[BaseFileLock]:
310 class DynamicFileLock(BaseFileLock):
311 def _acquire(self) -> None:
312 raise NotImplementedError
313
314 def _release(self) -> None:
315 raise NotImplementedError
316
317 return DynamicFileLock
318
319
320 class _NarrowFileLock(BaseFileLock):
321 _lifetime_supported = True
322
323 def __init__(self, lock_file: str) -> None:
324 super().__init__(lock_file)
325
326 def _acquire(self) -> None:
327 raise NotImplementedError
328
329 def _release(self) -> None:
330 raise NotImplementedError
331
332
333 class _NamedFileLock(BaseFileLock):
334 def __init__(self, lock_file: str, *, marker: int = 0) -> None:
335 super().__init__(lock_file)
336 self.marker = marker
337
338 def _acquire(self) -> None:
339 raise NotImplementedError
340
341 def _release(self) -> None:
342 raise NotImplementedError
343
344
345 class _NarrowAsyncFileLock(BaseAsyncFileLock):
346 _lifetime_supported = True
347
348 def __init__(self, lock_file: str) -> None:
349 super().__init__(lock_file)
350
351 def _acquire(self) -> None:
352 raise NotImplementedError
353
354 def _release(self) -> None:
355 raise NotImplementedError
356
357
358 class _ForwardingFileLock(BaseFileLock):
359 _lifetime_supported = True
360
361 def __init__(self, lock_file: str, **kwargs: Unpack[_FileLockOptions]) -> None:
362 super().__init__(lock_file, **kwargs)
363
364 def _acquire(self) -> None:
365 raise NotImplementedError
366
367 def _release(self) -> None:
368 raise NotImplementedError
369
370
371 class _ForwardingAsyncFileLock(BaseAsyncFileLock):
372 _lifetime_supported = True
373
374 def __init__(self, lock_file: str, **kwargs: Unpack[_AsyncFileLockOptions]) -> None:
375 super().__init__(lock_file, **kwargs)
376
377 def _acquire(self) -> None:
378 raise NotImplementedError
379
380 def _release(self) -> None:
381 raise NotImplementedError
382
383
384 class _FileLockOptions(TypedDict, total=False):
385 timeout: float
386 mode: int
387 thread_local: bool
388 blocking: bool
389 is_singleton: bool
390 poll_interval: float
391 lifetime: float | None
392 context_error_policy: ContextErrorPolicy
393 close_error_policy: CloseErrorPolicy
394 fallback_to_soft: bool
395 preserve_lock_file: bool
396 on_acquired: Callable[[int], None] | None
397
398
399 class _AsyncFileLockOptions(_FileLockOptions, total=False):
400 loop: asyncio.AbstractEventLoop | None
401 run_in_executor: bool
402 executor: Executor | None
403
404
405 class _UnknownFileLockConstructor(Protocol):
406 def __call__(self, lock_file: str, *, unknown: bool) -> BaseFileLock: ...