File: locket_tests.py

package info (click to toggle)
locket 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 136 kB
  • sloc: python: 449; makefile: 30; sh: 8
file content (315 lines) | stat: -rw-r--r-- 8,300 bytes parent folder | download | duplicates (2)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import functools
import os
import io
import sys
import time
import signal

import pytest
import spur

import locket
from .tempdir import create_temporary_dir


local_shell = spur.LocalShell()


@pytest.fixture(name="lock_path")
def _fixture_lock_path():
    with create_temporary_dir() as temp_dir:
        yield os.path.join(temp_dir, "some-lock")


@pytest.fixture(name="spawn_locker")
def _fixture_spawn_locker():
    lockers = []

    def spawn_locker(*args, **kwargs):
        locker = _Locker(*args, **kwargs)
        lockers.append(locker)
        return locker

    try:
        yield spawn_locker
    finally:
        for locker in lockers:
            locker.terminate()
            locker.wait()


def test_single_process_can_obtain_uncontested_lock(lock_path):
    has_run = False
    with locket.lock_file(lock_path):
        has_run = True

    assert has_run


def test_lock_can_be_acquired_with_timeout_of_zero(lock_path):
    has_run = False
    with locket.lock_file(lock_path, timeout=0):
        has_run = True

    assert has_run


def test_lock_is_released_by_context_manager_exit(lock_path):
    has_run = False

    # Keep a reference to first_lock so it holds onto the lock
    first_lock = locket.lock_file(lock_path, timeout=0)

    with first_lock:
        pass

    with locket.lock_file(lock_path, timeout=0):
        has_run = True

    assert has_run


def test_can_use_acquire_and_release_to_control_lock(lock_path):
    has_run = False
    lock = locket.lock_file(lock_path)
    lock.acquire()
    try:
        has_run = True
    finally:
        lock.release()

    assert has_run


def test_thread_cannot_obtain_lock_using_same_object_twice_without_release(lock_path):
    with locket.lock_file(lock_path, timeout=0) as lock:
        try:
            lock.acquire()
            assert False, "Expected LockError"
        except locket.LockError:
            pass


def test_thread_cannot_obtain_lock_using_same_path_twice_without_release(lock_path):
    with locket.lock_file(lock_path, timeout=0):
        lock = locket.lock_file(lock_path, timeout=0)
        try:
            lock.acquire()
            assert False, "Expected LockError"
        except locket.LockError:
            pass


def test_thread_cannot_obtain_lock_using_same_path_with_different_arguments_without_release(lock_path):
    lock1 = locket.lock_file(lock_path, timeout=None)
    lock2 = locket.lock_file(lock_path, timeout=0)
    lock1.acquire()
    try:
        lock2.acquire()
        assert False, "Expected LockError"
    except locket.LockError:
        pass


def test_calling_release_on_unlocked_lock_raises_lock_error(lock_path):
    lock = locket.lock_file(lock_path)
    try:
        lock.release()
        assert False, "Expected LockError"
    except locket.LockError as error:
        assert str(error) == "cannot release unlocked lock"


def test_the_same_lock_file_object_is_used_for_the_same_path(lock_path):
    # We explicitly check the same lock is used to ensure that the lock isn't
    # re-entrant, even if the underlying platform lock is re-entrant.
    first_lock = locket.lock_file(lock_path, timeout=0)
    second_lock = locket.lock_file(lock_path, timeout=0)
    assert first_lock._lock is second_lock._lock


def test_the_same_lock_file_object_is_used_for_the_same_path_with_different_arguments(lock_path):
    # We explicitly check the same lock is used to ensure that the lock isn't
    # re-entrant, even if the underlying platform lock is re-entrant.
    first_lock = locket.lock_file(lock_path, timeout=None)
    second_lock = locket.lock_file(lock_path, timeout=0)
    assert first_lock._lock is second_lock._lock


def test_different_file_objects_are_used_for_different_paths(lock_path):
    first_lock = locket.lock_file(lock_path, timeout=0)
    second_lock = locket.lock_file(lock_path + "-2", timeout=0)
    assert first_lock._lock is not second_lock._lock


