Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1 | """Unit tests for collections.py.""" |
| 2 | |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 3 | import unittest, doctest, operator |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 4 | from test.support import TESTFN, forget, unlink, import_fresh_module |
| 5 | import contextlib |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 6 | import inspect |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 7 | from test import support |
Raymond Hettinger | 426e052 | 2011-01-03 02:12:02 +0000 | [diff] [blame] | 8 | from collections import namedtuple, Counter, OrderedDict, _count_elements |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 9 | from test import mapping_tests |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 10 | import pickle, copy |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 11 | from random import randrange, shuffle |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 12 | import keyword |
| 13 | import re |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 14 | import sys |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 15 | import types |
Raymond Hettinger | 573b44c | 2015-05-22 16:56:32 -0700 | [diff] [blame] | 16 | from collections import UserDict, UserString, UserList |
Raymond Hettinger | 9fe1ccf | 2011-02-26 01:02:51 +0000 | [diff] [blame] | 17 | from collections import ChainMap |
Raymond Hettinger | 32ea165 | 2015-03-21 01:37:37 -0700 | [diff] [blame] | 18 | from collections import deque |
Yury Selivanov | e0104ae | 2015-05-14 12:19:16 -0400 | [diff] [blame] | 19 | from collections.abc import Awaitable, Coroutine, AsyncIterator, AsyncIterable |
Raymond Hettinger | bd60e8d | 2015-05-09 01:07:23 -0400 | [diff] [blame] | 20 | from collections.abc import Hashable, Iterable, Iterator, Generator |
Raymond Hettinger | 57d1a88 | 2011-02-23 00:46:28 +0000 | [diff] [blame] | 21 | from collections.abc import Sized, Container, Callable |
| 22 | from collections.abc import Set, MutableSet |
| 23 | from collections.abc import Mapping, MutableMapping, KeysView, ItemsView |
| 24 | from collections.abc import Sequence, MutableSequence |
| 25 | from collections.abc import ByteString |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 26 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 27 | |
Raymond Hettinger | 573b44c | 2015-05-22 16:56:32 -0700 | [diff] [blame] | 28 | class TestUserObjects(unittest.TestCase): |
| 29 | def _superset_test(self, a, b): |
| 30 | self.assertGreaterEqual( |
| 31 | set(dir(a)), |
| 32 | set(dir(b)), |
| 33 | '{a} should have all the methods of {b}'.format( |
| 34 | a=a.__name__, |
| 35 | b=b.__name__, |
| 36 | ), |
| 37 | ) |
| 38 | def test_str_protocol(self): |
| 39 | self._superset_test(UserString, str) |
| 40 | |
| 41 | def test_list_protocol(self): |
| 42 | self._superset_test(UserList, list) |
| 43 | |
| 44 | def test_dict_protocol(self): |
| 45 | self._superset_test(UserDict, dict) |
| 46 | |
| 47 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 48 | ################################################################################ |
Raymond Hettinger | 9fe1ccf | 2011-02-26 01:02:51 +0000 | [diff] [blame] | 49 | ### ChainMap (helper class for configparser and the string module) |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 50 | ################################################################################ |
| 51 | |
| 52 | class TestChainMap(unittest.TestCase): |
| 53 | |
| 54 | def test_basics(self): |
| 55 | c = ChainMap() |
| 56 | c['a'] = 1 |
| 57 | c['b'] = 2 |
| 58 | d = c.new_child() |
| 59 | d['b'] = 20 |
| 60 | d['c'] = 30 |
| 61 | self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state |
| 62 | self.assertEqual(d.items(), dict(a=1, b=20, c=30).items()) # check items/iter/getitem |
| 63 | self.assertEqual(len(d), 3) # check len |
| 64 | for key in 'abc': # check contains |
| 65 | self.assertIn(key, d) |
| 66 | for k, v in dict(a=1, b=20, c=30, z=100).items(): # check get |
| 67 | self.assertEqual(d.get(k, 100), v) |
| 68 | |
| 69 | del d['b'] # unmask a value |
| 70 | self.assertEqual(d.maps, [{'c':30}, {'a':1, 'b':2}]) # check internal state |
| 71 | self.assertEqual(d.items(), dict(a=1, b=2, c=30).items()) # check items/iter/getitem |
| 72 | self.assertEqual(len(d), 3) # check len |
| 73 | for key in 'abc': # check contains |
| 74 | self.assertIn(key, d) |
| 75 | for k, v in dict(a=1, b=2, c=30, z=100).items(): # check get |
| 76 | self.assertEqual(d.get(k, 100), v) |
| 77 | self.assertIn(repr(d), [ # check repr |
| 78 | type(d).__name__ + "({'c': 30}, {'a': 1, 'b': 2})", |
| 79 | type(d).__name__ + "({'c': 30}, {'b': 2, 'a': 1})" |
| 80 | ]) |
| 81 | |
| 82 | for e in d.copy(), copy.copy(d): # check shallow copies |
| 83 | self.assertEqual(d, e) |
| 84 | self.assertEqual(d.maps, e.maps) |
| 85 | self.assertIsNot(d, e) |
| 86 | self.assertIsNot(d.maps[0], e.maps[0]) |
| 87 | for m1, m2 in zip(d.maps[1:], e.maps[1:]): |
| 88 | self.assertIs(m1, m2) |
| 89 | |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 90 | # check deep copies |
| 91 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 92 | e = pickle.loads(pickle.dumps(d, proto)) |
| 93 | self.assertEqual(d, e) |
| 94 | self.assertEqual(d.maps, e.maps) |
| 95 | self.assertIsNot(d, e) |
| 96 | for m1, m2 in zip(d.maps, e.maps): |
| 97 | self.assertIsNot(m1, m2, e) |
| 98 | for e in [copy.deepcopy(d), |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 99 | eval(repr(d)) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 100 | ]: |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 101 | self.assertEqual(d, e) |
| 102 | self.assertEqual(d.maps, e.maps) |
| 103 | self.assertIsNot(d, e) |
| 104 | for m1, m2 in zip(d.maps, e.maps): |
| 105 | self.assertIsNot(m1, m2, e) |
| 106 | |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 107 | f = d.new_child() |
| 108 | f['b'] = 5 |
| 109 | self.assertEqual(f.maps, [{'b': 5}, {'c':30}, {'a':1, 'b':2}]) |
| 110 | self.assertEqual(f.parents.maps, [{'c':30}, {'a':1, 'b':2}]) # check parents |
| 111 | self.assertEqual(f['b'], 5) # find first in chain |
| 112 | self.assertEqual(f.parents['b'], 2) # look beyond maps[0] |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 113 | |
| 114 | def test_contructor(self): |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 115 | self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 116 | self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list |
| 117 | |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 118 | def test_bool(self): |
| 119 | self.assertFalse(ChainMap()) |
| 120 | self.assertFalse(ChainMap({}, {})) |
| 121 | self.assertTrue(ChainMap({1:2}, {})) |
| 122 | self.assertTrue(ChainMap({}, {1:2})) |
| 123 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 124 | def test_missing(self): |
| 125 | class DefaultChainMap(ChainMap): |
| 126 | def __missing__(self, key): |
| 127 | return 999 |
| 128 | d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30)) |
| 129 | for k, v in dict(a=1, b=2, c=30, d=999).items(): |
| 130 | self.assertEqual(d[k], v) # check __getitem__ w/missing |
| 131 | for k, v in dict(a=1, b=2, c=30, d=77).items(): |
| 132 | self.assertEqual(d.get(k, 77), v) # check get() w/ missing |
| 133 | for k, v in dict(a=True, b=True, c=True, d=False).items(): |
| 134 | self.assertEqual(k in d, v) # check __contains__ w/missing |
| 135 | self.assertEqual(d.pop('a', 1001), 1, d) |
| 136 | self.assertEqual(d.pop('a', 1002), 1002) # check pop() w/missing |
| 137 | self.assertEqual(d.popitem(), ('b', 2)) # check popitem() w/missing |
| 138 | with self.assertRaises(KeyError): |
| 139 | d.popitem() |
| 140 | |
| 141 | def test_dict_coercion(self): |
| 142 | d = ChainMap(dict(a=1, b=2), dict(b=20, c=30)) |
| 143 | self.assertEqual(dict(d), dict(a=1, b=2, c=30)) |
| 144 | self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30)) |
| 145 | |
Vinay Sajip | 1ba81ee | 2013-01-11 23:39:53 +0000 | [diff] [blame] | 146 | def test_new_child(self): |
| 147 | 'Tests for changes for issue #16613.' |
| 148 | c = ChainMap() |
| 149 | c['a'] = 1 |
| 150 | c['b'] = 2 |
| 151 | m = {'b':20, 'c': 30} |
| 152 | d = c.new_child(m) |
| 153 | self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state |
| 154 | self.assertIs(m, d.maps[0]) |
| 155 | |
| 156 | # Use a different map than a dict |
| 157 | class lowerdict(dict): |
| 158 | def __getitem__(self, key): |
| 159 | if isinstance(key, str): |
| 160 | key = key.lower() |
| 161 | return dict.__getitem__(self, key) |
| 162 | def __contains__(self, key): |
| 163 | if isinstance(key, str): |
| 164 | key = key.lower() |
| 165 | return dict.__contains__(self, key) |
| 166 | |
| 167 | c = ChainMap() |
| 168 | c['a'] = 1 |
| 169 | c['b'] = 2 |
| 170 | m = lowerdict(b=20, c=30) |
| 171 | d = c.new_child(m) |
| 172 | self.assertIs(m, d.maps[0]) |
| 173 | for key in 'abc': # check contains |
| 174 | self.assertIn(key, d) |
| 175 | for k, v in dict(a=1, B=20, C=30, z=100).items(): # check get |
| 176 | self.assertEqual(d.get(k, 100), v) |
| 177 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 178 | |
| 179 | ################################################################################ |
| 180 | ### Named Tuples |
| 181 | ################################################################################ |
| 182 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 183 | TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 184 | |
| 185 | class TestNamedTuple(unittest.TestCase): |
| 186 | |
| 187 | def test_factory(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 188 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 189 | self.assertEqual(Point.__name__, 'Point') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 190 | self.assertEqual(Point.__slots__, ()) |
| 191 | self.assertEqual(Point.__module__, __name__) |
| 192 | self.assertEqual(Point.__getitem__, tuple.__getitem__) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 193 | self.assertEqual(Point._fields, ('x', 'y')) |
Raymond Hettinger | 2ebea41 | 2011-03-23 12:52:23 -0700 | [diff] [blame] | 194 | self.assertIn('class Point(tuple)', Point._source) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 195 | |
| 196 | self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi') # type has non-alpha char |
| 197 | self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword |
| 198 | self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi') # type starts with digit |
| 199 | |
| 200 | self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi') # field with non-alpha char |
| 201 | self.assertRaises(ValueError, namedtuple, 'abc', 'abc class') # field has keyword |
| 202 | self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi') # field starts with digit |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 203 | self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi') # field with leading underscore |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 204 | self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi') # duplicate field |
| 205 | |
| 206 | namedtuple('Point0', 'x1 y2') # Verify that numbers are allowed in names |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 207 | namedtuple('_', 'a b c') # Test leading underscores in a typename |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 208 | |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 209 | nt = namedtuple('nt', 'the quick brown fox') # check unicode input |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 210 | self.assertNotIn("u'", repr(nt._fields)) |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 211 | nt = namedtuple('nt', ('the', 'quick')) # check unicode input |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 212 | self.assertNotIn("u'", repr(nt._fields)) |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 213 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 214 | self.assertRaises(TypeError, Point._make, [11]) # catch too few args |
| 215 | self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args |
| 216 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 217 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 218 | "Docstrings are omitted with -O2 and above") |
| 219 | def test_factory_doc_attr(self): |
| 220 | Point = namedtuple('Point', 'x y') |
| 221 | self.assertEqual(Point.__doc__, 'Point(x, y)') |
| 222 | |
Raymond Hettinger | eac503a | 2015-05-13 01:09:59 -0700 | [diff] [blame] | 223 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 224 | "Docstrings are omitted with -O2 and above") |
| 225 | def test_doc_writable(self): |
| 226 | Point = namedtuple('Point', 'x y') |
| 227 | self.assertEqual(Point.x.__doc__, 'Alias for field number 0') |
| 228 | Point.x.__doc__ = 'docstring for Point.x' |
| 229 | self.assertEqual(Point.x.__doc__, 'docstring for Point.x') |
| 230 | |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 231 | def test_name_fixer(self): |
| 232 | for spec, renamed in [ |
Raymond Hettinger | 5614524 | 2009-04-02 22:31:59 +0000 | [diff] [blame] | 233 | [('efg', 'g%hi'), ('efg', '_1')], # field with non-alpha char |
| 234 | [('abc', 'class'), ('abc', '_1')], # field has keyword |
| 235 | [('8efg', '9ghi'), ('_0', '_1')], # field starts with digit |
| 236 | [('abc', '_efg'), ('abc', '_1')], # field with leading underscore |
| 237 | [('abc', 'efg', 'efg', 'ghi'), ('abc', 'efg', '_2', 'ghi')], # duplicate field |
| 238 | [('abc', '', 'x'), ('abc', '_1', 'x')], # fieldname is a space |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 239 | ]: |
| 240 | self.assertEqual(namedtuple('NT', spec, rename=True)._fields, renamed) |
| 241 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 242 | def test_instance(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 243 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 244 | p = Point(11, 22) |
| 245 | self.assertEqual(p, Point(x=11, y=22)) |
| 246 | self.assertEqual(p, Point(11, y=22)) |
| 247 | self.assertEqual(p, Point(y=22, x=11)) |
| 248 | self.assertEqual(p, Point(*(11, 22))) |
| 249 | self.assertEqual(p, Point(**dict(x=11, y=22))) |
| 250 | self.assertRaises(TypeError, Point, 1) # too few args |
| 251 | self.assertRaises(TypeError, Point, 1, 2, 3) # too many args |
| 252 | self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument |
| 253 | self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument |
| 254 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 255 | self.assertNotIn('__weakref__', dir(p)) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 256 | self.assertEqual(p, Point._make([11, 22])) # test _make classmethod |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 257 | self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute |
| 258 | self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method |
Raymond Hettinger | 163e982 | 2013-05-18 00:05:20 -0700 | [diff] [blame] | 259 | self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method |
| 260 | self.assertEqual(vars(p), p._asdict()) # verify that vars() works |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 261 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 262 | try: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 263 | p._replace(x=1, error=2) |
| 264 | except ValueError: |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 265 | pass |
| 266 | else: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 267 | self._fail('Did not detect an incorrect fieldname') |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 268 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 269 | # verify that field string can have commas |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 270 | Point = namedtuple('Point', 'x, y') |
| 271 | p = Point(x=11, y=22) |
| 272 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
| 273 | |
| 274 | # verify that fieldspec can be a non-string sequence |
| 275 | Point = namedtuple('Point', ('x', 'y')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 276 | p = Point(x=11, y=22) |
| 277 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 278 | |
| 279 | def test_tupleness(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 280 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 281 | p = Point(11, 22) |
| 282 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 283 | self.assertIsInstance(p, tuple) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 284 | self.assertEqual(p, (11, 22)) # matches a real tuple |
| 285 | self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple |
| 286 | self.assertEqual(list(p), [11, 22]) # coercable to a list |
| 287 | self.assertEqual(max(p), 22) # iterable |
| 288 | self.assertEqual(max(*p), 22) # star-able |
| 289 | x, y = p |
| 290 | self.assertEqual(p, (x, y)) # unpacks like a tuple |
| 291 | self.assertEqual((p[0], p[1]), (11, 22)) # indexable like a tuple |
| 292 | self.assertRaises(IndexError, p.__getitem__, 3) |
| 293 | |
| 294 | self.assertEqual(p.x, x) |
| 295 | self.assertEqual(p.y, y) |
| 296 | self.assertRaises(AttributeError, eval, 'p.z', locals()) |
| 297 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 298 | def test_odd_sizes(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 299 | Zero = namedtuple('Zero', '') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 300 | self.assertEqual(Zero(), ()) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 301 | self.assertEqual(Zero._make([]), ()) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 302 | self.assertEqual(repr(Zero()), 'Zero()') |
| 303 | self.assertEqual(Zero()._asdict(), {}) |
| 304 | self.assertEqual(Zero()._fields, ()) |
| 305 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 306 | Dot = namedtuple('Dot', 'd') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 307 | self.assertEqual(Dot(1), (1,)) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 308 | self.assertEqual(Dot._make([1]), (1,)) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 309 | self.assertEqual(Dot(1).d, 1) |
| 310 | self.assertEqual(repr(Dot(1)), 'Dot(d=1)') |
| 311 | self.assertEqual(Dot(1)._asdict(), {'d':1}) |
| 312 | self.assertEqual(Dot(1)._replace(d=999), (999,)) |
| 313 | self.assertEqual(Dot(1)._fields, ('d',)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 314 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 315 | # n = 5000 |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 316 | n = 254 # SyntaxError: more than 255 arguments: |
| 317 | import string, random |
Georg Brandl | b533e26 | 2008-05-25 18:19:30 +0000 | [diff] [blame] | 318 | names = list(set(''.join([random.choice(string.ascii_letters) |
| 319 | for j in range(10)]) for i in range(n))) |
| 320 | n = len(names) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 321 | Big = namedtuple('Big', names) |
| 322 | b = Big(*range(n)) |
| 323 | self.assertEqual(b, tuple(range(n))) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 324 | self.assertEqual(Big._make(range(n)), tuple(range(n))) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 325 | for pos, name in enumerate(names): |
| 326 | self.assertEqual(getattr(b, name), pos) |
| 327 | repr(b) # make sure repr() doesn't blow-up |
| 328 | d = b._asdict() |
| 329 | d_expected = dict(zip(names, range(n))) |
| 330 | self.assertEqual(d, d_expected) |
| 331 | b2 = b._replace(**dict([(names[1], 999),(names[-5], 42)])) |
| 332 | b2_expected = list(range(n)) |
| 333 | b2_expected[1] = 999 |
| 334 | b2_expected[-5] = 42 |
| 335 | self.assertEqual(b2, tuple(b2_expected)) |
| 336 | self.assertEqual(b._fields, tuple(names)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 337 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 338 | def test_pickle(self): |
| 339 | p = TestNT(x=10, y=20, z=30) |
| 340 | for module in (pickle,): |
| 341 | loads = getattr(module, 'loads') |
| 342 | dumps = getattr(module, 'dumps') |
Eric V. Smith | 4d5d69d | 2014-02-05 10:33:14 -0500 | [diff] [blame] | 343 | for protocol in range(-1, module.HIGHEST_PROTOCOL + 1): |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 344 | q = loads(dumps(p, protocol)) |
| 345 | self.assertEqual(p, q) |
| 346 | self.assertEqual(p._fields, q._fields) |
Raymond Hettinger | b98dcc1 | 2013-05-03 02:24:15 -0700 | [diff] [blame] | 347 | self.assertNotIn(b'OrderedDict', dumps(p, protocol)) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 348 | |
| 349 | def test_copy(self): |
| 350 | p = TestNT(x=10, y=20, z=30) |
| 351 | for copier in copy.copy, copy.deepcopy: |
| 352 | q = copier(p) |
| 353 | self.assertEqual(p, q) |
| 354 | self.assertEqual(p._fields, q._fields) |
| 355 | |
Raymond Hettinger | 089ba7f | 2009-05-27 00:38:24 +0000 | [diff] [blame] | 356 | def test_name_conflicts(self): |
| 357 | # Some names like "self", "cls", "tuple", "itemgetter", and "property" |
| 358 | # failed when used as field names. Test to make sure these now work. |
| 359 | T = namedtuple('T', 'itemgetter property self cls tuple') |
| 360 | t = T(1, 2, 3, 4, 5) |
| 361 | self.assertEqual(t, (1,2,3,4,5)) |
| 362 | newt = t._replace(itemgetter=10, property=20, self=30, cls=40, tuple=50) |
| 363 | self.assertEqual(newt, (10,20,30,40,50)) |
| 364 | |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 365 | # Broader test of all interesting names in a template |
| 366 | with support.captured_stdout() as template: |
| 367 | T = namedtuple('T', 'x', verbose=True) |
| 368 | words = set(re.findall('[A-Za-z]+', template.getvalue())) |
| 369 | words -= set(keyword.kwlist) |
| 370 | T = namedtuple('T', words) |
| 371 | # test __new__ |
| 372 | values = tuple(range(len(words))) |
| 373 | t = T(*values) |
| 374 | self.assertEqual(t, values) |
| 375 | t = T(**dict(zip(T._fields, values))) |
| 376 | self.assertEqual(t, values) |
| 377 | # test _make |
| 378 | t = T._make(values) |
| 379 | self.assertEqual(t, values) |
| 380 | # exercise __repr__ |
| 381 | repr(t) |
| 382 | # test _asdict |
| 383 | self.assertEqual(t._asdict(), dict(zip(T._fields, values))) |
| 384 | # test _replace |
| 385 | t = T._make(values) |
| 386 | newvalues = tuple(v*10 for v in values) |
| 387 | newt = t._replace(**dict(zip(T._fields, newvalues))) |
| 388 | self.assertEqual(newt, newvalues) |
| 389 | # test _fields |
| 390 | self.assertEqual(T._fields, tuple(words)) |
| 391 | # test __getnewargs__ |
| 392 | self.assertEqual(t.__getnewargs__(), values) |
| 393 | |
Raymond Hettinger | d331ce9 | 2010-08-08 01:13:42 +0000 | [diff] [blame] | 394 | def test_repr(self): |
| 395 | with support.captured_stdout() as template: |
| 396 | A = namedtuple('A', 'x', verbose=True) |
| 397 | self.assertEqual(repr(A(1)), 'A(x=1)') |
| 398 | # repr should show the name of the subclass |
| 399 | class B(A): |
| 400 | pass |
| 401 | self.assertEqual(repr(B(1)), 'B(x=1)') |
| 402 | |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 403 | def test_source(self): |
| 404 | # verify that _source can be run through exec() |
Raymond Hettinger | d4652fa | 2011-03-24 09:45:43 -0700 | [diff] [blame] | 405 | tmp = namedtuple('NTColor', 'red green blue') |
| 406 | globals().pop('NTColor', None) # remove artifacts from other tests |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 407 | exec(tmp._source, globals()) |
Raymond Hettinger | d4652fa | 2011-03-24 09:45:43 -0700 | [diff] [blame] | 408 | self.assertIn('NTColor', globals()) |
| 409 | c = NTColor(10, 20, 30) |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 410 | self.assertEqual((c.red, c.green, c.blue), (10, 20, 30)) |
Raymond Hettinger | d4652fa | 2011-03-24 09:45:43 -0700 | [diff] [blame] | 411 | self.assertEqual(NTColor._fields, ('red', 'green', 'blue')) |
| 412 | globals().pop('NTColor', None) # clean-up after this test |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 413 | |
Raymond Hettinger | d331ce9 | 2010-08-08 01:13:42 +0000 | [diff] [blame] | 414 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 415 | ################################################################################ |
| 416 | ### Abstract Base Classes |
| 417 | ################################################################################ |
| 418 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 419 | class ABCTestCase(unittest.TestCase): |
| 420 | |
| 421 | def validate_abstract_methods(self, abc, *names): |
| 422 | methodstubs = dict.fromkeys(names, lambda s, *args: 0) |
| 423 | |
| 424 | # everything should work will all required methods are present |
| 425 | C = type('C', (abc,), methodstubs) |
| 426 | C() |
| 427 | |
| 428 | # instantiation should fail if a required method is missing |
| 429 | for name in names: |
| 430 | stubs = methodstubs.copy() |
| 431 | del stubs[name] |
| 432 | C = type('C', (abc,), stubs) |
| 433 | self.assertRaises(TypeError, C, name) |
| 434 | |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 435 | def validate_isinstance(self, abc, name): |
| 436 | stub = lambda s, *args: 0 |
| 437 | |
| 438 | C = type('C', (object,), {'__hash__': None}) |
| 439 | setattr(C, name, stub) |
| 440 | self.assertIsInstance(C(), abc) |
| 441 | self.assertTrue(issubclass(C, abc)) |
| 442 | |
| 443 | C = type('C', (object,), {'__hash__': None}) |
| 444 | self.assertNotIsInstance(C(), abc) |
| 445 | self.assertFalse(issubclass(C, abc)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 446 | |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 447 | def validate_comparison(self, instance): |
| 448 | ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] |
| 449 | operators = {} |
| 450 | for op in ops: |
| 451 | name = '__' + op + '__' |
| 452 | operators[name] = getattr(operator, name) |
| 453 | |
| 454 | class Other: |
| 455 | def __init__(self): |
| 456 | self.right_side = False |
| 457 | def __eq__(self, other): |
| 458 | self.right_side = True |
| 459 | return True |
| 460 | __lt__ = __eq__ |
| 461 | __gt__ = __eq__ |
| 462 | __le__ = __eq__ |
| 463 | __ge__ = __eq__ |
| 464 | __ne__ = __eq__ |
| 465 | __ror__ = __eq__ |
| 466 | __rand__ = __eq__ |
| 467 | __rxor__ = __eq__ |
| 468 | __rsub__ = __eq__ |
| 469 | |
| 470 | for name, op in operators.items(): |
| 471 | if not hasattr(instance, name): |
| 472 | continue |
| 473 | other = Other() |
| 474 | op(instance, other) |
| 475 | self.assertTrue(other.right_side,'Right side not called for %s.%s' |
| 476 | % (type(instance), name)) |
| 477 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 478 | class TestOneTrickPonyABCs(ABCTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 479 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 480 | def test_Awaitable(self): |
| 481 | def gen(): |
| 482 | yield |
| 483 | |
| 484 | @types.coroutine |
| 485 | def coro(): |
| 486 | yield |
| 487 | |
| 488 | async def new_coro(): |
| 489 | pass |
| 490 | |
| 491 | class Bar: |
| 492 | def __await__(self): |
| 493 | yield |
| 494 | |
| 495 | class MinimalCoro(Coroutine): |
| 496 | def send(self, value): |
| 497 | return value |
| 498 | def throw(self, typ, val=None, tb=None): |
| 499 | super().throw(typ, val, tb) |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 500 | def __await__(self): |
| 501 | yield |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 502 | |
| 503 | non_samples = [None, int(), gen(), object()] |
| 504 | for x in non_samples: |
| 505 | self.assertNotIsInstance(x, Awaitable) |
| 506 | self.assertFalse(issubclass(type(x), Awaitable), repr(type(x))) |
| 507 | |
| 508 | samples = [Bar(), MinimalCoro()] |
| 509 | for x in samples: |
| 510 | self.assertIsInstance(x, Awaitable) |
| 511 | self.assertTrue(issubclass(type(x), Awaitable)) |
| 512 | |
| 513 | c = coro() |
| 514 | self.assertIsInstance(c, Awaitable) |
| 515 | c.close() # awoid RuntimeWarning that coro() was not awaited |
| 516 | |
| 517 | c = new_coro() |
| 518 | self.assertIsInstance(c, Awaitable) |
| 519 | c.close() # awoid RuntimeWarning that coro() was not awaited |
| 520 | |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 521 | class CoroLike: pass |
Yury Selivanov | aded55c | 2015-05-13 23:41:55 -0400 | [diff] [blame] | 522 | Coroutine.register(CoroLike) |
Yury Selivanov | 08e5300 | 2015-05-13 23:57:59 -0400 | [diff] [blame] | 523 | self.assertTrue(isinstance(CoroLike(), Awaitable)) |
| 524 | self.assertTrue(issubclass(CoroLike, Awaitable)) |
| 525 | CoroLike = None |
| 526 | support.gc_collect() # Kill CoroLike to clean-up ABCMeta cache |
Yury Selivanov | aded55c | 2015-05-13 23:41:55 -0400 | [diff] [blame] | 527 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 528 | def test_Coroutine(self): |
| 529 | def gen(): |
| 530 | yield |
| 531 | |
| 532 | @types.coroutine |
| 533 | def coro(): |
| 534 | yield |
| 535 | |
| 536 | async def new_coro(): |
| 537 | pass |
| 538 | |
| 539 | class Bar: |
| 540 | def __await__(self): |
| 541 | yield |
| 542 | |
| 543 | class MinimalCoro(Coroutine): |
| 544 | def send(self, value): |
| 545 | return value |
| 546 | def throw(self, typ, val=None, tb=None): |
| 547 | super().throw(typ, val, tb) |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 548 | def __await__(self): |
| 549 | yield |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 550 | |
| 551 | non_samples = [None, int(), gen(), object(), Bar()] |
| 552 | for x in non_samples: |
| 553 | self.assertNotIsInstance(x, Coroutine) |
| 554 | self.assertFalse(issubclass(type(x), Coroutine), repr(type(x))) |
| 555 | |
| 556 | samples = [MinimalCoro()] |
| 557 | for x in samples: |
| 558 | self.assertIsInstance(x, Awaitable) |
| 559 | self.assertTrue(issubclass(type(x), Awaitable)) |
| 560 | |
| 561 | c = coro() |
| 562 | self.assertIsInstance(c, Coroutine) |
| 563 | c.close() # awoid RuntimeWarning that coro() was not awaited |
| 564 | |
| 565 | c = new_coro() |
| 566 | self.assertIsInstance(c, Coroutine) |
| 567 | c.close() # awoid RuntimeWarning that coro() was not awaited |
| 568 | |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 569 | class CoroLike: |
| 570 | def send(self, value): |
| 571 | pass |
| 572 | def throw(self, typ, val=None, tb=None): |
| 573 | pass |
| 574 | def close(self): |
| 575 | pass |
| 576 | def __await__(self): |
| 577 | pass |
| 578 | self.assertTrue(isinstance(CoroLike(), Coroutine)) |
| 579 | self.assertTrue(issubclass(CoroLike, Coroutine)) |
| 580 | |
| 581 | class CoroLike: |
| 582 | def send(self, value): |
| 583 | pass |
| 584 | def close(self): |
| 585 | pass |
| 586 | def __await__(self): |
| 587 | pass |
| 588 | self.assertFalse(isinstance(CoroLike(), Coroutine)) |
| 589 | self.assertFalse(issubclass(CoroLike, Coroutine)) |
| 590 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 591 | def test_Hashable(self): |
| 592 | # Check some non-hashables |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 593 | non_samples = [bytearray(), list(), set(), dict()] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 594 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 595 | self.assertNotIsInstance(x, Hashable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 596 | self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 597 | # Check some hashables |
| 598 | samples = [None, |
| 599 | int(), float(), complex(), |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 600 | str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 601 | tuple(), frozenset(), |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 602 | int, list, object, type, bytes() |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 603 | ] |
| 604 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 605 | self.assertIsInstance(x, Hashable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 606 | self.assertTrue(issubclass(type(x), Hashable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 607 | self.assertRaises(TypeError, Hashable) |
| 608 | # Check direct subclassing |
| 609 | class H(Hashable): |
| 610 | def __hash__(self): |
| 611 | return super().__hash__() |
| 612 | self.assertEqual(hash(H()), 0) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 613 | self.assertFalse(issubclass(int, H)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 614 | self.validate_abstract_methods(Hashable, '__hash__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 615 | self.validate_isinstance(Hashable, '__hash__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 616 | |
Yury Selivanov | e0104ae | 2015-05-14 12:19:16 -0400 | [diff] [blame] | 617 | def test_AsyncIterable(self): |
| 618 | class AI: |
| 619 | async def __aiter__(self): |
| 620 | return self |
| 621 | self.assertTrue(isinstance(AI(), AsyncIterable)) |
| 622 | self.assertTrue(issubclass(AI, AsyncIterable)) |
| 623 | # Check some non-iterables |
| 624 | non_samples = [None, object, []] |
| 625 | for x in non_samples: |
| 626 | self.assertNotIsInstance(x, AsyncIterable) |
| 627 | self.assertFalse(issubclass(type(x), AsyncIterable), repr(type(x))) |
| 628 | self.validate_abstract_methods(AsyncIterable, '__aiter__') |
| 629 | self.validate_isinstance(AsyncIterable, '__aiter__') |
| 630 | |
| 631 | def test_AsyncIterator(self): |
| 632 | class AI: |
| 633 | async def __aiter__(self): |
| 634 | return self |
| 635 | async def __anext__(self): |
| 636 | raise StopAsyncIteration |
| 637 | self.assertTrue(isinstance(AI(), AsyncIterator)) |
| 638 | self.assertTrue(issubclass(AI, AsyncIterator)) |
| 639 | non_samples = [None, object, []] |
| 640 | # Check some non-iterables |
| 641 | for x in non_samples: |
| 642 | self.assertNotIsInstance(x, AsyncIterator) |
| 643 | self.assertFalse(issubclass(type(x), AsyncIterator), repr(type(x))) |
| 644 | # Similarly to regular iterators (see issue 10565) |
| 645 | class AnextOnly: |
| 646 | async def __anext__(self): |
| 647 | raise StopAsyncIteration |
| 648 | self.assertNotIsInstance(AnextOnly(), AsyncIterator) |
| 649 | self.validate_abstract_methods(AsyncIterator, '__anext__', '__aiter__') |
| 650 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 651 | def test_Iterable(self): |
| 652 | # Check some non-iterables |
| 653 | non_samples = [None, 42, 3.14, 1j] |
| 654 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 655 | self.assertNotIsInstance(x, Iterable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 656 | self.assertFalse(issubclass(type(x), Iterable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 657 | # Check some iterables |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 658 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 659 | tuple(), list(), set(), frozenset(), dict(), |
| 660 | dict().keys(), dict().items(), dict().values(), |
| 661 | (lambda: (yield))(), |
| 662 | (x for x in []), |
| 663 | ] |
| 664 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 665 | self.assertIsInstance(x, Iterable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 666 | self.assertTrue(issubclass(type(x), Iterable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 667 | # Check direct subclassing |
| 668 | class I(Iterable): |
| 669 | def __iter__(self): |
| 670 | return super().__iter__() |
| 671 | self.assertEqual(list(I()), []) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 672 | self.assertFalse(issubclass(str, I)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 673 | self.validate_abstract_methods(Iterable, '__iter__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 674 | self.validate_isinstance(Iterable, '__iter__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 675 | |
| 676 | def test_Iterator(self): |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 677 | non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 678 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 679 | self.assertNotIsInstance(x, Iterator) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 680 | self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 681 | samples = [iter(bytes()), iter(str()), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 682 | iter(tuple()), iter(list()), iter(dict()), |
| 683 | iter(set()), iter(frozenset()), |
| 684 | iter(dict().keys()), iter(dict().items()), |
| 685 | iter(dict().values()), |
| 686 | (lambda: (yield))(), |
| 687 | (x for x in []), |
| 688 | ] |
| 689 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 690 | self.assertIsInstance(x, Iterator) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 691 | self.assertTrue(issubclass(type(x), Iterator), repr(type(x))) |
Raymond Hettinger | ead2222 | 2010-11-29 03:56:12 +0000 | [diff] [blame] | 692 | self.validate_abstract_methods(Iterator, '__next__', '__iter__') |
| 693 | |
| 694 | # Issue 10565 |
| 695 | class NextOnly: |
| 696 | def __next__(self): |
| 697 | yield 1 |
Raymond Hettinger | bb6c0aa | 2014-11-22 22:14:41 -0800 | [diff] [blame] | 698 | return |
Raymond Hettinger | ead2222 | 2010-11-29 03:56:12 +0000 | [diff] [blame] | 699 | self.assertNotIsInstance(NextOnly(), Iterator) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 700 | |
Raymond Hettinger | bd60e8d | 2015-05-09 01:07:23 -0400 | [diff] [blame] | 701 | def test_Generator(self): |
| 702 | class NonGen1: |
| 703 | def __iter__(self): return self |
| 704 | def __next__(self): return None |
| 705 | def close(self): pass |
| 706 | def throw(self, typ, val=None, tb=None): pass |
| 707 | |
| 708 | class NonGen2: |
| 709 | def __iter__(self): return self |
| 710 | def __next__(self): return None |
| 711 | def close(self): pass |
| 712 | def send(self, value): return value |
| 713 | |
| 714 | class NonGen3: |
| 715 | def close(self): pass |
| 716 | def send(self, value): return value |
| 717 | def throw(self, typ, val=None, tb=None): pass |
| 718 | |
| 719 | non_samples = [ |
| 720 | None, 42, 3.14, 1j, b"", "", (), [], {}, set(), |
| 721 | iter(()), iter([]), NonGen1(), NonGen2(), NonGen3()] |
| 722 | for x in non_samples: |
| 723 | self.assertNotIsInstance(x, Generator) |
| 724 | self.assertFalse(issubclass(type(x), Generator), repr(type(x))) |
| 725 | |
| 726 | class Gen: |
| 727 | def __iter__(self): return self |
| 728 | def __next__(self): return None |
| 729 | def close(self): pass |
| 730 | def send(self, value): return value |
| 731 | def throw(self, typ, val=None, tb=None): pass |
| 732 | |
| 733 | class MinimalGen(Generator): |
| 734 | def send(self, value): |
| 735 | return value |
| 736 | def throw(self, typ, val=None, tb=None): |
| 737 | super().throw(typ, val, tb) |
| 738 | |
| 739 | def gen(): |
| 740 | yield 1 |
| 741 | |
| 742 | samples = [gen(), (lambda: (yield))(), Gen(), MinimalGen()] |
| 743 | for x in samples: |
| 744 | self.assertIsInstance(x, Iterator) |
| 745 | self.assertIsInstance(x, Generator) |
| 746 | self.assertTrue(issubclass(type(x), Generator), repr(type(x))) |
| 747 | self.validate_abstract_methods(Generator, 'send', 'throw') |
| 748 | |
| 749 | # mixin tests |
| 750 | mgen = MinimalGen() |
| 751 | self.assertIs(mgen, iter(mgen)) |
| 752 | self.assertIs(mgen.send(None), next(mgen)) |
| 753 | self.assertEqual(2, mgen.send(2)) |
| 754 | self.assertIsNone(mgen.close()) |
| 755 | self.assertRaises(ValueError, mgen.throw, ValueError) |
| 756 | self.assertRaisesRegex(ValueError, "^huhu$", |
| 757 | mgen.throw, ValueError, ValueError("huhu")) |
| 758 | self.assertRaises(StopIteration, mgen.throw, StopIteration()) |
| 759 | |
| 760 | class FailOnClose(Generator): |
| 761 | def send(self, value): return value |
| 762 | def throw(self, *args): raise ValueError |
| 763 | |
| 764 | self.assertRaises(ValueError, FailOnClose().close) |
| 765 | |
| 766 | class IgnoreGeneratorExit(Generator): |
| 767 | def send(self, value): return value |
| 768 | def throw(self, *args): pass |
| 769 | |
| 770 | self.assertRaises(RuntimeError, IgnoreGeneratorExit().close) |
| 771 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 772 | def test_Sized(self): |
| 773 | non_samples = [None, 42, 3.14, 1j, |
| 774 | (lambda: (yield))(), |
| 775 | (x for x in []), |
| 776 | ] |
| 777 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 778 | self.assertNotIsInstance(x, Sized) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 779 | self.assertFalse(issubclass(type(x), Sized), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 780 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 781 | tuple(), list(), set(), frozenset(), dict(), |
| 782 | dict().keys(), dict().items(), dict().values(), |
| 783 | ] |
| 784 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 785 | self.assertIsInstance(x, Sized) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 786 | self.assertTrue(issubclass(type(x), Sized), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 787 | self.validate_abstract_methods(Sized, '__len__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 788 | self.validate_isinstance(Sized, '__len__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 789 | |
| 790 | def test_Container(self): |
| 791 | non_samples = [None, 42, 3.14, 1j, |
| 792 | (lambda: (yield))(), |
| 793 | (x for x in []), |
| 794 | ] |
| 795 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 796 | self.assertNotIsInstance(x, Container) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 797 | self.assertFalse(issubclass(type(x), Container), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 798 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 799 | tuple(), list(), set(), frozenset(), dict(), |
| 800 | dict().keys(), dict().items(), |
| 801 | ] |
| 802 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 803 | self.assertIsInstance(x, Container) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 804 | self.assertTrue(issubclass(type(x), Container), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 805 | self.validate_abstract_methods(Container, '__contains__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 806 | self.validate_isinstance(Container, '__contains__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 807 | |
| 808 | def test_Callable(self): |
| 809 | non_samples = [None, 42, 3.14, 1j, |
| 810 | "", b"", (), [], {}, set(), |
| 811 | (lambda: (yield))(), |
| 812 | (x for x in []), |
| 813 | ] |
| 814 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 815 | self.assertNotIsInstance(x, Callable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 816 | self.assertFalse(issubclass(type(x), Callable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 817 | samples = [lambda: None, |
| 818 | type, int, object, |
| 819 | len, |
| 820 | list.append, [].append, |
| 821 | ] |
| 822 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 823 | self.assertIsInstance(x, Callable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 824 | self.assertTrue(issubclass(type(x), Callable), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 825 | self.validate_abstract_methods(Callable, '__call__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 826 | self.validate_isinstance(Callable, '__call__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 827 | |
| 828 | def test_direct_subclassing(self): |
| 829 | for B in Hashable, Iterable, Iterator, Sized, Container, Callable: |
| 830 | class C(B): |
| 831 | pass |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 832 | self.assertTrue(issubclass(C, B)) |
| 833 | self.assertFalse(issubclass(int, C)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 834 | |
| 835 | def test_registration(self): |
| 836 | for B in Hashable, Iterable, Iterator, Sized, Container, Callable: |
| 837 | class C: |
| 838 | __hash__ = None # Make sure it isn't hashable by default |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 839 | self.assertFalse(issubclass(C, B), B.__name__) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 840 | B.register(C) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 841 | self.assertTrue(issubclass(C, B)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 842 | |
Raymond Hettinger | 3f10a95 | 2009-04-01 19:05:50 +0000 | [diff] [blame] | 843 | class WithSet(MutableSet): |
| 844 | |
| 845 | def __init__(self, it=()): |
| 846 | self.data = set(it) |
| 847 | |
| 848 | def __len__(self): |
| 849 | return len(self.data) |
| 850 | |
| 851 | def __iter__(self): |
| 852 | return iter(self.data) |
| 853 | |
| 854 | def __contains__(self, item): |
| 855 | return item in self.data |
| 856 | |
| 857 | def add(self, item): |
| 858 | self.data.add(item) |
| 859 | |
| 860 | def discard(self, item): |
| 861 | self.data.discard(item) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 862 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 863 | class TestCollectionABCs(ABCTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 864 | |
| 865 | # XXX For now, we only test some virtual inheritance properties. |
| 866 | # We should also test the proper behavior of the collection ABCs |
| 867 | # as real base classes or mix-in classes. |
| 868 | |
| 869 | def test_Set(self): |
| 870 | for sample in [set, frozenset]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 871 | self.assertIsInstance(sample(), Set) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 872 | self.assertTrue(issubclass(sample, Set)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 873 | self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 874 | class MySet(Set): |
| 875 | def __contains__(self, x): |
| 876 | return False |
| 877 | def __len__(self): |
| 878 | return 0 |
| 879 | def __iter__(self): |
| 880 | return iter([]) |
| 881 | self.validate_comparison(MySet()) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 882 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 883 | def test_hash_Set(self): |
| 884 | class OneTwoThreeSet(Set): |
| 885 | def __init__(self): |
| 886 | self.contents = [1, 2, 3] |
| 887 | def __contains__(self, x): |
| 888 | return x in self.contents |
| 889 | def __len__(self): |
| 890 | return len(self.contents) |
| 891 | def __iter__(self): |
| 892 | return iter(self.contents) |
| 893 | def __hash__(self): |
| 894 | return self._hash() |
| 895 | a, b = OneTwoThreeSet(), OneTwoThreeSet() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 896 | self.assertTrue(hash(a) == hash(b)) |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 897 | |
Raymond Hettinger | 2d452ee | 2014-05-25 18:28:39 -0700 | [diff] [blame] | 898 | def test_isdisjoint_Set(self): |
| 899 | class MySet(Set): |
| 900 | def __init__(self, itr): |
| 901 | self.contents = itr |
| 902 | def __contains__(self, x): |
| 903 | return x in self.contents |
| 904 | def __iter__(self): |
| 905 | return iter(self.contents) |
| 906 | def __len__(self): |
| 907 | return len([x for x in self.contents]) |
| 908 | s1 = MySet((1, 2, 3)) |
| 909 | s2 = MySet((4, 5, 6)) |
| 910 | s3 = MySet((1, 5, 6)) |
| 911 | self.assertTrue(s1.isdisjoint(s2)) |
| 912 | self.assertFalse(s1.isdisjoint(s3)) |
| 913 | |
| 914 | def test_equality_Set(self): |
| 915 | class MySet(Set): |
| 916 | def __init__(self, itr): |
| 917 | self.contents = itr |
| 918 | def __contains__(self, x): |
| 919 | return x in self.contents |
| 920 | def __iter__(self): |
| 921 | return iter(self.contents) |
| 922 | def __len__(self): |
| 923 | return len([x for x in self.contents]) |
| 924 | s1 = MySet((1,)) |
| 925 | s2 = MySet((1, 2)) |
| 926 | s3 = MySet((3, 4)) |
| 927 | s4 = MySet((3, 4)) |
| 928 | self.assertTrue(s2 > s1) |
| 929 | self.assertTrue(s1 < s2) |
| 930 | self.assertFalse(s2 <= s1) |
| 931 | self.assertFalse(s2 <= s3) |
| 932 | self.assertFalse(s1 >= s2) |
| 933 | self.assertEqual(s3, s4) |
| 934 | self.assertNotEqual(s2, s3) |
| 935 | |
| 936 | def test_arithmetic_Set(self): |
| 937 | class MySet(Set): |
| 938 | def __init__(self, itr): |
| 939 | self.contents = itr |
| 940 | def __contains__(self, x): |
| 941 | return x in self.contents |
| 942 | def __iter__(self): |
| 943 | return iter(self.contents) |
| 944 | def __len__(self): |
| 945 | return len([x for x in self.contents]) |
| 946 | s1 = MySet((1, 2, 3)) |
| 947 | s2 = MySet((3, 4, 5)) |
| 948 | s3 = s1 & s2 |
| 949 | self.assertEqual(s3, MySet((3,))) |
| 950 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 951 | def test_MutableSet(self): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 952 | self.assertIsInstance(set(), MutableSet) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 953 | self.assertTrue(issubclass(set, MutableSet)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 954 | self.assertNotIsInstance(frozenset(), MutableSet) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 955 | self.assertFalse(issubclass(frozenset, MutableSet)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 956 | self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__', |
| 957 | 'add', 'discard') |
| 958 | |
Raymond Hettinger | 3f10a95 | 2009-04-01 19:05:50 +0000 | [diff] [blame] | 959 | def test_issue_5647(self): |
| 960 | # MutableSet.__iand__ mutated the set during iteration |
| 961 | s = WithSet('abcd') |
| 962 | s &= WithSet('cdef') # This used to fail |
| 963 | self.assertEqual(set(s), set('cd')) |
| 964 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 965 | def test_issue_4920(self): |
| 966 | # MutableSet.pop() method did not work |
Raymond Hettinger | 57d1a88 | 2011-02-23 00:46:28 +0000 | [diff] [blame] | 967 | class MySet(MutableSet): |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 968 | __slots__=['__s'] |
| 969 | def __init__(self,items=None): |
| 970 | if items is None: |
| 971 | items=[] |
| 972 | self.__s=set(items) |
| 973 | def __contains__(self,v): |
| 974 | return v in self.__s |
| 975 | def __iter__(self): |
| 976 | return iter(self.__s) |
| 977 | def __len__(self): |
| 978 | return len(self.__s) |
| 979 | def add(self,v): |
| 980 | result=v not in self.__s |
| 981 | self.__s.add(v) |
| 982 | return result |
| 983 | def discard(self,v): |
| 984 | result=v in self.__s |
| 985 | self.__s.discard(v) |
| 986 | return result |
| 987 | def __repr__(self): |
| 988 | return "MySet(%s)" % repr(list(self)) |
| 989 | s = MySet([5,43,2,1]) |
| 990 | self.assertEqual(s.pop(), 1) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 991 | |
Daniel Stutzbach | 31da5b2 | 2010-08-24 20:49:57 +0000 | [diff] [blame] | 992 | def test_issue8750(self): |
| 993 | empty = WithSet() |
| 994 | full = WithSet(range(10)) |
| 995 | s = WithSet(full) |
| 996 | s -= s |
| 997 | self.assertEqual(s, empty) |
| 998 | s = WithSet(full) |
| 999 | s ^= s |
| 1000 | self.assertEqual(s, empty) |
| 1001 | s = WithSet(full) |
| 1002 | s &= s |
| 1003 | self.assertEqual(s, full) |
| 1004 | s |= s |
| 1005 | self.assertEqual(s, full) |
| 1006 | |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1007 | def test_issue16373(self): |
| 1008 | # Recursion error comparing comparable and noncomparable |
| 1009 | # Set instances |
| 1010 | class MyComparableSet(Set): |
| 1011 | def __contains__(self, x): |
| 1012 | return False |
| 1013 | def __len__(self): |
| 1014 | return 0 |
| 1015 | def __iter__(self): |
| 1016 | return iter([]) |
| 1017 | class MyNonComparableSet(Set): |
| 1018 | def __contains__(self, x): |
| 1019 | return False |
| 1020 | def __len__(self): |
| 1021 | return 0 |
| 1022 | def __iter__(self): |
| 1023 | return iter([]) |
| 1024 | def __le__(self, x): |
| 1025 | return NotImplemented |
| 1026 | def __lt__(self, x): |
| 1027 | return NotImplemented |
| 1028 | |
| 1029 | cs = MyComparableSet() |
| 1030 | ncs = MyNonComparableSet() |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1031 | self.assertFalse(ncs < cs) |
| 1032 | self.assertTrue(ncs <= cs) |
| 1033 | self.assertFalse(ncs > cs) |
| 1034 | self.assertTrue(ncs >= cs) |
| 1035 | |
| 1036 | def assertSameSet(self, s1, s2): |
| 1037 | # coerce both to a real set then check equality |
| 1038 | self.assertSetEqual(set(s1), set(s2)) |
| 1039 | |
| 1040 | def test_Set_interoperability_with_real_sets(self): |
| 1041 | # Issue: 8743 |
| 1042 | class ListSet(Set): |
| 1043 | def __init__(self, elements=()): |
| 1044 | self.data = [] |
| 1045 | for elem in elements: |
| 1046 | if elem not in self.data: |
| 1047 | self.data.append(elem) |
| 1048 | def __contains__(self, elem): |
| 1049 | return elem in self.data |
| 1050 | def __iter__(self): |
| 1051 | return iter(self.data) |
| 1052 | def __len__(self): |
| 1053 | return len(self.data) |
| 1054 | def __repr__(self): |
| 1055 | return 'Set({!r})'.format(self.data) |
| 1056 | |
| 1057 | r1 = set('abc') |
| 1058 | r2 = set('bcd') |
| 1059 | r3 = set('abcde') |
| 1060 | f1 = ListSet('abc') |
| 1061 | f2 = ListSet('bcd') |
| 1062 | f3 = ListSet('abcde') |
| 1063 | l1 = list('abccba') |
| 1064 | l2 = list('bcddcb') |
| 1065 | l3 = list('abcdeedcba') |
| 1066 | |
| 1067 | target = r1 & r2 |
| 1068 | self.assertSameSet(f1 & f2, target) |
| 1069 | self.assertSameSet(f1 & r2, target) |
| 1070 | self.assertSameSet(r2 & f1, target) |
| 1071 | self.assertSameSet(f1 & l2, target) |
| 1072 | |
| 1073 | target = r1 | r2 |
| 1074 | self.assertSameSet(f1 | f2, target) |
| 1075 | self.assertSameSet(f1 | r2, target) |
| 1076 | self.assertSameSet(r2 | f1, target) |
| 1077 | self.assertSameSet(f1 | l2, target) |
| 1078 | |
| 1079 | fwd_target = r1 - r2 |
| 1080 | rev_target = r2 - r1 |
| 1081 | self.assertSameSet(f1 - f2, fwd_target) |
| 1082 | self.assertSameSet(f2 - f1, rev_target) |
| 1083 | self.assertSameSet(f1 - r2, fwd_target) |
| 1084 | self.assertSameSet(f2 - r1, rev_target) |
| 1085 | self.assertSameSet(r1 - f2, fwd_target) |
| 1086 | self.assertSameSet(r2 - f1, rev_target) |
| 1087 | self.assertSameSet(f1 - l2, fwd_target) |
| 1088 | self.assertSameSet(f2 - l1, rev_target) |
| 1089 | |
| 1090 | target = r1 ^ r2 |
| 1091 | self.assertSameSet(f1 ^ f2, target) |
| 1092 | self.assertSameSet(f1 ^ r2, target) |
| 1093 | self.assertSameSet(r2 ^ f1, target) |
| 1094 | self.assertSameSet(f1 ^ l2, target) |
| 1095 | |
| 1096 | # Don't change the following to use assertLess or other |
| 1097 | # "more specific" unittest assertions. The current |
| 1098 | # assertTrue/assertFalse style makes the pattern of test |
| 1099 | # case combinations clear and allows us to know for sure |
| 1100 | # the exact operator being invoked. |
| 1101 | |
| 1102 | # proper subset |
| 1103 | self.assertTrue(f1 < f3) |
| 1104 | self.assertFalse(f1 < f1) |
| 1105 | self.assertFalse(f1 < f2) |
| 1106 | self.assertTrue(r1 < f3) |
| 1107 | self.assertFalse(r1 < f1) |
| 1108 | self.assertFalse(r1 < f2) |
| 1109 | self.assertTrue(r1 < r3) |
| 1110 | self.assertFalse(r1 < r1) |
| 1111 | self.assertFalse(r1 < r2) |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1112 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1113 | f1 < l3 |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1114 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1115 | f1 < l1 |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1116 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1117 | f1 < l2 |
| 1118 | |
| 1119 | # any subset |
| 1120 | self.assertTrue(f1 <= f3) |
| 1121 | self.assertTrue(f1 <= f1) |
| 1122 | self.assertFalse(f1 <= f2) |
| 1123 | self.assertTrue(r1 <= f3) |
| 1124 | self.assertTrue(r1 <= f1) |
| 1125 | self.assertFalse(r1 <= f2) |
| 1126 | self.assertTrue(r1 <= r3) |
| 1127 | self.assertTrue(r1 <= r1) |
| 1128 | self.assertFalse(r1 <= r2) |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1129 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1130 | f1 <= l3 |
| 1131 | with self.assertRaises(TypeError): |
| 1132 | f1 <= l1 |
| 1133 | with self.assertRaises(TypeError): |
| 1134 | f1 <= l2 |
| 1135 | |
| 1136 | # proper superset |
| 1137 | self.assertTrue(f3 > f1) |
| 1138 | self.assertFalse(f1 > f1) |
| 1139 | self.assertFalse(f2 > f1) |
| 1140 | self.assertTrue(r3 > r1) |
| 1141 | self.assertFalse(f1 > r1) |
| 1142 | self.assertFalse(f2 > r1) |
| 1143 | self.assertTrue(r3 > r1) |
| 1144 | self.assertFalse(r1 > r1) |
| 1145 | self.assertFalse(r2 > r1) |
| 1146 | with self.assertRaises(TypeError): |
| 1147 | f1 > l3 |
| 1148 | with self.assertRaises(TypeError): |
| 1149 | f1 > l1 |
| 1150 | with self.assertRaises(TypeError): |
| 1151 | f1 > l2 |
| 1152 | |
| 1153 | # any superset |
| 1154 | self.assertTrue(f3 >= f1) |
| 1155 | self.assertTrue(f1 >= f1) |
| 1156 | self.assertFalse(f2 >= f1) |
| 1157 | self.assertTrue(r3 >= r1) |
| 1158 | self.assertTrue(f1 >= r1) |
| 1159 | self.assertFalse(f2 >= r1) |
| 1160 | self.assertTrue(r3 >= r1) |
| 1161 | self.assertTrue(r1 >= r1) |
| 1162 | self.assertFalse(r2 >= r1) |
| 1163 | with self.assertRaises(TypeError): |
| 1164 | f1 >= l3 |
| 1165 | with self.assertRaises(TypeError): |
| 1166 | f1 >=l1 |
| 1167 | with self.assertRaises(TypeError): |
| 1168 | f1 >= l2 |
| 1169 | |
| 1170 | # equality |
| 1171 | self.assertTrue(f1 == f1) |
| 1172 | self.assertTrue(r1 == f1) |
| 1173 | self.assertTrue(f1 == r1) |
| 1174 | self.assertFalse(f1 == f3) |
| 1175 | self.assertFalse(r1 == f3) |
| 1176 | self.assertFalse(f1 == r3) |
| 1177 | self.assertFalse(f1 == l3) |
| 1178 | self.assertFalse(f1 == l1) |
| 1179 | self.assertFalse(f1 == l2) |
| 1180 | |
| 1181 | # inequality |
| 1182 | self.assertFalse(f1 != f1) |
| 1183 | self.assertFalse(r1 != f1) |
| 1184 | self.assertFalse(f1 != r1) |
| 1185 | self.assertTrue(f1 != f3) |
| 1186 | self.assertTrue(r1 != f3) |
| 1187 | self.assertTrue(f1 != r3) |
| 1188 | self.assertTrue(f1 != l3) |
| 1189 | self.assertTrue(f1 != l1) |
| 1190 | self.assertTrue(f1 != l2) |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1191 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1192 | def test_Mapping(self): |
| 1193 | for sample in [dict]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1194 | self.assertIsInstance(sample(), Mapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1195 | self.assertTrue(issubclass(sample, Mapping)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1196 | self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', |
| 1197 | '__getitem__') |
Raymond Hettinger | 57d1a88 | 2011-02-23 00:46:28 +0000 | [diff] [blame] | 1198 | class MyMapping(Mapping): |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 1199 | def __len__(self): |
| 1200 | return 0 |
| 1201 | def __getitem__(self, i): |
| 1202 | raise IndexError |
| 1203 | def __iter__(self): |
| 1204 | return iter(()) |
| 1205 | self.validate_comparison(MyMapping()) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1206 | |
| 1207 | def test_MutableMapping(self): |
| 1208 | for sample in [dict]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1209 | self.assertIsInstance(sample(), MutableMapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1210 | self.assertTrue(issubclass(sample, MutableMapping)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1211 | self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__', |
| 1212 | '__getitem__', '__setitem__', '__delitem__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1213 | |
Raymond Hettinger | 9117c75 | 2010-08-22 07:44:24 +0000 | [diff] [blame] | 1214 | def test_MutableMapping_subclass(self): |
| 1215 | # Test issue 9214 |
| 1216 | mymap = UserDict() |
| 1217 | mymap['red'] = 5 |
| 1218 | self.assertIsInstance(mymap.keys(), Set) |
| 1219 | self.assertIsInstance(mymap.keys(), KeysView) |
| 1220 | self.assertIsInstance(mymap.items(), Set) |
| 1221 | self.assertIsInstance(mymap.items(), ItemsView) |
| 1222 | |
| 1223 | mymap = UserDict() |
| 1224 | mymap['red'] = 5 |
| 1225 | z = mymap.keys() | {'orange'} |
| 1226 | self.assertIsInstance(z, set) |
| 1227 | list(z) |
| 1228 | mymap['blue'] = 7 # Shouldn't affect 'z' |
| 1229 | self.assertEqual(sorted(z), ['orange', 'red']) |
| 1230 | |
| 1231 | mymap = UserDict() |
| 1232 | mymap['red'] = 5 |
| 1233 | z = mymap.items() | {('orange', 3)} |
| 1234 | self.assertIsInstance(z, set) |
| 1235 | list(z) |
| 1236 | mymap['blue'] = 7 # Shouldn't affect 'z' |
| 1237 | self.assertEqual(sorted(z), [('orange', 3), ('red', 5)]) |
| 1238 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1239 | def test_Sequence(self): |
| 1240 | for sample in [tuple, list, bytes, str]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1241 | self.assertIsInstance(sample(), Sequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1242 | self.assertTrue(issubclass(sample, Sequence)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1243 | self.assertIsInstance(range(10), Sequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1244 | self.assertTrue(issubclass(range, Sequence)) |
Nick Coghlan | 45163cc | 2013-10-02 22:31:47 +1000 | [diff] [blame] | 1245 | self.assertIsInstance(memoryview(b""), Sequence) |
| 1246 | self.assertTrue(issubclass(memoryview, Sequence)) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1247 | self.assertTrue(issubclass(str, Sequence)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1248 | self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', |
| 1249 | '__getitem__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1250 | |
Raymond Hettinger | ec219ba | 2015-05-22 19:29:22 -0700 | [diff] [blame] | 1251 | def test_Sequence_mixins(self): |
| 1252 | class SequenceSubclass(Sequence): |
| 1253 | def __init__(self, seq=()): |
| 1254 | self.seq = seq |
| 1255 | |
| 1256 | def __getitem__(self, index): |
| 1257 | return self.seq[index] |
| 1258 | |
| 1259 | def __len__(self): |
| 1260 | return len(self.seq) |
| 1261 | |
| 1262 | # Compare Sequence.index() behavior to (list|str).index() behavior |
| 1263 | def assert_index_same(seq1, seq2, index_args): |
| 1264 | try: |
| 1265 | expected = seq1.index(*index_args) |
| 1266 | except ValueError: |
| 1267 | with self.assertRaises(ValueError): |
| 1268 | seq2.index(*index_args) |
| 1269 | else: |
| 1270 | actual = seq2.index(*index_args) |
| 1271 | self.assertEqual( |
| 1272 | actual, expected, '%r.index%s' % (seq1, index_args)) |
| 1273 | |
| 1274 | for ty in list, str: |
| 1275 | nativeseq = ty('abracadabra') |
| 1276 | indexes = [-10000, -9999] + list(range(-3, len(nativeseq) + 3)) |
| 1277 | seqseq = SequenceSubclass(nativeseq) |
| 1278 | for letter in set(nativeseq) | {'z'}: |
| 1279 | assert_index_same(nativeseq, seqseq, (letter,)) |
| 1280 | for start in range(-3, len(nativeseq) + 3): |
| 1281 | assert_index_same(nativeseq, seqseq, (letter, start)) |
| 1282 | for stop in range(-3, len(nativeseq) + 3): |
| 1283 | assert_index_same( |
| 1284 | nativeseq, seqseq, (letter, start, stop)) |
| 1285 | |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1286 | def test_ByteString(self): |
| 1287 | for sample in [bytes, bytearray]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1288 | self.assertIsInstance(sample(), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1289 | self.assertTrue(issubclass(sample, ByteString)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1290 | for sample in [str, list, tuple]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1291 | self.assertNotIsInstance(sample(), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1292 | self.assertFalse(issubclass(sample, ByteString)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1293 | self.assertNotIsInstance(memoryview(b""), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1294 | self.assertFalse(issubclass(memoryview, ByteString)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1295 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1296 | def test_MutableSequence(self): |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1297 | for sample in [tuple, str, bytes]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1298 | self.assertNotIsInstance(sample(), MutableSequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1299 | self.assertFalse(issubclass(sample, MutableSequence)) |
Raymond Hettinger | 32ea165 | 2015-03-21 01:37:37 -0700 | [diff] [blame] | 1300 | for sample in [list, bytearray, deque]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1301 | self.assertIsInstance(sample(), MutableSequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1302 | self.assertTrue(issubclass(sample, MutableSequence)) |
| 1303 | self.assertFalse(issubclass(str, MutableSequence)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1304 | self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', |
| 1305 | '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1306 | |
Eli Bendersky | 0716a57 | 2011-03-04 10:38:14 +0000 | [diff] [blame] | 1307 | def test_MutableSequence_mixins(self): |
| 1308 | # Test the mixins of MutableSequence by creating a miminal concrete |
| 1309 | # class inherited from it. |
| 1310 | class MutableSequenceSubclass(MutableSequence): |
| 1311 | def __init__(self): |
| 1312 | self.lst = [] |
| 1313 | |
| 1314 | def __setitem__(self, index, value): |
| 1315 | self.lst[index] = value |
| 1316 | |
| 1317 | def __getitem__(self, index): |
| 1318 | return self.lst[index] |
| 1319 | |
| 1320 | def __len__(self): |
| 1321 | return len(self.lst) |
| 1322 | |
| 1323 | def __delitem__(self, index): |
| 1324 | del self.lst[index] |
| 1325 | |
| 1326 | def insert(self, index, value): |
| 1327 | self.lst.insert(index, value) |
| 1328 | |
| 1329 | mss = MutableSequenceSubclass() |
| 1330 | mss.append(0) |
| 1331 | mss.extend((1, 2, 3, 4)) |
| 1332 | self.assertEqual(len(mss), 5) |
| 1333 | self.assertEqual(mss[3], 3) |
| 1334 | mss.reverse() |
| 1335 | self.assertEqual(mss[3], 1) |
| 1336 | mss.pop() |
| 1337 | self.assertEqual(len(mss), 4) |
| 1338 | mss.remove(3) |
| 1339 | self.assertEqual(len(mss), 3) |
| 1340 | mss += (10, 20, 30) |
| 1341 | self.assertEqual(len(mss), 6) |
| 1342 | self.assertEqual(mss[-1], 30) |
| 1343 | mss.clear() |
| 1344 | self.assertEqual(len(mss), 0) |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 1345 | |
| 1346 | ################################################################################ |
| 1347 | ### Counter |
| 1348 | ################################################################################ |
| 1349 | |
Raymond Hettinger | cb1d96f | 2013-10-04 16:51:02 -0700 | [diff] [blame] | 1350 | class CounterSubclassWithSetItem(Counter): |
| 1351 | # Test a counter subclass that overrides __setitem__ |
| 1352 | def __init__(self, *args, **kwds): |
| 1353 | self.called = False |
| 1354 | Counter.__init__(self, *args, **kwds) |
| 1355 | def __setitem__(self, key, value): |
| 1356 | self.called = True |
| 1357 | Counter.__setitem__(self, key, value) |
| 1358 | |
| 1359 | class CounterSubclassWithGet(Counter): |
| 1360 | # Test a counter subclass that overrides get() |
| 1361 | def __init__(self, *args, **kwds): |
| 1362 | self.called = False |
| 1363 | Counter.__init__(self, *args, **kwds) |
| 1364 | def get(self, key, default): |
| 1365 | self.called = True |
| 1366 | return Counter.get(self, key, default) |
| 1367 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1368 | class TestCounter(unittest.TestCase): |
| 1369 | |
| 1370 | def test_basics(self): |
| 1371 | c = Counter('abcaba') |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1372 | self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) |
| 1373 | self.assertEqual(c, Counter(a=3, b=2, c=1)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1374 | self.assertIsInstance(c, dict) |
| 1375 | self.assertIsInstance(c, Mapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1376 | self.assertTrue(issubclass(Counter, dict)) |
| 1377 | self.assertTrue(issubclass(Counter, Mapping)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1378 | self.assertEqual(len(c), 3) |
| 1379 | self.assertEqual(sum(c.values()), 6) |
| 1380 | self.assertEqual(sorted(c.values()), [1, 2, 3]) |
| 1381 | self.assertEqual(sorted(c.keys()), ['a', 'b', 'c']) |
| 1382 | self.assertEqual(sorted(c), ['a', 'b', 'c']) |
| 1383 | self.assertEqual(sorted(c.items()), |
| 1384 | [('a', 3), ('b', 2), ('c', 1)]) |
| 1385 | self.assertEqual(c['b'], 2) |
| 1386 | self.assertEqual(c['z'], 0) |
| 1387 | self.assertEqual(c.__contains__('c'), True) |
| 1388 | self.assertEqual(c.__contains__('z'), False) |
| 1389 | self.assertEqual(c.get('b', 10), 2) |
| 1390 | self.assertEqual(c.get('z', 10), 10) |
| 1391 | self.assertEqual(c, dict(a=3, b=2, c=1)) |
| 1392 | self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") |
| 1393 | self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)]) |
| 1394 | for i in range(5): |
| 1395 | self.assertEqual(c.most_common(i), |
| 1396 | [('a', 3), ('b', 2), ('c', 1)][:i]) |
| 1397 | self.assertEqual(''.join(sorted(c.elements())), 'aaabbc') |
| 1398 | c['a'] += 1 # increment an existing value |
| 1399 | c['b'] -= 2 # sub existing value to zero |
| 1400 | del c['c'] # remove an entry |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1401 | del c['c'] # make sure that del doesn't raise KeyError |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1402 | c['d'] -= 2 # sub from a missing value |
| 1403 | c['e'] = -5 # directly assign a missing value |
| 1404 | c['f'] += 4 # add to a missing value |
| 1405 | self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) |
| 1406 | self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') |
| 1407 | self.assertEqual(c.pop('f'), 4) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 1408 | self.assertNotIn('f', c) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1409 | for i in range(3): |
| 1410 | elem, cnt = c.popitem() |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 1411 | self.assertNotIn(elem, c) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1412 | c.clear() |
| 1413 | self.assertEqual(c, {}) |
| 1414 | self.assertEqual(repr(c), 'Counter()') |
| 1415 | self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc') |
| 1416 | self.assertRaises(TypeError, hash, c) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1417 | c.update(dict(a=5, b=3)) |
| 1418 | c.update(c=1) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1419 | c.update(Counter('a' * 50 + 'b' * 30)) |
| 1420 | c.update() # test case with no args |
| 1421 | c.__init__('a' * 500 + 'b' * 300) |
| 1422 | c.__init__('cdc') |
| 1423 | c.__init__() |
| 1424 | self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) |
| 1425 | self.assertEqual(c.setdefault('d', 5), 1) |
| 1426 | self.assertEqual(c['d'], 1) |
| 1427 | self.assertEqual(c.setdefault('e', 5), 5) |
| 1428 | self.assertEqual(c['e'], 5) |
| 1429 | |
Serhiy Storchaka | ae5cb21 | 2014-11-27 16:25:51 +0200 | [diff] [blame] | 1430 | def test_init(self): |
| 1431 | self.assertEqual(list(Counter(self=42).items()), [('self', 42)]) |
| 1432 | self.assertEqual(list(Counter(iterable=42).items()), [('iterable', 42)]) |
| 1433 | self.assertEqual(list(Counter(iterable=None).items()), [('iterable', None)]) |
| 1434 | self.assertRaises(TypeError, Counter, 42) |
| 1435 | self.assertRaises(TypeError, Counter, (), ()) |
| 1436 | self.assertRaises(TypeError, Counter.__init__) |
| 1437 | |
| 1438 | def test_update(self): |
| 1439 | c = Counter() |
| 1440 | c.update(self=42) |
| 1441 | self.assertEqual(list(c.items()), [('self', 42)]) |
| 1442 | c = Counter() |
| 1443 | c.update(iterable=42) |
| 1444 | self.assertEqual(list(c.items()), [('iterable', 42)]) |
| 1445 | c = Counter() |
| 1446 | c.update(iterable=None) |
| 1447 | self.assertEqual(list(c.items()), [('iterable', None)]) |
| 1448 | self.assertRaises(TypeError, Counter().update, 42) |
| 1449 | self.assertRaises(TypeError, Counter().update, {}, {}) |
| 1450 | self.assertRaises(TypeError, Counter.update) |
| 1451 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1452 | def test_copying(self): |
| 1453 | # Check that counters are copyable, deepcopyable, picklable, and |
| 1454 | #have a repr/eval round-trip |
| 1455 | words = Counter('which witch had which witches wrist watch'.split()) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1456 | def check(dup): |
| 1457 | msg = "\ncopy: %s\nwords: %s" % (dup, words) |
| 1458 | self.assertIsNot(dup, words, msg) |
| 1459 | self.assertEqual(dup, words) |
| 1460 | check(words.copy()) |
| 1461 | check(copy.copy(words)) |
| 1462 | check(copy.deepcopy(words)) |
| 1463 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1464 | with self.subTest(proto=proto): |
| 1465 | check(pickle.loads(pickle.dumps(words, proto))) |
| 1466 | check(eval(repr(words))) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1467 | update_test = Counter() |
| 1468 | update_test.update(words) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1469 | check(update_test) |
| 1470 | check(Counter(words)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1471 | |
Raymond Hettinger | 1c746c2 | 2011-04-15 13:16:46 -0700 | [diff] [blame] | 1472 | def test_copy_subclass(self): |
| 1473 | class MyCounter(Counter): |
| 1474 | pass |
| 1475 | c = MyCounter('slartibartfast') |
| 1476 | d = c.copy() |
| 1477 | self.assertEqual(d, c) |
| 1478 | self.assertEqual(len(d), len(c)) |
| 1479 | self.assertEqual(type(d), type(c)) |
| 1480 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1481 | def test_conversions(self): |
| 1482 | # Convert to: set, list, dict |
| 1483 | s = 'she sells sea shells by the sea shore' |
| 1484 | self.assertEqual(sorted(Counter(s).elements()), sorted(s)) |
| 1485 | self.assertEqual(sorted(Counter(s)), sorted(set(s))) |
| 1486 | self.assertEqual(dict(Counter(s)), dict(Counter(s).items())) |
| 1487 | self.assertEqual(set(Counter(s)), set(s)) |
| 1488 | |
Raymond Hettinger | 670eaec | 2009-01-21 23:14:07 +0000 | [diff] [blame] | 1489 | def test_invariant_for_the_in_operator(self): |
| 1490 | c = Counter(a=10, b=-2, c=0) |
| 1491 | for elem in c: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1492 | self.assertTrue(elem in c) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1493 | self.assertIn(elem, c) |
Raymond Hettinger | 670eaec | 2009-01-21 23:14:07 +0000 | [diff] [blame] | 1494 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1495 | def test_multiset_operations(self): |
| 1496 | # Verify that adding a zero counter will strip zeros and negatives |
| 1497 | c = Counter(a=10, b=-2, c=0) + Counter() |
| 1498 | self.assertEqual(dict(c), dict(a=10)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1499 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1500 | elements = 'abcd' |
| 1501 | for i in range(1000): |
| 1502 | # test random pairs of multisets |
| 1503 | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 1504 | p.update(e=1, f=-1, g=0) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1505 | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 1506 | q.update(h=1, i=-1, j=0) |
| 1507 | for counterop, numberop in [ |
| 1508 | (Counter.__add__, lambda x, y: max(0, x+y)), |
| 1509 | (Counter.__sub__, lambda x, y: max(0, x-y)), |
| 1510 | (Counter.__or__, lambda x, y: max(0,x,y)), |
| 1511 | (Counter.__and__, lambda x, y: max(0, min(x,y))), |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1512 | ]: |
| 1513 | result = counterop(p, q) |
| 1514 | for x in elements: |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 1515 | self.assertEqual(numberop(p[x], q[x]), result[x], |
| 1516 | (counterop, x, p, q)) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1517 | # verify that results exclude non-positive counts |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1518 | self.assertTrue(x>0 for x in result.values()) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1519 | |
| 1520 | elements = 'abcdef' |
| 1521 | for i in range(100): |
| 1522 | # verify that random multisets with no repeats are exactly like sets |
| 1523 | p = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |
| 1524 | q = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |
| 1525 | for counterop, setop in [ |
| 1526 | (Counter.__sub__, set.__sub__), |
| 1527 | (Counter.__or__, set.__or__), |
| 1528 | (Counter.__and__, set.__and__), |
| 1529 | ]: |
| 1530 | counter_result = counterop(p, q) |
| 1531 | set_result = setop(set(p.elements()), set(q.elements())) |
| 1532 | self.assertEqual(counter_result, dict.fromkeys(set_result, 1)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1533 | |
Raymond Hettinger | becd568 | 2011-10-19 13:40:37 -0700 | [diff] [blame] | 1534 | def test_inplace_operations(self): |
| 1535 | elements = 'abcd' |
| 1536 | for i in range(1000): |
| 1537 | # test random pairs of multisets |
| 1538 | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
| 1539 | p.update(e=1, f=-1, g=0) |
| 1540 | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
| 1541 | q.update(h=1, i=-1, j=0) |
| 1542 | for inplace_op, regular_op in [ |
| 1543 | (Counter.__iadd__, Counter.__add__), |
| 1544 | (Counter.__isub__, Counter.__sub__), |
| 1545 | (Counter.__ior__, Counter.__or__), |
| 1546 | (Counter.__iand__, Counter.__and__), |
| 1547 | ]: |
| 1548 | c = p.copy() |
| 1549 | c_id = id(c) |
| 1550 | regular_result = regular_op(c, q) |
| 1551 | inplace_result = inplace_op(c, q) |
| 1552 | self.assertEqual(inplace_result, regular_result) |
| 1553 | self.assertEqual(id(inplace_result), c_id) |
| 1554 | |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 1555 | def test_subtract(self): |
| 1556 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 1557 | c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50) |
| 1558 | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |
| 1559 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 1560 | c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)) |
| 1561 | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |
| 1562 | c = Counter('aaabbcd') |
| 1563 | c.subtract('aaaabbcce') |
| 1564 | self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1)) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1565 | |
Serhiy Storchaka | ae5cb21 | 2014-11-27 16:25:51 +0200 | [diff] [blame] | 1566 | c = Counter() |
| 1567 | c.subtract(self=42) |
| 1568 | self.assertEqual(list(c.items()), [('self', -42)]) |
| 1569 | c = Counter() |
| 1570 | c.subtract(iterable=42) |
| 1571 | self.assertEqual(list(c.items()), [('iterable', -42)]) |
| 1572 | self.assertRaises(TypeError, Counter().subtract, 42) |
| 1573 | self.assertRaises(TypeError, Counter().subtract, {}, {}) |
| 1574 | self.assertRaises(TypeError, Counter.subtract) |
| 1575 | |
Raymond Hettinger | fcb393c | 2011-08-09 13:00:40 -0700 | [diff] [blame] | 1576 | def test_unary(self): |
| 1577 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 1578 | self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40)) |
| 1579 | self.assertEqual(dict(-c), dict(a=5)) |
| 1580 | |
Raymond Hettinger | 4e6bf41 | 2011-11-05 13:35:26 -0700 | [diff] [blame] | 1581 | def test_repr_nonsortable(self): |
| 1582 | c = Counter(a=2, b=None) |
| 1583 | r = repr(c) |
| 1584 | self.assertIn("'a': 2", r) |
| 1585 | self.assertIn("'b': None", r) |
Raymond Hettinger | 68fb89f | 2011-11-05 13:43:01 -0700 | [diff] [blame] | 1586 | |
Raymond Hettinger | 426e052 | 2011-01-03 02:12:02 +0000 | [diff] [blame] | 1587 | def test_helper_function(self): |
| 1588 | # two paths, one for real dicts and one for other mappings |
| 1589 | elems = list('abracadabra') |
| 1590 | |
| 1591 | d = dict() |
| 1592 | _count_elements(d, elems) |
| 1593 | self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) |
| 1594 | |
| 1595 | m = OrderedDict() |
| 1596 | _count_elements(m, elems) |
| 1597 | self.assertEqual(m, |
| 1598 | OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])) |
| 1599 | |
Raymond Hettinger | cb1d96f | 2013-10-04 16:51:02 -0700 | [diff] [blame] | 1600 | # test fidelity to the pure python version |
| 1601 | c = CounterSubclassWithSetItem('abracadabra') |
| 1602 | self.assertTrue(c.called) |
Raymond Hettinger | facd0a3 | 2013-10-05 17:14:51 -0700 | [diff] [blame] | 1603 | self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 }) |
Raymond Hettinger | cb1d96f | 2013-10-04 16:51:02 -0700 | [diff] [blame] | 1604 | c = CounterSubclassWithGet('abracadabra') |
| 1605 | self.assertTrue(c.called) |
Raymond Hettinger | facd0a3 | 2013-10-05 17:14:51 -0700 | [diff] [blame] | 1606 | self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 }) |
Raymond Hettinger | cb1d96f | 2013-10-04 16:51:02 -0700 | [diff] [blame] | 1607 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 1608 | |
| 1609 | ################################################################################ |
| 1610 | ### OrderedDict |
| 1611 | ################################################################################ |
| 1612 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1613 | py_coll = import_fresh_module('collections', blocked=['_collections']) |
| 1614 | c_coll = import_fresh_module('collections', fresh=['_collections']) |
| 1615 | |
| 1616 | |
| 1617 | @contextlib.contextmanager |
| 1618 | def replaced_module(name, replacement): |
| 1619 | original_module = sys.modules[name] |
| 1620 | sys.modules[name] = replacement |
| 1621 | try: |
| 1622 | yield |
| 1623 | finally: |
| 1624 | sys.modules[name] = original_module |
| 1625 | |
| 1626 | |
| 1627 | class OrderedDictTests: |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1628 | |
| 1629 | def test_init(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1630 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1631 | with self.assertRaises(TypeError): |
| 1632 | OrderedDict([('a', 1), ('b', 2)], None) # too many args |
| 1633 | pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] |
| 1634 | self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input |
| 1635 | self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input |
| 1636 | self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input |
| 1637 | self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)], |
| 1638 | c=3, e=5).items()), pairs) # mixed input |
| 1639 | |
| 1640 | # make sure no positional args conflict with possible kwdargs |
Serhiy Storchaka | ae5cb21 | 2014-11-27 16:25:51 +0200 | [diff] [blame] | 1641 | self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)]) |
| 1642 | self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)]) |
| 1643 | self.assertRaises(TypeError, OrderedDict, 42) |
| 1644 | self.assertRaises(TypeError, OrderedDict, (), ()) |
| 1645 | self.assertRaises(TypeError, OrderedDict.__init__) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1646 | |
| 1647 | # Make sure that direct calls to __init__ do not clear previous contents |
| 1648 | d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) |
| 1649 | d.__init__([('e', 5), ('f', 6)], g=7, d=4) |
| 1650 | self.assertEqual(list(d.items()), |
| 1651 | [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) |
| 1652 | |
| 1653 | def test_update(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1654 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1655 | with self.assertRaises(TypeError): |
| 1656 | OrderedDict().update([('a', 1), ('b', 2)], None) # too many args |
| 1657 | pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] |
| 1658 | od = OrderedDict() |
| 1659 | od.update(dict(pairs)) |
| 1660 | self.assertEqual(sorted(od.items()), pairs) # dict input |
| 1661 | od = OrderedDict() |
| 1662 | od.update(**dict(pairs)) |
| 1663 | self.assertEqual(sorted(od.items()), pairs) # kwds input |
| 1664 | od = OrderedDict() |
| 1665 | od.update(pairs) |
| 1666 | self.assertEqual(list(od.items()), pairs) # pairs input |
| 1667 | od = OrderedDict() |
| 1668 | od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5) |
| 1669 | self.assertEqual(list(od.items()), pairs) # mixed input |
| 1670 | |
Mark Dickinson | b214e90 | 2010-07-11 18:53:06 +0000 | [diff] [blame] | 1671 | # Issue 9137: Named argument called 'other' or 'self' |
| 1672 | # shouldn't be treated specially. |
| 1673 | od = OrderedDict() |
| 1674 | od.update(self=23) |
| 1675 | self.assertEqual(list(od.items()), [('self', 23)]) |
| 1676 | od = OrderedDict() |
| 1677 | od.update(other={}) |
| 1678 | self.assertEqual(list(od.items()), [('other', {})]) |
| 1679 | od = OrderedDict() |
| 1680 | od.update(red=5, blue=6, other=7, self=8) |
| 1681 | self.assertEqual(sorted(list(od.items())), |
| 1682 | [('blue', 6), ('other', 7), ('red', 5), ('self', 8)]) |
| 1683 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1684 | # Make sure that direct calls to update do not clear previous contents |
| 1685 | # add that updates items are not moved to the end |
| 1686 | d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) |
| 1687 | d.update([('e', 5), ('f', 6)], g=7, d=4) |
| 1688 | self.assertEqual(list(d.items()), |
| 1689 | [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) |
| 1690 | |
Serhiy Storchaka | ae5cb21 | 2014-11-27 16:25:51 +0200 | [diff] [blame] | 1691 | self.assertRaises(TypeError, OrderedDict().update, 42) |
| 1692 | self.assertRaises(TypeError, OrderedDict().update, (), ()) |
| 1693 | self.assertRaises(TypeError, OrderedDict.update) |
| 1694 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1695 | self.assertRaises(TypeError, OrderedDict().update, 42) |
| 1696 | self.assertRaises(TypeError, OrderedDict().update, (), ()) |
| 1697 | self.assertRaises(TypeError, OrderedDict.update) |
| 1698 | |
Eric Snow | ac02ef3 | 2015-06-02 20:42:14 -0600 | [diff] [blame] | 1699 | def test_fromkeys(self): |
| 1700 | OrderedDict = self.module.OrderedDict |
| 1701 | od = OrderedDict.fromkeys('abc') |
| 1702 | self.assertEqual(list(od.items()), [(c, None) for c in 'abc']) |
| 1703 | od = OrderedDict.fromkeys('abc', value=None) |
| 1704 | self.assertEqual(list(od.items()), [(c, None) for c in 'abc']) |
| 1705 | od = OrderedDict.fromkeys('abc', value=0) |
| 1706 | self.assertEqual(list(od.items()), [(c, 0) for c in 'abc']) |
| 1707 | |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 1708 | def test_abc(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1709 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 1710 | self.assertIsInstance(OrderedDict(), MutableMapping) |
| 1711 | self.assertTrue(issubclass(OrderedDict, MutableMapping)) |
| 1712 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1713 | def test_clear(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1714 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1715 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1716 | shuffle(pairs) |
| 1717 | od = OrderedDict(pairs) |
| 1718 | self.assertEqual(len(od), len(pairs)) |
| 1719 | od.clear() |
| 1720 | self.assertEqual(len(od), 0) |
| 1721 | |
| 1722 | def test_delitem(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1723 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1724 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1725 | od = OrderedDict(pairs) |
| 1726 | del od['a'] |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1727 | self.assertNotIn('a', od) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1728 | with self.assertRaises(KeyError): |
| 1729 | del od['a'] |
| 1730 | self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) |
| 1731 | |
| 1732 | def test_setitem(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1733 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1734 | od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)]) |
| 1735 | od['c'] = 10 # existing element |
| 1736 | od['f'] = 20 # new element |
| 1737 | self.assertEqual(list(od.items()), |
| 1738 | [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)]) |
| 1739 | |
| 1740 | def test_iterators(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1741 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1742 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1743 | shuffle(pairs) |
| 1744 | od = OrderedDict(pairs) |
| 1745 | self.assertEqual(list(od), [t[0] for t in pairs]) |
| 1746 | self.assertEqual(list(od.keys()), [t[0] for t in pairs]) |
| 1747 | self.assertEqual(list(od.values()), [t[1] for t in pairs]) |
| 1748 | self.assertEqual(list(od.items()), pairs) |
| 1749 | self.assertEqual(list(reversed(od)), |
| 1750 | [t[0] for t in reversed(pairs)]) |
Serhiy Storchaka | 578c921 | 2014-04-04 15:19:36 +0300 | [diff] [blame] | 1751 | self.assertEqual(list(reversed(od.keys())), |
| 1752 | [t[0] for t in reversed(pairs)]) |
| 1753 | self.assertEqual(list(reversed(od.values())), |
| 1754 | [t[1] for t in reversed(pairs)]) |
| 1755 | self.assertEqual(list(reversed(od.items())), list(reversed(pairs))) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1756 | |
Raymond Hettinger | 53d2c41 | 2014-05-03 21:58:45 -0700 | [diff] [blame] | 1757 | def test_detect_deletion_during_iteration(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1758 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 53d2c41 | 2014-05-03 21:58:45 -0700 | [diff] [blame] | 1759 | od = OrderedDict.fromkeys('abc') |
| 1760 | it = iter(od) |
| 1761 | key = next(it) |
| 1762 | del od[key] |
| 1763 | with self.assertRaises(Exception): |
| 1764 | # Note, the exact exception raised is not guaranteed |
| 1765 | # The only guarantee that the next() will not succeed |
| 1766 | next(it) |
| 1767 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1768 | def test_sorted_iterators(self): |
| 1769 | OrderedDict = self.module.OrderedDict |
| 1770 | with self.assertRaises(TypeError): |
| 1771 | OrderedDict([('a', 1), ('b', 2)], None) |
| 1772 | pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] |
| 1773 | od = OrderedDict(pairs) |
| 1774 | self.assertEqual(sorted(od), [t[0] for t in pairs]) |
| 1775 | self.assertEqual(sorted(od.keys()), [t[0] for t in pairs]) |
| 1776 | self.assertEqual(sorted(od.values()), [t[1] for t in pairs]) |
| 1777 | self.assertEqual(sorted(od.items()), pairs) |
| 1778 | self.assertEqual(sorted(reversed(od)), |
| 1779 | sorted([t[0] for t in reversed(pairs)])) |
| 1780 | |
Eric Snow | 67fb92e | 2015-05-30 11:43:36 -0600 | [diff] [blame] | 1781 | def test_iterators_empty(self): |
| 1782 | OrderedDict = self.module.OrderedDict |
| 1783 | od = OrderedDict() |
| 1784 | empty = [] |
| 1785 | self.assertEqual(list(od), empty) |
| 1786 | self.assertEqual(list(od.keys()), empty) |
| 1787 | self.assertEqual(list(od.values()), empty) |
| 1788 | self.assertEqual(list(od.items()), empty) |
| 1789 | self.assertEqual(list(reversed(od)), empty) |
| 1790 | self.assertEqual(list(reversed(od.keys())), empty) |
| 1791 | self.assertEqual(list(reversed(od.values())), empty) |
| 1792 | self.assertEqual(list(reversed(od.items())), empty) |
| 1793 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1794 | def test_popitem(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1795 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1796 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1797 | shuffle(pairs) |
| 1798 | od = OrderedDict(pairs) |
| 1799 | while pairs: |
| 1800 | self.assertEqual(od.popitem(), pairs.pop()) |
| 1801 | with self.assertRaises(KeyError): |
| 1802 | od.popitem() |
| 1803 | self.assertEqual(len(od), 0) |
| 1804 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1805 | def test_popitem_last(self): |
| 1806 | OrderedDict = self.module.OrderedDict |
| 1807 | pairs = [(i, i) for i in range(30)] |
| 1808 | |
| 1809 | obj = OrderedDict(pairs) |
| 1810 | for i in range(8): |
| 1811 | obj.popitem(True) |
| 1812 | obj.popitem(True) |
Eric Snow | ac02ef3 | 2015-06-02 20:42:14 -0600 | [diff] [blame] | 1813 | obj.popitem(last=True) |
| 1814 | self.assertEqual(len(obj), 20) |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1815 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1816 | def test_pop(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1817 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1818 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1819 | shuffle(pairs) |
| 1820 | od = OrderedDict(pairs) |
| 1821 | shuffle(pairs) |
| 1822 | while pairs: |
| 1823 | k, v = pairs.pop() |
| 1824 | self.assertEqual(od.pop(k), v) |
| 1825 | with self.assertRaises(KeyError): |
| 1826 | od.pop('xyz') |
| 1827 | self.assertEqual(len(od), 0) |
| 1828 | self.assertEqual(od.pop(k, 12345), 12345) |
| 1829 | |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 1830 | # make sure pop still works when __missing__ is defined |
| 1831 | class Missing(OrderedDict): |
| 1832 | def __missing__(self, key): |
| 1833 | return 0 |
| 1834 | m = Missing(a=1) |
| 1835 | self.assertEqual(m.pop('b', 5), 5) |
| 1836 | self.assertEqual(m.pop('a', 6), 1) |
| 1837 | self.assertEqual(m.pop('a', 6), 6) |
Eric Snow | ac02ef3 | 2015-06-02 20:42:14 -0600 | [diff] [blame] | 1838 | self.assertEqual(m.pop('a', default=6), 6) |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 1839 | with self.assertRaises(KeyError): |
| 1840 | m.pop('a') |
| 1841 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1842 | def test_equality(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1843 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1844 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1845 | shuffle(pairs) |
| 1846 | od1 = OrderedDict(pairs) |
| 1847 | od2 = OrderedDict(pairs) |
| 1848 | self.assertEqual(od1, od2) # same order implies equality |
| 1849 | pairs = pairs[2:] + pairs[:2] |
| 1850 | od2 = OrderedDict(pairs) |
| 1851 | self.assertNotEqual(od1, od2) # different order implies inequality |
| 1852 | # comparison to regular dict is not order sensitive |
| 1853 | self.assertEqual(od1, dict(od2)) |
| 1854 | self.assertEqual(dict(od2), od1) |
| 1855 | # different length implied inequality |
| 1856 | self.assertNotEqual(od1, OrderedDict(pairs[:-1])) |
| 1857 | |
| 1858 | def test_copying(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1859 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1860 | # Check that ordered dicts are copyable, deepcopyable, picklable, |
| 1861 | # and have a repr/eval round-trip |
| 1862 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1863 | od = OrderedDict(pairs) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1864 | def check(dup): |
| 1865 | msg = "\ncopy: %s\nod: %s" % (dup, od) |
| 1866 | self.assertIsNot(dup, od, msg) |
| 1867 | self.assertEqual(dup, od) |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1868 | self.assertEqual(list(dup.items()), list(od.items())) |
| 1869 | self.assertEqual(len(dup), len(od)) |
| 1870 | self.assertEqual(type(dup), type(od)) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1871 | check(od.copy()) |
| 1872 | check(copy.copy(od)) |
| 1873 | check(copy.deepcopy(od)) |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1874 | # pickle directly pulls the module, so we have to fake it |
| 1875 | with replaced_module('collections', self.module): |
| 1876 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1877 | with self.subTest(proto=proto): |
| 1878 | check(pickle.loads(pickle.dumps(od, proto))) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1879 | check(eval(repr(od))) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1880 | update_test = OrderedDict() |
| 1881 | update_test.update(od) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1882 | check(update_test) |
| 1883 | check(OrderedDict(od)) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1884 | |
Raymond Hettinger | 5b26fb5 | 2009-03-03 22:38:22 +0000 | [diff] [blame] | 1885 | def test_yaml_linkage(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1886 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 5b26fb5 | 2009-03-03 22:38:22 +0000 | [diff] [blame] | 1887 | # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. |
| 1888 | # In yaml, lists are native but tuples are not. |
| 1889 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1890 | od = OrderedDict(pairs) |
| 1891 | # yaml.dump(od) --> |
| 1892 | # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1893 | self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) |
Raymond Hettinger | 5b26fb5 | 2009-03-03 22:38:22 +0000 | [diff] [blame] | 1894 | |
Raymond Hettinger | b212157 | 2009-03-03 22:50:04 +0000 | [diff] [blame] | 1895 | def test_reduce_not_too_fat(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1896 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | b212157 | 2009-03-03 22:50:04 +0000 | [diff] [blame] | 1897 | # do not save instance dictionary if not needed |
| 1898 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1899 | od = OrderedDict(pairs) |
Serhiy Storchaka | 3ee6dab | 2013-05-21 12:47:57 +0300 | [diff] [blame] | 1900 | self.assertIsNone(od.__reduce__()[2]) |
Raymond Hettinger | b212157 | 2009-03-03 22:50:04 +0000 | [diff] [blame] | 1901 | od.x = 10 |
Serhiy Storchaka | 3ee6dab | 2013-05-21 12:47:57 +0300 | [diff] [blame] | 1902 | self.assertIsNotNone(od.__reduce__()[2]) |
| 1903 | |
| 1904 | def test_pickle_recursive(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1905 | OrderedDict = self.module.OrderedDict |
Serhiy Storchaka | 3ee6dab | 2013-05-21 12:47:57 +0300 | [diff] [blame] | 1906 | od = OrderedDict() |
| 1907 | od[1] = od |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1908 | |
| 1909 | # pickle directly pulls the module, so we have to fake it |
| 1910 | with replaced_module('collections', self.module): |
| 1911 | for proto in range(-1, pickle.HIGHEST_PROTOCOL + 1): |
| 1912 | dup = pickle.loads(pickle.dumps(od, proto)) |
| 1913 | self.assertIsNot(dup, od) |
| 1914 | self.assertEqual(list(dup.keys()), [1]) |
| 1915 | self.assertIs(dup[1], dup) |
Raymond Hettinger | b212157 | 2009-03-03 22:50:04 +0000 | [diff] [blame] | 1916 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1917 | def test_repr(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1918 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1919 | od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]) |
| 1920 | self.assertEqual(repr(od), |
| 1921 | "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])") |
| 1922 | self.assertEqual(eval(repr(od)), od) |
| 1923 | self.assertEqual(repr(OrderedDict()), "OrderedDict()") |
| 1924 | |
Raymond Hettinger | dc08a14 | 2010-09-12 05:15:22 +0000 | [diff] [blame] | 1925 | def test_repr_recursive(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1926 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | dc08a14 | 2010-09-12 05:15:22 +0000 | [diff] [blame] | 1927 | # See issue #9826 |
| 1928 | od = OrderedDict.fromkeys('abc') |
| 1929 | od['x'] = od |
| 1930 | self.assertEqual(repr(od), |
| 1931 | "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") |
| 1932 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1933 | def test_setdefault(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1934 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1935 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 1936 | shuffle(pairs) |
| 1937 | od = OrderedDict(pairs) |
| 1938 | pair_order = list(od.items()) |
| 1939 | self.assertEqual(od.setdefault('a', 10), 3) |
| 1940 | # make sure order didn't change |
| 1941 | self.assertEqual(list(od.items()), pair_order) |
| 1942 | self.assertEqual(od.setdefault('x', 10), 10) |
| 1943 | # make sure 'x' is added to the end |
| 1944 | self.assertEqual(list(od.items())[-1], ('x', 10)) |
Eric Snow | ac02ef3 | 2015-06-02 20:42:14 -0600 | [diff] [blame] | 1945 | self.assertEqual(od.setdefault('g', default=9), 9) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1946 | |
Raymond Hettinger | a673b1f | 2010-12-31 23:16:17 +0000 | [diff] [blame] | 1947 | # make sure setdefault still works when __missing__ is defined |
| 1948 | class Missing(OrderedDict): |
| 1949 | def __missing__(self, key): |
| 1950 | return 0 |
| 1951 | self.assertEqual(Missing().setdefault(5, 9), 9) |
| 1952 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1953 | def test_reinsert(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1954 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1955 | # Given insert a, insert b, delete a, re-insert a, |
| 1956 | # verify that a is now later than b. |
| 1957 | od = OrderedDict() |
| 1958 | od['a'] = 1 |
| 1959 | od['b'] = 2 |
| 1960 | del od['a'] |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1961 | self.assertEqual(list(od.items()), [('b', 2)]) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1962 | od['a'] = 1 |
| 1963 | self.assertEqual(list(od.items()), [('b', 2), ('a', 1)]) |
| 1964 | |
Raymond Hettinger | f45abc9 | 2010-09-06 21:26:09 +0000 | [diff] [blame] | 1965 | def test_move_to_end(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1966 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | f45abc9 | 2010-09-06 21:26:09 +0000 | [diff] [blame] | 1967 | od = OrderedDict.fromkeys('abcde') |
| 1968 | self.assertEqual(list(od), list('abcde')) |
| 1969 | od.move_to_end('c') |
| 1970 | self.assertEqual(list(od), list('abdec')) |
| 1971 | od.move_to_end('c', 0) |
| 1972 | self.assertEqual(list(od), list('cabde')) |
| 1973 | od.move_to_end('c', 0) |
| 1974 | self.assertEqual(list(od), list('cabde')) |
| 1975 | od.move_to_end('e') |
| 1976 | self.assertEqual(list(od), list('cabde')) |
Eric Snow | ac02ef3 | 2015-06-02 20:42:14 -0600 | [diff] [blame] | 1977 | od.move_to_end('b', last=False) |
| 1978 | self.assertEqual(list(od), list('bcade')) |
Raymond Hettinger | f45abc9 | 2010-09-06 21:26:09 +0000 | [diff] [blame] | 1979 | with self.assertRaises(KeyError): |
| 1980 | od.move_to_end('x') |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1981 | with self.assertRaises(KeyError): |
| 1982 | od.move_to_end('x', 0) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1983 | |
Raymond Hettinger | 35c87f2 | 2010-09-16 19:10:17 +0000 | [diff] [blame] | 1984 | def test_sizeof(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1985 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 35c87f2 | 2010-09-16 19:10:17 +0000 | [diff] [blame] | 1986 | # Wimpy test: Just verify the reported size is larger than a regular dict |
| 1987 | d = dict(a=1) |
| 1988 | od = OrderedDict(**d) |
| 1989 | self.assertGreater(sys.getsizeof(od), sys.getsizeof(d)) |
| 1990 | |
Raymond Hettinger | c074e9d | 2015-05-26 01:47:58 -0700 | [diff] [blame] | 1991 | def test_views(self): |
Eric Snow | e39facf | 2015-05-30 13:24:54 -0600 | [diff] [blame] | 1992 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | c074e9d | 2015-05-26 01:47:58 -0700 | [diff] [blame] | 1993 | # See http://bugs.python.org/issue24286 |
| 1994 | s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split() |
| 1995 | od = OrderedDict.fromkeys(s) |
| 1996 | self.assertEqual(od.keys(), dict(od).keys()) |
| 1997 | self.assertEqual(od.items(), dict(od).items()) |
| 1998 | |
Raymond Hettinger | 32062e9 | 2011-01-01 22:38:00 +0000 | [diff] [blame] | 1999 | def test_override_update(self): |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 2000 | OrderedDict = self.module.OrderedDict |
Raymond Hettinger | 32062e9 | 2011-01-01 22:38:00 +0000 | [diff] [blame] | 2001 | # Verify that subclasses can override update() without breaking __init__() |
| 2002 | class MyOD(OrderedDict): |
| 2003 | def update(self, *args, **kwds): |
| 2004 | raise Exception() |
| 2005 | items = [('a', 1), ('c', 3), ('b', 2)] |
| 2006 | self.assertEqual(list(MyOD(items).items()), items) |
| 2007 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 2008 | |
| 2009 | class PurePythonOrderedDictTests(OrderedDictTests, unittest.TestCase): |
| 2010 | |
| 2011 | module = py_coll |
| 2012 | |
| 2013 | |
| 2014 | @unittest.skipUnless(c_coll, 'requires the C version of the collections module') |
| 2015 | class CPythonOrderedDictTests(OrderedDictTests, unittest.TestCase): |
| 2016 | |
| 2017 | module = c_coll |
| 2018 | |
| 2019 | def test_delitem_hash_collision(self): |
| 2020 | OrderedDict = self.module.OrderedDict |
| 2021 | |
| 2022 | class Key: |
| 2023 | def __init__(self, hash): |
| 2024 | self._hash = hash |
| 2025 | self.value = str(id(self)) |
| 2026 | def __hash__(self): |
| 2027 | return self._hash |
| 2028 | def __eq__(self, other): |
| 2029 | try: |
| 2030 | return self.value == other.value |
| 2031 | except AttributeError: |
| 2032 | return False |
| 2033 | def __repr__(self): |
| 2034 | return self.value |
| 2035 | |
| 2036 | def blocking_hash(hash): |
| 2037 | # See the collision-handling in lookdict (in Objects/dictobject.c). |
| 2038 | MINSIZE = 8 |
| 2039 | i = (hash & MINSIZE-1) |
| 2040 | return (i << 2) + i + hash + 1 |
| 2041 | |
| 2042 | COLLIDING = 1 |
| 2043 | |
| 2044 | key = Key(COLLIDING) |
| 2045 | colliding = Key(COLLIDING) |
| 2046 | blocking = Key(blocking_hash(COLLIDING)) |
| 2047 | |
| 2048 | od = OrderedDict() |
| 2049 | od[key] = ... |
| 2050 | od[blocking] = ... |
| 2051 | od[colliding] = ... |
| 2052 | od['after'] = ... |
| 2053 | |
| 2054 | del od[blocking] |
| 2055 | del od[colliding] |
| 2056 | self.assertEqual(list(od.items()), [(key, ...), ('after', ...)]) |
| 2057 | |
Eric Snow | 4fabf02 | 2015-06-04 00:09:56 -0600 | [diff] [blame] | 2058 | def test_key_change_during_iteration(self): |
| 2059 | OrderedDict = self.module.OrderedDict |
| 2060 | |
| 2061 | od = OrderedDict.fromkeys('abcde') |
| 2062 | self.assertEqual(list(od), list('abcde')) |
| 2063 | with self.assertRaises(RuntimeError): |
| 2064 | for i, k in enumerate(od): |
| 2065 | od.move_to_end(k) |
| 2066 | self.assertLess(i, 5) |
| 2067 | with self.assertRaises(RuntimeError): |
| 2068 | for k in od: |
| 2069 | od['f'] = None |
| 2070 | with self.assertRaises(RuntimeError): |
| 2071 | for k in od: |
| 2072 | del od['c'] |
| 2073 | self.assertEqual(list(od), list('bdeaf')) |
| 2074 | |
Eric Snow | a762af7 | 2015-06-01 22:59:08 -0600 | [diff] [blame] | 2075 | def test_issue24347(self): |
| 2076 | OrderedDict = self.module.OrderedDict |
| 2077 | |
| 2078 | class Key: |
| 2079 | def __hash__(self): |
| 2080 | return randrange(100000) |
| 2081 | |
| 2082 | od = OrderedDict() |
| 2083 | for i in range(100): |
| 2084 | key = Key() |
| 2085 | od[key] = i |
| 2086 | |
| 2087 | # These should not crash. |
| 2088 | with self.assertRaises(KeyError): |
| 2089 | repr(od) |
| 2090 | with self.assertRaises(KeyError): |
| 2091 | od.copy() |
| 2092 | |
Eric Snow | d171975 | 2015-06-01 23:12:13 -0600 | [diff] [blame] | 2093 | def test_issue24348(self): |
| 2094 | OrderedDict = self.module.OrderedDict |
| 2095 | |
| 2096 | class Key: |
| 2097 | def __hash__(self): |
| 2098 | return 1 |
| 2099 | |
| 2100 | od = OrderedDict() |
| 2101 | od[Key()] = 0 |
| 2102 | # This should not crash. |
| 2103 | od.popitem() |
| 2104 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 2105 | |
| 2106 | class PurePythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 2107 | |
| 2108 | @classmethod |
| 2109 | def setUpClass(cls): |
| 2110 | cls.type2test = py_coll.OrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 2111 | |
Raymond Hettinger | dc879f0 | 2009-03-19 20:30:56 +0000 | [diff] [blame] | 2112 | def test_popitem(self): |
| 2113 | d = self._empty_mapping() |
| 2114 | self.assertRaises(KeyError, d.popitem) |
| 2115 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 2116 | |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 2117 | @unittest.skipUnless(c_coll, 'requires the C version of the collections module') |
| 2118 | class CPythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 2119 | |
| 2120 | @classmethod |
| 2121 | def setUpClass(cls): |
| 2122 | cls.type2test = c_coll.OrderedDict |
| 2123 | |
| 2124 | def test_popitem(self): |
| 2125 | d = self._empty_mapping() |
| 2126 | self.assertRaises(KeyError, d.popitem) |
| 2127 | |
| 2128 | |
| 2129 | class PurePythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 2130 | |
| 2131 | @classmethod |
| 2132 | def setUpClass(cls): |
| 2133 | class MyOrderedDict(py_coll.OrderedDict): |
| 2134 | pass |
| 2135 | cls.type2test = MyOrderedDict |
| 2136 | |
| 2137 | def test_popitem(self): |
| 2138 | d = self._empty_mapping() |
| 2139 | self.assertRaises(KeyError, d.popitem) |
| 2140 | |
| 2141 | |
| 2142 | @unittest.skipUnless(c_coll, 'requires the C version of the collections module') |
| 2143 | class CPythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 2144 | |
| 2145 | @classmethod |
| 2146 | def setUpClass(cls): |
| 2147 | class MyOrderedDict(c_coll.OrderedDict): |
| 2148 | pass |
| 2149 | cls.type2test = MyOrderedDict |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 2150 | |
Raymond Hettinger | dc879f0 | 2009-03-19 20:30:56 +0000 | [diff] [blame] | 2151 | def test_popitem(self): |
| 2152 | d = self._empty_mapping() |
| 2153 | self.assertRaises(KeyError, d.popitem) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 2154 | |
| 2155 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 2156 | ################################################################################ |
| 2157 | ### Run tests |
| 2158 | ################################################################################ |
| 2159 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 2160 | import doctest, collections |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 2161 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2162 | def test_main(verbose=None): |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2163 | NamedTupleDocs = doctest.DocTestSuite(module=collections) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 2164 | test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 2165 | TestCollectionABCs, TestCounter, TestChainMap, |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 2166 | PurePythonOrderedDictTests, CPythonOrderedDictTests, |
| 2167 | PurePythonGeneralMappingTests, CPythonGeneralMappingTests, |
| 2168 | PurePythonSubclassMappingTests, CPythonSubclassMappingTests, |
| 2169 | TestUserObjects, |
| 2170 | ] |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2171 | support.run_unittest(*test_classes) |
| 2172 | support.run_doctest(collections, verbose) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2173 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 2174 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2175 | if __name__ == "__main__": |
| 2176 | test_main(verbose=True) |