Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1 | """Unit tests for collections.py.""" |
| 2 | |
Serhiy Storchaka | 33e7ea5 | 2015-11-25 17:09:01 +0200 | [diff] [blame] | 3 | import collections |
| 4 | import copy |
| 5 | import doctest |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 6 | import inspect |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 7 | import keyword |
Serhiy Storchaka | 33e7ea5 | 2015-11-25 17:09:01 +0200 | [diff] [blame] | 8 | import operator |
| 9 | import pickle |
| 10 | from random import choice, randrange |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 11 | import re |
Serhiy Storchaka | 33e7ea5 | 2015-11-25 17:09:01 +0200 | [diff] [blame] | 12 | import string |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 13 | import sys |
Serhiy Storchaka | 33e7ea5 | 2015-11-25 17:09:01 +0200 | [diff] [blame] | 14 | from test import support |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 15 | import types |
Serhiy Storchaka | 33e7ea5 | 2015-11-25 17:09:01 +0200 | [diff] [blame] | 16 | import unittest |
| 17 | |
| 18 | from collections import namedtuple, Counter, OrderedDict, _count_elements |
Raymond Hettinger | 573b44c | 2015-05-22 16:56:32 -0700 | [diff] [blame] | 19 | from collections import UserDict, UserString, UserList |
Raymond Hettinger | 9fe1ccf | 2011-02-26 01:02:51 +0000 | [diff] [blame] | 20 | from collections import ChainMap |
Raymond Hettinger | 32ea165 | 2015-03-21 01:37:37 -0700 | [diff] [blame] | 21 | from collections import deque |
Yury Selivanov | e0104ae | 2015-05-14 12:19:16 -0400 | [diff] [blame] | 22 | from collections.abc import Awaitable, Coroutine, AsyncIterator, AsyncIterable |
Raymond Hettinger | bd60e8d | 2015-05-09 01:07:23 -0400 | [diff] [blame] | 23 | from collections.abc import Hashable, Iterable, Iterator, Generator |
Raymond Hettinger | 57d1a88 | 2011-02-23 00:46:28 +0000 | [diff] [blame] | 24 | from collections.abc import Sized, Container, Callable |
| 25 | from collections.abc import Set, MutableSet |
| 26 | from collections.abc import Mapping, MutableMapping, KeysView, ItemsView |
| 27 | from collections.abc import Sequence, MutableSequence |
| 28 | from collections.abc import ByteString |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 29 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 30 | |
Raymond Hettinger | 573b44c | 2015-05-22 16:56:32 -0700 | [diff] [blame] | 31 | class TestUserObjects(unittest.TestCase): |
| 32 | def _superset_test(self, a, b): |
| 33 | self.assertGreaterEqual( |
| 34 | set(dir(a)), |
| 35 | set(dir(b)), |
| 36 | '{a} should have all the methods of {b}'.format( |
| 37 | a=a.__name__, |
| 38 | b=b.__name__, |
| 39 | ), |
| 40 | ) |
| 41 | def test_str_protocol(self): |
| 42 | self._superset_test(UserString, str) |
| 43 | |
| 44 | def test_list_protocol(self): |
| 45 | self._superset_test(UserList, list) |
| 46 | |
| 47 | def test_dict_protocol(self): |
| 48 | self._superset_test(UserDict, dict) |
| 49 | |
| 50 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 51 | ################################################################################ |
Raymond Hettinger | 9fe1ccf | 2011-02-26 01:02:51 +0000 | [diff] [blame] | 52 | ### ChainMap (helper class for configparser and the string module) |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 53 | ################################################################################ |
| 54 | |
| 55 | class TestChainMap(unittest.TestCase): |
| 56 | |
| 57 | def test_basics(self): |
| 58 | c = ChainMap() |
| 59 | c['a'] = 1 |
| 60 | c['b'] = 2 |
| 61 | d = c.new_child() |
| 62 | d['b'] = 20 |
| 63 | d['c'] = 30 |
| 64 | self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state |
| 65 | self.assertEqual(d.items(), dict(a=1, b=20, c=30).items()) # check items/iter/getitem |
| 66 | self.assertEqual(len(d), 3) # check len |
| 67 | for key in 'abc': # check contains |
| 68 | self.assertIn(key, d) |
| 69 | for k, v in dict(a=1, b=20, c=30, z=100).items(): # check get |
| 70 | self.assertEqual(d.get(k, 100), v) |
| 71 | |
| 72 | del d['b'] # unmask a value |
| 73 | self.assertEqual(d.maps, [{'c':30}, {'a':1, 'b':2}]) # check internal state |
| 74 | self.assertEqual(d.items(), dict(a=1, b=2, c=30).items()) # check items/iter/getitem |
| 75 | self.assertEqual(len(d), 3) # check len |
| 76 | for key in 'abc': # check contains |
| 77 | self.assertIn(key, d) |
| 78 | for k, v in dict(a=1, b=2, c=30, z=100).items(): # check get |
| 79 | self.assertEqual(d.get(k, 100), v) |
| 80 | self.assertIn(repr(d), [ # check repr |
| 81 | type(d).__name__ + "({'c': 30}, {'a': 1, 'b': 2})", |
| 82 | type(d).__name__ + "({'c': 30}, {'b': 2, 'a': 1})" |
| 83 | ]) |
| 84 | |
| 85 | for e in d.copy(), copy.copy(d): # check shallow copies |
| 86 | self.assertEqual(d, e) |
| 87 | self.assertEqual(d.maps, e.maps) |
| 88 | self.assertIsNot(d, e) |
| 89 | self.assertIsNot(d.maps[0], e.maps[0]) |
| 90 | for m1, m2 in zip(d.maps[1:], e.maps[1:]): |
| 91 | self.assertIs(m1, m2) |
| 92 | |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 93 | # check deep copies |
| 94 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 95 | e = pickle.loads(pickle.dumps(d, proto)) |
| 96 | self.assertEqual(d, e) |
| 97 | self.assertEqual(d.maps, e.maps) |
| 98 | self.assertIsNot(d, e) |
| 99 | for m1, m2 in zip(d.maps, e.maps): |
| 100 | self.assertIsNot(m1, m2, e) |
| 101 | for e in [copy.deepcopy(d), |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 102 | eval(repr(d)) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 103 | ]: |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 104 | self.assertEqual(d, e) |
| 105 | self.assertEqual(d.maps, e.maps) |
| 106 | self.assertIsNot(d, e) |
| 107 | for m1, m2 in zip(d.maps, e.maps): |
| 108 | self.assertIsNot(m1, m2, e) |
| 109 | |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 110 | f = d.new_child() |
| 111 | f['b'] = 5 |
| 112 | self.assertEqual(f.maps, [{'b': 5}, {'c':30}, {'a':1, 'b':2}]) |
| 113 | self.assertEqual(f.parents.maps, [{'c':30}, {'a':1, 'b':2}]) # check parents |
| 114 | self.assertEqual(f['b'], 5) # find first in chain |
| 115 | self.assertEqual(f.parents['b'], 2) # look beyond maps[0] |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 116 | |
Martin Panter | eb99570 | 2016-07-28 01:11:04 +0000 | [diff] [blame] | 117 | def test_constructor(self): |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 118 | self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 119 | self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list |
| 120 | |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 121 | def test_bool(self): |
| 122 | self.assertFalse(ChainMap()) |
| 123 | self.assertFalse(ChainMap({}, {})) |
| 124 | self.assertTrue(ChainMap({1:2}, {})) |
| 125 | self.assertTrue(ChainMap({}, {1:2})) |
| 126 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 127 | def test_missing(self): |
| 128 | class DefaultChainMap(ChainMap): |
| 129 | def __missing__(self, key): |
| 130 | return 999 |
| 131 | d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30)) |
| 132 | for k, v in dict(a=1, b=2, c=30, d=999).items(): |
| 133 | self.assertEqual(d[k], v) # check __getitem__ w/missing |
| 134 | for k, v in dict(a=1, b=2, c=30, d=77).items(): |
| 135 | self.assertEqual(d.get(k, 77), v) # check get() w/ missing |
| 136 | for k, v in dict(a=True, b=True, c=True, d=False).items(): |
| 137 | self.assertEqual(k in d, v) # check __contains__ w/missing |
| 138 | self.assertEqual(d.pop('a', 1001), 1, d) |
| 139 | self.assertEqual(d.pop('a', 1002), 1002) # check pop() w/missing |
| 140 | self.assertEqual(d.popitem(), ('b', 2)) # check popitem() w/missing |
| 141 | with self.assertRaises(KeyError): |
| 142 | d.popitem() |
| 143 | |
| 144 | def test_dict_coercion(self): |
| 145 | d = ChainMap(dict(a=1, b=2), dict(b=20, c=30)) |
| 146 | self.assertEqual(dict(d), dict(a=1, b=2, c=30)) |
| 147 | self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30)) |
| 148 | |
Vinay Sajip | 1ba81ee | 2013-01-11 23:39:53 +0000 | [diff] [blame] | 149 | def test_new_child(self): |
| 150 | 'Tests for changes for issue #16613.' |
| 151 | c = ChainMap() |
| 152 | c['a'] = 1 |
| 153 | c['b'] = 2 |
| 154 | m = {'b':20, 'c': 30} |
| 155 | d = c.new_child(m) |
| 156 | self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state |
| 157 | self.assertIs(m, d.maps[0]) |
| 158 | |
| 159 | # Use a different map than a dict |
| 160 | class lowerdict(dict): |
| 161 | def __getitem__(self, key): |
| 162 | if isinstance(key, str): |
| 163 | key = key.lower() |
| 164 | return dict.__getitem__(self, key) |
| 165 | def __contains__(self, key): |
| 166 | if isinstance(key, str): |
| 167 | key = key.lower() |
| 168 | return dict.__contains__(self, key) |
| 169 | |
| 170 | c = ChainMap() |
| 171 | c['a'] = 1 |
| 172 | c['b'] = 2 |
| 173 | m = lowerdict(b=20, c=30) |
| 174 | d = c.new_child(m) |
| 175 | self.assertIs(m, d.maps[0]) |
| 176 | for key in 'abc': # check contains |
| 177 | self.assertIn(key, d) |
| 178 | for k, v in dict(a=1, B=20, C=30, z=100).items(): # check get |
| 179 | self.assertEqual(d.get(k, 100), v) |
| 180 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 181 | |
| 182 | ################################################################################ |
| 183 | ### Named Tuples |
| 184 | ################################################################################ |
| 185 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 186 | TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 187 | |
| 188 | class TestNamedTuple(unittest.TestCase): |
| 189 | |
| 190 | def test_factory(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 191 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 192 | self.assertEqual(Point.__name__, 'Point') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 193 | self.assertEqual(Point.__slots__, ()) |
| 194 | self.assertEqual(Point.__module__, __name__) |
| 195 | self.assertEqual(Point.__getitem__, tuple.__getitem__) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 196 | self.assertEqual(Point._fields, ('x', 'y')) |
Raymond Hettinger | 2ebea41 | 2011-03-23 12:52:23 -0700 | [diff] [blame] | 197 | self.assertIn('class Point(tuple)', Point._source) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 198 | |
| 199 | self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi') # type has non-alpha char |
| 200 | self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword |
| 201 | self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi') # type starts with digit |
| 202 | |
| 203 | self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi') # field with non-alpha char |
| 204 | self.assertRaises(ValueError, namedtuple, 'abc', 'abc class') # field has keyword |
| 205 | self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi') # field starts with digit |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 206 | self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi') # field with leading underscore |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 207 | self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi') # duplicate field |
| 208 | |
| 209 | namedtuple('Point0', 'x1 y2') # Verify that numbers are allowed in names |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 210 | namedtuple('_', 'a b c') # Test leading underscores in a typename |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 211 | |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 212 | nt = namedtuple('nt', 'the quick brown fox') # check unicode input |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 213 | self.assertNotIn("u'", repr(nt._fields)) |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 214 | nt = namedtuple('nt', ('the', 'quick')) # check unicode input |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 215 | self.assertNotIn("u'", repr(nt._fields)) |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 216 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 217 | self.assertRaises(TypeError, Point._make, [11]) # catch too few args |
| 218 | self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args |
| 219 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 220 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 221 | "Docstrings are omitted with -O2 and above") |
| 222 | def test_factory_doc_attr(self): |
| 223 | Point = namedtuple('Point', 'x y') |
| 224 | self.assertEqual(Point.__doc__, 'Point(x, y)') |
| 225 | |
Raymond Hettinger | eac503a | 2015-05-13 01:09:59 -0700 | [diff] [blame] | 226 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 227 | "Docstrings are omitted with -O2 and above") |
| 228 | def test_doc_writable(self): |
| 229 | Point = namedtuple('Point', 'x y') |
| 230 | self.assertEqual(Point.x.__doc__, 'Alias for field number 0') |
| 231 | Point.x.__doc__ = 'docstring for Point.x' |
| 232 | self.assertEqual(Point.x.__doc__, 'docstring for Point.x') |
| 233 | |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 234 | def test_name_fixer(self): |
| 235 | for spec, renamed in [ |
Raymond Hettinger | 5614524 | 2009-04-02 22:31:59 +0000 | [diff] [blame] | 236 | [('efg', 'g%hi'), ('efg', '_1')], # field with non-alpha char |
| 237 | [('abc', 'class'), ('abc', '_1')], # field has keyword |
| 238 | [('8efg', '9ghi'), ('_0', '_1')], # field starts with digit |
| 239 | [('abc', '_efg'), ('abc', '_1')], # field with leading underscore |
| 240 | [('abc', 'efg', 'efg', 'ghi'), ('abc', 'efg', '_2', 'ghi')], # duplicate field |
| 241 | [('abc', '', 'x'), ('abc', '_1', 'x')], # fieldname is a space |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 242 | ]: |
| 243 | self.assertEqual(namedtuple('NT', spec, rename=True)._fields, renamed) |
| 244 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 245 | def test_instance(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 246 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 247 | p = Point(11, 22) |
| 248 | self.assertEqual(p, Point(x=11, y=22)) |
| 249 | self.assertEqual(p, Point(11, y=22)) |
| 250 | self.assertEqual(p, Point(y=22, x=11)) |
| 251 | self.assertEqual(p, Point(*(11, 22))) |
| 252 | self.assertEqual(p, Point(**dict(x=11, y=22))) |
| 253 | self.assertRaises(TypeError, Point, 1) # too few args |
| 254 | self.assertRaises(TypeError, Point, 1, 2, 3) # too many args |
| 255 | self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument |
| 256 | self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument |
| 257 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 258 | self.assertNotIn('__weakref__', dir(p)) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 259 | self.assertEqual(p, Point._make([11, 22])) # test _make classmethod |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 260 | self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute |
| 261 | self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method |
Raymond Hettinger | 163e982 | 2013-05-18 00:05:20 -0700 | [diff] [blame] | 262 | self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 263 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 264 | try: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 265 | p._replace(x=1, error=2) |
| 266 | except ValueError: |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 267 | pass |
| 268 | else: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 269 | self._fail('Did not detect an incorrect fieldname') |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 270 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 271 | # verify that field string can have commas |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 272 | Point = namedtuple('Point', 'x, y') |
| 273 | p = Point(x=11, y=22) |
| 274 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
| 275 | |
| 276 | # verify that fieldspec can be a non-string sequence |
| 277 | Point = namedtuple('Point', ('x', 'y')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 278 | p = Point(x=11, y=22) |
| 279 | self.assertEqual(repr(p), 'Point(x=11, y=22)') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 280 | |
| 281 | def test_tupleness(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 282 | Point = namedtuple('Point', 'x y') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 283 | p = Point(11, 22) |
| 284 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 285 | self.assertIsInstance(p, tuple) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 286 | self.assertEqual(p, (11, 22)) # matches a real tuple |
| 287 | self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple |
| 288 | self.assertEqual(list(p), [11, 22]) # coercable to a list |
| 289 | self.assertEqual(max(p), 22) # iterable |
| 290 | self.assertEqual(max(*p), 22) # star-able |
| 291 | x, y = p |
| 292 | self.assertEqual(p, (x, y)) # unpacks like a tuple |
| 293 | self.assertEqual((p[0], p[1]), (11, 22)) # indexable like a tuple |
| 294 | self.assertRaises(IndexError, p.__getitem__, 3) |
| 295 | |
| 296 | self.assertEqual(p.x, x) |
| 297 | self.assertEqual(p.y, y) |
| 298 | self.assertRaises(AttributeError, eval, 'p.z', locals()) |
| 299 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 300 | def test_odd_sizes(self): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 301 | Zero = namedtuple('Zero', '') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 302 | self.assertEqual(Zero(), ()) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 303 | self.assertEqual(Zero._make([]), ()) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 304 | self.assertEqual(repr(Zero()), 'Zero()') |
| 305 | self.assertEqual(Zero()._asdict(), {}) |
| 306 | self.assertEqual(Zero()._fields, ()) |
| 307 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 308 | Dot = namedtuple('Dot', 'd') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 309 | self.assertEqual(Dot(1), (1,)) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 310 | self.assertEqual(Dot._make([1]), (1,)) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 311 | self.assertEqual(Dot(1).d, 1) |
| 312 | self.assertEqual(repr(Dot(1)), 'Dot(d=1)') |
| 313 | self.assertEqual(Dot(1)._asdict(), {'d':1}) |
| 314 | self.assertEqual(Dot(1)._replace(d=999), (999,)) |
| 315 | self.assertEqual(Dot(1)._fields, ('d',)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 316 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 317 | # n = 5000 |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 318 | n = 254 # SyntaxError: more than 255 arguments: |
Serhiy Storchaka | 33e7ea5 | 2015-11-25 17:09:01 +0200 | [diff] [blame] | 319 | names = list(set(''.join([choice(string.ascii_letters) |
Georg Brandl | b533e26 | 2008-05-25 18:19:30 +0000 | [diff] [blame] | 320 | for j in range(10)]) for i in range(n))) |
| 321 | n = len(names) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 322 | Big = namedtuple('Big', names) |
| 323 | b = Big(*range(n)) |
| 324 | self.assertEqual(b, tuple(range(n))) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 325 | self.assertEqual(Big._make(range(n)), tuple(range(n))) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 326 | for pos, name in enumerate(names): |
| 327 | self.assertEqual(getattr(b, name), pos) |
| 328 | repr(b) # make sure repr() doesn't blow-up |
| 329 | d = b._asdict() |
| 330 | d_expected = dict(zip(names, range(n))) |
| 331 | self.assertEqual(d, d_expected) |
| 332 | b2 = b._replace(**dict([(names[1], 999),(names[-5], 42)])) |
| 333 | b2_expected = list(range(n)) |
| 334 | b2_expected[1] = 999 |
| 335 | b2_expected[-5] = 42 |
| 336 | self.assertEqual(b2, tuple(b2_expected)) |
| 337 | self.assertEqual(b._fields, tuple(names)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 338 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 339 | def test_pickle(self): |
| 340 | p = TestNT(x=10, y=20, z=30) |
| 341 | for module in (pickle,): |
| 342 | loads = getattr(module, 'loads') |
| 343 | dumps = getattr(module, 'dumps') |
Eric V. Smith | 4d5d69d | 2014-02-05 10:33:14 -0500 | [diff] [blame] | 344 | for protocol in range(-1, module.HIGHEST_PROTOCOL + 1): |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 345 | q = loads(dumps(p, protocol)) |
| 346 | self.assertEqual(p, q) |
| 347 | self.assertEqual(p._fields, q._fields) |
Raymond Hettinger | b98dcc1 | 2013-05-03 02:24:15 -0700 | [diff] [blame] | 348 | self.assertNotIn(b'OrderedDict', dumps(p, protocol)) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 349 | |
| 350 | def test_copy(self): |
| 351 | p = TestNT(x=10, y=20, z=30) |
| 352 | for copier in copy.copy, copy.deepcopy: |
| 353 | q = copier(p) |
| 354 | self.assertEqual(p, q) |
| 355 | self.assertEqual(p._fields, q._fields) |
| 356 | |
Raymond Hettinger | 089ba7f | 2009-05-27 00:38:24 +0000 | [diff] [blame] | 357 | def test_name_conflicts(self): |
| 358 | # Some names like "self", "cls", "tuple", "itemgetter", and "property" |
| 359 | # failed when used as field names. Test to make sure these now work. |
| 360 | T = namedtuple('T', 'itemgetter property self cls tuple') |
| 361 | t = T(1, 2, 3, 4, 5) |
| 362 | self.assertEqual(t, (1,2,3,4,5)) |
| 363 | newt = t._replace(itemgetter=10, property=20, self=30, cls=40, tuple=50) |
| 364 | self.assertEqual(newt, (10,20,30,40,50)) |
| 365 | |
Raymond Hettinger | 499b2ee | 2009-05-27 01:53:46 +0000 | [diff] [blame] | 366 | # Broader test of all interesting names in a template |
| 367 | with support.captured_stdout() as template: |
| 368 | T = namedtuple('T', 'x', verbose=True) |
| 369 | words = set(re.findall('[A-Za-z]+', template.getvalue())) |
| 370 | words -= set(keyword.kwlist) |
| 371 | T = namedtuple('T', words) |
| 372 | # test __new__ |
| 373 | values = tuple(range(len(words))) |
| 374 | t = T(*values) |
| 375 | self.assertEqual(t, values) |
| 376 | t = T(**dict(zip(T._fields, values))) |
| 377 | self.assertEqual(t, values) |
| 378 | # test _make |
| 379 | t = T._make(values) |
| 380 | self.assertEqual(t, values) |
| 381 | # exercise __repr__ |
| 382 | repr(t) |
| 383 | # test _asdict |
| 384 | self.assertEqual(t._asdict(), dict(zip(T._fields, values))) |
| 385 | # test _replace |
| 386 | t = T._make(values) |
| 387 | newvalues = tuple(v*10 for v in values) |
| 388 | newt = t._replace(**dict(zip(T._fields, newvalues))) |
| 389 | self.assertEqual(newt, newvalues) |
| 390 | # test _fields |
| 391 | self.assertEqual(T._fields, tuple(words)) |
| 392 | # test __getnewargs__ |
| 393 | self.assertEqual(t.__getnewargs__(), values) |
| 394 | |
Raymond Hettinger | d331ce9 | 2010-08-08 01:13:42 +0000 | [diff] [blame] | 395 | def test_repr(self): |
| 396 | with support.captured_stdout() as template: |
| 397 | A = namedtuple('A', 'x', verbose=True) |
| 398 | self.assertEqual(repr(A(1)), 'A(x=1)') |
| 399 | # repr should show the name of the subclass |
| 400 | class B(A): |
| 401 | pass |
| 402 | self.assertEqual(repr(B(1)), 'B(x=1)') |
| 403 | |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 404 | def test_source(self): |
| 405 | # verify that _source can be run through exec() |
Raymond Hettinger | d4652fa | 2011-03-24 09:45:43 -0700 | [diff] [blame] | 406 | tmp = namedtuple('NTColor', 'red green blue') |
| 407 | globals().pop('NTColor', None) # remove artifacts from other tests |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 408 | exec(tmp._source, globals()) |
Raymond Hettinger | d4652fa | 2011-03-24 09:45:43 -0700 | [diff] [blame] | 409 | self.assertIn('NTColor', globals()) |
| 410 | c = NTColor(10, 20, 30) |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 411 | self.assertEqual((c.red, c.green, c.blue), (10, 20, 30)) |
Raymond Hettinger | d4652fa | 2011-03-24 09:45:43 -0700 | [diff] [blame] | 412 | self.assertEqual(NTColor._fields, ('red', 'green', 'blue')) |
| 413 | globals().pop('NTColor', None) # clean-up after this test |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 414 | |
Raymond Hettinger | d331ce9 | 2010-08-08 01:13:42 +0000 | [diff] [blame] | 415 | |
Raymond Hettinger | 7a3602e | 2015-08-30 09:13:48 -0700 | [diff] [blame] | 416 | def test_namedtuple_subclass_issue_24931(self): |
| 417 | class Point(namedtuple('_Point', ['x', 'y'])): |
| 418 | pass |
| 419 | |
| 420 | a = Point(3, 4) |
| 421 | self.assertEqual(a._asdict(), OrderedDict([('x', 3), ('y', 4)])) |
| 422 | |
| 423 | a.w = 5 |
| 424 | self.assertEqual(a.__dict__, {'w': 5}) |
| 425 | |
| 426 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 427 | ################################################################################ |
| 428 | ### Abstract Base Classes |
| 429 | ################################################################################ |
| 430 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 431 | class ABCTestCase(unittest.TestCase): |
| 432 | |
| 433 | def validate_abstract_methods(self, abc, *names): |
| 434 | methodstubs = dict.fromkeys(names, lambda s, *args: 0) |
| 435 | |
| 436 | # everything should work will all required methods are present |
| 437 | C = type('C', (abc,), methodstubs) |
| 438 | C() |
| 439 | |
| 440 | # instantiation should fail if a required method is missing |
| 441 | for name in names: |
| 442 | stubs = methodstubs.copy() |
| 443 | del stubs[name] |
| 444 | C = type('C', (abc,), stubs) |
| 445 | self.assertRaises(TypeError, C, name) |
| 446 | |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 447 | def validate_isinstance(self, abc, name): |
| 448 | stub = lambda s, *args: 0 |
| 449 | |
| 450 | C = type('C', (object,), {'__hash__': None}) |
| 451 | setattr(C, name, stub) |
| 452 | self.assertIsInstance(C(), abc) |
| 453 | self.assertTrue(issubclass(C, abc)) |
| 454 | |
| 455 | C = type('C', (object,), {'__hash__': None}) |
| 456 | self.assertNotIsInstance(C(), abc) |
| 457 | self.assertFalse(issubclass(C, abc)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 458 | |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 459 | def validate_comparison(self, instance): |
| 460 | ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] |
| 461 | operators = {} |
| 462 | for op in ops: |
| 463 | name = '__' + op + '__' |
| 464 | operators[name] = getattr(operator, name) |
| 465 | |
| 466 | class Other: |
| 467 | def __init__(self): |
| 468 | self.right_side = False |
| 469 | def __eq__(self, other): |
| 470 | self.right_side = True |
| 471 | return True |
| 472 | __lt__ = __eq__ |
| 473 | __gt__ = __eq__ |
| 474 | __le__ = __eq__ |
| 475 | __ge__ = __eq__ |
| 476 | __ne__ = __eq__ |
| 477 | __ror__ = __eq__ |
| 478 | __rand__ = __eq__ |
| 479 | __rxor__ = __eq__ |
| 480 | __rsub__ = __eq__ |
| 481 | |
| 482 | for name, op in operators.items(): |
| 483 | if not hasattr(instance, name): |
| 484 | continue |
| 485 | other = Other() |
| 486 | op(instance, other) |
| 487 | self.assertTrue(other.right_side,'Right side not called for %s.%s' |
| 488 | % (type(instance), name)) |
| 489 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 490 | class TestOneTrickPonyABCs(ABCTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 491 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 492 | def test_Awaitable(self): |
| 493 | def gen(): |
| 494 | yield |
| 495 | |
| 496 | @types.coroutine |
| 497 | def coro(): |
| 498 | yield |
| 499 | |
| 500 | async def new_coro(): |
| 501 | pass |
| 502 | |
| 503 | class Bar: |
| 504 | def __await__(self): |
| 505 | yield |
| 506 | |
| 507 | class MinimalCoro(Coroutine): |
| 508 | def send(self, value): |
| 509 | return value |
| 510 | def throw(self, typ, val=None, tb=None): |
| 511 | super().throw(typ, val, tb) |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 512 | def __await__(self): |
| 513 | yield |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 514 | |
| 515 | non_samples = [None, int(), gen(), object()] |
| 516 | for x in non_samples: |
| 517 | self.assertNotIsInstance(x, Awaitable) |
| 518 | self.assertFalse(issubclass(type(x), Awaitable), repr(type(x))) |
| 519 | |
| 520 | samples = [Bar(), MinimalCoro()] |
| 521 | for x in samples: |
| 522 | self.assertIsInstance(x, Awaitable) |
| 523 | self.assertTrue(issubclass(type(x), Awaitable)) |
| 524 | |
| 525 | c = coro() |
Yury Selivanov | fdbeb2b | 2015-07-03 13:11:35 -0400 | [diff] [blame] | 526 | # Iterable coroutines (generators with CO_ITERABLE_COROUTINE |
| 527 | # flag don't have '__await__' method, hence can't be instances |
| 528 | # of Awaitable. Use inspect.isawaitable to detect them. |
| 529 | self.assertNotIsInstance(c, Awaitable) |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 530 | |
| 531 | c = new_coro() |
| 532 | self.assertIsInstance(c, Awaitable) |
| 533 | c.close() # awoid RuntimeWarning that coro() was not awaited |
| 534 | |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 535 | class CoroLike: pass |
Yury Selivanov | aded55c | 2015-05-13 23:41:55 -0400 | [diff] [blame] | 536 | Coroutine.register(CoroLike) |
Yury Selivanov | 08e5300 | 2015-05-13 23:57:59 -0400 | [diff] [blame] | 537 | self.assertTrue(isinstance(CoroLike(), Awaitable)) |
| 538 | self.assertTrue(issubclass(CoroLike, Awaitable)) |
| 539 | CoroLike = None |
| 540 | support.gc_collect() # Kill CoroLike to clean-up ABCMeta cache |
Yury Selivanov | aded55c | 2015-05-13 23:41:55 -0400 | [diff] [blame] | 541 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 542 | def test_Coroutine(self): |
| 543 | def gen(): |
| 544 | yield |
| 545 | |
| 546 | @types.coroutine |
| 547 | def coro(): |
| 548 | yield |
| 549 | |
| 550 | async def new_coro(): |
| 551 | pass |
| 552 | |
| 553 | class Bar: |
| 554 | def __await__(self): |
| 555 | yield |
| 556 | |
| 557 | class MinimalCoro(Coroutine): |
| 558 | def send(self, value): |
| 559 | return value |
| 560 | def throw(self, typ, val=None, tb=None): |
| 561 | super().throw(typ, val, tb) |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 562 | def __await__(self): |
| 563 | yield |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 564 | |
| 565 | non_samples = [None, int(), gen(), object(), Bar()] |
| 566 | for x in non_samples: |
| 567 | self.assertNotIsInstance(x, Coroutine) |
| 568 | self.assertFalse(issubclass(type(x), Coroutine), repr(type(x))) |
| 569 | |
| 570 | samples = [MinimalCoro()] |
| 571 | for x in samples: |
| 572 | self.assertIsInstance(x, Awaitable) |
| 573 | self.assertTrue(issubclass(type(x), Awaitable)) |
| 574 | |
| 575 | c = coro() |
Yury Selivanov | fdbeb2b | 2015-07-03 13:11:35 -0400 | [diff] [blame] | 576 | # Iterable coroutines (generators with CO_ITERABLE_COROUTINE |
| 577 | # flag don't have '__await__' method, hence can't be instances |
| 578 | # of Coroutine. Use inspect.isawaitable to detect them. |
| 579 | self.assertNotIsInstance(c, Coroutine) |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 580 | |
| 581 | c = new_coro() |
| 582 | self.assertIsInstance(c, Coroutine) |
| 583 | c.close() # awoid RuntimeWarning that coro() was not awaited |
| 584 | |
Yury Selivanov | 56fc614 | 2015-05-29 09:01:29 -0400 | [diff] [blame] | 585 | class CoroLike: |
| 586 | def send(self, value): |
| 587 | pass |
| 588 | def throw(self, typ, val=None, tb=None): |
| 589 | pass |
| 590 | def close(self): |
| 591 | pass |
| 592 | def __await__(self): |
| 593 | pass |
| 594 | self.assertTrue(isinstance(CoroLike(), Coroutine)) |
| 595 | self.assertTrue(issubclass(CoroLike, Coroutine)) |
| 596 | |
| 597 | class CoroLike: |
| 598 | def send(self, value): |
| 599 | pass |
| 600 | def close(self): |
| 601 | pass |
| 602 | def __await__(self): |
| 603 | pass |
| 604 | self.assertFalse(isinstance(CoroLike(), Coroutine)) |
| 605 | self.assertFalse(issubclass(CoroLike, Coroutine)) |
| 606 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 607 | def test_Hashable(self): |
| 608 | # Check some non-hashables |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 609 | non_samples = [bytearray(), list(), set(), dict()] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 610 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 611 | self.assertNotIsInstance(x, Hashable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 612 | self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 613 | # Check some hashables |
| 614 | samples = [None, |
| 615 | int(), float(), complex(), |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 616 | str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 617 | tuple(), frozenset(), |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 618 | int, list, object, type, bytes() |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 619 | ] |
| 620 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 621 | self.assertIsInstance(x, Hashable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 622 | self.assertTrue(issubclass(type(x), Hashable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 623 | self.assertRaises(TypeError, Hashable) |
| 624 | # Check direct subclassing |
| 625 | class H(Hashable): |
| 626 | def __hash__(self): |
| 627 | return super().__hash__() |
| 628 | self.assertEqual(hash(H()), 0) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 629 | self.assertFalse(issubclass(int, H)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 630 | self.validate_abstract_methods(Hashable, '__hash__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 631 | self.validate_isinstance(Hashable, '__hash__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 632 | |
Yury Selivanov | e0104ae | 2015-05-14 12:19:16 -0400 | [diff] [blame] | 633 | def test_AsyncIterable(self): |
| 634 | class AI: |
| 635 | async def __aiter__(self): |
| 636 | return self |
| 637 | self.assertTrue(isinstance(AI(), AsyncIterable)) |
| 638 | self.assertTrue(issubclass(AI, AsyncIterable)) |
| 639 | # Check some non-iterables |
| 640 | non_samples = [None, object, []] |
| 641 | for x in non_samples: |
| 642 | self.assertNotIsInstance(x, AsyncIterable) |
| 643 | self.assertFalse(issubclass(type(x), AsyncIterable), repr(type(x))) |
| 644 | self.validate_abstract_methods(AsyncIterable, '__aiter__') |
| 645 | self.validate_isinstance(AsyncIterable, '__aiter__') |
| 646 | |
| 647 | def test_AsyncIterator(self): |
| 648 | class AI: |
| 649 | async def __aiter__(self): |
| 650 | return self |
| 651 | async def __anext__(self): |
| 652 | raise StopAsyncIteration |
| 653 | self.assertTrue(isinstance(AI(), AsyncIterator)) |
| 654 | self.assertTrue(issubclass(AI, AsyncIterator)) |
| 655 | non_samples = [None, object, []] |
| 656 | # Check some non-iterables |
| 657 | for x in non_samples: |
| 658 | self.assertNotIsInstance(x, AsyncIterator) |
| 659 | self.assertFalse(issubclass(type(x), AsyncIterator), repr(type(x))) |
| 660 | # Similarly to regular iterators (see issue 10565) |
| 661 | class AnextOnly: |
| 662 | async def __anext__(self): |
| 663 | raise StopAsyncIteration |
| 664 | self.assertNotIsInstance(AnextOnly(), AsyncIterator) |
| 665 | self.validate_abstract_methods(AsyncIterator, '__anext__', '__aiter__') |
| 666 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 667 | def test_Iterable(self): |
| 668 | # Check some non-iterables |
| 669 | non_samples = [None, 42, 3.14, 1j] |
| 670 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 671 | self.assertNotIsInstance(x, Iterable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 672 | self.assertFalse(issubclass(type(x), Iterable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 673 | # Check some iterables |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 674 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 675 | tuple(), list(), set(), frozenset(), dict(), |
| 676 | dict().keys(), dict().items(), dict().values(), |
| 677 | (lambda: (yield))(), |
| 678 | (x for x in []), |
| 679 | ] |
| 680 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 681 | self.assertIsInstance(x, Iterable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 682 | self.assertTrue(issubclass(type(x), Iterable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 683 | # Check direct subclassing |
| 684 | class I(Iterable): |
| 685 | def __iter__(self): |
| 686 | return super().__iter__() |
| 687 | self.assertEqual(list(I()), []) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 688 | self.assertFalse(issubclass(str, I)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 689 | self.validate_abstract_methods(Iterable, '__iter__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 690 | self.validate_isinstance(Iterable, '__iter__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 691 | |
| 692 | def test_Iterator(self): |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 693 | non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 694 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 695 | self.assertNotIsInstance(x, Iterator) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 696 | self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 697 | samples = [iter(bytes()), iter(str()), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 698 | iter(tuple()), iter(list()), iter(dict()), |
| 699 | iter(set()), iter(frozenset()), |
| 700 | iter(dict().keys()), iter(dict().items()), |
| 701 | iter(dict().values()), |
| 702 | (lambda: (yield))(), |
| 703 | (x for x in []), |
| 704 | ] |
| 705 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 706 | self.assertIsInstance(x, Iterator) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 707 | self.assertTrue(issubclass(type(x), Iterator), repr(type(x))) |
Raymond Hettinger | ead2222 | 2010-11-29 03:56:12 +0000 | [diff] [blame] | 708 | self.validate_abstract_methods(Iterator, '__next__', '__iter__') |
| 709 | |
| 710 | # Issue 10565 |
| 711 | class NextOnly: |
| 712 | def __next__(self): |
| 713 | yield 1 |
Raymond Hettinger | bb6c0aa | 2014-11-22 22:14:41 -0800 | [diff] [blame] | 714 | return |
Raymond Hettinger | ead2222 | 2010-11-29 03:56:12 +0000 | [diff] [blame] | 715 | self.assertNotIsInstance(NextOnly(), Iterator) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 716 | |
Raymond Hettinger | bd60e8d | 2015-05-09 01:07:23 -0400 | [diff] [blame] | 717 | def test_Generator(self): |
| 718 | class NonGen1: |
| 719 | def __iter__(self): return self |
| 720 | def __next__(self): return None |
| 721 | def close(self): pass |
| 722 | def throw(self, typ, val=None, tb=None): pass |
| 723 | |
| 724 | class NonGen2: |
| 725 | def __iter__(self): return self |
| 726 | def __next__(self): return None |
| 727 | def close(self): pass |
| 728 | def send(self, value): return value |
| 729 | |
| 730 | class NonGen3: |
| 731 | def close(self): pass |
| 732 | def send(self, value): return value |
| 733 | def throw(self, typ, val=None, tb=None): pass |
| 734 | |
| 735 | non_samples = [ |
| 736 | None, 42, 3.14, 1j, b"", "", (), [], {}, set(), |
| 737 | iter(()), iter([]), NonGen1(), NonGen2(), NonGen3()] |
| 738 | for x in non_samples: |
| 739 | self.assertNotIsInstance(x, Generator) |
| 740 | self.assertFalse(issubclass(type(x), Generator), repr(type(x))) |
| 741 | |
| 742 | class Gen: |
| 743 | def __iter__(self): return self |
| 744 | def __next__(self): return None |
| 745 | def close(self): pass |
| 746 | def send(self, value): return value |
| 747 | def throw(self, typ, val=None, tb=None): pass |
| 748 | |
| 749 | class MinimalGen(Generator): |
| 750 | def send(self, value): |
| 751 | return value |
| 752 | def throw(self, typ, val=None, tb=None): |
| 753 | super().throw(typ, val, tb) |
| 754 | |
| 755 | def gen(): |
| 756 | yield 1 |
| 757 | |
| 758 | samples = [gen(), (lambda: (yield))(), Gen(), MinimalGen()] |
| 759 | for x in samples: |
| 760 | self.assertIsInstance(x, Iterator) |
| 761 | self.assertIsInstance(x, Generator) |
| 762 | self.assertTrue(issubclass(type(x), Generator), repr(type(x))) |
| 763 | self.validate_abstract_methods(Generator, 'send', 'throw') |
| 764 | |
| 765 | # mixin tests |
| 766 | mgen = MinimalGen() |
| 767 | self.assertIs(mgen, iter(mgen)) |
| 768 | self.assertIs(mgen.send(None), next(mgen)) |
| 769 | self.assertEqual(2, mgen.send(2)) |
| 770 | self.assertIsNone(mgen.close()) |
| 771 | self.assertRaises(ValueError, mgen.throw, ValueError) |
| 772 | self.assertRaisesRegex(ValueError, "^huhu$", |
| 773 | mgen.throw, ValueError, ValueError("huhu")) |
| 774 | self.assertRaises(StopIteration, mgen.throw, StopIteration()) |
| 775 | |
| 776 | class FailOnClose(Generator): |
| 777 | def send(self, value): return value |
| 778 | def throw(self, *args): raise ValueError |
| 779 | |
| 780 | self.assertRaises(ValueError, FailOnClose().close) |
| 781 | |
| 782 | class IgnoreGeneratorExit(Generator): |
| 783 | def send(self, value): return value |
| 784 | def throw(self, *args): pass |
| 785 | |
| 786 | self.assertRaises(RuntimeError, IgnoreGeneratorExit().close) |
| 787 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 788 | def test_Sized(self): |
| 789 | non_samples = [None, 42, 3.14, 1j, |
| 790 | (lambda: (yield))(), |
| 791 | (x for x in []), |
| 792 | ] |
| 793 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 794 | self.assertNotIsInstance(x, Sized) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 795 | self.assertFalse(issubclass(type(x), Sized), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 796 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 797 | tuple(), list(), set(), frozenset(), dict(), |
| 798 | dict().keys(), dict().items(), dict().values(), |
| 799 | ] |
| 800 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 801 | self.assertIsInstance(x, Sized) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 802 | self.assertTrue(issubclass(type(x), Sized), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 803 | self.validate_abstract_methods(Sized, '__len__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 804 | self.validate_isinstance(Sized, '__len__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 805 | |
| 806 | def test_Container(self): |
| 807 | non_samples = [None, 42, 3.14, 1j, |
| 808 | (lambda: (yield))(), |
| 809 | (x for x in []), |
| 810 | ] |
| 811 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 812 | self.assertNotIsInstance(x, Container) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 813 | self.assertFalse(issubclass(type(x), Container), repr(type(x))) |
Guido van Rossum | 07d4e78 | 2007-07-03 16:59:47 +0000 | [diff] [blame] | 814 | samples = [bytes(), str(), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 815 | tuple(), list(), set(), frozenset(), dict(), |
| 816 | dict().keys(), dict().items(), |
| 817 | ] |
| 818 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 819 | self.assertIsInstance(x, Container) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 820 | self.assertTrue(issubclass(type(x), Container), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 821 | self.validate_abstract_methods(Container, '__contains__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 822 | self.validate_isinstance(Container, '__contains__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 823 | |
| 824 | def test_Callable(self): |
| 825 | non_samples = [None, 42, 3.14, 1j, |
| 826 | "", b"", (), [], {}, set(), |
| 827 | (lambda: (yield))(), |
| 828 | (x for x in []), |
| 829 | ] |
| 830 | for x in non_samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 831 | self.assertNotIsInstance(x, Callable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 832 | self.assertFalse(issubclass(type(x), Callable), repr(type(x))) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 833 | samples = [lambda: None, |
| 834 | type, int, object, |
| 835 | len, |
| 836 | list.append, [].append, |
| 837 | ] |
| 838 | for x in samples: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 839 | self.assertIsInstance(x, Callable) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 840 | self.assertTrue(issubclass(type(x), Callable), repr(type(x))) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 841 | self.validate_abstract_methods(Callable, '__call__') |
Florent Xicluna | ce153f6 | 2010-03-08 15:34:35 +0000 | [diff] [blame] | 842 | self.validate_isinstance(Callable, '__call__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 843 | |
| 844 | def test_direct_subclassing(self): |
| 845 | for B in Hashable, Iterable, Iterator, Sized, Container, Callable: |
| 846 | class C(B): |
| 847 | pass |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 848 | self.assertTrue(issubclass(C, B)) |
| 849 | self.assertFalse(issubclass(int, C)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 850 | |
| 851 | def test_registration(self): |
| 852 | for B in Hashable, Iterable, Iterator, Sized, Container, Callable: |
| 853 | class C: |
| 854 | __hash__ = None # Make sure it isn't hashable by default |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 855 | self.assertFalse(issubclass(C, B), B.__name__) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 856 | B.register(C) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 857 | self.assertTrue(issubclass(C, B)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 858 | |
Raymond Hettinger | 3f10a95 | 2009-04-01 19:05:50 +0000 | [diff] [blame] | 859 | class WithSet(MutableSet): |
| 860 | |
| 861 | def __init__(self, it=()): |
| 862 | self.data = set(it) |
| 863 | |
| 864 | def __len__(self): |
| 865 | return len(self.data) |
| 866 | |
| 867 | def __iter__(self): |
| 868 | return iter(self.data) |
| 869 | |
| 870 | def __contains__(self, item): |
| 871 | return item in self.data |
| 872 | |
| 873 | def add(self, item): |
| 874 | self.data.add(item) |
| 875 | |
| 876 | def discard(self, item): |
| 877 | self.data.discard(item) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 878 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 879 | class TestCollectionABCs(ABCTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 880 | |
| 881 | # XXX For now, we only test some virtual inheritance properties. |
| 882 | # We should also test the proper behavior of the collection ABCs |
| 883 | # as real base classes or mix-in classes. |
| 884 | |
| 885 | def test_Set(self): |
| 886 | for sample in [set, frozenset]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 887 | self.assertIsInstance(sample(), Set) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 888 | self.assertTrue(issubclass(sample, Set)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 889 | self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 890 | class MySet(Set): |
| 891 | def __contains__(self, x): |
| 892 | return False |
| 893 | def __len__(self): |
| 894 | return 0 |
| 895 | def __iter__(self): |
| 896 | return iter([]) |
| 897 | self.validate_comparison(MySet()) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 898 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 899 | def test_hash_Set(self): |
| 900 | class OneTwoThreeSet(Set): |
| 901 | def __init__(self): |
| 902 | self.contents = [1, 2, 3] |
| 903 | def __contains__(self, x): |
| 904 | return x in self.contents |
| 905 | def __len__(self): |
| 906 | return len(self.contents) |
| 907 | def __iter__(self): |
| 908 | return iter(self.contents) |
| 909 | def __hash__(self): |
| 910 | return self._hash() |
| 911 | a, b = OneTwoThreeSet(), OneTwoThreeSet() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 912 | self.assertTrue(hash(a) == hash(b)) |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 913 | |
Raymond Hettinger | 2d452ee | 2014-05-25 18:28:39 -0700 | [diff] [blame] | 914 | def test_isdisjoint_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, 2, 3)) |
| 925 | s2 = MySet((4, 5, 6)) |
| 926 | s3 = MySet((1, 5, 6)) |
| 927 | self.assertTrue(s1.isdisjoint(s2)) |
| 928 | self.assertFalse(s1.isdisjoint(s3)) |
| 929 | |
| 930 | def test_equality_Set(self): |
| 931 | class MySet(Set): |
| 932 | def __init__(self, itr): |
| 933 | self.contents = itr |
| 934 | def __contains__(self, x): |
| 935 | return x in self.contents |
| 936 | def __iter__(self): |
| 937 | return iter(self.contents) |
| 938 | def __len__(self): |
| 939 | return len([x for x in self.contents]) |
| 940 | s1 = MySet((1,)) |
| 941 | s2 = MySet((1, 2)) |
| 942 | s3 = MySet((3, 4)) |
| 943 | s4 = MySet((3, 4)) |
| 944 | self.assertTrue(s2 > s1) |
| 945 | self.assertTrue(s1 < s2) |
| 946 | self.assertFalse(s2 <= s1) |
| 947 | self.assertFalse(s2 <= s3) |
| 948 | self.assertFalse(s1 >= s2) |
| 949 | self.assertEqual(s3, s4) |
| 950 | self.assertNotEqual(s2, s3) |
| 951 | |
| 952 | def test_arithmetic_Set(self): |
| 953 | class MySet(Set): |
| 954 | def __init__(self, itr): |
| 955 | self.contents = itr |
| 956 | def __contains__(self, x): |
| 957 | return x in self.contents |
| 958 | def __iter__(self): |
| 959 | return iter(self.contents) |
| 960 | def __len__(self): |
| 961 | return len([x for x in self.contents]) |
| 962 | s1 = MySet((1, 2, 3)) |
| 963 | s2 = MySet((3, 4, 5)) |
| 964 | s3 = s1 & s2 |
| 965 | self.assertEqual(s3, MySet((3,))) |
| 966 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 967 | def test_MutableSet(self): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 968 | self.assertIsInstance(set(), MutableSet) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 969 | self.assertTrue(issubclass(set, MutableSet)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 970 | self.assertNotIsInstance(frozenset(), MutableSet) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 971 | self.assertFalse(issubclass(frozenset, MutableSet)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 972 | self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__', |
| 973 | 'add', 'discard') |
| 974 | |
Raymond Hettinger | 3f10a95 | 2009-04-01 19:05:50 +0000 | [diff] [blame] | 975 | def test_issue_5647(self): |
| 976 | # MutableSet.__iand__ mutated the set during iteration |
| 977 | s = WithSet('abcd') |
| 978 | s &= WithSet('cdef') # This used to fail |
| 979 | self.assertEqual(set(s), set('cd')) |
| 980 | |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 981 | def test_issue_4920(self): |
| 982 | # MutableSet.pop() method did not work |
Raymond Hettinger | 57d1a88 | 2011-02-23 00:46:28 +0000 | [diff] [blame] | 983 | class MySet(MutableSet): |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 984 | __slots__=['__s'] |
| 985 | def __init__(self,items=None): |
| 986 | if items is None: |
| 987 | items=[] |
| 988 | self.__s=set(items) |
| 989 | def __contains__(self,v): |
| 990 | return v in self.__s |
| 991 | def __iter__(self): |
| 992 | return iter(self.__s) |
| 993 | def __len__(self): |
| 994 | return len(self.__s) |
| 995 | def add(self,v): |
| 996 | result=v not in self.__s |
| 997 | self.__s.add(v) |
| 998 | return result |
| 999 | def discard(self,v): |
| 1000 | result=v in self.__s |
| 1001 | self.__s.discard(v) |
| 1002 | return result |
| 1003 | def __repr__(self): |
| 1004 | return "MySet(%s)" % repr(list(self)) |
| 1005 | s = MySet([5,43,2,1]) |
| 1006 | self.assertEqual(s.pop(), 1) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1007 | |
Daniel Stutzbach | 31da5b2 | 2010-08-24 20:49:57 +0000 | [diff] [blame] | 1008 | def test_issue8750(self): |
| 1009 | empty = WithSet() |
| 1010 | full = WithSet(range(10)) |
| 1011 | s = WithSet(full) |
| 1012 | s -= s |
| 1013 | self.assertEqual(s, empty) |
| 1014 | s = WithSet(full) |
| 1015 | s ^= s |
| 1016 | self.assertEqual(s, empty) |
| 1017 | s = WithSet(full) |
| 1018 | s &= s |
| 1019 | self.assertEqual(s, full) |
| 1020 | s |= s |
| 1021 | self.assertEqual(s, full) |
| 1022 | |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1023 | def test_issue16373(self): |
| 1024 | # Recursion error comparing comparable and noncomparable |
| 1025 | # Set instances |
| 1026 | class MyComparableSet(Set): |
| 1027 | def __contains__(self, x): |
| 1028 | return False |
| 1029 | def __len__(self): |
| 1030 | return 0 |
| 1031 | def __iter__(self): |
| 1032 | return iter([]) |
| 1033 | class MyNonComparableSet(Set): |
| 1034 | def __contains__(self, x): |
| 1035 | return False |
| 1036 | def __len__(self): |
| 1037 | return 0 |
| 1038 | def __iter__(self): |
| 1039 | return iter([]) |
| 1040 | def __le__(self, x): |
| 1041 | return NotImplemented |
| 1042 | def __lt__(self, x): |
| 1043 | return NotImplemented |
| 1044 | |
| 1045 | cs = MyComparableSet() |
| 1046 | ncs = MyNonComparableSet() |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1047 | self.assertFalse(ncs < cs) |
| 1048 | self.assertTrue(ncs <= cs) |
| 1049 | self.assertFalse(ncs > cs) |
| 1050 | self.assertTrue(ncs >= cs) |
| 1051 | |
| 1052 | def assertSameSet(self, s1, s2): |
| 1053 | # coerce both to a real set then check equality |
| 1054 | self.assertSetEqual(set(s1), set(s2)) |
| 1055 | |
| 1056 | def test_Set_interoperability_with_real_sets(self): |
| 1057 | # Issue: 8743 |
| 1058 | class ListSet(Set): |
| 1059 | def __init__(self, elements=()): |
| 1060 | self.data = [] |
| 1061 | for elem in elements: |
| 1062 | if elem not in self.data: |
| 1063 | self.data.append(elem) |
| 1064 | def __contains__(self, elem): |
| 1065 | return elem in self.data |
| 1066 | def __iter__(self): |
| 1067 | return iter(self.data) |
| 1068 | def __len__(self): |
| 1069 | return len(self.data) |
| 1070 | def __repr__(self): |
| 1071 | return 'Set({!r})'.format(self.data) |
| 1072 | |
| 1073 | r1 = set('abc') |
| 1074 | r2 = set('bcd') |
| 1075 | r3 = set('abcde') |
| 1076 | f1 = ListSet('abc') |
| 1077 | f2 = ListSet('bcd') |
| 1078 | f3 = ListSet('abcde') |
| 1079 | l1 = list('abccba') |
| 1080 | l2 = list('bcddcb') |
| 1081 | l3 = list('abcdeedcba') |
| 1082 | |
| 1083 | target = r1 & r2 |
| 1084 | self.assertSameSet(f1 & f2, target) |
| 1085 | self.assertSameSet(f1 & r2, target) |
| 1086 | self.assertSameSet(r2 & f1, target) |
| 1087 | self.assertSameSet(f1 & l2, target) |
| 1088 | |
| 1089 | target = r1 | r2 |
| 1090 | self.assertSameSet(f1 | f2, target) |
| 1091 | self.assertSameSet(f1 | r2, target) |
| 1092 | self.assertSameSet(r2 | f1, target) |
| 1093 | self.assertSameSet(f1 | l2, target) |
| 1094 | |
| 1095 | fwd_target = r1 - r2 |
| 1096 | rev_target = r2 - r1 |
| 1097 | self.assertSameSet(f1 - f2, fwd_target) |
| 1098 | self.assertSameSet(f2 - f1, rev_target) |
| 1099 | self.assertSameSet(f1 - r2, fwd_target) |
| 1100 | self.assertSameSet(f2 - r1, rev_target) |
| 1101 | self.assertSameSet(r1 - f2, fwd_target) |
| 1102 | self.assertSameSet(r2 - f1, rev_target) |
| 1103 | self.assertSameSet(f1 - l2, fwd_target) |
| 1104 | self.assertSameSet(f2 - l1, rev_target) |
| 1105 | |
| 1106 | target = r1 ^ r2 |
| 1107 | self.assertSameSet(f1 ^ f2, target) |
| 1108 | self.assertSameSet(f1 ^ r2, target) |
| 1109 | self.assertSameSet(r2 ^ f1, target) |
| 1110 | self.assertSameSet(f1 ^ l2, target) |
| 1111 | |
| 1112 | # Don't change the following to use assertLess or other |
| 1113 | # "more specific" unittest assertions. The current |
| 1114 | # assertTrue/assertFalse style makes the pattern of test |
| 1115 | # case combinations clear and allows us to know for sure |
| 1116 | # the exact operator being invoked. |
| 1117 | |
| 1118 | # proper subset |
| 1119 | self.assertTrue(f1 < f3) |
| 1120 | self.assertFalse(f1 < f1) |
| 1121 | self.assertFalse(f1 < f2) |
| 1122 | self.assertTrue(r1 < f3) |
| 1123 | self.assertFalse(r1 < f1) |
| 1124 | self.assertFalse(r1 < f2) |
| 1125 | self.assertTrue(r1 < r3) |
| 1126 | self.assertFalse(r1 < r1) |
| 1127 | self.assertFalse(r1 < r2) |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1128 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1129 | f1 < l3 |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1130 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1131 | f1 < l1 |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1132 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1133 | f1 < l2 |
| 1134 | |
| 1135 | # any subset |
| 1136 | self.assertTrue(f1 <= f3) |
| 1137 | self.assertTrue(f1 <= f1) |
| 1138 | self.assertFalse(f1 <= f2) |
| 1139 | self.assertTrue(r1 <= f3) |
| 1140 | self.assertTrue(r1 <= f1) |
| 1141 | self.assertFalse(r1 <= f2) |
| 1142 | self.assertTrue(r1 <= r3) |
| 1143 | self.assertTrue(r1 <= r1) |
| 1144 | self.assertFalse(r1 <= r2) |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1145 | with self.assertRaises(TypeError): |
Raymond Hettinger | dd5e53a | 2014-05-26 00:09:04 -0700 | [diff] [blame] | 1146 | f1 <= l3 |
| 1147 | with self.assertRaises(TypeError): |
| 1148 | f1 <= l1 |
| 1149 | with self.assertRaises(TypeError): |
| 1150 | f1 <= l2 |
| 1151 | |
| 1152 | # proper superset |
| 1153 | self.assertTrue(f3 > f1) |
| 1154 | self.assertFalse(f1 > f1) |
| 1155 | self.assertFalse(f2 > f1) |
| 1156 | self.assertTrue(r3 > r1) |
| 1157 | self.assertFalse(f1 > r1) |
| 1158 | self.assertFalse(f2 > r1) |
| 1159 | self.assertTrue(r3 > r1) |
| 1160 | self.assertFalse(r1 > r1) |
| 1161 | self.assertFalse(r2 > r1) |
| 1162 | with self.assertRaises(TypeError): |
| 1163 | f1 > l3 |
| 1164 | with self.assertRaises(TypeError): |
| 1165 | f1 > l1 |
| 1166 | with self.assertRaises(TypeError): |
| 1167 | f1 > l2 |
| 1168 | |
| 1169 | # any superset |
| 1170 | self.assertTrue(f3 >= f1) |
| 1171 | self.assertTrue(f1 >= f1) |
| 1172 | self.assertFalse(f2 >= f1) |
| 1173 | self.assertTrue(r3 >= r1) |
| 1174 | self.assertTrue(f1 >= r1) |
| 1175 | self.assertFalse(f2 >= r1) |
| 1176 | self.assertTrue(r3 >= r1) |
| 1177 | self.assertTrue(r1 >= r1) |
| 1178 | self.assertFalse(r2 >= r1) |
| 1179 | with self.assertRaises(TypeError): |
| 1180 | f1 >= l3 |
| 1181 | with self.assertRaises(TypeError): |
| 1182 | f1 >=l1 |
| 1183 | with self.assertRaises(TypeError): |
| 1184 | f1 >= l2 |
| 1185 | |
| 1186 | # equality |
| 1187 | self.assertTrue(f1 == f1) |
| 1188 | self.assertTrue(r1 == f1) |
| 1189 | self.assertTrue(f1 == r1) |
| 1190 | self.assertFalse(f1 == f3) |
| 1191 | self.assertFalse(r1 == f3) |
| 1192 | self.assertFalse(f1 == r3) |
| 1193 | self.assertFalse(f1 == l3) |
| 1194 | self.assertFalse(f1 == l1) |
| 1195 | self.assertFalse(f1 == l2) |
| 1196 | |
| 1197 | # inequality |
| 1198 | self.assertFalse(f1 != f1) |
| 1199 | self.assertFalse(r1 != f1) |
| 1200 | self.assertFalse(f1 != r1) |
| 1201 | self.assertTrue(f1 != f3) |
| 1202 | self.assertTrue(r1 != f3) |
| 1203 | self.assertTrue(f1 != r3) |
| 1204 | self.assertTrue(f1 != l3) |
| 1205 | self.assertTrue(f1 != l1) |
| 1206 | self.assertTrue(f1 != l2) |
Andrew Svetlov | bcac6ad | 2012-11-01 13:28:54 +0200 | [diff] [blame] | 1207 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1208 | def test_Mapping(self): |
| 1209 | for sample in [dict]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1210 | self.assertIsInstance(sample(), Mapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1211 | self.assertTrue(issubclass(sample, Mapping)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1212 | self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', |
| 1213 | '__getitem__') |
Raymond Hettinger | 57d1a88 | 2011-02-23 00:46:28 +0000 | [diff] [blame] | 1214 | class MyMapping(Mapping): |
Benjamin Peterson | 4ad6bd5 | 2010-05-21 20:55:22 +0000 | [diff] [blame] | 1215 | def __len__(self): |
| 1216 | return 0 |
| 1217 | def __getitem__(self, i): |
| 1218 | raise IndexError |
| 1219 | def __iter__(self): |
| 1220 | return iter(()) |
| 1221 | self.validate_comparison(MyMapping()) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1222 | |
| 1223 | def test_MutableMapping(self): |
| 1224 | for sample in [dict]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1225 | self.assertIsInstance(sample(), MutableMapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1226 | self.assertTrue(issubclass(sample, MutableMapping)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1227 | self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__', |
| 1228 | '__getitem__', '__setitem__', '__delitem__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1229 | |
Raymond Hettinger | 9117c75 | 2010-08-22 07:44:24 +0000 | [diff] [blame] | 1230 | def test_MutableMapping_subclass(self): |
| 1231 | # Test issue 9214 |
| 1232 | mymap = UserDict() |
| 1233 | mymap['red'] = 5 |
| 1234 | self.assertIsInstance(mymap.keys(), Set) |
| 1235 | self.assertIsInstance(mymap.keys(), KeysView) |
| 1236 | self.assertIsInstance(mymap.items(), Set) |
| 1237 | self.assertIsInstance(mymap.items(), ItemsView) |
| 1238 | |
| 1239 | mymap = UserDict() |
| 1240 | mymap['red'] = 5 |
| 1241 | z = mymap.keys() | {'orange'} |
| 1242 | self.assertIsInstance(z, set) |
| 1243 | list(z) |
| 1244 | mymap['blue'] = 7 # Shouldn't affect 'z' |
| 1245 | self.assertEqual(sorted(z), ['orange', 'red']) |
| 1246 | |
| 1247 | mymap = UserDict() |
| 1248 | mymap['red'] = 5 |
| 1249 | z = mymap.items() | {('orange', 3)} |
| 1250 | self.assertIsInstance(z, set) |
| 1251 | list(z) |
| 1252 | mymap['blue'] = 7 # Shouldn't affect 'z' |
| 1253 | self.assertEqual(sorted(z), [('orange', 3), ('red', 5)]) |
| 1254 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1255 | def test_Sequence(self): |
| 1256 | for sample in [tuple, list, bytes, str]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1257 | self.assertIsInstance(sample(), Sequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1258 | self.assertTrue(issubclass(sample, Sequence)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1259 | self.assertIsInstance(range(10), Sequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1260 | self.assertTrue(issubclass(range, Sequence)) |
Nick Coghlan | 45163cc | 2013-10-02 22:31:47 +1000 | [diff] [blame] | 1261 | self.assertIsInstance(memoryview(b""), Sequence) |
| 1262 | self.assertTrue(issubclass(memoryview, Sequence)) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1263 | self.assertTrue(issubclass(str, Sequence)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1264 | self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', |
| 1265 | '__getitem__') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1266 | |
Raymond Hettinger | ec219ba | 2015-05-22 19:29:22 -0700 | [diff] [blame] | 1267 | def test_Sequence_mixins(self): |
| 1268 | class SequenceSubclass(Sequence): |
| 1269 | def __init__(self, seq=()): |
| 1270 | self.seq = seq |
| 1271 | |
| 1272 | def __getitem__(self, index): |
| 1273 | return self.seq[index] |
| 1274 | |
| 1275 | def __len__(self): |
| 1276 | return len(self.seq) |
| 1277 | |
| 1278 | # Compare Sequence.index() behavior to (list|str).index() behavior |
| 1279 | def assert_index_same(seq1, seq2, index_args): |
| 1280 | try: |
| 1281 | expected = seq1.index(*index_args) |
| 1282 | except ValueError: |
| 1283 | with self.assertRaises(ValueError): |
| 1284 | seq2.index(*index_args) |
| 1285 | else: |
| 1286 | actual = seq2.index(*index_args) |
| 1287 | self.assertEqual( |
| 1288 | actual, expected, '%r.index%s' % (seq1, index_args)) |
| 1289 | |
| 1290 | for ty in list, str: |
| 1291 | nativeseq = ty('abracadabra') |
| 1292 | indexes = [-10000, -9999] + list(range(-3, len(nativeseq) + 3)) |
| 1293 | seqseq = SequenceSubclass(nativeseq) |
| 1294 | for letter in set(nativeseq) | {'z'}: |
| 1295 | assert_index_same(nativeseq, seqseq, (letter,)) |
| 1296 | for start in range(-3, len(nativeseq) + 3): |
| 1297 | assert_index_same(nativeseq, seqseq, (letter, start)) |
| 1298 | for stop in range(-3, len(nativeseq) + 3): |
| 1299 | assert_index_same( |
| 1300 | nativeseq, seqseq, (letter, start, stop)) |
| 1301 | |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1302 | def test_ByteString(self): |
| 1303 | for sample in [bytes, bytearray]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1304 | self.assertIsInstance(sample(), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1305 | self.assertTrue(issubclass(sample, ByteString)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1306 | for sample in [str, list, tuple]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1307 | self.assertNotIsInstance(sample(), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1308 | self.assertFalse(issubclass(sample, ByteString)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1309 | self.assertNotIsInstance(memoryview(b""), ByteString) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1310 | self.assertFalse(issubclass(memoryview, ByteString)) |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1311 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1312 | def test_MutableSequence(self): |
Guido van Rossum | d05eb00 | 2007-11-21 22:26:24 +0000 | [diff] [blame] | 1313 | for sample in [tuple, str, bytes]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1314 | self.assertNotIsInstance(sample(), MutableSequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1315 | self.assertFalse(issubclass(sample, MutableSequence)) |
Raymond Hettinger | 32ea165 | 2015-03-21 01:37:37 -0700 | [diff] [blame] | 1316 | for sample in [list, bytearray, deque]: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1317 | self.assertIsInstance(sample(), MutableSequence) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1318 | self.assertTrue(issubclass(sample, MutableSequence)) |
| 1319 | self.assertFalse(issubclass(str, MutableSequence)) |
Raymond Hettinger | ae65018 | 2009-01-28 23:33:59 +0000 | [diff] [blame] | 1320 | self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', |
| 1321 | '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1322 | |
Eli Bendersky | 0716a57 | 2011-03-04 10:38:14 +0000 | [diff] [blame] | 1323 | def test_MutableSequence_mixins(self): |
| 1324 | # Test the mixins of MutableSequence by creating a miminal concrete |
| 1325 | # class inherited from it. |
| 1326 | class MutableSequenceSubclass(MutableSequence): |
| 1327 | def __init__(self): |
| 1328 | self.lst = [] |
| 1329 | |
| 1330 | def __setitem__(self, index, value): |
| 1331 | self.lst[index] = value |
| 1332 | |
| 1333 | def __getitem__(self, index): |
| 1334 | return self.lst[index] |
| 1335 | |
| 1336 | def __len__(self): |
| 1337 | return len(self.lst) |
| 1338 | |
| 1339 | def __delitem__(self, index): |
| 1340 | del self.lst[index] |
| 1341 | |
| 1342 | def insert(self, index, value): |
| 1343 | self.lst.insert(index, value) |
| 1344 | |
| 1345 | mss = MutableSequenceSubclass() |
| 1346 | mss.append(0) |
| 1347 | mss.extend((1, 2, 3, 4)) |
| 1348 | self.assertEqual(len(mss), 5) |
| 1349 | self.assertEqual(mss[3], 3) |
| 1350 | mss.reverse() |
| 1351 | self.assertEqual(mss[3], 1) |
| 1352 | mss.pop() |
| 1353 | self.assertEqual(len(mss), 4) |
| 1354 | mss.remove(3) |
| 1355 | self.assertEqual(len(mss), 3) |
| 1356 | mss += (10, 20, 30) |
| 1357 | self.assertEqual(len(mss), 6) |
| 1358 | self.assertEqual(mss[-1], 30) |
| 1359 | mss.clear() |
| 1360 | self.assertEqual(len(mss), 0) |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 1361 | |
| 1362 | ################################################################################ |
| 1363 | ### Counter |
| 1364 | ################################################################################ |
| 1365 | |
Raymond Hettinger | cb1d96f | 2013-10-04 16:51:02 -0700 | [diff] [blame] | 1366 | class CounterSubclassWithSetItem(Counter): |
| 1367 | # Test a counter subclass that overrides __setitem__ |
| 1368 | def __init__(self, *args, **kwds): |
| 1369 | self.called = False |
| 1370 | Counter.__init__(self, *args, **kwds) |
| 1371 | def __setitem__(self, key, value): |
| 1372 | self.called = True |
| 1373 | Counter.__setitem__(self, key, value) |
| 1374 | |
| 1375 | class CounterSubclassWithGet(Counter): |
| 1376 | # Test a counter subclass that overrides get() |
| 1377 | def __init__(self, *args, **kwds): |
| 1378 | self.called = False |
| 1379 | Counter.__init__(self, *args, **kwds) |
| 1380 | def get(self, key, default): |
| 1381 | self.called = True |
| 1382 | return Counter.get(self, key, default) |
| 1383 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1384 | class TestCounter(unittest.TestCase): |
| 1385 | |
| 1386 | def test_basics(self): |
| 1387 | c = Counter('abcaba') |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1388 | self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) |
| 1389 | self.assertEqual(c, Counter(a=3, b=2, c=1)) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1390 | self.assertIsInstance(c, dict) |
| 1391 | self.assertIsInstance(c, Mapping) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1392 | self.assertTrue(issubclass(Counter, dict)) |
| 1393 | self.assertTrue(issubclass(Counter, Mapping)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1394 | self.assertEqual(len(c), 3) |
| 1395 | self.assertEqual(sum(c.values()), 6) |
| 1396 | self.assertEqual(sorted(c.values()), [1, 2, 3]) |
| 1397 | self.assertEqual(sorted(c.keys()), ['a', 'b', 'c']) |
| 1398 | self.assertEqual(sorted(c), ['a', 'b', 'c']) |
| 1399 | self.assertEqual(sorted(c.items()), |
| 1400 | [('a', 3), ('b', 2), ('c', 1)]) |
| 1401 | self.assertEqual(c['b'], 2) |
| 1402 | self.assertEqual(c['z'], 0) |
| 1403 | self.assertEqual(c.__contains__('c'), True) |
| 1404 | self.assertEqual(c.__contains__('z'), False) |
| 1405 | self.assertEqual(c.get('b', 10), 2) |
| 1406 | self.assertEqual(c.get('z', 10), 10) |
| 1407 | self.assertEqual(c, dict(a=3, b=2, c=1)) |
| 1408 | self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") |
| 1409 | self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)]) |
| 1410 | for i in range(5): |
| 1411 | self.assertEqual(c.most_common(i), |
| 1412 | [('a', 3), ('b', 2), ('c', 1)][:i]) |
| 1413 | self.assertEqual(''.join(sorted(c.elements())), 'aaabbc') |
| 1414 | c['a'] += 1 # increment an existing value |
| 1415 | c['b'] -= 2 # sub existing value to zero |
| 1416 | del c['c'] # remove an entry |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1417 | del c['c'] # make sure that del doesn't raise KeyError |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1418 | c['d'] -= 2 # sub from a missing value |
| 1419 | c['e'] = -5 # directly assign a missing value |
| 1420 | c['f'] += 4 # add to a missing value |
| 1421 | self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) |
| 1422 | self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') |
| 1423 | self.assertEqual(c.pop('f'), 4) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 1424 | self.assertNotIn('f', c) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1425 | for i in range(3): |
| 1426 | elem, cnt = c.popitem() |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 1427 | self.assertNotIn(elem, c) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1428 | c.clear() |
| 1429 | self.assertEqual(c, {}) |
| 1430 | self.assertEqual(repr(c), 'Counter()') |
| 1431 | self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc') |
| 1432 | self.assertRaises(TypeError, hash, c) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1433 | c.update(dict(a=5, b=3)) |
| 1434 | c.update(c=1) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1435 | c.update(Counter('a' * 50 + 'b' * 30)) |
| 1436 | c.update() # test case with no args |
| 1437 | c.__init__('a' * 500 + 'b' * 300) |
| 1438 | c.__init__('cdc') |
| 1439 | c.__init__() |
| 1440 | self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) |
| 1441 | self.assertEqual(c.setdefault('d', 5), 1) |
| 1442 | self.assertEqual(c['d'], 1) |
| 1443 | self.assertEqual(c.setdefault('e', 5), 5) |
| 1444 | self.assertEqual(c['e'], 5) |
| 1445 | |
Serhiy Storchaka | ae5cb21 | 2014-11-27 16:25:51 +0200 | [diff] [blame] | 1446 | def test_init(self): |
| 1447 | self.assertEqual(list(Counter(self=42).items()), [('self', 42)]) |
| 1448 | self.assertEqual(list(Counter(iterable=42).items()), [('iterable', 42)]) |
| 1449 | self.assertEqual(list(Counter(iterable=None).items()), [('iterable', None)]) |
| 1450 | self.assertRaises(TypeError, Counter, 42) |
| 1451 | self.assertRaises(TypeError, Counter, (), ()) |
| 1452 | self.assertRaises(TypeError, Counter.__init__) |
| 1453 | |
| 1454 | def test_update(self): |
| 1455 | c = Counter() |
| 1456 | c.update(self=42) |
| 1457 | self.assertEqual(list(c.items()), [('self', 42)]) |
| 1458 | c = Counter() |
| 1459 | c.update(iterable=42) |
| 1460 | self.assertEqual(list(c.items()), [('iterable', 42)]) |
| 1461 | c = Counter() |
| 1462 | c.update(iterable=None) |
| 1463 | self.assertEqual(list(c.items()), [('iterable', None)]) |
| 1464 | self.assertRaises(TypeError, Counter().update, 42) |
| 1465 | self.assertRaises(TypeError, Counter().update, {}, {}) |
| 1466 | self.assertRaises(TypeError, Counter.update) |
| 1467 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1468 | def test_copying(self): |
| 1469 | # Check that counters are copyable, deepcopyable, picklable, and |
| 1470 | #have a repr/eval round-trip |
| 1471 | words = Counter('which witch had which witches wrist watch'.split()) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1472 | def check(dup): |
| 1473 | msg = "\ncopy: %s\nwords: %s" % (dup, words) |
| 1474 | self.assertIsNot(dup, words, msg) |
| 1475 | self.assertEqual(dup, words) |
| 1476 | check(words.copy()) |
| 1477 | check(copy.copy(words)) |
| 1478 | check(copy.deepcopy(words)) |
| 1479 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1480 | with self.subTest(proto=proto): |
| 1481 | check(pickle.loads(pickle.dumps(words, proto))) |
| 1482 | check(eval(repr(words))) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1483 | update_test = Counter() |
| 1484 | update_test.update(words) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 1485 | check(update_test) |
| 1486 | check(Counter(words)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1487 | |
Raymond Hettinger | 1c746c2 | 2011-04-15 13:16:46 -0700 | [diff] [blame] | 1488 | def test_copy_subclass(self): |
| 1489 | class MyCounter(Counter): |
| 1490 | pass |
| 1491 | c = MyCounter('slartibartfast') |
| 1492 | d = c.copy() |
| 1493 | self.assertEqual(d, c) |
| 1494 | self.assertEqual(len(d), len(c)) |
| 1495 | self.assertEqual(type(d), type(c)) |
| 1496 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1497 | def test_conversions(self): |
| 1498 | # Convert to: set, list, dict |
| 1499 | s = 'she sells sea shells by the sea shore' |
| 1500 | self.assertEqual(sorted(Counter(s).elements()), sorted(s)) |
| 1501 | self.assertEqual(sorted(Counter(s)), sorted(set(s))) |
| 1502 | self.assertEqual(dict(Counter(s)), dict(Counter(s).items())) |
| 1503 | self.assertEqual(set(Counter(s)), set(s)) |
| 1504 | |
Raymond Hettinger | 670eaec | 2009-01-21 23:14:07 +0000 | [diff] [blame] | 1505 | def test_invariant_for_the_in_operator(self): |
| 1506 | c = Counter(a=10, b=-2, c=0) |
| 1507 | for elem in c: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1508 | self.assertTrue(elem in c) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1509 | self.assertIn(elem, c) |
Raymond Hettinger | 670eaec | 2009-01-21 23:14:07 +0000 | [diff] [blame] | 1510 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1511 | def test_multiset_operations(self): |
| 1512 | # Verify that adding a zero counter will strip zeros and negatives |
| 1513 | c = Counter(a=10, b=-2, c=0) + Counter() |
| 1514 | self.assertEqual(dict(c), dict(a=10)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1515 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1516 | elements = 'abcd' |
| 1517 | for i in range(1000): |
| 1518 | # test random pairs of multisets |
| 1519 | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 1520 | p.update(e=1, f=-1, g=0) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1521 | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 1522 | q.update(h=1, i=-1, j=0) |
| 1523 | for counterop, numberop in [ |
| 1524 | (Counter.__add__, lambda x, y: max(0, x+y)), |
| 1525 | (Counter.__sub__, lambda x, y: max(0, x-y)), |
| 1526 | (Counter.__or__, lambda x, y: max(0,x,y)), |
| 1527 | (Counter.__and__, lambda x, y: max(0, min(x,y))), |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1528 | ]: |
| 1529 | result = counterop(p, q) |
| 1530 | for x in elements: |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 1531 | self.assertEqual(numberop(p[x], q[x]), result[x], |
| 1532 | (counterop, x, p, q)) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1533 | # verify that results exclude non-positive counts |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1534 | self.assertTrue(x>0 for x in result.values()) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 1535 | |
| 1536 | elements = 'abcdef' |
| 1537 | for i in range(100): |
| 1538 | # verify that random multisets with no repeats are exactly like sets |
| 1539 | p = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |
| 1540 | q = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |
| 1541 | for counterop, setop in [ |
| 1542 | (Counter.__sub__, set.__sub__), |
| 1543 | (Counter.__or__, set.__or__), |
| 1544 | (Counter.__and__, set.__and__), |
| 1545 | ]: |
| 1546 | counter_result = counterop(p, q) |
| 1547 | set_result = setop(set(p.elements()), set(q.elements())) |
| 1548 | self.assertEqual(counter_result, dict.fromkeys(set_result, 1)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1549 | |
Raymond Hettinger | becd568 | 2011-10-19 13:40:37 -0700 | [diff] [blame] | 1550 | def test_inplace_operations(self): |
| 1551 | elements = 'abcd' |
| 1552 | for i in range(1000): |
| 1553 | # test random pairs of multisets |
| 1554 | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
| 1555 | p.update(e=1, f=-1, g=0) |
| 1556 | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |
| 1557 | q.update(h=1, i=-1, j=0) |
| 1558 | for inplace_op, regular_op in [ |
| 1559 | (Counter.__iadd__, Counter.__add__), |
| 1560 | (Counter.__isub__, Counter.__sub__), |
| 1561 | (Counter.__ior__, Counter.__or__), |
| 1562 | (Counter.__iand__, Counter.__and__), |
| 1563 | ]: |
| 1564 | c = p.copy() |
| 1565 | c_id = id(c) |
| 1566 | regular_result = regular_op(c, q) |
| 1567 | inplace_result = inplace_op(c, q) |
| 1568 | self.assertEqual(inplace_result, regular_result) |
| 1569 | self.assertEqual(id(inplace_result), c_id) |
| 1570 | |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 1571 | def test_subtract(self): |
| 1572 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 1573 | c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50) |
| 1574 | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |
| 1575 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 1576 | c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)) |
| 1577 | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |
| 1578 | c = Counter('aaabbcd') |
| 1579 | c.subtract('aaaabbcce') |
| 1580 | 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] | 1581 | |
Serhiy Storchaka | ae5cb21 | 2014-11-27 16:25:51 +0200 | [diff] [blame] | 1582 | c = Counter() |
| 1583 | c.subtract(self=42) |
| 1584 | self.assertEqual(list(c.items()), [('self', -42)]) |
| 1585 | c = Counter() |
| 1586 | c.subtract(iterable=42) |
| 1587 | self.assertEqual(list(c.items()), [('iterable', -42)]) |
| 1588 | self.assertRaises(TypeError, Counter().subtract, 42) |
| 1589 | self.assertRaises(TypeError, Counter().subtract, {}, {}) |
| 1590 | self.assertRaises(TypeError, Counter.subtract) |
| 1591 | |
Raymond Hettinger | fcb393c | 2011-08-09 13:00:40 -0700 | [diff] [blame] | 1592 | def test_unary(self): |
| 1593 | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |
| 1594 | self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40)) |
| 1595 | self.assertEqual(dict(-c), dict(a=5)) |
| 1596 | |
Raymond Hettinger | 4e6bf41 | 2011-11-05 13:35:26 -0700 | [diff] [blame] | 1597 | def test_repr_nonsortable(self): |
| 1598 | c = Counter(a=2, b=None) |
| 1599 | r = repr(c) |
| 1600 | self.assertIn("'a': 2", r) |
| 1601 | self.assertIn("'b': None", r) |
Raymond Hettinger | 68fb89f | 2011-11-05 13:43:01 -0700 | [diff] [blame] | 1602 | |
Raymond Hettinger | 426e052 | 2011-01-03 02:12:02 +0000 | [diff] [blame] | 1603 | def test_helper_function(self): |
| 1604 | # two paths, one for real dicts and one for other mappings |
| 1605 | elems = list('abracadabra') |
| 1606 | |
| 1607 | d = dict() |
| 1608 | _count_elements(d, elems) |
| 1609 | self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) |
| 1610 | |
| 1611 | m = OrderedDict() |
| 1612 | _count_elements(m, elems) |
| 1613 | self.assertEqual(m, |
| 1614 | OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])) |
| 1615 | |
Raymond Hettinger | cb1d96f | 2013-10-04 16:51:02 -0700 | [diff] [blame] | 1616 | # test fidelity to the pure python version |
| 1617 | c = CounterSubclassWithSetItem('abracadabra') |
| 1618 | self.assertTrue(c.called) |
Raymond Hettinger | facd0a3 | 2013-10-05 17:14:51 -0700 | [diff] [blame] | 1619 | 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] | 1620 | c = CounterSubclassWithGet('abracadabra') |
| 1621 | self.assertTrue(c.called) |
Raymond Hettinger | facd0a3 | 2013-10-05 17:14:51 -0700 | [diff] [blame] | 1622 | 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] | 1623 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 1624 | |
| 1625 | ################################################################################ |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 1626 | ### Run tests |
| 1627 | ################################################################################ |
| 1628 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1629 | def test_main(verbose=None): |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 1630 | NamedTupleDocs = doctest.DocTestSuite(module=collections) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 1631 | test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 1632 | TestCollectionABCs, TestCounter, TestChainMap, |
Eric Snow | 47db717 | 2015-05-29 22:21:39 -0600 | [diff] [blame] | 1633 | TestUserObjects, |
| 1634 | ] |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1635 | support.run_unittest(*test_classes) |
| 1636 | support.run_doctest(collections, verbose) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1637 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1638 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1639 | if __name__ == "__main__": |
| 1640 | test_main(verbose=True) |