| 1 |
import collections |
| 2 |
import collections.abc |
| 3 |
import gc |
| 4 |
import pickle |
| 5 |
import random |
| 6 |
import string |
| 7 |
import sys |
| 8 |
import unittest |
| 9 |
import weakref |
| 10 |
from test import support |
| 11 |
from test.support import import_helper, get_c_recursion_limit |
| 12 |
|
| 13 |
|
| 14 |
class CustomHash: |
| 15 |
def __init__(self, hash): |
| 16 |
self.hash = hash |
| 17 |
def __hash__(self): |
| 18 |
return self.hash |
| 19 |
def __repr__(self): |
| 20 |
return f'<CustomHash {self.hash} at {id(self):#x}>' |
| 21 |
|
| 22 |
|
| 23 |
class DictTest(unittest.TestCase): |
| 24 |
|
| 25 |
def test_invalid_keyword_arguments(self): |
| 26 |
class Custom(dict): |
| 27 |
pass |
| 28 |
for invalid in {1 : 2}, Custom({1 : 2}): |
| 29 |
with self.assertRaises(TypeError): |
| 30 |
dict(**invalid) |
| 31 |
with self.assertRaises(TypeError): |
| 32 |
{}.update(**invalid) |
| 33 |
|
| 34 |
def test_constructor(self): |
| 35 |
# calling built-in types without argument must return empty |
| 36 |
self.assertEqual(dict(), {}) |
| 37 |
self.assertIsNot(dict(), {}) |
| 38 |
|
| 39 |
def test_literal_constructor(self): |
| 40 |
# check literal constructor for different sized dicts |
| 41 |
# (to exercise the BUILD_MAP oparg). |
| 42 |
for n in (0, 1, 6, 256, 400): |
| 43 |
items = [(''.join(random.sample(string.ascii_letters, 8)), i) |
| 44 |
for i in range(n)] |
| 45 |
random.shuffle(items) |
| 46 |
formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items) |
| 47 |
dictliteral = '{' + ', '.join(formatted_items) + '}' |
| 48 |
self.assertEqual(eval(dictliteral), dict(items)) |
| 49 |
|
| 50 |
def test_merge_operator(self): |
| 51 |
|
| 52 |
a = {0: 0, 1: 1, 2: 1} |
| 53 |
b = {1: 1, 2: 2, 3: 3} |
| 54 |
|
| 55 |
c = a.copy() |
| 56 |
c |= b |
| 57 |
|
| 58 |
self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3}) |
| 59 |
self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3}) |
| 60 |
|
| 61 |
c = b.copy() |
| 62 |
c |= a |
| 63 |
|
| 64 |
self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0}) |
| 65 |
self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0}) |
| 66 |
|
| 67 |
c = a.copy() |
| 68 |
c |= [(1, 1), (2, 2), (3, 3)] |
| 69 |
|
| 70 |
self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3}) |
| 71 |
|
| 72 |
self.assertIs(a.__or__(None), NotImplemented) |
| 73 |
self.assertIs(a.__or__(()), NotImplemented) |
| 74 |
self.assertIs(a.__or__("BAD"), NotImplemented) |
| 75 |
self.assertIs(a.__or__(""), NotImplemented) |
| 76 |
|
| 77 |
self.assertRaises(TypeError, a.__ior__, None) |
| 78 |
self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1}) |
| 79 |
self.assertRaises(ValueError, a.__ior__, "BAD") |
| 80 |
self.assertEqual(a.__ior__(""), {0: 0, 1: 1, 2: 1}) |
| 81 |
|
| 82 |
def test_bool(self): |
| 83 |
self.assertIs(not {}, True) |
| 84 |
self.assertTrue({1: 2}) |
| 85 |
self.assertIs(bool({}), False) |
| 86 |
self.assertIs(bool({1: 2}), True) |
| 87 |
|
| 88 |
def test_keys(self): |
| 89 |
d = {} |
| 90 |
self.assertEqual(set(d.keys()), set()) |
| 91 |
d = {'a': 1, 'b': 2} |
| 92 |
k = d.keys() |
| 93 |
self.assertEqual(set(k), {'a', 'b'}) |
| 94 |
self.assertIn('a', k) |
| 95 |
self.assertIn('b', k) |
| 96 |
self.assertIn('a', d) |
| 97 |
self.assertIn('b', d) |
| 98 |
self.assertRaises(TypeError, d.keys, None) |
| 99 |
self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])") |
| 100 |
|
| 101 |
def test_values(self): |
| 102 |
d = {} |
| 103 |
self.assertEqual(set(d.values()), set()) |
| 104 |
d = {1:2} |
| 105 |
self.assertEqual(set(d.values()), {2}) |
| 106 |
self.assertRaises(TypeError, d.values, None) |
| 107 |
self.assertEqual(repr(dict(a=1).values()), "dict_values([1])") |
| 108 |
|
| 109 |
def test_items(self): |
| 110 |
d = {} |
| 111 |
self.assertEqual(set(d.items()), set()) |
| 112 |
|
| 113 |
d = {1:2} |
| 114 |
self.assertEqual(set(d.items()), {(1, 2)}) |
| 115 |
self.assertRaises(TypeError, d.items, None) |
| 116 |
self.assertEqual(repr(dict(a=1).items()), "dict_items([('a', 1)])") |
| 117 |
|
| 118 |
def test_views_mapping(self): |
| 119 |
mappingproxy = type(type.__dict__) |
| 120 |
class Dict(dict): |
| 121 |
pass |
| 122 |
for cls in [dict, Dict]: |
| 123 |
d = cls() |
| 124 |
m1 = d.keys().mapping |
| 125 |
m2 = d.values().mapping |
| 126 |
m3 = d.items().mapping |
| 127 |
|
| 128 |
for m in [m1, m2, m3]: |
| 129 |
self.assertIsInstance(m, mappingproxy) |
| 130 |
self.assertEqual(m, d) |
| 131 |
|
| 132 |
d["foo"] = "bar" |
| 133 |
|
| 134 |
for m in [m1, m2, m3]: |
| 135 |
self.assertIsInstance(m, mappingproxy) |
| 136 |
self.assertEqual(m, d) |
| 137 |
|
| 138 |
def test_contains(self): |
| 139 |
d = {} |
| 140 |
self.assertNotIn('a', d) |
| 141 |
self.assertFalse('a' in d) |
| 142 |
self.assertTrue('a' not in d) |
| 143 |
d = {'a': 1, 'b': 2} |
| 144 |
self.assertIn('a', d) |
| 145 |
self.assertIn('b', d) |
| 146 |
self.assertNotIn('c', d) |
| 147 |
|
| 148 |
self.assertRaises(TypeError, d.__contains__) |
| 149 |
|
| 150 |
def test_len(self): |
| 151 |
d = {} |
| 152 |
self.assertEqual(len(d), 0) |
| 153 |
d = {'a': 1, 'b': 2} |
| 154 |
self.assertEqual(len(d), 2) |
| 155 |
|
| 156 |
def test_getitem(self): |
| 157 |
d = {'a': 1, 'b': 2} |
| 158 |
self.assertEqual(d['a'], 1) |
| 159 |
self.assertEqual(d['b'], 2) |
| 160 |
d['c'] = 3 |
| 161 |
d['a'] = 4 |
| 162 |
self.assertEqual(d['c'], 3) |
| 163 |
self.assertEqual(d['a'], 4) |
| 164 |
del d['b'] |
| 165 |
self.assertEqual(d, {'a': 4, 'c': 3}) |
| 166 |
|
| 167 |
self.assertRaises(TypeError, d.__getitem__) |
| 168 |
|
| 169 |
class BadEq(object): |
| 170 |
def __eq__(self, other): |
| 171 |
raise Exc() |
| 172 |
def __hash__(self): |
| 173 |
return 24 |
| 174 |
|
| 175 |
d = {} |
| 176 |
d[BadEq()] = 42 |
| 177 |
self.assertRaises(KeyError, d.__getitem__, 23) |
| 178 |
|
| 179 |
class Exc(Exception): pass |
| 180 |
|
| 181 |
class BadHash(object): |
| 182 |
fail = False |
| 183 |
def __hash__(self): |
| 184 |
if self.fail: |
| 185 |
raise Exc() |
| 186 |
else: |
| 187 |
return 42 |
| 188 |
|
| 189 |
x = BadHash() |
| 190 |
d[x] = 42 |
| 191 |
x.fail = True |
| 192 |
self.assertRaises(Exc, d.__getitem__, x) |
| 193 |
|
| 194 |
def test_clear(self): |
| 195 |
d = {1:1, 2:2, 3:3} |
| 196 |
d.clear() |
| 197 |
self.assertEqual(d, {}) |
| 198 |
|
| 199 |
self.assertRaises(TypeError, d.clear, None) |
| 200 |
|
| 201 |
def test_update(self): |
| 202 |
d = {} |
| 203 |
d.update({1:100}) |
| 204 |
d.update({2:20}) |
| 205 |
d.update({1:1, 2:2, 3:3}) |
| 206 |
self.assertEqual(d, {1:1, 2:2, 3:3}) |
| 207 |
|
| 208 |
d.update() |
| 209 |
self.assertEqual(d, {1:1, 2:2, 3:3}) |
| 210 |
|
| 211 |
self.assertRaises((TypeError, AttributeError), d.update, None) |
| 212 |
|
| 213 |
class SimpleUserDict: |
| 214 |
def __init__(self): |
| 215 |
self.d = {1:1, 2:2, 3:3} |
| 216 |
def keys(self): |
| 217 |
return self.d.keys() |
| 218 |
def __getitem__(self, i): |
| 219 |
return self.d[i] |
| 220 |
d.clear() |
| 221 |
d.update(SimpleUserDict()) |
| 222 |
self.assertEqual(d, {1:1, 2:2, 3:3}) |
| 223 |
|
| 224 |
class Exc(Exception): pass |
| 225 |
|
| 226 |
d.clear() |
| 227 |
class FailingUserDict: |
| 228 |
def keys(self): |
| 229 |
raise Exc |
| 230 |
self.assertRaises(Exc, d.update, FailingUserDict()) |
| 231 |
|
| 232 |
class FailingUserDict: |
| 233 |
def keys(self): |
| 234 |
class BogonIter: |
| 235 |
def __init__(self): |
| 236 |
self.i = 1 |
| 237 |
def __iter__(self): |
| 238 |
return self |
| 239 |
def __next__(self): |
| 240 |
if self.i: |
| 241 |
self.i = 0 |
| 242 |
return 'a' |
| 243 |
raise Exc |
| 244 |
return BogonIter() |
| 245 |
def __getitem__(self, key): |
| 246 |
return key |
| 247 |
self.assertRaises(Exc, d.update, FailingUserDict()) |
| 248 |
|
| 249 |
class FailingUserDict: |
| 250 |
def keys(self): |
| 251 |
class BogonIter: |
| 252 |
def __init__(self): |
| 253 |
self.i = ord('a') |
| 254 |
def __iter__(self): |
| 255 |
return self |
| 256 |
def __next__(self): |
| 257 |
if self.i <= ord('z'): |
| 258 |
rtn = chr(self.i) |
| 259 |
self.i += 1 |
| 260 |
return rtn |
| 261 |
raise StopIteration |
| 262 |
return BogonIter() |
| 263 |
def __getitem__(self, key): |
| 264 |
raise Exc |
| 265 |
self.assertRaises(Exc, d.update, FailingUserDict()) |
| 266 |
|
| 267 |
class badseq(object): |
| 268 |
def __iter__(self): |
| 269 |
return self |
| 270 |
def __next__(self): |
| 271 |
raise Exc() |
| 272 |
|
| 273 |
self.assertRaises(Exc, {}.update, badseq()) |
| 274 |
|
| 275 |
self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) |
| 276 |
|
| 277 |
def test_update_shared_keys(self): |
| 278 |
class MyClass: pass |
| 279 |
|
| 280 |
# Subclass str to enable us to create an object during the |
| 281 |
# dict.update() call. |
| 282 |
class MyStr(str): |
| 283 |
def __hash__(self): |
| 284 |
return super().__hash__() |
| 285 |
|
| 286 |
def __eq__(self, other): |
| 287 |
# Create an object that shares the same PyDictKeysObject as |
| 288 |
# obj.__dict__. |
| 289 |
obj2 = MyClass() |
| 290 |
obj2.a = "a" |
| 291 |
obj2.b = "b" |
| 292 |
obj2.c = "c" |
| 293 |
return super().__eq__(other) |
| 294 |
|
| 295 |
obj = MyClass() |
| 296 |
obj.a = "a" |
| 297 |
obj.b = "b" |
| 298 |
|
| 299 |
x = {} |
| 300 |
x[MyStr("a")] = MyStr("a") |
| 301 |
|
| 302 |
# gh-132617: this previously raised "dict mutated during update" error |
| 303 |
x.update(obj.__dict__) |
| 304 |
|
| 305 |
self.assertEqual(x, { |
| 306 |
MyStr("a"): "a", |
| 307 |
"b": "b", |
| 308 |
}) |
| 309 |
|
| 310 |
def test_fromkeys(self): |
| 311 |
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) |
| 312 |
d = {} |
| 313 |
self.assertIsNot(d.fromkeys('abc'), d) |
| 314 |
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) |
| 315 |
self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) |
| 316 |
self.assertEqual(d.fromkeys([]), {}) |
| 317 |
def g(): |
| 318 |
yield 1 |
| 319 |
self.assertEqual(d.fromkeys(g()), {1:None}) |
| 320 |
self.assertRaises(TypeError, {}.fromkeys, 3) |
| 321 |
class dictlike(dict): pass |
| 322 |
self.assertEqual(dictlike.fromkeys('a'), {'a':None}) |
| 323 |
self.assertEqual(dictlike().fromkeys('a'), {'a':None}) |
| 324 |
self.assertIsInstance(dictlike.fromkeys('a'), dictlike) |
| 325 |
self.assertIsInstance(dictlike().fromkeys('a'), dictlike) |
| 326 |
class mydict(dict): |
| 327 |
def __new__(cls): |
| 328 |
return collections.UserDict() |
| 329 |
ud = mydict.fromkeys('ab') |
| 330 |
self.assertEqual(ud, {'a':None, 'b':None}) |
| 331 |
self.assertIsInstance(ud, collections.UserDict) |
| 332 |
self.assertRaises(TypeError, dict.fromkeys) |
| 333 |
|
| 334 |
class Exc(Exception): pass |
| 335 |
|
| 336 |
class baddict1(dict): |
| 337 |
def __init__(self): |
| 338 |
raise Exc() |
| 339 |
|
| 340 |
self.assertRaises(Exc, baddict1.fromkeys, [1]) |
| 341 |
|
| 342 |
class BadSeq(object): |
| 343 |
def __iter__(self): |
| 344 |
return self |
| 345 |
def __next__(self): |
| 346 |
raise Exc() |
| 347 |
|
| 348 |
self.assertRaises(Exc, dict.fromkeys, BadSeq()) |
| 349 |
|
| 350 |
class baddict2(dict): |
| 351 |
def __setitem__(self, key, value): |
| 352 |
raise Exc() |
| 353 |
|
| 354 |
self.assertRaises(Exc, baddict2.fromkeys, [1]) |
| 355 |
|
| 356 |
# test fast path for dictionary inputs |
| 357 |
res = dict(zip(range(6), [0]*6)) |
| 358 |
d = dict(zip(range(6), range(6))) |
| 359 |
self.assertEqual(dict.fromkeys(d, 0), res) |
| 360 |
# test fast path for set inputs |
| 361 |
d = set(range(6)) |
| 362 |
self.assertEqual(dict.fromkeys(d, 0), res) |
| 363 |
# test slow path for other iterable inputs |
| 364 |
d = list(range(6)) |
| 365 |
self.assertEqual(dict.fromkeys(d, 0), res) |
| 366 |
|
| 367 |
# test fast path when object's constructor returns large non-empty dict |
| 368 |
class baddict3(dict): |
| 369 |
def __new__(cls): |
| 370 |
return d |
| 371 |
d = {i : i for i in range(1000)} |
| 372 |
res = d.copy() |
| 373 |
res.update(a=None, b=None, c=None) |
| 374 |
self.assertEqual(baddict3.fromkeys({"a", "b", "c"}), res) |
| 375 |
|
| 376 |
# test slow path when object is a proper subclass of dict |
| 377 |
class baddict4(dict): |
| 378 |
def __init__(self): |
| 379 |
dict.__init__(self, d) |
| 380 |
d = {i : i for i in range(1000)} |
| 381 |
res = d.copy() |
| 382 |
res.update(a=None, b=None, c=None) |
| 383 |
self.assertEqual(baddict4.fromkeys({"a", "b", "c"}), res) |
| 384 |
|
| 385 |
def test_copy(self): |
| 386 |
d = {1: 1, 2: 2, 3: 3} |
| 387 |
self.assertIsNot(d.copy(), d) |
| 388 |
self.assertEqual(d.copy(), d) |
| 389 |
self.assertEqual(d.copy(), {1: 1, 2: 2, 3: 3}) |
| 390 |
|
| 391 |
copy = d.copy() |
| 392 |
d[4] = 4 |
| 393 |
self.assertNotEqual(copy, d) |
| 394 |
|
| 395 |
self.assertEqual({}.copy(), {}) |
| 396 |
self.assertRaises(TypeError, d.copy, None) |
| 397 |
|
| 398 |
def test_copy_fuzz(self): |
| 399 |
for dict_size in [10, 100, 1000, 10000, 100000]: |
| 400 |
dict_size = random.randrange( |
| 401 |
dict_size // 2, dict_size + dict_size // 2) |
| 402 |
with self.subTest(dict_size=dict_size): |
| 403 |
d = {} |
| 404 |
for i in range(dict_size): |
| 405 |
d[i] = i |
| 406 |
|
| 407 |
d2 = d.copy() |
| 408 |
self.assertIsNot(d2, d) |
| 409 |
self.assertEqual(d, d2) |
| 410 |
d2['key'] = 'value' |
| 411 |
self.assertNotEqual(d, d2) |
| 412 |
self.assertEqual(len(d2), len(d) + 1) |
| 413 |
|
| 414 |
def test_copy_maintains_tracking(self): |
| 415 |
class A: |
| 416 |
pass |
| 417 |
|
| 418 |
key = A() |
| 419 |
|
| 420 |
for d in ({}, {'a': 1}, {key: 'val'}): |
| 421 |
d2 = d.copy() |
| 422 |
self.assertEqual(gc.is_tracked(d), gc.is_tracked(d2)) |
| 423 |
|
| 424 |
def test_copy_noncompact(self): |
| 425 |
# Dicts don't compact themselves on del/pop operations. |
| 426 |
# Copy will use a slow merging strategy that produces |
| 427 |
# a compacted copy when roughly 33% of dict is a non-used |
| 428 |
# keys-space (to optimize memory footprint). |
| 429 |
# In this test we want to hit the slow/compacting |
| 430 |
# branch of dict.copy() and make sure it works OK. |
| 431 |
d = {k: k for k in range(1000)} |
| 432 |
for k in range(950): |
| 433 |
del d[k] |
| 434 |
d2 = d.copy() |
| 435 |
self.assertEqual(d2, d) |
| 436 |
|
| 437 |
def test_get(self): |
| 438 |
d = {} |
| 439 |
self.assertIs(d.get('c'), None) |
| 440 |
self.assertEqual(d.get('c', 3), 3) |
| 441 |
d = {'a': 1, 'b': 2} |
| 442 |
self.assertIs(d.get('c'), None) |
| 443 |
self.assertEqual(d.get('c', 3), 3) |
| 444 |
self.assertEqual(d.get('a'), 1) |
| 445 |
self.assertEqual(d.get('a', 3), 1) |
| 446 |
self.assertRaises(TypeError, d.get) |
| 447 |
self.assertRaises(TypeError, d.get, None, None, None) |
| 448 |
|
| 449 |
def test_setdefault(self): |
| 450 |
# dict.setdefault() |
| 451 |
d = {} |
| 452 |
self.assertIs(d.setdefault('key0'), None) |
| 453 |
d.setdefault('key0', []) |
| 454 |
self.assertIs(d.setdefault('key0'), None) |
| 455 |
d.setdefault('key', []).append(3) |
| 456 |
self.assertEqual(d['key'][0], 3) |
| 457 |
d.setdefault('key', []).append(4) |
| 458 |
self.assertEqual(len(d['key']), 2) |
| 459 |
self.assertRaises(TypeError, d.setdefault) |
| 460 |
|
| 461 |
class Exc(Exception): pass |
| 462 |
|
| 463 |
class BadHash(object): |
| 464 |
fail = False |
| 465 |
def __hash__(self): |
| 466 |
if self.fail: |
| 467 |
raise Exc() |
| 468 |
else: |
| 469 |
return 42 |
| 470 |
|
| 471 |
x = BadHash() |
| 472 |
d[x] = 42 |
| 473 |
x.fail = True |
| 474 |
self.assertRaises(Exc, d.setdefault, x, []) |
| 475 |
|
| 476 |
def test_setdefault_atomic(self): |
| 477 |
# Issue #13521: setdefault() calls __hash__ and __eq__ only once. |
| 478 |
class Hashed(object): |
| 479 |
def __init__(self): |
| 480 |
self.hash_count = 0 |
| 481 |
self.eq_count = 0 |
| 482 |
def __hash__(self): |
| 483 |
self.hash_count += 1 |
| 484 |
return 42 |
| 485 |
def __eq__(self, other): |
| 486 |
self.eq_count += 1 |
| 487 |
return id(self) == id(other) |
| 488 |
hashed1 = Hashed() |
| 489 |
y = {hashed1: 5} |
| 490 |
hashed2 = Hashed() |
| 491 |
y.setdefault(hashed2, []) |
| 492 |
self.assertEqual(hashed1.hash_count, 1) |
| 493 |
self.assertEqual(hashed2.hash_count, 1) |
| 494 |
self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1) |
| 495 |
|
| 496 |
def test_setitem_atomic_at_resize(self): |
| 497 |
class Hashed(object): |
| 498 |
def __init__(self): |
| 499 |
self.hash_count = 0 |
| 500 |
self.eq_count = 0 |
| 501 |
def __hash__(self): |
| 502 |
self.hash_count += 1 |
| 503 |
return 42 |
| 504 |
def __eq__(self, other): |
| 505 |
self.eq_count += 1 |
| 506 |
return id(self) == id(other) |
| 507 |
hashed1 = Hashed() |
| 508 |
# 5 items |
| 509 |
y = {hashed1: 5, 0: 0, 1: 1, 2: 2, 3: 3} |
| 510 |
hashed2 = Hashed() |
| 511 |
# 6th item forces a resize |
| 512 |
y[hashed2] = [] |
| 513 |
self.assertEqual(hashed1.hash_count, 1) |
| 514 |
self.assertEqual(hashed2.hash_count, 1) |
| 515 |
self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1) |
| 516 |
|
| 517 |
def test_popitem(self): |
| 518 |
# dict.popitem() |
| 519 |
for copymode in -1, +1: |
| 520 |
# -1: b has same structure as a |
| 521 |
# +1: b is a.copy() |
| 522 |
for log2size in range(12): |
| 523 |
size = 2**log2size |
| 524 |
a = {} |
| 525 |
b = {} |
| 526 |
for i in range(size): |
| 527 |
a[repr(i)] = i |
| 528 |
if copymode < 0: |
| 529 |
b[repr(i)] = i |
| 530 |
if copymode > 0: |
| 531 |
b = a.copy() |
| 532 |
for i in range(size): |
| 533 |
ka, va = ta = a.popitem() |
| 534 |
self.assertEqual(va, int(ka)) |
| 535 |
kb, vb = tb = b.popitem() |
| 536 |
self.assertEqual(vb, int(kb)) |
| 537 |
self.assertFalse(copymode < 0 and ta != tb) |
| 538 |
self.assertFalse(a) |
| 539 |
self.assertFalse(b) |
| 540 |
|
| 541 |
d = {} |
| 542 |
self.assertRaises(KeyError, d.popitem) |
| 543 |
|
| 544 |
def test_pop(self): |
| 545 |
# Tests for pop with specified key |
| 546 |
d = {} |
| 547 |
k, v = 'abc', 'def' |
| 548 |
d[k] = v |
| 549 |
self.assertRaises(KeyError, d.pop, 'ghi') |
| 550 |
|
| 551 |
self.assertEqual(d.pop(k), v) |
| 552 |
self.assertEqual(len(d), 0) |
| 553 |
|
| 554 |
self.assertRaises(KeyError, d.pop, k) |
| 555 |
|
| 556 |
self.assertEqual(d.pop(k, v), v) |
| 557 |
d[k] = v |
| 558 |
self.assertEqual(d.pop(k, 1), v) |
| 559 |
|
| 560 |
self.assertRaises(TypeError, d.pop) |
| 561 |
|
| 562 |
class Exc(Exception): pass |
| 563 |
|
| 564 |
class BadHash(object): |
| 565 |
fail = False |
| 566 |
def __hash__(self): |
| 567 |
if self.fail: |
| 568 |
raise Exc() |
| 569 |
else: |
| 570 |
return 42 |
| 571 |
|
| 572 |
x = BadHash() |
| 573 |
d[x] = 42 |
| 574 |
x.fail = True |
| 575 |
self.assertRaises(Exc, d.pop, x) |
| 576 |
|
| 577 |
def test_mutating_iteration(self): |
| 578 |
# changing dict size during iteration |
| 579 |
d = {} |
| 580 |
d[1] = 1 |
| 581 |
with self.assertRaises(RuntimeError): |
| 582 |
for i in d: |
| 583 |
d[i+1] = 1 |
| 584 |
|
| 585 |
def test_mutating_iteration_delete(self): |
| 586 |
# change dict content during iteration |
| 587 |
d = {} |
| 588 |
d[0] = 0 |
| 589 |
with self.assertRaises(RuntimeError): |
| 590 |
for i in d: |
| 591 |
del d[0] |
| 592 |
d[0] = 0 |
| 593 |
|
| 594 |
def test_mutating_iteration_delete_over_values(self): |
| 595 |
# change dict content during iteration |
| 596 |
d = {} |
| 597 |
d[0] = 0 |
| 598 |
with self.assertRaises(RuntimeError): |
| 599 |
for i in d.values(): |
| 600 |
del d[0] |
| 601 |
d[0] = 0 |
| 602 |
|
| 603 |
def test_mutating_iteration_delete_over_items(self): |
| 604 |
# change dict content during iteration |
| 605 |
d = {} |
| 606 |
d[0] = 0 |
| 607 |
with self.assertRaises(RuntimeError): |
| 608 |
for i in d.items(): |
| 609 |
del d[0] |
| 610 |
d[0] = 0 |
| 611 |
|
| 612 |
def test_mutating_lookup(self): |
| 613 |
# changing dict during a lookup (issue #14417) |
| 614 |
class NastyKey: |
| 615 |
mutate_dict = None |
| 616 |
|
| 617 |
def __init__(self, value): |
| 618 |
self.value = value |
| 619 |
|
| 620 |
def __hash__(self): |
| 621 |
# hash collision! |
| 622 |
return 1 |
| 623 |
|
| 624 |
def __eq__(self, other): |
| 625 |
if NastyKey.mutate_dict: |
| 626 |
mydict, key = NastyKey.mutate_dict |
| 627 |
NastyKey.mutate_dict = None |
| 628 |
del mydict[key] |
| 629 |
return self.value == other.value |
| 630 |
|
| 631 |
key1 = NastyKey(1) |
| 632 |
key2 = NastyKey(2) |
| 633 |
d = {key1: 1} |
| 634 |
NastyKey.mutate_dict = (d, key1) |
| 635 |
d[key2] = 2 |
| 636 |
self.assertEqual(d, {key2: 2}) |
| 637 |
|
| 638 |
def test_repr(self): |
| 639 |
d = {} |
| 640 |
self.assertEqual(repr(d), '{}') |
| 641 |
d[1] = 2 |
| 642 |
self.assertEqual(repr(d), '{1: 2}') |
| 643 |
d = {} |
| 644 |
d[1] = d |
| 645 |
self.assertEqual(repr(d), '{1: {...}}') |
| 646 |
|
| 647 |
class Exc(Exception): pass |
| 648 |
|
| 649 |
class BadRepr(object): |
| 650 |
def __repr__(self): |
| 651 |
raise Exc() |
| 652 |
|
| 653 |
d = {1: BadRepr()} |
| 654 |
self.assertRaises(Exc, repr, d) |
| 655 |
|
| 656 |
def test_repr_deep(self): |
| 657 |
d = {} |
| 658 |
for i in range(get_c_recursion_limit() + 1): |
| 659 |
d = {1: d} |
| 660 |
self.assertRaises(RecursionError, repr, d) |
| 661 |
|
| 662 |
def test_eq(self): |
| 663 |
self.assertEqual({}, {}) |
| 664 |
self.assertEqual({1: 2}, {1: 2}) |
| 665 |
|
| 666 |
class Exc(Exception): pass |
| 667 |
|
| 668 |
class BadCmp(object): |
| 669 |
def __eq__(self, other): |
| 670 |
raise Exc() |
| 671 |
def __hash__(self): |
| 672 |
return 1 |
| 673 |
|
| 674 |
d1 = {BadCmp(): 1} |
| 675 |
d2 = {1: 1} |
| 676 |
|
| 677 |
with self.assertRaises(Exc): |
| 678 |
d1 == d2 |
| 679 |
|
| 680 |
def test_keys_contained(self): |
| 681 |
self.helper_keys_contained(lambda x: x.keys()) |
| 682 |
self.helper_keys_contained(lambda x: x.items()) |
| 683 |
|
| 684 |
def helper_keys_contained(self, fn): |
| 685 |
# Test rich comparisons against dict key views, which should behave the |
| 686 |
# same as sets. |
| 687 |
empty = fn(dict()) |
| 688 |
empty2 = fn(dict()) |
| 689 |
smaller = fn({1:1, 2:2}) |
| 690 |
larger = fn({1:1, 2:2, 3:3}) |
| 691 |
larger2 = fn({1:1, 2:2, 3:3}) |
| 692 |
larger3 = fn({4:1, 2:2, 3:3}) |
| 693 |
|
| 694 |
self.assertTrue(smaller < larger) |
| 695 |
self.assertTrue(smaller <= larger) |
| 696 |
self.assertTrue(larger > smaller) |
| 697 |
self.assertTrue(larger >= smaller) |
| 698 |
|
| 699 |
self.assertFalse(smaller >= larger) |
| 700 |
self.assertFalse(smaller > larger) |
| 701 |
self.assertFalse(larger <= smaller) |
| 702 |
self.assertFalse(larger < smaller) |
| 703 |
|
| 704 |
self.assertFalse(smaller < larger3) |
| 705 |
self.assertFalse(smaller <= larger3) |
| 706 |
self.assertFalse(larger3 > smaller) |
| 707 |
self.assertFalse(larger3 >= smaller) |
| 708 |
|
| 709 |
# Inequality strictness |
| 710 |
self.assertTrue(larger2 >= larger) |
| 711 |
self.assertTrue(larger2 <= larger) |
| 712 |
self.assertFalse(larger2 > larger) |
| 713 |
self.assertFalse(larger2 < larger) |
| 714 |
|
| 715 |
self.assertTrue(larger == larger2) |
| 716 |
self.assertTrue(smaller != larger) |
| 717 |
|
| 718 |
# There is an optimization on the zero-element case. |
| 719 |
self.assertTrue(empty == empty2) |
| 720 |
self.assertFalse(empty != empty2) |
| 721 |
self.assertFalse(empty == smaller) |
| 722 |
self.assertTrue(empty != smaller) |
| 723 |
|
| 724 |
# With the same size, an elementwise compare happens |
| 725 |
self.assertTrue(larger != larger3) |
| 726 |
self.assertFalse(larger == larger3) |
| 727 |
|
| 728 |
def test_errors_in_view_containment_check(self): |
| 729 |
class C: |
| 730 |
def __eq__(self, other): |
| 731 |
raise RuntimeError |
| 732 |
|
| 733 |
d1 = {1: C()} |
| 734 |
d2 = {1: C()} |
| 735 |
with self.assertRaises(RuntimeError): |
| 736 |
d1.items() == d2.items() |
| 737 |
with self.assertRaises(RuntimeError): |
| 738 |
d1.items() != d2.items() |
| 739 |
with self.assertRaises(RuntimeError): |
| 740 |
d1.items() <= d2.items() |
| 741 |
with self.assertRaises(RuntimeError): |
| 742 |
d1.items() >= d2.items() |
| 743 |
|
| 744 |
d3 = {1: C(), 2: C()} |
| 745 |
with self.assertRaises(RuntimeError): |
| 746 |
d2.items() < d3.items() |
| 747 |
with self.assertRaises(RuntimeError): |
| 748 |
d3.items() > d2.items() |
| 749 |
|
| 750 |
def test_dictview_set_operations_on_keys(self): |
| 751 |
k1 = {1:1, 2:2}.keys() |
| 752 |
k2 = {1:1, 2:2, 3:3}.keys() |
| 753 |
k3 = {4:4}.keys() |
| 754 |
|
| 755 |
self.assertEqual(k1 - k2, set()) |
| 756 |
self.assertEqual(k1 - k3, {1,2}) |
| 757 |
self.assertEqual(k2 - k1, {3}) |
| 758 |
self.assertEqual(k3 - k1, {4}) |
| 759 |
self.assertEqual(k1 & k2, {1,2}) |
| 760 |
self.assertEqual(k1 & k3, set()) |
| 761 |
self.assertEqual(k1 | k2, {1,2,3}) |
| 762 |
self.assertEqual(k1 ^ k2, {3}) |
| 763 |
self.assertEqual(k1 ^ k3, {1,2,4}) |
| 764 |
|
| 765 |
def test_dictview_set_operations_on_items(self): |
| 766 |
k1 = {1:1, 2:2}.items() |
| 767 |
k2 = {1:1, 2:2, 3:3}.items() |
| 768 |
k3 = {4:4}.items() |
| 769 |
|
| 770 |
self.assertEqual(k1 - k2, set()) |
| 771 |
self.assertEqual(k1 - k3, {(1,1), (2,2)}) |
| 772 |
self.assertEqual(k2 - k1, {(3,3)}) |
| 773 |
self.assertEqual(k3 - k1, {(4,4)}) |
| 774 |
self.assertEqual(k1 & k2, {(1,1), (2,2)}) |
| 775 |
self.assertEqual(k1 & k3, set()) |
| 776 |
self.assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) |
| 777 |
self.assertEqual(k1 ^ k2, {(3,3)}) |
| 778 |
self.assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) |
| 779 |
|
| 780 |
def test_items_symmetric_difference(self): |
| 781 |
rr = random.randrange |
| 782 |
for _ in range(100): |
| 783 |
left = {x:rr(3) for x in range(20) if rr(2)} |
| 784 |
right = {x:rr(3) for x in range(20) if rr(2)} |
| 785 |
with self.subTest(left=left, right=right): |
| 786 |
expected = set(left.items()) ^ set(right.items()) |
| 787 |
actual = left.items() ^ right.items() |
| 788 |
self.assertEqual(actual, expected) |
| 789 |
|
| 790 |
def test_dictview_mixed_set_operations(self): |
| 791 |
# Just a few for .keys() |
| 792 |
self.assertTrue({1:1}.keys() == {1}) |
| 793 |
self.assertTrue({1} == {1:1}.keys()) |
| 794 |
self.assertEqual({1:1}.keys() | {2}, {1, 2}) |
| 795 |
self.assertEqual({2} | {1:1}.keys(), {1, 2}) |
| 796 |
# And a few for .items() |
| 797 |
self.assertTrue({1:1}.items() == {(1,1)}) |
| 798 |
self.assertTrue({(1,1)} == {1:1}.items()) |
| 799 |
self.assertEqual({1:1}.items() | {2}, {(1,1), 2}) |
| 800 |
self.assertEqual({2} | {1:1}.items(), {(1,1), 2}) |
| 801 |
|
| 802 |
def test_missing(self): |
| 803 |
# Make sure dict doesn't have a __missing__ method |
| 804 |
self.assertFalse(hasattr(dict, "__missing__")) |
| 805 |
self.assertFalse(hasattr({}, "__missing__")) |
| 806 |
# Test several cases: |
| 807 |
# (D) subclass defines __missing__ method returning a value |
| 808 |
# (E) subclass defines __missing__ method raising RuntimeError |
| 809 |
# (F) subclass sets __missing__ instance variable (no effect) |
| 810 |
# (G) subclass doesn't define __missing__ at all |
| 811 |
class D(dict): |
| 812 |
def __missing__(self, key): |
| 813 |
return 42 |
| 814 |
d = D({1: 2, 3: 4}) |
| 815 |
self.assertEqual(d[1], 2) |
| 816 |
self.assertEqual(d[3], 4) |
| 817 |
self.assertNotIn(2, d) |
| 818 |
self.assertNotIn(2, d.keys()) |
| 819 |
self.assertEqual(d[2], 42) |
| 820 |
|
| 821 |
class E(dict): |
| 822 |
def __missing__(self, key): |
| 823 |
raise RuntimeError(key) |
| 824 |
e = E() |
| 825 |
with self.assertRaises(RuntimeError) as c: |
| 826 |
e[42] |
| 827 |
self.assertEqual(c.exception.args, (42,)) |
| 828 |
|
| 829 |
class F(dict): |
| 830 |
def __init__(self): |
| 831 |
# An instance variable __missing__ should have no effect |
| 832 |
self.__missing__ = lambda key: None |
| 833 |
f = F() |
| 834 |
with self.assertRaises(KeyError) as c: |
| 835 |
f[42] |
| 836 |
self.assertEqual(c.exception.args, (42,)) |
| 837 |
|
| 838 |
class G(dict): |
| 839 |
pass |
| 840 |
g = G() |
| 841 |
with self.assertRaises(KeyError) as c: |
| 842 |
g[42] |
| 843 |
self.assertEqual(c.exception.args, (42,)) |
| 844 |
|
| 845 |
def test_tuple_keyerror(self): |
| 846 |
# SF #1576657 |
| 847 |
d = {} |
| 848 |
with self.assertRaises(KeyError) as c: |
| 849 |
d[(1,)] |
| 850 |
self.assertEqual(c.exception.args, ((1,),)) |
| 851 |
|
| 852 |
def test_bad_key(self): |
| 853 |
# Dictionary lookups should fail if __eq__() raises an exception. |
| 854 |
class CustomException(Exception): |
| 855 |
pass |
| 856 |
|
| 857 |
class BadDictKey: |
| 858 |
def __hash__(self): |
| 859 |
return hash(self.__class__) |
| 860 |
|
| 861 |
def __eq__(self, other): |
| 862 |
if isinstance(other, self.__class__): |
| 863 |
raise CustomException |
| 864 |
return other |
| 865 |
|
| 866 |
d = {} |
| 867 |
x1 = BadDictKey() |
| 868 |
x2 = BadDictKey() |
| 869 |
d[x1] = 1 |
| 870 |
for stmt in ['d[x2] = 2', |
| 871 |
'z = d[x2]', |
| 872 |
'x2 in d', |
| 873 |
'd.get(x2)', |
| 874 |
'd.setdefault(x2, 42)', |
| 875 |
'd.pop(x2)', |
| 876 |
'd.update({x2: 2})']: |
| 877 |
with self.assertRaises(CustomException): |
| 878 |
exec(stmt, locals()) |
| 879 |
|
| 880 |
def test_resize1(self): |
| 881 |
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development. |
| 882 |
# This version got an assert failure in debug build, infinite loop in |
| 883 |
# release build. Unfortunately, provoking this kind of stuff requires |
| 884 |
# a mix of inserts and deletes hitting exactly the right hash codes in |
| 885 |
# exactly the right order, and I can't think of a randomized approach |
| 886 |
# that would be *likely* to hit a failing case in reasonable time. |
| 887 |
|
| 888 |
d = {} |
| 889 |
for i in range(5): |
| 890 |
d[i] = i |
| 891 |
for i in range(5): |
| 892 |
del d[i] |
| 893 |
for i in range(5, 9): # i==8 was the problem |
| 894 |
d[i] = i |
| 895 |
|
| 896 |
def test_resize2(self): |
| 897 |
# Another dict resizing bug (SF bug #1456209). |
| 898 |
# This caused Segmentation faults or Illegal instructions. |
| 899 |
|
| 900 |
class X(object): |
| 901 |
def __hash__(self): |
| 902 |
return 5 |
| 903 |
def __eq__(self, other): |
| 904 |
if resizing: |
| 905 |
d.clear() |
| 906 |
return False |
| 907 |
d = {} |
| 908 |
resizing = False |
| 909 |
d[X()] = 1 |
| 910 |
d[X()] = 2 |
| 911 |
d[X()] = 3 |
| 912 |
d[X()] = 4 |
| 913 |
d[X()] = 5 |
| 914 |
# now trigger a resize |
| 915 |
resizing = True |
| 916 |
d[9] = 6 |
| 917 |
|
| 918 |
def test_empty_presized_dict_in_freelist(self): |
| 919 |
# Bug #3537: if an empty but presized dict with a size larger |
| 920 |
# than 7 was in the freelist, it triggered an assertion failure |
| 921 |
with self.assertRaises(ZeroDivisionError): |
| 922 |
d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None, |
| 923 |
'f': None, 'g': None, 'h': None} |
| 924 |
d = {} |
| 925 |
|
| 926 |
def test_container_iterator(self): |
| 927 |
# Bug #3680: tp_traverse was not implemented for dictiter and |
| 928 |
# dictview objects. |
| 929 |
class C(object): |
| 930 |
pass |
| 931 |
views = (dict.items, dict.values, dict.keys) |
| 932 |
for v in views: |
| 933 |
obj = C() |
| 934 |
ref = weakref.ref(obj) |
| 935 |
container = {obj: 1} |
| 936 |
obj.v = v(container) |
| 937 |
obj.x = iter(obj.v) |
| 938 |
del obj, container |
| 939 |
gc.collect() |
| 940 |
self.assertIs(ref(), None, "Cycle was not collected") |
| 941 |
|
| 942 |
def _not_tracked(self, t): |
| 943 |
# Nested containers can take several collections to untrack |
| 944 |
gc.collect() |
| 945 |
gc.collect() |
| 946 |
self.assertFalse(gc.is_tracked(t), t) |
| 947 |
|
| 948 |
def _tracked(self, t): |
| 949 |
self.assertTrue(gc.is_tracked(t), t) |
| 950 |
gc.collect() |
| 951 |
gc.collect() |
| 952 |
self.assertTrue(gc.is_tracked(t), t) |
| 953 |
|
| 954 |
def test_string_keys_can_track_values(self): |
| 955 |
# Test that this doesn't leak. |
| 956 |
for i in range(10): |
| 957 |
d = {} |
| 958 |
for j in range(10): |
| 959 |
d[str(j)] = j |
| 960 |
d["foo"] = d |
| 961 |
|
| 962 |
@support.cpython_only |
| 963 |
def test_track_literals(self): |
| 964 |
# Test GC-optimization of dict literals |
| 965 |
x, y, z, w = 1.5, "a", (1, None), [] |
| 966 |
|
| 967 |
self._not_tracked({}) |
| 968 |
self._not_tracked({x:(), y:x, z:1}) |
| 969 |
self._not_tracked({1: "a", "b": 2}) |
| 970 |
self._not_tracked({1: 2, (None, True, False, ()): int}) |
| 971 |
self._not_tracked({1: object()}) |
| 972 |
|
| 973 |
# Dicts with mutable elements are always tracked, even if those |
| 974 |
# elements are not tracked right now. |
| 975 |
self._tracked({1: []}) |
| 976 |
self._tracked({1: ([],)}) |
| 977 |
self._tracked({1: {}}) |
| 978 |
self._tracked({1: set()}) |
| 979 |
|
| 980 |
@support.cpython_only |
| 981 |
def test_track_dynamic(self): |
| 982 |
# Test GC-optimization of dynamically-created dicts |
| 983 |
class MyObject(object): |
| 984 |
pass |
| 985 |
x, y, z, w, o = 1.5, "a", (1, object()), [], MyObject() |
| 986 |
|
| 987 |
d = dict() |
| 988 |
self._not_tracked(d) |
| 989 |
d[1] = "a" |
| 990 |
self._not_tracked(d) |
| 991 |
d[y] = 2 |
| 992 |
self._not_tracked(d) |
| 993 |
d[z] = 3 |
| 994 |
self._not_tracked(d) |
| 995 |
self._not_tracked(d.copy()) |
| 996 |
d[4] = w |
| 997 |
self._tracked(d) |
| 998 |
self._tracked(d.copy()) |
| 999 |
d[4] = None |
| 1000 |
self._not_tracked(d) |
| 1001 |
self._not_tracked(d.copy()) |
| 1002 |
|
| 1003 |
# dd isn't tracked right now, but it may mutate and therefore d |
| 1004 |
# which contains it must be tracked. |
| 1005 |
d = dict() |
| 1006 |
dd = dict() |
| 1007 |
d[1] = dd |
| 1008 |
self._not_tracked(dd) |
| 1009 |
self._tracked(d) |
| 1010 |
dd[1] = d |
| 1011 |
self._tracked(dd) |
| 1012 |
|
| 1013 |
d = dict.fromkeys([x, y, z]) |
| 1014 |
self._not_tracked(d) |
| 1015 |
dd = dict() |
| 1016 |
dd.update(d) |
| 1017 |
self._not_tracked(dd) |
| 1018 |
d = dict.fromkeys([x, y, z, o]) |
| 1019 |
self._tracked(d) |
| 1020 |
dd = dict() |
| 1021 |
dd.update(d) |
| 1022 |
self._tracked(dd) |
| 1023 |
|
| 1024 |
d = dict(x=x, y=y, z=z) |
| 1025 |
self._not_tracked(d) |
| 1026 |
d = dict(x=x, y=y, z=z, w=w) |
| 1027 |
self._tracked(d) |
| 1028 |
d = dict() |
| 1029 |
d.update(x=x, y=y, z=z) |
| 1030 |
self._not_tracked(d) |
| 1031 |
d.update(w=w) |
| 1032 |
self._tracked(d) |
| 1033 |
|
| 1034 |
d = dict([(x, y), (z, 1)]) |
| 1035 |
self._not_tracked(d) |
| 1036 |
d = dict([(x, y), (z, w)]) |
| 1037 |
self._tracked(d) |
| 1038 |
d = dict() |
| 1039 |
d.update([(x, y), (z, 1)]) |
| 1040 |
self._not_tracked(d) |
| 1041 |
d.update([(x, y), (z, w)]) |
| 1042 |
self._tracked(d) |
| 1043 |
|
| 1044 |
@support.cpython_only |
| 1045 |
def test_track_subtypes(self): |
| 1046 |
# Dict subtypes are always tracked |
| 1047 |
class MyDict(dict): |
| 1048 |
pass |
| 1049 |
self._tracked(MyDict()) |
| 1050 |
|
| 1051 |
@support.cpython_only |
| 1052 |
def test_track_lazy_instance_dicts(self): |
| 1053 |
class C: |
| 1054 |
pass |
| 1055 |
o = C() |
| 1056 |
d = o.__dict__ |
| 1057 |
self._not_tracked(d) |
| 1058 |
o.untracked = 42 |
| 1059 |
self._not_tracked(d) |
| 1060 |
o.tracked = [] |
| 1061 |
self._tracked(d) |
| 1062 |
|
| 1063 |
def make_shared_key_dict(self, n): |
| 1064 |
class C: |
| 1065 |
pass |
| 1066 |
|
| 1067 |
dicts = [] |
| 1068 |
for i in range(n): |
| 1069 |
a = C() |
| 1070 |
a.x, a.y, a.z = 1, 2, 3 |
| 1071 |
dicts.append(a.__dict__) |
| 1072 |
|
| 1073 |
return dicts |
| 1074 |
|
| 1075 |
@support.cpython_only |
| 1076 |
def test_splittable_setdefault(self): |
| 1077 |
"""split table must keep correct insertion |
| 1078 |
order when attributes are adding using setdefault()""" |
| 1079 |
a, b = self.make_shared_key_dict(2) |
| 1080 |
|
| 1081 |
a['a'] = 1 |
| 1082 |
size_a = sys.getsizeof(a) |
| 1083 |
a['b'] = 2 |
| 1084 |
b.setdefault('b', 2) |
| 1085 |
size_b = sys.getsizeof(b) |
| 1086 |
b['a'] = 1 |
| 1087 |
|
| 1088 |
self.assertEqual(list(a), ['x', 'y', 'z', 'a', 'b']) |
| 1089 |
self.assertEqual(list(b), ['x', 'y', 'z', 'b', 'a']) |
| 1090 |
|
| 1091 |
@support.cpython_only |
| 1092 |
def test_splittable_del(self): |
| 1093 |
"""split table must be combined when del d[k]""" |
| 1094 |
a, b = self.make_shared_key_dict(2) |
| 1095 |
|
| 1096 |
orig_size = sys.getsizeof(a) |
| 1097 |
|
| 1098 |
del a['y'] # split table is combined |
| 1099 |
with self.assertRaises(KeyError): |
| 1100 |
del a['y'] |
| 1101 |
|
| 1102 |
self.assertEqual(list(a), ['x', 'z']) |
| 1103 |
self.assertEqual(list(b), ['x', 'y', 'z']) |
| 1104 |
|
| 1105 |
# Two dicts have different insertion order. |
| 1106 |
a['y'] = 42 |
| 1107 |
self.assertEqual(list(a), ['x', 'z', 'y']) |
| 1108 |
self.assertEqual(list(b), ['x', 'y', 'z']) |
| 1109 |
|
| 1110 |
@support.cpython_only |
| 1111 |
def test_splittable_pop(self): |
| 1112 |
a, b = self.make_shared_key_dict(2) |
| 1113 |
|
| 1114 |
a.pop('y') |
| 1115 |
with self.assertRaises(KeyError): |
| 1116 |
a.pop('y') |
| 1117 |
|
| 1118 |
self.assertEqual(list(a), ['x', 'z']) |
| 1119 |
self.assertEqual(list(b), ['x', 'y', 'z']) |
| 1120 |
|
| 1121 |
# Two dicts have different insertion order. |
| 1122 |
a['y'] = 42 |
| 1123 |
self.assertEqual(list(a), ['x', 'z', 'y']) |
| 1124 |
self.assertEqual(list(b), ['x', 'y', 'z']) |
| 1125 |
|
| 1126 |
@support.cpython_only |
| 1127 |
def test_splittable_pop_pending(self): |
| 1128 |
"""pop a pending key in a split table should not crash""" |
| 1129 |
a, b = self.make_shared_key_dict(2) |
| 1130 |
|
| 1131 |
a['a'] = 4 |
| 1132 |
with self.assertRaises(KeyError): |
| 1133 |
b.pop('a') |
| 1134 |
|
| 1135 |
@support.cpython_only |
| 1136 |
def test_splittable_popitem(self): |
| 1137 |
"""split table must be combined when d.popitem()""" |
| 1138 |
a, b = self.make_shared_key_dict(2) |
| 1139 |
|
| 1140 |
orig_size = sys.getsizeof(a) |
| 1141 |
|
| 1142 |
item = a.popitem() # split table is combined |
| 1143 |
self.assertEqual(item, ('z', 3)) |
| 1144 |
with self.assertRaises(KeyError): |
| 1145 |
del a['z'] |
| 1146 |
|
| 1147 |
self.assertGreater(sys.getsizeof(a), orig_size) |
| 1148 |
self.assertEqual(list(a), ['x', 'y']) |
| 1149 |
self.assertEqual(list(b), ['x', 'y', 'z']) |
| 1150 |
|
| 1151 |
@support.cpython_only |
| 1152 |
def test_splittable_update(self): |
| 1153 |
"""dict.update(other) must preserve order in other.""" |
| 1154 |
class C: |
| 1155 |
def __init__(self, order): |
| 1156 |
if order: |
| 1157 |
self.a, self.b, self.c = 1, 2, 3 |
| 1158 |
else: |
| 1159 |
self.c, self.b, self.a = 1, 2, 3 |
| 1160 |
o = C(True) |
| 1161 |
o = C(False) # o.__dict__ has reversed order. |
| 1162 |
self.assertEqual(list(o.__dict__), ["c", "b", "a"]) |
| 1163 |
|
| 1164 |
d = {} |
| 1165 |
d.update(o.__dict__) |
| 1166 |
self.assertEqual(list(d), ["c", "b", "a"]) |
| 1167 |
|
| 1168 |
@support.cpython_only |
| 1169 |
def test_splittable_to_generic_combinedtable(self): |
| 1170 |
"""split table must be correctly resized and converted to generic combined table""" |
| 1171 |
class C: |
| 1172 |
pass |
| 1173 |
|
| 1174 |
a = C() |
| 1175 |
a.x = 1 |
| 1176 |
d = a.__dict__ |
| 1177 |
d[2] = 2 # split table is resized to a generic combined table |
| 1178 |
|
| 1179 |
self.assertEqual(list(d), ['x', 2]) |
| 1180 |
|
| 1181 |
def test_iterator_pickling(self): |
| 1182 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1183 |
data = {1:"a", 2:"b", 3:"c"} |
| 1184 |
it = iter(data) |
| 1185 |
d = pickle.dumps(it, proto) |
| 1186 |
it = pickle.loads(d) |
| 1187 |
self.assertEqual(list(it), list(data)) |
| 1188 |
|
| 1189 |
it = pickle.loads(d) |
| 1190 |
try: |
| 1191 |
drop = next(it) |
| 1192 |
except StopIteration: |
| 1193 |
continue |
| 1194 |
d = pickle.dumps(it, proto) |
| 1195 |
it = pickle.loads(d) |
| 1196 |
del data[drop] |
| 1197 |
self.assertEqual(list(it), list(data)) |
| 1198 |
|
| 1199 |
def test_itemiterator_pickling(self): |
| 1200 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1201 |
data = {1:"a", 2:"b", 3:"c"} |
| 1202 |
# dictviews aren't picklable, only their iterators |
| 1203 |
itorg = iter(data.items()) |
| 1204 |
d = pickle.dumps(itorg, proto) |
| 1205 |
it = pickle.loads(d) |
| 1206 |
# note that the type of the unpickled iterator |
| 1207 |
# is not necessarily the same as the original. It is |
| 1208 |
# merely an object supporting the iterator protocol, yielding |
| 1209 |
# the same objects as the original one. |
| 1210 |
# self.assertEqual(type(itorg), type(it)) |
| 1211 |
self.assertIsInstance(it, collections.abc.Iterator) |
| 1212 |
self.assertEqual(dict(it), data) |
| 1213 |
|
| 1214 |
it = pickle.loads(d) |
| 1215 |
drop = next(it) |
| 1216 |
d = pickle.dumps(it, proto) |
| 1217 |
it = pickle.loads(d) |
| 1218 |
del data[drop[0]] |
| 1219 |
self.assertEqual(dict(it), data) |
| 1220 |
|
| 1221 |
def test_valuesiterator_pickling(self): |
| 1222 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1223 |
data = {1:"a", 2:"b", 3:"c"} |
| 1224 |
# data.values() isn't picklable, only its iterator |
| 1225 |
it = iter(data.values()) |
| 1226 |
d = pickle.dumps(it, proto) |
| 1227 |
it = pickle.loads(d) |
| 1228 |
self.assertEqual(list(it), list(data.values())) |
| 1229 |
|
| 1230 |
it = pickle.loads(d) |
| 1231 |
drop = next(it) |
| 1232 |
d = pickle.dumps(it, proto) |
| 1233 |
it = pickle.loads(d) |
| 1234 |
values = list(it) + [drop] |
| 1235 |
self.assertEqual(sorted(values), sorted(list(data.values()))) |
| 1236 |
|
| 1237 |
def test_reverseiterator_pickling(self): |
| 1238 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1239 |
data = {1:"a", 2:"b", 3:"c"} |
| 1240 |
it = reversed(data) |
| 1241 |
d = pickle.dumps(it, proto) |
| 1242 |
it = pickle.loads(d) |
| 1243 |
self.assertEqual(list(it), list(reversed(data))) |
| 1244 |
|
| 1245 |
it = pickle.loads(d) |
| 1246 |
try: |
| 1247 |
drop = next(it) |
| 1248 |
except StopIteration: |
| 1249 |
continue |
| 1250 |
d = pickle.dumps(it, proto) |
| 1251 |
it = pickle.loads(d) |
| 1252 |
del data[drop] |
| 1253 |
self.assertEqual(list(it), list(reversed(data))) |
| 1254 |
|
| 1255 |
def test_reverseitemiterator_pickling(self): |
| 1256 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1257 |
data = {1:"a", 2:"b", 3:"c"} |
| 1258 |
# dictviews aren't picklable, only their iterators |
| 1259 |
itorg = reversed(data.items()) |
| 1260 |
d = pickle.dumps(itorg, proto) |
| 1261 |
it = pickle.loads(d) |
| 1262 |
# note that the type of the unpickled iterator |
| 1263 |
# is not necessarily the same as the original. It is |
| 1264 |
# merely an object supporting the iterator protocol, yielding |
| 1265 |
# the same objects as the original one. |
| 1266 |
# self.assertEqual(type(itorg), type(it)) |
| 1267 |
self.assertIsInstance(it, collections.abc.Iterator) |
| 1268 |
self.assertEqual(dict(it), data) |
| 1269 |
|
| 1270 |
it = pickle.loads(d) |
| 1271 |
drop = next(it) |
| 1272 |
d = pickle.dumps(it, proto) |
| 1273 |
it = pickle.loads(d) |
| 1274 |
del data[drop[0]] |
| 1275 |
self.assertEqual(dict(it), data) |
| 1276 |
|
| 1277 |
def test_reversevaluesiterator_pickling(self): |
| 1278 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1279 |
data = {1:"a", 2:"b", 3:"c"} |
| 1280 |
# data.values() isn't picklable, only its iterator |
| 1281 |
it = reversed(data.values()) |
| 1282 |
d = pickle.dumps(it, proto) |
| 1283 |
it = pickle.loads(d) |
| 1284 |
self.assertEqual(list(it), list(reversed(data.values()))) |
| 1285 |
|
| 1286 |
it = pickle.loads(d) |
| 1287 |
drop = next(it) |
| 1288 |
d = pickle.dumps(it, proto) |
| 1289 |
it = pickle.loads(d) |
| 1290 |
values = list(it) + [drop] |
| 1291 |
self.assertEqual(sorted(values), sorted(data.values())) |
| 1292 |
|
| 1293 |
def test_instance_dict_getattr_str_subclass(self): |
| 1294 |
class Foo: |
| 1295 |
def __init__(self, msg): |
| 1296 |
self.msg = msg |
| 1297 |
f = Foo('123') |
| 1298 |
class _str(str): |
| 1299 |
pass |
| 1300 |
self.assertEqual(f.msg, getattr(f, _str('msg'))) |
| 1301 |
self.assertEqual(f.msg, f.__dict__[_str('msg')]) |
| 1302 |
|
| 1303 |
def test_object_set_item_single_instance_non_str_key(self): |
| 1304 |
class Foo: pass |
| 1305 |
f = Foo() |
| 1306 |
f.__dict__[1] = 1 |
| 1307 |
f.a = 'a' |
| 1308 |
self.assertEqual(f.__dict__, {1:1, 'a':'a'}) |
| 1309 |
|
| 1310 |
def check_reentrant_insertion(self, mutate): |
| 1311 |
# This object will trigger mutation of the dict when replaced |
| 1312 |
# by another value. Note this relies on refcounting: the test |
| 1313 |
# won't achieve its purpose on fully-GCed Python implementations. |
| 1314 |
class Mutating: |
| 1315 |
def __del__(self): |
| 1316 |
mutate(d) |
| 1317 |
|
| 1318 |
d = {k: Mutating() for k in 'abcdefghijklmnopqr'} |
| 1319 |
for k in list(d): |
| 1320 |
d[k] = k |
| 1321 |
|
| 1322 |
def test_reentrant_insertion(self): |
| 1323 |
# Reentrant insertion shouldn't crash (see issue #22653) |
| 1324 |
def mutate(d): |
| 1325 |
d['b'] = 5 |
| 1326 |
self.check_reentrant_insertion(mutate) |
| 1327 |
|
| 1328 |
def mutate(d): |
| 1329 |
d.update(self.__dict__) |
| 1330 |
d.clear() |
| 1331 |
self.check_reentrant_insertion(mutate) |
| 1332 |
|
| 1333 |
def mutate(d): |
| 1334 |
while d: |
| 1335 |
d.popitem() |
| 1336 |
self.check_reentrant_insertion(mutate) |
| 1337 |
|
| 1338 |
def test_merge_and_mutate(self): |
| 1339 |
class X: |
| 1340 |
def __hash__(self): |
| 1341 |
return 0 |
| 1342 |
|
| 1343 |
def __eq__(self, o): |
| 1344 |
other.clear() |
| 1345 |
return False |
| 1346 |
|
| 1347 |
l = [(i,0) for i in range(1, 1337)] |
| 1348 |
other = dict(l) |
| 1349 |
other[X()] = 0 |
| 1350 |
d = {X(): 0, 1: 1} |
| 1351 |
self.assertRaises(RuntimeError, d.update, other) |
| 1352 |
|
| 1353 |
def test_free_after_iterating(self): |
| 1354 |
support.check_free_after_iterating(self, iter, dict) |
| 1355 |
support.check_free_after_iterating(self, lambda d: iter(d.keys()), dict) |
| 1356 |
support.check_free_after_iterating(self, lambda d: iter(d.values()), dict) |
| 1357 |
support.check_free_after_iterating(self, lambda d: iter(d.items()), dict) |
| 1358 |
|
| 1359 |
def test_equal_operator_modifying_operand(self): |
| 1360 |
# test fix for seg fault reported in bpo-27945 part 3. |
| 1361 |
class X(): |
| 1362 |
def __del__(self): |
| 1363 |
dict_b.clear() |
| 1364 |
|
| 1365 |
def __eq__(self, other): |
| 1366 |
dict_a.clear() |
| 1367 |
return True |
| 1368 |
|
| 1369 |
def __hash__(self): |
| 1370 |
return 13 |
| 1371 |
|
| 1372 |
dict_a = {X(): 0} |
| 1373 |
dict_b = {X(): X()} |
| 1374 |
self.assertTrue(dict_a == dict_b) |
| 1375 |
|
| 1376 |
# test fix for seg fault reported in bpo-38588 part 1. |
| 1377 |
class Y: |
| 1378 |
def __eq__(self, other): |
| 1379 |
dict_d.clear() |
| 1380 |
return True |
| 1381 |
|
| 1382 |
dict_c = {0: Y()} |
| 1383 |
dict_d = {0: set()} |
| 1384 |
self.assertTrue(dict_c == dict_d) |
| 1385 |
|
| 1386 |
def test_fromkeys_operator_modifying_dict_operand(self): |
| 1387 |
# test fix for seg fault reported in issue 27945 part 4a. |
| 1388 |
class X(int): |
| 1389 |
def __hash__(self): |
| 1390 |
return 13 |
| 1391 |
|
| 1392 |
def __eq__(self, other): |
| 1393 |
if len(d) > 1: |
| 1394 |
d.clear() |
| 1395 |
return False |
| 1396 |
|
| 1397 |
d = {} # this is required to exist so that d can be constructed! |
| 1398 |
d = {X(1): 1, X(2): 2} |
| 1399 |
try: |
| 1400 |
dict.fromkeys(d) # shouldn't crash |
| 1401 |
except RuntimeError: # implementation defined |
| 1402 |
pass |
| 1403 |
|
| 1404 |
def test_fromkeys_operator_modifying_set_operand(self): |
| 1405 |
# test fix for seg fault reported in issue 27945 part 4b. |
| 1406 |
class X(int): |
| 1407 |
def __hash__(self): |
| 1408 |
return 13 |
| 1409 |
|
| 1410 |
def __eq__(self, other): |
| 1411 |
if len(d) > 1: |
| 1412 |
d.clear() |
| 1413 |
return False |
| 1414 |
|
| 1415 |
d = {} # this is required to exist so that d can be constructed! |
| 1416 |
d = {X(1), X(2)} |
| 1417 |
try: |
| 1418 |
dict.fromkeys(d) # shouldn't crash |
| 1419 |
except RuntimeError: # implementation defined |
| 1420 |
pass |
| 1421 |
|
| 1422 |
def test_dictitems_contains_use_after_free(self): |
| 1423 |
class X: |
| 1424 |
def __eq__(self, other): |
| 1425 |
d.clear() |
| 1426 |
return NotImplemented |
| 1427 |
|
| 1428 |
d = {0: set()} |
| 1429 |
(0, X()) in d.items() |
| 1430 |
|
| 1431 |
def test_dict_contain_use_after_free(self): |
| 1432 |
# bpo-40489 |
| 1433 |
class S(str): |
| 1434 |
def __eq__(self, other): |
| 1435 |
d.clear() |
| 1436 |
return NotImplemented |
| 1437 |
|
| 1438 |
def __hash__(self): |
| 1439 |
return hash('test') |
| 1440 |
|
| 1441 |
d = {S(): 'value'} |
| 1442 |
self.assertFalse('test' in d) |
| 1443 |
|
| 1444 |
def test_init_use_after_free(self): |
| 1445 |
class X: |
| 1446 |
def __hash__(self): |
| 1447 |
pair[:] = [] |
| 1448 |
return 13 |
| 1449 |
|
| 1450 |
pair = [X(), 123] |
| 1451 |
dict([pair]) |
| 1452 |
|
| 1453 |
def test_oob_indexing_dictiter_iternextitem(self): |
| 1454 |
class X(int): |
| 1455 |
def __del__(self): |
| 1456 |
d.clear() |
| 1457 |
|
| 1458 |
d = {i: X(i) for i in range(8)} |
| 1459 |
|
| 1460 |
def iter_and_mutate(): |
| 1461 |
for result in d.items(): |
| 1462 |
if result[0] == 2: |
| 1463 |
d[2] = None # free d[2] --> X(2).__del__ was called |
| 1464 |
|
| 1465 |
self.assertRaises(RuntimeError, iter_and_mutate) |
| 1466 |
|
| 1467 |
def test_reversed(self): |
| 1468 |
d = {"a": 1, "b": 2, "foo": 0, "c": 3, "d": 4} |
| 1469 |
del d["foo"] |
| 1470 |
r = reversed(d) |
| 1471 |
self.assertEqual(list(r), list('dcba')) |
| 1472 |
self.assertRaises(StopIteration, next, r) |
| 1473 |
|
| 1474 |
def test_reverse_iterator_for_empty_dict(self): |
| 1475 |
# bpo-38525: reversed iterator should work properly |
| 1476 |
|
| 1477 |
# empty dict is directly used for reference count test |
| 1478 |
self.assertEqual(list(reversed({})), []) |
| 1479 |
self.assertEqual(list(reversed({}.items())), []) |
| 1480 |
self.assertEqual(list(reversed({}.values())), []) |
| 1481 |
self.assertEqual(list(reversed({}.keys())), []) |
| 1482 |
|
| 1483 |
# dict() and {} don't trigger the same code path |
| 1484 |
self.assertEqual(list(reversed(dict())), []) |
| 1485 |
self.assertEqual(list(reversed(dict().items())), []) |
| 1486 |
self.assertEqual(list(reversed(dict().values())), []) |
| 1487 |
self.assertEqual(list(reversed(dict().keys())), []) |
| 1488 |
|
| 1489 |
def test_reverse_iterator_for_shared_shared_dicts(self): |
| 1490 |
class A: |
| 1491 |
def __init__(self, x, y): |
| 1492 |
if x: self.x = x |
| 1493 |
if y: self.y = y |
| 1494 |
|
| 1495 |
self.assertEqual(list(reversed(A(1, 2).__dict__)), ['y', 'x']) |
| 1496 |
self.assertEqual(list(reversed(A(1, 0).__dict__)), ['x']) |
| 1497 |
self.assertEqual(list(reversed(A(0, 1).__dict__)), ['y']) |
| 1498 |
|
| 1499 |
def test_dict_copy_order(self): |
| 1500 |
# bpo-34320 |
| 1501 |
od = collections.OrderedDict([('a', 1), ('b', 2)]) |
| 1502 |
od.move_to_end('a') |
| 1503 |
expected = list(od.items()) |
| 1504 |
|
| 1505 |
copy = dict(od) |
| 1506 |
self.assertEqual(list(copy.items()), expected) |
| 1507 |
|
| 1508 |
# dict subclass doesn't override __iter__ |
| 1509 |
class CustomDict(dict): |
| 1510 |
pass |
| 1511 |
|
| 1512 |
pairs = [('a', 1), ('b', 2), ('c', 3)] |
| 1513 |
|
| 1514 |
d = CustomDict(pairs) |
| 1515 |
self.assertEqual(pairs, list(dict(d).items())) |
| 1516 |
|
| 1517 |
class CustomReversedDict(dict): |
| 1518 |
def keys(self): |
| 1519 |
return reversed(list(dict.keys(self))) |
| 1520 |
|
| 1521 |
__iter__ = keys |
| 1522 |
|
| 1523 |
def items(self): |
| 1524 |
return reversed(dict.items(self)) |
| 1525 |
|
| 1526 |
d = CustomReversedDict(pairs) |
| 1527 |
self.assertEqual(pairs[::-1], list(dict(d).items())) |
| 1528 |
|
| 1529 |
@support.cpython_only |
| 1530 |
def test_dict_items_result_gc(self): |
| 1531 |
# bpo-42536: dict.items's tuple-reuse speed trick breaks the GC's |
| 1532 |
# assumptions about what can be untracked. Make sure we re-track result |
| 1533 |
# tuples whenever we reuse them. |
| 1534 |
it = iter({None: []}.items()) |
| 1535 |
gc.collect() |
| 1536 |
# That GC collection probably untracked the recycled internal result |
| 1537 |
# tuple, which is initialized to (None, None). Make sure it's re-tracked |
| 1538 |
# when it's mutated and returned from __next__: |
| 1539 |
self.assertTrue(gc.is_tracked(next(it))) |
| 1540 |
|
| 1541 |
@support.cpython_only |
| 1542 |
def test_dict_items_result_gc_reversed(self): |
| 1543 |
# Same as test_dict_items_result_gc above, but reversed. |
| 1544 |
it = reversed({None: []}.items()) |
| 1545 |
gc.collect() |
| 1546 |
self.assertTrue(gc.is_tracked(next(it))) |
| 1547 |
|
| 1548 |
def test_store_evilattr(self): |
| 1549 |
class EvilAttr: |
| 1550 |
def __init__(self, d): |
| 1551 |
self.d = d |
| 1552 |
|
| 1553 |
def __del__(self): |
| 1554 |
if 'attr' in self.d: |
| 1555 |
del self.d['attr'] |
| 1556 |
gc.collect() |
| 1557 |
|
| 1558 |
class Obj: |
| 1559 |
pass |
| 1560 |
|
| 1561 |
obj = Obj() |
| 1562 |
obj.__dict__ = {} |
| 1563 |
for _ in range(10): |
| 1564 |
obj.attr = EvilAttr(obj.__dict__) |
| 1565 |
|
| 1566 |
def test_str_nonstr(self): |
| 1567 |
# cpython uses a different lookup function if the dict only contains |
| 1568 |
# `str` keys. Make sure the unoptimized path is used when a non-`str` |
| 1569 |
# key appears. |
| 1570 |
|
| 1571 |
class StrSub(str): |
| 1572 |
pass |
| 1573 |
|
| 1574 |
eq_count = 0 |
| 1575 |
# This class compares equal to the string 'key3' |
| 1576 |
class Key3: |
| 1577 |
def __hash__(self): |
| 1578 |
return hash('key3') |
| 1579 |
|
| 1580 |
def __eq__(self, other): |
| 1581 |
nonlocal eq_count |
| 1582 |
if isinstance(other, Key3) or isinstance(other, str) and other == 'key3': |
| 1583 |
eq_count += 1 |
| 1584 |
return True |
| 1585 |
return False |
| 1586 |
|
| 1587 |
key3_1 = StrSub('key3') |
| 1588 |
key3_2 = Key3() |
| 1589 |
key3_3 = Key3() |
| 1590 |
|
| 1591 |
dicts = [] |
| 1592 |
|
| 1593 |
# Create dicts of the form `{'key1': 42, 'key2': 43, key3: 44}` in a |
| 1594 |
# bunch of different ways. In all cases, `key3` is not of type `str`. |
| 1595 |
# `key3_1` is a `str` subclass and `key3_2` is a completely unrelated |
| 1596 |
# type. |
| 1597 |
for key3 in (key3_1, key3_2): |
| 1598 |
# A literal |
| 1599 |
dicts.append({'key1': 42, 'key2': 43, key3: 44}) |
| 1600 |
|
| 1601 |
# key3 inserted via `dict.__setitem__` |
| 1602 |
d = {'key1': 42, 'key2': 43} |
| 1603 |
d[key3] = 44 |
| 1604 |
dicts.append(d) |
| 1605 |
|
| 1606 |
# key3 inserted via `dict.setdefault` |
| 1607 |
d = {'key1': 42, 'key2': 43} |
| 1608 |
self.assertEqual(d.setdefault(key3, 44), 44) |
| 1609 |
dicts.append(d) |
| 1610 |
|
| 1611 |
# key3 inserted via `dict.update` |
| 1612 |
d = {'key1': 42, 'key2': 43} |
| 1613 |
d.update({key3: 44}) |
| 1614 |
dicts.append(d) |
| 1615 |
|
| 1616 |
# key3 inserted via `dict.__ior__` |
| 1617 |
d = {'key1': 42, 'key2': 43} |
| 1618 |
d |= {key3: 44} |
| 1619 |
dicts.append(d) |
| 1620 |
|
| 1621 |
# `dict(iterable)` |
| 1622 |
def make_pairs(): |
| 1623 |
yield ('key1', 42) |
| 1624 |
yield ('key2', 43) |
| 1625 |
yield (key3, 44) |
| 1626 |
d = dict(make_pairs()) |
| 1627 |
dicts.append(d) |
| 1628 |
|
| 1629 |
# `dict.copy` |
| 1630 |
d = d.copy() |
| 1631 |
dicts.append(d) |
| 1632 |
|
| 1633 |
# dict comprehension |
| 1634 |
d = {key: 42 + i for i,key in enumerate(['key1', 'key2', key3])} |
| 1635 |
dicts.append(d) |
| 1636 |
|
| 1637 |
for d in dicts: |
| 1638 |
with self.subTest(d=d): |
| 1639 |
self.assertEqual(d.get('key1'), 42) |
| 1640 |
|
| 1641 |
# Try to make an object that is of type `str` and is equal to |
| 1642 |
# `'key1'`, but (at least on cpython) is a different object. |
| 1643 |
noninterned_key1 = 'ke' |
| 1644 |
noninterned_key1 += 'y1' |
| 1645 |
if support.check_impl_detail(cpython=True): |
| 1646 |
# suppress a SyntaxWarning |
| 1647 |
interned_key1 = 'key1' |
| 1648 |
self.assertFalse(noninterned_key1 is interned_key1) |
| 1649 |
self.assertEqual(d.get(noninterned_key1), 42) |
| 1650 |
|
| 1651 |
self.assertEqual(d.get('key3'), 44) |
| 1652 |
self.assertEqual(d.get(key3_1), 44) |
| 1653 |
self.assertEqual(d.get(key3_2), 44) |
| 1654 |
|
| 1655 |
# `key3_3` itself is definitely not a dict key, so make sure |
| 1656 |
# that `__eq__` gets called. |
| 1657 |
# |
| 1658 |
# Note that this might not hold for `key3_1` and `key3_2` |
| 1659 |
# because they might be the same object as one of the dict keys, |
| 1660 |
# in which case implementations are allowed to skip the call to |
| 1661 |
# `__eq__`. |
| 1662 |
eq_count = 0 |
| 1663 |
self.assertEqual(d.get(key3_3), 44) |
| 1664 |
self.assertGreaterEqual(eq_count, 1) |
| 1665 |
|
| 1666 |
def test_clear_at_lookup(self): |
| 1667 |
# gh-140551 dict crash if clear is called at lookup stage |
| 1668 |
class X: |
| 1669 |
def __hash__(self): |
| 1670 |
return 1 |
| 1671 |
def __eq__(self, other): |
| 1672 |
nonlocal d |
| 1673 |
d.clear() |
| 1674 |
|
| 1675 |
d = {} |
| 1676 |
for _ in range(10): |
| 1677 |
d[X()] = None |
| 1678 |
|
| 1679 |
self.assertEqual(len(d), 1) |
| 1680 |
|
| 1681 |
d = {} |
| 1682 |
for _ in range(10): |
| 1683 |
d.setdefault(X(), None) |
| 1684 |
|
| 1685 |
self.assertEqual(len(d), 1) |
| 1686 |
|
| 1687 |
def test_split_table_update_with_str_subclass(self): |
| 1688 |
# gh-142218: inserting into a split table dictionary with a non str |
| 1689 |
# key that matches an existing key. |
| 1690 |
class MyStr(str): pass |
| 1691 |
class MyClass: pass |
| 1692 |
obj = MyClass() |
| 1693 |
obj.attr = 1 |
| 1694 |
obj.__dict__[MyStr('attr')] = 2 |
| 1695 |
self.assertEqual(obj.attr, 2) |
| 1696 |
|
| 1697 |
def test_split_table_insert_with_str_subclass(self): |
| 1698 |
# gh-143189: inserting into split table dictionary with a non str |
| 1699 |
# key that matches an existing key in the shared table but not in |
| 1700 |
# the dict yet. |
| 1701 |
|
| 1702 |
class MyStr(str): pass |
| 1703 |
class MyClass: pass |
| 1704 |
|
| 1705 |
obj = MyClass() |
| 1706 |
obj.attr1 = 1 |
| 1707 |
|
| 1708 |
obj2 = MyClass() |
| 1709 |
d = obj2.__dict__ |
| 1710 |
d[MyStr("attr1")] = 2 |
| 1711 |
self.assertIsInstance(list(d)[0], MyStr) |
| 1712 |
|
| 1713 |
def test_hash_collision_remove_add(self): |
| 1714 |
self.maxDiff = None |
| 1715 |
# There should be enough space, so all elements with unique hash |
| 1716 |
# will be placed in corresponding cells without collision. |
| 1717 |
n = 64 |
| 1718 |
items = [(CustomHash(h), h) for h in range(n)] |
| 1719 |
# Keys with hash collision. |
| 1720 |
a = CustomHash(n) |
| 1721 |
b = CustomHash(n) |
| 1722 |
items += [(a, 'a'), (b, 'b')] |
| 1723 |
d = dict(items) |
| 1724 |
self.assertEqual(len(d), len(items), d) |
| 1725 |
del d[a] |
| 1726 |
# "a" has been replaced with a dummy. |
| 1727 |
del items[n] |
| 1728 |
self.assertEqual(len(d), len(items), d) |
| 1729 |
self.assertEqual(d, dict(items)) |
| 1730 |
d[b] = 'c' |
| 1731 |
# "b" should not replace the dummy. |
| 1732 |
items[n] = (b, 'c') |
| 1733 |
self.assertEqual(len(d), len(items), d) |
| 1734 |
self.assertEqual(d, dict(items)) |
| 1735 |
|
| 1736 |
|
| 1737 |
class CAPITest(unittest.TestCase): |
| 1738 |
|
| 1739 |
# Test _PyDict_GetItem_KnownHash() |
| 1740 |
@support.cpython_only |
| 1741 |
def test_getitem_knownhash(self): |
| 1742 |
_testinternalcapi = import_helper.import_module('_testinternalcapi') |
| 1743 |
dict_getitem_knownhash = _testinternalcapi.dict_getitem_knownhash |
| 1744 |
|
| 1745 |
d = {'x': 1, 'y': 2, 'z': 3} |
| 1746 |
self.assertEqual(dict_getitem_knownhash(d, 'x', hash('x')), 1) |
| 1747 |
self.assertEqual(dict_getitem_knownhash(d, 'y', hash('y')), 2) |
| 1748 |
self.assertEqual(dict_getitem_knownhash(d, 'z', hash('z')), 3) |
| 1749 |
|
| 1750 |
# not a dict |
| 1751 |
self.assertRaises(SystemError, dict_getitem_knownhash, [], 1, hash(1)) |
| 1752 |
# key does not exist |
| 1753 |
self.assertRaises(KeyError, dict_getitem_knownhash, {}, 1, hash(1)) |
| 1754 |
|
| 1755 |
class Exc(Exception): pass |
| 1756 |
class BadEq: |
| 1757 |
def __eq__(self, other): |
| 1758 |
raise Exc |
| 1759 |
def __hash__(self): |
| 1760 |
return 7 |
| 1761 |
|
| 1762 |
k1, k2 = BadEq(), BadEq() |
| 1763 |
d = {k1: 1} |
| 1764 |
self.assertEqual(dict_getitem_knownhash(d, k1, hash(k1)), 1) |
| 1765 |
self.assertRaises(Exc, dict_getitem_knownhash, d, k2, hash(k2)) |
| 1766 |
|
| 1767 |
|
| 1768 |
from test import mapping_tests |
| 1769 |
|
| 1770 |
class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 1771 |
type2test = dict |
| 1772 |
|
| 1773 |
class Dict(dict): |
| 1774 |
pass |
| 1775 |
|
| 1776 |
class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 1777 |
type2test = Dict |
| 1778 |
|
| 1779 |
|
| 1780 |
if __name__ == "__main__": |
| 1781 |
unittest.main() |