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 |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 4 | import inspect |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 5 | from test import support |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 6 | from collections import namedtuple, Counter, OrderedDict |
| 7 | from test import mapping_tests |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 8 | import pickle, copy |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 9 | from random import randrange, shuffle |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 10 | import keyword |
| 11 | import re |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 12 | import sys |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 13 | from collections import Hashable, Iterable, Iterator |
| 14 | from collections import Sized, Container, Callable |
| 15 | from collections import Set, MutableSet |
Raymond Hettinger | 9117c75 | 2010-08-22 07:44:24 +0000 | [diff] [blame] | 16 | from collections import Mapping, MutableMapping, KeysView, ItemsView, UserDict |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 17 | from collections import Sequence, MutableSequence |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 18 | from collections import ByteString |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 19 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 20 | TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 21 | |
| 22 | class TestNamedTuple(unittest.TestCase): |
| 23 | |
| 24 | def test_factory(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 25 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 26 | self.assertEqual(Point.__name__, 'Point') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 27 | self.assertEqual(Point.__slots__, ()) |
| 28 | self.assertEqual(Point.__module__, __name__) |
| 29 | self.assertEqual(Point.__getitem__, tuple.__getitem__) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 30 | self.assertEqual(Point._fields, ('x', 'y')) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 31 | |
| 32 | self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi') # type has non-alpha char |
| 33 | self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword |
| 34 | self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi') # type starts with digit |
| 35 | |
| 36 | self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi') # field with non-alpha char |
| 37 | self.assertRaises(ValueError, namedtuple, 'abc', 'abc class') # field has keyword |
| 38 | self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi') # field starts with digit |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 39 | self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi') # field with leading underscore |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 40 | self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi') # duplicate field |
| 41 | |
| 42 | namedtuple('Point0', 'x1 y2') # Verify that numbers are allowed in names |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 43 | namedtuple('_', 'a b c') # Test leading underscores in a typename |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 44 | |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 45 | nt = namedtuple('nt', 'the quick brown fox') # check unicode input |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 46 | self.assertNotIn("u'", repr(nt._fields)) |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 47 | nt = namedtuple('nt', ('the', 'quick')) # check unicode input |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 48 | self.assertNotIn("u'", repr(nt._fields)) |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 49 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 50 | self.assertRaises(TypeError, Point._make, [11]) # catch too few args |
| 51 | self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args |
| 52 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 53 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 54 | "Docstrings are omitted with -O2 and above") |
| 55 | def test_factory_doc_attr(self): |
| 56 | Point = namedtuple('Point', 'x y') |
| 57 | self.assertEqual(Point.__doc__, 'Point(x, y)') |
| 58 | |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 59 | def test_name_fixer(self): |
| 60 | for spec, renamed in [ |
Raymond Hettinger | 5614524 | 2009-04-02 22:31:59 +0000 | [diff] [blame] | 61 | [('efg', 'g%hi'), ('efg', '_1')], # field with non-alpha char |
| 62 | [('abc', 'class'), ('abc', '_1')], # field has keyword |
| 63 | [('8efg', '9ghi'), ('_0', '_1')], # field starts with digit |
| 64 | [('abc', '_efg'), ('abc', '_1')], # field with leading underscore |
| 65 | [('abc', 'efg', 'efg', 'ghi'), ('abc', 'efg', '_2', 'ghi')], # duplicate field |
| 66 | [('abc', '', 'x'), ('abc', '_1', 'x')], # fieldname is a space |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 67 | ]: |
| 68 | self.assertEqual(namedtuple('NT', spec, rename=True)._fields, renamed) |
| 69 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 70 | def test_instance(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 71 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 72 | p = Point(11, 22) |
| 73 | self.assertEqual(p, Point(x=11, y=22)) |
| 74 | self.assertEqual(p, Point(11, y=22)) |
| 75 | self.assertEqual(p, Point(y=22, x=11)) |
| 76 | self.assertEqual(p, Point(*(11, 22))) |
| 77 | self.assertEqual(p, Point(**dict(x=11, y=22))) |
| 78 | self.assertRaises(TypeError, Point, 1) # too few args |
| 79 | self.assertRaises(TypeError, Point, 1, 2, 3) # too many args |
| 80 | self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument |
| 81 | self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument |
| 82 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 83 | self.assertNotIn('__dict__', dir(p)) # verify instance has no dict |
| 84 | self.assertNotIn('__weakref__', dir(p)) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 85 | self.assertEqual(p, Point._make([11, 22])) # test _make classmethod |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 86 | self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute |
| 87 | self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method |
| 88 | self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 89 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 90 | try: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 91 | p._replace(x=1, error=2) |
| 92 | except ValueError: |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 93 | pass |
| 94 | else: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 95 | self._fail('Did not detect an incorrect fieldname') |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 96 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 97 | # verify that field string can have commas |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 98 | Point = namedtuple('Point', 'x, y') |
| 99 | p = Point(x=11, y=22) |
| 100 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
| 101 | |
| 102 | # verify that fieldspec can be a non-string sequence |
| 103 | Point = namedtuple('Point', ('x', 'y')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 104 | p = Point(x=11, y=22) |
| 105 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 106 | |
| 107 | def test_tupleness(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 108 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 109 | p = Point(11, 22) |
| 110 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 111 | self.assertIsInstance(p, tuple) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 112 | self.assertEqual(p, (11, 22)) # matches a real tuple |
| 113 | self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple |
| 114 | self.assertEqual(list(p), [11, 22]) # coercable to a list |
| 115 | self.assertEqual(max(p), 22) # iterable |
| 116 | self.assertEqual(max(*p), 22) # star-able |
| 117 | x, y = p |
| 118 | self.assertEqual(p, (x, y)) # unpacks like a tuple |
| 119 | self.assertEqual((p[0], p[1]), (11, 22)) # indexable like a tuple |
| 120 | self.assertRaises(IndexError, p.__getitem__, 3) |
| 121 | |
| 122 | self.assertEqual(p.x, x) |
| 123 | self.assertEqual(p.y, y) |
| 124 | self.assertRaises(AttributeError, eval, 'p.z', locals()) |
| 125 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 126 | def test_odd_sizes(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 127 | Zero = namedtuple('Zero', '') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 128 | self.assertEqual(Zero(), ()) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 129 | self.assertEqual(Zero._make([]), ()) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 130 | self.assertEqual(repr(Zero()), 'Zero()') |
| 131 | self.assertEqual(Zero()._asdict(), {}) |
| 132 | self.assertEqual(Zero()._fields, ()) |
| 133 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 134 | Dot = namedtuple('Dot', 'd') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 135 | self.assertEqual(Dot(1), (1,)) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 136 | self.assertEqual(Dot._make([1]), (1,)) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 137 | self.assertEqual(Dot(1).d, 1) |
| 138 | self.assertEqual(repr(Dot(1)), 'Dot(d=1)') |
| 139 | self.assertEqual(Dot(1)._asdict(), {'d':1}) |
| 140 | self.assertEqual(Dot(1)._replace(d=999), (999,)) |
| 141 | self.assertEqual(Dot(1)._fields, ('d',)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 142 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 143 | # n = 5000 |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 144 | n = 254 # SyntaxError: more than 255 arguments: |
| 145 | import string, random |
Georg Brandl | b533e26 | 2008-05-25 18:19:30 +0000 | [diff] [blame] | 146 | names = list(set(''.join([random.choice(string.ascii_letters) |
| 147 | for j in range(10)]) for i in range(n))) |
| 148 | n = len(names) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 149 | Big = namedtuple('Big', names) |
| 150 | b = Big(*range(n)) |
| 151 | self.assertEqual(b, tuple(range(n))) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 152 | self.assertEqual(Big._make(range(n)), tuple(range(n))) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 153 | for pos, name in enumerate(names): |
| 154 | self.assertEqual(getattr(b, name), pos) |
| 155 | repr(b) # make sure repr() doesn't blow-up |
| 156 | d = b._asdict() |
| 157 | d_expected = dict(zip(names, range(n))) |
| 158 | self.assertEqual(d, d_expected) |
| 159 | b2 = b._replace(**dict([(names[1], 999),(names[-5], 42)])) |
| 160 | b2_expected = list(range(n)) |
| 161 | b2_expected[1] = 999 |
| 162 | b2_expected[-5] = 42 |
| 163 | self.assertEqual(b2, tuple(b2_expected)) |
| 164 | self.assertEqual(b._fields, tuple(names)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 165 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 166 | def test_pickle(self): |
| 167 | p = TestNT(x=10, y=20, z=30) |
| 168 | for module in (pickle,): |
| 169 | loads = getattr(module, 'loads') |
| 170 | dumps = getattr(module, 'dumps') |
| 171 | for protocol in -1, 0, 1, 2: |
| 172 | q = loads(dumps(p, protocol)) |
| 173 | self.assertEqual(p, q) |
| 174 | self.assertEqual(p._fields, q._fields) |
| 175 | |
| 176 | def test_copy(self): |
| 177 | p = TestNT(x=10, y=20, z=30) |
| 178 | for copier in copy.copy, copy.deepcopy: |
| 179 | q = copier(p) |
| 180 | self.assertEqual(p, q) |
| 181 | self.assertEqual(p._fields, q._fields) |
| 182 | |
Raymond Hettinger | 089ba7f | 2009-05-27 00:38:24 +0000 | [diff] [blame] | 183 | def test_name_conflicts(self): |
| 184 | # Some names like "self", "cls", "tuple", "itemgetter", and "property" |
| 185 | # failed when used as field names. Test to make sure these now work. |
| 186 | T = namedtuple('T', 'itemgetter property self cls tuple') |
| 187 | t = T(1, 2, 3, 4, 5) |
| 188 | self.assertEqual(t, (1,2,3,4,5)) |
| 189 | newt = t._replace(itemgetter=10, property=20, self=30, cls=40, tuple=50) |
| 190 | self.assertEqual(newt, (10,20,30,40,50)) |
| 191 | |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 192 | # Broader test of all interesting names in a template |
| 193 | with support.captured_stdout() as template: |
| 194 | T = namedtuple('T', 'x', verbose=True) |
| 195 | words = set(re.findall('[A-Za-z]+', template.getvalue())) |
| 196 | words -= set(keyword.kwlist) |
| 197 | T = namedtuple('T', words) |
| 198 | # test __new__ |
| 199 | values = tuple(range(len(words))) |
| 200 | t = T(*values) |
| 201 | self.assertEqual(t, values) |
| 202 | t = T(**dict(zip(T._fields, values))) |
| 203 | self.assertEqual(t, values) |
| 204 | # test _make |
| 205 | t = T._make(values) |
| 206 | self.assertEqual(t, values) |
| 207 | # exercise __repr__ |
| 208 | repr(t) |
| 209 | # test _asdict |
| 210 | self.assertEqual(t._asdict(), dict(zip(T._fields, values))) |
| 211 | # test _replace |
| 212 | t = T._make(values) |
| 213 | newvalues = tuple(v*10 for v in values) |
| 214 | newt = t._replace(**dict(zip(T._fields, newvalues))) |
| 215 | self.assertEqual(newt, newvalues) |
| 216 | # test _fields |
| 217 | self.assertEqual(T._fields, tuple(words)) |
| 218 | # test __getnewargs__ |
| 219 | self.assertEqual(t.__getnewargs__(), values) |
| 220 | |
Raymond Hettinger | d331ce9 | 2010-08-08 01:13:42 +0000 | [diff] [blame] | 221 | def test_repr(self): |
| 222 | with support.captured_stdout() as template: |
| 223 | A = namedtuple('A', 'x', verbose=True) |
| 224 | self.assertEqual(repr(A(1)), 'A(x=1)') |
| 225 | # repr should show the name of the subclass |
| 226 | class B(A): |
| 227 | pass |
| 228 | self.assertEqual(repr(B(1)), 'B(x=1)') |
| 229 | |
| 230 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 231 | class ABCTestCase(unittest.TestCase): |
| 232 | |
| 233 | def validate_abstract_methods(self, abc, *names): |
| 234 | methodstubs = dict.fromkeys(names, lambda s, *args: 0) |
| 235 | |
| 236 | # everything should work will all required methods are present |
| 237 | C = type('C', (abc,), methodstubs) |
| 238 | C() |
| 239 | |
| 240 | # instantiation should fail if a required method is missing |
| 241 | for name in names: |
| 242 | stubs = methodstubs.copy() |
| 243 | del stubs[name] |
| 244 | C = type('C', (abc,), stubs) |
| 245 | self.assertRaises(TypeError, C, name) |
| 246 | |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 247 | def validate_isinstance(self, abc, name): |
| 248 | stub = lambda s, *args: 0 |
| 249 | |
| 250 | C = type('C', (object,), {'__hash__': None}) |
| 251 | setattr(C, name, stub) |
| 252 | self.assertIsInstance(C(), abc) |
| 253 | self.assertTrue(issubclass(C, abc)) |
| 254 | |
| 255 | C = type('C', (object,), {'__hash__': None}) |
| 256 | self.assertNotIsInstance(C(), abc) |
| 257 | self.assertFalse(issubclass(C, abc)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 258 | |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 259 | def validate_comparison(self, instance): |
| 260 | ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] |
| 261 | operators = {} |
| 262 | for op in ops: |
| 263 | name = '__' + op + '__' |
| 264 | operators[name] = getattr(operator, name) |
| 265 | |
| 266 | class Other: |
| 267 | def __init__(self): |
| 268 | self.right_side = False |
| 269 | def __eq__(self, other): |
| 270 | self.right_side = True |
| 271 | return True |
| 272 | __lt__ = __eq__ |
| 273 | __gt__ = __eq__ |
| 274 | __le__ = __eq__ |
| 275 | __ge__ = __eq__ |
| 276 | __ne__ = __eq__ |
| 277 | __ror__ = __eq__ |
| 278 | __rand__ = __eq__ |
| 279 | __rxor__ = __eq__ |
| 280 | __rsub__ = __eq__ |
| 281 | |
| 282 | for name, op in operators.items(): |
| 283 | if not hasattr(instance, name): |
| 284 | continue |
| 285 | other = Other() |
| 286 | op(instance, other) |
| 287 | self.assertTrue(other.right_side,'Right side not called for %s.%s' |
| 288 | % (type(instance), name)) |
| 289 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 290 | class TestOneTrickPonyABCs(ABCTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 291 | |
| 292 | def test_Hashable(self): |
| 293 | # Check some non-hashables |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 294 | non_samples = [bytearray(), list(), set(), dict()] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 295 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 296 | self.assertNotIsInstance(x, Hashable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 297 | self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 298 | # Check some hashables |
| 299 | samples = [None, |
| 300 | int(), float(), complex(), |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 301 | str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 302 | tuple(), frozenset(), |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 303 | int, list, object, type, bytes() |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 304 | ] |
| 305 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 306 | self.assertIsInstance(x, Hashable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 307 | self.assertTrue(issubclass(type(x), Hashable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 308 | self.assertRaises(TypeError, Hashable) |
| 309 | # Check direct subclassing |
| 310 | class H(Hashable): |
| 311 | def __hash__(self): |
| 312 | return super().__hash__() |
| 313 | self.assertEqual(hash(H()), 0) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 314 | self.assertFalse(issubclass(int, H)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 315 | self.validate_abstract_methods(Hashable, '__hash__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 316 | self.validate_isinstance(Hashable, '__hash__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 317 | |
| 318 | def test_Iterable(self): |
| 319 | # Check some non-iterables |
| 320 | non_samples = [None, 42, 3.14, 1j] |
| 321 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 322 | self.assertNotIsInstance(x, Iterable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 323 | self.assertFalse(issubclass(type(x), Iterable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 324 | # Check some iterables |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 325 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 326 | tuple(), list(), set(), frozenset(), dict(), |
| 327 | dict().keys(), dict().items(), dict().values(), |
| 328 | (lambda: (yield))(), |
| 329 | (x for x in []), |
| 330 | ] |
| 331 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 332 | self.assertIsInstance(x, Iterable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 333 | self.assertTrue(issubclass(type(x), Iterable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 334 | # Check direct subclassing |
| 335 | class I(Iterable): |
| 336 | def __iter__(self): |
| 337 | return super().__iter__() |
| 338 | self.assertEqual(list(I()), []) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 339 | self.assertFalse(issubclass(str, I)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 340 | self.validate_abstract_methods(Iterable, '__iter__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 341 | self.validate_isinstance(Iterable, '__iter__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 342 | |
| 343 | def test_Iterator(self): |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 344 | non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 345 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 346 | self.assertNotIsInstance(x, Iterator) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 347 | self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 348 | samples = [iter(bytes()), iter(str()), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 349 | iter(tuple()), iter(list()), iter(dict()), |
| 350 | iter(set()), iter(frozenset()), |
| 351 | iter(dict().keys()), iter(dict().items()), |
| 352 | iter(dict().values()), |
| 353 | (lambda: (yield))(), |
| 354 | (x for x in []), |
| 355 | ] |
| 356 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 357 | self.assertIsInstance(x, Iterator) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 358 | self.assertTrue(issubclass(type(x), Iterator), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 359 | self.validate_abstract_methods(Iterator, '__next__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 360 | self.validate_isinstance(Iterator, '__next__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 361 | |
| 362 | def test_Sized(self): |
| 363 | non_samples = [None, 42, 3.14, 1j, |
| 364 | (lambda: (yield))(), |
| 365 | (x for x in []), |
| 366 | ] |
| 367 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 368 | self.assertNotIsInstance(x, Sized) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 369 | self.assertFalse(issubclass(type(x), Sized), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 370 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 371 | tuple(), list(), set(), frozenset(), dict(), |
| 372 | dict().keys(), dict().items(), dict().values(), |
| 373 | ] |
| 374 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 375 | self.assertIsInstance(x, Sized) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 376 | self.assertTrue(issubclass(type(x), Sized), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 377 | self.validate_abstract_methods(Sized, '__len__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 378 | self.validate_isinstance(Sized, '__len__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 379 | |
| 380 | def test_Container(self): |
| 381 | non_samples = [None, 42, 3.14, 1j, |
| 382 | (lambda: (yield))(), |
| 383 | (x for x in []), |
| 384 | ] |
| 385 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 386 | self.assertNotIsInstance(x, Container) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 387 | self.assertFalse(issubclass(type(x), Container), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 388 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 389 | tuple(), list(), set(), frozenset(), dict(), |
| 390 | dict().keys(), dict().items(), |
| 391 | ] |
| 392 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 393 | self.assertIsInstance(x, Container) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 394 | self.assertTrue(issubclass(type(x), Container), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 395 | self.validate_abstract_methods(Container, '__contains__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 396 | self.validate_isinstance(Container, '__contains__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 397 | |
| 398 | def test_Callable(self): |
| 399 | non_samples = [None, 42, 3.14, 1j, |
| 400 | "", b"", (), [], {}, set(), |
| 401 | (lambda: (yield))(), |
| 402 | (x for x in []), |
| 403 | ] |
| 404 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 405 | self.assertNotIsInstance(x, Callable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 406 | self.assertFalse(issubclass(type(x), Callable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 407 | samples = [lambda: None, |
| 408 | type, int, object, |
| 409 | len, |
| 410 | list.append, [].append, |
| 411 | ] |
| 412 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 413 | self.assertIsInstance(x, Callable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 414 | self.assertTrue(issubclass(type(x), Callable), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 415 | self.validate_abstract_methods(Callable, '__call__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 416 | self.validate_isinstance(Callable, '__call__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 417 | |
| 418 | def test_direct_subclassing(self): |
| 419 | for B in Hashable, Iterable, Iterator, Sized, Container, Callable: |
| 420 | class C(B): |
| 421 | pass |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 422 | self.assertTrue(issubclass(C, B)) |
| 423 | self.assertFalse(issubclass(int, C)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 424 | |
| 425 | def test_registration(self): |
| 426 | for B in Hashable, Iterable, Iterator, Sized, Container, Callable: |
| 427 | class C: |
| 428 | __hash__ = None # Make sure it isn't hashable by default |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 429 | self.assertFalse(issubclass(C, B), B.__name__) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 430 | B.register(C) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 431 | self.assertTrue(issubclass(C, B)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 432 | |
Raymond Hettinger | 3f10a95 | 2009-04-01 19:05:50 +0000 | [diff] [blame] | 433 | class WithSet(MutableSet): |
| 434 | |
| 435 | def __init__(self, it=()): |
| 436 | self.data = set(it) |
| 437 | |
| 438 | def __len__(self): |
| 439 | return len(self.data) |
| 440 | |
| 441 | def __iter__(self): |
| 442 | return iter(self.data) |
| 443 | |
| 444 | def __contains__(self, item): |
| 445 | return item in self.data |
| 446 | |
| 447 | def add(self, item): |
| 448 | self.data.add(item) |
| 449 | |
| 450 | def discard(self, item): |
| 451 | self.data.discard(item) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 452 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 453 | class TestCollectionABCs(ABCTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 454 | |
| 455 | # XXX For now, we only test some virtual inheritance properties. |
| 456 | # We should also test the proper behavior of the collection ABCs |
| 457 | # as real base classes or mix-in classes. |
| 458 | |
| 459 | def test_Set(self): |
| 460 | for sample in [set, frozenset]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 461 | self.assertIsInstance(sample(), Set) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 462 | self.assertTrue(issubclass(sample, Set)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 463 | self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 464 | class MySet(Set): |
| 465 | def __contains__(self, x): |
| 466 | return False |
| 467 | def __len__(self): |
| 468 | return 0 |
| 469 | def __iter__(self): |
| 470 | return iter([]) |
| 471 | self.validate_comparison(MySet()) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 472 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 473 | def test_hash_Set(self): |
| 474 | class OneTwoThreeSet(Set): |
| 475 | def __init__(self): |
| 476 | self.contents = [1, 2, 3] |
| 477 | def __contains__(self, x): |
| 478 | return x in self.contents |
| 479 | def __len__(self): |
| 480 | return len(self.contents) |
| 481 | def __iter__(self): |
| 482 | return iter(self.contents) |
| 483 | def __hash__(self): |
| 484 | return self._hash() |
| 485 | a, b = OneTwoThreeSet(), OneTwoThreeSet() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 486 | self.assertTrue(hash(a) == hash(b)) |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 487 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 488 | def test_MutableSet(self): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 489 | self.assertIsInstance(set(), MutableSet) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 490 | self.assertTrue(issubclass(set, MutableSet)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 491 | self.assertNotIsInstance(frozenset(), MutableSet) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 492 | self.assertFalse(issubclass(frozenset, MutableSet)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 493 | self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__', |
| 494 | 'add', 'discard') |
| 495 | |
Raymond Hettinger | 3f10a95 | 2009-04-01 19:05:50 +0000 | [diff] [blame] | 496 | def test_issue_5647(self): |
| 497 | # MutableSet.__iand__ mutated the set during iteration |
| 498 | s = WithSet('abcd') |
| 499 | s &= WithSet('cdef') # This used to fail |
| 500 | self.assertEqual(set(s), set('cd')) |
| 501 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 502 | def test_issue_4920(self): |
| 503 | # MutableSet.pop() method did not work |
| 504 | class MySet(collections.MutableSet): |
| 505 | __slots__=['__s'] |
| 506 | def __init__(self,items=None): |
| 507 | if items is None: |
| 508 | items=[] |
| 509 | self.__s=set(items) |
| 510 | def __contains__(self,v): |
| 511 | return v in self.__s |
| 512 | def __iter__(self): |
| 513 | return iter(self.__s) |
| 514 | def __len__(self): |
| 515 | return len(self.__s) |
| 516 | def add(self,v): |
| 517 | result=v not in self.__s |
| 518 | self.__s.add(v) |
| 519 | return result |
| 520 | def discard(self,v): |
| 521 | result=v in self.__s |
| 522 | self.__s.discard(v) |
| 523 | return result |
| 524 | def __repr__(self): |
| 525 | return "MySet(%s)" % repr(list(self)) |
| 526 | s = MySet([5,43,2,1]) |
| 527 | self.assertEqual(s.pop(), 1) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 528 | |
Daniel Stutzbach | 31da5b2 | 2010-08-24 20:49:57 +0000 | [diff] [blame] | 529 | def test_issue8750(self): |
| 530 | empty = WithSet() |
| 531 | full = WithSet(range(10)) |
| 532 | s = WithSet(full) |
| 533 | s -= s |
| 534 | self.assertEqual(s, empty) |
| 535 | s = WithSet(full) |
| 536 | s ^= s |
| 537 | self.assertEqual(s, empty) |
| 538 | s = WithSet(full) |
| 539 | s &= s |
| 540 | self.assertEqual(s, full) |
| 541 | s |= s |
| 542 | self.assertEqual(s, full) |
| 543 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 544 | def test_Mapping(self): |
| 545 | for sample in [dict]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 546 | self.assertIsInstance(sample(), Mapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 547 | self.assertTrue(issubclass(sample, Mapping)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 548 | self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', |
| 549 | '__getitem__') |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 550 | class MyMapping(collections.Mapping): |
| 551 | def __len__(self): |
| 552 | return 0 |
| 553 | def __getitem__(self, i): |
| 554 | raise IndexError |
| 555 | def __iter__(self): |
| 556 | return iter(()) |
| 557 | self.validate_comparison(MyMapping()) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 558 | |
| 559 | def test_MutableMapping(self): |
| 560 | for sample in [dict]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 561 | self.assertIsInstance(sample(), MutableMapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 562 | self.assertTrue(issubclass(sample, MutableMapping)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 563 | self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__', |
| 564 | '__getitem__', '__setitem__', '__delitem__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 565 | |
Raymond Hettinger | 9117c75 | 2010-08-22 07:44:24 +0000 | [diff] [blame] | 566 | def test_MutableMapping_subclass(self): |
| 567 | # Test issue 9214 |
| 568 | mymap = UserDict() |
| 569 | mymap['red'] = 5 |
| 570 | self.assertIsInstance(mymap.keys(), Set) |
| 571 | self.assertIsInstance(mymap.keys(), KeysView) |
| 572 | self.assertIsInstance(mymap.items(), Set) |
| 573 | self.assertIsInstance(mymap.items(), ItemsView) |
| 574 | |
| 575 | mymap = UserDict() |
| 576 | mymap['red'] = 5 |
| 577 | z = mymap.keys() | {'orange'} |
| 578 | self.assertIsInstance(z, set) |
| 579 | list(z) |
| 580 | mymap['blue'] = 7 # Shouldn't affect 'z' |
| 581 | self.assertEqual(sorted(z), ['orange', 'red']) |
| 582 | |
| 583 | mymap = UserDict() |
| 584 | mymap['red'] = 5 |
| 585 | z = mymap.items() | {('orange', 3)} |
| 586 | self.assertIsInstance(z, set) |
| 587 | list(z) |
| 588 | mymap['blue'] = 7 # Shouldn't affect 'z' |
| 589 | self.assertEqual(sorted(z), [('orange', 3), ('red', 5)]) |
| 590 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 591 | def test_Sequence(self): |
| 592 | for sample in [tuple, list, bytes, str]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 593 | self.assertIsInstance(sample(), Sequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 594 | self.assertTrue(issubclass(sample, Sequence)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 595 | self.assertIsInstance(range(10), Sequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 596 | self.assertTrue(issubclass(range, Sequence)) |
| 597 | self.assertTrue(issubclass(str, Sequence)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 598 | self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', |
| 599 | '__getitem__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 600 | |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 601 | def test_ByteString(self): |
| 602 | for sample in [bytes, bytearray]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 603 | self.assertIsInstance(sample(), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 604 | self.assertTrue(issubclass(sample, ByteString)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 605 | for sample in [str, list, tuple]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 606 | self.assertNotIsInstance(sample(), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 607 | self.assertFalse(issubclass(sample, ByteString)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 608 | self.assertNotIsInstance(memoryview(b""), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 609 | self.assertFalse(issubclass(memoryview, ByteString)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 610 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 611 | def test_MutableSequence(self): |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 612 | for sample in [tuple, str, bytes]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 613 | self.assertNotIsInstance(sample(), MutableSequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 614 | self.assertFalse(issubclass(sample, MutableSequence)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 615 | for sample in [list, bytearray]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 616 | self.assertIsInstance(sample(), MutableSequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 617 | self.assertTrue(issubclass(sample, MutableSequence)) |
| 618 | self.assertFalse(issubclass(str, MutableSequence)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 619 | self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', |
| 620 | '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 621 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 622 | class TestCounter(unittest.TestCase): |
| 623 | |
| 624 | def test_basics(self): |
| 625 | c = Counter('abcaba') |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 626 | self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) |
| 627 | self.assertEqual(c, Counter(a=3, b=2, c=1)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 628 | self.assertIsInstance(c, dict) |
| 629 | self.assertIsInstance(c, Mapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 630 | self.assertTrue(issubclass(Counter, dict)) |
| 631 | self.assertTrue(issubclass(Counter, Mapping)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 632 | self.assertEqual(len(c), 3) |
| 633 | self.assertEqual(sum(c.values()), 6) |
| 634 | self.assertEqual(sorted(c.values()), [1, 2, 3]) |
| 635 | self.assertEqual(sorted(c.keys()), ['a', 'b', 'c']) |
| 636 | self.assertEqual(sorted(c), ['a', 'b', 'c']) |
| 637 | self.assertEqual(sorted(c.items()), |
| 638 | [('a', 3), ('b', 2), ('c', 1)]) |
| 639 | self.assertEqual(c['b'], 2) |
| 640 | self.assertEqual(c['z'], 0) |
| 641 | self.assertEqual(c.__contains__('c'), True) |
| 642 | self.assertEqual(c.__contains__('z'), False) |
| 643 | self.assertEqual(c.get('b', 10), 2) |
| 644 | self.assertEqual(c.get('z', 10), 10) |
| 645 | self.assertEqual(c, dict(a=3, b=2, c=1)) |
| 646 | self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") |
| 647 | self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)]) |
| 648 | for i in range(5): |
| 649 | self.assertEqual(c.most_common(i), |
| 650 | [('a', 3), ('b', 2), ('c', 1)][:i]) |
| 651 | self.assertEqual(''.join(sorted(c.elements())), 'aaabbc') |
| 652 | c['a'] += 1 # increment an existing value |
| 653 | c['b'] -= 2 # sub existing value to zero |
| 654 | del c['c'] # remove an entry |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 655 | del c['c'] # make sure that del doesn't raise KeyError |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 656 | c['d'] -= 2 # sub from a missing value |
| 657 | c['e'] = -5 # directly assign a missing value |
| 658 | c['f'] += 4 # add to a missing value |
| 659 | self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) |
| 660 | self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') |
| 661 | self.assertEqual(c.pop('f'), 4) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 662 | self.assertNotIn('f', c) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 663 | for i in range(3): |
| 664 | elem, cnt = c.popitem() |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 665 | self.assertNotIn(elem, c) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 666 | c.clear() |
| 667 | self.assertEqual(c, {}) |
| 668 | self.assertEqual(repr(c), 'Counter()') |
| 669 | self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc') |
| 670 | self.assertRaises(TypeError, hash, c) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 671 | c.update(dict(a=5, b=3)) |
| 672 | c.update(c=1) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 673 | c.update(Counter('a' * 50 + 'b' * 30)) |
| 674 | c.update() # test case with no args |
| 675 | c.__init__('a' * 500 + 'b' * 300) |
| 676 | c.__init__('cdc') |
| 677 | c.__init__() |
| 678 | self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) |
| 679 | self.assertEqual(c.setdefault('d', 5), 1) |
| 680 | self.assertEqual(c['d'], 1) |
| 681 | self.assertEqual(c.setdefault('e', 5), 5) |
| 682 | self.assertEqual(c['e'], 5) |
| 683 | |
| 684 | def test_copying(self): |
| 685 | # Check that counters are copyable, deepcopyable, picklable, and |
| 686 | #have a repr/eval round-trip |
| 687 | words = Counter('which witch had which witches wrist watch'.split()) |
| 688 | update_test = Counter() |
| 689 | update_test.update(words) |
| 690 | for i, dup in enumerate([ |
| 691 | words.copy(), |
| 692 | copy.copy(words), |
| 693 | copy.deepcopy(words), |
| 694 | pickle.loads(pickle.dumps(words, 0)), |
| 695 | pickle.loads(pickle.dumps(words, 1)), |
| 696 | pickle.loads(pickle.dumps(words, 2)), |
| 697 | pickle.loads(pickle.dumps(words, -1)), |
| 698 | eval(repr(words)), |
| 699 | update_test, |
| 700 | Counter(words), |
| 701 | ]): |
| 702 | msg = (i, dup, words) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 703 | self.assertTrue(dup is not words) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 704 | self.assertEquals(dup, words) |
| 705 | self.assertEquals(len(dup), len(words)) |
| 706 | self.assertEquals(type(dup), type(words)) |
| 707 | |
| 708 | def test_conversions(self): |
| 709 | # Convert to: set, list, dict |
| 710 | s = 'she sells sea shells by the sea shore' |
| 711 | self.assertEqual(sorted(Counter(s).elements()), sorted(s)) |
| 712 | self.assertEqual(sorted(Counter(s)), sorted(set(s))) |
| 713 | self.assertEqual(dict(Counter(s)), dict(Counter(s).items())) |
| 714 | self.assertEqual(set(Counter(s)), set(s)) |
| 715 | |
Raymond Hettinger | 670eaec | 2009-01-21 23:14:07 +0000 | [diff] [blame] | 716 | def test_invariant_for_the_in_operator(self): |
| 717 | c = Counter(a=10, b=-2, c=0) |
| 718 | for elem in c: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 719 | self.assertTrue(elem in c) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 720 | self.assertIn(elem, c) |
Raymond Hettinger | 670eaec | 2009-01-21 23:14:07 +0000 | [diff] [blame] | 721 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 722 | def test_multiset_operations(self): |
| 723 | # Verify that adding a zero counter will strip zeros and negatives |
| 724 | c = Counter(a=10, b=-2, c=0) + Counter() |
| 725 | self.assertEqual(dict(c), dict(a=10)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 726 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 727 | elements = 'abcd' |
| 728 | for i in range(1000): |
| 729 | # test random pairs of multisets |
| 730 | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 731 | p.update(e=1, f=-1, g=0) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 732 | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 733 | q.update(h=1, i=-1, j=0) |
| 734 | for counterop, numberop in [ |
| 735 | (Counter.__add__, lambda x, y: max(0, x+y)), |
| 736 | (Counter.__sub__, lambda x, y: max(0, x-y)), |
| 737 | (Counter.__or__, lambda x, y: max(0,x,y)), |
| 738 | (Counter.__and__, lambda x, y: max(0, min(x,y))), |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 739 | ]: |
| 740 | result = counterop(p, q) |
| 741 | for x in elements: |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 742 | self.assertEqual(numberop(p[x], q[x]), result[x], |
| 743 | (counterop, x, p, q)) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 744 | # verify that results exclude non-positive counts |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 745 | self.assertTrue(x>0 for x in result.values()) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 746 | |
| 747 | elements = 'abcdef' |
| 748 | for i in range(100): |
| 749 | # verify that random multisets with no repeats are exactly like sets |
| 750 | p = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |
| 751 | q = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |
| 752 | for counterop, setop in [ |
| 753 | (Counter.__sub__, set.__sub__), |
| 754 | (Counter.__or__, set.__or__), |
| 755 | (Counter.__and__, set.__and__), |
| 756 | ]: |
| 757 | counter_result = counterop(p, q) |
| 758 | set_result = setop(set(p.elements()), set(q.elements())) |
| 759 | self.assertEqual(counter_result, dict.fromkeys(set_result, 1)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 760 | |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 761 | def test_subtract(self): |
| 762 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 763 | c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50) |
| 764 | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |
| 765 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 766 | c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)) |
| 767 | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |
| 768 | c = Counter('aaabbcd') |
| 769 | c.subtract('aaaabbcce') |
| 770 | 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] | 771 | |
| 772 | class TestOrderedDict(unittest.TestCase): |
| 773 | |
| 774 | def test_init(self): |
| 775 | with self.assertRaises(TypeError): |
| 776 | OrderedDict([('a', 1), ('b', 2)], None) # too many args |
| 777 | pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] |
| 778 | self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input |
| 779 | self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input |
| 780 | self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input |
| 781 | self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)], |
| 782 | c=3, e=5).items()), pairs) # mixed input |
| 783 | |
| 784 | # make sure no positional args conflict with possible kwdargs |
| 785 | self.assertEqual(inspect.getargspec(OrderedDict.__dict__['__init__']).args, |
| 786 | ['self']) |
| 787 | |
| 788 | # Make sure that direct calls to __init__ do not clear previous contents |
| 789 | d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) |
| 790 | d.__init__([('e', 5), ('f', 6)], g=7, d=4) |
| 791 | self.assertEqual(list(d.items()), |
| 792 | [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) |
| 793 | |
| 794 | def test_update(self): |
| 795 | with self.assertRaises(TypeError): |
| 796 | OrderedDict().update([('a', 1), ('b', 2)], None) # too many args |
| 797 | pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] |
| 798 | od = OrderedDict() |
| 799 | od.update(dict(pairs)) |
| 800 | self.assertEqual(sorted(od.items()), pairs) # dict input |
| 801 | od = OrderedDict() |
| 802 | od.update(**dict(pairs)) |
| 803 | self.assertEqual(sorted(od.items()), pairs) # kwds input |
| 804 | od = OrderedDict() |
| 805 | od.update(pairs) |
| 806 | self.assertEqual(list(od.items()), pairs) # pairs input |
| 807 | od = OrderedDict() |
| 808 | od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5) |
| 809 | self.assertEqual(list(od.items()), pairs) # mixed input |
| 810 | |
Mark Dickinson | b214e90 | 2010-07-11 18:53:06 +0000 | [diff] [blame] | 811 | # Issue 9137: Named argument called 'other' or 'self' |
| 812 | # shouldn't be treated specially. |
| 813 | od = OrderedDict() |
| 814 | od.update(self=23) |
| 815 | self.assertEqual(list(od.items()), [('self', 23)]) |
| 816 | od = OrderedDict() |
| 817 | od.update(other={}) |
| 818 | self.assertEqual(list(od.items()), [('other', {})]) |
| 819 | od = OrderedDict() |
| 820 | od.update(red=5, blue=6, other=7, self=8) |
| 821 | self.assertEqual(sorted(list(od.items())), |
| 822 | [('blue', 6), ('other', 7), ('red', 5), ('self', 8)]) |
| 823 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 824 | # Make sure that direct calls to update do not clear previous contents |
| 825 | # add that updates items are not moved to the end |
| 826 | d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) |
| 827 | d.update([('e', 5), ('f', 6)], g=7, d=4) |
| 828 | self.assertEqual(list(d.items()), |
| 829 | [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) |
| 830 | |
| 831 | def test_clear(self): |
| 832 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 833 | shuffle(pairs) |
| 834 | od = OrderedDict(pairs) |
| 835 | self.assertEqual(len(od), len(pairs)) |
| 836 | od.clear() |
| 837 | self.assertEqual(len(od), 0) |
| 838 | |
| 839 | def test_delitem(self): |
| 840 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 841 | od = OrderedDict(pairs) |
| 842 | del od['a'] |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 843 | self.assertNotIn('a', od) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 844 | with self.assertRaises(KeyError): |
| 845 | del od['a'] |
| 846 | self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) |
| 847 | |
| 848 | def test_setitem(self): |
| 849 | od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)]) |
| 850 | od['c'] = 10 # existing element |
| 851 | od['f'] = 20 # new element |
| 852 | self.assertEqual(list(od.items()), |
| 853 | [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)]) |
| 854 | |
| 855 | def test_iterators(self): |
| 856 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 857 | shuffle(pairs) |
| 858 | od = OrderedDict(pairs) |
| 859 | self.assertEqual(list(od), [t[0] for t in pairs]) |
| 860 | self.assertEqual(list(od.keys()), [t[0] for t in pairs]) |
| 861 | self.assertEqual(list(od.values()), [t[1] for t in pairs]) |
| 862 | self.assertEqual(list(od.items()), pairs) |
| 863 | self.assertEqual(list(reversed(od)), |
| 864 | [t[0] for t in reversed(pairs)]) |
| 865 | |
| 866 | def test_popitem(self): |
| 867 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 868 | shuffle(pairs) |
| 869 | od = OrderedDict(pairs) |
| 870 | while pairs: |
| 871 | self.assertEqual(od.popitem(), pairs.pop()) |
| 872 | with self.assertRaises(KeyError): |
| 873 | od.popitem() |
| 874 | self.assertEqual(len(od), 0) |
| 875 | |
| 876 | def test_pop(self): |
| 877 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 878 | shuffle(pairs) |
| 879 | od = OrderedDict(pairs) |
| 880 | shuffle(pairs) |
| 881 | while pairs: |
| 882 | k, v = pairs.pop() |
| 883 | self.assertEqual(od.pop(k), v) |
| 884 | with self.assertRaises(KeyError): |
| 885 | od.pop('xyz') |
| 886 | self.assertEqual(len(od), 0) |
| 887 | self.assertEqual(od.pop(k, 12345), 12345) |
| 888 | |
| 889 | def test_equality(self): |
| 890 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 891 | shuffle(pairs) |
| 892 | od1 = OrderedDict(pairs) |
| 893 | od2 = OrderedDict(pairs) |
| 894 | self.assertEqual(od1, od2) # same order implies equality |
| 895 | pairs = pairs[2:] + pairs[:2] |
| 896 | od2 = OrderedDict(pairs) |
| 897 | self.assertNotEqual(od1, od2) # different order implies inequality |
| 898 | # comparison to regular dict is not order sensitive |
| 899 | self.assertEqual(od1, dict(od2)) |
| 900 | self.assertEqual(dict(od2), od1) |
| 901 | # different length implied inequality |
| 902 | self.assertNotEqual(od1, OrderedDict(pairs[:-1])) |
| 903 | |
| 904 | def test_copying(self): |
| 905 | # Check that ordered dicts are copyable, deepcopyable, picklable, |
| 906 | # and have a repr/eval round-trip |
| 907 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 908 | od = OrderedDict(pairs) |
| 909 | update_test = OrderedDict() |
| 910 | update_test.update(od) |
| 911 | for i, dup in enumerate([ |
| 912 | od.copy(), |
| 913 | copy.copy(od), |
| 914 | copy.deepcopy(od), |
| 915 | pickle.loads(pickle.dumps(od, 0)), |
| 916 | pickle.loads(pickle.dumps(od, 1)), |
| 917 | pickle.loads(pickle.dumps(od, 2)), |
| 918 | pickle.loads(pickle.dumps(od, 3)), |
| 919 | pickle.loads(pickle.dumps(od, -1)), |
| 920 | eval(repr(od)), |
| 921 | update_test, |
| 922 | OrderedDict(od), |
| 923 | ]): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 924 | self.assertTrue(dup is not od) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 925 | self.assertEquals(dup, od) |
| 926 | self.assertEquals(list(dup.items()), list(od.items())) |
| 927 | self.assertEquals(len(dup), len(od)) |
| 928 | self.assertEquals(type(dup), type(od)) |
| 929 | |
Raymond Hettinger | 5b26fb5 | 2009-03-03 22:38:22 +0000 | [diff] [blame] | 930 | def test_yaml_linkage(self): |
| 931 | # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. |
| 932 | # In yaml, lists are native but tuples are not. |
| 933 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 934 | od = OrderedDict(pairs) |
| 935 | # yaml.dump(od) --> |
| 936 | # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 937 | self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) |
Raymond Hettinger | 5b26fb5 | 2009-03-03 22:38:22 +0000 | [diff] [blame] | 938 | |
Raymond Hettinger | b212157 | 2009-03-03 22:50:04 +0000 | [diff] [blame] | 939 | def test_reduce_not_too_fat(self): |
| 940 | # do not save instance dictionary if not needed |
| 941 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 942 | od = OrderedDict(pairs) |
| 943 | self.assertEqual(len(od.__reduce__()), 2) |
| 944 | od.x = 10 |
| 945 | self.assertEqual(len(od.__reduce__()), 3) |
| 946 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 947 | def test_repr(self): |
| 948 | od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]) |
| 949 | self.assertEqual(repr(od), |
| 950 | "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])") |
| 951 | self.assertEqual(eval(repr(od)), od) |
| 952 | self.assertEqual(repr(OrderedDict()), "OrderedDict()") |
| 953 | |
Raymond Hettinger | dc08a14 | 2010-09-12 05:15:22 +0000 | [diff] [blame] | 954 | def test_repr_recursive(self): |
| 955 | # See issue #9826 |
| 956 | od = OrderedDict.fromkeys('abc') |
| 957 | od['x'] = od |
| 958 | self.assertEqual(repr(od), |
| 959 | "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") |
| 960 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 961 | def test_setdefault(self): |
| 962 | pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |
| 963 | shuffle(pairs) |
| 964 | od = OrderedDict(pairs) |
| 965 | pair_order = list(od.items()) |
| 966 | self.assertEqual(od.setdefault('a', 10), 3) |
| 967 | # make sure order didn't change |
| 968 | self.assertEqual(list(od.items()), pair_order) |
| 969 | self.assertEqual(od.setdefault('x', 10), 10) |
| 970 | # make sure 'x' is added to the end |
| 971 | self.assertEqual(list(od.items())[-1], ('x', 10)) |
| 972 | |
| 973 | def test_reinsert(self): |
| 974 | # Given insert a, insert b, delete a, re-insert a, |
| 975 | # verify that a is now later than b. |
| 976 | od = OrderedDict() |
| 977 | od['a'] = 1 |
| 978 | od['b'] = 2 |
| 979 | del od['a'] |
| 980 | od['a'] = 1 |
| 981 | self.assertEqual(list(od.items()), [('b', 2), ('a', 1)]) |
| 982 | |
Raymond Hettinger | f45abc9 | 2010-09-06 21:26:09 +0000 | [diff] [blame] | 983 | def test_move_to_end(self): |
| 984 | od = OrderedDict.fromkeys('abcde') |
| 985 | self.assertEqual(list(od), list('abcde')) |
| 986 | od.move_to_end('c') |
| 987 | self.assertEqual(list(od), list('abdec')) |
| 988 | od.move_to_end('c', 0) |
| 989 | self.assertEqual(list(od), list('cabde')) |
| 990 | od.move_to_end('c', 0) |
| 991 | self.assertEqual(list(od), list('cabde')) |
| 992 | od.move_to_end('e') |
| 993 | self.assertEqual(list(od), list('cabde')) |
| 994 | with self.assertRaises(KeyError): |
| 995 | od.move_to_end('x') |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 996 | |
Raymond Hettinger | 35c87f2 | 2010-09-16 19:10:17 +0000 | [diff] [blame] | 997 | def test_sizeof(self): |
| 998 | # Wimpy test: Just verify the reported size is larger than a regular dict |
| 999 | d = dict(a=1) |
| 1000 | od = OrderedDict(**d) |
| 1001 | self.assertGreater(sys.getsizeof(od), sys.getsizeof(d)) |
| 1002 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1003 | class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 1004 | type2test = OrderedDict |
| 1005 | |
Raymond Hettinger | dc879f0 | 2009-03-19 20:30:56 +0000 | [diff] [blame] | 1006 | def test_popitem(self): |
| 1007 | d = self._empty_mapping() |
| 1008 | self.assertRaises(KeyError, d.popitem) |
| 1009 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1010 | class MyOrderedDict(OrderedDict): |
| 1011 | pass |
| 1012 | |
| 1013 | class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): |
| 1014 | type2test = MyOrderedDict |
| 1015 | |
Raymond Hettinger | dc879f0 | 2009-03-19 20:30:56 +0000 | [diff] [blame] | 1016 | def test_popitem(self): |
| 1017 | d = self._empty_mapping() |
| 1018 | self.assertRaises(KeyError, d.popitem) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1019 | |
| 1020 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1021 | import doctest, collections |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1022 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1023 | def test_main(verbose=None): |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 1024 | NamedTupleDocs = doctest.DocTestSuite(module=collections) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1025 | test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 1026 | TestCollectionABCs, TestCounter, |
| 1027 | TestOrderedDict, GeneralMappingTests, SubclassMappingTests] |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1028 | support.run_unittest(*test_classes) |
| 1029 | support.run_doctest(collections, verbose) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1030 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1031 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1032 | if __name__ == "__main__": |
| 1033 | test_main(verbose=True) |