ยปCore Development>Code coverage>Lib/test/test_ordered_dict.py

Python code coverage for Lib/test/test_ordered_dict.py

#countcontent
1n/aimport builtins
2n/aimport contextlib
3n/aimport copy
4n/aimport gc
5n/aimport pickle
6n/afrom random import randrange, shuffle
7n/aimport struct
8n/aimport sys
9n/aimport unittest
10n/aimport weakref
11n/afrom collections.abc import MutableMapping
12n/afrom test import mapping_tests, support
13n/a
14n/a
15n/apy_coll = support.import_fresh_module('collections', blocked=['_collections'])
16n/ac_coll = support.import_fresh_module('collections', fresh=['_collections'])
17n/a
18n/a
19n/a@contextlib.contextmanager
20n/adef replaced_module(name, replacement):
21n/a original_module = sys.modules[name]
22n/a sys.modules[name] = replacement
23n/a try:
24n/a yield
25n/a finally:
26n/a sys.modules[name] = original_module
27n/a
28n/a
29n/aclass OrderedDictTests:
30n/a
31n/a def test_init(self):
32n/a OrderedDict = self.OrderedDict
33n/a with self.assertRaises(TypeError):
34n/a OrderedDict([('a', 1), ('b', 2)], None) # too many args
35n/a pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
36n/a self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input
37n/a self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input
38n/a self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input
39n/a self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)],
40n/a c=3, e=5).items()), pairs) # mixed input
41n/a
42n/a # make sure no positional args conflict with possible kwdargs
43n/a self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)])
44n/a self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)])
45n/a self.assertRaises(TypeError, OrderedDict, 42)
46n/a self.assertRaises(TypeError, OrderedDict, (), ())
47n/a self.assertRaises(TypeError, OrderedDict.__init__)
48n/a
49n/a # Make sure that direct calls to __init__ do not clear previous contents
50n/a d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
51n/a d.__init__([('e', 5), ('f', 6)], g=7, d=4)
52n/a self.assertEqual(list(d.items()),
53n/a [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
54n/a
55n/a def test_468(self):
56n/a OrderedDict = self.OrderedDict
57n/a items = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]
58n/a shuffle(items)
59n/a argdict = OrderedDict(items)
60n/a d = OrderedDict(**argdict)
61n/a self.assertEqual(list(d.items()), items)
62n/a
63n/a def test_update(self):
64n/a OrderedDict = self.OrderedDict
65n/a with self.assertRaises(TypeError):
66n/a OrderedDict().update([('a', 1), ('b', 2)], None) # too many args
67n/a pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
68n/a od = OrderedDict()
69n/a od.update(dict(pairs))
70n/a self.assertEqual(sorted(od.items()), pairs) # dict input
71n/a od = OrderedDict()
72n/a od.update(**dict(pairs))
73n/a self.assertEqual(sorted(od.items()), pairs) # kwds input
74n/a od = OrderedDict()
75n/a od.update(pairs)
76n/a self.assertEqual(list(od.items()), pairs) # pairs input
77n/a od = OrderedDict()
78n/a od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)
79n/a self.assertEqual(list(od.items()), pairs) # mixed input
80n/a
81n/a # Issue 9137: Named argument called 'other' or 'self'
82n/a # shouldn't be treated specially.
83n/a od = OrderedDict()
84n/a od.update(self=23)
85n/a self.assertEqual(list(od.items()), [('self', 23)])
86n/a od = OrderedDict()
87n/a od.update(other={})
88n/a self.assertEqual(list(od.items()), [('other', {})])
89n/a od = OrderedDict()
90n/a od.update(red=5, blue=6, other=7, self=8)
91n/a self.assertEqual(sorted(list(od.items())),
92n/a [('blue', 6), ('other', 7), ('red', 5), ('self', 8)])
93n/a
94n/a # Make sure that direct calls to update do not clear previous contents
95n/a # add that updates items are not moved to the end
96n/a d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
97n/a d.update([('e', 5), ('f', 6)], g=7, d=4)
98n/a self.assertEqual(list(d.items()),
99n/a [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
100n/a
101n/a self.assertRaises(TypeError, OrderedDict().update, 42)
102n/a self.assertRaises(TypeError, OrderedDict().update, (), ())
103n/a self.assertRaises(TypeError, OrderedDict.update)
104n/a
105n/a self.assertRaises(TypeError, OrderedDict().update, 42)
106n/a self.assertRaises(TypeError, OrderedDict().update, (), ())
107n/a self.assertRaises(TypeError, OrderedDict.update)
108n/a
109n/a def test_init_calls(self):
110n/a calls = []
111n/a class Spam:
112n/a def keys(self):
113n/a calls.append('keys')
114n/a return ()
115n/a def items(self):
116n/a calls.append('items')
117n/a return ()
118n/a
119n/a self.OrderedDict(Spam())
120n/a self.assertEqual(calls, ['keys'])
121n/a
122n/a def test_fromkeys(self):
123n/a OrderedDict = self.OrderedDict
124n/a od = OrderedDict.fromkeys('abc')
125n/a self.assertEqual(list(od.items()), [(c, None) for c in 'abc'])
126n/a od = OrderedDict.fromkeys('abc', value=None)
127n/a self.assertEqual(list(od.items()), [(c, None) for c in 'abc'])
128n/a od = OrderedDict.fromkeys('abc', value=0)
129n/a self.assertEqual(list(od.items()), [(c, 0) for c in 'abc'])
130n/a
131n/a def test_abc(self):
132n/a OrderedDict = self.OrderedDict
133n/a self.assertIsInstance(OrderedDict(), MutableMapping)
134n/a self.assertTrue(issubclass(OrderedDict, MutableMapping))
135n/a
136n/a def test_clear(self):
137n/a OrderedDict = self.OrderedDict
138n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
139n/a shuffle(pairs)
140n/a od = OrderedDict(pairs)
141n/a self.assertEqual(len(od), len(pairs))
142n/a od.clear()
143n/a self.assertEqual(len(od), 0)
144n/a
145n/a def test_delitem(self):
146n/a OrderedDict = self.OrderedDict
147n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
148n/a od = OrderedDict(pairs)
149n/a del od['a']
150n/a self.assertNotIn('a', od)
151n/a with self.assertRaises(KeyError):
152n/a del od['a']
153n/a self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
154n/a
155n/a def test_setitem(self):
156n/a OrderedDict = self.OrderedDict
157n/a od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)])
158n/a od['c'] = 10 # existing element
159n/a od['f'] = 20 # new element
160n/a self.assertEqual(list(od.items()),
161n/a [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)])
162n/a
163n/a def test_iterators(self):
164n/a OrderedDict = self.OrderedDict
165n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
166n/a shuffle(pairs)
167n/a od = OrderedDict(pairs)
168n/a self.assertEqual(list(od), [t[0] for t in pairs])
169n/a self.assertEqual(list(od.keys()), [t[0] for t in pairs])
170n/a self.assertEqual(list(od.values()), [t[1] for t in pairs])
171n/a self.assertEqual(list(od.items()), pairs)
172n/a self.assertEqual(list(reversed(od)),
173n/a [t[0] for t in reversed(pairs)])
174n/a self.assertEqual(list(reversed(od.keys())),
175n/a [t[0] for t in reversed(pairs)])
176n/a self.assertEqual(list(reversed(od.values())),
177n/a [t[1] for t in reversed(pairs)])
178n/a self.assertEqual(list(reversed(od.items())), list(reversed(pairs)))
179n/a
180n/a def test_detect_deletion_during_iteration(self):
181n/a OrderedDict = self.OrderedDict
182n/a od = OrderedDict.fromkeys('abc')
183n/a it = iter(od)
184n/a key = next(it)
185n/a del od[key]
186n/a with self.assertRaises(Exception):
187n/a # Note, the exact exception raised is not guaranteed
188n/a # The only guarantee that the next() will not succeed
189n/a next(it)
190n/a
191n/a def test_sorted_iterators(self):
192n/a OrderedDict = self.OrderedDict
193n/a with self.assertRaises(TypeError):
194n/a OrderedDict([('a', 1), ('b', 2)], None)
195n/a pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
196n/a od = OrderedDict(pairs)
197n/a self.assertEqual(sorted(od), [t[0] for t in pairs])
198n/a self.assertEqual(sorted(od.keys()), [t[0] for t in pairs])
199n/a self.assertEqual(sorted(od.values()), [t[1] for t in pairs])
200n/a self.assertEqual(sorted(od.items()), pairs)
201n/a self.assertEqual(sorted(reversed(od)),
202n/a sorted([t[0] for t in reversed(pairs)]))
203n/a
204n/a def test_iterators_empty(self):
205n/a OrderedDict = self.OrderedDict
206n/a od = OrderedDict()
207n/a empty = []
208n/a self.assertEqual(list(od), empty)
209n/a self.assertEqual(list(od.keys()), empty)
210n/a self.assertEqual(list(od.values()), empty)
211n/a self.assertEqual(list(od.items()), empty)
212n/a self.assertEqual(list(reversed(od)), empty)
213n/a self.assertEqual(list(reversed(od.keys())), empty)
214n/a self.assertEqual(list(reversed(od.values())), empty)
215n/a self.assertEqual(list(reversed(od.items())), empty)
216n/a
217n/a def test_popitem(self):
218n/a OrderedDict = self.OrderedDict
219n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
220n/a shuffle(pairs)
221n/a od = OrderedDict(pairs)
222n/a while pairs:
223n/a self.assertEqual(od.popitem(), pairs.pop())
224n/a with self.assertRaises(KeyError):
225n/a od.popitem()
226n/a self.assertEqual(len(od), 0)
227n/a
228n/a def test_popitem_last(self):
229n/a OrderedDict = self.OrderedDict
230n/a pairs = [(i, i) for i in range(30)]
231n/a
232n/a obj = OrderedDict(pairs)
233n/a for i in range(8):
234n/a obj.popitem(True)
235n/a obj.popitem(True)
236n/a obj.popitem(last=True)
237n/a self.assertEqual(len(obj), 20)
238n/a
239n/a def test_pop(self):
240n/a OrderedDict = self.OrderedDict
241n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
242n/a shuffle(pairs)
243n/a od = OrderedDict(pairs)
244n/a shuffle(pairs)
245n/a while pairs:
246n/a k, v = pairs.pop()
247n/a self.assertEqual(od.pop(k), v)
248n/a with self.assertRaises(KeyError):
249n/a od.pop('xyz')
250n/a self.assertEqual(len(od), 0)
251n/a self.assertEqual(od.pop(k, 12345), 12345)
252n/a
253n/a # make sure pop still works when __missing__ is defined
254n/a class Missing(OrderedDict):
255n/a def __missing__(self, key):
256n/a return 0
257n/a m = Missing(a=1)
258n/a self.assertEqual(m.pop('b', 5), 5)
259n/a self.assertEqual(m.pop('a', 6), 1)
260n/a self.assertEqual(m.pop('a', 6), 6)
261n/a self.assertEqual(m.pop('a', default=6), 6)
262n/a with self.assertRaises(KeyError):
263n/a m.pop('a')
264n/a
265n/a def test_equality(self):
266n/a OrderedDict = self.OrderedDict
267n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
268n/a shuffle(pairs)
269n/a od1 = OrderedDict(pairs)
270n/a od2 = OrderedDict(pairs)
271n/a self.assertEqual(od1, od2) # same order implies equality
272n/a pairs = pairs[2:] + pairs[:2]
273n/a od2 = OrderedDict(pairs)
274n/a self.assertNotEqual(od1, od2) # different order implies inequality
275n/a # comparison to regular dict is not order sensitive
276n/a self.assertEqual(od1, dict(od2))
277n/a self.assertEqual(dict(od2), od1)
278n/a # different length implied inequality
279n/a self.assertNotEqual(od1, OrderedDict(pairs[:-1]))
280n/a
281n/a def test_copying(self):
282n/a OrderedDict = self.OrderedDict
283n/a # Check that ordered dicts are copyable, deepcopyable, picklable,
284n/a # and have a repr/eval round-trip
285n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
286n/a od = OrderedDict(pairs)
287n/a def check(dup):
288n/a msg = "\ncopy: %s\nod: %s" % (dup, od)
289n/a self.assertIsNot(dup, od, msg)
290n/a self.assertEqual(dup, od)
291n/a self.assertEqual(list(dup.items()), list(od.items()))
292n/a self.assertEqual(len(dup), len(od))
293n/a self.assertEqual(type(dup), type(od))
294n/a check(od.copy())
295n/a check(copy.copy(od))
296n/a check(copy.deepcopy(od))
297n/a # pickle directly pulls the module, so we have to fake it
298n/a with replaced_module('collections', self.module):
299n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
300n/a with self.subTest(proto=proto):
301n/a check(pickle.loads(pickle.dumps(od, proto)))
302n/a check(eval(repr(od)))
303n/a update_test = OrderedDict()
304n/a update_test.update(od)
305n/a check(update_test)
306n/a check(OrderedDict(od))
307n/a
308n/a def test_yaml_linkage(self):
309n/a OrderedDict = self.OrderedDict
310n/a # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
311n/a # In yaml, lists are native but tuples are not.
312n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
313n/a od = OrderedDict(pairs)
314n/a # yaml.dump(od) -->
315n/a # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n'
316n/a self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))
317n/a
318n/a def test_reduce_not_too_fat(self):
319n/a OrderedDict = self.OrderedDict
320n/a # do not save instance dictionary if not needed
321n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
322n/a od = OrderedDict(pairs)
323n/a self.assertIsInstance(od.__dict__, dict)
324n/a self.assertIsNone(od.__reduce__()[2])
325n/a od.x = 10
326n/a self.assertEqual(od.__dict__['x'], 10)
327n/a self.assertEqual(od.__reduce__()[2], {'x': 10})
328n/a
329n/a def test_pickle_recursive(self):
330n/a OrderedDict = self.OrderedDict
331n/a od = OrderedDict()
332n/a od[1] = od
333n/a
334n/a # pickle directly pulls the module, so we have to fake it
335n/a with replaced_module('collections', self.module):
336n/a for proto in range(-1, pickle.HIGHEST_PROTOCOL + 1):
337n/a dup = pickle.loads(pickle.dumps(od, proto))
338n/a self.assertIsNot(dup, od)
339n/a self.assertEqual(list(dup.keys()), [1])
340n/a self.assertIs(dup[1], dup)
341n/a
342n/a def test_repr(self):
343n/a OrderedDict = self.OrderedDict
344n/a od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])
345n/a self.assertEqual(repr(od),
346n/a "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])")
347n/a self.assertEqual(eval(repr(od)), od)
348n/a self.assertEqual(repr(OrderedDict()), "OrderedDict()")
349n/a
350n/a def test_repr_recursive(self):
351n/a OrderedDict = self.OrderedDict
352n/a # See issue #9826
353n/a od = OrderedDict.fromkeys('abc')
354n/a od['x'] = od
355n/a self.assertEqual(repr(od),
356n/a "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])")
357n/a
358n/a def test_setdefault(self):
359n/a OrderedDict = self.OrderedDict
360n/a pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
361n/a shuffle(pairs)
362n/a od = OrderedDict(pairs)
363n/a pair_order = list(od.items())
364n/a self.assertEqual(od.setdefault('a', 10), 3)
365n/a # make sure order didn't change
366n/a self.assertEqual(list(od.items()), pair_order)
367n/a self.assertEqual(od.setdefault('x', 10), 10)
368n/a # make sure 'x' is added to the end
369n/a self.assertEqual(list(od.items())[-1], ('x', 10))
370n/a self.assertEqual(od.setdefault('g', default=9), 9)
371n/a
372n/a # make sure setdefault still works when __missing__ is defined
373n/a class Missing(OrderedDict):
374n/a def __missing__(self, key):
375n/a return 0
376n/a self.assertEqual(Missing().setdefault(5, 9), 9)
377n/a
378n/a def test_reinsert(self):
379n/a OrderedDict = self.OrderedDict
380n/a # Given insert a, insert b, delete a, re-insert a,
381n/a # verify that a is now later than b.
382n/a od = OrderedDict()
383n/a od['a'] = 1
384n/a od['b'] = 2
385n/a del od['a']
386n/a self.assertEqual(list(od.items()), [('b', 2)])
387n/a od['a'] = 1
388n/a self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])
389n/a
390n/a def test_move_to_end(self):
391n/a OrderedDict = self.OrderedDict
392n/a od = OrderedDict.fromkeys('abcde')
393n/a self.assertEqual(list(od), list('abcde'))
394n/a od.move_to_end('c')
395n/a self.assertEqual(list(od), list('abdec'))
396n/a od.move_to_end('c', 0)
397n/a self.assertEqual(list(od), list('cabde'))
398n/a od.move_to_end('c', 0)
399n/a self.assertEqual(list(od), list('cabde'))
400n/a od.move_to_end('e')
401n/a self.assertEqual(list(od), list('cabde'))
402n/a od.move_to_end('b', last=False)
403n/a self.assertEqual(list(od), list('bcade'))
404n/a with self.assertRaises(KeyError):
405n/a od.move_to_end('x')
406n/a with self.assertRaises(KeyError):
407n/a od.move_to_end('x', 0)
408n/a
409n/a def test_move_to_end_issue25406(self):
410n/a OrderedDict = self.OrderedDict
411n/a od = OrderedDict.fromkeys('abc')
412n/a od.move_to_end('c', last=False)
413n/a self.assertEqual(list(od), list('cab'))
414n/a od.move_to_end('a', last=False)
415n/a self.assertEqual(list(od), list('acb'))
416n/a
417n/a od = OrderedDict.fromkeys('abc')
418n/a od.move_to_end('a')
419n/a self.assertEqual(list(od), list('bca'))
420n/a od.move_to_end('c')
421n/a self.assertEqual(list(od), list('bac'))
422n/a
423n/a def test_sizeof(self):
424n/a OrderedDict = self.OrderedDict
425n/a # Wimpy test: Just verify the reported size is larger than a regular dict
426n/a d = dict(a=1)
427n/a od = OrderedDict(**d)
428n/a self.assertGreater(sys.getsizeof(od), sys.getsizeof(d))
429n/a
430n/a def test_views(self):
431n/a OrderedDict = self.OrderedDict
432n/a # See http://bugs.python.org/issue24286
433n/a s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split()
434n/a od = OrderedDict.fromkeys(s)
435n/a self.assertEqual(od.keys(), dict(od).keys())
436n/a self.assertEqual(od.items(), dict(od).items())
437n/a
438n/a def test_override_update(self):
439n/a OrderedDict = self.OrderedDict
440n/a # Verify that subclasses can override update() without breaking __init__()
441n/a class MyOD(OrderedDict):
442n/a def update(self, *args, **kwds):
443n/a raise Exception()
444n/a items = [('a', 1), ('c', 3), ('b', 2)]
445n/a self.assertEqual(list(MyOD(items).items()), items)
446n/a
447n/a def test_highly_nested(self):
448n/a # Issue 25395: crashes during garbage collection
449n/a OrderedDict = self.OrderedDict
450n/a obj = None
451n/a for _ in range(1000):
452n/a obj = OrderedDict([(None, obj)])
453n/a del obj
454n/a support.gc_collect()
455n/a
456n/a def test_highly_nested_subclass(self):
457n/a # Issue 25395: crashes during garbage collection
458n/a OrderedDict = self.OrderedDict
459n/a deleted = []
460n/a class MyOD(OrderedDict):
461n/a def __del__(self):
462n/a deleted.append(self.i)
463n/a obj = None
464n/a for i in range(100):
465n/a obj = MyOD([(None, obj)])
466n/a obj.i = i
467n/a del obj
468n/a support.gc_collect()
469n/a self.assertEqual(deleted, list(reversed(range(100))))
470n/a
471n/a def test_delitem_hash_collision(self):
472n/a OrderedDict = self.OrderedDict
473n/a
474n/a class Key:
475n/a def __init__(self, hash):
476n/a self._hash = hash
477n/a self.value = str(id(self))
478n/a def __hash__(self):
479n/a return self._hash
480n/a def __eq__(self, other):
481n/a try:
482n/a return self.value == other.value
483n/a except AttributeError:
484n/a return False
485n/a def __repr__(self):
486n/a return self.value
487n/a
488n/a def blocking_hash(hash):
489n/a # See the collision-handling in lookdict (in Objects/dictobject.c).
490n/a MINSIZE = 8
491n/a i = (hash & MINSIZE-1)
492n/a return (i << 2) + i + hash + 1
493n/a
494n/a COLLIDING = 1
495n/a
496n/a key = Key(COLLIDING)
497n/a colliding = Key(COLLIDING)
498n/a blocking = Key(blocking_hash(COLLIDING))
499n/a
500n/a od = OrderedDict()
501n/a od[key] = ...
502n/a od[blocking] = ...
503n/a od[colliding] = ...
504n/a od['after'] = ...
505n/a
506n/a del od[blocking]
507n/a del od[colliding]
508n/a self.assertEqual(list(od.items()), [(key, ...), ('after', ...)])
509n/a
510n/a def test_issue24347(self):
511n/a OrderedDict = self.OrderedDict
512n/a
513n/a class Key:
514n/a def __hash__(self):
515n/a return randrange(100000)
516n/a
517n/a od = OrderedDict()
518n/a for i in range(100):
519n/a key = Key()
520n/a od[key] = i
521n/a
522n/a # These should not crash.
523n/a with self.assertRaises(KeyError):
524n/a list(od.values())
525n/a with self.assertRaises(KeyError):
526n/a list(od.items())
527n/a with self.assertRaises(KeyError):
528n/a repr(od)
529n/a with self.assertRaises(KeyError):
530n/a od.copy()
531n/a
532n/a def test_issue24348(self):
533n/a OrderedDict = self.OrderedDict
534n/a
535n/a class Key:
536n/a def __hash__(self):
537n/a return 1
538n/a
539n/a od = OrderedDict()
540n/a od[Key()] = 0
541n/a # This should not crash.
542n/a od.popitem()
543n/a
544n/a def test_issue24667(self):
545n/a """
546n/a dict resizes after a certain number of insertion operations,
547n/a whether or not there were deletions that freed up slots in the
548n/a hash table. During fast node lookup, OrderedDict must correctly
549n/a respond to all resizes, even if the current "size" is the same
550n/a as the old one. We verify that here by forcing a dict resize
551n/a on a sparse odict and then perform an operation that should
552n/a trigger an odict resize (e.g. popitem). One key aspect here is
553n/a that we will keep the size of the odict the same at each popitem
554n/a call. This verifies that we handled the dict resize properly.
555n/a """
556n/a OrderedDict = self.OrderedDict
557n/a
558n/a od = OrderedDict()
559n/a for c0 in '0123456789ABCDEF':
560n/a for c1 in '0123456789ABCDEF':
561n/a if len(od) == 4:
562n/a # This should not raise a KeyError.
563n/a od.popitem(last=False)
564n/a key = c0 + c1
565n/a od[key] = key
566n/a
567n/a # Direct use of dict methods
568n/a
569n/a def test_dict_setitem(self):
570n/a OrderedDict = self.OrderedDict
571n/a od = OrderedDict()
572n/a dict.__setitem__(od, 'spam', 1)
573n/a self.assertNotIn('NULL', repr(od))
574n/a
575n/a def test_dict_delitem(self):
576n/a OrderedDict = self.OrderedDict
577n/a od = OrderedDict()
578n/a od['spam'] = 1
579n/a od['ham'] = 2
580n/a dict.__delitem__(od, 'spam')
581n/a with self.assertRaises(KeyError):
582n/a repr(od)
583n/a
584n/a def test_dict_clear(self):
585n/a OrderedDict = self.OrderedDict
586n/a od = OrderedDict()
587n/a od['spam'] = 1
588n/a od['ham'] = 2
589n/a dict.clear(od)
590n/a self.assertNotIn('NULL', repr(od))
591n/a
592n/a def test_dict_pop(self):
593n/a OrderedDict = self.OrderedDict
594n/a od = OrderedDict()
595n/a od['spam'] = 1
596n/a od['ham'] = 2
597n/a dict.pop(od, 'spam')
598n/a with self.assertRaises(KeyError):
599n/a repr(od)
600n/a
601n/a def test_dict_popitem(self):
602n/a OrderedDict = self.OrderedDict
603n/a od = OrderedDict()
604n/a od['spam'] = 1
605n/a od['ham'] = 2
606n/a dict.popitem(od)
607n/a with self.assertRaises(KeyError):
608n/a repr(od)
609n/a
610n/a def test_dict_setdefault(self):
611n/a OrderedDict = self.OrderedDict
612n/a od = OrderedDict()
613n/a dict.setdefault(od, 'spam', 1)
614n/a self.assertNotIn('NULL', repr(od))
615n/a
616n/a def test_dict_update(self):
617n/a OrderedDict = self.OrderedDict
618n/a od = OrderedDict()
619n/a dict.update(od, [('spam', 1)])
620n/a self.assertNotIn('NULL', repr(od))
621n/a
622n/a def test_reference_loop(self):
623n/a # Issue 25935
624n/a OrderedDict = self.OrderedDict
625n/a class A:
626n/a od = OrderedDict()
627n/a A.od[A] = None
628n/a r = weakref.ref(A)
629n/a del A
630n/a gc.collect()
631n/a self.assertIsNone(r())
632n/a
633n/a def test_free_after_iterating(self):
634n/a support.check_free_after_iterating(self, iter, self.OrderedDict)
635n/a support.check_free_after_iterating(self, lambda d: iter(d.keys()), self.OrderedDict)
636n/a support.check_free_after_iterating(self, lambda d: iter(d.values()), self.OrderedDict)
637n/a support.check_free_after_iterating(self, lambda d: iter(d.items()), self.OrderedDict)
638n/a
639n/a
640n/aclass PurePythonOrderedDictTests(OrderedDictTests, unittest.TestCase):
641n/a
642n/a module = py_coll
643n/a OrderedDict = py_coll.OrderedDict
644n/a
645n/a
646n/aclass CPythonBuiltinDictTests(unittest.TestCase):
647n/a """Builtin dict preserves insertion order.
648n/a
649n/a Reuse some of tests in OrderedDict selectively.
650n/a """
651n/a
652n/a module = builtins
653n/a OrderedDict = dict
654n/a
655n/afor method in (
656n/a "test_init test_update test_abc test_clear test_delitem " +
657n/a "test_setitem test_detect_deletion_during_iteration " +
658n/a "test_popitem test_reinsert test_override_update " +
659n/a "test_highly_nested test_highly_nested_subclass " +
660n/a "test_delitem_hash_collision ").split():
661n/a setattr(CPythonBuiltinDictTests, method, getattr(OrderedDictTests, method))
662n/adel method
663n/a
664n/a
665n/a@unittest.skipUnless(c_coll, 'requires the C version of the collections module')
666n/aclass CPythonOrderedDictTests(OrderedDictTests, unittest.TestCase):
667n/a
668n/a module = c_coll
669n/a OrderedDict = c_coll.OrderedDict
670n/a check_sizeof = support.check_sizeof
671n/a
672n/a @support.cpython_only
673n/a def test_sizeof_exact(self):
674n/a OrderedDict = self.OrderedDict
675n/a calcsize = struct.calcsize
676n/a size = support.calcobjsize
677n/a check = self.check_sizeof
678n/a
679n/a basicsize = size('nQ2P' + '3PnPn2P') + calcsize('2nP2n')
680n/a
681n/a entrysize = calcsize('n2P')
682n/a p = calcsize('P')
683n/a nodesize = calcsize('Pn2P')
684n/a
685n/a od = OrderedDict()
686n/a check(od, basicsize + 8*p + 8 + 5*entrysize) # 8byte indicies + 8*2//3 * entry table
687n/a od.x = 1
688n/a check(od, basicsize + 8*p + 8 + 5*entrysize)
689n/a od.update([(i, i) for i in range(3)])
690n/a check(od, basicsize + 8*p + 8 + 5*entrysize + 3*nodesize)
691n/a od.update([(i, i) for i in range(3, 10)])
692n/a check(od, basicsize + 16*p + 16 + 10*entrysize + 10*nodesize)
693n/a
694n/a check(od.keys(), size('P'))
695n/a check(od.items(), size('P'))
696n/a check(od.values(), size('P'))
697n/a
698n/a itersize = size('iP2n2P')
699n/a check(iter(od), itersize)
700n/a check(iter(od.keys()), itersize)
701n/a check(iter(od.items()), itersize)
702n/a check(iter(od.values()), itersize)
703n/a
704n/a def test_key_change_during_iteration(self):
705n/a OrderedDict = self.OrderedDict
706n/a
707n/a od = OrderedDict.fromkeys('abcde')
708n/a self.assertEqual(list(od), list('abcde'))
709n/a with self.assertRaises(RuntimeError):
710n/a for i, k in enumerate(od):
711n/a od.move_to_end(k)
712n/a self.assertLess(i, 5)
713n/a with self.assertRaises(RuntimeError):
714n/a for k in od:
715n/a od['f'] = None
716n/a with self.assertRaises(RuntimeError):
717n/a for k in od:
718n/a del od['c']
719n/a self.assertEqual(list(od), list('bdeaf'))
720n/a
721n/a
722n/aclass PurePythonOrderedDictSubclassTests(PurePythonOrderedDictTests):
723n/a
724n/a module = py_coll
725n/a class OrderedDict(py_coll.OrderedDict):
726n/a pass
727n/a
728n/a
729n/aclass CPythonOrderedDictSubclassTests(CPythonOrderedDictTests):
730n/a
731n/a module = c_coll
732n/a class OrderedDict(c_coll.OrderedDict):
733n/a pass
734n/a
735n/a
736n/aclass PurePythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
737n/a
738n/a @classmethod
739n/a def setUpClass(cls):
740n/a cls.type2test = py_coll.OrderedDict
741n/a
742n/a def test_popitem(self):
743n/a d = self._empty_mapping()
744n/a self.assertRaises(KeyError, d.popitem)
745n/a
746n/a
747n/a@unittest.skipUnless(c_coll, 'requires the C version of the collections module')
748n/aclass CPythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
749n/a
750n/a @classmethod
751n/a def setUpClass(cls):
752n/a cls.type2test = c_coll.OrderedDict
753n/a
754n/a def test_popitem(self):
755n/a d = self._empty_mapping()
756n/a self.assertRaises(KeyError, d.popitem)
757n/a
758n/a
759n/aclass PurePythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
760n/a
761n/a @classmethod
762n/a def setUpClass(cls):
763n/a class MyOrderedDict(py_coll.OrderedDict):
764n/a pass
765n/a cls.type2test = MyOrderedDict
766n/a
767n/a def test_popitem(self):
768n/a d = self._empty_mapping()
769n/a self.assertRaises(KeyError, d.popitem)
770n/a
771n/a
772n/a@unittest.skipUnless(c_coll, 'requires the C version of the collections module')
773n/aclass CPythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
774n/a
775n/a @classmethod
776n/a def setUpClass(cls):
777n/a class MyOrderedDict(c_coll.OrderedDict):
778n/a pass
779n/a cls.type2test = MyOrderedDict
780n/a
781n/a def test_popitem(self):
782n/a d = self._empty_mapping()
783n/a self.assertRaises(KeyError, d.popitem)
784n/a
785n/a
786n/aif __name__ == "__main__":
787n/a unittest.main()