| 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 |
"""Tests for :mod:`bidict`. |
| 8 |
|
| 9 |
Mainly these are property-based tests implemented via https://hypothesis.works. |
| 10 |
""" |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import gc |
| 15 |
import pickle |
| 16 |
import sys |
| 17 |
import typing as t |
| 18 |
import weakref |
| 19 |
from collections import UserDict |
| 20 |
from collections.abc import Callable |
| 21 |
from collections.abc import Mapping |
| 22 |
from collections.abc import Reversible |
| 23 |
from collections.abc import Sequence |
| 24 |
from copy import copy |
| 25 |
from copy import deepcopy |
| 26 |
from functools import partial |
| 27 |
from functools import reduce |
| 28 |
from itertools import product |
| 29 |
from itertools import starmap |
| 30 |
from random import Random |
| 31 |
from typing import assert_type |
| 32 |
from unittest.mock import ANY |
| 33 |
|
| 34 |
import pytest |
| 35 |
from bidict_test_fixtures import BAD_ITEMS |
| 36 |
from bidict_test_fixtures import BB |
| 37 |
from bidict_test_fixtures import BT |
| 38 |
from bidict_test_fixtures import KT |
| 39 |
from bidict_test_fixtures import MBT |
| 40 |
from bidict_test_fixtures import SET_OPS |
| 41 |
from bidict_test_fixtures import VT |
| 42 |
from bidict_test_fixtures import Oracle |
| 43 |
from bidict_test_fixtures import SupportsKeysAndGetItem |
| 44 |
from bidict_test_fixtures import Tagged |
| 45 |
from bidict_test_fixtures import UserBi |
| 46 |
from bidict_test_fixtures import UserBiBackedByDictSub |
| 47 |
from bidict_test_fixtures import UserBiNotOwnInv |
| 48 |
from bidict_test_fixtures import UserOrderedBi |
| 49 |
from bidict_test_fixtures import UserOrderedBiBase |
| 50 |
from bidict_test_fixtures import WriteRefused |
| 51 |
from bidict_test_fixtures import bidict_refusing_nth_write |
| 52 |
from bidict_test_fixtures import bidict_types |
| 53 |
from bidict_test_fixtures import bomb |
| 54 |
from bidict_test_fixtures import dedup |
| 55 |
from bidict_test_fixtures import invdict |
| 56 |
from bidict_test_fixtures import mutable_bidict_types |
| 57 |
from bidict_test_fixtures import pickle_copy |
| 58 |
from bidict_test_fixtures import powerset |
| 59 |
from bidict_test_fixtures import should_be_reversible |
| 60 |
from bidict_test_fixtures import update_arg_types |
| 61 |
from bidict_test_fixtures import zip_equal |
| 62 |
from hypothesis import assume |
| 63 |
from hypothesis import example |
| 64 |
from hypothesis import given |
| 65 |
from hypothesis import note |
| 66 |
from hypothesis.stateful import RuleBasedStateMachine |
| 67 |
from hypothesis.stateful import initialize |
| 68 |
from hypothesis.stateful import invariant |
| 69 |
from hypothesis.stateful import precondition |
| 70 |
from hypothesis.stateful import rule |
| 71 |
from hypothesis.strategies import booleans |
| 72 |
from hypothesis.strategies import randoms |
| 73 |
from hypothesis.strategies import sampled_from |
| 74 |
from typing_extensions import TypeIs |
| 75 |
|
| 76 |
from bidict import BidictKeysView |
| 77 |
from bidict import BidirectionalMapping |
| 78 |
from bidict import DuplicationError |
| 79 |
from bidict import KeyAndValueDuplicationError |
| 80 |
from bidict import MutableBidict |
| 81 |
from bidict import MutableBidirectionalMapping |
| 82 |
from bidict import OnDup |
| 83 |
from bidict import OnDupAction |
| 84 |
from bidict import OrderedBidict |
| 85 |
from bidict import OrderedBidictBase |
| 86 |
from bidict import ValueDuplicationError |
| 87 |
from bidict import bidict |
| 88 |
from bidict import frozenbidict |
| 89 |
from bidict import inverted |
| 90 |
from bidict._orderedbase import Node as OrderedBidictNode |
| 91 |
from bidict._orderedbase import WeakAttr |
| 92 |
from bidict._typing import MapOrItems |
| 93 |
from bidict._typing import override |
| 94 |
|
| 95 |
|
| 96 |
Items = Sequence[tuple[int, int]] |
| 97 |
Items121 = dict[t.Any, t.Any] |
| 98 |
|
| 99 |
ks = tuple(range(1, 5)) |
| 100 |
vs = tuple(range(-1, -5, -1)) |
| 101 |
keys = sampled_from(ks) |
| 102 |
vals = sampled_from(vs) |
| 103 |
items = sampled_from(list(powerset(product(ks, vs)))) |
| 104 |
items121 = items.map(dedup) |
| 105 |
# Items that can never duplicate anything in a bidict under test: their keys and values are |
| 106 |
# disjoint from ks and vs, and they are 1:1 among themselves. |
| 107 |
fresh_items = sampled_from(list(powerset((k, -k) for k in range(5, 9)))) |
| 108 |
bidict_t = sampled_from(bidict_types) |
| 109 |
mut_bidict_t = sampled_from(mutable_bidict_types) |
| 110 |
updates_t = sampled_from(update_arg_types) |
| 111 |
on_dups = tuple(starmap(OnDup, product(OnDupAction, repeat=2))) |
| 112 |
on_dup = sampled_from(on_dups) |
| 113 |
|
| 114 |
|
| 115 |
def is_ordered(bi: BidirectionalMapping[int, int]) -> TypeIs[OrderedBidict[int, int]]: |
| 116 |
return isinstance(bi, OrderedBidict) |
| 117 |
|
| 118 |
|
| 119 |
class BidictStateMachine(RuleBasedStateMachine): |
| 120 |
bi: MutableBidict[int, int] |
| 121 |
oracle: Oracle[int, int] |
| 122 |
|
| 123 |
@initialize(mut_bidict_t=mut_bidict_t, items121=items121) |
| 124 |
def init(self, mut_bidict_t: type[MutableBidict[int, int]], items121: Items121) -> None: |
| 125 |
self.bi = mut_bidict_t(items121) |
| 126 |
self.oracle = Oracle(items121, ordered=self.is_ordered()) |
| 127 |
|
| 128 |
def is_ordered(self) -> bool: |
| 129 |
return is_ordered(self.bi) |
| 130 |
|
| 131 |
@invariant() |
| 132 |
def assert_match_oracle(self) -> None: |
| 133 |
note(f'> {self.bi=}\n> {self.oracle.data=}') |
| 134 |
self.oracle.assert_match(self.bi) |
| 135 |
|
| 136 |
viewnames = sampled_from(('keys', 'values', 'items')) |
| 137 |
|
| 138 |
# TODO: Try @invariant rather than @rule now that hypothesis is faster / it might not slow down the tests too much. |
| 139 |
@rule(rand=randoms(), viewname=viewnames, set_op=sampled_from(SET_OPS), other_set=items.map(frozenset)) |
| 140 |
def assert_views_match_oracle(self, rand: Random, viewname: str, set_op: t.Any, other_set: t.Any) -> None: |
| 141 |
check = getattr(self.bi, viewname)() |
| 142 |
expect = getattr(self.oracle.data, viewname)() if viewname != 'values' else self.oracle.data_inv.keys() |
| 143 |
assert len(check) == len(expect) |
| 144 |
if self.is_ordered(): |
| 145 |
assert zip_equal(check, expect) |
| 146 |
else: |
| 147 |
assert check == frozenset(expect) |
| 148 |
missing = ('foo', 'bar') if viewname == 'items' else 'foo' |
| 149 |
assert missing not in check |
| 150 |
if self.oracle.data: |
| 151 |
contained = rand.choice(tuple(expect)) |
| 152 |
assert contained in check |
| 153 |
if viewname != 'items': |
| 154 |
other_set = {k for (k, _) in other_set} |
| 155 |
assert_calls_match( |
| 156 |
partial(set_op, check, other_set), |
| 157 |
partial(set_op, expect, other_set), |
| 158 |
) |
| 159 |
if viewname == 'items': |
| 160 |
other_set = self.bi.__class__(dedup(other_set)).items() |
| 161 |
assert_calls_match( |
| 162 |
partial(set_op, check, other_set), |
| 163 |
partial(set_op, expect, other_set), |
| 164 |
) |
| 165 |
|
| 166 |
@invariant() |
| 167 |
def assert_bi_and_inv_are_inverse(self) -> None: |
| 168 |
assert_bi_and_inv_are_inverse(self.bi) |
| 169 |
|
| 170 |
@invariant() |
| 171 |
def assert_values_correspond_to_keys(self) -> None: |
| 172 |
"""values() must correspond elementwise to keys(), as a plain dict's does. |
| 173 |
|
| 174 |
Overwriting an item reorders a non-ordered bidict's backing _invm relative to its |
| 175 |
_fwdm, so a values() view sourced from _invm's keys would silently mispair here. |
| 176 |
Only reachable by mutating: a bulk __init__ that would cause it raises instead. |
| 177 |
""" |
| 178 |
for b in (self.bi, self.bi.inv): |
| 179 |
assert list(b.values()) == [b[k] for k in b] |
| 180 |
|
| 181 |
@precondition(lambda self: should_be_reversible(self.bi.__class__)) |
| 182 |
@invariant() |
| 183 |
def assert_reversed_works(self) -> None: |
| 184 |
assert list(reversed(self.bi)) == list(self.bi)[::-1] |
| 185 |
items = self.bi.items() |
| 186 |
assert isinstance(items, Reversible) |
| 187 |
assert list(reversed(items)) == list(items)[::-1] |
| 188 |
if self.is_ordered(): |
| 189 |
assert zip_equal(reversed(self.bi), reversed(self.oracle.data)) |
| 190 |
assert zip_equal(reversed(items), reversed(self.oracle.data.items())) |
| 191 |
values = self.bi.values() |
| 192 |
assert isinstance(values, Reversible) |
| 193 |
assert zip_equal(reversed(values), reversed(self.oracle.data.values())) |
| 194 |
|
| 195 |
@rule() |
| 196 |
def copy(self) -> None: |
| 197 |
for cp in (copy(self.bi), deepcopy(self.bi)): |
| 198 |
assert_bi_and_inv_are_inverse(cp) |
| 199 |
assert_bidicts_equal(cp, self.bi) |
| 200 |
|
| 201 |
@rule() |
| 202 |
def pickle(self) -> None: |
| 203 |
for b in (self.bi, self.bi.inv): |
| 204 |
roundtripped = pickle_copy(b) |
| 205 |
assert_bi_and_inv_are_inverse(roundtripped) |
| 206 |
assert_bidicts_equal(roundtripped, b) |
| 207 |
|
| 208 |
@rule() |
| 209 |
def clear(self) -> None: |
| 210 |
self.bi.clear() |
| 211 |
self.oracle.clear() |
| 212 |
|
| 213 |
@rule(key=keys, val=vals, on_dup=on_dup) |
| 214 |
def put(self, key: int, val: int, on_dup: OnDup) -> None: |
| 215 |
assert_calls_match( |
| 216 |
partial(self.bi.put, key, val, on_dup), |
| 217 |
partial(self.oracle.put, key, val, on_dup), |
| 218 |
) |
| 219 |
|
| 220 |
@rule(updates=items, updates_t=updates_t, on_dup=on_dup) |
| 221 |
def putall(self, updates: MapOrItems[int, int], updates_t: t.Any, on_dup: OnDup) -> None: |
| 222 |
# Don't let the updates_t(updates) calls below raise a DuplicationError. |
| 223 |
if isinstance(updates_t, type) and issubclass(updates_t, BidirectionalMapping): |
| 224 |
updates = dedup(updates) |
| 225 |
# Since updates_t can be iter, can't extract the two updates_t(updates) calls below into a single value. |
| 226 |
assert_calls_match( |
| 227 |
partial(self.bi.putall, updates_t(updates), on_dup), |
| 228 |
partial(self.oracle.putall, updates_t(updates), on_dup), |
| 229 |
) |
| 230 |
|
| 231 |
@rule(new=fresh_items, on_dup=on_dup) |
| 232 |
def putall_with_bad_item(self, new: Items, on_dup: OnDup) -> None: |
| 233 |
"""A bulk update whose last item raises must apply none of it, whatever the on_dup. |
| 234 |
|
| 235 |
The preceding items are fresh, so the only thing that can fail is the bad item. |
| 236 |
Pass an iterator so this always takes the incremental rollback path. |
| 237 |
""" |
| 238 |
assert_update_fails_clean(self.bi, iter([*new, (bomb, 0)]), RuntimeError, on_dup) |
| 239 |
|
| 240 |
@precondition(is_ordered) |
| 241 |
@rule(updates=items, on_dup=on_dup) |
| 242 |
def putall_with_bad_item_after_overwrites(self, updates: Items, on_dup: OnDup) -> None: |
| 243 |
"""An ordered bidict must restore its *order* too, not just its contents. |
| 244 |
|
| 245 |
Unlike the rule above this lets the preceding items overwrite existing ones, which |
| 246 |
is what makes the linked list's order diverge from the backing mappings'. Only |
| 247 |
ordered bidicts guarantee this: rolling back an overwrite reinserts the overwritten |
| 248 |
item at the end of a backing mapping rather than in its original position, so a |
| 249 |
non-ordered bidict is restored contents-only. See "Updates Fail Clean" in the docs. |
| 250 |
""" |
| 251 |
arg = iter([*updates, (bomb, 0)]) |
| 252 |
assert_update_fails_clean(self.bi, arg, (RuntimeError, DuplicationError), on_dup) |
| 253 |
|
| 254 |
@rule(other=items121) |
| 255 |
def __ior__(self, other: Mapping[int, int]) -> None: |
| 256 |
assert_calls_match( |
| 257 |
partial(self.bi.__ior__, other), |
| 258 |
partial(self.oracle.__ior__, other), |
| 259 |
) |
| 260 |
|
| 261 |
@rule(other=items121) |
| 262 |
def __or__(self, other: Mapping[int, int]) -> None: |
| 263 |
assert_calls_match( |
| 264 |
partial(self.bi.__or__, other), |
| 265 |
partial(self.oracle.__or__, other), |
| 266 |
) |
| 267 |
|
| 268 |
# https://bidict.rtfd.io/basic-usage.html#order-matters |
| 269 |
@precondition(lambda self: zip_equal(self.bi, self.oracle.data)) |
| 270 |
@rule(other=items121) |
| 271 |
def __ror__(self, other: Mapping[int, int]) -> None: |
| 272 |
assert_calls_match( |
| 273 |
partial(self.bi.__ror__, other), |
| 274 |
partial(self.oracle.__ror__, other), |
| 275 |
) |
| 276 |
|
| 277 |
@precondition(lambda self: len(self.bi) >= 2) |
| 278 |
@rule(random=randoms()) |
| 279 |
def update_with_dup(self, random: Random) -> None: |
| 280 |
# Covered nondeterministically by the more general "putall" rule above, but this ensures that basic duplication |
| 281 |
# scenarios are deterministically covered. |
| 282 |
# Choose two existing items at random. |
| 283 |
(k1, v1), (k2, v2) = random.sample(tuple(self.oracle.data.items()), 2) |
| 284 |
# Inserting (new_key, dup_val) should raise ValueDuplicationError. |
| 285 |
assert_update_fails_clean(self.bi, [('foo', 'foo'), ('bar', v1)], ValueDuplicationError) |
| 286 |
# key and value duplication across two different items should raise KeyAndValueDuplicationError. |
| 287 |
for key, val in ((k1, v2), (k2, v1)): |
| 288 |
assert_update_fails_clean(self.bi, [('foo', 'foo'), (key, val)], KeyAndValueDuplicationError) |
| 289 |
# Inserting already-present items should be a no-op. |
| 290 |
before = self.bi.copy() |
| 291 |
self.bi.update([(k1, v1), (k2, v2)]) |
| 292 |
assert self.bi.equals_order_sensitive(before) |
| 293 |
assert self.bi.inv.equals_order_sensitive(before.inv) |
| 294 |
|
| 295 |
def is_empty(self) -> bool: |
| 296 |
return not self.bi |
| 297 |
|
| 298 |
@precondition(is_empty) |
| 299 |
@rule() |
| 300 |
def popitem_empty(self) -> None: |
| 301 |
with pytest.raises(KeyError): |
| 302 |
self.bi.popitem() |
| 303 |
|
| 304 |
def is_nonempty(self) -> bool: |
| 305 |
return bool(self.bi) |
| 306 |
|
| 307 |
@precondition(is_nonempty) |
| 308 |
@rule(last=booleans(), flip=booleans(), inv=booleans()) |
| 309 |
def popitem(self, last: bool, inv: bool, flip: bool) -> None: |
| 310 |
bi, oracle = self.bi, self.oracle |
| 311 |
if is_ordered(bi): |
| 312 |
if not inv: |
| 313 |
expect = oracle.popitem(last=last) |
| 314 |
check = bi.popitem(last=last) |
| 315 |
else: |
| 316 |
expect = oracle.popitem(last=last)[::-1] |
| 317 |
check = bi.inv.popitem(last=last) |
| 318 |
assert check == expect |
| 319 |
assert check not in bi.items() |
| 320 |
else: |
| 321 |
fst, snd = (bi, oracle) if flip else (oracle, bi) |
| 322 |
k, v = fst.popitem() |
| 323 |
assert snd.pop(k) == v |
| 324 |
assert (k, v) not in bi.items() |
| 325 |
|
| 326 |
@precondition(is_nonempty) |
| 327 |
@rule(random=randoms()) |
| 328 |
def pop_randkey(self, random: Random) -> None: |
| 329 |
key = random.choice(tuple(self.oracle.data)) |
| 330 |
expect = self.oracle.pop(key) |
| 331 |
check = self.bi.pop(key) |
| 332 |
assert check == expect |
| 333 |
|
| 334 |
@precondition(is_ordered) |
| 335 |
@precondition(is_nonempty) |
| 336 |
@rule(random=randoms(), last=booleans()) |
| 337 |
def move_to_end_randkey(self, random: Random, last: bool) -> None: |
| 338 |
assert is_ordered(self.bi) |
| 339 |
key, val = random.choice(tuple(self.oracle.data.items())) |
| 340 |
self.bi.move_to_end(key, last=last) |
| 341 |
self.oracle.move_to_end(key, last=last) |
| 342 |
it: t.Any = reversed if last else iter |
| 343 |
assert (key, val) == next(it(self.bi.items())) |
| 344 |
assert (val, key) == next(it(self.bi.inv.items())) |
| 345 |
assert (key, val) == next(it(self.oracle.data.items())) |
| 346 |
assert (val, key) == next(it(self.oracle.data_inv.items())) |
| 347 |
|
| 348 |
|
| 349 |
BidictStateMachineTest = BidictStateMachine.TestCase |
| 350 |
|
| 351 |
|
| 352 |
@pytest.mark.parametrize('bi_t', bidict_types) |
| 353 |
def test_init_and_update_with_bad_args(bi_t: BT[KT, VT]) -> None: |
| 354 |
bad_args: t.Any |
| 355 |
for bad_args in ((None,), (0,), (False,), (True,), ({}, {})): |
| 356 |
# ty raises on unpacking an `Any`/unknown-length arg into a call; see |
| 357 |
# https://github.com/astral-sh/ty/issues/3649 |
| 358 |
with pytest.raises(TypeError): |
| 359 |
bi_t(*bad_args) # ty: ignore[invalid-argument-type, too-many-positional-arguments] |
| 360 |
if not issubclass(bi_t, MutableBidict): |
| 361 |
continue |
| 362 |
bi = bi_t() |
| 363 |
with pytest.raises(TypeError): |
| 364 |
bi.update(*bad_args) # ty: ignore[invalid-argument-type, too-many-positional-arguments] # https://github.com/astral-sh/ty/issues/3649 |
| 365 |
|
| 366 |
|
| 367 |
@pytest.mark.parametrize('bi_t', bidict_types) |
| 368 |
def test_inv_attrs_readonly(bi_t: BT[KT, VT]) -> None: |
| 369 |
"""Attempting to set .inverse or .inv should raise AttributeError.""" |
| 370 |
bi: t.Any = bi_t() |
| 371 |
with pytest.raises(AttributeError): |
| 372 |
bi.inverse = 'foo' |
| 373 |
with pytest.raises(AttributeError): |
| 374 |
bi.inv = 'foo' |
| 375 |
|
| 376 |
|
| 377 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 378 |
def test_pop_missing_key(bi_t: MBT[t.Any, t.Any]) -> None: |
| 379 |
bi = bi_t() |
| 380 |
with pytest.raises(KeyError): |
| 381 |
bi.pop('foo') |
| 382 |
assert bi.pop('foo', 'bar') == 'bar' |
| 383 |
|
| 384 |
|
| 385 |
@pytest.mark.parametrize('bi_t', [OrderedBidict, UserOrderedBi]) |
| 386 |
def test_move_to_end_missing_key(bi_t: type[OrderedBidict[KT, VT]]) -> None: |
| 387 |
bi = bi_t() |
| 388 |
with pytest.raises(KeyError): |
| 389 |
bi.move_to_end('foo') # ty: ignore[invalid-argument-type] |
| 390 |
|
| 391 |
|
| 392 |
@pytest.mark.parametrize('bi_t', bidict_types) |
| 393 |
def test_eq_defers_to_other_eq(bi_t: BT[KT, VT]) -> None: |
| 394 |
"""bidict.__eq__(other) should defer to other.__eq__ when other is not a mapping.""" |
| 395 |
# ANY.__eq__ always returns true, so this test will fail if bi_t.__eq__ fails to defer. |
| 396 |
assert bi_t() == ANY |
| 397 |
|
| 398 |
|
| 399 |
@pytest.mark.parametrize(('bi_t', 'non_mapping'), list(product(bidict_types, (None, 1, [], SupportsKeysAndGetItem({}))))) |
| 400 |
def test_eq_and_or_with_non_mapping(bi_t: BT[KT, VT], non_mapping: t.Any) -> None: |
| 401 |
bi = bi_t() |
| 402 |
assert bi != non_mapping |
| 403 |
assert not bi.equals_order_sensitive(non_mapping) |
| 404 |
with pytest.raises(TypeError): |
| 405 |
bi | non_mapping |
| 406 |
with pytest.raises(TypeError): |
| 407 |
non_mapping | bi |
| 408 |
|
| 409 |
|
| 410 |
@given(items121=items121, bidict_t=bidict_t, rand=randoms()) |
| 411 |
def test_equals_order_sensitive(items121: Items121, bidict_t: BT[KT, VT], rand: Random) -> None: |
| 412 |
# Ensure there are at least 3 items in items121. |
| 413 |
items121.update({5: -5, 6: -6, 7: -7}) |
| 414 |
bi = bidict_t(items121) |
| 415 |
items_shuf = list(items121.items()) |
| 416 |
rand.shuffle(items_shuf) |
| 417 |
assume(not zip_equal(items_shuf, items121.items())) |
| 418 |
map_shuf = dict(items_shuf) |
| 419 |
assert bi == map_shuf |
| 420 |
assert not bi.equals_order_sensitive(map_shuf) |
| 421 |
|
| 422 |
|
| 423 |
@given(items=items, bidict_t=bidict_t) |
| 424 |
def test_inverted(items: Items, bidict_t: BT[int, int]) -> None: |
| 425 |
check = tuple(inverted(inverted(items))) |
| 426 |
expect = items |
| 427 |
assert check == expect |
| 428 |
items_nodup = dedup(items) |
| 429 |
check_bi = bidict_t(inverted(bidict_t(items_nodup))) |
| 430 |
expect_bi = bidict_t({v: k for (k, v) in items_nodup.items()}) |
| 431 |
assert_bidicts_equal(check_bi, expect_bi) |
| 432 |
|
| 433 |
|
| 434 |
@given(items=items, bidict_t=bidict_t) |
| 435 |
# Pin the case that actually exercises the divergence, rather than relying on it being |
| 436 |
# generated: (3, -1) overwrites (1, -1) in place, so an ordered bidict keeps the item's |
| 437 |
# original position while its backing mappings append the new key and drop the old one. |
| 438 |
@example(items=((1, -1), (2, -2), (3, -1)), bidict_t=UserOrderedBiBase) |
| 439 |
def test_views_agree_with_iteration_order(items: Items, bidict_t: BT[int, int]) -> None: |
| 440 |
"""Every order-sensitive API must agree with the bidict's own iteration order. |
| 441 |
|
| 442 |
For ordered bidicts the order lives in the linked list, not in the backing mappings, |
| 443 |
and the two diverge as soon as an item is overwritten -- including during __init__, |
| 444 |
for a type whose on_dup permits it. So the views must not delegate to _fwdm. |
| 445 |
""" |
| 446 |
try: |
| 447 |
bi = bidict_t(items) |
| 448 |
except DuplicationError: # this type's on_dup rejects these items; settle for a 1:1 init |
| 449 |
bi = bidict_t(dedup(items)) |
| 450 |
expect = [(k, bi[k]) for k in bi] # the items in iteration order, without using items() |
| 451 |
assert list(bi.keys()) == list(bi) |
| 452 |
assert list(bi.items()) == expect |
| 453 |
assert list(dict(bi)) == list(bi) # dict(mapping) goes through keys() |
| 454 |
assert bi.equals_order_sensitive(bidict_t(expect)) |
| 455 |
assert list(bi.values()) == [v for (_, v) in expect] |
| 456 |
assert list(bi.items()) == list(zip(bi.keys(), bi.values(), strict=True)) |
| 457 |
if should_be_reversible(bidict_t): |
| 458 |
keysview, itemsview = bi.keys(), bi.items() |
| 459 |
assert isinstance(keysview, Reversible) |
| 460 |
assert isinstance(itemsview, Reversible) |
| 461 |
assert list(reversed(keysview)) == list(bi)[::-1] |
| 462 |
assert list(reversed(itemsview)) == expect[::-1] |
| 463 |
|
| 464 |
|
| 465 |
@given(items121=items121) |
| 466 |
def test_frozenbidicts_hashable(items121: Items121) -> None: |
| 467 |
"""Frozen bidicts can be hashed (and therefore inserted into sets and mappings).""" |
| 468 |
bi = frozenbidict(items121) |
| 469 |
h1 = hash(bi) |
| 470 |
h2 = hash(bi) |
| 471 |
assert h1 == h2 |
| 472 |
assert {bi} |
| 473 |
assert {bi: bi} |
| 474 |
bi2 = frozenbidict(items121) |
| 475 |
assert bi2 == bi |
| 476 |
assert hash(bi2) == h1 |
| 477 |
|
| 478 |
|
| 479 |
# These test cases ensure coverage of all branches in [Ordered]BidictBase._undo_write. |
| 480 |
# (Hypothesis doesn't always generate examples that cover all the branches otherwise.) |
| 481 |
@pytest.mark.parametrize(('bi_t', 'on_dup'), list(product(mutable_bidict_types, on_dups))) |
| 482 |
def test_putall_matches_bulk_put(bi_t: type[MutableBidict[int, int]], on_dup: OnDup) -> None: |
| 483 |
bi = bi_t({0: 0, 1: 1}) |
| 484 |
for k1, v1, k2, v2 in product(range(4), repeat=4): |
| 485 |
for b in bi, bi.inv: |
| 486 |
assert_putall_matches_bulk_put(b, [(k1, v1), (k2, v2)], on_dup) |
| 487 |
|
| 488 |
|
| 489 |
def assert_putall_matches_bulk_put(bi: MutableBidict[int, int], new_items: Items, on_dup: OnDup) -> None: |
| 490 |
tmp = bi.copy() |
| 491 |
checkexc = None |
| 492 |
expectexc = None |
| 493 |
try: |
| 494 |
for key, val in new_items: |
| 495 |
tmp.put(key, val, on_dup) |
| 496 |
except DuplicationError as exc: |
| 497 |
expectexc = type(exc) |
| 498 |
tmp = bi # Since bulk updates fail clean, expect no changes (i.e. revert to bi). |
| 499 |
try: |
| 500 |
bi.putall(new_items, on_dup) |
| 501 |
except DuplicationError as exc: |
| 502 |
checkexc = type(exc) |
| 503 |
assert checkexc == expectexc |
| 504 |
assert bi == tmp |
| 505 |
assert bi.inv == tmp.inv |
| 506 |
|
| 507 |
|
| 508 |
def assert_update_fails_clean( |
| 509 |
bi: MutableBidict[t.Any, t.Any], |
| 510 |
updates: t.Any, |
| 511 |
exc_t: type[Exception] | tuple[type[Exception], ...], |
| 512 |
on_dup: OnDup | None = None, |
| 513 |
) -> None: |
| 514 |
"""Check that a bulk update that raises *exc_t* leaves *bi* exactly as it was. |
| 515 |
|
| 516 |
Exercises update() (i.e. bi's own on_dup) when *on_dup* is None, else putall(). |
| 517 |
""" |
| 518 |
before = bi.copy() |
| 519 |
do_update = partial(bi.update, updates) if on_dup is None else partial(bi.putall, updates, on_dup) |
| 520 |
with pytest.raises(exc_t): |
| 521 |
do_update() |
| 522 |
assert bi.equals_order_sensitive(before) |
| 523 |
assert bi.inv.equals_order_sensitive(before.inv) |
| 524 |
|
| 525 |
|
| 526 |
# A RAISE-free on_dup must fail clean too: a bulk update can raise for reasons that have |
| 527 |
# nothing to do with duplication, so rollback cannot be conditioned on on_dup. |
| 528 |
@pytest.mark.parametrize(('bi_t', 'on_dup'), list(product(mutable_bidict_types, (None, *on_dups)))) |
| 529 |
def test_update_with_bad_last_item_fails_clean(bi_t: MBT[t.Any, t.Any], on_dup: OnDup | None) -> None: |
| 530 |
# Keep self at least as large as updates so this sized arg takes the |
| 531 |
# in-place rollback path rather than the copy fast path. |
| 532 |
bi = bi_t({ |
| 533 |
0: 0, |
| 534 |
1: 1, |
| 535 |
2: 2, |
| 536 |
}) |
| 537 |
for b in (bi, bi.inv): |
| 538 |
for exc, bad in BAD_ITEMS: |
| 539 |
# The items before the bad one are all new, so the update fails for the |
| 540 |
# bad item's reason regardless of the on_dup. |
| 541 |
updates = [(3, 3), (4, 4), bad] |
| 542 |
assert_update_fails_clean(b, updates, exc, on_dup) |
| 543 |
|
| 544 |
|
| 545 |
@pytest.mark.parametrize('bi_t', [bidict, OrderedBidict]) |
| 546 |
@pytest.mark.parametrize( |
| 547 |
('init', 'write', 'nwrites'), |
| 548 |
[ |
| 549 |
# One case per kind of duplication BidictBase._write() handles, with the number of writes |
| 550 |
# to the backing mappings it performs: two to insert the new item, plus one to remove each |
| 551 |
# item that the new one displaces. |
| 552 |
({1: 'a'}, lambda b: b.__setitem__(2, 'b'), 2), |
| 553 |
({1: 'a'}, lambda b: b.__setitem__(1, 'z'), 3), |
| 554 |
({1: 'a'}, lambda b: b.forceput(9, 'a'), 3), |
| 555 |
({1: 'a', 2: 'b'}, lambda b: b.forceput(1, 'b'), 4), |
| 556 |
], |
| 557 |
ids=['no-dup', 'dup-key', 'dup-val', 'dup-key-and-val'], |
| 558 |
) |
| 559 |
def test_write_fails_clean_when_a_backing_mapping_refuses( |
| 560 |
bi_t: MBT[t.Any, t.Any], init: dict[t.Any, t.Any], write: t.Any, nwrites: int |
| 561 |
) -> None: |
| 562 |
"""Writing one item must fail clean when a backing mapping refuses part-way through. |
| 563 |
|
| 564 |
_write() sets both backing mappings, and for some kinds of duplication deletes from them too. |
| 565 |
Backing mappings are user-supplied (see _fwdm_cls and _invm_cls), so any one of those writes |
| 566 |
can be refused, and everything already written must then be undone. |
| 567 |
""" |
| 568 |
unchanged = dict(init), invdict(init) |
| 569 |
refused = 0 |
| 570 |
for n in range(1, nwrites + 2): # one past the last, which must find nothing left to refuse |
| 571 |
bi = bidict_refusing_nth_write(bi_t, init, n) |
| 572 |
try: |
| 573 |
write(bi) |
| 574 |
except WriteRefused: |
| 575 |
refused += 1 |
| 576 |
assert (dict(bi._fwdm), dict(bi._invm)) == unchanged, f'refusing write #{n} left bi changed' |
| 577 |
else: |
| 578 |
break |
| 579 |
assert refused == nwrites |
| 580 |
|
| 581 |
|
| 582 |
@pytest.mark.parametrize('bi_t', [bidict, OrderedBidict]) |
| 583 |
@pytest.mark.parametrize( |
| 584 |
('remove', 'nwrites'), |
| 585 |
[ |
| 586 |
# Removing an item takes two writes whichever way it is asked for: one to each |
| 587 |
# backing mapping. |
| 588 |
(lambda b: b.__delitem__(1), 2), |
| 589 |
(lambda b: b.pop(1), 2), |
| 590 |
(lambda b: b.popitem(), 2), |
| 591 |
], |
| 592 |
ids=['delitem', 'pop', 'popitem'], |
| 593 |
) |
| 594 |
def test_remove_fails_clean_when_a_backing_mapping_refuses(bi_t: MBT[t.Any, t.Any], remove: t.Any, nwrites: int) -> None: |
| 595 |
"""Removing an item must fail clean when a backing mapping refuses part-way through. |
| 596 |
|
| 597 |
The removing counterpart of test_write_fails_clean_when_a_backing_mapping_refuses: |
| 598 |
removing from one backing mapping and then being refused by the other must not leave |
| 599 |
the two disagreeing. |
| 600 |
""" |
| 601 |
init = {1: 'a', 2: 'b'} |
| 602 |
unchanged = dict(init), invdict(init) |
| 603 |
refused = 0 |
| 604 |
for n in range(1, nwrites + 2): # one past the last, which must find nothing left to refuse |
| 605 |
bi = bidict_refusing_nth_write(bi_t, init, n) |
| 606 |
try: |
| 607 |
remove(bi) |
| 608 |
except WriteRefused: |
| 609 |
refused += 1 |
| 610 |
assert (dict(bi._fwdm), dict(bi._invm)) == unchanged, f'refusing write #{n} left bi changed' |
| 611 |
else: |
| 612 |
break |
| 613 |
assert refused == nwrites |
| 614 |
|
| 615 |
|
| 616 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 617 |
@pytest.mark.parametrize('roundtrip', [copy, deepcopy, pickle_copy], ids=['copy', 'deepcopy', 'pickle']) |
| 618 |
def test_roundtrip_preserves_iteration_order(bi_t: MBT[t.Any, t.Any], roundtrip: t.Any) -> None: |
| 619 |
"""Duplicating a bidict must preserve its own iteration order. |
| 620 |
|
| 621 |
An ordered bidict preserves its inverse's order too, since both read the same linked list. |
| 622 |
A non-ordered one does not: its inverse gets rebuilt by inverting the forward mapping, which |
| 623 |
leaves it in the forward mapping's order -- the same thing that happens whenever a bidict is |
| 624 |
built from items, and the reason to reach for an OrderedBidict when order matters. |
| 625 |
""" |
| 626 |
bi = bi_t({1: -1, 2: -2, 3: -3}) |
| 627 |
bi.forceput(4, -2) # a value-duplicating overwrite, which skews the inverse's order |
| 628 |
cp = roundtrip(bi) |
| 629 |
assert cp.equals_order_sensitive(bi) |
| 630 |
if isinstance(bi, OrderedBidictBase): |
| 631 |
assert cp.inv.equals_order_sensitive(bi.inv) |
| 632 |
|
| 633 |
|
| 634 |
def test_pickle_preserves_order_of_generated_inverse_class() -> None: |
| 635 |
"""An instance of a dynamically-generated inverse class keeps its own order. |
| 636 |
|
| 637 |
Such a class used to have no name pickle could reference it by, so __reduce__ pickled an |
| 638 |
instance of the class it was generated from and reconstructed this one by inverting, which |
| 639 |
left the order of the object being pickled derived rather than recorded. It is now pickled |
| 640 |
by reference like any other class (see _make_inv_cls), so the items are this object's own. |
| 641 |
""" |
| 642 |
b: MutableBidict[t.Any, t.Any] = UserBiNotOwnInv() |
| 643 |
b.forceupdate([(1, 'a'), (2, 'b'), (3, 'a')]) # the last item skews the inverse's order |
| 644 |
inv = b.inverse |
| 645 |
assert list(inv.items()) == [('a', 3), ('b', 2)] |
| 646 |
roundtripped = pickle_copy(inv) |
| 647 |
assert type(roundtripped) is type(inv) |
| 648 |
assert roundtripped.equals_order_sensitive(inv) |
| 649 |
|
| 650 |
|
| 651 |
def test_pickling_costs_no_extra_space() -> None: |
| 652 |
"""Preserving the order must not have made pickles bigger. |
| 653 |
|
| 654 |
Recording the inverse's key order alongside the forward mapping would: measured at up to 150% |
| 655 |
more space, or ~10% more time once conditioned on actually being needed. Making the generated |
| 656 |
class referenceable instead costs neither, since only the forward items are ever written. |
| 657 |
""" |
| 658 |
bi = bidict({i: -i for i in range(1000)}) |
| 659 |
assert len(pickle.dumps(bi)) < len(pickle.dumps(dict(bi))) * 1.1 |
| 660 |
|
| 661 |
|
| 662 |
def test_pickle_orderedbi_whose_order_disagrees_with_fwdm() -> None: |
| 663 |
"""An OrderedBidict whose order does not match its _fwdm's should pickle with the correct order.""" |
| 664 |
ob = OrderedBidict({0: 1, 2: 3}) |
| 665 |
# First get ob._fwdm's order to disagree with ob's: |
| 666 |
ob.inv[1] = 4 |
| 667 |
assert list(ob.items()) == [(4, 1), (2, 3)] |
| 668 |
assert list(ob._fwdm.items()) == [(2, 3), (4, 1)] |
| 669 |
# Now check that its order is preserved after pickling and unpickling: |
| 670 |
roundtripped = pickle_copy(ob) |
| 671 |
assert list(roundtripped.items()) == [(4, 1), (2, 3)] |
| 672 |
assert roundtripped.equals_order_sensitive(ob) |
| 673 |
|
| 674 |
|
| 675 |
def test_pickle_dynamically_generated_inverse_bidict() -> None: |
| 676 |
"""Instances of dynamically-generated inverse bidict classes should be pickleable.""" |
| 677 |
ub: MutableBidict[str, int] = UserBiNotOwnInv(one=1, two=2) |
| 678 |
roundtripped = pickle_copy(ub) |
| 679 |
assert roundtripped == ub == UserBiNotOwnInv({'one': 1, 'two': 2}) |
| 680 |
assert dict(roundtripped) == dict(ub) |
| 681 |
# Now for the inverse: |
| 682 |
assert repr(ub.inverse) == "UserBiNotOwnInvInv({1: 'one', 2: 'two'})" |
| 683 |
# We can still pickle the inverse, even though its class, UserBiNotOwnInvInv, was |
| 684 |
# dynamically generated, and we didn't save a reference to it named "UserBiNotOwnInvInv" |
| 685 |
# anywhere that pickle could find it in sys.modules: |
| 686 |
for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1): |
| 687 |
ubinv = pickle_copy(ub.inverse, protocol) |
| 688 |
assert repr(ubinv) == "UserBiNotOwnInvInv({1: 'one', 2: 'two'})" |
| 689 |
assert ub._inv_cls.__name__ not in (name for m in sys.modules for name in dir(m)) |
| 690 |
# What pickle finds it by instead is its __qualname__, which spells out the attribute of |
| 691 |
# UserBiNotOwnInv that it is reachable through. Check that that lookup resolves back to it. |
| 692 |
assert ub._inv_cls.__qualname__ == 'UserBiNotOwnInv._inv_cls' |
| 693 |
module = sys.modules[ub._inv_cls.__module__] |
| 694 |
assert reduce(getattr, ub._inv_cls.__qualname__.split('.'), module) is ub._inv_cls |
| 695 |
|
| 696 |
|
| 697 |
def test_abstract_bimap_init_fails() -> None: |
| 698 |
class AbstractBimap(BidirectionalMapping[t.Any, t.Any]): |
| 699 |
"""Does not override `inverse` and therefore should not be instantiable.""" |
| 700 |
|
| 701 |
for bi_t in (BidirectionalMapping, MutableBidirectionalMapping, AbstractBimap): |
| 702 |
with pytest.raises(TypeError, match="Can't instantiate abstract class"): |
| 703 |
bi_t() |
| 704 |
|
| 705 |
|
| 706 |
def test_bimap_bad_inverse() -> None: |
| 707 |
# Overrides `inverse`, but merely calls the abstract superclass implementation. |
| 708 |
class BimapBadInverse(BidirectionalMapping[t.Any, t.Any]): |
| 709 |
__getitem__ = __iter__ = __len__ = ... |
| 710 |
|
| 711 |
@property |
| 712 |
@override |
| 713 |
def inverse(self) -> t.Any: |
| 714 |
return super().inverse |
| 715 |
|
| 716 |
bi = BimapBadInverse() |
| 717 |
with pytest.raises(NotImplementedError): |
| 718 |
bi.inverse # ruff: ignore[useless-expression] # evaluating it is the point: it must raise |
| 719 |
|
| 720 |
|
| 721 |
skip_if_pypy = pytest.mark.skipif( |
| 722 |
sys.implementation.name == 'pypy', |
| 723 |
reason='Requires CPython refcounting behavior', |
| 724 |
) |
| 725 |
|
| 726 |
|
| 727 |
@skip_if_pypy |
| 728 |
@given(bidict_t=bidict_t) |
| 729 |
def test_bidicts_freed_on_zero_refcount(bidict_t: BT[KT, VT]) -> None: |
| 730 |
"""On CPython, the moment you have no more (strong) references to a bidict, |
| 731 |
there are no remaining (internal) strong references to it |
| 732 |
(i.e. no reference cycle was created between it and its inverse), |
| 733 |
allowing the memory to be reclaimed immediately, even with GC disabled. |
| 734 |
""" |
| 735 |
gc.disable() |
| 736 |
try: |
| 737 |
bi = bidict_t() |
| 738 |
weak = weakref.ref(bi) |
| 739 |
assert weak() is not None |
| 740 |
del bi |
| 741 |
assert weak() is None |
| 742 |
finally: |
| 743 |
gc.enable() |
| 744 |
|
| 745 |
|
| 746 |
@skip_if_pypy |
| 747 |
@given(items121=items121) |
| 748 |
def test_orderedbidict_nodes_freed_on_zero_refcount(items121: Items121) -> None: |
| 749 |
"""On CPython, the moment you have no more references to an ordered bidict, |
| 750 |
the refcount of each of its internal nodes drops to 0 |
| 751 |
(i.e. the linked list of nodes does not create a reference cycle), |
| 752 |
allowing the memory to be reclaimed immediately. |
| 753 |
""" |
| 754 |
gc.disable() |
| 755 |
try: |
| 756 |
ob = OrderedBidict(items121) |
| 757 |
nodes = weakref.WeakSet(ob._sntl.iternodes()) |
| 758 |
assert len(nodes) == len(ob) |
| 759 |
del ob |
| 760 |
assert len(nodes) == 0 |
| 761 |
finally: |
| 762 |
gc.enable() |
| 763 |
|
| 764 |
|
| 765 |
@given(items121=items121) |
| 766 |
def test_orderedbidict_nodes_consistent(items121: Items121) -> None: |
| 767 |
"""The nodes in an ordered bidict's backing linked list should be the same as those in its backing mapping.""" |
| 768 |
ob = OrderedBidict(items121) |
| 769 |
mapnodes = set(ob._node_by_korv.inverse) |
| 770 |
linkedlistnodes = set(ob._sntl.iternodes()) |
| 771 |
assert mapnodes == linkedlistnodes |
| 772 |
|
| 773 |
|
| 774 |
def test_dict_subclass_backing_gets_native_views() -> None: |
| 775 |
"""A backing mapping that is a dict subclass should get the same views a dict would. |
| 776 |
|
| 777 |
keys()/items() dispatch on isinstance(fwdm, dict) rather than `fwdm_cls is dict`, so a |
| 778 |
dict subclass -- which is what every backing in the docs' recipes actually is, e.g. |
| 779 |
sortedcontainers.SortedDict -- gets its own native views. Those are reversible, carry a |
| 780 |
.mapping attribute, and implement their set operations in C, none of which a generic |
| 781 |
view over the bidict provides. |
| 782 |
""" |
| 783 |
b = UserBiBackedByDictSub({1: 'one', 2: 'two'}) # backed by OrderedDict |
| 784 |
keysview, itemsview = b.keys(), b.items() |
| 785 |
assert not isinstance(keysview, BidictKeysView) # the backing's own view, not a fallback |
| 786 |
assert isinstance(keysview, Reversible) |
| 787 |
assert isinstance(itemsview, Reversible) |
| 788 |
assert hasattr(keysview, 'mapping') |
| 789 |
assert hasattr(itemsview, 'mapping') |
| 790 |
assert list(reversed(keysview)) == [2, 1] |
| 791 |
assert list(reversed(itemsview)) == [(2, 'two'), (1, 'one')] |
| 792 |
# ...and the views still agree with the bidict itself. |
| 793 |
assert list(keysview) == list(b) == [1, 2] |
| 794 |
assert list(itemsview) == [(1, 'one'), (2, 'two')] |
| 795 |
assert keysview == {1, 2} |
| 796 |
assert list(b.values()) == ['one', 'two'] |
| 797 |
|
| 798 |
|
| 799 |
def test_non_dict_backing_falls_back_to_generic_views() -> None: |
| 800 |
"""A backing mapping that is not a dict at all still gets a view over the bidict.""" |
| 801 |
b = UserBi({1: 'one', 2: 'two'}) # backed by UserDict |
| 802 |
assert isinstance(b.keys(), BidictKeysView) |
| 803 |
assert list(b.keys()) == [1, 2] |
| 804 |
assert b.keys() == {1, 2} |
| 805 |
assert list(b.items()) == [(1, 'one'), (2, 'two')] |
| 806 |
|
| 807 |
|
| 808 |
def test_subclass_can_regain_reversibility() -> None: |
| 809 |
"""A subclass whose backing mappings are reversible must be reversible. |
| 810 |
|
| 811 |
Regression test: _set_reversed() decided whether __reversed__ had been overridden by |
| 812 |
comparing the resolved value to BidictBase's. A class whose backing mappings are not |
| 813 |
reversible has __reversed__ set to None by _set_reversed() itself, and a subclass of |
| 814 |
it inherits that None, which compared unequal to BidictBase's and so was misread as a |
| 815 |
deliberate override -- leaving the subclass non-reversible no matter its own backings. |
| 816 |
""" |
| 817 |
|
| 818 |
class NotReversible(bidict[t.Any, t.Any]): |
| 819 |
_fwdm_cls = UserDict |
| 820 |
_invm_cls = UserDict |
| 821 |
|
| 822 |
class ReversibleAgain(NotReversible): |
| 823 |
_fwdm_cls = dict |
| 824 |
_invm_cls = dict |
| 825 |
|
| 826 |
assert not issubclass(NotReversible, Reversible) # UserDict is not reversible |
| 827 |
assert issubclass(ReversibleAgain, Reversible) # but dict is |
| 828 |
bi = ReversibleAgain({1: 'one', 2: 'two'}) |
| 829 |
assert list(reversed(bi)) == [2, 1] |
| 830 |
assert list(reversed(bi.keys())) == [2, 1] |
| 831 |
assert list(reversed(bi.values())) == ['two', 'one'] |
| 832 |
|
| 833 |
|
| 834 |
def test_user_provided_reversed_is_honored_and_inherited() -> None: |
| 835 |
"""_set_reversed() must never clobber a __reversed__ that a user provided. |
| 836 |
|
| 837 |
This is what keeps OrderedBidict, which does not define __reversed__ itself, from |
| 838 |
computing one from its backing mappings and losing OrderedBidictBase's. |
| 839 |
""" |
| 840 |
|
| 841 |
class CustomReversed(bidict[t.Any, t.Any]): |
| 842 |
@override |
| 843 |
def __reversed__(self) -> t.Any: |
| 844 |
return iter(['custom']) |
| 845 |
|
| 846 |
class SubCustom(CustomReversed): # even with backings that are not reversible |
| 847 |
_fwdm_cls = UserDict |
| 848 |
_invm_cls = UserDict |
| 849 |
|
| 850 |
for bi_t in (CustomReversed, SubCustom): |
| 851 |
assert issubclass(bi_t, Reversible) |
| 852 |
assert list(reversed(bi_t())) == ['custom'], bi_t |
| 853 |
|
| 854 |
|
| 855 |
def test_set_reversed_is_idempotent() -> None: |
| 856 |
"""Running _set_reversed() again must not make a computed __reversed__ look user-provided. |
| 857 |
|
| 858 |
It only runs once per class today, but were a repeat ever to mark the class as having a |
| 859 |
user-provided __reversed__, subclasses would inherit that and stop computing their own, |
| 860 |
which is exactly the bug that test_subclass_can_regain_reversibility covers. |
| 861 |
""" |
| 862 |
|
| 863 |
class Computed(bidict[t.Any, t.Any]): |
| 864 |
pass |
| 865 |
|
| 866 |
Computed._set_reversed() |
| 867 |
assert not Computed._reversed_is_user_provided |
| 868 |
|
| 869 |
class SubComputed(Computed): |
| 870 |
_fwdm_cls = UserDict |
| 871 |
_invm_cls = UserDict |
| 872 |
|
| 873 |
assert not issubclass(SubComputed, Reversible) # still free to compute its own answer |
| 874 |
|
| 875 |
|
| 876 |
def test_reversed_opt_out_is_honored_and_inherited() -> None: |
| 877 |
"""Setting __reversed__ to None opts out of reversed(), for subclasses too. |
| 878 |
|
| 879 |
Unnecessary as of v0.22 for the usual case of non-reversible backing mappings, which |
| 880 |
_set_reversed() now detects, but still the way to opt out deliberately. |
| 881 |
""" |
| 882 |
|
| 883 |
class OptedOut(bidict[t.Any, t.Any]): |
| 884 |
__reversed__ = None |
| 885 |
|
| 886 |
class SubOptedOut(OptedOut): |
| 887 |
pass |
| 888 |
|
| 889 |
for bi_t in (OptedOut, SubOptedOut): |
| 890 |
bi: t.Any = bi_t({1: 'one'}) |
| 891 |
assert not isinstance(bi, Reversible), bi_t |
| 892 |
with pytest.raises(TypeError): |
| 893 |
reversed(bi) |
| 894 |
# The values view must not offer what the bidict itself declines to. |
| 895 |
assert not isinstance(bi.values(), Reversible), bi_t |
| 896 |
|
| 897 |
|
| 898 |
#: Ways to mutate an ordered bidict, keyed by name. Each takes the bidict and the key |
| 899 |
#: just yielded by the iteration in progress. |
| 900 |
_MUTATIONS_DURING_ITERATION: t.Any = { |
| 901 |
'insert': lambda ob, key: ob.__setitem__(f'new{key}', f'new{key}'), |
| 902 |
'delete': lambda ob, key: ob.pop(next(k for k in ob if k != key), None), |
| 903 |
'clear': lambda ob, _key: ob.clear(), |
| 904 |
'move_to_end': lambda ob, key: ob.move_to_end(key), |
| 905 |
'collapse_to_fewer_items': lambda ob, key: ob.forceput(key, next(iter(ob.inv))), |
| 906 |
'insert_via_the_inverse': lambda ob, key: ob.inv.__setitem__(f'new{key}', f'new{key}'), |
| 907 |
} |
| 908 |
|
| 909 |
|
| 910 |
def _iterate_while_mutating(ob: OrderedBidict[t.Any, t.Any], iterate: t.Any, mutate: t.Any) -> None: |
| 911 |
"""Iterate *ob* via *iterate*, applying *mutate* to it on each step. |
| 912 |
|
| 913 |
Bounded, so that a failure to detect the mutation fails the test rather than hanging it: |
| 914 |
inserting during iteration used to grow the linked list ahead of the iterator forever. |
| 915 |
""" |
| 916 |
for i, key in enumerate(iterate(ob)): |
| 917 |
assert i < 100, 'iteration did not terminate after mutation' |
| 918 |
mutate(ob, key) |
| 919 |
|
| 920 |
|
| 921 |
@pytest.mark.parametrize('mutate', _MUTATIONS_DURING_ITERATION.values(), ids=list(_MUTATIONS_DURING_ITERATION)) |
| 922 |
@pytest.mark.parametrize('iterate', [iter, reversed], ids=['forward', 'reverse']) |
| 923 |
def test_orderedbidict_mutation_during_iteration_raises(mutate: t.Any, iterate: t.Any) -> None: |
| 924 |
"""Mutating an ordered bidict while iterating it must raise RuntimeError. |
| 925 |
|
| 926 |
dict and OrderedDict both do this. Without it, inserting during iteration looped forever, |
| 927 |
clear() raised a KeyError naming an internal Node, and deleting silently skipped items. |
| 928 |
Note the last mutation goes through the inverse, which shares the linked list, so it must |
| 929 |
invalidate this iterator too. |
| 930 |
""" |
| 931 |
ob: OrderedBidict[t.Any, t.Any] = OrderedBidict({1: 'one', 2: 'two', 3: 'three'}) |
| 932 |
with pytest.raises(RuntimeError): |
| 933 |
_iterate_while_mutating(ob, iterate, mutate) |
| 934 |
|
| 935 |
|
| 936 |
def test_orderedbidict_mutation_on_final_item_raises() -> None: |
| 937 |
"""Mutating while the last item is being visited raises, unlike OrderedDict. |
| 938 |
|
| 939 |
dict raises here and OrderedDict does not, so the two disagree and we cannot match both. |
| 940 |
Raising is the safer of the two, keeps OrderedBidict consistent with plain bidict (which |
| 941 |
is backed by a dict and so already raises), and avoids code that works or not depending |
| 942 |
on which iteration the mutating branch happens to be taken on. |
| 943 |
""" |
| 944 |
ob = OrderedBidict({1: 'one', 2: 'two'}) |
| 945 |
with pytest.raises(RuntimeError): |
| 946 |
_iterate_while_mutating(ob, iter, lambda o, key: o.__setitem__(3, 'three') if key == 2 else None) |
| 947 |
|
| 948 |
|
| 949 |
def test_orderedbidict_iteration_allows_value_only_update() -> None: |
| 950 |
"""Updating an existing key's value does not restructure the list, so it must not raise. |
| 951 |
|
| 952 |
dict and OrderedDict both permit this, and an ordered bidict's iteration order is |
| 953 |
unaffected by it: the item keeps its node, and so its position. |
| 954 |
""" |
| 955 |
ob = OrderedBidict({1: 'one', 2: 'two'}) |
| 956 |
for key in ob: |
| 957 |
ob[key] = f'updated{key}' |
| 958 |
assert list(ob.items()) == [(1, 'updated1'), (2, 'updated2')] |
| 959 |
|
| 960 |
|
| 961 |
def test_orderedbidict_iterator_created_before_mutation_raises() -> None: |
| 962 |
"""The check must catch a mutation made after the iterator was created but before it ran. |
| 963 |
|
| 964 |
OrderedDict does this too, which is why iternodes() captures the version eagerly rather |
| 965 |
than on the first next() call. |
| 966 |
""" |
| 967 |
ob = OrderedBidict({1: 'one', 2: 'two'}) |
| 968 |
it = iter(ob) |
| 969 |
ob[3] = 'three' |
| 970 |
with pytest.raises(RuntimeError): |
| 971 |
list(it) |
| 972 |
|
| 973 |
|
| 974 |
def test_orderedbidict_iteration_unaffected_by_unrelated_bidict() -> None: |
| 975 |
"""Only mutations to *this* bidict's linked list invalidate its iterators.""" |
| 976 |
ob, other = OrderedBidict({1: 'one', 2: 'two'}), OrderedBidict({3: 'three'}) |
| 977 |
keys = [] |
| 978 |
for key in ob: |
| 979 |
other[key] = f'x{key}' # a different bidict, so a different linked list |
| 980 |
keys.append(key) |
| 981 |
assert keys == [1, 2] |
| 982 |
|
| 983 |
|
| 984 |
#: (label, mutation) pairs, each writing an item that duplicates a contained key, a contained |
| 985 |
#: value, or both, using an object that is equal to the contained one but not identical to it. |
| 986 |
_DUPLICATING_WRITES: t.Any = { |
| 987 |
'key_duplication': lambda b: b.__setitem__(Tagged(1, 'new'), 'other'), |
| 988 |
'value_duplication': lambda b: b.forceput(Tagged(9, 'new'), Tagged(2, 'new')), |
| 989 |
'collapse': lambda b: b.forceput(Tagged(1, 'new'), Tagged(2, 'new')), |
| 990 |
} |
| 991 |
|
| 992 |
|
| 993 |
@pytest.mark.parametrize('mutate', _DUPLICATING_WRITES.values(), ids=list(_DUPLICATING_WRITES)) |
| 994 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 995 |
def test_one_object_per_item_in_both_directions(bi_t: MBT[t.Any, t.Any], mutate: t.Any) -> None: |
| 996 |
"""A bidict and its inverse must hold the same object for each item, not equal copies. |
| 997 |
|
| 998 |
dict keeps the key object it already has when a key is overwritten, but takes the new |
| 999 |
value object. In a bidict a value is also a key of the inverse, so those two conventions |
| 1000 |
conflict; applying each to its own backing mapping left the two holding equal but distinct |
| 1001 |
objects for one item, and so left b.inverse[b[key]] not identical to key. |
| 1002 |
""" |
| 1003 |
bi = bi_t({Tagged(1, 'orig'): Tagged(2, 'orig')}) |
| 1004 |
mutate(bi) |
| 1005 |
for key in bi: |
| 1006 |
val = bi[key] |
| 1007 |
assert bi.inverse[val] is key, 'key differs between a bidict and its inverse' |
| 1008 |
inv_key = next(k for k in bi.inverse if k == val) |
| 1009 |
assert inv_key is val, 'value differs between a bidict and its inverse' |
| 1010 |
|
| 1011 |
|
| 1012 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 1013 |
def test_duplicating_write_keeps_the_contained_object(bi_t: MBT[t.Any, t.Any]) -> None: |
| 1014 |
"""Of two equal objects, the one already contained is the one kept. |
| 1015 |
|
| 1016 |
That is what a dict does for keys, and it is the only self-consistent choice here: |
| 1017 |
adopting the incoming key object instead would mean deleting and reinserting it, which |
| 1018 |
would move the item to the end and so silently reorder the bidict. |
| 1019 |
""" |
| 1020 |
bi = bi_t({Tagged(1, 'orig'): Tagged(2, 'orig')}) |
| 1021 |
bi[Tagged(1, 'new')] = Tagged(3, 'new') # key duplicates the contained Tagged(1) |
| 1022 |
(key,) = bi |
| 1023 |
assert key.tag == 'orig' |
| 1024 |
assert bi.inverse[bi[key]].tag == 'orig' |
| 1025 |
|
| 1026 |
|
| 1027 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 1028 |
def test_duplicating_write_does_not_reorder(bi_t: MBT[t.Any, t.Any]) -> None: |
| 1029 |
"""Keeping the contained key object also keeps the item in place.""" |
| 1030 |
bi = bi_t({Tagged(1): 'one', Tagged(2): 'two'}) |
| 1031 |
bi[Tagged(1, 'new')] = 'uno' |
| 1032 |
assert [k.n for k in bi] == [1, 2] |
| 1033 |
|
| 1034 |
|
| 1035 |
def test_orderedbidict_weakattr_class_access() -> None: |
| 1036 |
"""Accessing a WeakAttr descriptor from the Node class should return the descriptor itself.""" |
| 1037 |
descriptor = OrderedBidictNode.prv |
| 1038 |
assert isinstance(descriptor, WeakAttr) |
| 1039 |
|
| 1040 |
|
| 1041 |
def test_orderedbidictbase_order_diverges_from_backing_mappings() -> None: |
| 1042 |
"""Spell out the scenario behind test_views_agree_with_iteration_order's @example. |
| 1043 |
|
| 1044 |
That test checks the views against the bidict's own iteration order, so on its own it |
| 1045 |
could not tell you whether the two orders ever actually differ. This pins that they do, |
| 1046 |
with absolute expectations, and covers repr() (which goes through items()) besides. |
| 1047 |
|
| 1048 |
Regression test: the keys()/items() overrides used to live on OrderedBidict, justified |
| 1049 |
by a *mutable* ordered bidict getting out of sync with its backing mappings after |
| 1050 |
mutation. But an overwrite during __init__ suffices, so OrderedBidictBase needs them too. |
| 1051 |
""" |
| 1052 |
ob = UserOrderedBiBase([(1, 'a'), (2, 'b'), (3, 'a')]) # (3, 'a') overwrites (1, 'a') in place |
| 1053 |
assert list(ob) == [3, 2] # the item formerly keyed 1 is now keyed 3, in its original position |
| 1054 |
assert list(ob._fwdm) == [2, 3] # whereas the backing dict appended 3 and dropped 1 |
| 1055 |
assert repr(ob) == "UserOrderedBiBase({3: 'a', 2: 'b'})" |
| 1056 |
|
| 1057 |
|
| 1058 |
def test_orderedbidict_cross_view_set_operations() -> None: |
| 1059 |
"""Set operations between an OrderedBidict keys view and an items view (or vice versa) should |
| 1060 |
behave like the equivalent plain dict views rather than raising TypeError or giving a wrong result. |
| 1061 |
|
| 1062 |
Regression test: the set-operation proxy methods in _OrderedBidictKeysView and |
| 1063 |
_OrderedBidictItemsView previously passed the opposing custom view type directly to the |
| 1064 |
C-level dict_keys/dict_items methods, which returned NotImplemented (they only recognize |
| 1065 |
dict_keys and dict_items). With both sides returning NotImplemented, Python raised TypeError |
| 1066 |
(for the ordering comparisons) or fell back to the wrong answer (e.g. identity-based __eq__). |
| 1067 |
The fix extracts the backing dict view from a cross-type _OView arg before forwarding. |
| 1068 |
""" |
| 1069 |
ob1 = OrderedBidict({'a': 1, 'b': 2}) |
| 1070 |
ob2 = OrderedBidict({'a': 1}) |
| 1071 |
d1 = {'a': 1, 'b': 2} |
| 1072 |
d2 = {'a': 1} |
| 1073 |
# The comparison operators return bools; the set-algebra operators return sets/bools. In every |
| 1074 |
# case the OrderedBidict view result must match the equivalent plain dict view result exactly. |
| 1075 |
# fmt: off |
| 1076 |
ops = ( |
| 1077 |
'__lt__', '__le__', '__gt__', '__ge__', '__eq__', '__ne__', # comparisons |
| 1078 |
'__sub__', '__or__', '__xor__', '__and__', 'isdisjoint', # set algebra |
| 1079 |
) |
| 1080 |
# fmt: on |
| 1081 |
for op in ops: |
| 1082 |
assert getattr(ob1.keys(), op)(ob2.items()) == getattr(d1.keys(), op)(d2.items()), op |
| 1083 |
assert getattr(ob1.items(), op)(ob2.keys()) == getattr(d1.items(), op)(d2.keys()), op |
| 1084 |
|
| 1085 |
|
| 1086 |
def test_abc_slots() -> None: |
| 1087 |
"""Bidict ABCs should define __slots__. |
| 1088 |
|
| 1089 |
Ref: https://docs.python.org/3/reference/datamodel.html#notes-on-using-slots |
| 1090 |
|
| 1091 |
Note: non-abstract bidict types do not define __slots__ as of v0.22.0. |
| 1092 |
""" |
| 1093 |
assert BidirectionalMapping.__dict__['__slots__'] == () |
| 1094 |
assert MutableBidirectionalMapping.__dict__['__slots__'] == () |
| 1095 |
|
| 1096 |
|
| 1097 |
@pytest.mark.parametrize('bi_t', bidict_types) |
| 1098 |
def test_values_view_reversibility_matches_bidict(bi_t: BT[t.Any, t.Any]) -> None: |
| 1099 |
"""values() iterates the backing forward mapping, so it must be reversible |
| 1100 |
exactly when the bidict itself is -- never advertising a reversed() that raises. |
| 1101 |
""" |
| 1102 |
bi = bi_t({1: -1, 2: -2}) |
| 1103 |
values = bi.values() |
| 1104 |
if isinstance(bi, Reversible): |
| 1105 |
assert isinstance(values, Reversible) |
| 1106 |
assert list(reversed(values)) == list(bi.values())[::-1] |
| 1107 |
else: |
| 1108 |
assert not isinstance(values, Reversible) |
| 1109 |
with pytest.raises(TypeError): # and the claim is not a lie |
| 1110 |
reversed(t.cast('t.Any', values)) |
| 1111 |
|
| 1112 |
|
| 1113 |
@pytest.mark.parametrize('bi_t', bidict_types) |
| 1114 |
def test_inv_aliases_inverse(bi_t: BT[KT, VT]) -> None: |
| 1115 |
"""bi.inv should alias bi.inverse.""" |
| 1116 |
bi = bi_t() |
| 1117 |
assert bi.inverse is bi.inv |
| 1118 |
assert bi.inv.inverse is bi.inverse.inv |
| 1119 |
|
| 1120 |
|
| 1121 |
def test_static_types() -> None: |
| 1122 |
d = {'1': 1} |
| 1123 |
fb = frozenbidict(d) |
| 1124 |
assert_type(fb, frozenbidict[str, int]) |
| 1125 |
assert_type(fb.inv, frozenbidict[int, str]) |
| 1126 |
|
| 1127 |
|
| 1128 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 1129 |
def test_setitem_existing_is_noop_with_nonreflexive_eq(bi_t: MBT[t.Any, t.Any]) -> None: |
| 1130 |
"""Setting an existing (key, val) pair should be a no-op even when key == key is False. |
| 1131 |
|
| 1132 |
Float NaN has non-reflexive equality (nan != nan), so it exercises |
| 1133 |
the identity-based same-item check in _dedup. |
| 1134 |
|
| 1135 |
(Previously, _dedup used an equality-based same-item check that caused |
| 1136 |
spurious KeyAndValueDuplicationErrors and AssertionErrors. See #377.) |
| 1137 |
""" |
| 1138 |
nan = float('nan') |
| 1139 |
# NaN as key: b[nan] = 'a' again must not raise |
| 1140 |
b1 = bi_t() |
| 1141 |
b1[nan] = 'a' |
| 1142 |
b1[nan] = 'a' |
| 1143 |
assert len(b1) == 1 |
| 1144 |
assert b1[nan] == 'a' |
| 1145 |
# NaN as value: b['x'] = nan again must not raise |
| 1146 |
b2 = bi_t() |
| 1147 |
b2['x'] = nan |
| 1148 |
b2['x'] = nan |
| 1149 |
assert len(b2) == 1 |
| 1150 |
assert b2['x'] is nan |
| 1151 |
# A key or value that duplicates an existing item's key and an existing |
| 1152 |
# *different* item's value must still raise, even when it's the same NaN object: |
| 1153 |
b3 = bi_t() |
| 1154 |
b3[nan] = 'a' |
| 1155 |
b3['x'] = nan |
| 1156 |
with pytest.raises(KeyAndValueDuplicationError): |
| 1157 |
b3[nan] = nan |
| 1158 |
|
| 1159 |
|
| 1160 |
class _AsymStored: |
| 1161 |
"""Pathological type equal to _AsymLookup instances, but only when on the left-hand side.""" |
| 1162 |
|
| 1163 |
@override |
| 1164 |
def __hash__(self) -> int: |
| 1165 |
return 1 |
| 1166 |
|
| 1167 |
@override |
| 1168 |
def __eq__(self, other: object) -> bool: |
| 1169 |
return isinstance(other, _AsymLookup) |
| 1170 |
|
| 1171 |
|
| 1172 |
class _AsymLookup: |
| 1173 |
"""Pathological type that is never equal to anything, even when an _AsymStored equals it.""" |
| 1174 |
|
| 1175 |
@override |
| 1176 |
def __hash__(self) -> int: |
| 1177 |
return 1 |
| 1178 |
|
| 1179 |
@override |
| 1180 |
def __eq__(self, other: object) -> bool: |
| 1181 |
return False |
| 1182 |
|
| 1183 |
|
| 1184 |
@pytest.mark.parametrize('bi_t', mutable_bidict_types) |
| 1185 |
def test_setitem_existing_is_noop_with_asymmetric_eq(bi_t: MBT[t.Any, t.Any]) -> None: |
| 1186 |
"""Setting an existing (key, val) pair should be a no-op even when __eq__ is asymmetric. |
| 1187 |
|
| 1188 |
dict lookup compares stored == lookup, so a lookup key that a stored key compares equal to |
| 1189 |
hits the stored key's item even when lookup == stored is False. |
| 1190 |
|
| 1191 |
_dedup must agree with the dict lookups rather than re-checking equality itself |
| 1192 |
(with operands in the opposite order) and wrongly concluding the items differ. |
| 1193 |
See #382. |
| 1194 |
""" |
| 1195 |
stored, lookup = _AsymStored(), _AsymLookup() |
| 1196 |
probe: dict[t.Any, str] = {stored: 'hit'} |
| 1197 |
if probe.get(lookup) != 'hit': |
| 1198 |
pytest.skip('dict lookup on this runtime does not compare stored == lookup') |
| 1199 |
# Asymmetric key: dict considers *lookup* the same key as *stored* -> no-op |
| 1200 |
b1 = bi_t() |
| 1201 |
b1[stored] = 'v' |
| 1202 |
b1[lookup] = 'v' |
| 1203 |
assert len(b1) == 1 |
| 1204 |
assert next(iter(b1)) is stored |
| 1205 |
# Asymmetric value -> no-op |
| 1206 |
b2 = bi_t() |
| 1207 |
b2['x'] = stored |
| 1208 |
b2['x'] = lookup |
| 1209 |
assert len(b2) == 1 |
| 1210 |
assert b2['x'] is stored |
| 1211 |
|
| 1212 |
|
| 1213 |
def assert_calls_match(call1: Callable[..., t.Any], call2: Callable[..., t.Any]) -> None: |
| 1214 |
results: dict[t.Any, t.Any] = {call1: None, call2: None} |
| 1215 |
for call in results: |
| 1216 |
try: |
| 1217 |
results[call] = call() |
| 1218 |
except Exception as exc: # ruff: ignore[blind-except] |
| 1219 |
results[call] = exc.__class__ |
| 1220 |
assert results[call1] == results[call2] |
| 1221 |
|
| 1222 |
|
| 1223 |
def assert_mappings_are_inverse(m1: Mapping[KT, VT], m2: Mapping[VT, KT]) -> None: |
| 1224 |
assert len(m1) == len(m2) |
| 1225 |
assert all(k == m2[v] for (k, v) in m1.items()) |
| 1226 |
assert m1.keys() == frozenset(m2.values()) |
| 1227 |
assert frozenset(m1.values()) == m2.keys() |
| 1228 |
|
| 1229 |
|
| 1230 |
def assert_bi_and_inv_are_inverse(bi: BB[KT, VT]) -> None: |
| 1231 |
assert_mappings_are_inverse(bi, bi.inv) |
| 1232 |
assert bi is bi.inv.inv |
| 1233 |
assert bi.inv is bi.inv.inv.inv |
| 1234 |
|
| 1235 |
|
| 1236 |
def assert_bidicts_equal(b1: BB[KT, VT], b2: BB[KT, VT]) -> None: |
| 1237 |
assert b1 == b2 |
| 1238 |
assert b1.inv == b2.inv |
| 1239 |
assert_mappings_are_inverse(b1, b2.inv) |
| 1240 |
assert_mappings_are_inverse(b1.inv, b2) |