File: test_immutabledict.py

package info (click to toggle)
python-immutabledict 4.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 248 kB
  • sloc: python: 359; makefile: 30
file content (289 lines) | stat: -rw-r--r-- 9,941 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
import pickle
import platform
from io import BytesIO
from typing import Any, Dict, Union

import pytest

from immutabledict import ImmutableOrderedDict, immutabledict


class TestImmutableDict:
    def test_covariance(self) -> None:
        """Not a real unit test, but test covariance
        as mypy runs on the tests.
        """

        class Base:
            pass

        class One(Base):
            pass

        class Two(Base):
            pass

        # Value test
        my_dict: immutabledict[str, Union[Base, One]] = immutabledict()
        second_dict: immutabledict[str, Two] = immutabledict({"t": Two()})
        my_dict = second_dict
        assert my_dict == second_dict

    def test_new_init_methods(self) -> None:
        assert "__new__" in immutabledict.__dict__
        assert "__init__" not in immutabledict.__dict__

    def test_cannot_assign_value(self) -> None:
        with pytest.raises(AttributeError):
            immutabledict().setitem("key", "value")  # type: ignore

    def test_from_keys(self) -> None:
        keys = ["a", "b", "c"]
        immutable_dict: immutabledict[str, Any] = immutabledict.fromkeys(keys)
        assert "a" in immutable_dict
        assert "b" in immutable_dict
        assert "c" in immutable_dict

    def test_init_and_compare(self) -> None:
        normal_dict = {"a": "value", "b": "other_value"}
        immutable_dict: immutabledict[str, str] = immutabledict(normal_dict)
        assert immutable_dict == normal_dict

    def test_get_existing(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict({"a": "value"})
        assert immutable_dict["a"] == "value"

    def test_get_not_existing(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict({"a": "value"})
        with pytest.raises(KeyError):
            immutable_dict["b"]

    def test_contains(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict({"a": "value"})
        assert "a" in immutable_dict

    def test_contains_not_existing(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict({"a": "value"})
        assert "b" not in immutable_dict

    def test_copy(self) -> None:
        original: immutabledict[str, str] = immutabledict({"a": "value"})
        copy = original.copy()
        assert original == copy
        assert id(original) != id(copy)

    def test_iter(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict(
            {"a": "value", "b": "other_value"}
        )
        itered_keys = set(immutable_dict)
        assert immutable_dict.keys() == itered_keys

    def test_len(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict(
            {"a": "value", "b": "other_value"}
        )
        assert len(immutable_dict) == 2

    def test_len_empty(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict({})
        assert len(immutable_dict) == 0

    def test_repr(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict(
            {"a": "value", "b": "other_value"}
        )
        repr_ret = repr(immutable_dict)
        assert repr_ret.startswith("immutabledict")
        assert repr_ret.endswith(")")

    def test_repr_should_eval(self) -> None:
        immutable_dict: immutabledict[str, str] = immutabledict(
            {"a": "value", "b": "other_value"}
        )
        eval_ret = eval(repr(immutable_dict))  # noqa: S307
        assert immutable_dict == eval_ret

    def test_hash(self) -> None:
        first_dict: immutabledict[str, str] = immutabledict(
            {"a": "value", "b": "other_value"}
        )
        second_dict: immutabledict[str, str] = immutabledict(
            {"a": "value", "b": "other_value"}
        )

        assert hash(first_dict) == hash(second_dict)

    def test_union_operator_merge(self) -> None:
        first_dict: immutabledict[str, str] = immutabledict({"a": "a", "b": "b"})
        second_dict: immutabledict[str, str] = immutabledict({"a": "A", "c": "c"})
        merged_dict = first_dict | second_dict
        assert isinstance(merged_dict, immutabledict)
        assert merged_dict == {
            "a": "A",
            "b": "b",
            "c": "c",
        }
        assert first_dict == {"a": "a", "b": "b"}
        assert second_dict == {"a": "A", "c": "c"}

    def test_union_operator_merge_with_dict_first(self) -> None:
        first_dict: Dict[str, str] = dict({"a": "a", "b": "b"})
        second_dict: immutabledict[str, str] = immutabledict({"a": "A", "c": "c"})
        merged_dict = first_dict | second_dict
        assert isinstance(merged_dict, dict)
        assert merged_dict == {
            "a": "A",
            "b": "b",
            "c": "c",
        }
        assert first_dict == {"a": "a", "b": "b"}
        assert second_dict == {"a": "A", "c": "c"}

    def test_union_operator_merge_with_dict_second(self) -> None:
        first_dict: immutabledict[str, str] = immutabledict({"a": "a", "b": "b"})
        second_dict: Dict[str, str] = dict({"a": "A", "c": "c"})
        merged_dict = first_dict | second_dict
        assert isinstance(merged_dict, immutabledict)
        assert merged_dict == {
            "a": "A",
            "b": "b",
            "c": "c",
        }
        assert first_dict == {"a": "a", "b": "b"}
        assert second_dict == {"a": "A", "c": "c"}

    def test_union_operator_merge_fail(self) -> None:
        first_dict: immutabledict[str, str] = immutabledict({"a": "a", "b": "b"})

        with pytest.raises(TypeError):
            first_dict | 0  # type: ignore

        with pytest.raises(TypeError):
            0 | first_dict  # type: ignore

    def test_union_operator_update(self) -> None:
        first_dict: immutabledict[str, str] = immutabledict({"a": "a", "b": "b"})
        second_dict: immutabledict[str, str] = immutabledict({"a": "A", "c": "c"})

        with pytest.raises(TypeError):
            first_dict |= second_dict

    def test_union_operator_update_with_dict_first(self) -> None:
        first_dict: Dict[str, str] = dict({"a": "a", "b": "b"})
        second_dict: immutabledict[str, str] = immutabledict({"a": "A", "c": "c"})

        first_dict |= second_dict
        assert isinstance(first_dict, dict)
        assert first_dict == {
            "a": "A",
            "b": "b",
            "c": "c",
        }
        assert second_dict == {"a": "A", "c": "c"}

    def test_union_operator_update_with_dict_second(self) -> None:
        first_dict: immutabledict[str, str] = immutabledict({"a": "a", "b": "b"})
        second_dict: Dict[str, str] = dict({"a": "A", "c": "c"})

        with pytest.raises(TypeError):
            first_dict |= second_dict
        assert isinstance(first_dict, immutabledict)
        assert first_dict == {"a": "a", "b": "b"}
        assert second_dict == {"a": "A", "c": "c"}

    @pytest.mark.skipif(
        platform.python_implementation() == "PyPy",
        reason="Performance is just checked against CPython",
    )
    @pytest.mark.parametrize(
        "statement",
        [
            "for k, v in d.items(): s += 1",
            "for v in d.values(): s += 1",
            "for k in d.keys(): s += 1",
        ],
    )
    def test_performance(self, statement: str) -> None:
        from timeit import timeit

        time_standard = timeit(
            statement,
            number=3,
            setup="s=0; d = {i:i for i in range(1000000)}",
        )

        time_immutable = timeit(
            statement,
            globals=globals(),
            number=3,
            setup="s=0; d = immutabledict({i:i for i in range(1000000)})",
        )

        assert time_immutable < 1.4 * time_standard

    def test_set_delete_update(self) -> None:
        d: immutabledict[str, int] = immutabledict(a=1, b=2)

        assert d.set("a", 10) == immutabledict(a=10, b=2) == dict(a=10, b=2)
        assert d.delete("a") == immutabledict(b=2) == dict(b=2)

        with pytest.raises(KeyError):
            d.delete("c")

        assert d.update({"a": 3}) == immutabledict(a=3, b=2) == dict(a=3, b=2)

        assert (
            d.update({"c": 17}) == immutabledict(a=1, b=2, c=17) == dict(a=1, b=2, c=17)
        )

        # Make sure d doesn't change
        assert d == immutabledict(a=1, b=2) == dict(a=1, b=2)

    def test_discard(self) -> None:
        d: immutabledict[str, int] = immutabledict(a=1, b=2)

        # Key present
        assert d.discard("a") == immutabledict(b=2) == {"b": 2}
        assert hash(d.discard("a")) != hash(d)

        # Key not present
        assert d.discard("c") == d == {"a": 1, "b": 2}
        assert hash(d.discard("c")) == hash(d)
        assert d.discard("c") is d

    def test_new_kwargs(self) -> None:
        immutable_dict: immutabledict[str, int] = immutabledict(a=1, b=2)
        assert immutable_dict == {"a": 1, "b": 2} == dict(a=1, b=2)

    def test_reduce(self) -> None:
        my_dict: immutabledict[str, int] = immutabledict(a=1, b=2)
        reduce_cls, reduce_args = my_dict.__reduce__()

        assert reduce_cls == immutabledict
        assert reduce_args == (my_dict._dict,)

    def test_pickle(self) -> None:
        my_dict: immutabledict[str, int] = immutabledict(a=1, b=2)
        bytes_io = BytesIO()
        pickle.dump(my_dict, bytes_io)
        bytes_io.seek(0)

        from_pickle_dict = pickle.loads(bytes_io.getvalue())  # noqa: S301

        assert my_dict == from_pickle_dict


class TestImmutableOrderedDict:
    def test_ordered(self) -> None:
        ordered: ImmutableOrderedDict[str, str] = ImmutableOrderedDict(
            {
                "a": "1",
                "b": "2",
                "c": "3",
            }
        )  # type: ignore
        itered_keys = list(ordered)
        assert itered_keys[0] == "a"
        assert itered_keys[1] == "b"
        assert itered_keys[2] == "c"