File: test_lock.py

package info (click to toggle)
python-sherlock 0.4.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 344 kB
  • sloc: python: 2,008; makefile: 162
file content (487 lines) | stat: -rw-r--r-- 17,521 bytes parent folder | download
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
"""
    Tests for all sorts of locks.
"""

import datetime
import pathlib
import tempfile
import unittest
from importlib import reload
from unittest.mock import Mock, patch

import etcd
import kubernetes.client
import kubernetes.client.exceptions

import sherlock


class TestBaseLock(unittest.TestCase):
    def test_init_uses_global_defaults(self):
        sherlock.configure(namespace="new_namespace")
        lock = sherlock.lock.BaseLock("lockname")
        self.assertEqual(lock.namespace, "new_namespace")

    def test_init_does_not_use_global_default_for_client_obj(self):
        client_obj = etcd.Client()
        sherlock.configure(client=client_obj)
        lock = sherlock.lock.BaseLock("lockname")
        self.assertNotEqual(lock.client, client_obj)

    def test__locked_raises_not_implemented_error(self):
        def _test():
            sherlock.lock.BaseLock("")._locked

        self.assertRaises(NotImplementedError, _test)

    def test_locked_raises_not_implemented_error(self):
        self.assertRaises(NotImplementedError, sherlock.lock.BaseLock("").locked)

    def test__acquire_raises_not_implemented_error(self):
        self.assertRaises(NotImplementedError, sherlock.lock.BaseLock("")._acquire)

    def test_acquire_raises_not_implemented_error(self):
        self.assertRaises(NotImplementedError, sherlock.lock.BaseLock("").acquire)

    def test__release_raises_not_implemented_error(self):
        self.assertRaises(NotImplementedError, sherlock.lock.BaseLock("")._release)

    def test_release_raises_not_implemented_error(self):
        self.assertRaises(NotImplementedError, sherlock.lock.BaseLock("").release)

    def test_acquire_acquires_blocking_lock(self):
        lock = sherlock.lock.BaseLock("")
        lock._acquire = Mock(return_value=True)
        self.assertTrue(lock.acquire())

    def test_acquire_acquires_non_blocking_lock(self):
        lock = sherlock.lock.BaseLock("123")
        lock._acquire = Mock(return_value=True)
        self.assertTrue(lock.acquire())

    def test_acquire_obeys_timeout(self):
        lock = sherlock.lock.BaseLock("123", timeout=1)
        lock._acquire = Mock(return_value=False)
        self.assertRaises(sherlock.LockTimeoutException, lock.acquire)

    def test_acquire_obeys_retry_interval(self):
        lock = sherlock.lock.BaseLock("123", timeout=0.5, retry_interval=0.1)
        lock._acquire = Mock(return_value=False)
        try:
            lock.acquire()
        except sherlock.LockTimeoutException:
            pass
        self.assertEqual(lock._acquire.call_count, 6)

    def test_deleting_lock_object_releases_the_lock(self):
        lock = sherlock.lock.BaseLock("123")
        release_func = Mock()
        lock.release = release_func
        del lock
        self.assertTrue(release_func.called)


class TestLock(unittest.TestCase):
    def setUp(self):
        reload(sherlock)
        reload(sherlock.lock)

    def test_lock_does_not_accept_custom_client_object(self):
        self.assertRaises(TypeError, sherlock.lock.Lock, client=None)

    def test_lock_does_not_create_proxy_when_backend_is_not_set(self):
        sherlock._configuration._backend = None
        sherlock._configuration._client = None
        lock = sherlock.lock.Lock("")
        self.assertEqual(lock._lock_proxy, None)

        self.assertRaises(sherlock.lock.LockException, lock.acquire)
        self.assertRaises(sherlock.lock.LockException, lock.release)
        self.assertRaises(sherlock.lock.LockException, lock.locked)

    def test_lock_creates_proxy_when_backend_is_set(self):
        sherlock._configuration.backend = sherlock.backends.ETCD
        lock = sherlock.lock.Lock("")
        self.assertTrue(isinstance(lock._lock_proxy, sherlock.lock.EtcdLock))

    def test_lock_uses_proxys_methods(self):
        sherlock.lock.RedisLock._acquire = Mock(return_value=True)
        sherlock.lock.RedisLock._release = Mock()
        sherlock.lock.RedisLock.locked = Mock(return_value=False)

        sherlock._configuration.backend = sherlock.backends.REDIS
        lock = sherlock.lock.Lock("")

        lock.acquire()
        self.assertTrue(sherlock.lock.RedisLock._acquire.called)

        lock.release()
        self.assertTrue(sherlock.lock.RedisLock._release.called)

        lock.locked()
        self.assertTrue(sherlock.lock.RedisLock.locked.called)

    def test_lock_sets_client_object_on_lock_proxy_when_globally_configured(self):
        client = etcd.Client(host="8.8.8.8")
        sherlock.configure(client=client)
        lock = sherlock.lock.Lock("lock")
        self.assertEqual(lock._lock_proxy.client, client)


