File: test_objects.py

package info (click to toggle)
kombu 5.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,968 kB
  • sloc: python: 28,815; makefile: 318
file content (85 lines) | stat: -rw-r--r-- 2,091 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
from __future__ import annotations

from unittest import mock

from kombu.utils.objects import cached_property


class test_cached_property:

    def test_deleting(self):

        class X:
            xx = False

            @cached_property
            def foo(self):
                return 42

            @foo.deleter
            def foo(self, value):
                self.xx = value

        x = X()
        del x.foo
        assert not x.xx
        x.__dict__['foo'] = 'here'
        del x.foo
        assert x.xx == 'here'

    def test_when_access_from_class(self):

        class X:
            xx = None

            @cached_property
            def foo(self):
                return 42

            @foo.setter
            def foo(self, value):
                self.xx = 10

        desc = X.__dict__['foo']
        assert X.foo is desc

        assert desc.__get__(None) is desc
        assert desc.__set__(None, 1) is desc
        assert desc.__delete__(None) is desc
        assert desc.setter(1)

        x = X()
        x.foo = 30
        assert x.xx == 10

        del x.foo

    def test_locks_on_access(self):

        class X:
            @cached_property
            def foo(self):
                return 42

        x = X()

        # Getting the value acquires the lock, and may do so recursively
        # on Python < 3.12 because the superclass acquires it.
        with mock.patch.object(X.foo, 'lock') as mock_lock:
            assert x.foo == 42
        mock_lock.__enter__.assert_called()
        mock_lock.__exit__.assert_called()

        # Setting a value also acquires the lock.
        with mock.patch.object(X.foo, 'lock') as mock_lock:
            x.foo = 314
        assert x.foo == 314
        mock_lock.__enter__.assert_called_once()
        mock_lock.__exit__.assert_called_once()

        # .. as does clearing the cached value to recompute it.
        with mock.patch.object(X.foo, 'lock') as mock_lock:
            del x.foo
        assert x.foo == 42
        mock_lock.__enter__.assert_called_once()
        mock_lock.__exit__.assert_called_once()