def test_lock_file_blocks_until_lock_is_available(lock_path, spawn_locker):
    locker_1 = spawn_locker(lock_path)
    locker_2 = spawn_locker(lock_path)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.acquire()
    time.sleep(0.1)
    locker_2.acquire()
    time.sleep(0.1)

    assert locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.release()
    time.sleep(0.1)

    assert not locker_1.has_lock()
    assert locker_2.has_lock()

    locker_2.release()
    time.sleep(0.1)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()


def test_lock_is_released_if_holding_process_is_brutally_killed(lock_path, spawn_locker):
    locker_1 = spawn_locker(lock_path)
    locker_2 = spawn_locker(lock_path)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.acquire()
    time.sleep(0.1)
    locker_2.acquire()
    time.sleep(0.1)

    assert locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.terminate()
    time.sleep(0.1)

    assert locker_2.has_lock()
    locker_2.release()


def test_can_set_timeout_to_zero_to_raise_exception_if_lock_cannot_be_acquired(lock_path, spawn_locker):
    locker_1 = spawn_locker(lock_path)
    locker_2 = spawn_locker(lock_path, timeout=0)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.acquire()
    time.sleep(0.1)
    locker_2.acquire()
    time.sleep(0.1)

    assert locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.release()
    time.sleep(0.1)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()
    assert locker_2.has_error()


def test_error_is_raised_after_timeout_has_expired(lock_path, spawn_locker):
    locker_1 = spawn_locker(lock_path)
    locker_2 = spawn_locker(lock_path, timeout=0.5)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.acquire()
    time.sleep(0.1)
    locker_2.acquire()
    time.sleep(0.1)

    assert locker_1.has_lock()
    assert not locker_2.has_lock()
    assert not locker_2.has_error()

    time.sleep(1)

    assert locker_1.has_lock()
    assert not locker_2.has_lock()
    assert locker_2.has_error()

    locker_1.release()


def test_lock_is_acquired_if_available_before_timeout_expires(lock_path, spawn_locker):
    locker_1 = spawn_locker(lock_path)
    locker_2 = spawn_locker(lock_path, timeout=2)

    assert not locker_1.has_lock()
    assert not locker_2.has_lock()

    locker_1.acquire()
    time.sleep(0.1)
    locker_2.acquire()
    time.sleep(0.1)

    assert locker_1.has_lock()
    assert not locker_2.has_lock()
    assert not locker_2.has_error()

    time.sleep(0.5)
    locker_1.release()
    time.sleep(0.1)

    assert not locker_1.has_lock()
    assert locker_2.has_lock()

    locker_2.release()



class _Locker(object):
    def __init__(self, path, timeout=None):
        self._stdout = io.BytesIO()
        self._stderr = io.BytesIO()
        self._process = local_shell.spawn(
            [sys.executable, _locker_script_path, path, str(timeout)],
            stdout=self._stdout,
            stderr=self._stderr,
            allow_error=True,
        )

    def acquire(self):
        self._process.stdin_write(b"\n")

    def release(self):
        self._process.stdin_write(b"\n")

    def wait_for_lock(self):
        start_time = time.time()
        while not self.has_lock():
            if not self._process.is_running():
                raise self._process.wait_for_result().to_error()
            time.sleep(0.1)
            if time.time() - start_time > 1:
                raise RuntimeError("Could not acquire lock, stdout:\n{0}".format(self._stdout.getvalue()))

    def has_lock(self):
        lines = self._stdout_lines()
        return "Acquired" in lines and "Released" not in lines

    def has_error(self):
        return "LockError" in self._stdout_lines()

    def terminate(self):
        pid = int(self._stdout_lines()[0].strip())
        if self._process.is_running():
            os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM))

    def wait(self):
        self._process.wait_for_result()

    def _stdout_lines(self):
        output = self._stdout.getvalue().decode("ascii")
        return [line.strip() for line in output.split("\n")]

_locker_script_path = os.path.join(os.path.dirname(__file__), "locker.py")