filelock 4.2.6__tar.gz → 4.2.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. {filelock-4.2.6 → filelock-4.2.8}/PKG-INFO +3 -1
  2. {filelock-4.2.6 → filelock-4.2.8}/docs/changelog.rst +31 -0
  3. {filelock-4.2.6 → filelock-4.2.8}/docs/how-to.rst +12 -7
  4. {filelock-4.2.6 → filelock-4.2.8}/pyproject.toml +7 -6
  5. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_descriptor.py +8 -4
  6. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_lease.py +4 -5
  7. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/version.py +2 -2
  8. {filelock-4.2.6 → filelock-4.2.8}/tests/soft_rw/test_soft_rw_sync.py +16 -5
  9. {filelock-4.2.6 → filelock-4.2.8}/tests/test_filelock.py +24 -15
  10. {filelock-4.2.6 → filelock-4.2.8}/tests/test_marker_records.py +19 -2
  11. {filelock-4.2.6 → filelock-4.2.8}/tests/test_read_write_unit.py +7 -1
  12. {filelock-4.2.6 → filelock-4.2.8}/tests/test_soft_lease.py +15 -2
  13. {filelock-4.2.6 → filelock-4.2.8}/tests/test_soft_stale.py +14 -2
  14. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft_failures.py +37 -12
  15. {filelock-4.2.6 → filelock-4.2.8}/.gitignore +0 -0
  16. {filelock-4.2.6 → filelock-4.2.8}/LICENSE +0 -0
  17. {filelock-4.2.6 → filelock-4.2.8}/docs/_static/custom.css +0 -0
  18. {filelock-4.2.6 → filelock-4.2.8}/docs/api.rst +0 -0
  19. {filelock-4.2.6 → filelock-4.2.8}/docs/concepts.rst +0 -0
  20. {filelock-4.2.6 → filelock-4.2.8}/docs/conf.py +0 -0
  21. {filelock-4.2.6 → filelock-4.2.8}/docs/example.gif +0 -0
  22. {filelock-4.2.6 → filelock-4.2.8}/docs/index.rst +0 -0
  23. {filelock-4.2.6 → filelock-4.2.8}/docs/license.rst +0 -0
  24. {filelock-4.2.6 → filelock-4.2.8}/docs/logo.svg +0 -0
  25. {filelock-4.2.6 → filelock-4.2.8}/docs/tutorials.rst +0 -0
  26. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/__init__.py +0 -0
  27. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_api.py +0 -0
  28. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_async.py +0 -0
  29. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_async_read_write.py +0 -0
  30. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_error.py +0 -0
  31. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_identity.py +0 -0
  32. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_marker.py +0 -0
  33. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_read_write.py +0 -0
  34. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft.py +0 -0
  35. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft_protocol.py +0 -0
  36. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft_rw/__init__.py +0 -0
  37. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft_rw/_async.py +0 -0
  38. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft_rw/_protocol.py +0 -0
  39. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft_rw/_storage.py +0 -0
  40. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_soft_rw/_sync.py +0 -0
  41. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_strict.py +0 -0
  42. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_unix.py +0 -0
  43. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_util.py +0 -0
  44. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/_windows.py +0 -0
  45. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/asyncio.py +0 -0
  46. {filelock-4.2.6 → filelock-4.2.8}/src/filelock/py.typed +0 -0
  47. {filelock-4.2.6 → filelock-4.2.8}/tasks/benchmark.py +0 -0
  48. {filelock-4.2.6 → filelock-4.2.8}/tasks/capabilities.py +0 -0
  49. {filelock-4.2.6 → filelock-4.2.8}/tasks/capability/assert_fallback.py +0 -0
  50. {filelock-4.2.6 → filelock-4.2.8}/tasks/capability/sitecustomize.py +0 -0
  51. {filelock-4.2.6 → filelock-4.2.8}/tasks/coverage_pragmas.py +0 -0
  52. {filelock-4.2.6 → filelock-4.2.8}/tasks/deny_symlink.py +0 -0
  53. {filelock-4.2.6 → filelock-4.2.8}/tasks/termux/Dockerfile +0 -0
  54. {filelock-4.2.6 → filelock-4.2.8}/tasks/verify_filesystem.py +0 -0
  55. {filelock-4.2.6 → filelock-4.2.8}/tests/async_filelock_cancellation_helpers.py +0 -0
  56. {filelock-4.2.6 → filelock-4.2.8}/tests/capability_marks.py +0 -0
  57. {filelock-4.2.6 → filelock-4.2.8}/tests/conftest.py +0 -0
  58. {filelock-4.2.6 → filelock-4.2.8}/tests/descriptor_helpers.py +0 -0
  59. {filelock-4.2.6 → filelock-4.2.8}/tests/fork_helpers.py +0 -0
  60. {filelock-4.2.6 → filelock-4.2.8}/tests/pid_namespace_helpers.py +0 -0
  61. {filelock-4.2.6 → filelock-4.2.8}/tests/process_helpers.py +0 -0
  62. {filelock-4.2.6 → filelock-4.2.8}/tests/read_write_helpers.py +0 -0
  63. {filelock-4.2.6 → filelock-4.2.8}/tests/soft_rw/conftest.py +0 -0
  64. {filelock-4.2.6 → filelock-4.2.8}/tests/soft_rw/test_soft_rw_async.py +0 -0
  65. {filelock-4.2.6 → filelock-4.2.8}/tests/soft_rw/test_soft_rw_protocol.py +0 -0
  66. {filelock-4.2.6 → filelock-4.2.8}/tests/soft_rw/test_soft_rw_storage.py +0 -0
  67. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_filelock.py +0 -0
  68. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_filelock_acquire_cancellation.py +0 -0
  69. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_filelock_release_cancellation.py +0 -0
  70. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_filelock_rollback_agnostic.py +0 -0
  71. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_filelock_runner_shutdown.py +0 -0
  72. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_filelock_transition_admission.py +0 -0
  73. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_read_write.py +0 -0
  74. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_read_write_cancel_wait.py +0 -0
  75. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_read_write_cancellation.py +0 -0
  76. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_read_write_worker_ownership.py +0 -0
  77. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_soft_contracts.py +0 -0
  78. {filelock-4.2.6 → filelock-4.2.8}/tests/test_async_transition_gate.py +0 -0
  79. {filelock-4.2.6 → filelock-4.2.8}/tests/test_default_mode.py +0 -0
  80. {filelock-4.2.6 → filelock-4.2.8}/tests/test_descriptor_helpers.py +0 -0
  81. {filelock-4.2.6 → filelock-4.2.8}/tests/test_error.py +0 -0
  82. {filelock-4.2.6 → filelock-4.2.8}/tests/test_fork_backends.py +0 -0
  83. {filelock-4.2.6 → filelock-4.2.8}/tests/test_fork_coordination.py +0 -0
  84. {filelock-4.2.6 → filelock-4.2.8}/tests/test_fork_ownership.py +0 -0
  85. {filelock-4.2.6 → filelock-4.2.8}/tests/test_fork_registries.py +0 -0
  86. {filelock-4.2.6 → filelock-4.2.8}/tests/test_host_name_grammar.py +0 -0
  87. {filelock-4.2.6 → filelock-4.2.8}/tests/test_lazy_import.py +0 -0
  88. {filelock-4.2.6 → filelock-4.2.8}/tests/test_lifetime_validation.py +0 -0
  89. {filelock-4.2.6 → filelock-4.2.8}/tests/test_lock_expiry.py +0 -0
  90. {filelock-4.2.6 → filelock-4.2.8}/tests/test_process_identity.py +0 -0
  91. {filelock-4.2.6 → filelock-4.2.8}/tests/test_read_write.py +0 -0
  92. {filelock-4.2.6 → filelock-4.2.8}/tests/test_read_write_fork.py +0 -0
  93. {filelock-4.2.6 → filelock-4.2.8}/tests/test_read_write_private_link.py +0 -0
  94. {filelock-4.2.6 → filelock-4.2.8}/tests/test_soft_lifetime_warning.py +0 -0
  95. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft.py +0 -0
  96. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft_compat.py +0 -0
  97. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft_paths.py +0 -0
  98. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft_races.py +0 -0
  99. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft_recovery.py +0 -0
  100. {filelock-4.2.6 → filelock-4.2.8}/tests/test_strict_soft_stress.py +0 -0
  101. {filelock-4.2.6 → filelock-4.2.8}/tests/test_subclass_options.py +0 -0
  102. {filelock-4.2.6 → filelock-4.2.8}/tests/test_unix_fallback.py +0 -0
  103. {filelock-4.2.6 → filelock-4.2.8}/tests/test_util.py +0 -0
  104. {filelock-4.2.6 → filelock-4.2.8}/tests/test_virtualenv.py +0 -0
  105. {filelock-4.2.6 → filelock-4.2.8}/tox.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: filelock