class TestRedisLock(unittest.TestCase):
    def setUp(self):
        reload(sherlock)
        reload(sherlock.lock)

    def test_valid_key_names_are_generated_when_namespace_not_set(self):
        name = "lock"
        lock = sherlock.lock.RedisLock(name)
        self.assertEqual(lock._key_name, name)

    def test_valid_key_names_are_generated_when_namespace_is_set(self):
        name = "lock"
        lock = sherlock.lock.RedisLock(name, namespace="local_namespace")
        self.assertEqual(lock._key_name, "local_namespace_%s" % name)

        sherlock.configure(namespace="global_namespace")
        lock = sherlock.lock.RedisLock(name)
        self.assertEqual(lock._key_name, "global_namespace_%s" % name)


class TestEtcdLock(unittest.TestCase):
    def setUp(self):
        reload(sherlock)
        reload(sherlock.lock)

    def test_valid_key_names_are_generated_when_namespace_not_set(self):
        name = "lock"
        lock = sherlock.lock.EtcdLock(name)
        self.assertEqual(lock._key_name, "/" + name)

    def test_valid_key_names_are_generated_when_namespace_is_set(self):
        name = "lock"
        lock = sherlock.lock.EtcdLock(name, namespace="local_namespace")
        self.assertEqual(lock._key_name, "/local_namespace/%s" % name)

        sherlock.configure(namespace="global_namespace")
        lock = sherlock.lock.EtcdLock(name)
        self.assertEqual(lock._key_name, "/global_namespace/%s" % name)


class TestMCLock(unittest.TestCase):
    def setUp(self):
        reload(sherlock)
        reload(sherlock.lock)

    def test_valid_key_names_are_generated_when_namespace_not_set(self):
        name = "lock"
        lock = sherlock.lock.MCLock(name)
        self.assertEqual(lock._key_name, name)

    def test_valid_key_names_are_generated_when_namespace_is_set(self):
        name = "lock"
        lock = sherlock.lock.MCLock(name, namespace="local_namespace")
        self.assertEqual(lock._key_name, "local_namespace_%s" % name)

        sherlock.configure(namespace="global_namespace")
        lock = sherlock.lock.MCLock(name)
        self.assertEqual(lock._key_name, "global_namespace_%s" % name)


