Skip to content

Commit 000a3fa

Browse files
nefrobgaborbernat
andauthored
Raise error on incompatible singleton timeout and mode args (#320)
Co-authored-by: Bernát Gábor <[email protected]>
1 parent 312fb4e commit 000a3fa

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/filelock/_api.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,8 @@ class BaseFileLock(ABC, contextlib.ContextDecorator):
8282
def __new__( # noqa: PLR0913
8383
cls,
8484
lock_file: str | os.PathLike[str],
85-
timeout: float = -1, # noqa: ARG003
86-
mode: int = 0o644, # noqa: ARG003
85+
timeout: float = -1,
86+
mode: int = 0o644,
8787
thread_local: bool = True, # noqa: ARG003, FBT001, FBT002
8888
*,
8989
is_singleton: bool = False,
@@ -97,6 +97,9 @@ def __new__( # noqa: PLR0913
9797
if not instance:
9898
instance = super().__new__(cls)
9999
cls._instances[str(lock_file)] = instance
100+
elif timeout != instance.timeout or mode != instance.mode:
101+
msg = "Singleton lock instances cannot be initialized with differing arguments"
102+
raise ValueError(msg)
100103

101104
return instance # type: ignore[return-value] # https://github.com/python/mypy/issues/15322
102105

@@ -174,6 +177,11 @@ def timeout(self, value: float | str) -> None:
174177
"""
175178
self._context.timeout = float(value)
176179

180+
@property
181+
def mode(self) -> int:
182+
""":return: the file permissions for the lockfile"""
183+
return self._context.mode
184+
177185
@abstractmethod
178186
def _acquire(self) -> None:
179187
"""If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""

tests/test_filelock.py

+11
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,17 @@ def test_singleton_locks_are_distinct_per_lock_file(lock_type: type[BaseFileLock
676676
assert lock_1 is not lock_2
677677

678678

679+
@pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
680+
def test_singleton_locks_must_be_initialized_with_the_same_args(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
681+
lock_path = tmp_path / "a"
682+
lock = lock_type(str(lock_path), is_singleton=True) # noqa: F841
683+
684+
with pytest.raises(ValueError, match="Singleton lock instances cannot be initialized with differing arguments"):
685+
lock_type(str(lock_path), timeout=10, is_singleton=True)
686+
with pytest.raises(ValueError, match="Singleton lock instances cannot be initialized with differing arguments"):
687+
lock_type(str(lock_path), mode=0, is_singleton=True)
688+
689+
679690
@pytest.mark.skipif(hasattr(sys, "pypy_version_info"), reason="del() does not trigger GC in PyPy")
680691
@pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
681692
def test_singleton_locks_are_deleted_when_no_external_references_exist(

0 commit comments

Comments
 (0)