| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import gc |
| 4 |
import os |
| 5 |
import socket |
| 6 |
import sys |
| 7 |
import threading |
| 8 |
from contextlib import contextmanager |
| 9 |
from errno import EACCES, EINTR, ENODEV, ENOSPC, EPERM |
| 10 |
from pathlib import Path |
| 11 |
from typing import TYPE_CHECKING, Final |
| 12 |
|
| 13 |
import pytest |
| 14 |
from capabilities import CAPABILITIES |
| 15 |
|
| 16 |
from filelock import CloseErrorPolicy, SoftFileLock |
| 17 |
from filelock._identity import process_start_token |
| 18 |
from filelock._soft import _MAX_LOCK_FILE_SIZE |
| 19 |
from tests.capability_marks import NEEDS_POSIX_SIGNALS, NEEDS_SYMLINK, NEEDS_UNLINK_OPEN_FILE |
| 20 |
|
| 21 |
if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 22 |
from builtins import ExceptionGroup # pragma: >=3.11 cover |
| 23 |
else: # pragma: no cover (<py311) |
| 24 |
from exceptiongroup import ExceptionGroup |
| 25 |
|
| 26 |
if TYPE_CHECKING: |
| 27 |
from collections.abc import Iterator |
| 28 |
from unittest.mock import MagicMock |
| 29 |
|
| 30 |
from pytest_mock import MockerFixture |
| 31 |
|
| 32 |
_WINDOWS_ONLY: Final[pytest.MarkDecorator] = pytest.mark.skipif(sys.platform != "win32", reason="windows-only") |
| 33 |
|
| 34 |
_HOST: Final[str] = socket.gethostname() |
| 35 |
_DEAD_PID: Final[int] = 2**22 + 1 |
| 36 |
_WIN_ERROR_ACCESS_DENIED: Final[int] = 5 |
| 37 |
_WIN_ERROR_INVALID_PARAMETER: Final[int] = 87 |
| 38 |
|
| 39 |
|
| 40 |
@pytest.fixture |
| 41 |
def lock_path(tmp_path: Path) -> Path: |
| 42 |
return tmp_path / "test.lock" |
| 43 |
|
| 44 |
|
| 45 |
def _holder(pid: int, *, host: str = _HOST, start: int | None = None) -> str: |
| 46 |
return "\n".join([str(pid), host, *([] if start is None else [str(start)])]) + "\n" |
| 47 |
|
| 48 |
|
| 49 |
def test_lock_writes_pid_and_hostname(lock_path: Path) -> None: |
| 50 |
with SoftFileLock(lock_path): |
| 51 |
lines = lock_path.read_text(encoding="utf-8").strip().splitlines() |
| 52 |
assert lines[:2] == [str(os.getpid()), _HOST] |
| 53 |
# Every platform with a proven start time writes it as an integer third line; one without writes two lines. |
| 54 |
if (token := process_start_token(os.getpid())) is not None: |
| 55 |
assert lines == [str(os.getpid()), _HOST, str(token)] |
| 56 |
else: # pragma: no cover # every CI platform exposes a start time |
| 57 |
assert lines == [str(os.getpid()), _HOST] |
| 58 |
|
| 59 |
|
| 60 |
@pytest.mark.parametrize( |
| 61 |
"content", |
| 62 |
[ |
| 63 |
pytest.param(_holder(_DEAD_PID), id="two_line"), |
| 64 |
pytest.param(_holder(_DEAD_PID, start=123456789), id="three_line"), |
| 65 |
], |
| 66 |
) |
| 67 |
def test_stale_lock_broken_when_process_dead(lock_path: Path, mocker: MockerFixture, content: str) -> None: |
| 68 |
lock_path.write_text(content, encoding="utf-8") |
| 69 |
mocker.patch("filelock._identity.process_alive", return_value=False) |
| 70 |
_assert_self_heals(lock_path) |
| 71 |
|
| 72 |
|
| 73 |
def test_stale_lock_not_broken_when_process_alive(lock_path: Path, mocker: MockerFixture) -> None: |
| 74 |
lock_path.write_text(_holder(os.getpid()), encoding="utf-8") |
| 75 |
mocker.patch("filelock._identity.process_alive", return_value=True) |
| 76 |
_assert_times_out(lock_path) |
| 77 |
|
| 78 |
|
| 79 |
def test_stale_lock_not_broken_different_hostname(lock_path: Path) -> None: |
| 80 |
lock_path.write_text(_holder(_DEAD_PID, host="other-host.example.com"), encoding="utf-8") |
| 81 |
_assert_times_out(lock_path) |
| 82 |
|
| 83 |
|
| 84 |
_REQUIRES_START_TOKEN: Final[pytest.MarkDecorator] = pytest.mark.skipif( |
| 85 |
process_start_token(os.getpid()) is None, reason="platform exposes no proven process start time" |
| 86 |
) |
| 87 |
|
| 88 |
|
| 89 |
@_REQUIRES_START_TOKEN |
| 90 |
def test_recycled_pid_marker_self_heals(lock_path: Path) -> None: |
| 91 |
# A live PID (our own) whose recorded start token differs is a recycled PID: the process that wrote the marker is |
| 92 |
# gone even though the number is now in use. No mock: the real start token is read and found not to match. |
| 93 |
token = process_start_token(os.getpid()) |
| 94 |
assert token is not None |
| 95 |
lock_path.write_text(_holder(os.getpid(), start=token + 1), encoding="utf-8") |
| 96 |
_assert_self_heals(lock_path) |
| 97 |
|
| 98 |
|
| 99 |
@_REQUIRES_START_TOKEN |
| 100 |
def test_live_process_with_matching_start_token_retained(lock_path: Path) -> None: |
| 101 |
# Our own PID and our own start token: the recorded owner is this live process, so the marker must stand. |
| 102 |
lock_path.write_text(_holder(os.getpid(), start=process_start_token(os.getpid())), encoding="utf-8") |
| 103 |
_assert_times_out(lock_path) |
| 104 |
|
| 105 |
|
| 106 |
def test_live_process_without_start_token_falls_back_to_pid(lock_path: Path) -> None: |
| 107 |
# A two-line marker carries no start token, so liveness rests on the PID alone; a live PID is left held. |
| 108 |
lock_path.write_text(_holder(os.getpid()), encoding="utf-8") |
| 109 |
_assert_times_out(lock_path) |
| 110 |
|
| 111 |
|
| 112 |
@NEEDS_POSIX_SIGNALS # pragma: needs posix-signals |
| 113 |
@pytest.mark.parametrize( |
| 114 |
"errno", |
| 115 |
[pytest.param(EPERM, id="eperm"), pytest.param(ENODEV, id="unexpected_device")], |
| 116 |
) |
| 117 |
def test_stale_lock_not_broken_on_kill_error(lock_path: Path, mocker: MockerFixture, errno: int) -> None: |
| 118 |
lock_path.write_text(_holder(99999), encoding="utf-8") |
| 119 |
mocker.patch("filelock._identity.os.kill", side_effect=OSError(errno, "kill failed")) |
| 120 |
_assert_times_out(lock_path) |
| 121 |
|
| 122 |
|
| 123 |
@pytest.mark.parametrize( |
| 124 |
"content", |
| 125 |
[ |
| 126 |
pytest.param(b"not-a-pid\n", id="malformed"), |
| 127 |
pytest.param(b"", id="empty"), |
| 128 |
pytest.param(b"x" * (_MAX_LOCK_FILE_SIZE + 1), id="oversized"), |
| 129 |
pytest.param(b"not-a-pid\nhostname\n", id="two_line_bad_pid"), |
| 130 |
pytest.param(f"{_DEAD_PID}\nhostname\nnot-a-token\n".encode(), id="three_line_bad_start_token"), |
| 131 |
], |
| 132 |
) |
| 133 |
def test_unparseable_lock_evicted_when_old(lock_path: Path, content: bytes) -> None: |
| 134 |
lock_path.write_bytes(content) |
| 135 |
os.utime(lock_path, (0, 0)) |
| 136 |
# An unreadable lock (bad line count, non-integer pid/start token, empty, or oversized) must self-heal |
| 137 |
# instead of staying stuck; a matching line count alone does not make a file well-formed. |
| 138 |
_assert_self_heals(lock_path) |
| 139 |
|
| 140 |
|
| 141 |
@pytest.mark.parametrize( |
| 142 |
"content", |
| 143 |
[ |
| 144 |
pytest.param(b"not-a-pid\n", id="malformed"), |
| 145 |
pytest.param(b"", id="empty"), |
| 146 |
pytest.param(b"not-a-pid\nhostname\n", id="two_line_bad_pid"), |
| 147 |
], |
| 148 |
) |
| 149 |
def test_unparseable_lock_not_evicted_when_fresh(lock_path: Path, content: bytes) -> None: |
| 150 |
lock_path.write_bytes(content) |
| 151 |
_assert_times_out(lock_path) |
| 152 |
|
| 153 |
|
| 154 |
@pytest.mark.parametrize( |
| 155 |
"pid", |
| 156 |
[ |
| 157 |
pytest.param(0, id="zero"), |
| 158 |
pytest.param(-1, id="negative"), |
| 159 |
pytest.param(2**31, id="oversized"), |
| 160 |
], |
| 161 |
) |
| 162 |
def test_out_of_range_pid_self_heals_when_old(lock_path: Path, pid: int) -> None: |
| 163 |
lock_path.write_text(_holder(pid), encoding="utf-8") |
| 164 |
os.utime(lock_path, (0, 0)) |
| 165 |
# pid 0 or -1 makes os.kill probe the caller's own process group (reads as alive), so the lock is never |
| 166 |
# reclaimed; an oversized pid raises OverflowError out of stale detection. Both are malformed and must |
| 167 |
# self-heal, matching what _parse_marker_bytes rejects. |
| 168 |
_assert_self_heals(lock_path) |
| 169 |
|
| 170 |
|
| 171 |
def test_out_of_range_pid_not_evicted_when_fresh(lock_path: Path) -> None: |
| 172 |
lock_path.write_text(_holder(0), encoding="utf-8") |
| 173 |
# A fresh out-of-range pid is malformed too, but like any malformed lock it is left alone until it ages |
| 174 |
# past the threshold, so a peer mid-write is not mistaken for a stale lock. |
| 175 |
_assert_times_out(lock_path) |
| 176 |
|
| 177 |
|
| 178 |
def test_stale_lock_rename_race(lock_path: Path, mocker: MockerFixture) -> None: |
| 179 |
lock_path.write_text(_holder(_DEAD_PID), encoding="utf-8") |
| 180 |
mocker.patch("filelock._identity.process_alive", return_value=False) |
| 181 |
mocker.patch.object(Path, "rename", side_effect=FileNotFoundError("already gone")) |
| 182 |
_assert_times_out(lock_path) |
| 183 |
|
| 184 |
|
| 185 |
@NEEDS_SYMLINK |
| 186 |
def test_symlinked_lock_file_is_not_followed(tmp_path: Path, lock_path: Path) -> None: # pragma: needs symlink |
| 187 |
target = tmp_path / "target" |
| 188 |
target.write_text(_holder(99999), encoding="utf-8") |
| 189 |
lock_path.symlink_to(target) |
| 190 |
|
| 191 |
# Neither the pid read nor stale detection may follow the symlink onto the target file. |
| 192 |
assert SoftFileLock(lock_path).pid is None |
| 193 |
assert target.read_text(encoding="utf-8") == _holder(99999) |
| 194 |
|
| 195 |
|
| 196 |
def test_fifo_lock_file_does_not_block(lock_path: Path) -> None: |
| 197 |
if sys.platform == "win32" or not CAPABILITIES["fifo"]: # pragma: win32 cover |
| 198 |
pytest.skip("os.mkfifo is unavailable") # the platform arm also narrows so ty resolves os.mkfifo below |
| 199 |
# An attacker-placed FIFO must not stall the open; O_NONBLOCK makes the read bail instead of hang. |
| 200 |
os.mkfifo(lock_path) # pragma: win32 no cover |
| 201 |
assert SoftFileLock(lock_path).pid is None # pragma: win32 no cover |
| 202 |
|
| 203 |
|
| 204 |
def test_fifo_lock_file_with_attached_writer_self_heals(lock_path: Path) -> None: |
| 205 |
if sys.platform == "win32" or not CAPABILITIES["fifo"]: # pragma: win32 cover |
| 206 |
pytest.skip("os.mkfifo is unavailable") # the platform arm also narrows so ty resolves os.mkfifo below |
| 207 |
# A same-UID peer can plant a FIFO with a writer attached so a non-blocking read would raise EAGAIN. The lstat |
| 208 |
# guard classifies it as a malformed lock before any open, so an aged FIFO self-heals like any other node. |
| 209 |
os.mkfifo(lock_path) # pragma: win32 no cover |
| 210 |
reader = os.open(lock_path, os.O_RDONLY | os.O_NONBLOCK) # pragma: win32 no cover |
| 211 |
writer = os.open(lock_path, os.O_WRONLY | os.O_NONBLOCK) # pragma: win32 no cover |
| 212 |
try: # pragma: win32 no cover |
| 213 |
os.utime(lock_path, (0, 0)) |
| 214 |
_assert_self_heals(lock_path) |
| 215 |
finally: |
| 216 |
os.close(reader) # pragma: win32 no cover |
| 217 |
os.close(writer) # pragma: win32 no cover |
| 218 |
|
| 219 |
|
| 220 |
def test_socket_lock_file_self_heals(lock_path: Path) -> None: |
| 221 |
if sys.platform == "win32": # pragma: win32 cover |
| 222 |
pytest.skip("AF_UNIX sockets are unix-only") |
| 223 |
sock = socket.socket(socket.AF_UNIX) # pragma: win32 no cover |
| 224 |
try: # pragma: win32 no cover |
| 225 |
sock.bind(str(lock_path)) |
| 226 |
except OSError: # pragma: darwin cover |
| 227 |
sock.close() # pragma: darwin cover |
| 228 |
pytest.skip("AF_UNIX path too long for this temp dir") # pragma: darwin cover |
| 229 |
# A Unix-domain socket cannot be os.open()ed as a file. Before the lstat guard the failed open was swallowed by |
| 230 |
# stale detection so acquisition wedged; an aged socket now self-heals like any other non-regular node. |
| 231 |
try: # pragma: linux cover |
| 232 |
os.utime(lock_path, (0, 0)) |
| 233 |
_assert_self_heals(lock_path) |
| 234 |
finally: |
| 235 |
sock.close() # pragma: linux cover |
| 236 |
|
| 237 |
|
| 238 |
def test_stale_detection_errors_suppressed(lock_path: Path, mocker: MockerFixture) -> None: |
| 239 |
lock_path.write_text(_holder(os.getpid()), encoding="utf-8") |
| 240 |
mock_read: MagicMock = mocker.patch("filelock._soft._read_lock_file", side_effect=OSError("read failed")) |
| 241 |
_assert_times_out(lock_path) |
| 242 |
mock_read.assert_called() |
| 243 |
|
| 244 |
|
| 245 |
@_WINDOWS_ONLY |
| 246 |
@pytest.mark.parametrize( |
| 247 |
("captured_error", "ambient_error", "acquires"), |
| 248 |
[ |
| 249 |
pytest.param(_WIN_ERROR_INVALID_PARAMETER, _WIN_ERROR_ACCESS_DENIED, True, id="dead"), |
| 250 |
pytest.param(_WIN_ERROR_ACCESS_DENIED, _WIN_ERROR_INVALID_PARAMETER, False, id="access-denied"), |
| 251 |
], |
| 252 |
) |
| 253 |
def test_windows_stale_lock_uses_captured_process_error( # pragma: win32 cover |
| 254 |
lock_path: Path, |
| 255 |
mocker: MockerFixture, |
| 256 |
captured_error: int, |
| 257 |
ambient_error: int, |
| 258 |
*, |
| 259 |
acquires: bool, |
| 260 |
) -> None: |
| 261 |
if sys.platform != "win32": # pragma: win32 cover |
| 262 |
pytest.skip("windows-only") # pragma: no cover # win32-only test; this guard never runs |
| 263 |
import ctypes |
| 264 |
|
| 265 |
def fail_open_process(_access: int, _inherit_handle: bool, _pid: int) -> None: |
| 266 |
ctypes.set_last_error(captured_error) |
| 267 |
ctypes.windll.kernel32.SetLastError(ambient_error) |
| 268 |
|
| 269 |
# ctypes function pointers do not expose a Python signature for autospec. |
| 270 |
mocker.patch("filelock._identity._KERNEL32.OpenProcess", side_effect=fail_open_process) |
| 271 |
lock_path.write_text(_holder(_DEAD_PID), encoding="utf-8") |
| 272 |
if acquires: |
| 273 |
_assert_self_heals(lock_path) |
| 274 |
else: |
| 275 |
_assert_times_out(lock_path) |
| 276 |
|
| 277 |
|
| 278 |
@_WINDOWS_ONLY |
| 279 |
def test_windows_stale_lock_broken_when_pid_recycled(lock_path: Path) -> None: # pragma: win32 cover |
| 280 |
process_marker = lock_path.with_suffix(".process") |
| 281 |
with SoftFileLock(process_marker): |
| 282 |
start = int(process_marker.read_text(encoding="utf-8").splitlines()[2]) |
| 283 |
lock_path.write_text(_holder(os.getpid(), start=start + 1), encoding="utf-8") |
| 284 |
_assert_self_heals(lock_path) |
| 285 |
|
| 286 |
|
| 287 |
@_WINDOWS_ONLY |
| 288 |
def test_windows_live_process_marker_retained(lock_path: Path) -> None: # pragma: win32 cover |
| 289 |
lock = SoftFileLock(lock_path) |
| 290 |
lock.acquire() |
| 291 |
try: |
| 292 |
_assert_times_out(lock_path) |
| 293 |
finally: |
| 294 |
lock.release() |
| 295 |
|
| 296 |
|
| 297 |
@_WINDOWS_ONLY |
| 298 |
def test_windows_live_process_marker_without_start_token_retained(lock_path: Path) -> None: # pragma: win32 cover |
| 299 |
lock_path.write_text(_holder(os.getpid()), encoding="utf-8") |
| 300 |
_assert_times_out(lock_path) |
| 301 |
|
| 302 |
|
| 303 |
@_WINDOWS_ONLY |
| 304 |
def test_windows_process_probe_closes_handles(lock_path: Path) -> None: # pragma: win32 cover |
| 305 |
lock = SoftFileLock(lock_path) |
| 306 |
lock.acquire() |
| 307 |
try: |
| 308 |
handle_count = _current_process_handle_count() |
| 309 |
for _attempt in range(50): |
| 310 |
_assert_times_out(lock_path, timeout=0) |
| 311 |
# A per-probe handle leak would add one handle per iteration, so ~50 over the loop. Assert no growth beyond a |
| 312 |
# small margin rather than exact equality, which another thread opening or closing a handle would break. |
| 313 |
assert _current_process_handle_count() <= handle_count + 5 |
| 314 |
finally: |
| 315 |
lock.release() |
| 316 |
|
| 317 |
|
| 318 |
@pytest.mark.parametrize( |
| 319 |
("content", "expected"), |
| 320 |
[ |
| 321 |
pytest.param(None, None, id="no_file"), |
| 322 |
pytest.param(b"not-a-number\n", None, id="malformed"), |
| 323 |
pytest.param(b"\xff\xfe\n", None, id="non_utf8"), |
| 324 |
pytest.param(b"x" * (_MAX_LOCK_FILE_SIZE + 1), None, id="oversized"), |
| 325 |
pytest.param(b"42\n", None, id="single_line"), |
| 326 |
pytest.param(_holder(0).encode(), None, id="out_of_range_pid"), |
| 327 |
pytest.param(_holder(os.getpid()).encode(), os.getpid(), id="valid"), |
| 328 |
], |
| 329 |
) |
| 330 |
def test_pid(lock_path: Path, content: bytes | None, expected: int | None) -> None: |
| 331 |
if content is not None: |
| 332 |
lock_path.write_bytes(content) |
| 333 |
assert SoftFileLock(lock_path).pid == expected |
| 334 |
|
| 335 |
|
| 336 |
def test_pid_while_locked(lock_path: Path) -> None: |
| 337 |
lock = SoftFileLock(lock_path) |
| 338 |
with lock: |
| 339 |
assert lock.pid == os.getpid() |
| 340 |
|
| 341 |
|
| 342 |
@pytest.mark.parametrize( |
| 343 |
("content", "expected"), |
| 344 |
[ |
| 345 |
pytest.param(None, False, id="no_file"), |
| 346 |
pytest.param(_holder(os.getpid() + 1), False, id="different_pid"), |
| 347 |
pytest.param(_holder(os.getpid()), True, id="same_pid"), |
| 348 |
pytest.param(_holder(os.getpid(), host="other-host"), False, id="same_pid_different_host"), |
| 349 |
], |
| 350 |
) |
| 351 |
def test_is_lock_held_by_us(lock_path: Path, content: str | None, expected: bool) -> None: |
| 352 |
if content is not None: |
| 353 |
lock_path.write_text(content, encoding="utf-8") |
| 354 |
assert SoftFileLock(lock_path).is_lock_held_by_us is expected |
| 355 |
|
| 356 |
|
| 357 |
@pytest.mark.parametrize( |
| 358 |
"exists", |
| 359 |
[pytest.param(True, id="exists"), pytest.param(False, id="missing")], |
| 360 |
) |
| 361 |
def test_break_lock(lock_path: Path, *, exists: bool) -> None: |
| 362 |
if exists: |
| 363 |
lock_path.write_text(_holder(os.getpid()), encoding="utf-8") |
| 364 |
SoftFileLock(lock_path).break_lock() |
| 365 |
assert not lock_path.exists() |
| 366 |
|
| 367 |
|
| 368 |
def test_write_failure_rolls_back_acquire(lock_path: Path, mocker: MockerFixture) -> None: |
| 369 |
mocker.patch("filelock._util.os.write", side_effect=OSError(ENOSPC, "No space left on device")) |
| 370 |
|
| 371 |
lock = SoftFileLock(lock_path) |
| 372 |
with pytest.raises(OSError, match="No space left on device"): |
| 373 |
lock.acquire() |
| 374 |
assert not lock.is_locked |
| 375 |
assert not lock_path.exists() |
| 376 |
|
| 377 |
|
| 378 |
def _assert_self_heals(lock_path: Path) -> None: |
| 379 |
lock = SoftFileLock(lock_path, timeout=1) |
| 380 |
with lock: |
| 381 |
assert lock.is_locked |
| 382 |
|
| 383 |
|
| 384 |
def _assert_times_out(lock_path: Path, *, timeout: float = 0.1) -> None: |
| 385 |
with pytest.raises(TimeoutError): |
| 386 |
SoftFileLock(lock_path, timeout=timeout).acquire() |
| 387 |
|
| 388 |
|
| 389 |
def _current_process_handle_count() -> int: # pragma: win32 cover |
| 390 |
if sys.platform != "win32": # pragma: win32 cover |
| 391 |
pytest.skip("windows-only") # pragma: no cover # only ever called on win32, so this guard never runs |
| 392 |
import ctypes |
| 393 |
from ctypes import wintypes |
| 394 |
|
| 395 |
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) |
| 396 |
kernel32.GetCurrentProcess.argtypes = [] |
| 397 |
kernel32.GetCurrentProcess.restype = wintypes.HANDLE |
| 398 |
kernel32.GetProcessHandleCount.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] |
| 399 |
kernel32.GetProcessHandleCount.restype = wintypes.BOOL |
| 400 |
count = wintypes.DWORD() |
| 401 |
assert kernel32.GetProcessHandleCount(kernel32.GetCurrentProcess(), ctypes.byref(count)), ctypes.WinError( |
| 402 |
ctypes.get_last_error() |
| 403 |
) |
| 404 |
return count.value |
| 405 |
|
| 406 |
|
| 407 |
def _hold_reports_foreign_identity(mocker: MockerFixture) -> None: |
| 408 |
# Make the held descriptor report a different inode than the file on disk, as if a peer replaced the marker at the |
| 409 |
# path. fstat runs only on our own lock fd, so nothing else in acquire or release is disturbed. |
| 410 |
mocker.patch("filelock._soft.os.fstat", return_value=mocker.Mock(st_dev=1, st_ino=999)) |
| 411 |
|
| 412 |
|
| 413 |
def test_short_writes_still_write_the_whole_record(lock_path: Path, mocker: MockerFixture) -> None: |
| 414 |
real_write = os.write |
| 415 |
mocker.patch("filelock._util.os.write", side_effect=lambda fd, data: real_write(fd, bytes(data[:1]))) |
| 416 |
|
| 417 |
with SoftFileLock(lock_path): |
| 418 |
lines = lock_path.read_text(encoding="utf-8").splitlines() |
| 419 |
assert lines[0] == str(os.getpid()) |
| 420 |
assert lines[1] == _HOST |
| 421 |
|
| 422 |
|
| 423 |
def test_zero_write_rolls_back_acquire(lock_path: Path, mocker: MockerFixture) -> None: |
| 424 |
mocker.patch("filelock._util.os.write", return_value=0) |
| 425 |
|
| 426 |
lock = SoftFileLock(lock_path) |
| 427 |
with pytest.raises(OSError, match="0 bytes"): |
| 428 |
lock.acquire() |
| 429 |
assert not lock.is_locked |
| 430 |
assert not lock_path.exists() |
| 431 |
|
| 432 |
|
| 433 |
def test_failed_acquire_cleanup_spares_a_replacement(lock_path: Path, mocker: MockerFixture) -> None: |
| 434 |
mocker.patch("filelock._util.os.write", side_effect=OSError(ENOSPC, "No space left on device")) |
| 435 |
_hold_reports_foreign_identity(mocker) |
| 436 |
|
| 437 |
lock = SoftFileLock(lock_path) |
| 438 |
with pytest.raises(OSError, match="No space left on device"): |
| 439 |
lock.acquire() |
| 440 |
assert lock_path.exists() |
| 441 |
|
| 442 |
|
| 443 |
def test_release_without_identity_skips_unlink(lock_path: Path, mocker: MockerFixture) -> None: |
| 444 |
lock = SoftFileLock(lock_path) |
| 445 |
lock.acquire() |
| 446 |
# The held descriptor can no longer be identified, so release cannot prove the path is still ours: it closes and |
| 447 |
# clears held state without unlinking rather than risk deleting a successor's marker. |
| 448 |
mocker.patch("filelock._soft.os.fstat", side_effect=OSError) |
| 449 |
lock.release() |
| 450 |
assert not lock.is_locked |
| 451 |
assert lock_path.exists() |
| 452 |
|
| 453 |
|
| 454 |
def test_normal_release_removes_own_marker(lock_path: Path) -> None: |
| 455 |
with SoftFileLock(lock_path): |
| 456 |
assert lock_path.exists() |
| 457 |
assert not lock_path.exists() |
| 458 |
|
| 459 |
|
| 460 |
def test_del_suppresses_a_release_error(lock_path: Path, mocker: MockerFixture) -> None: |
| 461 |
# A dropped, still-held lock is finalized by __del__. A release error there must not escape as an unraisable |
| 462 |
# exception during garbage collection, which pytest would fail on and attribute to an unrelated test. Finalizing |
| 463 |
# under a raising release and forcing collection here leaves the run clean only if __del__ swallows the error. |
| 464 |
lock = SoftFileLock(lock_path) |
| 465 |
lock.acquire() |
| 466 |
mocker.patch.object(SoftFileLock, "release", side_effect=OSError("release failed")) |
| 467 |
del lock |
| 468 |
gc.collect() |
| 469 |
|
| 470 |
|
| 471 |
@NEEDS_UNLINK_OPEN_FILE |
| 472 |
def test_stale_release_spares_a_successor(lock_path: Path) -> None: # pragma: needs unlink-open-file |
| 473 |
holder = SoftFileLock(lock_path) |
| 474 |
holder.acquire() |
| 475 |
# A peer breaks the stale marker and installs its own at the same path; unlink first so it gets a fresh inode. |
| 476 |
lock_path.unlink() |
| 477 |
lock_path.write_text(_holder(_DEAD_PID), encoding="utf-8") |
| 478 |
holder.release() |
| 479 |
assert lock_path.exists() |
| 480 |
assert str(_DEAD_PID) in lock_path.read_text(encoding="utf-8") |
| 481 |
|
| 482 |
|
| 483 |
@_WINDOWS_ONLY |
| 484 |
def test_windows_release_spares_a_replacement(lock_path: Path, mocker: MockerFixture) -> None: # pragma: win32 cover |
| 485 |
lock = SoftFileLock(lock_path) |
| 486 |
lock.acquire() |
| 487 |
_hold_reports_foreign_identity(mocker) |
| 488 |
lock.release() |
| 489 |
assert lock_path.exists() |
| 490 |
lock_path.unlink() |
| 491 |
|
| 492 |
|
| 493 |
@pytest.mark.parametrize( |
| 494 |
("policy", "surfaces"), |
| 495 |
[ |
| 496 |
pytest.param("default", True, id="default"), |
| 497 |
pytest.param("raise", True, id="raise"), |
| 498 |
pytest.param("suppress", False, id="suppress"), |
| 499 |
], |
| 500 |
) |
| 501 |
def test_close_error_policy_cleans_marker( |
| 502 |
lock_path: Path, |
| 503 |
mocker: MockerFixture, |
| 504 |
policy: CloseErrorPolicy, |
| 505 |
*, |
| 506 |
surfaces: bool, |
| 507 |
) -> None: |
| 508 |
lock = SoftFileLock(lock_path, close_error_policy=policy) |
| 509 |
lock.acquire() |
| 510 |
with _close_after_commit(mocker, lock) as (close_error, attempts): |
| 511 |
if surfaces: |
| 512 |
with pytest.raises(OSError, match="close failed") as info: |
| 513 |
lock.release() |
| 514 |
assert info.value is close_error |
| 515 |
else: |
| 516 |
lock.release() |
| 517 |
assert (len(attempts), lock.is_locked, lock.lock_counter, lock_path.exists()) == (1, False, 0, False) |
| 518 |
|
| 519 |
|
| 520 |
@pytest.mark.parametrize( |
| 521 |
("depth", "force"), |
| 522 |
[pytest.param(2, False, id="nested"), pytest.param(2, True, id="forced")], |
| 523 |
) |
| 524 |
def test_close_error_suppression_releases_once( |
| 525 |
lock_path: Path, |
| 526 |
mocker: MockerFixture, |
| 527 |
depth: int, |
| 528 |
*, |
| 529 |
force: bool, |
| 530 |
) -> None: |
| 531 |
lock = SoftFileLock(lock_path, close_error_policy="suppress") |
| 532 |
for _acquisition in range(depth): |
| 533 |
lock.acquire() |
| 534 |
with _close_after_commit(mocker, lock) as (_, attempts): |
| 535 |
if force: |
| 536 |
lock.release(force=True) |
| 537 |
else: |
| 538 |
for _release in range(depth): |
| 539 |
lock.release() |
| 540 |
assert (len(attempts), lock.is_locked, lock.lock_counter, lock_path.exists()) == (1, False, 0, False) |
| 541 |
|
| 542 |
|
| 543 |
@pytest.mark.parametrize( |
| 544 |
"use_proxy", |
| 545 |
[pytest.param(False, id="direct"), pytest.param(True, id="proxy")], |
| 546 |
) |
| 547 |
def test_context_surfaces_close_error_after_cleanup( |
| 548 |
lock_path: Path, |
| 549 |
mocker: MockerFixture, |
| 550 |
*, |
| 551 |
use_proxy: bool, |
| 552 |
) -> None: |
| 553 |
lock = SoftFileLock(lock_path) |
| 554 |
with ( |
| 555 |
_close_after_commit(mocker, lock) as (close_error, attempts), |
| 556 |
pytest.raises(OSError, match="close failed") as info, |
| 557 |
lock.acquire() if use_proxy else lock, |
| 558 |
): |
| 559 |
pass |
| 560 |
assert (info.value, len(attempts), lock.is_locked, lock_path.exists()) == (close_error, 1, False, False) |
| 561 |
|
| 562 |
|
| 563 |
def test_second_release_does_not_close_reused_descriptor( |
| 564 |
lock_path: Path, |
| 565 |
tmp_path: Path, |
| 566 |
mocker: MockerFixture, |
| 567 |
) -> None: |
| 568 |
lock = SoftFileLock(lock_path) |
| 569 |
lock.acquire() |
| 570 |
with ( |
| 571 |
_close_after_commit(mocker, lock) as (close_error, attempts), |
| 572 |
pytest.raises(OSError, match="close failed") as info, |
| 573 |
): |
| 574 |
lock.release() |
| 575 |
assert info.value is close_error |
| 576 |
reused_fd = os.open(tmp_path / "reused", os.O_CREAT | os.O_WRONLY) |
| 577 |
assert reused_fd == attempts[0] |
| 578 |
try: |
| 579 |
lock.release() |
| 580 |
os.fstat(reused_fd) |
| 581 |
finally: |
| 582 |
os.close(reused_fd) |
| 583 |
|
| 584 |
|
| 585 |
@NEEDS_UNLINK_OPEN_FILE # pragma: needs unlink-open-file |
| 586 |
def test_close_error_spares_successor_marker(lock_path: Path, mocker: MockerFixture) -> None: |
| 587 |
holder = SoftFileLock(lock_path) |
| 588 |
holder.acquire() |
| 589 |
lock_path.unlink() |
| 590 |
lock_path.write_text(_holder(_DEAD_PID), encoding="utf-8") |
| 591 |
with _close_after_commit(mocker, holder) as (_, _attempts), pytest.raises(OSError, match="close failed"): |
| 592 |
holder.release() |
| 593 |
assert lock_path.read_text(encoding="utf-8") == _holder(_DEAD_PID) |
| 594 |
|
| 595 |
|
| 596 |
def test_close_and_marker_cleanup_failures_are_grouped(lock_path: Path, mocker: MockerFixture) -> None: |
| 597 |
lock = SoftFileLock(lock_path) |
| 598 |
lock.acquire() |
| 599 |
cleanup_error = RuntimeError("cleanup failed") |
| 600 |
unlink_mock = mocker.patch("filelock._soft.Path.unlink", side_effect=cleanup_error) |
| 601 |
with _close_after_commit(mocker, lock) as (close_error, _attempts), pytest.raises(ExceptionGroup) as info: |
| 602 |
lock.release() |
| 603 |
mocker.stop(unlink_mock) |
| 604 |
assert ( |
| 605 |
info.value.message, |
| 606 |
info.value.exceptions, |
| 607 |
close_error.__context__, |
| 608 |
cleanup_error.__context__, |
| 609 |
lock.is_locked, |
| 610 |
) == ( |
| 611 |
"lock descriptor close and marker cleanup both failed", |
| 612 |
(close_error, cleanup_error), |
| 613 |
None, |
| 614 |
None, |
| 615 |
False, |
| 616 |
) |
| 617 |
|
| 618 |
|
| 619 |
def test_close_after_commit_ignores_other_descriptors(lock_path: Path, mocker: MockerFixture) -> None: |
| 620 |
# The patch binds os.close process-wide, so a descriptor that is not the lock's, whether closed on another thread |
| 621 |
# or by a finalizer the collector happens to run on this one, must pass through cleanly and stay out of the |
| 622 |
# recorded attempts. |
| 623 |
lock = SoftFileLock(lock_path) |
| 624 |
lock.acquire() |
| 625 |
closed: list[int] = [] |
| 626 |
|
| 627 |
def close_a_pipe() -> None: |
| 628 |
read_fd, write_fd = os.pipe() |
| 629 |
os.close(read_fd) |
| 630 |
os.close(write_fd) |
| 631 |
closed.extend((read_fd, write_fd)) |
| 632 |
|
| 633 |
with _close_after_commit(mocker, lock) as (_close_error, attempts): |
| 634 |
close_a_pipe() |
| 635 |
worker = threading.Thread(target=close_a_pipe) |
| 636 |
worker.start() |
| 637 |
worker.join() |
| 638 |
with pytest.raises(OSError, match="close failed"): |
| 639 |
lock.release() |
| 640 |
|
| 641 |
assert (len(closed), len(attempts), attempts[0] in closed) == (4, 1, False) |
| 642 |
|
| 643 |
|
| 644 |
@contextmanager |
| 645 |
def _close_after_commit(mocker: MockerFixture, lock: SoftFileLock) -> Iterator[tuple[OSError, list[int]]]: |
| 646 |
real_close = os.close |
| 647 |
close_error = OSError(EINTR, "close failed") |
| 648 |
attempts: list[int] = [] |
| 649 |
# close is an attribute of the shared os module, so this patch binds for every close in the process while the |
| 650 |
# window is open, including one a GC-run finalizer (a multiprocessing pipe from an earlier test, say) makes on this |
| 651 |
# very thread. Fail only the descriptor this lock lets go of: it clears its bookkeeping right before the one close |
| 652 |
# attempt, so record the descriptor as it does. |
| 653 |
released: list[int | None] = [] |
| 654 |
real_mark_released = lock._mark_descriptor_released |
| 655 |
|
| 656 |
def mark_released() -> None: |
| 657 |
released.append(lock._context.lock_file_fd) |
| 658 |
real_mark_released() |
| 659 |
|
| 660 |
def close(fd: int) -> None: |
| 661 |
real_close(fd) |
| 662 |
if fd not in released: |
| 663 |
return |
| 664 |
attempts.append(fd) |
| 665 |
raise close_error |
| 666 |
|
| 667 |
mocker.patch.object(lock, "_mark_descriptor_released", side_effect=mark_released) |
| 668 |
close_mock = mocker.patch("filelock._soft.os.close", side_effect=close) |
| 669 |
try: |
| 670 |
yield close_error, attempts |
| 671 |
finally: |
| 672 |
mocker.stop(close_mock) |
| 673 |
|
| 674 |
|
| 675 |
def test_soft_windows_unlink_gives_up_after_every_attempt_is_denied(tmp_path: Path, mocker: MockerFixture) -> None: |
| 676 |
# Windows can still hold a handle just after close, so the marker unlink retries on EACCES. Deny every attempt to |
| 677 |
# prove the retry runs and then stops, and that the denial never escapes to the caller. |
| 678 |
from filelock._soft import _file_identity |
| 679 |
|
| 680 |
marker = tmp_path / "a" |
| 681 |
marker.write_text("x", encoding="utf-8") |
| 682 |
lock = SoftFileLock(marker) |
| 683 |
mocker.patch("filelock._soft.time.sleep") |
| 684 |
mocker.patch("filelock._soft.Path.unlink", side_effect=PermissionError(EACCES, "handle still open")) |
| 685 |
|
| 686 |
lock._windows_unlink_if_ours(_file_identity(os.lstat(marker))) |
| 687 |
|
| 688 |
assert marker.exists() |