class TestKubernetesLock(unittest.TestCase):
    def setUp(self):
        reload(sherlock)
        reload(sherlock.lock)

    def test_valid_key_names_are_generated_when_namespace_not_set(self):
        name = "lock"
        k8s_namespace = "default"
        lock = sherlock.lock.KubernetesLock(name, k8s_namespace, client=Mock())
        self.assertEqual(lock._key_name, name)

    def test_valid_key_names_are_generated_when_namespace_is_set(self):
        name = "lock"
        k8s_namespace = "default"
        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=Mock(),
            namespace="local-namespace",
        )
        self.assertEqual(lock._key_name, "local-namespace-%s" % name)

        sherlock.configure(namespace="global-namespace")
        lock = sherlock.lock.KubernetesLock(name, k8s_namespace, client=Mock())
        self.assertEqual(lock._key_name, "global-namespace-%s" % name)

    def test_exception_raised_when_invalid_names_set(self):
        test_cases = [
            (
                "lock_name",
                "my-k8s-namespace",
                "my-namespace",
                "lock_name must conform to RFC1123's definition of a DNS label for KubernetesLock",  # noqa: disable=501
            ),
            (
                "lock-name",
                "my_k8s_namespace",
                "my-namespace",
                "k8s_namespace must conform to RFC1123's definition of a DNS label for KubernetesLock",  # noqa: disable=501
            ),
            (
                "lock-name",
                "my-k8s-namespace",
                "my_namespace",
                "namespace must conform to RFC1123's definition of a DNS label for KubernetesLock",  # noqa: disable=501
            ),
        ]
        for lock_name, k8s_namespace, namespace, err_msg in test_cases:
            with self.assertRaises(ValueError) as cm:
                sherlock.lock.KubernetesLock(
                    lock_name,
                    k8s_namespace,
                    client=Mock(),
                    namespace=namespace,
                )
            self.assertEqual(cm.exception.args[0], err_msg)

            sherlock.configure(namespace=namespace)
            with self.assertRaises(ValueError) as cm:
                sherlock.lock.KubernetesLock(
                    lock_name,
                    k8s_namespace,
                    client=Mock(),
                    namespace=namespace,
                )
            self.assertEqual(cm.exception.args[0], err_msg)

    @patch("kubernetes.client.CoordinationV1Api")
    def test_acquire_create_race_condition(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        # Mock the client to reproduce the scenario where the Lease
        # does not exist when read but does when created.
        mock_client.read_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Not Found")
        )
        mock_client.create_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Conflict")
        )
        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )
        self.assertFalse(lock._acquire())

    @patch("kubernetes.client.CoordinationV1Api")
    def test_acquire_create_failed(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        # Mock the client to reproduce the scenario where the Lease
        # does not exist and we fail to create it for some other reason.
        mock_client.read_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Not Found")
        )
        mock_client.create_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Not Conflict")
        )
        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )
        self.assertRaisesRegex(
            sherlock.lock.LockException,
            "Failed to create Lock.",
            lock._acquire,
        )

    @patch("kubernetes.client.CoordinationV1Api")
    def test_acquire_get_failed(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        # Mock the client to reproduce the scenario where we fail to read the Lease
        # for some other reason other than it doesn't exist.
        mock_client.read_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Unexpected")
        )
        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )
        self.assertRaisesRegex(
            sherlock.lock.LockException,
            "Failed to read Lock.",
            lock._acquire,
        )

    @patch("kubernetes.client.CoordinationV1Api")
    def test_acquire_replaced_race_condition(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )

        now = lock._now() - datetime.timedelta(seconds=10)
        lease = kubernetes.client.V1Lease(
            metadata=kubernetes.client.V1ObjectMeta(name=name, namespace=k8s_namespace),
            spec=kubernetes.client.V1LeaseSpec(
                acquire_time=now,
                holder_identity="test-identity",
                lease_duration_seconds=1,
                renew_time=now,
            ),
        )

        # Mock the client to reproduce the scenario where we try to acquire
        # the Lock but someone beats us to it.
        mock_client.read_namespaced_lease.return_value = lease
        mock_client.replace_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Conflict")
        )

        self.assertFalse(lock._acquire())

    @patch("kubernetes.client.CoordinationV1Api")
    def test_acquire_replaced_failed(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )

        now = lock._now() - datetime.timedelta(seconds=10)
        lease = kubernetes.client.V1Lease(
            metadata=kubernetes.client.V1ObjectMeta(name=name, namespace=k8s_namespace),
            spec=kubernetes.client.V1LeaseSpec(
                acquire_time=now,
                holder_identity="test-identity",
                lease_duration_seconds=1,
                renew_time=now,
            ),
        )

        # Mock the client to reproduce the scenario where we try to acquire
        # the Lock but fail to replace the Lease for an unexpected reason.
        mock_client.read_namespaced_lease.return_value = lease
        mock_client.replace_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Unexpected")
        )

        self.assertRaisesRegex(
            sherlock.lock.LockException,
            "Failed to update Lock.",
            lock._acquire,
        )

    @patch("kubernetes.client.CoordinationV1Api")
    def test_release_delete_race_condition(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )
        lock._owner = "test-identity"

        now = lock._now() - datetime.timedelta(seconds=10)
        lease = kubernetes.client.V1Lease(
            metadata=kubernetes.client.V1ObjectMeta(name=name, namespace=k8s_namespace),
            spec=kubernetes.client.V1LeaseSpec(
                acquire_time=now,
                holder_identity=lock._owner,
                lease_duration_seconds=1,
                renew_time=now,
            ),
        )

        # Mock the client to reproduce the scenario where we try to release
        # the Lock but someone acquires it before we get a chance.
        mock_client.read_namespaced_lease.return_value = lease
        mock_client.delete_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Not Found")
        )

        # This should return without issue.
        self.assertIsNone(lock.release())

    @patch("kubernetes.client.CoordinationV1Api")
    def test_release_delete_failed(self, mock_client):
        name = "lock"
        k8s_namespace = "default"

        lock = sherlock.lock.KubernetesLock(
            name,
            k8s_namespace,
            client=mock_client,
        )
        lock._owner = "test-identity"

        now = lock._now() - datetime.timedelta(seconds=10)
        lease = kubernetes.client.V1Lease(
            metadata=kubernetes.client.V1ObjectMeta(name=name, namespace=k8s_namespace),
            spec=kubernetes.client.V1LeaseSpec(
                acquire_time=now,
                holder_identity=lock._owner,
                lease_duration_seconds=1,
                renew_time=now,
            ),
        )

        # Mock the client to reproduce the scenario where we try to release
        # the Lock but fail to delete the Lease for an unexpected reason.
        mock_client.read_namespaced_lease.return_value = lease
        mock_client.delete_namespaced_lease.side_effect = (
            kubernetes.client.exceptions.ApiException(reason="Unexpected")
        )

        self.assertRaisesRegex(
            sherlock.lock.LockException,
            "Failed to release Lock.",
            lock.release,
        )


class TestFileLock(unittest.TestCase):
    def setUp(self):
        reload(sherlock)
        reload(sherlock.lock)

    def test_valid_key_names_are_generated_when_namespace_not_set(self):
        name = "lock"

        with tempfile.TemporaryDirectory() as tmpdir:
            lock = sherlock.lock.FileLock(name, client=pathlib.Path(tmpdir))

        self.assertEqual(lock._key_name, name)

    def test_valid_key_names_are_generated_when_namespace_is_set(self):
        name = "lock"

        with tempfile.TemporaryDirectory() as tmpdir:
            lock = sherlock.lock.FileLock(
                name,
                client=pathlib.Path(tmpdir),
                namespace="local_namespace",
            )

        self.assertEqual(lock._key_name, "local_namespace_%s" % name)

        sherlock.configure(namespace="global_namespace")
        with tempfile.TemporaryDirectory() as tmpdir:
            lock = sherlock.lock.FileLock(name, client=pathlib.Path(tmpdir))
        self.assertEqual(lock._key_name, "global_namespace_%s" % name)