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