Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 1 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2 | from test import support |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 3 | |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 4 | import collections, random, string |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 5 | import collections.abc |
Antoine Pitrou | 7ddda78 | 2009-01-01 15:35:33 +0000 | [diff] [blame] | 6 | import gc, weakref |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 7 | import pickle |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 8 | |
| 9 | |
| 10 | class DictTest(unittest.TestCase): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 11 | |
Benjamin Peterson | fb88636 | 2010-04-24 18:21:17 +0000 | [diff] [blame] | 12 | def test_invalid_keyword_arguments(self): |
Benjamin Peterson | f609654 | 2010-11-17 22:33:12 +0000 | [diff] [blame] | 13 | class Custom(dict): |
| 14 | pass |
| 15 | for invalid in {1 : 2}, Custom({1 : 2}): |
| 16 | with self.assertRaises(TypeError): |
| 17 | dict(**invalid) |
| 18 | with self.assertRaises(TypeError): |
| 19 | {}.update(**invalid) |
Benjamin Peterson | fb88636 | 2010-04-24 18:21:17 +0000 | [diff] [blame] | 20 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 21 | def test_constructor(self): |
| 22 | # calling built-in types without argument must return empty |
| 23 | self.assertEqual(dict(), {}) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 24 | self.assertIsNot(dict(), {}) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 25 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 26 | def test_literal_constructor(self): |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 27 | # check literal constructor for different sized dicts |
| 28 | # (to exercise the BUILD_MAP oparg). |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 29 | for n in (0, 1, 6, 256, 400): |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 30 | items = [(''.join(random.sample(string.ascii_letters, 8)), i) |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 31 | for i in range(n)] |
| 32 | random.shuffle(items) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 33 | formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items) |
| 34 | dictliteral = '{' + ', '.join(formatted_items) + '}' |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 35 | self.assertEqual(eval(dictliteral), dict(items)) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 36 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 37 | def test_bool(self): |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 38 | self.assertIs(not {}, True) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 39 | self.assertTrue({1: 2}) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 40 | self.assertIs(bool({}), False) |
| 41 | self.assertIs(bool({1: 2}), True) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 42 | |
| 43 | def test_keys(self): |
| 44 | d = {} |
Guido van Rossum | e34cdd1 | 2007-02-14 17:49:04 +0000 | [diff] [blame] | 45 | self.assertEqual(set(d.keys()), set()) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 46 | d = {'a': 1, 'b': 2} |
| 47 | k = d.keys() |
Ezio Melotti | 4e1f3d6 | 2013-10-05 03:07:03 +0300 | [diff] [blame] | 48 | self.assertEqual(set(k), {'a', 'b'}) |
| 49 | self.assertIn('a', k) |
| 50 | self.assertIn('b', k) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 51 | self.assertIn('a', d) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 52 | self.assertIn('b', d) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 53 | self.assertRaises(TypeError, d.keys, None) |
Raymond Hettinger | b0d56af | 2009-03-03 10:52:49 +0000 | [diff] [blame] | 54 | self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])") |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 55 | |
| 56 | def test_values(self): |
| 57 | d = {} |
Guido van Rossum | e34cdd1 | 2007-02-14 17:49:04 +0000 | [diff] [blame] | 58 | self.assertEqual(set(d.values()), set()) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 59 | d = {1:2} |
Guido van Rossum | e34cdd1 | 2007-02-14 17:49:04 +0000 | [diff] [blame] | 60 | self.assertEqual(set(d.values()), {2}) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 61 | self.assertRaises(TypeError, d.values, None) |
Raymond Hettinger | b0d56af | 2009-03-03 10:52:49 +0000 | [diff] [blame] | 62 | self.assertEqual(repr(dict(a=1).values()), "dict_values([1])") |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 63 | |
| 64 | def test_items(self): |
| 65 | d = {} |
Guido van Rossum | e34cdd1 | 2007-02-14 17:49:04 +0000 | [diff] [blame] | 66 | self.assertEqual(set(d.items()), set()) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 67 | |
| 68 | d = {1:2} |
Guido van Rossum | e34cdd1 | 2007-02-14 17:49:04 +0000 | [diff] [blame] | 69 | self.assertEqual(set(d.items()), {(1, 2)}) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 70 | self.assertRaises(TypeError, d.items, None) |
Raymond Hettinger | b0d56af | 2009-03-03 10:52:49 +0000 | [diff] [blame] | 71 | self.assertEqual(repr(dict(a=1).items()), "dict_items([('a', 1)])") |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 72 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 73 | def test_contains(self): |
| 74 | d = {} |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 75 | self.assertNotIn('a', d) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 76 | self.assertFalse('a' in d) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 77 | self.assertTrue('a' not in d) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 78 | d = {'a': 1, 'b': 2} |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 79 | self.assertIn('a', d) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 80 | self.assertIn('b', d) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 81 | self.assertNotIn('c', d) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 82 | |
| 83 | self.assertRaises(TypeError, d.__contains__) |
| 84 | |
| 85 | def test_len(self): |
| 86 | d = {} |
| 87 | self.assertEqual(len(d), 0) |
| 88 | d = {'a': 1, 'b': 2} |
| 89 | self.assertEqual(len(d), 2) |
| 90 | |
| 91 | def test_getitem(self): |
| 92 | d = {'a': 1, 'b': 2} |
| 93 | self.assertEqual(d['a'], 1) |
| 94 | self.assertEqual(d['b'], 2) |
| 95 | d['c'] = 3 |
| 96 | d['a'] = 4 |
| 97 | self.assertEqual(d['c'], 3) |
| 98 | self.assertEqual(d['a'], 4) |
| 99 | del d['b'] |
| 100 | self.assertEqual(d, {'a': 4, 'c': 3}) |
| 101 | |
| 102 | self.assertRaises(TypeError, d.__getitem__) |
| 103 | |
| 104 | class BadEq(object): |
| 105 | def __eq__(self, other): |
| 106 | raise Exc() |
Guido van Rossum | 3893815 | 2006-08-21 23:36:26 +0000 | [diff] [blame] | 107 | def __hash__(self): |
| 108 | return 24 |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 109 | |
| 110 | d = {} |
| 111 | d[BadEq()] = 42 |
| 112 | self.assertRaises(KeyError, d.__getitem__, 23) |
| 113 | |
| 114 | class Exc(Exception): pass |
| 115 | |
| 116 | class BadHash(object): |
| 117 | fail = False |
| 118 | def __hash__(self): |
| 119 | if self.fail: |
| 120 | raise Exc() |
| 121 | else: |
| 122 | return 42 |
| 123 | |
| 124 | x = BadHash() |
| 125 | d[x] = 42 |
| 126 | x.fail = True |
| 127 | self.assertRaises(Exc, d.__getitem__, x) |
| 128 | |
| 129 | def test_clear(self): |
| 130 | d = {1:1, 2:2, 3:3} |
| 131 | d.clear() |
| 132 | self.assertEqual(d, {}) |
| 133 | |
| 134 | self.assertRaises(TypeError, d.clear, None) |
| 135 | |
| 136 | def test_update(self): |
| 137 | d = {} |
| 138 | d.update({1:100}) |
| 139 | d.update({2:20}) |
| 140 | d.update({1:1, 2:2, 3:3}) |
| 141 | self.assertEqual(d, {1:1, 2:2, 3:3}) |
| 142 | |
| 143 | d.update() |
| 144 | self.assertEqual(d, {1:1, 2:2, 3:3}) |
| 145 | |
| 146 | self.assertRaises((TypeError, AttributeError), d.update, None) |
| 147 | |
| 148 | class SimpleUserDict: |
| 149 | def __init__(self): |
| 150 | self.d = {1:1, 2:2, 3:3} |
| 151 | def keys(self): |
| 152 | return self.d.keys() |
| 153 | def __getitem__(self, i): |
| 154 | return self.d[i] |
| 155 | d.clear() |
| 156 | d.update(SimpleUserDict()) |
| 157 | self.assertEqual(d, {1:1, 2:2, 3:3}) |
| 158 | |
| 159 | class Exc(Exception): pass |
| 160 | |
| 161 | d.clear() |
| 162 | class FailingUserDict: |
| 163 | def keys(self): |
| 164 | raise Exc |
| 165 | self.assertRaises(Exc, d.update, FailingUserDict()) |
| 166 | |
| 167 | class FailingUserDict: |
| 168 | def keys(self): |
| 169 | class BogonIter: |
| 170 | def __init__(self): |
| 171 | self.i = 1 |
| 172 | def __iter__(self): |
| 173 | return self |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 174 | def __next__(self): |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 175 | if self.i: |
| 176 | self.i = 0 |
| 177 | return 'a' |
| 178 | raise Exc |
| 179 | return BogonIter() |
| 180 | def __getitem__(self, key): |
| 181 | return key |
| 182 | self.assertRaises(Exc, d.update, FailingUserDict()) |
| 183 | |
| 184 | class FailingUserDict: |
| 185 | def keys(self): |
| 186 | class BogonIter: |
| 187 | def __init__(self): |
| 188 | self.i = ord('a') |
| 189 | def __iter__(self): |
| 190 | return self |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 191 | def __next__(self): |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 192 | if self.i <= ord('z'): |
| 193 | rtn = chr(self.i) |
| 194 | self.i += 1 |
| 195 | return rtn |
| 196 | raise StopIteration |
| 197 | return BogonIter() |
| 198 | def __getitem__(self, key): |
| 199 | raise Exc |
| 200 | self.assertRaises(Exc, d.update, FailingUserDict()) |
| 201 | |
| 202 | class badseq(object): |
| 203 | def __iter__(self): |
| 204 | return self |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 205 | def __next__(self): |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 206 | raise Exc() |
| 207 | |
| 208 | self.assertRaises(Exc, {}.update, badseq()) |
| 209 | |
| 210 | self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) |
| 211 | |
| 212 | def test_fromkeys(self): |
| 213 | self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) |
| 214 | d = {} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 215 | self.assertIsNot(d.fromkeys('abc'), d) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 216 | self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) |
| 217 | self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) |
| 218 | self.assertEqual(d.fromkeys([]), {}) |
| 219 | def g(): |
| 220 | yield 1 |
| 221 | self.assertEqual(d.fromkeys(g()), {1:None}) |
| 222 | self.assertRaises(TypeError, {}.fromkeys, 3) |
| 223 | class dictlike(dict): pass |
| 224 | self.assertEqual(dictlike.fromkeys('a'), {'a':None}) |
| 225 | self.assertEqual(dictlike().fromkeys('a'), {'a':None}) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 226 | self.assertIsInstance(dictlike.fromkeys('a'), dictlike) |
| 227 | self.assertIsInstance(dictlike().fromkeys('a'), dictlike) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 228 | class mydict(dict): |
| 229 | def __new__(cls): |
Raymond Hettinger | f80680d | 2008-02-06 00:07:11 +0000 | [diff] [blame] | 230 | return collections.UserDict() |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 231 | ud = mydict.fromkeys('ab') |
| 232 | self.assertEqual(ud, {'a':None, 'b':None}) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 233 | self.assertIsInstance(ud, collections.UserDict) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 234 | self.assertRaises(TypeError, dict.fromkeys) |
| 235 | |
| 236 | class Exc(Exception): pass |
| 237 | |
| 238 | class baddict1(dict): |
| 239 | def __init__(self): |
| 240 | raise Exc() |
| 241 | |
| 242 | self.assertRaises(Exc, baddict1.fromkeys, [1]) |
| 243 | |
| 244 | class BadSeq(object): |
| 245 | def __iter__(self): |
| 246 | return self |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 247 | def __next__(self): |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 248 | raise Exc() |
| 249 | |
| 250 | self.assertRaises(Exc, dict.fromkeys, BadSeq()) |
| 251 | |
| 252 | class baddict2(dict): |
| 253 | def __setitem__(self, key, value): |
| 254 | raise Exc() |
| 255 | |
| 256 | self.assertRaises(Exc, baddict2.fromkeys, [1]) |
| 257 | |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 258 | # test fast path for dictionary inputs |
| 259 | d = dict(zip(range(6), range(6))) |
| 260 | self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6))) |
| 261 | |
Benjamin Peterson | d1f2cb3 | 2012-10-31 14:05:55 -0400 | [diff] [blame] | 262 | class baddict3(dict): |
| 263 | def __new__(cls): |
| 264 | return d |
| 265 | d = {i : i for i in range(10)} |
| 266 | res = d.copy() |
| 267 | res.update(a=None, b=None, c=None) |
| 268 | self.assertEqual(baddict3.fromkeys({"a", "b", "c"}), res) |
| 269 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 270 | def test_copy(self): |
| 271 | d = {1:1, 2:2, 3:3} |
| 272 | self.assertEqual(d.copy(), {1:1, 2:2, 3:3}) |
| 273 | self.assertEqual({}.copy(), {}) |
| 274 | self.assertRaises(TypeError, d.copy, None) |
| 275 | |
| 276 | def test_get(self): |
| 277 | d = {} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 278 | self.assertIs(d.get('c'), None) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 279 | self.assertEqual(d.get('c', 3), 3) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 280 | d = {'a': 1, 'b': 2} |
| 281 | self.assertIs(d.get('c'), None) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 282 | self.assertEqual(d.get('c', 3), 3) |
| 283 | self.assertEqual(d.get('a'), 1) |
| 284 | self.assertEqual(d.get('a', 3), 1) |
| 285 | self.assertRaises(TypeError, d.get) |
| 286 | self.assertRaises(TypeError, d.get, None, None, None) |
| 287 | |
| 288 | def test_setdefault(self): |
| 289 | # dict.setdefault() |
| 290 | d = {} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 291 | self.assertIs(d.setdefault('key0'), None) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 292 | d.setdefault('key0', []) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 293 | self.assertIs(d.setdefault('key0'), None) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 294 | d.setdefault('key', []).append(3) |
| 295 | self.assertEqual(d['key'][0], 3) |
| 296 | d.setdefault('key', []).append(4) |
| 297 | self.assertEqual(len(d['key']), 2) |
| 298 | self.assertRaises(TypeError, d.setdefault) |
| 299 | |
| 300 | class Exc(Exception): pass |
| 301 | |
| 302 | class BadHash(object): |
| 303 | fail = False |
| 304 | def __hash__(self): |
| 305 | if self.fail: |
| 306 | raise Exc() |
| 307 | else: |
| 308 | return 42 |
| 309 | |
| 310 | x = BadHash() |
| 311 | d[x] = 42 |
| 312 | x.fail = True |
| 313 | self.assertRaises(Exc, d.setdefault, x, []) |
| 314 | |
Antoine Pitrou | e965d97 | 2012-02-27 00:45:12 +0100 | [diff] [blame] | 315 | def test_setdefault_atomic(self): |
| 316 | # Issue #13521: setdefault() calls __hash__ and __eq__ only once. |
| 317 | class Hashed(object): |
| 318 | def __init__(self): |
| 319 | self.hash_count = 0 |
| 320 | self.eq_count = 0 |
| 321 | def __hash__(self): |
| 322 | self.hash_count += 1 |
| 323 | return 42 |
| 324 | def __eq__(self, other): |
| 325 | self.eq_count += 1 |
| 326 | return id(self) == id(other) |
| 327 | hashed1 = Hashed() |
| 328 | y = {hashed1: 5} |
| 329 | hashed2 = Hashed() |
| 330 | y.setdefault(hashed2, []) |
| 331 | self.assertEqual(hashed1.hash_count, 1) |
| 332 | self.assertEqual(hashed2.hash_count, 1) |
| 333 | self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1) |
| 334 | |
Benjamin Peterson | 7d95e40 | 2012-04-23 11:24:50 -0400 | [diff] [blame] | 335 | def test_setitem_atomic_at_resize(self): |
| 336 | class Hashed(object): |
| 337 | def __init__(self): |
| 338 | self.hash_count = 0 |
| 339 | self.eq_count = 0 |
| 340 | def __hash__(self): |
| 341 | self.hash_count += 1 |
| 342 | return 42 |
| 343 | def __eq__(self, other): |
| 344 | self.eq_count += 1 |
| 345 | return id(self) == id(other) |
| 346 | hashed1 = Hashed() |
| 347 | # 5 items |
| 348 | y = {hashed1: 5, 0: 0, 1: 1, 2: 2, 3: 3} |
| 349 | hashed2 = Hashed() |
| 350 | # 6th item forces a resize |
| 351 | y[hashed2] = [] |
| 352 | self.assertEqual(hashed1.hash_count, 1) |
| 353 | self.assertEqual(hashed2.hash_count, 1) |
| 354 | self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1) |
| 355 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 356 | def test_popitem(self): |
| 357 | # dict.popitem() |
| 358 | for copymode in -1, +1: |
| 359 | # -1: b has same structure as a |
| 360 | # +1: b is a.copy() |
| 361 | for log2size in range(12): |
| 362 | size = 2**log2size |
| 363 | a = {} |
| 364 | b = {} |
| 365 | for i in range(size): |
| 366 | a[repr(i)] = i |
| 367 | if copymode < 0: |
| 368 | b[repr(i)] = i |
| 369 | if copymode > 0: |
| 370 | b = a.copy() |
| 371 | for i in range(size): |
| 372 | ka, va = ta = a.popitem() |
| 373 | self.assertEqual(va, int(ka)) |
| 374 | kb, vb = tb = b.popitem() |
| 375 | self.assertEqual(vb, int(kb)) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 376 | self.assertFalse(copymode < 0 and ta != tb) |
| 377 | self.assertFalse(a) |
| 378 | self.assertFalse(b) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 379 | |
| 380 | d = {} |
| 381 | self.assertRaises(KeyError, d.popitem) |
| 382 | |
| 383 | def test_pop(self): |
| 384 | # Tests for pop with specified key |
| 385 | d = {} |
| 386 | k, v = 'abc', 'def' |
| 387 | d[k] = v |
| 388 | self.assertRaises(KeyError, d.pop, 'ghi') |
| 389 | |
| 390 | self.assertEqual(d.pop(k), v) |
| 391 | self.assertEqual(len(d), 0) |
| 392 | |
| 393 | self.assertRaises(KeyError, d.pop, k) |
| 394 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 395 | self.assertEqual(d.pop(k, v), v) |
| 396 | d[k] = v |
| 397 | self.assertEqual(d.pop(k, 1), v) |
| 398 | |
| 399 | self.assertRaises(TypeError, d.pop) |
| 400 | |
| 401 | class Exc(Exception): pass |
| 402 | |
| 403 | class BadHash(object): |
| 404 | fail = False |
| 405 | def __hash__(self): |
| 406 | if self.fail: |
| 407 | raise Exc() |
| 408 | else: |
| 409 | return 42 |
| 410 | |
| 411 | x = BadHash() |
| 412 | d[x] = 42 |
| 413 | x.fail = True |
| 414 | self.assertRaises(Exc, d.pop, x) |
| 415 | |
Victor Stinner | 198b291 | 2012-03-06 01:03:13 +0100 | [diff] [blame] | 416 | def test_mutating_iteration(self): |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 417 | # changing dict size during iteration |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 418 | d = {} |
| 419 | d[1] = 1 |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 420 | with self.assertRaises(RuntimeError): |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 421 | for i in d: |
| 422 | d[i+1] = 1 |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 423 | |
Victor Stinner | 198b291 | 2012-03-06 01:03:13 +0100 | [diff] [blame] | 424 | def test_mutating_lookup(self): |
Antoine Pitrou | 9a23490 | 2012-05-13 20:48:01 +0200 | [diff] [blame] | 425 | # changing dict during a lookup (issue #14417) |
Victor Stinner | 198b291 | 2012-03-06 01:03:13 +0100 | [diff] [blame] | 426 | class NastyKey: |
| 427 | mutate_dict = None |
| 428 | |
Victor Stinner | 2839382 | 2012-03-09 22:58:51 +0100 | [diff] [blame] | 429 | def __init__(self, value): |
| 430 | self.value = value |
| 431 | |
Victor Stinner | 198b291 | 2012-03-06 01:03:13 +0100 | [diff] [blame] | 432 | def __hash__(self): |
| 433 | # hash collision! |
| 434 | return 1 |
| 435 | |
| 436 | def __eq__(self, other): |
Victor Stinner | 2839382 | 2012-03-09 22:58:51 +0100 | [diff] [blame] | 437 | if NastyKey.mutate_dict: |
| 438 | mydict, key = NastyKey.mutate_dict |
| 439 | NastyKey.mutate_dict = None |
| 440 | del mydict[key] |
| 441 | return self.value == other.value |
Victor Stinner | 198b291 | 2012-03-06 01:03:13 +0100 | [diff] [blame] | 442 | |
Victor Stinner | 2839382 | 2012-03-09 22:58:51 +0100 | [diff] [blame] | 443 | key1 = NastyKey(1) |
| 444 | key2 = NastyKey(2) |
| 445 | d = {key1: 1} |
| 446 | NastyKey.mutate_dict = (d, key1) |
Antoine Pitrou | 9a23490 | 2012-05-13 20:48:01 +0200 | [diff] [blame] | 447 | d[key2] = 2 |
| 448 | self.assertEqual(d, {key2: 2}) |
Victor Stinner | 198b291 | 2012-03-06 01:03:13 +0100 | [diff] [blame] | 449 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 450 | def test_repr(self): |
| 451 | d = {} |
| 452 | self.assertEqual(repr(d), '{}') |
| 453 | d[1] = 2 |
| 454 | self.assertEqual(repr(d), '{1: 2}') |
| 455 | d = {} |
| 456 | d[1] = d |
| 457 | self.assertEqual(repr(d), '{1: {...}}') |
| 458 | |
| 459 | class Exc(Exception): pass |
| 460 | |
| 461 | class BadRepr(object): |
| 462 | def __repr__(self): |
| 463 | raise Exc() |
| 464 | |
| 465 | d = {1: BadRepr()} |
| 466 | self.assertRaises(Exc, repr, d) |
| 467 | |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 468 | def test_eq(self): |
| 469 | self.assertEqual({}, {}) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 470 | self.assertEqual({1: 2}, {1: 2}) |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 471 | |
| 472 | class Exc(Exception): pass |
| 473 | |
| 474 | class BadCmp(object): |
| 475 | def __eq__(self, other): |
| 476 | raise Exc() |
Guido van Rossum | 3893815 | 2006-08-21 23:36:26 +0000 | [diff] [blame] | 477 | def __hash__(self): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 478 | return 1 |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 479 | |
| 480 | d1 = {BadCmp(): 1} |
| 481 | d2 = {1: 1} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 482 | |
| 483 | with self.assertRaises(Exc): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 484 | d1 == d2 |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 485 | |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 486 | def test_keys_contained(self): |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 487 | self.helper_keys_contained(lambda x: x.keys()) |
| 488 | self.helper_keys_contained(lambda x: x.items()) |
| 489 | |
| 490 | def helper_keys_contained(self, fn): |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 491 | # Test rich comparisons against dict key views, which should behave the |
| 492 | # same as sets. |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 493 | empty = fn(dict()) |
| 494 | empty2 = fn(dict()) |
| 495 | smaller = fn({1:1, 2:2}) |
| 496 | larger = fn({1:1, 2:2, 3:3}) |
| 497 | larger2 = fn({1:1, 2:2, 3:3}) |
| 498 | larger3 = fn({4:1, 2:2, 3:3}) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 499 | |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 500 | self.assertTrue(smaller < larger) |
| 501 | self.assertTrue(smaller <= larger) |
| 502 | self.assertTrue(larger > smaller) |
| 503 | self.assertTrue(larger >= smaller) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 504 | |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 505 | self.assertFalse(smaller >= larger) |
| 506 | self.assertFalse(smaller > larger) |
| 507 | self.assertFalse(larger <= smaller) |
| 508 | self.assertFalse(larger < smaller) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 509 | |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 510 | self.assertFalse(smaller < larger3) |
| 511 | self.assertFalse(smaller <= larger3) |
| 512 | self.assertFalse(larger3 > smaller) |
| 513 | self.assertFalse(larger3 >= smaller) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 514 | |
| 515 | # Inequality strictness |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 516 | self.assertTrue(larger2 >= larger) |
| 517 | self.assertTrue(larger2 <= larger) |
| 518 | self.assertFalse(larger2 > larger) |
| 519 | self.assertFalse(larger2 < larger) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 520 | |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 521 | self.assertTrue(larger == larger2) |
| 522 | self.assertTrue(smaller != larger) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 523 | |
| 524 | # There is an optimization on the zero-element case. |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 525 | self.assertTrue(empty == empty2) |
| 526 | self.assertFalse(empty != empty2) |
| 527 | self.assertFalse(empty == smaller) |
| 528 | self.assertTrue(empty != smaller) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 529 | |
| 530 | # With the same size, an elementwise compare happens |
Guido van Rossum | cf2ce36 | 2007-08-24 23:49:54 +0000 | [diff] [blame] | 531 | self.assertTrue(larger != larger3) |
| 532 | self.assertFalse(larger == larger3) |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 533 | |
| 534 | def test_errors_in_view_containment_check(self): |
| 535 | class C: |
| 536 | def __eq__(self, other): |
| 537 | raise RuntimeError |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 538 | |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 539 | d1 = {1: C()} |
| 540 | d2 = {1: C()} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 541 | with self.assertRaises(RuntimeError): |
| 542 | d1.items() == d2.items() |
| 543 | with self.assertRaises(RuntimeError): |
| 544 | d1.items() != d2.items() |
| 545 | with self.assertRaises(RuntimeError): |
| 546 | d1.items() <= d2.items() |
| 547 | with self.assertRaises(RuntimeError): |
| 548 | d1.items() >= d2.items() |
| 549 | |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 550 | d3 = {1: C(), 2: C()} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 551 | with self.assertRaises(RuntimeError): |
| 552 | d2.items() < d3.items() |
| 553 | with self.assertRaises(RuntimeError): |
| 554 | d3.items() > d2.items() |
Guido van Rossum | aac530c | 2007-08-24 22:33:45 +0000 | [diff] [blame] | 555 | |
Guido van Rossum | be53471 | 2007-08-24 23:43:52 +0000 | [diff] [blame] | 556 | def test_dictview_set_operations_on_keys(self): |
Guido van Rossum | 523259b | 2007-08-24 23:41:22 +0000 | [diff] [blame] | 557 | k1 = {1:1, 2:2}.keys() |
| 558 | k2 = {1:1, 2:2, 3:3}.keys() |
| 559 | k3 = {4:4}.keys() |
| 560 | |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 561 | self.assertEqual(k1 - k2, set()) |
| 562 | self.assertEqual(k1 - k3, {1,2}) |
| 563 | self.assertEqual(k2 - k1, {3}) |
| 564 | self.assertEqual(k3 - k1, {4}) |
| 565 | self.assertEqual(k1 & k2, {1,2}) |
| 566 | self.assertEqual(k1 & k3, set()) |
| 567 | self.assertEqual(k1 | k2, {1,2,3}) |
| 568 | self.assertEqual(k1 ^ k2, {3}) |
| 569 | self.assertEqual(k1 ^ k3, {1,2,4}) |
Guido van Rossum | 523259b | 2007-08-24 23:41:22 +0000 | [diff] [blame] | 570 | |
Guido van Rossum | be53471 | 2007-08-24 23:43:52 +0000 | [diff] [blame] | 571 | def test_dictview_set_operations_on_items(self): |
| 572 | k1 = {1:1, 2:2}.items() |
| 573 | k2 = {1:1, 2:2, 3:3}.items() |
| 574 | k3 = {4:4}.items() |
| 575 | |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 576 | self.assertEqual(k1 - k2, set()) |
| 577 | self.assertEqual(k1 - k3, {(1,1), (2,2)}) |
| 578 | self.assertEqual(k2 - k1, {(3,3)}) |
| 579 | self.assertEqual(k3 - k1, {(4,4)}) |
| 580 | self.assertEqual(k1 & k2, {(1,1), (2,2)}) |
| 581 | self.assertEqual(k1 & k3, set()) |
| 582 | self.assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) |
| 583 | self.assertEqual(k1 ^ k2, {(3,3)}) |
| 584 | self.assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) |
Guido van Rossum | 523259b | 2007-08-24 23:41:22 +0000 | [diff] [blame] | 585 | |
Guido van Rossum | 1d71996 | 2007-08-24 23:47:30 +0000 | [diff] [blame] | 586 | def test_dictview_mixed_set_operations(self): |
| 587 | # Just a few for .keys() |
Guido van Rossum | a401bbe | 2007-08-24 23:51:55 +0000 | [diff] [blame] | 588 | self.assertTrue({1:1}.keys() == {1}) |
| 589 | self.assertTrue({1} == {1:1}.keys()) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 590 | self.assertEqual({1:1}.keys() | {2}, {1, 2}) |
| 591 | self.assertEqual({2} | {1:1}.keys(), {1, 2}) |
Guido van Rossum | 1d71996 | 2007-08-24 23:47:30 +0000 | [diff] [blame] | 592 | # And a few for .items() |
Guido van Rossum | a401bbe | 2007-08-24 23:51:55 +0000 | [diff] [blame] | 593 | self.assertTrue({1:1}.items() == {(1,1)}) |
| 594 | self.assertTrue({(1,1)} == {1:1}.items()) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 595 | self.assertEqual({1:1}.items() | {2}, {(1,1), 2}) |
| 596 | self.assertEqual({2} | {1:1}.items(), {(1,1), 2}) |
Guido van Rossum | 1d71996 | 2007-08-24 23:47:30 +0000 | [diff] [blame] | 597 | |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 598 | def test_missing(self): |
| 599 | # Make sure dict doesn't have a __missing__ method |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 600 | self.assertFalse(hasattr(dict, "__missing__")) |
| 601 | self.assertFalse(hasattr({}, "__missing__")) |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 602 | # Test several cases: |
| 603 | # (D) subclass defines __missing__ method returning a value |
| 604 | # (E) subclass defines __missing__ method raising RuntimeError |
| 605 | # (F) subclass sets __missing__ instance variable (no effect) |
Serhiy Storchaka | d65c949 | 2015-11-02 14:10:23 +0200 | [diff] [blame] | 606 | # (G) subclass doesn't define __missing__ at all |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 607 | class D(dict): |
| 608 | def __missing__(self, key): |
| 609 | return 42 |
| 610 | d = D({1: 2, 3: 4}) |
| 611 | self.assertEqual(d[1], 2) |
| 612 | self.assertEqual(d[3], 4) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 613 | self.assertNotIn(2, d) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 614 | self.assertNotIn(2, d.keys()) |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 615 | self.assertEqual(d[2], 42) |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 616 | |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 617 | class E(dict): |
| 618 | def __missing__(self, key): |
| 619 | raise RuntimeError(key) |
| 620 | e = E() |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 621 | with self.assertRaises(RuntimeError) as c: |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 622 | e[42] |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 623 | self.assertEqual(c.exception.args, (42,)) |
| 624 | |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 625 | class F(dict): |
| 626 | def __init__(self): |
| 627 | # An instance variable __missing__ should have no effect |
| 628 | self.__missing__ = lambda key: None |
| 629 | f = F() |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 630 | with self.assertRaises(KeyError) as c: |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 631 | f[42] |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 632 | self.assertEqual(c.exception.args, (42,)) |
| 633 | |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 634 | class G(dict): |
| 635 | pass |
| 636 | g = G() |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 637 | with self.assertRaises(KeyError) as c: |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 638 | g[42] |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 639 | self.assertEqual(c.exception.args, (42,)) |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 640 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 641 | def test_tuple_keyerror(self): |
| 642 | # SF #1576657 |
| 643 | d = {} |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 644 | with self.assertRaises(KeyError) as c: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 645 | d[(1,)] |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 646 | self.assertEqual(c.exception.args, ((1,),)) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 647 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 648 | def test_bad_key(self): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 649 | # Dictionary lookups should fail if __eq__() raises an exception. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 650 | class CustomException(Exception): |
| 651 | pass |
| 652 | |
| 653 | class BadDictKey: |
| 654 | def __hash__(self): |
| 655 | return hash(self.__class__) |
| 656 | |
| 657 | def __eq__(self, other): |
| 658 | if isinstance(other, self.__class__): |
| 659 | raise CustomException |
| 660 | return other |
| 661 | |
| 662 | d = {} |
| 663 | x1 = BadDictKey() |
| 664 | x2 = BadDictKey() |
| 665 | d[x1] = 1 |
| 666 | for stmt in ['d[x2] = 2', |
| 667 | 'z = d[x2]', |
| 668 | 'x2 in d', |
| 669 | 'd.get(x2)', |
| 670 | 'd.setdefault(x2, 42)', |
| 671 | 'd.pop(x2)', |
| 672 | 'd.update({x2: 2})']: |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 673 | with self.assertRaises(CustomException): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 674 | exec(stmt, locals()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 675 | |
| 676 | def test_resize1(self): |
| 677 | # Dict resizing bug, found by Jack Jansen in 2.2 CVS development. |
| 678 | # This version got an assert failure in debug build, infinite loop in |
| 679 | # release build. Unfortunately, provoking this kind of stuff requires |
| 680 | # a mix of inserts and deletes hitting exactly the right hash codes in |
| 681 | # exactly the right order, and I can't think of a randomized approach |
| 682 | # that would be *likely* to hit a failing case in reasonable time. |
| 683 | |
| 684 | d = {} |
| 685 | for i in range(5): |
| 686 | d[i] = i |
| 687 | for i in range(5): |
| 688 | del d[i] |
| 689 | for i in range(5, 9): # i==8 was the problem |
| 690 | d[i] = i |
| 691 | |
| 692 | def test_resize2(self): |
| 693 | # Another dict resizing bug (SF bug #1456209). |
| 694 | # This caused Segmentation faults or Illegal instructions. |
| 695 | |
| 696 | class X(object): |
| 697 | def __hash__(self): |
| 698 | return 5 |
| 699 | def __eq__(self, other): |
| 700 | if resizing: |
| 701 | d.clear() |
| 702 | return False |
| 703 | d = {} |
| 704 | resizing = False |
| 705 | d[X()] = 1 |
| 706 | d[X()] = 2 |
| 707 | d[X()] = 3 |
| 708 | d[X()] = 4 |
| 709 | d[X()] = 5 |
| 710 | # now trigger a resize |
| 711 | resizing = True |
| 712 | d[9] = 6 |
| 713 | |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 714 | def test_empty_presized_dict_in_freelist(self): |
| 715 | # Bug #3537: if an empty but presized dict with a size larger |
| 716 | # than 7 was in the freelist, it triggered an assertion failure |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 717 | with self.assertRaises(ZeroDivisionError): |
| 718 | d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None, |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 719 | 'f': None, 'g': None, 'h': None} |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 720 | d = {} |
| 721 | |
Antoine Pitrou | 7ddda78 | 2009-01-01 15:35:33 +0000 | [diff] [blame] | 722 | def test_container_iterator(self): |
| 723 | # Bug #3680: tp_traverse was not implemented for dictiter and |
| 724 | # dictview objects. |
| 725 | class C(object): |
| 726 | pass |
| 727 | views = (dict.items, dict.values, dict.keys) |
| 728 | for v in views: |
| 729 | obj = C() |
| 730 | ref = weakref.ref(obj) |
| 731 | container = {obj: 1} |
| 732 | obj.v = v(container) |
| 733 | obj.x = iter(obj.v) |
| 734 | del obj, container |
| 735 | gc.collect() |
Florent Xicluna | a988e42 | 2010-03-02 16:06:24 +0000 | [diff] [blame] | 736 | self.assertIs(ref(), None, "Cycle was not collected") |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 737 | |
Antoine Pitrou | 3a652b1 | 2009-03-23 18:52:06 +0000 | [diff] [blame] | 738 | def _not_tracked(self, t): |
| 739 | # Nested containers can take several collections to untrack |
| 740 | gc.collect() |
| 741 | gc.collect() |
| 742 | self.assertFalse(gc.is_tracked(t), t) |
| 743 | |
| 744 | def _tracked(self, t): |
| 745 | self.assertTrue(gc.is_tracked(t), t) |
| 746 | gc.collect() |
| 747 | gc.collect() |
| 748 | self.assertTrue(gc.is_tracked(t), t) |
| 749 | |
Benjamin Peterson | 3e5cd1d | 2010-06-27 21:45:24 +0000 | [diff] [blame] | 750 | @support.cpython_only |
Antoine Pitrou | 3a652b1 | 2009-03-23 18:52:06 +0000 | [diff] [blame] | 751 | def test_track_literals(self): |
| 752 | # Test GC-optimization of dict literals |
| 753 | x, y, z, w = 1.5, "a", (1, None), [] |
| 754 | |
| 755 | self._not_tracked({}) |
| 756 | self._not_tracked({x:(), y:x, z:1}) |
| 757 | self._not_tracked({1: "a", "b": 2}) |
| 758 | self._not_tracked({1: 2, (None, True, False, ()): int}) |
| 759 | self._not_tracked({1: object()}) |
| 760 | |
| 761 | # Dicts with mutable elements are always tracked, even if those |
| 762 | # elements are not tracked right now. |
| 763 | self._tracked({1: []}) |
| 764 | self._tracked({1: ([],)}) |
| 765 | self._tracked({1: {}}) |
| 766 | self._tracked({1: set()}) |
| 767 | |
Benjamin Peterson | 3e5cd1d | 2010-06-27 21:45:24 +0000 | [diff] [blame] | 768 | @support.cpython_only |
Antoine Pitrou | 3a652b1 | 2009-03-23 18:52:06 +0000 | [diff] [blame] | 769 | def test_track_dynamic(self): |
| 770 | # Test GC-optimization of dynamically-created dicts |
| 771 | class MyObject(object): |
| 772 | pass |
| 773 | x, y, z, w, o = 1.5, "a", (1, object()), [], MyObject() |
| 774 | |
| 775 | d = dict() |
| 776 | self._not_tracked(d) |
| 777 | d[1] = "a" |
| 778 | self._not_tracked(d) |
| 779 | d[y] = 2 |
| 780 | self._not_tracked(d) |
| 781 | d[z] = 3 |
| 782 | self._not_tracked(d) |
| 783 | self._not_tracked(d.copy()) |
| 784 | d[4] = w |
| 785 | self._tracked(d) |
| 786 | self._tracked(d.copy()) |
| 787 | d[4] = None |
| 788 | self._not_tracked(d) |
| 789 | self._not_tracked(d.copy()) |
| 790 | |
| 791 | # dd isn't tracked right now, but it may mutate and therefore d |
| 792 | # which contains it must be tracked. |
| 793 | d = dict() |
| 794 | dd = dict() |
| 795 | d[1] = dd |
| 796 | self._not_tracked(dd) |
| 797 | self._tracked(d) |
| 798 | dd[1] = d |
| 799 | self._tracked(dd) |
| 800 | |
| 801 | d = dict.fromkeys([x, y, z]) |
| 802 | self._not_tracked(d) |
| 803 | dd = dict() |
| 804 | dd.update(d) |
| 805 | self._not_tracked(dd) |
| 806 | d = dict.fromkeys([x, y, z, o]) |
| 807 | self._tracked(d) |
| 808 | dd = dict() |
| 809 | dd.update(d) |
| 810 | self._tracked(dd) |
| 811 | |
| 812 | d = dict(x=x, y=y, z=z) |
| 813 | self._not_tracked(d) |
| 814 | d = dict(x=x, y=y, z=z, w=w) |
| 815 | self._tracked(d) |
| 816 | d = dict() |
| 817 | d.update(x=x, y=y, z=z) |
| 818 | self._not_tracked(d) |
| 819 | d.update(w=w) |
| 820 | self._tracked(d) |
| 821 | |
| 822 | d = dict([(x, y), (z, 1)]) |
| 823 | self._not_tracked(d) |
| 824 | d = dict([(x, y), (z, w)]) |
| 825 | self._tracked(d) |
| 826 | d = dict() |
| 827 | d.update([(x, y), (z, 1)]) |
| 828 | self._not_tracked(d) |
| 829 | d.update([(x, y), (z, w)]) |
| 830 | self._tracked(d) |
| 831 | |
Benjamin Peterson | 3e5cd1d | 2010-06-27 21:45:24 +0000 | [diff] [blame] | 832 | @support.cpython_only |
Antoine Pitrou | 3a652b1 | 2009-03-23 18:52:06 +0000 | [diff] [blame] | 833 | def test_track_subtypes(self): |
| 834 | # Dict subtypes are always tracked |
| 835 | class MyDict(dict): |
| 836 | pass |
| 837 | self._tracked(MyDict()) |
| 838 | |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 839 | def test_iterator_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 840 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 841 | data = {1:"a", 2:"b", 3:"c"} |
| 842 | it = iter(data) |
| 843 | d = pickle.dumps(it, proto) |
| 844 | it = pickle.loads(d) |
| 845 | self.assertEqual(sorted(it), sorted(data)) |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 846 | |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 847 | it = pickle.loads(d) |
| 848 | try: |
| 849 | drop = next(it) |
| 850 | except StopIteration: |
| 851 | continue |
| 852 | d = pickle.dumps(it, proto) |
| 853 | it = pickle.loads(d) |
| 854 | del data[drop] |
| 855 | self.assertEqual(sorted(it), sorted(data)) |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 856 | |
| 857 | def test_itemiterator_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 858 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 859 | data = {1:"a", 2:"b", 3:"c"} |
| 860 | # dictviews aren't picklable, only their iterators |
| 861 | itorg = iter(data.items()) |
| 862 | d = pickle.dumps(itorg, proto) |
| 863 | it = pickle.loads(d) |
Martin Panter | a90a4a9 | 2016-05-30 04:04:50 +0000 | [diff] [blame] | 864 | # note that the type of the unpickled iterator |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 865 | # is not necessarily the same as the original. It is |
| 866 | # merely an object supporting the iterator protocol, yielding |
| 867 | # the same objects as the original one. |
| 868 | # self.assertEqual(type(itorg), type(it)) |
| 869 | self.assertIsInstance(it, collections.abc.Iterator) |
| 870 | self.assertEqual(dict(it), data) |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 871 | |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 872 | it = pickle.loads(d) |
| 873 | drop = next(it) |
| 874 | d = pickle.dumps(it, proto) |
| 875 | it = pickle.loads(d) |
| 876 | del data[drop[0]] |
| 877 | self.assertEqual(dict(it), data) |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 878 | |
| 879 | def test_valuesiterator_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 880 | for proto in range(pickle.HIGHEST_PROTOCOL): |
| 881 | data = {1:"a", 2:"b", 3:"c"} |
| 882 | # data.values() isn't picklable, only its iterator |
| 883 | it = iter(data.values()) |
| 884 | d = pickle.dumps(it, proto) |
| 885 | it = pickle.loads(d) |
| 886 | self.assertEqual(sorted(list(it)), sorted(list(data.values()))) |
Kristján Valur Jónsson | 31668b8 | 2012-04-03 10:49:41 +0000 | [diff] [blame] | 887 | |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 888 | it = pickle.loads(d) |
| 889 | drop = next(it) |
| 890 | d = pickle.dumps(it, proto) |
| 891 | it = pickle.loads(d) |
| 892 | values = list(it) + [drop] |
| 893 | self.assertEqual(sorted(values), sorted(list(data.values()))) |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 894 | |
Benjamin Peterson | db780d0 | 2012-04-23 13:44:32 -0400 | [diff] [blame] | 895 | def test_instance_dict_getattr_str_subclass(self): |
| 896 | class Foo: |
| 897 | def __init__(self, msg): |
| 898 | self.msg = msg |
| 899 | f = Foo('123') |
| 900 | class _str(str): |
| 901 | pass |
| 902 | self.assertEqual(f.msg, getattr(f, _str('msg'))) |
| 903 | self.assertEqual(f.msg, f.__dict__[_str('msg')]) |
| 904 | |
Benjamin Peterson | 15ee821 | 2012-04-24 14:44:18 -0400 | [diff] [blame] | 905 | def test_object_set_item_single_instance_non_str_key(self): |
| 906 | class Foo: pass |
| 907 | f = Foo() |
| 908 | f.__dict__[1] = 1 |
| 909 | f.a = 'a' |
| 910 | self.assertEqual(f.__dict__, {1:1, 'a':'a'}) |
| 911 | |
Antoine Pitrou | d696732 | 2014-10-18 00:35:00 +0200 | [diff] [blame] | 912 | def check_reentrant_insertion(self, mutate): |
| 913 | # This object will trigger mutation of the dict when replaced |
| 914 | # by another value. Note this relies on refcounting: the test |
| 915 | # won't achieve its purpose on fully-GCed Python implementations. |
| 916 | class Mutating: |
| 917 | def __del__(self): |
| 918 | mutate(d) |
| 919 | |
| 920 | d = {k: Mutating() for k in 'abcdefghijklmnopqr'} |
| 921 | for k in list(d): |
| 922 | d[k] = k |
| 923 | |
| 924 | def test_reentrant_insertion(self): |
| 925 | # Reentrant insertion shouldn't crash (see issue #22653) |
| 926 | def mutate(d): |
| 927 | d['b'] = 5 |
| 928 | self.check_reentrant_insertion(mutate) |
| 929 | |
| 930 | def mutate(d): |
| 931 | d.update(self.__dict__) |
| 932 | d.clear() |
| 933 | self.check_reentrant_insertion(mutate) |
| 934 | |
| 935 | def mutate(d): |
| 936 | while d: |
| 937 | d.popitem() |
| 938 | self.check_reentrant_insertion(mutate) |
| 939 | |
Benjamin Peterson | a82f77f | 2015-07-04 19:55:16 -0500 | [diff] [blame] | 940 | def test_merge_and_mutate(self): |
| 941 | class X: |
| 942 | def __hash__(self): |
| 943 | return 0 |
| 944 | |
| 945 | def __eq__(self, o): |
| 946 | other.clear() |
| 947 | return False |
| 948 | |
| 949 | l = [(i,0) for i in range(1, 1337)] |
| 950 | other = dict(l) |
| 951 | other[X()] = 0 |
| 952 | d = {X(): 0, 1: 1} |
| 953 | self.assertRaises(RuntimeError, d.update, other) |
Antoine Pitrou | d696732 | 2014-10-18 00:35:00 +0200 | [diff] [blame] | 954 | |
Serhiy Storchaka | fbb1c5e | 2016-03-30 20:40:02 +0300 | [diff] [blame] | 955 | def test_free_after_iterating(self): |
| 956 | support.check_free_after_iterating(self, iter, dict) |
| 957 | support.check_free_after_iterating(self, lambda d: iter(d.keys()), dict) |
| 958 | support.check_free_after_iterating(self, lambda d: iter(d.values()), dict) |
| 959 | support.check_free_after_iterating(self, lambda d: iter(d.items()), dict) |
| 960 | |
Neal Norwitz | c3e54b8 | 2006-03-24 07:38:37 +0000 | [diff] [blame] | 961 | from test import mapping_tests |
Raymond Hettinger | 49c522b | 2004-09-30 15:07:29 +0000 | [diff] [blame] | 962 | |
| 963 | class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 964 | type2test = dict |
| 965 | |
| 966 | class Dict(dict): |
| 967 | pass |
| 968 | |
| 969 | class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 970 | type2test = Dict |
| 971 | |
Walter Dörwald | 59b23e8 | 2004-09-30 13:46:00 +0000 | [diff] [blame] | 972 | if __name__ == "__main__": |
Zachary Ware | 38c707e | 2015-04-13 15:00:43 -0500 | [diff] [blame] | 973 | unittest.main() |