summaryrefslogtreecommitdiffstats
path: root/contrib/python/yarl/tests/test_helpers.py
blob: cdfff129e6d3465db2e1f2e5660eaeff15c9a86c (plain) (blame)
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
import platform

import pytest

from yarl import _helpers, _helpers_py

IS_PYPY = platform.python_implementation() == "PyPy"


class CachedPropertyMixin:
    cached_property = NotImplemented

    def test_cached_property(self) -> None:
        class A:
            def __init__(self):
                self._cache = {}

            @self.cached_property  # type: ignore[misc]
            def prop(self):
                return 1

        a = A()
        assert a.prop == 1

    def test_cached_property_class(self) -> None:
        class A:
            def __init__(self):
                """Init."""
                # self._cache not set because its never accessed in this test

            @self.cached_property  # type: ignore[misc]
            def prop(self):
                """Docstring."""

        assert isinstance(A.prop, self.cached_property)
        assert A.prop.__doc__ == "Docstring."

    def test_cached_property_assignment(self) -> None:
        class A:
            def __init__(self):
                self._cache = {}

            @self.cached_property  # type: ignore[misc]
            def prop(self):
                """Mock property."""

        a = A()

        with pytest.raises(AttributeError):
            a.prop = 123

    def test_cached_property_without_cache(self) -> None:
        class A:
            def __init__(self):
                pass

            @self.cached_property  # type: ignore[misc]
            def prop(self):
                """Mock property."""

        a = A()

        with pytest.raises(AttributeError):
            a.prop = 123

    def test_cached_property_check_without_cache(self) -> None:
        class A:
            def __init__(self):
                pass

            @self.cached_property  # type: ignore[misc]
            def prop(self):
                """Mock property."""

        a = A()
        with pytest.raises(AttributeError):
            assert a.prop == 1


class TestPyCachedProperty(CachedPropertyMixin):
    cached_property = _helpers_py.cached_property  # type: ignore[assignment]


if (
    not _helpers.NO_EXTENSIONS
    and not IS_PYPY
    and hasattr(_helpers, "cached_property_c")
):

    class TestCCachedProperty(CachedPropertyMixin):
        cached_property = _helpers.cached_property_c  # type: ignore[assignment, attr-defined, unused-ignore] # noqa: E501