Debian Codegraph @

tests/bidict_test_fixtures.py

raw
1 # Copyright 2009-2026 Joshua Bronson. All rights reserved.
2 #
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 from __future__ import annotations
8
9 import operator
10 import pickle
11 import typing as t
12 from collections import OrderedDict
13 from collections import UserDict
14 from collections.abc import Iterable
15 from collections.abc import KeysView
16 from collections.abc import Mapping
17 from collections.abc import MutableMapping
18 from collections.abc import Reversible
19 from dataclasses import dataclass
20 from itertools import chain
21 from itertools import combinations
22
23 from bidict import DROP_NEW
24 from bidict import DROP_OLD
25 from bidict import ON_DUP_DROP_OLD
26 from bidict import RAISE
27 from bidict import BidictBase
28 from bidict import DuplicationError
29 from bidict import KeyAndValueDuplicationError
30 from bidict import KeyDuplicationError
31 from bidict import MutableBidirectionalMapping
32 from bidict import OnDup
33 from bidict import OrderedBidict
34 from bidict import OrderedBidictBase
35 from bidict import ValueDuplicationError
36 from bidict import bidict
37 from bidict import frozenbidict
38 from bidict._typing import Maplike
39 from bidict._typing import MapOrItems
40 from bidict._typing import override
41
42
43 KT = t.TypeVar('KT')
44 VT = t.TypeVar('VT')
45
46
47 class SupportsKeysAndGetItem(t.Generic[KT, VT]):
48 def __init__(self, *args: t.Any, **kw: t.Any) -> None:
49 # This fixture trusts its *args/**kw (typed Any); dict(**kw) yields str keys, so cast to the declared type.
50 self._mapping = t.cast('Mapping[KT, VT]', dict(*args, **kw))
51
52 def keys(self) -> KeysView[KT]:
53 return self._mapping.keys()
54
55 def __getitem__(self, key: KT) -> VT:
56 return self._mapping[key]
57
58
59 BB = BidictBase[KT, VT]
60 BT = type[BidictBase[KT, VT]]
61 user_bidict_types: list[BT[t.Any, t.Any]] = []
62
63 _B = t.TypeVar('_B', bound=BidictBase[t.Any, t.Any])
64 _BT = t.TypeVar('_BT', bound=type[BidictBase[t.Any, t.Any]])
65
66
67 def pickle_copy(b: _B, protocol: int | None = None) -> _B:
68 return pickle.loads(pickle.dumps(b, protocol))
69
70
71 def user_bidict(cls: _BT) -> _BT:
72 # Preserve the exact decorated class type (a plain `BT[KT, VT]` return would widen it to BidictBase).
73 user_bidict_types.append(cls)
74 return cls
75
76
77 @user_bidict
78 class UserBi(bidict[KT, VT]):
79 _fwdm_cls = UserDict
80 _invm_cls = UserDict
81
82
83 @user_bidict
84 class UserOrderedBi(OrderedBidict[KT, VT]):
85 _fwdm_cls = UserDict
86 _invm_cls = UserDict
87
88
89 @user_bidict
90 class UserBiNotOwnInv(bidict[KT, VT]):
91 """A custom bidict whose inverse class is not itself."""
92
93 _fwdm_cls = dict
94 _invm_cls = UserDict
95
96
97 @user_bidict
98 class UserBiBackedByDictSub(bidict[KT, VT]):
99 """A bidict backed by a dict *subclass*, which gets the same native views as a dict."""
100
101 _fwdm_cls = OrderedDict
102 _invm_cls = OrderedDict
103
104
105 @user_bidict
106 class UserOrderedBiBase(OrderedBidictBase[KT, VT]):
107 """An immutable ordered bidict, i.e. an OrderedBidictBase that is not an OrderedBidict.
108
109 Uses a permissive on_dup so that even a bulk __init__ can overwrite an existing item.
110 That is what makes the backing mappings' order diverge from the bidict's own order,
111 which is otherwise only reachable by mutating an OrderedBidict.
112 """
113
114 on_dup = ON_DUP_DROP_OLD
115
116
117 UserBiNotOwnInvInv = UserBiNotOwnInv._inv_cls
118 assert UserBiNotOwnInvInv is not UserBiNotOwnInv
119
120 BTs = tuple[BT[t.Any, t.Any], ...]
121 builtin_bidict_types: BTs = (bidict, frozenbidict, OrderedBidict)
122 bidict_types: BTs = (*builtin_bidict_types, *user_bidict_types)
123 update_arg_types = (*bidict_types, list, dict, iter, SupportsKeysAndGetItem)
124 mutable_bidict_types: BTs = tuple(t for t in bidict_types if issubclass(t, MutableBidirectionalMapping))
125 assert frozenbidict not in mutable_bidict_types
126 MBT = type[bidict[KT, VT]] | type[OrderedBidict[KT, VT]]
127
128
129 def should_be_reversible(bi_t: BT[KT, VT]) -> bool:
130 # Every ordered bidict is reversible regardless of its backing mappings, since it
131 # iterates its linked list rather than them. Any other bidict is reversible exactly
132 # when both its backing mappings are.
133 if bi_t in builtin_bidict_types or issubclass(bi_t, OrderedBidictBase):
134 return True
135 return all(issubclass(i, Reversible) for i in (bi_t._fwdm_cls, bi_t._invm_cls))
136
137
138 assert all(not should_be_reversible(bi_t) or issubclass(bi_t, Reversible) for bi_t in bidict_types)
139
140
141 def powerset(iterable: Iterable[t.Any]) -> Iterable[tuple[t.Any, ...]]:
142 iterable = tuple(iterable)
143 return chain.from_iterable(combinations(iterable, r) for r in range(len(iterable) + 1))
144
145
146 SET_OPS: t.Any = (
147 operator.le,
148 operator.lt,
149 operator.gt,
150 operator.ge,
151 operator.eq,
152 operator.ne,
153 operator.and_,
154 operator.or_,
155 operator.sub,
156 operator.xor,
157 (lambda x, y: x.isdisjoint(y)),
158 )
159
160
161 DEFAULT_ON_DUP = OnDup(DROP_OLD, RAISE)
162
163
164 @dataclass
165 class Oracle(t.Generic[KT, VT]):
166 data: dict[KT, VT]
167 ordered: bool
168
169 @property
170 def data_inv(self) -> dict[VT, KT]:
171 return {v: k for (k, v) in self.data.items()}
172
173 def assert_match(self, bi: BidictBase[KT, VT]) -> None:
174 assert dict(bi) == self.data
175 assert dict(bi.inv) == self.data_inv
176 self.assert_items_match(bi)
177
178 def assert_items_match(self, bi: BidictBase[KT, VT]) -> None:
179 if self.ordered:
180 assert zip_equal(bi.items(), self.data.items())
181 else:
182 assert bi.items() == self.data.items()
183
184 def clear(self) -> None:
185 self.data.clear()
186
187 def pop(self, key: KT) -> VT:
188 return self.data.pop(key)
189
190 def popitem(self, last: bool = True) -> tuple[KT, VT]:
191 if last:
192 return self.data.popitem()
193 key = next(iter(self.data))
194 return key, self.data.pop(key)
195
196 def put(self, key: KT, val: VT, on_dup: OnDup = DEFAULT_ON_DUP) -> None:
197 oldval = self.data.get(key)
198 oldkey = self.data_inv.get(val)
199 isdupkey = oldval is not None
200 isdupval = oldkey is not None
201 if isdupkey and isdupval:
202 if key == oldkey: # (key, val) duplicates an existing item -> no-op
203 assert val == oldval
204 return
205 # key and val each duplicate a different existing item.
206 if on_dup.val is RAISE:
207 raise KeyAndValueDuplicationError(key, val)
208 if on_dup.val is DROP_NEW:
209 return
210 assert on_dup.val is DROP_OLD
211 elif isdupkey:
212 if on_dup.key is RAISE:
213 raise KeyDuplicationError(key)
214 if on_dup.key is DROP_NEW:
215 return
216 assert on_dup.key is DROP_OLD
217 elif isdupval:
218 if on_dup.val is RAISE:
219 raise ValueDuplicationError(val)
220 if on_dup.val is DROP_NEW:
221 return
222 assert on_dup.val is DROP_OLD
223 if not self.ordered:
224 self.data[key] = val
225 self.data.pop(oldkey, None)
226 return
227 # Ensure insertion order is preserved in the case of a sequence of overwriting updates.
228 updated = {}
229 for k, v in self.data.items():
230 if k == oldkey or v == oldval:
231 if k == oldkey and isdupkey and isdupval:
232 continue
233 updated[key] = val
234 else:
235 updated[k] = v
236 updated[key] = val
237 self.data = updated
238
239 def putall(self, updates: MapOrItems[KT, VT], on_dup: OnDup = DEFAULT_ON_DUP) -> None:
240 # https://bidict.readthedocs.io/en/main/basic-usage.html#order-matters
241 tmp = self.data.copy()
242 items: Iterable[tuple[KT, VT]]
243 if isinstance(updates, Mapping):
244 items = t.cast('Mapping[KT, VT]', updates).items()
245 elif isinstance(updates, Maplike):
246 items = [(key, updates[key]) for key in updates.keys()]
247 else:
248 items = updates
249 try:
250 for key, val in items:
251 self.put(key, val, on_dup)
252 except DuplicationError:
253 self.data = tmp # fail clean (no partially-applied updates)
254 raise
255
256 def __ior__(self, other: Mapping[KT, VT]) -> dict[KT, VT]:
257 self.putall(other)
258 return self.data
259
260 def __or__(self, other: Mapping[KT, VT]) -> dict[KT, VT]:
261 before = self.data.copy()
262 self.putall(other)
263 after = self.data
264 self.data = before
265 return after
266
267 def __ror__(self, other: Mapping[KT, VT]) -> dict[KT, VT]:
268 before = self.data.copy()
269 self.data = {}
270 try:
271 self.putall(other)
272 self.putall(before)
273 except DuplicationError:
274 self.data = before
275 raise
276 after = self.data
277 self.data = before
278 return after
279
280 def move_to_end(self, key: KT, last: bool = True) -> None:
281 val = self.pop(key)
282 if last:
283 self.put(key, val)
284 else:
285 self.data = {key: val, **self.data}
286
287
288 def zip_equal(i1: Iterable[t.Any], i2: Iterable[t.Any]) -> bool:
289 return all(map(operator.eq, i1, i2))
290
291
292 def invdict(d: dict[KT, VT]) -> dict[VT, KT]:
293 return {v: k for (k, v) in d.items()}
294
295
296 def dedup(x: MapOrItems[KT, VT]) -> dict[KT, VT]:
297 return invdict(invdict(dict(x)))
298
299
300 @dataclass(frozen=True)
301 class Tagged:
302 """Equal whenever *n* is equal, but each instance is distinguishable by its *tag*.
303
304 Stands in for the realistic case of value-equal objects that carry distinct state,
305 e.g. a dataclass whose __eq__ covers only some of its fields.
306 """
307
308 n: int
309 tag: str = ''
310
311 @override
312 def __eq__(self, other: object) -> bool:
313 return isinstance(other, Tagged) and self.n == other.n
314
315 @override
316 def __hash__(self) -> int:
317 return hash(self.n)
318
319
320 class HashRaises:
321 @override
322 def __hash__(self) -> int:
323 raise RuntimeError('boom!')
324
325
326 bomb = HashRaises()
327
328 BAD_ITEMS = (
329 (RuntimeError, (bomb, 0)), # hashing the key raises
330 (RuntimeError, (0, bomb)), # hashing the value raises
331 (TypeError, (['unhashable'], 0)),
332 (ValueError, (1, 2, 'bad len')),
333 )
334
335
336 class WriteRefused(Exception):
337 """Raised by the backing mappings that :func:`bidict_refusing_nth_write` provides."""
338
339
340 def bidict_refusing_nth_write(bi_t: BT[t.Any, t.Any], init: Mapping[t.Any, t.Any], n: int) -> BB[t.Any, t.Any]:
341 """Return a *bi_t* containing *init* whose nth write from now on raises :class:`WriteRefused`.
342
343 Stands in for a custom bidict's backing mapping that may raise on a write it will not accept,
344 e.g. SortedDict's TypeError when a key is not orderable with the keys already contained.
345
346 Both backing mappings are given the same class, so the count spans them
347 the way a single _write() does.
348 """
349 counting = False
350 counter = iter(range(1, 1000))
351
352 def tick() -> None:
353 if counting and next(counter) == n:
354 raise WriteRefused
355
356 class RefusingDict(UserDict[t.Any, t.Any]):
357 @override
358 def __setitem__(self, key: t.Any, item: t.Any) -> None:
359 tick()
360 super().__setitem__(key, item)
361
362 @override
363 def __delitem__(self, key: t.Any) -> None:
364 tick()
365 super().__delitem__(key)
366
367 @override
368 def popitem(self) -> tuple[t.Any, t.Any]:
369 # Python 3.15 gave UserDict a popitem() of its own that goes straight to self.data,
370 # bypassing __delitem__ and so escaping the count above. Take MutableMapping's
371 # implementation, which removes via __delitem__ on every supported Python.
372 return MutableMapping.popitem(self)
373
374 bi_t_refusing = type(f'Refusing{bi_t.__name__}', (bi_t,), {'_fwdm_cls': RefusingDict, '_invm_cls': RefusingDict})
375 bi = bi_t_refusing(init)
376 counting = True # writing init above must not count
377 return bi