File size: 2,201 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import os

import pytest

from free_claude_code.core import interprocess_lock


@pytest.mark.parametrize("stage", ["acquire", "wait"])
@pytest.mark.parametrize("error_type", [PermissionError, KeyboardInterrupt])
def test_failed_acquisition_closes_handle_and_allows_retry(
    tmp_path, monkeypatch, stage, error_type
):
    lock = interprocess_lock.InterprocessFileLock(tmp_path / "lock")
    opened = []
    failure = error_type("acquisition interrupted")

    def try_lock(handle):
        opened.append(handle)
        if stage == "acquire":
            raise failure
        return False

    def sleep(_):
        raise failure

    try:
        with monkeypatch.context() as patch:
            patch.setattr(interprocess_lock, "_try_lock", try_lock)
            patch.setattr(interprocess_lock.time, "sleep", sleep)
            with pytest.raises(error_type) as caught:
                lock.acquire(wait=stage == "wait")
            assert caught.value is failure
            assert opened[0].closed
        assert lock.acquire()
    finally:
        lock.release()
        for handle in opened:
            handle.close()


def test_empty_file_locked_by_another_handle_is_normal_contention(
    tmp_path, monkeypatch
):
    if os.name != "nt":
        pytest.skip("Windows byte-range locking")

    import msvcrt

    path = tmp_path / "lock"
    contender = interprocess_lock.InterprocessFileLock(path)
    opened = []
    try_lock = interprocess_lock._try_lock

    def capture(handle):
        opened.append(handle)
        return try_lock(handle)

    monkeypatch.setattr(interprocess_lock, "_try_lock", capture)
    with path.open("a+b") as holder:
        # Windows supports locks beyond EOF. Hold byte zero without writing it.
        msvcrt.locking(holder.fileno(), msvcrt.LK_NBLCK, 1)
        try:
            assert contender.acquire() is False
            assert opened[0].closed
        finally:
            msvcrt.locking(holder.fileno(), msvcrt.LK_UNLCK, 1)
            contender.release()
            for handle in opened:
                handle.close()
    try:
        assert contender.acquire()
        assert path.stat().st_size == 0
    finally:
        contender.release()