Debian Codegraph @

tests/test_async_soft_contracts.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import os
5 import sys
6 from typing import TYPE_CHECKING
7
8 import pytest
9
10 from filelock import AsyncSoftFileLease, AsyncStrictSoftFileLock, LeaseCompromise, Timeout
11
12 if TYPE_CHECKING:
13 from pathlib import Path
14
15 _DURATION: float = 0.9
16 _HEARTBEAT: float = 0.1
17
18
19 @pytest.fixture
20 def marker(tmp_path: Path) -> Path:
21 return tmp_path / "a.lock"
22
23
24 @pytest.mark.requires_hard_links
25 @pytest.mark.asyncio
26 async def test_async_strict_treats_a_foreign_marker_as_contention(marker: Path) -> None: # pragma: needs hard-link
27 await asyncio.to_thread(marker.write_text, "filelock/2\npid=999999\nhost=nowhere\nmode=strict\n", encoding="utf-8")
28 lock = AsyncStrictSoftFileLock(str(marker), timeout=0.2)
29
30 with pytest.raises(Timeout):
31 await lock.acquire()
32 assert await asyncio.to_thread(marker.exists)
33
34
35 @pytest.mark.requires_hard_links
36 @pytest.mark.asyncio
37 async def test_async_strict_publishes_a_held_claim(marker: Path) -> None: # pragma: needs hard-link
38 lock = AsyncStrictSoftFileLock(str(marker))
39
40 async with lock:
41 held = lock.claims
42
43 assert tuple(claim.state for claim in held) == ("held", "intent")
44 assert held[0].pid == os.getpid()
45
46
47 @pytest.mark.asyncio
48 async def test_async_lease_heartbeat_keeps_a_live_claim(marker: Path) -> None:
49 lease = AsyncSoftFileLease(str(marker), lease_duration=_DURATION, heartbeat_interval=_HEARTBEAT)
50
51 async with lease:
52 await asyncio.sleep(_DURATION * 1.5) # only a refreshing heartbeat keeps the claim past this
53 assert lease.compromise is None
54 assert lease.token is not None
55
56
57 @pytest.mark.skipif(
58 sys.platform == "win32",
59 reason="Windows keeps an open marker undeletable, so no peer can take it from a live holder",
60 )
61 @pytest.mark.asyncio
62 async def test_async_lease_reports_compromise_when_the_marker_vanishes(marker: Path) -> None: # pragma: win32 no cover
63 seen: list[LeaseCompromise] = []
64 lease = AsyncSoftFileLease(
65 str(marker), lease_duration=_DURATION, heartbeat_interval=_HEARTBEAT, on_compromise=seen.append
66 )
67
68 async with lease: # pragma: win32 no cover
69 await asyncio.to_thread(marker.unlink)
70 await asyncio.sleep(_HEARTBEAT * 5)
71
72 assert [c.reason for c in seen] == ["marker-missing"]