Debian Codegraph @

tests/test_unix_fallback.py

raw
1 from __future__ import annotations
2
3 import os
4 import socket
5 import subprocess # ruff:ignore[suspicious-subprocess-import] # a clean interpreter isolates the blocked fcntl import
6 import sys
7 from errno import EIO, ENOSYS
8 from textwrap import dedent
9 from typing import TYPE_CHECKING, Final
10
11 import pytest
12
13 from filelock import SoftFileLock, UnixFileLock
14 from filelock._identity import process_start_token
15 from tests.capability_marks import NEEDS_FCNTL
16
17 if TYPE_CHECKING:
18 from pathlib import Path
19 from unittest.mock import MagicMock
20
21 from pytest_mock import MockerFixture
22
23
24 @NEEDS_FCNTL
25 def test_import_without_fcntl_uses_soft_aliases_and_descriptor_errors() -> None: # pragma: needs fcntl
26 script: Final[str] = dedent(
27 """
28 import json
29 import sys
30 import warnings
31 from collections.abc import Callable
32 from errno import ENOSYS
33
34 sys.modules["fcntl"] = None
35 with warnings.catch_warnings(record=True) as caught:
36 warnings.simplefilter("always")
37 import filelock
38
39 def operation_errno(operation: Callable[[int], bool | None]) -> int | None:
40 try:
41 operation(-1)
42 except OSError as exception:
43 return exception.errno
44 return None
45
46 print(json.dumps({
47 "aliases": [
48 filelock.FileLock is filelock.SoftFileLock,
49 filelock.AsyncFileLock is filelock.AsyncSoftFileLock,
50 ],
51 "errors": [
52 operation_errno(filelock.lock_descriptor) == ENOSYS,
53 operation_errno(filelock.unlock_descriptor) == ENOSYS,
54 ],
55 "warnings": [str(item.message) for item in caught],
56 }, sort_keys=True))
57 """,
58 )
59 result: Final[subprocess.CompletedProcess[str]] = subprocess.run(
60 [sys.executable, "-c", script], check=True, capture_output=True, text=True
61 )
62
63 assert (result.stdout, result.stderr) == (
64 '{"aliases": [true, true], "errors": [true, true], "warnings": ["only soft file lock is available"]}\n',
65 "",
66 )
67
68
69 @NEEDS_FCNTL
70 @pytest.mark.usefixtures("unsupported_flock")
71 def test_fallback_emits_warning(tmp_path: Path) -> None: # pragma: needs fcntl
72 lock = UnixFileLock(tmp_path / "test.lock")
73
74 with pytest.warns(UserWarning, match="flock not supported on this filesystem, falling back to SoftFileLock"):
75 lock.acquire()
76 lock.release()
77
78
79 @NEEDS_FCNTL
80 @pytest.mark.filterwarnings("ignore:flock not supported on this filesystem:UserWarning")
81 @pytest.mark.usefixtures("unsupported_flock")
82 def test_fallback_swaps_to_soft(tmp_path: Path) -> None: # pragma: needs fcntl
83 lock = UnixFileLock(tmp_path / "test.lock")
84
85 with lock:
86 assert lock.is_locked
87 assert isinstance(lock, SoftFileLock)
88
89
90 @NEEDS_FCNTL
91 @pytest.mark.filterwarnings("ignore:flock not supported on this filesystem:UserWarning")
92 @pytest.mark.usefixtures("unsupported_flock")
93 def test_fallback_writes_pid_and_hostname(tmp_path: Path) -> None: # pragma: needs fcntl
94 lock_path = tmp_path / "test.lock"
95
96 with UnixFileLock(lock_path):
97 lines = lock_path.read_text(encoding="utf-8").splitlines()
98 expected = [str(os.getpid()), socket.gethostname()]
99 if (token := process_start_token(os.getpid())) is not None: # pragma: no branch # CI always exposes a start time
100 expected.append(str(token))
101 assert lines == expected
102
103
104 @NEEDS_FCNTL
105 @pytest.mark.filterwarnings("ignore:flock not supported on this filesystem:UserWarning")
106 @pytest.mark.usefixtures("unsupported_flock")
107 def test_fallback_release_unlinks_file(tmp_path: Path) -> None: # pragma: needs fcntl
108 lock_path = tmp_path / "test.lock"
109 lock = UnixFileLock(lock_path)
110
111 lock.acquire()
112 assert lock_path.exists()
113 lock.release()
114 assert not lock_path.exists()
115
116
117 @NEEDS_FCNTL
118 @pytest.mark.filterwarnings("ignore:flock not supported on this filesystem:UserWarning") # pragma: needs fcntl
119 def test_fallback_subsequent_acquire_skips_flock(tmp_path: Path, unsupported_flock: MagicMock) -> None:
120 lock = UnixFileLock(tmp_path / "test.lock")
121
122 lock.acquire()
123 lock.release()
124 unsupported_flock.reset_mock()
125
126 lock.acquire()
127 lock.release()
128 unsupported_flock.assert_not_called()
129
130
131 @NEEDS_FCNTL
132 @pytest.mark.filterwarnings("ignore:flock not supported on this filesystem:UserWarning")
133 @pytest.mark.usefixtures("unsupported_flock")
134 def test_fallback_reentrant_locking(tmp_path: Path) -> None: # pragma: needs fcntl
135 lock = UnixFileLock(tmp_path / "test.lock")
136
137 with lock:
138 with lock:
139 assert lock.is_locked
140 assert lock.is_locked
141 assert not lock.is_locked
142
143
144 @NEEDS_FCNTL
145 def test_release_suppresses_eio_on_close(tmp_path: Path, mocker: MockerFixture) -> None: # pragma: needs fcntl
146 lock = UnixFileLock(tmp_path / "test.lock")
147 lock.acquire()
148
149 real_close = os.close # capture before the patch so the fd still closes for real
150 fd_to_fail = lock._context.lock_file_fd # _release() nulls this before closing, so read it now
151
152 def _close_eio(fd: int) -> None:
153 real_close(fd)
154 if fd == fd_to_fail: # pragma: no branch # only the lock's own descriptor closes while the patch is live
155 raise OSError(EIO, "Input/output error")
156
157 mocker.patch("filelock._unix.os.close", side_effect=_close_eio)
158 lock.release()
159 assert not lock.is_locked
160
161
162 @NEEDS_FCNTL # pragma: needs fcntl
163 def test_acquire_flock_error_clears_pending_descriptor(tmp_path: Path, mocker: MockerFixture) -> None:
164 lock = UnixFileLock(tmp_path / "test.lock")
165 mocker.patch(
166 "filelock._unix.fcntl.flock",
167 side_effect=[OSError(EIO, "Input/output error"), None, None],
168 )
169
170 with pytest.raises(OSError, match="Input/output error"):
171 lock.acquire(timeout=0)
172 assert not lock.is_locked
173
174 lock.acquire(timeout=0)
175 assert lock.is_locked
176 lock.release()
177 assert not lock.is_locked
178
179
180 @pytest.fixture
181 def unsupported_flock(mocker: MockerFixture) -> MagicMock: # pragma: needs fcntl
182 return mocker.patch("filelock._unix.fcntl.flock", side_effect=OSError(ENOSYS, "Function not implemented"))