Debian Codegraph @

tests/read_write_helpers.py

raw
1 from __future__ import annotations
2
3 import multiprocessing
4 from typing import TYPE_CHECKING, Literal
5
6 from filelock import ReadWriteLock, Timeout
7
8 if TYPE_CHECKING:
9 from multiprocessing.sharedctypes import Synchronized
10
11
12 def assert_read_write_lock_state(lock_file: str, mode: Literal["read", "write"], *, available: bool) -> None:
13 context = multiprocessing.get_context("spawn")
14 acquired = context.Value("b", False)
15 probe = context.Process(target=_probe_read_write_lock, args=(lock_file, mode, acquired))
16 probe.start()
17 try:
18 probe.join(timeout=5)
19 assert not probe.is_alive(), "read-write lock probe did not exit"
20 assert (probe.exitcode, acquired.value) == (0, available)
21 finally:
22 if probe.is_alive(): # pragma: no cover - cleanup for a hung child after the assertion fails
23 probe.terminate()
24 probe.join(timeout=5)
25 probe.close()
26
27
28 def _probe_read_write_lock(lock_file: str, mode: Literal["read", "write"], acquired: Synchronized[bool]) -> None:
29 lock = ReadWriteLock(lock_file, is_singleton=False)
30 try:
31 (lock.acquire_read if mode == "read" else lock.acquire_write)(blocking=False)
32 except Timeout:
33 return
34 acquired.value = True
35 lock.release()
36 lock.close()
37
38
39 __all__ = ["assert_read_write_lock_state"]