| 1 |
# Test cases for dicts (compile and run) |
| 2 |
|
| 3 |
[case testDictStuff] |
| 4 |
from typing import Dict, Any, List, Set, Tuple |
| 5 |
from defaultdictwrap import make_dict |
| 6 |
|
| 7 |
def f(x: int) -> int: |
| 8 |
dict1 = {} # type: Dict[int, int] |
| 9 |
dict1[1] = 1 |
| 10 |
dict2 = {} # type: Dict[int, int] |
| 11 |
dict2[x] = 2 |
| 12 |
dict1.update(dict2) |
| 13 |
|
| 14 |
l = [(5, 2)] # type: Any |
| 15 |
dict1.update(l) |
| 16 |
d2 = {6: 4} # type: Any |
| 17 |
dict1.update(d2) |
| 18 |
|
| 19 |
return dict1[1] |
| 20 |
|
| 21 |
def g() -> int: |
| 22 |
d = make_dict() |
| 23 |
d['a'] = 10 |
| 24 |
d['a'] += 10 |
| 25 |
d['b'] += 10 |
| 26 |
l = [('c', 2)] # type: Any |
| 27 |
d.update(l) |
| 28 |
d2 = {'d': 4} # type: Any |
| 29 |
d.update(d2) |
| 30 |
return d['a'] + d['b'] |
| 31 |
|
| 32 |
def h() -> None: |
| 33 |
d = {} # type: Dict[Any, Any] |
| 34 |
d[{}] |
| 35 |
|
| 36 |
def update_dict(x: Dict[Any, Any], y: Any): |
| 37 |
x.update(y) |
| 38 |
|
| 39 |
def make_dict1(x: Any) -> Dict[Any, Any]: |
| 40 |
return dict(x) |
| 41 |
|
| 42 |
def make_dict2(x: Dict[Any, Any]) -> Dict[Any, Any]: |
| 43 |
return dict(x) |
| 44 |
|
| 45 |
def u(x: int) -> int: |
| 46 |
d = {} # type: Dict[str, int] |
| 47 |
d.update(x=x) |
| 48 |
return d['x'] |
| 49 |
|
| 50 |
def get_content(d: Dict[int, int]) -> Tuple[List[int], List[int], List[Tuple[int, int]]]: |
| 51 |
return list(d.keys()), list(d.values()), list(d.items()) |
| 52 |
|
| 53 |
def get_content_set(d: Dict[int, int]) -> Tuple[Set[int], Set[int], Set[Tuple[int, int]]]: |
| 54 |
return set(d.keys()), set(d.values()), set(d.items()) |
| 55 |
[file defaultdictwrap.py] |
| 56 |
from typing import Dict |
| 57 |
from collections import defaultdict # type: ignore |
| 58 |
def make_dict() -> Dict[str, int]: |
| 59 |
return defaultdict(int) |
| 60 |
|
| 61 |
[file driver.py] |
| 62 |
from collections import OrderedDict |
| 63 |
from native import ( |
| 64 |
f, g, h, u, make_dict1, make_dict2, update_dict, get_content, get_content_set |
| 65 |
) |
| 66 |
assert f(1) == 2 |
| 67 |
assert f(2) == 1 |
| 68 |
assert g() == 30 |
| 69 |
# Make sure we get a TypeError from indexing with unhashable and not KeyError |
| 70 |
try: |
| 71 |
h() |
| 72 |
except TypeError: |
| 73 |
pass |
| 74 |
else: |
| 75 |
assert False |
| 76 |
d = {'a': 1, 'b': 2} |
| 77 |
assert make_dict1(d) == d |
| 78 |
assert make_dict1(d.items()) == d |
| 79 |
assert make_dict2(d) == d |
| 80 |
# object.__dict__ is a "mappingproxy" and not a dict |
| 81 |
assert make_dict1(object.__dict__) == dict(object.__dict__) |
| 82 |
d = {} |
| 83 |
update_dict(d, object.__dict__) |
| 84 |
assert d == dict(object.__dict__) |
| 85 |
|
| 86 |
assert u(10) == 10 |
| 87 |
assert get_content({1: 2}) == ([1], [2], [(1, 2)]) |
| 88 |
od = OrderedDict([(1, 2), (3, 4)]) |
| 89 |
assert get_content(od) == ([1, 3], [2, 4], [(1, 2), (3, 4)]) |
| 90 |
od.move_to_end(1) |
| 91 |
assert get_content(od) == ([3, 1], [4, 2], [(3, 4), (1, 2)]) |
| 92 |
assert get_content_set({1: 2}) == ({1}, {2}, {(1, 2)}) |
| 93 |
assert get_content_set(od) == ({1, 3}, {2, 4}, {(1, 2), (3, 4)}) |
| 94 |
|
| 95 |
[typing fixtures/typing-full.pyi] |
| 96 |
|
| 97 |
[case testDictIterationMethodsRun] |
| 98 |
from typing import Dict, TypedDict, Union |
| 99 |
|
| 100 |
class ExtensionDict(TypedDict): |
| 101 |
python: str |
| 102 |
c: str |
| 103 |
|
| 104 |
def print_dict_methods(d1: Dict[int, int], |
| 105 |
d2: Dict[int, int], |
| 106 |
d3: Dict[int, int]) -> None: |
| 107 |
for k in d1.keys(): |
| 108 |
print(k) |
| 109 |
for k, v in d2.items(): |
| 110 |
print(k) |
| 111 |
print(v) |
| 112 |
for v in d3.values(): |
| 113 |
print(v) |
| 114 |
|
| 115 |
def print_dict_methods_special(d1: Union[Dict[int, int], Dict[str, str]], |
| 116 |
d2: ExtensionDict) -> None: |
| 117 |
for k in d1.keys(): |
| 118 |
print(k) |
| 119 |
for k, v in d1.items(): |
| 120 |
print(k) |
| 121 |
print(v) |
| 122 |
for v2 in d2.values(): |
| 123 |
print(v2) |
| 124 |
for k2, v2 in d2.items(): |
| 125 |
print(k2) |
| 126 |
print(v2) |
| 127 |
|
| 128 |
|
| 129 |
def clear_during_iter(d: Dict[int, int]) -> None: |
| 130 |
for k in d: |
| 131 |
d.clear() |
| 132 |
|
| 133 |
class Custom(Dict[int, int]): pass |
| 134 |
[file driver.py] |
| 135 |
from native import print_dict_methods, print_dict_methods_special, Custom, clear_during_iter |
| 136 |
from collections import OrderedDict |
| 137 |
print_dict_methods({}, {}, {}) |
| 138 |
print_dict_methods({1: 2}, {3: 4, 5: 6}, {7: 8}) |
| 139 |
print('==') |
| 140 |
c = Custom({0: 1}) |
| 141 |
print_dict_methods(c, c, c) |
| 142 |
print('==') |
| 143 |
d = OrderedDict([(1, 2), (3, 4)]) |
| 144 |
print_dict_methods(d, d, d) |
| 145 |
print('==') |
| 146 |
print_dict_methods_special({1: 2}, {"python": ".py", "c": ".c"}) |
| 147 |
d.move_to_end(1) |
| 148 |
print_dict_methods(d, d, d) |
| 149 |
clear_during_iter({}) # OK |
| 150 |
try: |
| 151 |
clear_during_iter({1: 2, 3: 4}) |
| 152 |
except RuntimeError as e: |
| 153 |
assert str(e) == "dictionary changed size during iteration" |
| 154 |
else: |
| 155 |
assert False |
| 156 |
try: |
| 157 |
clear_during_iter(d) |
| 158 |
except RuntimeError as e: |
| 159 |
assert str(e) in ( |
| 160 |
"OrderedDict changed size during iteration", |
| 161 |
# Error message changed in Python 3.13 and some 3.12 patch version |
| 162 |
"OrderedDict mutated during iteration", |
| 163 |
) |
| 164 |
else: |
| 165 |
assert False |
| 166 |
|
| 167 |
class CustomMad(dict): |
| 168 |
def __iter__(self): |
| 169 |
return self |
| 170 |
def __next__(self): |
| 171 |
raise ValueError |
| 172 |
m = CustomMad() |
| 173 |
try: |
| 174 |
clear_during_iter(m) |
| 175 |
except ValueError: |
| 176 |
pass |
| 177 |
else: |
| 178 |
assert False |
| 179 |
|
| 180 |
class CustomBad(dict): |
| 181 |
def items(self): |
| 182 |
return [(1, 2, 3)] # Oops |
| 183 |
b = CustomBad() |
| 184 |
try: |
| 185 |
print_dict_methods(b, b, b) |
| 186 |
except TypeError as e: |
| 187 |
assert str(e) == "a tuple of length 2 expected" |
| 188 |
else: |
| 189 |
assert False |
| 190 |
[typing fixtures/typing-full.pyi] |
| 191 |
[out] |
| 192 |
1 |
| 193 |
3 |
| 194 |
4 |
| 195 |
5 |
| 196 |
6 |
| 197 |
8 |
| 198 |
== |
| 199 |
0 |
| 200 |
0 |
| 201 |
1 |
| 202 |
1 |
| 203 |
== |
| 204 |
1 |
| 205 |
3 |
| 206 |
1 |
| 207 |
2 |
| 208 |
3 |
| 209 |
4 |
| 210 |
2 |
| 211 |
4 |
| 212 |
== |
| 213 |
1 |
| 214 |
1 |
| 215 |
2 |
| 216 |
.py |
| 217 |
.c |
| 218 |
python |
| 219 |
.py |
| 220 |
c |
| 221 |
.c |
| 222 |
3 |
| 223 |
1 |
| 224 |
3 |
| 225 |
4 |
| 226 |
1 |
| 227 |
2 |
| 228 |
4 |
| 229 |
2 |
| 230 |
|
| 231 |
[case testDictMethods] |
| 232 |
from collections import defaultdict |
| 233 |
from typing import Dict, Optional, List, Set |
| 234 |
|
| 235 |
def test_dict_clear() -> None: |
| 236 |
d = {'a': 1, 'b': 2} |
| 237 |
d.clear() |
| 238 |
assert d == {} |
| 239 |
dd: Dict[str, int] = defaultdict(int) |
| 240 |
dd['a'] = 1 |
| 241 |
dd.clear() |
| 242 |
assert dd == {} |
| 243 |
|
| 244 |
def test_dict_copy() -> None: |
| 245 |
d: Dict[str, int] = {} |
| 246 |
assert d.copy() == d |
| 247 |
d = {'a': 1, 'b': 2} |
| 248 |
assert d.copy() == d |
| 249 |
assert d.copy() is not d |
| 250 |
dd: Dict[str, int] = defaultdict(int) |
| 251 |
dd['a'] = 1 |
| 252 |
assert dd.copy() == dd |
| 253 |
assert isinstance(dd.copy(), defaultdict) |
| 254 |
|
| 255 |
class MyDict(dict): |
| 256 |
def __init__(self, *args, **kwargs): |
| 257 |
self.update(*args, **kwargs) |
| 258 |
|
| 259 |
def setdefault(self, k, v=None): |
| 260 |
if v is None: |
| 261 |
if k in self.keys(): |
| 262 |
return self[k] |
| 263 |
else: |
| 264 |
return None |
| 265 |
else: |
| 266 |
return super().setdefault(k, v) + 10 |
| 267 |
|
| 268 |
def test_dict_setdefault() -> None: |
| 269 |
d: Dict[str, Optional[int]] = {'a': 1, 'b': 2} |
| 270 |
assert d.setdefault('a', 2) == 1 |
| 271 |
assert d.setdefault('b', 2) == 2 |
| 272 |
assert d.setdefault('c', 3) == 3 |
| 273 |
assert d['a'] == 1 |
| 274 |
assert d['c'] == 3 |
| 275 |
assert d.setdefault('a') == 1 |
| 276 |
assert d.setdefault('e') == None |
| 277 |
assert d.setdefault('e', 100) == None |
| 278 |
|
| 279 |
def test_dict_subclass_setdefault() -> None: |
| 280 |
d = MyDict() |
| 281 |
d['a'] = 1 |
| 282 |
assert d.setdefault('a', 2) == 11 |
| 283 |
assert d.setdefault('b', 2) == 12 |
| 284 |
assert d.setdefault('c', 3) == 13 |
| 285 |
assert d['a'] == 1 |
| 286 |
assert d['c'] == 3 |
| 287 |
assert d.setdefault('a') == 1 |
| 288 |
assert d.setdefault('e') == None |
| 289 |
assert d.setdefault('e', 100) == 110 |
| 290 |
|
| 291 |
def test_dict_empty_collection_setdefault() -> None: |
| 292 |
d1: Dict[str, List[int]] = {'a': [1, 2, 3]} |
| 293 |
assert d1.setdefault('a', []) == [1, 2, 3] |
| 294 |
assert d1.setdefault('b', []) == [] |
| 295 |
assert 'b' in d1 |
| 296 |
d1.setdefault('b', []).append(3) |
| 297 |
assert d1['b'] == [3] |
| 298 |
assert d1.setdefault('c', [1]) == [1] |
| 299 |
|
| 300 |
d2: Dict[str, Dict[str, int]] = {'a': {'a': 1}} |
| 301 |
assert d2.setdefault('a', {}) == {'a': 1} |
| 302 |
assert d2.setdefault('b', {}) == {} |
| 303 |
assert 'b' in d2 |
| 304 |
d2.setdefault('b', {})['aa'] = 2 |
| 305 |
d2.setdefault('b', {})['bb'] = 3 |
| 306 |
assert d2['b'] == {'aa': 2, 'bb': 3} |
| 307 |
assert d2.setdefault('c', {'cc': 1}) == {'cc': 1} |
| 308 |
|
| 309 |
d3: Dict[str, Set[str]] = {'a': set('a')} |
| 310 |
assert d3.setdefault('a', set()) == {'a'} |
| 311 |
assert d3.setdefault('b', set()) == set() |
| 312 |
d3.setdefault('b', set()).add('b') |
| 313 |
d3.setdefault('b', set()).add('c') |
| 314 |
assert d3['b'] == {'b', 'c'} |
| 315 |
assert d3.setdefault('c', set('d')) == {'d'} |
| 316 |
|
| 317 |
[case testDictToBool] |
| 318 |
from typing import Dict, List |
| 319 |
|
| 320 |
def is_true(x: dict) -> bool: |
| 321 |
if x: |
| 322 |
return True |
| 323 |
else: |
| 324 |
return False |
| 325 |
|
| 326 |
def is_false(x: dict) -> bool: |
| 327 |
if not x: |
| 328 |
return True |
| 329 |
else: |
| 330 |
return False |
| 331 |
|
| 332 |
def test_dict_to_bool() -> None: |
| 333 |
assert is_false({}) |
| 334 |
assert not is_true({}) |
| 335 |
tmp_list: List[Dict] = [{2: bool}, {'a': 'b'}] |
| 336 |
for x in tmp_list: |
| 337 |
assert is_true(x) |
| 338 |
assert not is_false(x) |
| 339 |
|
| 340 |
[case testIsInstance] |
| 341 |
from copysubclass import subc |
| 342 |
def test_built_in() -> None: |
| 343 |
assert isinstance({}, dict) |
| 344 |
assert isinstance({'one': 1, 'two': 2}, dict) |
| 345 |
assert isinstance({1: 1, 'two': 2}, dict) |
| 346 |
assert isinstance(subc(), dict) |
| 347 |
assert isinstance(subc({'a': 1, 'b': 2}), dict) |
| 348 |
assert isinstance(subc({1: 'a', 2: 'b'}), dict) |
| 349 |
|
| 350 |
assert not isinstance(set(), dict) |
| 351 |
assert not isinstance((), dict) |
| 352 |
assert not isinstance((1,2,3), dict) |
| 353 |
assert not isinstance({'a','b'}, dict) |
| 354 |
assert not isinstance(int() + 1, dict) |
| 355 |
assert not isinstance(str() + 'a', dict) |
| 356 |
|
| 357 |
def test_user_defined() -> None: |
| 358 |
from userdefineddict import dict |
| 359 |
|
| 360 |
assert isinstance(dict(), dict) |
| 361 |
assert not isinstance({1: dict()}, dict) |
| 362 |
|
| 363 |
[file copysubclass.py] |
| 364 |
from typing import Any |
| 365 |
class subc(dict[Any, Any]): |
| 366 |
pass |
| 367 |
|
| 368 |
[file userdefineddict.py] |
| 369 |
class dict: |
| 370 |
pass |
| 371 |
|
| 372 |
[case testDunderDictAccessAfterDel] |
| 373 |
from mypy_extensions import mypyc_attr |
| 374 |
|
| 375 |
@mypyc_attr(allow_interpreted_subclasses=True) |
| 376 |
class NormDict(dict[str, str]): |
| 377 |
def __init__(self, attr: int = 42) -> None: |
| 378 |
super().__init__() |
| 379 |
self.attr = attr |
| 380 |
|
| 381 |
class SubNormDict(NormDict): |
| 382 |
def __init__(self, attr: int = 43) -> None: |
| 383 |
super().__init__(attr) |
| 384 |
|
| 385 |
def test_dict_access() -> None: |
| 386 |
n = NormDict(1) |
| 387 |
d = n.__dict__ |
| 388 |
assert d["attr"] == 1 |
| 389 |
del n |
| 390 |
assert d["attr"] == 1 |
| 391 |
|
| 392 |
def test_subclass_dict_access() -> None: |
| 393 |
s = SubNormDict(1) |
| 394 |
d = s.__dict__ |
| 395 |
assert d["attr"] == 1 |
| 396 |
del s |
| 397 |
assert d["attr"] == 1 |
| 398 |
|
| 399 |
[file driver.py] |
| 400 |
from native import NormDict, SubNormDict, test_dict_access, test_subclass_dict_access |
| 401 |
|
| 402 |
|
| 403 |
class InterpretedNormDict(NormDict): |
| 404 |
pass |
| 405 |
|
| 406 |
def test_dict_access_interpreted() -> None: |
| 407 |
n = NormDict() |
| 408 |
d = n.__dict__ |
| 409 |
assert d["attr"] == 42 |
| 410 |
del n |
| 411 |
assert d["attr"] == 42 |
| 412 |
|
| 413 |
def test_subclass_dict_access_interpreted() -> None: |
| 414 |
s = SubNormDict() |
| 415 |
d = s.__dict__ |
| 416 |
assert d["attr"] == 43 |
| 417 |
del s |
| 418 |
assert d["attr"] == 43 |
| 419 |
|
| 420 |
def test_allow_interpreted_subclass_dict_access() -> None: |
| 421 |
s = InterpretedNormDict() |
| 422 |
d = s.__dict__ |
| 423 |
assert d["attr"] == 42 |
| 424 |
del s |
| 425 |
assert d["attr"] == 42 |
| 426 |
|
| 427 |
test_dict_access() |
| 428 |
test_dict_access_interpreted() |
| 429 |
|
| 430 |
test_subclass_dict_access() |
| 431 |
test_subclass_dict_access_interpreted() |
| 432 |
test_allow_interpreted_subclass_dict_access() |
| 433 |
|
| 434 |
[fixture fixtures/typing-full.pyi] |
| 435 |
|
| 436 |
[case testCycleInDictSubclass] |
| 437 |
import gc |
| 438 |
from mypy_extensions import mypyc_attr |
| 439 |
|
| 440 |
events: list[str] = [] |
| 441 |
|
| 442 |
@mypyc_attr(allow_interpreted_subclasses=True) |
| 443 |
class CyclicDict(dict): |
| 444 |
def __init__(self) -> None: |
| 445 |
self["self"] = self |
| 446 |
|
| 447 |
def __del__(self) -> None: |
| 448 |
events.append("deleted") |
| 449 |
|
| 450 |
class SubCyclicDict(CyclicDict): |
| 451 |
def __init__(self) -> None: |
| 452 |
super().__init__() |
| 453 |
|
| 454 |
def __del__(self) -> None: |
| 455 |
events.append("sub deleted") |
| 456 |
|
| 457 |
def test_cyclic_dict_cleanup() -> None: |
| 458 |
global events |
| 459 |
events = [] |
| 460 |
|
| 461 |
c = CyclicDict() |
| 462 |
del c |
| 463 |
gc.collect() |
| 464 |
assert events == ["deleted"], events |
| 465 |
|
| 466 |
def test_sub_cyclic_dict_cleanup() -> None: |
| 467 |
global events |
| 468 |
events = [] |
| 469 |
|
| 470 |
c = SubCyclicDict() |
| 471 |
del c |
| 472 |
gc.collect() |
| 473 |
assert events == ["sub deleted"], events |
| 474 |
|
| 475 |
[file driver.py] |
| 476 |
import gc |
| 477 |
|
| 478 |
import native |
| 479 |
from native import CyclicDict, SubCyclicDict, test_cyclic_dict_cleanup, test_sub_cyclic_dict_cleanup |
| 480 |
|
| 481 |
|
| 482 |
class InterpretedCyclicDict(CyclicDict): |
| 483 |
def __del__(self) -> None: |
| 484 |
native.events.append("interpreted deleted") |
| 485 |
|
| 486 |
def test_cyclic_dict_cleanup_interpreted() -> None: |
| 487 |
native.events = [] |
| 488 |
|
| 489 |
c = CyclicDict() |
| 490 |
del c |
| 491 |
gc.collect() |
| 492 |
assert native.events == ["deleted"], events |
| 493 |
|
| 494 |
def test_sub_cyclic_dict_cleanup_interpreted() -> None: |
| 495 |
native.events = [] |
| 496 |
|
| 497 |
c = SubCyclicDict() |
| 498 |
del c |
| 499 |
gc.collect() |
| 500 |
assert native.events == ["sub deleted"], events |
| 501 |
|
| 502 |
def test_allow_interpreted_subclass_cyclic_dict_cleanup() -> None: |
| 503 |
native.events = [] |
| 504 |
|
| 505 |
c = InterpretedCyclicDict() |
| 506 |
del c |
| 507 |
gc.collect() |
| 508 |
assert native.events == ["interpreted deleted"], events |
| 509 |
|
| 510 |
test_cyclic_dict_cleanup() |
| 511 |
test_sub_cyclic_dict_cleanup() |
| 512 |
|
| 513 |
test_cyclic_dict_cleanup_interpreted() |
| 514 |
test_sub_cyclic_dict_cleanup_interpreted() |
| 515 |
test_allow_interpreted_subclass_cyclic_dict_cleanup() |