Debian Codegraph @

tests/test_util.py

raw
1 from __future__ import annotations
2
3 import os
4 import socket
5 import stat
6 import sys
7 import time
8 from contextlib import suppress
9 from pathlib import Path
10 from typing import TYPE_CHECKING, Final
11
12 import pytest
13
14 from filelock import SoftFileLock, Timeout
15 from filelock._util import break_lock_file, raise_on_not_writable_file, touch
16
17 if TYPE_CHECKING:
18 from collections.abc import Generator
19
20 from pytest_mock import MockerFixture
21
22 _SKIP_AS_ROOT: Final[pytest.MarkDecorator] = pytest.mark.skipif(
23 sys.platform != "win32" and os.geteuid() == 0,
24 reason="root can write a 0o444 file",
25 )
26
27
28 def test_break_lock_file_unlinks_unchanged_file(tmp_path: Path) -> None:
29 lock = tmp_path / "test.lock"
30 lock.write_text("stale", encoding="utf-8")
31 st = os.lstat(lock)
32 break_lock_file(str(lock), st.st_mtime, st.st_ino)
33 assert not lock.exists()
34 assert list(tmp_path.glob("test.lock.break.*")) == []
35
36
37 def test_break_lock_file_preserves_file_when_mtime_advanced(tmp_path: Path) -> None:
38 lock = tmp_path / "test.lock"
39 lock.write_text("live", encoding="utf-8")
40 # An mtime_before older than the file's real mtime models a peer recreating the lock after our stale read.
41 # break_lock_file renames the live file aside but must not unlink it, so we never end with two live holders.
42 break_lock_file(str(lock), mtime_before=0.0, ino_before=os.lstat(lock).st_ino)
43 assert not lock.exists()
44 leftover = list(tmp_path.glob("test.lock.break.*"))
45 assert len(leftover) == 1
46 assert leftover[0].read_text(encoding="utf-8") == "live"
47
48
49 def test_break_lock_file_preserves_file_when_inode_changed(tmp_path: Path) -> None:
50 lock = tmp_path / "test.lock"
51 lock.write_text("stale", encoding="utf-8")
52 st = os.lstat(lock)
53 # Model a coarse-granularity filesystem (NFS, FAT) where a peer broke and recreated the lock with a new inode
54 # but the same mtime second. Creating the replacement while the original still exists guarantees a fresh inode.
55 other = tmp_path / "recreated"
56 other.write_text("live", encoding="utf-8")
57 os.utime(other, ns=(st.st_atime_ns, st.st_mtime_ns))
58 assert os.lstat(other).st_ino != st.st_ino
59 other.replace(lock)
60 break_lock_file(str(lock), st.st_mtime, st.st_ino)
61 leftover = list(tmp_path.glob("test.lock.break.*"))
62 assert len(leftover) == 1
63 assert leftover[0].read_text(encoding="utf-8") == "live"
64
65
66 def test_break_lock_file_aborts_if_break_path_vanishes(tmp_path: Path, mocker: MockerFixture) -> None:
67 lock = tmp_path / "test.lock"
68 lock.write_text("x", encoding="utf-8")
69 ino = os.lstat(lock).st_ino
70 mocker.patch("filelock._util.os.lstat", side_effect=FileNotFoundError)
71 break_lock_file(str(lock), 0.0, ino)
72 assert not lock.exists()
73 assert len(list(tmp_path.glob("test.lock.break.*"))) == 1
74
75
76 def test_break_lock_file_missing_source_raises(tmp_path: Path) -> None:
77 with pytest.raises(FileNotFoundError):
78 break_lock_file(str(tmp_path / "nope.lock"), 0.0, 0)
79
80
81 def test_break_lock_file_break_path_not_targetable_by_a_peer(tmp_path: Path, mocker: MockerFixture) -> None:
82 lock = tmp_path / "test.lock"
83 lock.write_text("stale", encoding="utf-8")
84 st = os.lstat(lock)
85
86 # A second breaker in the same process independently computes this name (no random token). If break_lock_file
87 # used it too, the peer could rename a freshly recreated live lock onto our break path in the window between the
88 # re-verify lstat and the unlink, and we would delete a live lock the inode check just approved.
89 predictable = tmp_path / f"test.lock.break.{os.getpid()}"
90 real_lstat = os.lstat
91
92 def lstat_hook(path: str) -> os.stat_result:
93 result = real_lstat(path)
94 # break_lock_file lstats the break path exactly once, so this guard only ever runs its body (once).
95 if ".break." in path and not predictable.exists(): # pragma: no branch # the peer recreates a live lock
96 lock.write_text("live", encoding="utf-8")
97 lock.rename(predictable)
98 return result
99
100 mocker.patch("filelock._util.os.lstat", side_effect=lstat_hook)
101 break_lock_file(str(lock), st.st_mtime, st.st_ino)
102
103 assert predictable.read_text(encoding="utf-8") == "live"
104
105
106 @pytest.mark.skipif(sys.platform == "win32", reason="symlink-to-dir raises IsADirectoryError only on Unix")
107 def test_raise_on_not_writable_file_does_not_follow_symlink_to_dir(tmp_path: Path) -> None: # pragma: win32 no cover
108 target = tmp_path / "targetdir"
109 target.mkdir()
110 link = tmp_path / "my.lock"
111 link.symlink_to(target)
112 # Following the symlink would see a directory and raise IsADirectoryError; lstat sees the link itself.
113 raise_on_not_writable_file(str(link))
114 assert stat.S_ISLNK(os.lstat(link).st_mode)
115
116
117 @pytest.mark.skipif(sys.platform == "win32", reason="symlink + 0o444 semantics differ on Windows")
118 @_SKIP_AS_ROOT # pragma: win32 no cover
119 def test_raise_on_not_writable_file_does_not_follow_symlink_to_readonly(tmp_path: Path) -> None:
120 target = tmp_path / "readonly"
121 target.write_text("x", encoding="utf-8")
122 target.chmod(0o444)
123 link = tmp_path / "my.lock"
124 link.symlink_to(target)
125 # Following the symlink would see a read-only file and raise PermissionError; the link itself is writable.
126 raise_on_not_writable_file(str(link))
127
128
129 @pytest.mark.skipif(sys.platform == "win32", reason="real dir raises PermissionError on Windows")
130 def test_raise_on_not_writable_file_still_rejects_real_directory(tmp_path: Path) -> None: # pragma: win32 no cover
131 path = tmp_path / "a_dir"
132 path.mkdir()
133 with pytest.raises(IsADirectoryError): # pragma: win32 no cover
134 raise_on_not_writable_file(str(path))
135
136
137 @pytest.mark.skipif(sys.platform == "win32", reason="Windows does not have read only files in the same way")
138 @_SKIP_AS_ROOT
139 def test_raise_on_not_writable_file_still_rejects_readonly_file(tmp_path: Path) -> None: # pragma: win32 no cover
140 path = tmp_path / "ro.lock"
141 path.write_text("x", encoding="utf-8")
142 path.chmod(0o444)
143 try: # pragma: win32 no cover
144 with pytest.raises(PermissionError): # pragma: win32 no cover
145 raise_on_not_writable_file(str(path))
146 finally:
147 path.chmod(0o644)
148
149
150 @_SKIP_AS_ROOT
151 @pytest.mark.parametrize("mtime", [0, 2_000_000_000], ids=["mtime-zero", "mtime-future"])
152 def test_raise_on_not_writable_file_rejects_readonly_file_any_mtime(tmp_path: Path, mtime: int) -> None:
153 path = tmp_path / "ro.lock"
154 path.write_text("x", encoding="utf-8")
155 path.chmod(0o444)
156 try:
157 os.utime(path, (mtime, mtime))
158 with pytest.raises(PermissionError):
159 raise_on_not_writable_file(str(path))
160 finally:
161 path.chmod(0o644)
162
163
164 @pytest.mark.skipif(sys.platform == "win32", reason="a real directory raises PermissionError on Windows")
165 def test_raise_on_not_writable_file_rejects_directory_with_mtime_zero(tmp_path: Path) -> None: # pragma: win32 no cover
166 path = tmp_path / "a_dir"
167 path.mkdir()
168 os.utime(path, (0, 0))
169 with pytest.raises(IsADirectoryError): # pragma: win32 no cover
170 raise_on_not_writable_file(str(path))
171
172
173 @pytest.mark.parametrize(
174 "mode", [pytest.param(0o444, id="acl"), pytest.param(0o464, id="group"), pytest.param(0o446, id="other")]
175 )
176 @pytest.mark.parametrize("effective_ids", [pytest.param(True, id="supported"), pytest.param(False, id="unsupported")])
177 def test_writability_uses_open_credentials(
178 readonly_marker: Path, mocker: MockerFixture, mode: int, *, effective_ids: bool
179 ) -> None:
180 readonly_marker.chmod(mode)
181
182 def access(filename: str, permission: int, *, effective_ids: bool = False) -> bool:
183 assert (filename, permission) == (str(readonly_marker), os.W_OK)
184 return effective_ids == supported
185
186 supported: Final = effective_ids
187 probe: Final = mocker.patch("os.access", autospec=True, side_effect=access)
188 mocker.patch("os.supports_effective_ids", {probe} if effective_ids else set())
189 with pytest.raises(Timeout):
190 SoftFileLock(readonly_marker).acquire(timeout=0)
191
192
193 def test_writability_allows_creation_after_marker_disappears(readonly_marker: Path, mocker: MockerFixture) -> None:
194 def access(filename: str, permission: int, *, effective_ids: bool = False) -> bool:
195 assert (permission, effective_ids) == (os.W_OK, os.access in os.supports_effective_ids)
196 readonly_marker.chmod(0o644)
197 Path(filename).unlink()
198 return False
199
200 mocker.patch("os.access", autospec=True, side_effect=access)
201 with (lock := SoftFileLock(readonly_marker)).acquire(timeout=0):
202 assert lock.is_locked
203
204
205 def test_writability_rejects_denied_marker(readonly_marker: Path, mocker: MockerFixture) -> None:
206 mocker.patch("os.access", autospec=True, return_value=False)
207 with pytest.raises(PermissionError):
208 SoftFileLock(readonly_marker).acquire(timeout=0)
209
210
211 @pytest.fixture
212 def readonly_marker(tmp_path: Path) -> Generator[Path]:
213 path: Final = tmp_path / "test.lock"
214 path.write_text(f"424242\n{socket.gethostname()}-other\n", encoding="utf-8")
215 path.chmod(0o444)
216 try:
217 yield path
218 finally:
219 with suppress(FileNotFoundError):
220 path.chmod(0o644)
221
222
223 @pytest.mark.skipif(
224 os.utime not in os.supports_follow_symlinks, reason="os.utime cannot refuse symlinks on this platform"
225 )
226 def test_touch_does_not_follow_symlink(tmp_path: Path) -> None: # pragma: needs utime-nofollow
227 # A path-based touch must land on the link itself, not the file it points at, matching the O_NOFOLLOW reads
228 # elsewhere: a peer that swaps a symlink in cannot redirect the refresh onto a victim file.
229 victim = tmp_path / "victim"
230 victim.write_text("do-not-touch")
231 past = time.time() - 1000
232 os.utime(victim, (past, past))
233 link = tmp_path / "link"
234 link.symlink_to(victim)
235
236 touch(str(link))
237
238 assert victim.stat().st_mtime == pytest.approx(past, abs=1) # a timestamp round-trip need not be bit-exact
239 assert link.lstat().st_mtime > victim.stat().st_mtime