3
- Version: 4.2.6
3
+ Version: 4.2.8
4
4
  Import-Name: filelock
5
5
  Summary: A platform independent file lock.
6
6
  Project-URL: Changelog, https://py-filelock.readthedocs.io/en/latest/changelog.html
@@ -34,5 +34,7 @@ Description-Content-Type: text/markdown
34
34
  [![Documentation status](https://readthedocs.org/projects/py-filelock/badge/?version=latest)](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
35
35
  [![Downloads](https://static.pepy.tech/badge/filelock/month)](https://pepy.tech/project/filelock)
36
36
  [![check](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml/badge.svg)](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml)
37
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/tox-dev/filelock/badge)](https://scorecard.dev/viewer/?uri=github.com/tox-dev/filelock)
38
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/16250/badge)](https://www.bestpractices.dev/projects/16250)
37
39
 
38
40
  For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).
@@ -6,6 +6,37 @@
6
6
 
7
7
  .. towncrier release notes start
8
8
 
9
+ .. _release-4-2-8:
10
+
11
+ ********************
12
+ 4.2.8 (2026-11-04)
13
+ ********************
14
+
15
+ .. _release-4-2-8-documentation:
16
+
17
+ Documentation
18
+ =============
19
+
20
+ - Clarify the platform-specific locking primitive and range used by descriptor locks, and correct the guidance on
21
+ interoperating with byte-range lock protocols such as conda's repodata lock (:pr:`905`) by :user:`boyfeiyu`.
22
+
23
+ .. _release-4-2-7:
24
+
25
+ ********************
26
+ 4.2.7 (2026-11-02)
27
+ ********************
28
+
29
+ .. _release-4-2-7-fixed:
30
+
31
+ Fixed
32
+ =====
33
+
34
+ - A :class:`~filelock.SoftFileLease` reclaims a dead holder's lease marker even when that holder published another
35
+ ``lease_duration``. It used to raise :class:`~filelock.LeaseSettingsMismatch` on every attempt instead, so after a
36
+ holder crashed and its peers restarted with a changed duration the lock stayed wedged until :meth:`force_break()
37
+ <filelock.MarkerSoftFileLock.force_break>`. A live holder with another duration still raises (:pr:`900`) by
38
+ :user:`dxbjavid` and :user:`gaborbernat`.
39
+
9
40
  .. _release-4-2-6:
10
41
 
11
42
  ********************
@@ -1526,9 +1526,12 @@ would drop the callback without telling you. See :ref:`how-to:Fail closed instea
1526
1526
  *******************************************
1527
1527
 
1528
1528
  :func:`lock_descriptor <filelock.lock_descriptor>` and :func:`unlock_descriptor <filelock.unlock_descriptor>` take and
1529
- release the same one-byte native lock :class:`FileLock <filelock.FileLock>` uses, but on a file descriptor you opened
1529
+ release the same native lock :class:`FileLock <filelock.FileLock>` uses, but on a file descriptor you opened
1530
1530
  and own. They add no path handling: no open, truncate, close, unlink, chmod, canonicalize, or fallback. A descriptor
1531
- lock and a ``FileLock`` path lock on the same file contend with each other.
1531
+ lock and a native ``FileLock`` path lock on the same file contend with each other.
1532
+
1533
+ On Unix this is a whole-file :func:`fcntl.flock` lock. On Windows it is a ``LockFileEx`` lock of one byte at offset 0.
1534
+ Neither function accepts an offset or length, and seeking the descriptor does not change the locked range.
1532
1535
 
1533
1536
  .. code-block:: python
1534
1537
 
@@ -1551,11 +1554,13 @@ Blocking calls require a positive ``poll_interval`` of at most :data:`threading.
1551
1554
  wrapper. Run it in an executor, or drive ``blocking=False`` from your own polling loop. On Windows *fd* must be a
1552
1555
  synchronous descriptor.
1553
1556
 
1554
- This is the tool for interoperating with a lock protocol you did not define. `conda
1555
- <https://github.com/conda/conda>`_ locks a specific byte of its repodata state file rather than a sidecar path, because
1556
- the byte offset is an agreed constant that ``mamba`` also implements: the lock is part of a cross-tool contract, so the
1557
- pathname conventions of ``FileLock`` would put it on the wrong rendezvous. When the protocol names a descriptor and an
1558
- offset, take the descriptor.
1557
+ To interoperate with another tool, all participants must agree on the file, locking primitive, range, and protocol.
1558
+ For example, `conda's repodata lock
1559
+ <https://github.com/conda/conda/blob/main/conda/gateways/disk/lock.py>`_ locks one byte at offset 21 using
1560
+ :func:`fcntl.lockf` on Unix or :func:`msvcrt.locking` on Windows. ``lock_descriptor`` is not a portable replacement for
1561
+ that protocol: the Windows ranges do not overlap, and Unix ``flock`` and ``lockf`` are different primitives whose
1562
+ interaction depends on the operating system and filesystem. Use the primitive and range required by the existing
1563
+ protocol; sharing a file descriptor alone does not establish compatibility.
1559
1564
 
1560
1565
  Both functions raise ``OSError`` with :data:`errno.ENOSYS` when the Python build lacks the native locking primitive.
1561
1566
  The :class:`FileLock <filelock.FileLock>` and :class:`AsyncFileLock <filelock.AsyncFileLock>` aliases continue to select
@@ -104,19 +104,19 @@ pkg-meta = [
104
104
  ]
105
105
  release = [
106
106
  "prek>=0.5",
107
- "release-creator>=4.1",
107
+ "release-creator>=4.4",
108
108
  "towncrier>=26.9",
109
109
  ]
110
110
  release-news = [
111
- "release-creator>=4.1",
111
+ "release-creator>=4.4",
112
112
  "towncrier>=26.9",
113
113
  ]
114
114
  release-notes = [
115
- "release-creator>=4.1",
115
+ "release-creator>=4.4",
116
116
  ]
117
117
  release-prepare = [
118
118
  "prek>=0.5",
119
- "release-creator>=4.1",
119
+ "release-creator>=4.4",
120
120
  "towncrier>=26.9",
121
121
  ]
122
122
 
@@ -316,5 +316,6 @@ uploaded-prior-to = "P7D"
316
316
  decision-order = "stable"
317
317
  matrix.python = ">=3.15,<3.16"
318
318
  matrix.platforms = [ "linux_x86_64" ]
319
- # temporary, delete after 2026-11-02
320
- packages.release-creator.uploaded-prior-to = 2026-10-26T18:24:46Z
319
+ # release-creator 4.4.0 needs a seven-day cutoff exception through 2026-11-09.
320
+ # expires 2026-11-09
321
+ packages.release-creator.uploaded-prior-to = 2026-11-02T21:45:00Z
@@ -21,10 +21,14 @@ def lock_descriptor(fd: int, *, blocking: bool = True, poll_interval: float = 0.
21
21
  """
22
22
  Take the native OS lock on *fd*, a file descriptor the caller opened and owns.
23
23
 
24
- This is the same one-byte exclusive lock :class:`FileLock` uses, so a descriptor lock and a path lock on the same
25
- file contend with each other. Unlike :class:`FileLock` it adds no path handling: it never opens, truncates, closes,
26
- unlinks, chmods, canonicalizes, or falls back. The caller owns *fd* before, during, and after the call, and must
27
- close it. On Windows *fd* must be a synchronous descriptor (its handle not opened with ``FILE_FLAG_OVERLAPPED``).
24
+ This is the same exclusive lock the native :class:`FileLock` backend uses: a whole-file :func:`fcntl.flock` lock
25
+ on Unix, or a ``LockFileEx`` lock of one byte at offset 0 on Windows. A descriptor lock and a native path lock on
26
+ the same file contend with each other. There are no offset or length parameters; seeking *fd* does not change
27
+ the locked range. Interoperating with another tool requires agreement on the locking primitive, range, and protocol.
28
+
29
+ Unlike :class:`FileLock` it adds no path handling: it never opens, truncates, closes, unlinks, chmods,
30
+ canonicalizes, or falls back. The caller owns *fd* before, during, and after the call, and must close it.
31
+ On Windows *fd* must be a synchronous descriptor (its handle not opened with ``FILE_FLAG_OVERLAPPED``).
28
32
 
29
33
  For timeout, reentrancy, singleton, lifetime, or stale-break behavior, use :class:`FileLock`. There is no async
30
34
  wrapper. Run this in an executor, or drive ``blocking=False`` from your own polling loop.
@@ -261,6 +261,10 @@ class SoftFileLease(MarkerSoftFileLock):
261
261
  owner, marker = peer
262
262
  if pinned not in {None, marker.st_ino}: # pragma: win32 no cover # Windows pins nothing
263
263
  return # replaced before the read, so nothing keeps the number read from reuse
264
+ # Duration governs age-based expiry; a dead owner has no lease left to disagree with.
265
+ if owner.mode != "unknown" and owner_is_stale(owner.pid, owner.hostname, owner.start):
266
+ self._take_over(marker, owner.pid)
267
+ return
264
268
  # Only a peer that published a lease agreed to be superseded by age; an exclusive owner is reclaimed only once
265
269
  # it is provably dead, and a contract this version does not know never is. Raise the mismatch outside the read
266
270
  # so the suppression cannot swallow it.
@@ -270,11 +274,6 @@ class SoftFileLease(MarkerSoftFileLock):
270
274
  f"{self._lease_duration!r}s; every contender for a path must agree on lease_duration"
271
275
  )
272
276
  raise LeaseSettingsMismatch(msg)
273
- # A dead or recycled owner is reclaimed at once, whether it held a lease or an exclusive marker; a live lease
274
- # owner whose marker stops being refreshed is superseded on the schedule every contender agreed to.
275
- if owner.mode != "unknown" and owner_is_stale(owner.pid, owner.hostname, owner.start):
276
- self._take_over(marker, owner.pid)
277
- return
278
277
  if owner.mode == "lease" and self._marker_unchanged_for(marker) >= self._lease_duration:
279
278
  self._take_over(marker, None)
280
279
 
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '4.2.6'
22
- __version_tuple__ = version_tuple = (4, 2, 6)
21
+ __version__ = version = '4.2.8'
22
+ __version_tuple__ = version_tuple = (4, 2, 8)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -14,6 +14,7 @@ from errno import EIO
14
14
  from functools import partial
15
15
  from multiprocessing import Event, Process
16
16
  from pathlib import Path
17
+ from types import SimpleNamespace
17
18
  from typing import TYPE_CHECKING, Any, Final, Literal
18
19
 
19
20
  import pytest
@@ -942,11 +943,10 @@ def test_writer_evicted_while_draining_queues_behind_its_evictor(
942
943
  reader = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
943
944
  reader.acquire_read(timeout=2)
944
945
  writer = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
945
- real_sleep = time.sleep
946
946
  swapped = threading.Event()
947
947
  peer: list[str] = []
948
948
 
949
- def hook(seconds: float) -> None: # ruff:ignore[unused-function-argument] # replaces time.sleep; the duration is irrelevant to the swap
949
+ def hook(_seconds: float) -> None:
950
950
  if swapped.is_set():
951
951
  raise Timeout(lock_file)
952
952
  swapped.set()
@@ -959,14 +959,18 @@ def test_writer_evicted_while_draining_queues_behind_its_evictor(
959
959
  assert log.commit(Snapshot(generation=latest.generation + 1, writer=peer[0], readers=frozenset()))
960
960
  reader.release()
961
961
 
962
- monkeypatch.setattr(sync_mod.time, "sleep", hook)
962
+ monkeypatch.setattr(
963
+ sync_mod,
964
+ "time",
965
+ SimpleNamespace(monotonic=time.monotonic, perf_counter=time.perf_counter, sleep=hook),
966
+ )
963
967
  try:
964
968
  with pytest.raises(Timeout):
965
969
  writer.acquire_write(timeout=30)
966
970
  assert swapped.is_set()
967
971
  assert _state(lock_file).writer == peer[0]
968
972
  finally:
969
- monkeypatch.setattr(sync_mod.time, "sleep", real_sleep)
973
+ monkeypatch.setattr(sync_mod, "time", time)
970
974
  writer.close()
971
975
  reader.close()
972
976
 
@@ -1749,7 +1753,14 @@ def test_contention_obeys_acquisition_policy(
1749
1753
  assert 0 < seconds <= timeout
1750
1754
  real_sleep(seconds)
1751
1755
 
1752
- mocker.patch("time.sleep", autospec=True, side_effect=sleep)
1756
+ mocker.patch(
1757
+ "filelock._soft_rw._sync.time",
1758
+ new=SimpleNamespace(
1759
+ monotonic=time.monotonic,
1760
+ perf_counter=time.perf_counter,
1761
+ sleep=mocker.create_autospec(time.sleep, side_effect=sleep),
1762
+ ),
1763
+ )
1753
1764
  with closing(SoftReadWriteLock(lock_file, timeout=timeout, blocking=blocking, poll_interval=10)) as lock:
1754
1765
  acquire: Final = lock.acquire_read if mode == "read" else lock.acquire_write
1755
1766
  with pytest.raises(Timeout) as caught:
@@ -25,7 +25,7 @@ from pathlib import Path, PurePath
25
25
  from pkgutil import resolve_name
26
26
  from queue import Queue
27
27
  from stat import S_IMODE, S_IWGRP, S_IWOTH, S_IWUSR, filemode
28
- from types import CodeType, FrameType, TracebackType
28
+ from types import CodeType, FrameType, SimpleNamespace, TracebackType
29
29
  from typing import TYPE_CHECKING, Any, Final, Literal, cast, get_args
30
30
  from uuid import uuid4
31
31
  from weakref import WeakValueDictionary
@@ -64,6 +64,7 @@ from tests.process_helpers import call_within
64
64
 
65
65
  if TYPE_CHECKING:
66
66
  from collections.abc import Callable, Generator, Iterator
67
+ from unittest.mock import Mock
67
68
 
68
69
  from _typeshed import Unused
69
70
  from pytest_mock import MockerFixture
@@ -729,48 +730,52 @@ def test_default_poll_interval(lock_type: type[BaseFileLock], tmp_path: Path) ->
729
730
 
730
731
 
731
732
  @pytest.fixture
732
- def steady_clock(mocker: MockerFixture) -> None:
733
+ def steady_clock(mocker: MockerFixture) -> Mock:
733
734
  # These tests assert the sleep the lock asked for. The lock caps that sleep at the time left before its timeout, so
734
735
  # a stall on a loaded machine between the start and the first poll would shorten it. A clock that advances 10 ms
735
736
  # per reading keeps the first poll inside the timeout regardless of load.
736
- mocker.patch("filelock._api.time.perf_counter", side_effect=(reading / 100 for reading in count()))
737
+ sleep_mock: Final = mocker.create_autospec(time.sleep)
738
+ mocker.patch(
739
+ "filelock._api.time",
740
+ new=SimpleNamespace(
741
+ perf_counter=mocker.create_autospec(time.perf_counter, side_effect=(reading / 100 for reading in count())),
742
+ sleep=sleep_mock,
743
+ ),
744
+ )
745
+ return sleep_mock
737
746
 
738
747
 
739
- @pytest.mark.usefixtures("steady_clock")
740
748
  @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
741
749
  def test_poll_interval_used_by_context_manager(
742
- lock_type: type[BaseFileLock], tmp_path: Path, mocker: MockerFixture
750
+ lock_type: type[BaseFileLock], tmp_path: Path, steady_clock: Mock
743
751
  ) -> None:
744
752
  lock_path = tmp_path / "a"
745
753
  lock_1 = lock_type(str(lock_path))
746
754
  lock_2 = lock_type(str(lock_path), timeout=0.2, poll_interval=0.05)
747
755
 
748
756
  lock_1.acquire()
749
- sleep_mock = mocker.patch("filelock._api.time.sleep")
750
757
  with pytest.raises(Timeout):
751
758
  lock_2.acquire()
752
- sleep_mock.assert_any_call(0.05)
759
+ steady_clock.assert_any_call(0.05)
753
760
 
754
- sleep_mock.reset_mock()
761
+ steady_clock.reset_mock()
755
762
  lock_2.poll_interval = 0.1
756
763
  with pytest.raises(Timeout):
757
764
  lock_2.acquire()
758
- sleep_mock.assert_any_call(0.1)
765
+ steady_clock.assert_any_call(0.1)
759
766
  lock_1.release()
760
767
 
761
768
 
762
- @pytest.mark.usefixtures("steady_clock")
763
769
  @pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
764
- def test_poll_interval_acquire_override(lock_type: type[BaseFileLock], tmp_path: Path, mocker: MockerFixture) -> None:
770
+ def test_poll_interval_acquire_override(lock_type: type[BaseFileLock], tmp_path: Path, steady_clock: Mock) -> None:
765
771
  lock_path = tmp_path / "a"
766
772
  lock_1 = lock_type(str(lock_path))
767
773
  lock_2 = lock_type(str(lock_path), timeout=0.2, poll_interval=0.05)
768
774
 
769
775
  lock_1.acquire()
770
- sleep_mock = mocker.patch("filelock._api.time.sleep")
771
776
  with pytest.raises(Timeout):
772
777
  lock_2.acquire(poll_interval=0.15)
773
- sleep_mock.assert_any_call(0.15)
778
+ steady_clock.assert_any_call(0.15)
774
779
  lock_1.release()
775
780
 
776
781
 
@@ -1969,7 +1974,10 @@ def test_cancel_check_after_n_polls(lock_type: type[BaseFileLock], tmp_path: Pat
1969
1974
  call_count += 1
1970
1975
  return call_count >= 2
1971
1976
 
1972
- mocker.patch("filelock._api.time.sleep")
1977
+ mocker.patch(
1978
+ "filelock._api.time",
1979
+ new=SimpleNamespace(perf_counter=time.perf_counter, sleep=mocker.create_autospec(time.sleep)),
1980
+ )
1973
1981
  with pytest.raises(Timeout):
1974
1982
  lock_2.acquire(timeout=10, cancel_check=cancel_after_two)
1975
1983
  assert call_count == 2
@@ -3536,7 +3544,8 @@ def test_lock_descriptor_blocking_retries_until_free(
3536
3544
  assert lock_descriptor(holder, blocking=False) is True
3537
3545
  # Drive the real blocking loop: the first attempt sees contention, the mocked sleep frees the holder, and the
3538
3546
  # second attempt wins. Only the clock is mocked, so a single sleep call proves exactly one retry happened.
3539
- sleep = mocker.patch("filelock._descriptor.time.sleep", side_effect=lambda _: unlock_descriptor(holder))
3547
+ sleep: Final = mocker.create_autospec(time.sleep, side_effect=lambda _: unlock_descriptor(holder))
3548
+ mocker.patch("filelock._descriptor.time", new=SimpleNamespace(sleep=sleep))
3540
3549
  try:
3541
3550
  assert lock_descriptor(fd, blocking=True, poll_interval=poll_interval) is True
3542
3551
  sleep.assert_called_once_with(poll_interval)
@@ -5,6 +5,7 @@ import os
5
5
  import time
6
6
  from contextlib import suppress
7
7
  from multiprocessing import get_context
8
+ from types import SimpleNamespace
8
9
  from typing import TYPE_CHECKING, Final
9
10
 
10
11
  import pytest
@@ -166,7 +167,15 @@ def test_lease_never_ages_out_an_unknown_contract(tmp_path: Path) -> None:
166
167
  @NEEDS_STALE_RECLAIM
167
168
  def test_lease_ages_out_a_malformed_record(tmp_path: Path, mocker: MockerFixture) -> None:
168
169
  # The self-heal still applies to a record that states no contract at all, so corruption cannot wedge contenders.
169
- mocker.patch("filelock._soft.time.monotonic", side_effect=itertools.count(step=MALFORMED_LOCK_AGE_THRESHOLD))
170
+ mocker.patch(
171
+ "filelock._soft.time",
172
+ new=SimpleNamespace(
173
+ monotonic=mocker.create_autospec(
174
+ time.monotonic, side_effect=itertools.count(step=MALFORMED_LOCK_AGE_THRESHOLD)
175
+ ),
176
+ sleep=time.sleep,
177
+ ),
178
+ )
170
179
  marker = tmp_path / "a.lock"
171
180
  marker.write_text("filelock/2\nnot-a-record\n", encoding="utf-8")
172
181
 
@@ -286,7 +295,15 @@ def test_marker_lock_reclaims_dead_owner_before_its_process_is_closed(marker: Pa
286
295
  )
287
296
  @NEEDS_STALE_RECLAIM
288
297
  def test_marker_lock_reclaims_malformed_record(marker: Path, record: str, mocker: MockerFixture) -> None:
289
- mocker.patch("filelock._soft.time.monotonic", side_effect=itertools.count(step=MALFORMED_LOCK_AGE_THRESHOLD))
298
+ mocker.patch(
299
+ "filelock._soft.time",
300
+ new=SimpleNamespace(
301
+ monotonic=mocker.create_autospec(
302
+ time.monotonic, side_effect=itertools.count(step=MALFORMED_LOCK_AGE_THRESHOLD)
303
+ ),
304
+ sleep=time.sleep,
305
+ ),
306
+ )
290
307
  marker.write_text(record, encoding="utf-8")
291
308
  lock = MarkerSoftFileLock(marker)
292
309
  _acquire_after_reclaim(lock)
@@ -9,6 +9,7 @@ import time
9
9
  from concurrent.futures import ThreadPoolExecutor
10
10
  from contextlib import ExitStack, closing
11
11
  from functools import partial
12
+ from types import SimpleNamespace
12
13
  from typing import TYPE_CHECKING, Final, Literal
13
14
 
14
15
  import pytest
@@ -679,7 +680,12 @@ def test_busy_timeout_recomputed_after_journal_mode(
679
680
  lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"]
680
681
  ) -> None:
681
682
  counter = iter([0.0, 0.0, 0.0, 0.5])
682
- mocker.patch("filelock._read_write.time.perf_counter", side_effect=counter)
683
+ mocker.patch(
684
+ "filelock._read_write.time",
685
+ new=SimpleNamespace(
686
+ monotonic=time.monotonic, perf_counter=mocker.create_autospec(time.perf_counter, side_effect=counter)
687
+ ),
688
+ )
683
689
  lock = ReadWriteLock(lock_file, is_singleton=False)
684
690
  (lock.acquire_read if mode == "read" else lock.acquire_write)(timeout=2.0)
685
691
  lock.release()
@@ -226,6 +226,7 @@ def test_lease_self_heals_a_malformed_marker(marker: Path, mocker: MockerFixture
226
226
  "contract",
227
227
  [
228
228
  pytest.param(f"mode=lease\ntoken=abc\nduration={_DURATION!r}\n", id="lease"),
229
+ pytest.param(f"mode=lease\ntoken=abc\nduration={_DURATION * 3!r}\n", id="lease-other-duration"),
229
230
  pytest.param("mode=exclusive\n", id="exclusive"),
230
231
  ],
231
232
  )
@@ -700,7 +701,13 @@ def test_lease_supersedes_a_live_holder_once_its_claim_ages_out(marker: Path, mo
700
701
  # lease_duration without a refresh. Windows cannot delete a live holder's open marker, so drive the age branch with
701
702
  # a non-stale owner and a clock that steps a full duration per look rather than a real second process.
702
703
  mocker.patch("filelock._lease.owner_is_stale", return_value=False)
703
- mocker.patch("filelock._soft.time.monotonic", side_effect=itertools.count(step=_DURATION))
704
+ mocker.patch(
705
+ "filelock._soft.time",
706
+ new=SimpleNamespace(
707
+ monotonic=mocker.create_autospec(time.monotonic, side_effect=itertools.count(step=_DURATION)),
708
+ sleep=time.sleep,
709
+ ),
710
+ )
704
711
  marker.write_text(
705
712
  f"filelock/2\npid={os.getpid()}\nhost={host_name()}\nmode=lease\ntoken=stalled\nduration={_DURATION!r}\n",
706
713
  encoding="utf-8",
@@ -838,7 +845,13 @@ def test_native_lock_rejects_a_lease_duration(marker: Path) -> None:
838
845
  def test_lease_does_not_age_out_a_live_exclusive_owner(marker: Path, mocker: MockerFixture) -> None:
839
846
  # An exclusive owner never agreed to expire, so only proof of death may reclaim it, however long it sits unchanged.
840
847
  mocker.patch("filelock._lease.owner_is_stale", return_value=False)
841
- mocker.patch("filelock._soft.time.monotonic", side_effect=itertools.count(step=_DURATION))
848
+ mocker.patch(
849
+ "filelock._soft.time",
850
+ new=SimpleNamespace(
851
+ monotonic=mocker.create_autospec(time.monotonic, side_effect=itertools.count(step=_DURATION)),
852
+ sleep=time.sleep,
853
+ ),
854
+ )
842
855
  marker.write_text(f"filelock/2\npid={os.getpid()}\nhost={socket.gethostname()}\nmode=exclusive\n", encoding="utf-8")
843
856
 
844
857
  with pytest.raises(Timeout):
@@ -11,6 +11,7 @@ from contextlib import contextmanager, suppress
11
11
  from errno import EACCES, EINTR, EINVAL, EIO, ENODEV, ENOSPC, EPERM
12
12
  from multiprocessing import get_context
13
13
  from pathlib import Path
14
+ from types import SimpleNamespace
14
15
  from typing import TYPE_CHECKING, Final
15
16
 
16
17
  import pytest
@@ -1822,7 +1823,10 @@ def test_soft_windows_unlink_gives_up_after_every_attempt_is_denied(tmp_path: Pa
1822
1823
  marker = tmp_path / "a"
1823
1824
  marker.write_text("x", encoding="utf-8")
1824
1825
  lock = SoftFileLock(marker)
1825
- mocker.patch("filelock._soft.time.sleep")
1826
+ mocker.patch(
1827
+ "filelock._soft.time",
1828
+ new=SimpleNamespace(monotonic=time.monotonic, sleep=mocker.create_autospec(time.sleep)),
1829
+ )
1826
1830
  unlink: Final = mocker.patch("filelock._soft.unlink_path", side_effect=PermissionError(EACCES, "handle still open"))
1827
1831
 
1828
1832
  lock._windows_unlink_if_ours(_file_identity(os.lstat(marker)))
@@ -1838,7 +1842,15 @@ def test_soft_windows_unlink_gives_up_after_every_attempt_is_denied(tmp_path: Pa
1838
1842
  def unchanged_past_grace(mocker: MockerFixture) -> None:
1839
1843
  # Each look at the marker lands a full grace window after the previous one on the observer's clock, so an unchanged
1840
1844
  # malformed marker ages out on the second look without the test sleeping through the window.
1841
- mocker.patch("filelock._soft.time.monotonic", side_effect=itertools.count(step=MALFORMED_LOCK_AGE_THRESHOLD))
1845
+ mocker.patch(
1846
+ "filelock._soft.time",
1847
+ new=SimpleNamespace(
1848
+ monotonic=mocker.create_autospec(
1849
+ time.monotonic, side_effect=itertools.count(step=MALFORMED_LOCK_AGE_THRESHOLD)
1850
+ ),
1851
+ sleep=time.sleep,
1852
+ ),
1853
+ )
1842
1854
 
1843
1855
 
1844
1856
  def test_unparseable_lock_with_an_ancient_mtime_not_evicted_on_first_sight(lock_path: Path) -> None:
@@ -13,6 +13,7 @@ import threading
13
13
  import time
14
14
  from errno import EACCES, EEXIST, EIO, ENOENT, ENOSPC, ESTALE, EXDEV
15
15
  from pathlib import Path
16
+ from types import SimpleNamespace
16
17
  from typing import TYPE_CHECKING, Final, NoReturn
17
18
 
18
19
  import pytest
@@ -527,7 +528,8 @@ def test_strict_soft_reaper_does_not_retry_sharing_error(
527
528
  real_unlink(path, dir_fd=dir_fd)
528
529
 
529
530
  unlink = mocker.patch("filelock._strict.os.unlink", autospec=True, side_effect=deny_abandoned_record)
530
- sleep = mocker.patch("filelock._strict.time.sleep", autospec=True)
531
+ sleep: Final = mocker.create_autospec(time.sleep)
532
+ _patch_strict_clock(mocker, sleep=sleep)
531
533
  # A contender blocked by a foreign claim ages the record out in its scan without removing a claim of its own.
532
534
  _write_foreign_claim(Path(f"{lock_path}.filelock") / "claims", "f" * 32)
533
535
 
@@ -549,7 +551,7 @@ def test_strict_soft_reaper_ages_records_by_filesystem_clock(
549
551
  private_path = tmp_path / f".{lock_path.name}{_PRIVATE_RECORD_MARKER}{'0' * 32}.tmp"
550
552
  private_path.write_bytes(b"in-flight publication")
551
553
  # A client clock an hour ahead of the filesystem's would read the fresh record as abandoned.
552
- mocker.patch("filelock._strict.time.time", return_value=time.time() + 3600)
554
+ _patch_strict_clock(mocker, wall=lambda: time.time() + 3600)
553
555
 
554
556
  with StrictSoftFileLock(lock_path, timeout=0):
555
557
  assert private_path.read_bytes() == b"in-flight publication"
@@ -919,7 +921,7 @@ def test_strict_soft_unparsable_lock_path_raises_once_unchanged(
919
921
  ) -> None:
920
922
  lock_path = tmp_path / "resource.lock"
921
923
  lock_path.write_bytes(content)
922
- mocker.patch("filelock._strict.time.monotonic", autospec=True, side_effect=[0.0, 2.0])
924
+ _patch_strict_clock(mocker, monotonic=mocker.create_autospec(time.monotonic, side_effect=[0.0, 2.0]))
923
925
  lock = StrictSoftFileLock(lock_path, poll_interval=0)
924
926
 
925
927
  with pytest.raises(SoftFileLockProtocolError, match="marker it can parse, unchanged for 2 seconds"):
@@ -954,7 +956,8 @@ def test_strict_soft_exited_soft_lock_owner_raises_without_waiting(tmp_path: Pat
954
956
  ).stdout.strip()
955
957
  lock_path.write_text(f"{pid}\n{host_name()}\n", encoding="ascii")
956
958
  found = f"a soft-lock marker left by pid {pid} on {host_name()}, which has exited"
957
- sleep = mocker.patch("filelock._strict.time.sleep", autospec=True)
959
+ sleep: Final = mocker.create_autospec(time.sleep)
960
+ _patch_strict_clock(mocker, sleep=sleep)
958
961
  lock = StrictSoftFileLock(lock_path)
959
962
 
960
963
  with pytest.raises(SoftFileLockProtocolError, match=re.escape(f"found {found}")):
@@ -1024,7 +1027,9 @@ def test_strict_soft_sentinel_vanishing_before_open_is_republished(lock_path: Pa
1024
1027
  def test_strict_soft_rides_out_a_transient_non_sentinel(tmp_path: Path, mocker: MockerFixture) -> None:
1025
1028
  lock_path = tmp_path / "resource.lock"
1026
1029
  lock_path.mkdir()
1027
- mocker.patch("filelock._strict.time.sleep", autospec=True, side_effect=lambda _seconds: lock_path.rmdir())
1030
+ _patch_strict_clock(
1031
+ mocker, sleep=mocker.create_autospec(time.sleep, side_effect=lambda _seconds: lock_path.rmdir())
1032
+ )
1028
1033
 
1029
1034
  with StrictSoftFileLock(lock_path, timeout=0) as lock:
1030
1035
  assert lock.is_locked
@@ -2007,8 +2012,11 @@ def test_strict_soft_denied_claim_rechecks_directory(tmp_path: Path, mocker: Moc
2007
2012
  claim.unlink()
2008
2013
  return now
2009
2014
 
2010
- mocker.patch("filelock._strict.time.monotonic", autospec=True, side_effect=tick)
2011
- mocker.patch("filelock._strict.time.sleep", autospec=True)
2015
+ _patch_strict_clock(
2016
+ mocker,
2017
+ monotonic=mocker.create_autospec(time.monotonic, side_effect=tick),
2018
+ sleep=mocker.create_autospec(time.sleep),
2019
+ )
2012
2020
  _open_raising_for(claim, PermissionError(EACCES, "sharing violation"), mocker)
2013
2021
 
2014
2022
  if vanished:
@@ -2048,8 +2056,11 @@ def test_strict_soft_claims_removed_one_by_one_share_one_read_grace(tmp_path: Pa
2048
2056
  raise PermissionError(EACCES, "claim read denied")
2049
2057
  return real_open(path, flags, mode, dir_fd=dir_fd) # pragma: needs dir-fd
2050
2058
 
2051
- mocker.patch("filelock._strict.time.monotonic", autospec=True, side_effect=lambda: now)
2052
- mocker.patch("filelock._strict.time.sleep", autospec=True, side_effect=tick)
2059
+ _patch_strict_clock(
2060
+ mocker,
2061
+ monotonic=mocker.create_autospec(time.monotonic, side_effect=lambda: now),
2062
+ sleep=mocker.create_autospec(time.sleep, side_effect=tick),
2063
+ )
2053
2064
  _route_claim_opens_through_os_open(mocker)
2054
2065
  mocker.patch("filelock._strict.os.open", autospec=True, side_effect=deny_claims)
2055
2066
 
@@ -2202,8 +2213,11 @@ def test_strict_soft_claims_recheck_after_a_denied_claim_creates_no_file(tmp_pat
2202
2213
  claim: Final = _write_held_claim(Path(f"{lock_path}.filelock") / "claims")
2203
2214
  (private_path := _private_claim_path(lock_path, "0" * 32)).write_bytes(b"abandoned")
2204
2215
  os.utime(private_path, (0, 0))
2205
- mocker.patch("filelock._strict.time.monotonic", autospec=True, side_effect=[0, 1])
2206
- mocker.patch("filelock._strict.time.sleep", autospec=True)
2216
+ _patch_strict_clock(
2217
+ mocker,
2218
+ monotonic=mocker.create_autospec(time.monotonic, side_effect=[0, 1]),
2219
+ sleep=mocker.create_autospec(time.sleep),
2220
+ )
2207
2221
  opened: Final = _open_raising_for(claim, PermissionError(EACCES, "sharing violation"), mocker)
2208
2222
 
2209
2223
  with pytest.raises(SoftFileLockProtocolError, match="cannot read claim"):
@@ -2366,7 +2380,8 @@ def test_strict_soft_release_rides_out_a_transient_unlink_denial(lock_path: Path
2366
2380
  real_unlink(path, dir_fd=dir_fd)
2367
2381
 
2368
2382
  mocker.patch("filelock._strict.os.unlink", side_effect=deny_once)
2369
- sleep: Final = mocker.patch("filelock._strict.time.sleep", autospec=True)
2383
+ sleep: Final = mocker.create_autospec(time.sleep)
2384
+ _patch_strict_clock(mocker, sleep=sleep)
2370
2385
  lock.release()
2371
2386
 
2372
2387
  assert (len(denied), sleep.call_args_list, lock.claims) == (1, [mocker.call(0.001)], ())
@@ -2376,3 +2391,13 @@ def _write_foreign_claim(claims: Path, token: str, state: str = "held") -> Path:
2376
2391
  claim = claims / f"{state}-v1-{token}.claim"
2377
2392
  claim.write_bytes(b"filelock-strict-v1\n" + token.encode() + f"\n{os.getpid()}\n686f7374\n4242\n".encode())
2378
2393
  return claim
2394
+
2395
+
2396
+ def _patch_strict_clock(
2397
+ mocker: MockerFixture,
2398
+ *,
2399
+ monotonic: Callable[[], float] = time.monotonic,
2400
+ sleep: Callable[[float], None] = time.sleep,
2401
+ wall: Callable[[], float] = time.time,
2402
+ ) -> None:
2403
+ mocker.patch("filelock._strict.time", new=SimpleNamespace(monotonic=monotonic, sleep=sleep, time=wall))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes