# Python code coverage for Lib/test/test_collections.py

# | count | content |
---|---|---|

1 | n/a | """Unit tests for collections.py.""" |

2 | n/a | |

3 | n/a | import collections |

4 | n/a | import copy |

5 | n/a | import doctest |

6 | n/a | import inspect |

7 | n/a | import keyword |

8 | n/a | import operator |

9 | n/a | import pickle |

10 | n/a | from random import choice, randrange |

11 | n/a | import re |

12 | n/a | import string |

13 | n/a | import sys |

14 | n/a | from test import support |

15 | n/a | import types |

16 | n/a | import unittest |

17 | n/a | |

18 | n/a | from collections import namedtuple, Counter, OrderedDict, _count_elements |

19 | n/a | from collections import UserDict, UserString, UserList |

20 | n/a | from collections import ChainMap |

21 | n/a | from collections import deque |

22 | n/a | from collections.abc import Awaitable, Coroutine |

23 | n/a | from collections.abc import AsyncIterator, AsyncIterable, AsyncGenerator |

24 | n/a | from collections.abc import Hashable, Iterable, Iterator, Generator, Reversible |

25 | n/a | from collections.abc import Sized, Container, Callable, Collection |

26 | n/a | from collections.abc import Set, MutableSet |

27 | n/a | from collections.abc import Mapping, MutableMapping, KeysView, ItemsView, ValuesView |

28 | n/a | from collections.abc import Sequence, MutableSequence |

29 | n/a | from collections.abc import ByteString |

30 | n/a | |

31 | n/a | |

32 | n/a | class TestUserObjects(unittest.TestCase): |

33 | n/a | def _superset_test(self, a, b): |

34 | n/a | self.assertGreaterEqual( |

35 | n/a | set(dir(a)), |

36 | n/a | set(dir(b)), |

37 | n/a | '{a} should have all the methods of {b}'.format( |

38 | n/a | a=a.__name__, |

39 | n/a | b=b.__name__, |

40 | n/a | ), |

41 | n/a | ) |

42 | n/a | def test_str_protocol(self): |

43 | n/a | self._superset_test(UserString, str) |

44 | n/a | |

45 | n/a | def test_list_protocol(self): |

46 | n/a | self._superset_test(UserList, list) |

47 | n/a | |

48 | n/a | def test_dict_protocol(self): |

49 | n/a | self._superset_test(UserDict, dict) |

50 | n/a | |

51 | n/a | |

52 | n/a | ################################################################################ |

53 | n/a | ### ChainMap (helper class for configparser and the string module) |

54 | n/a | ################################################################################ |

55 | n/a | |

56 | n/a | class TestChainMap(unittest.TestCase): |

57 | n/a | |

58 | n/a | def test_basics(self): |

59 | n/a | c = ChainMap() |

60 | n/a | c['a'] = 1 |

61 | n/a | c['b'] = 2 |

62 | n/a | d = c.new_child() |

63 | n/a | d['b'] = 20 |

64 | n/a | d['c'] = 30 |

65 | n/a | self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state |

66 | n/a | self.assertEqual(d.items(), dict(a=1, b=20, c=30).items()) # check items/iter/getitem |

67 | n/a | self.assertEqual(len(d), 3) # check len |

68 | n/a | for key in 'abc': # check contains |

69 | n/a | self.assertIn(key, d) |

70 | n/a | for k, v in dict(a=1, b=20, c=30, z=100).items(): # check get |

71 | n/a | self.assertEqual(d.get(k, 100), v) |

72 | n/a | |

73 | n/a | del d['b'] # unmask a value |

74 | n/a | self.assertEqual(d.maps, [{'c':30}, {'a':1, 'b':2}]) # check internal state |

75 | n/a | self.assertEqual(d.items(), dict(a=1, b=2, c=30).items()) # check items/iter/getitem |

76 | n/a | self.assertEqual(len(d), 3) # check len |

77 | n/a | for key in 'abc': # check contains |

78 | n/a | self.assertIn(key, d) |

79 | n/a | for k, v in dict(a=1, b=2, c=30, z=100).items(): # check get |

80 | n/a | self.assertEqual(d.get(k, 100), v) |

81 | n/a | self.assertIn(repr(d), [ # check repr |

82 | n/a | type(d).__name__ + "({'c': 30}, {'a': 1, 'b': 2})", |

83 | n/a | type(d).__name__ + "({'c': 30}, {'b': 2, 'a': 1})" |

84 | n/a | ]) |

85 | n/a | |

86 | n/a | for e in d.copy(), copy.copy(d): # check shallow copies |

87 | n/a | self.assertEqual(d, e) |

88 | n/a | self.assertEqual(d.maps, e.maps) |

89 | n/a | self.assertIsNot(d, e) |

90 | n/a | self.assertIsNot(d.maps[0], e.maps[0]) |

91 | n/a | for m1, m2 in zip(d.maps[1:], e.maps[1:]): |

92 | n/a | self.assertIs(m1, m2) |

93 | n/a | |

94 | n/a | # check deep copies |

95 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |

96 | n/a | e = pickle.loads(pickle.dumps(d, proto)) |

97 | n/a | self.assertEqual(d, e) |

98 | n/a | self.assertEqual(d.maps, e.maps) |

99 | n/a | self.assertIsNot(d, e) |

100 | n/a | for m1, m2 in zip(d.maps, e.maps): |

101 | n/a | self.assertIsNot(m1, m2, e) |

102 | n/a | for e in [copy.deepcopy(d), |

103 | n/a | eval(repr(d)) |

104 | n/a | ]: |

105 | n/a | self.assertEqual(d, e) |

106 | n/a | self.assertEqual(d.maps, e.maps) |

107 | n/a | self.assertIsNot(d, e) |

108 | n/a | for m1, m2 in zip(d.maps, e.maps): |

109 | n/a | self.assertIsNot(m1, m2, e) |

110 | n/a | |

111 | n/a | f = d.new_child() |

112 | n/a | f['b'] = 5 |

113 | n/a | self.assertEqual(f.maps, [{'b': 5}, {'c':30}, {'a':1, 'b':2}]) |

114 | n/a | self.assertEqual(f.parents.maps, [{'c':30}, {'a':1, 'b':2}]) # check parents |

115 | n/a | self.assertEqual(f['b'], 5) # find first in chain |

116 | n/a | self.assertEqual(f.parents['b'], 2) # look beyond maps[0] |

117 | n/a | |

118 | n/a | def test_constructor(self): |

119 | n/a | self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict |

120 | n/a | self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list |

121 | n/a | |

122 | n/a | def test_bool(self): |

123 | n/a | self.assertFalse(ChainMap()) |

124 | n/a | self.assertFalse(ChainMap({}, {})) |

125 | n/a | self.assertTrue(ChainMap({1:2}, {})) |

126 | n/a | self.assertTrue(ChainMap({}, {1:2})) |

127 | n/a | |

128 | n/a | def test_missing(self): |

129 | n/a | class DefaultChainMap(ChainMap): |

130 | n/a | def __missing__(self, key): |

131 | n/a | return 999 |

132 | n/a | d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30)) |

133 | n/a | for k, v in dict(a=1, b=2, c=30, d=999).items(): |

134 | n/a | self.assertEqual(d[k], v) # check __getitem__ w/missing |

135 | n/a | for k, v in dict(a=1, b=2, c=30, d=77).items(): |

136 | n/a | self.assertEqual(d.get(k, 77), v) # check get() w/ missing |

137 | n/a | for k, v in dict(a=True, b=True, c=True, d=False).items(): |

138 | n/a | self.assertEqual(k in d, v) # check __contains__ w/missing |

139 | n/a | self.assertEqual(d.pop('a', 1001), 1, d) |

140 | n/a | self.assertEqual(d.pop('a', 1002), 1002) # check pop() w/missing |

141 | n/a | self.assertEqual(d.popitem(), ('b', 2)) # check popitem() w/missing |

142 | n/a | with self.assertRaises(KeyError): |

143 | n/a | d.popitem() |

144 | n/a | |

145 | n/a | def test_dict_coercion(self): |

146 | n/a | d = ChainMap(dict(a=1, b=2), dict(b=20, c=30)) |

147 | n/a | self.assertEqual(dict(d), dict(a=1, b=2, c=30)) |

148 | n/a | self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30)) |

149 | n/a | |

150 | n/a | def test_new_child(self): |

151 | n/a | 'Tests for changes for issue #16613.' |

152 | n/a | c = ChainMap() |

153 | n/a | c['a'] = 1 |

154 | n/a | c['b'] = 2 |

155 | n/a | m = {'b':20, 'c': 30} |

156 | n/a | d = c.new_child(m) |

157 | n/a | self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state |

158 | n/a | self.assertIs(m, d.maps[0]) |

159 | n/a | |

160 | n/a | # Use a different map than a dict |

161 | n/a | class lowerdict(dict): |

162 | n/a | def __getitem__(self, key): |

163 | n/a | if isinstance(key, str): |

164 | n/a | key = key.lower() |

165 | n/a | return dict.__getitem__(self, key) |

166 | n/a | def __contains__(self, key): |

167 | n/a | if isinstance(key, str): |

168 | n/a | key = key.lower() |

169 | n/a | return dict.__contains__(self, key) |

170 | n/a | |

171 | n/a | c = ChainMap() |

172 | n/a | c['a'] = 1 |

173 | n/a | c['b'] = 2 |

174 | n/a | m = lowerdict(b=20, c=30) |

175 | n/a | d = c.new_child(m) |

176 | n/a | self.assertIs(m, d.maps[0]) |

177 | n/a | for key in 'abc': # check contains |

178 | n/a | self.assertIn(key, d) |

179 | n/a | for k, v in dict(a=1, B=20, C=30, z=100).items(): # check get |

180 | n/a | self.assertEqual(d.get(k, 100), v) |

181 | n/a | |

182 | n/a | |

183 | n/a | ################################################################################ |

184 | n/a | ### Named Tuples |

185 | n/a | ################################################################################ |

186 | n/a | |

187 | n/a | TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests |

188 | n/a | |

189 | n/a | class TestNamedTuple(unittest.TestCase): |

190 | n/a | |

191 | n/a | def test_factory(self): |

192 | n/a | Point = namedtuple('Point', 'x y') |

193 | n/a | self.assertEqual(Point.__name__, 'Point') |

194 | n/a | self.assertEqual(Point.__slots__, ()) |

195 | n/a | self.assertEqual(Point.__module__, __name__) |

196 | n/a | self.assertEqual(Point.__getitem__, tuple.__getitem__) |

197 | n/a | self.assertEqual(Point._fields, ('x', 'y')) |

198 | n/a | self.assertIn('class Point(tuple)', Point._source) |

199 | n/a | |

200 | n/a | self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi') # type has non-alpha char |

201 | n/a | self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword |

202 | n/a | self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi') # type starts with digit |

203 | n/a | |

204 | n/a | self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi') # field with non-alpha char |

205 | n/a | self.assertRaises(ValueError, namedtuple, 'abc', 'abc class') # field has keyword |

206 | n/a | self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi') # field starts with digit |

207 | n/a | self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi') # field with leading underscore |

208 | n/a | self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi') # duplicate field |

209 | n/a | |

210 | n/a | namedtuple('Point0', 'x1 y2') # Verify that numbers are allowed in names |

211 | n/a | namedtuple('_', 'a b c') # Test leading underscores in a typename |

212 | n/a | |

213 | n/a | nt = namedtuple('nt', 'the quick brown fox') # check unicode input |

214 | n/a | self.assertNotIn("u'", repr(nt._fields)) |

215 | n/a | nt = namedtuple('nt', ('the', 'quick')) # check unicode input |

216 | n/a | self.assertNotIn("u'", repr(nt._fields)) |

217 | n/a | |

218 | n/a | self.assertRaises(TypeError, Point._make, [11]) # catch too few args |

219 | n/a | self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args |

220 | n/a | |

221 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |

222 | n/a | "Docstrings are omitted with -O2 and above") |

223 | n/a | def test_factory_doc_attr(self): |

224 | n/a | Point = namedtuple('Point', 'x y') |

225 | n/a | self.assertEqual(Point.__doc__, 'Point(x, y)') |

226 | n/a | |

227 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |

228 | n/a | "Docstrings are omitted with -O2 and above") |

229 | n/a | def test_doc_writable(self): |

230 | n/a | Point = namedtuple('Point', 'x y') |

231 | n/a | self.assertEqual(Point.x.__doc__, 'Alias for field number 0') |

232 | n/a | Point.x.__doc__ = 'docstring for Point.x' |

233 | n/a | self.assertEqual(Point.x.__doc__, 'docstring for Point.x') |

234 | n/a | |

235 | n/a | def test_name_fixer(self): |

236 | n/a | for spec, renamed in [ |

237 | n/a | [('efg', 'g%hi'), ('efg', '_1')], # field with non-alpha char |

238 | n/a | [('abc', 'class'), ('abc', '_1')], # field has keyword |

239 | n/a | [('8efg', '9ghi'), ('_0', '_1')], # field starts with digit |

240 | n/a | [('abc', '_efg'), ('abc', '_1')], # field with leading underscore |

241 | n/a | [('abc', 'efg', 'efg', 'ghi'), ('abc', 'efg', '_2', 'ghi')], # duplicate field |

242 | n/a | [('abc', '', 'x'), ('abc', '_1', 'x')], # fieldname is a space |

243 | n/a | ]: |

244 | n/a | self.assertEqual(namedtuple('NT', spec, rename=True)._fields, renamed) |

245 | n/a | |

246 | n/a | def test_module_parameter(self): |

247 | n/a | NT = namedtuple('NT', ['x', 'y'], module=collections) |

248 | n/a | self.assertEqual(NT.__module__, collections) |

249 | n/a | |

250 | n/a | def test_instance(self): |

251 | n/a | Point = namedtuple('Point', 'x y') |

252 | n/a | p = Point(11, 22) |

253 | n/a | self.assertEqual(p, Point(x=11, y=22)) |

254 | n/a | self.assertEqual(p, Point(11, y=22)) |

255 | n/a | self.assertEqual(p, Point(y=22, x=11)) |

256 | n/a | self.assertEqual(p, Point(*(11, 22))) |

257 | n/a | self.assertEqual(p, Point(**dict(x=11, y=22))) |

258 | n/a | self.assertRaises(TypeError, Point, 1) # too few args |

259 | n/a | self.assertRaises(TypeError, Point, 1, 2, 3) # too many args |

260 | n/a | self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument |

261 | n/a | self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument |

262 | n/a | self.assertEqual(repr(p), 'Point(x=11, y=22)') |

263 | n/a | self.assertNotIn('__weakref__', dir(p)) |

264 | n/a | self.assertEqual(p, Point._make([11, 22])) # test _make classmethod |

265 | n/a | self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute |

266 | n/a | self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method |

267 | n/a | self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method |

268 | n/a | |

269 | n/a | try: |

270 | n/a | p._replace(x=1, error=2) |

271 | n/a | except ValueError: |

272 | n/a | pass |

273 | n/a | else: |

274 | n/a | self._fail('Did not detect an incorrect fieldname') |

275 | n/a | |

276 | n/a | # verify that field string can have commas |

277 | n/a | Point = namedtuple('Point', 'x, y') |

278 | n/a | p = Point(x=11, y=22) |

279 | n/a | self.assertEqual(repr(p), 'Point(x=11, y=22)') |

280 | n/a | |

281 | n/a | # verify that fieldspec can be a non-string sequence |

282 | n/a | Point = namedtuple('Point', ('x', 'y')) |

283 | n/a | p = Point(x=11, y=22) |

284 | n/a | self.assertEqual(repr(p), 'Point(x=11, y=22)') |

285 | n/a | |

286 | n/a | def test_tupleness(self): |

287 | n/a | Point = namedtuple('Point', 'x y') |

288 | n/a | p = Point(11, 22) |

289 | n/a | |

290 | n/a | self.assertIsInstance(p, tuple) |

291 | n/a | self.assertEqual(p, (11, 22)) # matches a real tuple |

292 | n/a | self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple |

293 | n/a | self.assertEqual(list(p), [11, 22]) # coercable to a list |

294 | n/a | self.assertEqual(max(p), 22) # iterable |

295 | n/a | self.assertEqual(max(*p), 22) # star-able |

296 | n/a | x, y = p |

297 | n/a | self.assertEqual(p, (x, y)) # unpacks like a tuple |

298 | n/a | self.assertEqual((p[0], p[1]), (11, 22)) # indexable like a tuple |

299 | n/a | self.assertRaises(IndexError, p.__getitem__, 3) |

300 | n/a | |

301 | n/a | self.assertEqual(p.x, x) |

302 | n/a | self.assertEqual(p.y, y) |

303 | n/a | self.assertRaises(AttributeError, eval, 'p.z', locals()) |

304 | n/a | |

305 | n/a | def test_odd_sizes(self): |

306 | n/a | Zero = namedtuple('Zero', '') |

307 | n/a | self.assertEqual(Zero(), ()) |

308 | n/a | self.assertEqual(Zero._make([]), ()) |

309 | n/a | self.assertEqual(repr(Zero()), 'Zero()') |

310 | n/a | self.assertEqual(Zero()._asdict(), {}) |

311 | n/a | self.assertEqual(Zero()._fields, ()) |

312 | n/a | |

313 | n/a | Dot = namedtuple('Dot', 'd') |

314 | n/a | self.assertEqual(Dot(1), (1,)) |

315 | n/a | self.assertEqual(Dot._make([1]), (1,)) |

316 | n/a | self.assertEqual(Dot(1).d, 1) |

317 | n/a | self.assertEqual(repr(Dot(1)), 'Dot(d=1)') |

318 | n/a | self.assertEqual(Dot(1)._asdict(), {'d':1}) |

319 | n/a | self.assertEqual(Dot(1)._replace(d=999), (999,)) |

320 | n/a | self.assertEqual(Dot(1)._fields, ('d',)) |

321 | n/a | |

322 | n/a | n = 5000 |

323 | n/a | names = list(set(''.join([choice(string.ascii_letters) |

324 | n/a | for j in range(10)]) for i in range(n))) |

325 | n/a | n = len(names) |

326 | n/a | Big = namedtuple('Big', names) |

327 | n/a | b = Big(*range(n)) |

328 | n/a | self.assertEqual(b, tuple(range(n))) |

329 | n/a | self.assertEqual(Big._make(range(n)), tuple(range(n))) |

330 | n/a | for pos, name in enumerate(names): |

331 | n/a | self.assertEqual(getattr(b, name), pos) |

332 | n/a | repr(b) # make sure repr() doesn't blow-up |

333 | n/a | d = b._asdict() |

334 | n/a | d_expected = dict(zip(names, range(n))) |

335 | n/a | self.assertEqual(d, d_expected) |

336 | n/a | b2 = b._replace(**dict([(names[1], 999),(names[-5], 42)])) |

337 | n/a | b2_expected = list(range(n)) |

338 | n/a | b2_expected[1] = 999 |

339 | n/a | b2_expected[-5] = 42 |

340 | n/a | self.assertEqual(b2, tuple(b2_expected)) |

341 | n/a | self.assertEqual(b._fields, tuple(names)) |

342 | n/a | |

343 | n/a | def test_pickle(self): |

344 | n/a | p = TestNT(x=10, y=20, z=30) |

345 | n/a | for module in (pickle,): |

346 | n/a | loads = getattr(module, 'loads') |

347 | n/a | dumps = getattr(module, 'dumps') |

348 | n/a | for protocol in range(-1, module.HIGHEST_PROTOCOL + 1): |

349 | n/a | q = loads(dumps(p, protocol)) |

350 | n/a | self.assertEqual(p, q) |

351 | n/a | self.assertEqual(p._fields, q._fields) |

352 | n/a | self.assertNotIn(b'OrderedDict', dumps(p, protocol)) |

353 | n/a | |

354 | n/a | def test_copy(self): |

355 | n/a | p = TestNT(x=10, y=20, z=30) |

356 | n/a | for copier in copy.copy, copy.deepcopy: |

357 | n/a | q = copier(p) |

358 | n/a | self.assertEqual(p, q) |

359 | n/a | self.assertEqual(p._fields, q._fields) |

360 | n/a | |

361 | n/a | def test_name_conflicts(self): |

362 | n/a | # Some names like "self", "cls", "tuple", "itemgetter", and "property" |

363 | n/a | # failed when used as field names. Test to make sure these now work. |

364 | n/a | T = namedtuple('T', 'itemgetter property self cls tuple') |

365 | n/a | t = T(1, 2, 3, 4, 5) |

366 | n/a | self.assertEqual(t, (1,2,3,4,5)) |

367 | n/a | newt = t._replace(itemgetter=10, property=20, self=30, cls=40, tuple=50) |

368 | n/a | self.assertEqual(newt, (10,20,30,40,50)) |

369 | n/a | |

370 | n/a | # Broader test of all interesting names in a template |

371 | n/a | with support.captured_stdout() as template: |

372 | n/a | T = namedtuple('T', 'x', verbose=True) |

373 | n/a | words = set(re.findall('[A-Za-z]+', template.getvalue())) |

374 | n/a | words -= set(keyword.kwlist) |

375 | n/a | T = namedtuple('T', words) |

376 | n/a | # test __new__ |

377 | n/a | values = tuple(range(len(words))) |

378 | n/a | t = T(*values) |

379 | n/a | self.assertEqual(t, values) |

380 | n/a | t = T(**dict(zip(T._fields, values))) |

381 | n/a | self.assertEqual(t, values) |

382 | n/a | # test _make |

383 | n/a | t = T._make(values) |

384 | n/a | self.assertEqual(t, values) |

385 | n/a | # exercise __repr__ |

386 | n/a | repr(t) |

387 | n/a | # test _asdict |

388 | n/a | self.assertEqual(t._asdict(), dict(zip(T._fields, values))) |

389 | n/a | # test _replace |

390 | n/a | t = T._make(values) |

391 | n/a | newvalues = tuple(v*10 for v in values) |

392 | n/a | newt = t._replace(**dict(zip(T._fields, newvalues))) |

393 | n/a | self.assertEqual(newt, newvalues) |

394 | n/a | # test _fields |

395 | n/a | self.assertEqual(T._fields, tuple(words)) |

396 | n/a | # test __getnewargs__ |

397 | n/a | self.assertEqual(t.__getnewargs__(), values) |

398 | n/a | |

399 | n/a | def test_repr(self): |

400 | n/a | with support.captured_stdout() as template: |

401 | n/a | A = namedtuple('A', 'x', verbose=True) |

402 | n/a | self.assertEqual(repr(A(1)), 'A(x=1)') |

403 | n/a | # repr should show the name of the subclass |

404 | n/a | class B(A): |

405 | n/a | pass |

406 | n/a | self.assertEqual(repr(B(1)), 'B(x=1)') |

407 | n/a | |

408 | n/a | def test_source(self): |

409 | n/a | # verify that _source can be run through exec() |

410 | n/a | tmp = namedtuple('NTColor', 'red green blue') |

411 | n/a | globals().pop('NTColor', None) # remove artifacts from other tests |

412 | n/a | exec(tmp._source, globals()) |

413 | n/a | self.assertIn('NTColor', globals()) |

414 | n/a | c = NTColor(10, 20, 30) |

415 | n/a | self.assertEqual((c.red, c.green, c.blue), (10, 20, 30)) |

416 | n/a | self.assertEqual(NTColor._fields, ('red', 'green', 'blue')) |

417 | n/a | globals().pop('NTColor', None) # clean-up after this test |

418 | n/a | |

419 | n/a | def test_keyword_only_arguments(self): |

420 | n/a | # See issue 25628 |

421 | n/a | with support.captured_stdout() as template: |

422 | n/a | NT = namedtuple('NT', ['x', 'y'], verbose=True) |

423 | n/a | self.assertIn('class NT', NT._source) |

424 | n/a | with self.assertRaises(TypeError): |

425 | n/a | NT = namedtuple('NT', ['x', 'y'], True) |

426 | n/a | |

427 | n/a | NT = namedtuple('NT', ['abc', 'def'], rename=True) |

428 | n/a | self.assertEqual(NT._fields, ('abc', '_1')) |

429 | n/a | with self.assertRaises(TypeError): |

430 | n/a | NT = namedtuple('NT', ['abc', 'def'], False, True) |

431 | n/a | |

432 | n/a | def test_namedtuple_subclass_issue_24931(self): |

433 | n/a | class Point(namedtuple('_Point', ['x', 'y'])): |

434 | n/a | pass |

435 | n/a | |

436 | n/a | a = Point(3, 4) |

437 | n/a | self.assertEqual(a._asdict(), OrderedDict([('x', 3), ('y', 4)])) |

438 | n/a | |

439 | n/a | a.w = 5 |

440 | n/a | self.assertEqual(a.__dict__, {'w': 5}) |

441 | n/a | |

442 | n/a | |

443 | n/a | ################################################################################ |

444 | n/a | ### Abstract Base Classes |

445 | n/a | ################################################################################ |

446 | n/a | |

447 | n/a | class ABCTestCase(unittest.TestCase): |

448 | n/a | |

449 | n/a | def validate_abstract_methods(self, abc, *names): |

450 | n/a | methodstubs = dict.fromkeys(names, lambda s, *args: 0) |

451 | n/a | |

452 | n/a | # everything should work will all required methods are present |

453 | n/a | C = type('C', (abc,), methodstubs) |

454 | n/a | C() |

455 | n/a | |

456 | n/a | # instantiation should fail if a required method is missing |

457 | n/a | for name in names: |

458 | n/a | stubs = methodstubs.copy() |

459 | n/a | del stubs[name] |

460 | n/a | C = type('C', (abc,), stubs) |

461 | n/a | self.assertRaises(TypeError, C, name) |

462 | n/a | |

463 | n/a | def validate_isinstance(self, abc, name): |

464 | n/a | stub = lambda s, *args: 0 |

465 | n/a | |

466 | n/a | C = type('C', (object,), {'__hash__': None}) |

467 | n/a | setattr(C, name, stub) |

468 | n/a | self.assertIsInstance(C(), abc) |

469 | n/a | self.assertTrue(issubclass(C, abc)) |

470 | n/a | |

471 | n/a | C = type('C', (object,), {'__hash__': None}) |

472 | n/a | self.assertNotIsInstance(C(), abc) |

473 | n/a | self.assertFalse(issubclass(C, abc)) |

474 | n/a | |

475 | n/a | def validate_comparison(self, instance): |

476 | n/a | ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] |

477 | n/a | operators = {} |

478 | n/a | for op in ops: |

479 | n/a | name = '__' + op + '__' |

480 | n/a | operators[name] = getattr(operator, name) |

481 | n/a | |

482 | n/a | class Other: |

483 | n/a | def __init__(self): |

484 | n/a | self.right_side = False |

485 | n/a | def __eq__(self, other): |

486 | n/a | self.right_side = True |

487 | n/a | return True |

488 | n/a | __lt__ = __eq__ |

489 | n/a | __gt__ = __eq__ |

490 | n/a | __le__ = __eq__ |

491 | n/a | __ge__ = __eq__ |

492 | n/a | __ne__ = __eq__ |

493 | n/a | __ror__ = __eq__ |

494 | n/a | __rand__ = __eq__ |

495 | n/a | __rxor__ = __eq__ |

496 | n/a | __rsub__ = __eq__ |

497 | n/a | |

498 | n/a | for name, op in operators.items(): |

499 | n/a | if not hasattr(instance, name): |

500 | n/a | continue |

501 | n/a | other = Other() |

502 | n/a | op(instance, other) |

503 | n/a | self.assertTrue(other.right_side,'Right side not called for %s.%s' |

504 | n/a | % (type(instance), name)) |

505 | n/a | |

506 | n/a | def _test_gen(): |

507 | n/a | yield |

508 | n/a | |

509 | n/a | class TestOneTrickPonyABCs(ABCTestCase): |

510 | n/a | |

511 | n/a | def test_Awaitable(self): |

512 | n/a | def gen(): |

513 | n/a | yield |

514 | n/a | |

515 | n/a | @types.coroutine |

516 | n/a | def coro(): |

517 | n/a | yield |

518 | n/a | |

519 | n/a | async def new_coro(): |

520 | n/a | pass |

521 | n/a | |

522 | n/a | class Bar: |

523 | n/a | def __await__(self): |

524 | n/a | yield |

525 | n/a | |

526 | n/a | class MinimalCoro(Coroutine): |

527 | n/a | def send(self, value): |

528 | n/a | return value |

529 | n/a | def throw(self, typ, val=None, tb=None): |

530 | n/a | super().throw(typ, val, tb) |

531 | n/a | def __await__(self): |

532 | n/a | yield |

533 | n/a | |

534 | n/a | non_samples = [None, int(), gen(), object()] |

535 | n/a | for x in non_samples: |

536 | n/a | self.assertNotIsInstance(x, Awaitable) |

537 | n/a | self.assertFalse(issubclass(type(x), Awaitable), repr(type(x))) |

538 | n/a | |

539 | n/a | samples = [Bar(), MinimalCoro()] |

540 | n/a | for x in samples: |

541 | n/a | self.assertIsInstance(x, Awaitable) |

542 | n/a | self.assertTrue(issubclass(type(x), Awaitable)) |

543 | n/a | |

544 | n/a | c = coro() |

545 | n/a | # Iterable coroutines (generators with CO_ITERABLE_COROUTINE |

546 | n/a | # flag don't have '__await__' method, hence can't be instances |

547 | n/a | # of Awaitable. Use inspect.isawaitable to detect them. |

548 | n/a | self.assertNotIsInstance(c, Awaitable) |

549 | n/a | |

550 | n/a | c = new_coro() |

551 | n/a | self.assertIsInstance(c, Awaitable) |

552 | n/a | c.close() # awoid RuntimeWarning that coro() was not awaited |

553 | n/a | |

554 | n/a | class CoroLike: pass |

555 | n/a | Coroutine.register(CoroLike) |

556 | n/a | self.assertTrue(isinstance(CoroLike(), Awaitable)) |

557 | n/a | self.assertTrue(issubclass(CoroLike, Awaitable)) |

558 | n/a | CoroLike = None |

559 | n/a | support.gc_collect() # Kill CoroLike to clean-up ABCMeta cache |

560 | n/a | |

561 | n/a | def test_Coroutine(self): |

562 | n/a | def gen(): |

563 | n/a | yield |

564 | n/a | |

565 | n/a | @types.coroutine |

566 | n/a | def coro(): |

567 | n/a | yield |

568 | n/a | |

569 | n/a | async def new_coro(): |

570 | n/a | pass |

571 | n/a | |

572 | n/a | class Bar: |

573 | n/a | def __await__(self): |

574 | n/a | yield |

575 | n/a | |

576 | n/a | class MinimalCoro(Coroutine): |

577 | n/a | def send(self, value): |

578 | n/a | return value |

579 | n/a | def throw(self, typ, val=None, tb=None): |

580 | n/a | super().throw(typ, val, tb) |

581 | n/a | def __await__(self): |

582 | n/a | yield |

583 | n/a | |

584 | n/a | non_samples = [None, int(), gen(), object(), Bar()] |

585 | n/a | for x in non_samples: |

586 | n/a | self.assertNotIsInstance(x, Coroutine) |

587 | n/a | self.assertFalse(issubclass(type(x), Coroutine), repr(type(x))) |

588 | n/a | |

589 | n/a | samples = [MinimalCoro()] |

590 | n/a | for x in samples: |

591 | n/a | self.assertIsInstance(x, Awaitable) |

592 | n/a | self.assertTrue(issubclass(type(x), Awaitable)) |

593 | n/a | |

594 | n/a | c = coro() |

595 | n/a | # Iterable coroutines (generators with CO_ITERABLE_COROUTINE |

596 | n/a | # flag don't have '__await__' method, hence can't be instances |

597 | n/a | # of Coroutine. Use inspect.isawaitable to detect them. |

598 | n/a | self.assertNotIsInstance(c, Coroutine) |

599 | n/a | |

600 | n/a | c = new_coro() |

601 | n/a | self.assertIsInstance(c, Coroutine) |

602 | n/a | c.close() # awoid RuntimeWarning that coro() was not awaited |

603 | n/a | |

604 | n/a | class CoroLike: |

605 | n/a | def send(self, value): |

606 | n/a | pass |

607 | n/a | def throw(self, typ, val=None, tb=None): |

608 | n/a | pass |

609 | n/a | def close(self): |

610 | n/a | pass |

611 | n/a | def __await__(self): |

612 | n/a | pass |

613 | n/a | self.assertTrue(isinstance(CoroLike(), Coroutine)) |

614 | n/a | self.assertTrue(issubclass(CoroLike, Coroutine)) |

615 | n/a | |

616 | n/a | class CoroLike: |

617 | n/a | def send(self, value): |

618 | n/a | pass |

619 | n/a | def close(self): |

620 | n/a | pass |

621 | n/a | def __await__(self): |

622 | n/a | pass |

623 | n/a | self.assertFalse(isinstance(CoroLike(), Coroutine)) |

624 | n/a | self.assertFalse(issubclass(CoroLike, Coroutine)) |

625 | n/a | |

626 | n/a | def test_Hashable(self): |

627 | n/a | # Check some non-hashables |

628 | n/a | non_samples = [bytearray(), list(), set(), dict()] |

629 | n/a | for x in non_samples: |

630 | n/a | self.assertNotIsInstance(x, Hashable) |

631 | n/a | self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) |

632 | n/a | # Check some hashables |

633 | n/a | samples = [None, |

634 | n/a | int(), float(), complex(), |

635 | n/a | str(), |

636 | n/a | tuple(), frozenset(), |

637 | n/a | int, list, object, type, bytes() |

638 | n/a | ] |

639 | n/a | for x in samples: |

640 | n/a | self.assertIsInstance(x, Hashable) |

641 | n/a | self.assertTrue(issubclass(type(x), Hashable), repr(type(x))) |

642 | n/a | self.assertRaises(TypeError, Hashable) |

643 | n/a | # Check direct subclassing |

644 | n/a | class H(Hashable): |

645 | n/a | def __hash__(self): |

646 | n/a | return super().__hash__() |

647 | n/a | self.assertEqual(hash(H()), 0) |

648 | n/a | self.assertFalse(issubclass(int, H)) |

649 | n/a | self.validate_abstract_methods(Hashable, '__hash__') |

650 | n/a | self.validate_isinstance(Hashable, '__hash__') |

651 | n/a | |

652 | n/a | def test_AsyncIterable(self): |

653 | n/a | class AI: |

654 | n/a | async def __aiter__(self): |

655 | n/a | return self |

656 | n/a | self.assertTrue(isinstance(AI(), AsyncIterable)) |

657 | n/a | self.assertTrue(issubclass(AI, AsyncIterable)) |

658 | n/a | # Check some non-iterables |

659 | n/a | non_samples = [None, object, []] |

660 | n/a | for x in non_samples: |

661 | n/a | self.assertNotIsInstance(x, AsyncIterable) |

662 | n/a | self.assertFalse(issubclass(type(x), AsyncIterable), repr(type(x))) |

663 | n/a | self.validate_abstract_methods(AsyncIterable, '__aiter__') |

664 | n/a | self.validate_isinstance(AsyncIterable, '__aiter__') |

665 | n/a | |

666 | n/a | def test_AsyncIterator(self): |

667 | n/a | class AI: |

668 | n/a | async def __aiter__(self): |

669 | n/a | return self |

670 | n/a | async def __anext__(self): |

671 | n/a | raise StopAsyncIteration |

672 | n/a | self.assertTrue(isinstance(AI(), AsyncIterator)) |

673 | n/a | self.assertTrue(issubclass(AI, AsyncIterator)) |

674 | n/a | non_samples = [None, object, []] |

675 | n/a | # Check some non-iterables |

676 | n/a | for x in non_samples: |

677 | n/a | self.assertNotIsInstance(x, AsyncIterator) |

678 | n/a | self.assertFalse(issubclass(type(x), AsyncIterator), repr(type(x))) |

679 | n/a | # Similarly to regular iterators (see issue 10565) |

680 | n/a | class AnextOnly: |

681 | n/a | async def __anext__(self): |

682 | n/a | raise StopAsyncIteration |

683 | n/a | self.assertNotIsInstance(AnextOnly(), AsyncIterator) |

684 | n/a | self.validate_abstract_methods(AsyncIterator, '__anext__', '__aiter__') |

685 | n/a | |

686 | n/a | def test_Iterable(self): |

687 | n/a | # Check some non-iterables |

688 | n/a | non_samples = [None, 42, 3.14, 1j] |

689 | n/a | for x in non_samples: |

690 | n/a | self.assertNotIsInstance(x, Iterable) |

691 | n/a | self.assertFalse(issubclass(type(x), Iterable), repr(type(x))) |

692 | n/a | # Check some iterables |

693 | n/a | samples = [bytes(), str(), |

694 | n/a | tuple(), list(), set(), frozenset(), dict(), |

695 | n/a | dict().keys(), dict().items(), dict().values(), |

696 | n/a | _test_gen(), |

697 | n/a | (x for x in []), |

698 | n/a | ] |

699 | n/a | for x in samples: |

700 | n/a | self.assertIsInstance(x, Iterable) |

701 | n/a | self.assertTrue(issubclass(type(x), Iterable), repr(type(x))) |

702 | n/a | # Check direct subclassing |

703 | n/a | class I(Iterable): |

704 | n/a | def __iter__(self): |

705 | n/a | return super().__iter__() |

706 | n/a | self.assertEqual(list(I()), []) |

707 | n/a | self.assertFalse(issubclass(str, I)) |

708 | n/a | self.validate_abstract_methods(Iterable, '__iter__') |

709 | n/a | self.validate_isinstance(Iterable, '__iter__') |

710 | n/a | # Check None blocking |

711 | n/a | class It: |

712 | n/a | def __iter__(self): return iter([]) |

713 | n/a | class ItBlocked(It): |

714 | n/a | __iter__ = None |

715 | n/a | self.assertTrue(issubclass(It, Iterable)) |

716 | n/a | self.assertTrue(isinstance(It(), Iterable)) |

717 | n/a | self.assertFalse(issubclass(ItBlocked, Iterable)) |

718 | n/a | self.assertFalse(isinstance(ItBlocked(), Iterable)) |

719 | n/a | |

720 | n/a | def test_Reversible(self): |

721 | n/a | # Check some non-reversibles |

722 | n/a | non_samples = [None, 42, 3.14, 1j, dict(), set(), frozenset()] |

723 | n/a | for x in non_samples: |

724 | n/a | self.assertNotIsInstance(x, Reversible) |

725 | n/a | self.assertFalse(issubclass(type(x), Reversible), repr(type(x))) |

726 | n/a | # Check some non-reversible iterables |

727 | n/a | non_reversibles = [dict().keys(), dict().items(), dict().values(), |

728 | n/a | Counter(), Counter().keys(), Counter().items(), |

729 | n/a | Counter().values(), _test_gen(), |

730 | n/a | (x for x in []), iter([]), reversed([])] |

731 | n/a | for x in non_reversibles: |

732 | n/a | self.assertNotIsInstance(x, Reversible) |

733 | n/a | self.assertFalse(issubclass(type(x), Reversible), repr(type(x))) |

734 | n/a | # Check some reversible iterables |

735 | n/a | samples = [bytes(), str(), tuple(), list(), OrderedDict(), |

736 | n/a | OrderedDict().keys(), OrderedDict().items(), |

737 | n/a | OrderedDict().values()] |

738 | n/a | for x in samples: |

739 | n/a | self.assertIsInstance(x, Reversible) |

740 | n/a | self.assertTrue(issubclass(type(x), Reversible), repr(type(x))) |

741 | n/a | # Check also Mapping, MutableMapping, and Sequence |

742 | n/a | self.assertTrue(issubclass(Sequence, Reversible), repr(Sequence)) |

743 | n/a | self.assertFalse(issubclass(Mapping, Reversible), repr(Mapping)) |

744 | n/a | self.assertFalse(issubclass(MutableMapping, Reversible), repr(MutableMapping)) |

745 | n/a | # Check direct subclassing |

746 | n/a | class R(Reversible): |

747 | n/a | def __iter__(self): |

748 | n/a | return iter(list()) |

749 | n/a | def __reversed__(self): |

750 | n/a | return iter(list()) |

751 | n/a | self.assertEqual(list(reversed(R())), []) |

752 | n/a | self.assertFalse(issubclass(float, R)) |

753 | n/a | self.validate_abstract_methods(Reversible, '__reversed__', '__iter__') |

754 | n/a | # Check reversible non-iterable (which is not Reversible) |

755 | n/a | class RevNoIter: |

756 | n/a | def __reversed__(self): return reversed([]) |

757 | n/a | class RevPlusIter(RevNoIter): |

758 | n/a | def __iter__(self): return iter([]) |

759 | n/a | self.assertFalse(issubclass(RevNoIter, Reversible)) |

760 | n/a | self.assertFalse(isinstance(RevNoIter(), Reversible)) |

761 | n/a | self.assertTrue(issubclass(RevPlusIter, Reversible)) |

762 | n/a | self.assertTrue(isinstance(RevPlusIter(), Reversible)) |

763 | n/a | # Check None blocking |

764 | n/a | class Rev: |

765 | n/a | def __iter__(self): return iter([]) |

766 | n/a | def __reversed__(self): return reversed([]) |

767 | n/a | class RevItBlocked(Rev): |

768 | n/a | __iter__ = None |

769 | n/a | class RevRevBlocked(Rev): |

770 | n/a | __reversed__ = None |

771 | n/a | self.assertTrue(issubclass(Rev, Reversible)) |

772 | n/a | self.assertTrue(isinstance(Rev(), Reversible)) |

773 | n/a | self.assertFalse(issubclass(RevItBlocked, Reversible)) |

774 | n/a | self.assertFalse(isinstance(RevItBlocked(), Reversible)) |

775 | n/a | self.assertFalse(issubclass(RevRevBlocked, Reversible)) |

776 | n/a | self.assertFalse(isinstance(RevRevBlocked(), Reversible)) |

777 | n/a | |

778 | n/a | def test_Collection(self): |

779 | n/a | # Check some non-collections |

780 | n/a | non_collections = [None, 42, 3.14, 1j, lambda x: 2*x] |

781 | n/a | for x in non_collections: |

782 | n/a | self.assertNotIsInstance(x, Collection) |

783 | n/a | self.assertFalse(issubclass(type(x), Collection), repr(type(x))) |

784 | n/a | # Check some non-collection iterables |

785 | n/a | non_col_iterables = [_test_gen(), iter(b''), iter(bytearray()), |

786 | n/a | (x for x in []), dict().values()] |

787 | n/a | for x in non_col_iterables: |

788 | n/a | self.assertNotIsInstance(x, Collection) |

789 | n/a | self.assertFalse(issubclass(type(x), Collection), repr(type(x))) |

790 | n/a | # Check some collections |

791 | n/a | samples = [set(), frozenset(), dict(), bytes(), str(), tuple(), |

792 | n/a | list(), dict().keys(), dict().items()] |

793 | n/a | for x in samples: |

794 | n/a | self.assertIsInstance(x, Collection) |

795 | n/a | self.assertTrue(issubclass(type(x), Collection), repr(type(x))) |

796 | n/a | # Check also Mapping, MutableMapping, etc. |

797 | n/a | self.assertTrue(issubclass(Sequence, Collection), repr(Sequence)) |

798 | n/a | self.assertTrue(issubclass(Mapping, Collection), repr(Mapping)) |

799 | n/a | self.assertTrue(issubclass(MutableMapping, Collection), |

800 | n/a | repr(MutableMapping)) |

801 | n/a | self.assertTrue(issubclass(Set, Collection), repr(Set)) |

802 | n/a | self.assertTrue(issubclass(MutableSet, Collection), repr(MutableSet)) |

803 | n/a | self.assertTrue(issubclass(Sequence, Collection), repr(MutableSet)) |

804 | n/a | # Check direct subclassing |

805 | n/a | class Col(Collection): |

806 | n/a | def __iter__(self): |

807 | n/a | return iter(list()) |

808 | n/a | def __len__(self): |

809 | n/a | return 0 |

810 | n/a | def __contains__(self, item): |

811 | n/a | return False |

812 | n/a | class DerCol(Col): pass |

813 | n/a | self.assertEqual(list(iter(Col())), []) |

814 | n/a | self.assertFalse(issubclass(list, Col)) |

815 | n/a | self.assertFalse(issubclass(set, Col)) |

816 | n/a | self.assertFalse(issubclass(float, Col)) |

817 | n/a | self.assertEqual(list(iter(DerCol())), []) |

818 | n/a | self.assertFalse(issubclass(list, DerCol)) |

819 | n/a | self.assertFalse(issubclass(set, DerCol)) |

820 | n/a | self.assertFalse(issubclass(float, DerCol)) |

821 | n/a | self.validate_abstract_methods(Collection, '__len__', '__iter__', |

822 | n/a | '__contains__') |

823 | n/a | # Check sized container non-iterable (which is not Collection) etc. |

824 | n/a | class ColNoIter: |

825 | n/a | def __len__(self): return 0 |

826 | n/a | def __contains__(self, item): return False |

827 | n/a | class ColNoSize: |

828 | n/a | def __iter__(self): return iter([]) |

829 | n/a | def __contains__(self, item): return False |

830 | n/a | class ColNoCont: |

831 | n/a | def __iter__(self): return iter([]) |

832 | n/a | def __len__(self): return 0 |

833 | n/a | self.assertFalse(issubclass(ColNoIter, Collection)) |

834 | n/a | self.assertFalse(isinstance(ColNoIter(), Collection)) |

835 | n/a | self.assertFalse(issubclass(ColNoSize, Collection)) |

836 | n/a | self.assertFalse(isinstance(ColNoSize(), Collection)) |

837 | n/a | self.assertFalse(issubclass(ColNoCont, Collection)) |

838 | n/a | self.assertFalse(isinstance(ColNoCont(), Collection)) |

839 | n/a | # Check None blocking |

840 | n/a | class SizeBlock: |

841 | n/a | def __iter__(self): return iter([]) |

842 | n/a | def __contains__(self): return False |

843 | n/a | __len__ = None |

844 | n/a | class IterBlock: |

845 | n/a | def __len__(self): return 0 |

846 | n/a | def __contains__(self): return True |

847 | n/a | __iter__ = None |

848 | n/a | self.assertFalse(issubclass(SizeBlock, Collection)) |

849 | n/a | self.assertFalse(isinstance(SizeBlock(), Collection)) |

850 | n/a | self.assertFalse(issubclass(IterBlock, Collection)) |

851 | n/a | self.assertFalse(isinstance(IterBlock(), Collection)) |

852 | n/a | # Check None blocking in subclass |

853 | n/a | class ColImpl: |

854 | n/a | def __iter__(self): |

855 | n/a | return iter(list()) |

856 | n/a | def __len__(self): |

857 | n/a | return 0 |

858 | n/a | def __contains__(self, item): |

859 | n/a | return False |

860 | n/a | class NonCol(ColImpl): |

861 | n/a | __contains__ = None |

862 | n/a | self.assertFalse(issubclass(NonCol, Collection)) |

863 | n/a | self.assertFalse(isinstance(NonCol(), Collection)) |

864 | n/a | |

865 | n/a | |

866 | n/a | def test_Iterator(self): |

867 | n/a | non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] |

868 | n/a | for x in non_samples: |

869 | n/a | self.assertNotIsInstance(x, Iterator) |

870 | n/a | self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) |

871 | n/a | samples = [iter(bytes()), iter(str()), |

872 | n/a | iter(tuple()), iter(list()), iter(dict()), |

873 | n/a | iter(set()), iter(frozenset()), |

874 | n/a | iter(dict().keys()), iter(dict().items()), |

875 | n/a | iter(dict().values()), |

876 | n/a | _test_gen(), |

877 | n/a | (x for x in []), |

878 | n/a | ] |

879 | n/a | for x in samples: |

880 | n/a | self.assertIsInstance(x, Iterator) |

881 | n/a | self.assertTrue(issubclass(type(x), Iterator), repr(type(x))) |

882 | n/a | self.validate_abstract_methods(Iterator, '__next__', '__iter__') |

883 | n/a | |

884 | n/a | # Issue 10565 |

885 | n/a | class NextOnly: |

886 | n/a | def __next__(self): |

887 | n/a | yield 1 |

888 | n/a | return |

889 | n/a | self.assertNotIsInstance(NextOnly(), Iterator) |

890 | n/a | |

891 | n/a | def test_Generator(self): |

892 | n/a | class NonGen1: |

893 | n/a | def __iter__(self): return self |

894 | n/a | def __next__(self): return None |

895 | n/a | def close(self): pass |

896 | n/a | def throw(self, typ, val=None, tb=None): pass |

897 | n/a | |

898 | n/a | class NonGen2: |

899 | n/a | def __iter__(self): return self |

900 | n/a | def __next__(self): return None |

901 | n/a | def close(self): pass |

902 | n/a | def send(self, value): return value |

903 | n/a | |

904 | n/a | class NonGen3: |

905 | n/a | def close(self): pass |

906 | n/a | def send(self, value): return value |

907 | n/a | def throw(self, typ, val=None, tb=None): pass |

908 | n/a | |

909 | n/a | non_samples = [ |

910 | n/a | None, 42, 3.14, 1j, b"", "", (), [], {}, set(), |

911 | n/a | iter(()), iter([]), NonGen1(), NonGen2(), NonGen3()] |

912 | n/a | for x in non_samples: |

913 | n/a | self.assertNotIsInstance(x, Generator) |

914 | n/a | self.assertFalse(issubclass(type(x), Generator), repr(type(x))) |

915 | n/a | |

916 | n/a | class Gen: |

917 | n/a | def __iter__(self): return self |

918 | n/a | def __next__(self): return None |

919 | n/a | def close(self): pass |

920 | n/a | def send(self, value): return value |

921 | n/a | def throw(self, typ, val=None, tb=None): pass |

922 | n/a | |

923 | n/a | class MinimalGen(Generator): |

924 | n/a | def send(self, value): |

925 | n/a | return value |

926 | n/a | def throw(self, typ, val=None, tb=None): |

927 | n/a | super().throw(typ, val, tb) |

928 | n/a | |

929 | n/a | def gen(): |

930 | n/a | yield 1 |

931 | n/a | |

932 | n/a | samples = [gen(), (lambda: (yield))(), Gen(), MinimalGen()] |

933 | n/a | for x in samples: |

934 | n/a | self.assertIsInstance(x, Iterator) |

935 | n/a | self.assertIsInstance(x, Generator) |

936 | n/a | self.assertTrue(issubclass(type(x), Generator), repr(type(x))) |

937 | n/a | self.validate_abstract_methods(Generator, 'send', 'throw') |

938 | n/a | |

939 | n/a | # mixin tests |

940 | n/a | mgen = MinimalGen() |

941 | n/a | self.assertIs(mgen, iter(mgen)) |

942 | n/a | self.assertIs(mgen.send(None), next(mgen)) |

943 | n/a | self.assertEqual(2, mgen.send(2)) |

944 | n/a | self.assertIsNone(mgen.close()) |

945 | n/a | self.assertRaises(ValueError, mgen.throw, ValueError) |

946 | n/a | self.assertRaisesRegex(ValueError, "^huhu$", |

947 | n/a | mgen.throw, ValueError, ValueError("huhu")) |

948 | n/a | self.assertRaises(StopIteration, mgen.throw, StopIteration()) |

949 | n/a | |

950 | n/a | class FailOnClose(Generator): |

951 | n/a | def send(self, value): return value |

952 | n/a | def throw(self, *args): raise ValueError |

953 | n/a | |

954 | n/a | self.assertRaises(ValueError, FailOnClose().close) |

955 | n/a | |

956 | n/a | class IgnoreGeneratorExit(Generator): |

957 | n/a | def send(self, value): return value |

958 | n/a | def throw(self, *args): pass |

959 | n/a | |

960 | n/a | self.assertRaises(RuntimeError, IgnoreGeneratorExit().close) |

961 | n/a | |

962 | n/a | def test_AsyncGenerator(self): |

963 | n/a | class NonAGen1: |

964 | n/a | def __aiter__(self): return self |

965 | n/a | def __anext__(self): return None |

966 | n/a | def aclose(self): pass |

967 | n/a | def athrow(self, typ, val=None, tb=None): pass |

968 | n/a | |

969 | n/a | class NonAGen2: |

970 | n/a | def __aiter__(self): return self |

971 | n/a | def __anext__(self): return None |

972 | n/a | def aclose(self): pass |

973 | n/a | def asend(self, value): return value |

974 | n/a | |

975 | n/a | class NonAGen3: |

976 | n/a | def aclose(self): pass |

977 | n/a | def asend(self, value): return value |

978 | n/a | def athrow(self, typ, val=None, tb=None): pass |

979 | n/a | |

980 | n/a | non_samples = [ |

981 | n/a | None, 42, 3.14, 1j, b"", "", (), [], {}, set(), |

982 | n/a | iter(()), iter([]), NonAGen1(), NonAGen2(), NonAGen3()] |

983 | n/a | for x in non_samples: |

984 | n/a | self.assertNotIsInstance(x, AsyncGenerator) |

985 | n/a | self.assertFalse(issubclass(type(x), AsyncGenerator), repr(type(x))) |

986 | n/a | |

987 | n/a | class Gen: |

988 | n/a | def __aiter__(self): return self |

989 | n/a | async def __anext__(self): return None |

990 | n/a | async def aclose(self): pass |

991 | n/a | async def asend(self, value): return value |

992 | n/a | async def athrow(self, typ, val=None, tb=None): pass |

993 | n/a | |

994 | n/a | class MinimalAGen(AsyncGenerator): |

995 | n/a | async def asend(self, value): |

996 | n/a | return value |

997 | n/a | async def athrow(self, typ, val=None, tb=None): |

998 | n/a | await super().athrow(typ, val, tb) |

999 | n/a | |

1000 | n/a | async def gen(): |

1001 | n/a | yield 1 |

1002 | n/a | |

1003 | n/a | samples = [gen(), Gen(), MinimalAGen()] |

1004 | n/a | for x in samples: |

1005 | n/a | self.assertIsInstance(x, AsyncIterator) |

1006 | n/a | self.assertIsInstance(x, AsyncGenerator) |

1007 | n/a | self.assertTrue(issubclass(type(x), AsyncGenerator), repr(type(x))) |

1008 | n/a | self.validate_abstract_methods(AsyncGenerator, 'asend', 'athrow') |

1009 | n/a | |

1010 | n/a | def run_async(coro): |

1011 | n/a | result = None |

1012 | n/a | while True: |

1013 | n/a | try: |

1014 | n/a | coro.send(None) |

1015 | n/a | except StopIteration as ex: |

1016 | n/a | result = ex.args[0] if ex.args else None |

1017 | n/a | break |

1018 | n/a | return result |

1019 | n/a | |

1020 | n/a | # mixin tests |

1021 | n/a | mgen = MinimalAGen() |

1022 | n/a | self.assertIs(mgen, mgen.__aiter__()) |

1023 | n/a | self.assertIs(run_async(mgen.asend(None)), run_async(mgen.__anext__())) |

1024 | n/a | self.assertEqual(2, run_async(mgen.asend(2))) |

1025 | n/a | self.assertIsNone(run_async(mgen.aclose())) |

1026 | n/a | with self.assertRaises(ValueError): |

1027 | n/a | run_async(mgen.athrow(ValueError)) |

1028 | n/a | |

1029 | n/a | class FailOnClose(AsyncGenerator): |

1030 | n/a | async def asend(self, value): return value |

1031 | n/a | async def athrow(self, *args): raise ValueError |

1032 | n/a | |

1033 | n/a | with self.assertRaises(ValueError): |

1034 | n/a | run_async(FailOnClose().aclose()) |

1035 | n/a | |

1036 | n/a | class IgnoreGeneratorExit(AsyncGenerator): |

1037 | n/a | async def asend(self, value): return value |

1038 | n/a | async def athrow(self, *args): pass |

1039 | n/a | |

1040 | n/a | with self.assertRaises(RuntimeError): |

1041 | n/a | run_async(IgnoreGeneratorExit().aclose()) |

1042 | n/a | |

1043 | n/a | def test_Sized(self): |

1044 | n/a | non_samples = [None, 42, 3.14, 1j, |

1045 | n/a | _test_gen(), |

1046 | n/a | (x for x in []), |

1047 | n/a | ] |

1048 | n/a | for x in non_samples: |

1049 | n/a | self.assertNotIsInstance(x, Sized) |

1050 | n/a | self.assertFalse(issubclass(type(x), Sized), repr(type(x))) |

1051 | n/a | samples = [bytes(), str(), |

1052 | n/a | tuple(), list(), set(), frozenset(), dict(), |

1053 | n/a | dict().keys(), dict().items(), dict().values(), |

1054 | n/a | ] |

1055 | n/a | for x in samples: |

1056 | n/a | self.assertIsInstance(x, Sized) |

1057 | n/a | self.assertTrue(issubclass(type(x), Sized), repr(type(x))) |

1058 | n/a | self.validate_abstract_methods(Sized, '__len__') |

1059 | n/a | self.validate_isinstance(Sized, '__len__') |

1060 | n/a | |

1061 | n/a | def test_Container(self): |

1062 | n/a | non_samples = [None, 42, 3.14, 1j, |

1063 | n/a | _test_gen(), |

1064 | n/a | (x for x in []), |

1065 | n/a | ] |

1066 | n/a | for x in non_samples: |

1067 | n/a | self.assertNotIsInstance(x, Container) |

1068 | n/a | self.assertFalse(issubclass(type(x), Container), repr(type(x))) |

1069 | n/a | samples = [bytes(), str(), |

1070 | n/a | tuple(), list(), set(), frozenset(), dict(), |

1071 | n/a | dict().keys(), dict().items(), |

1072 | n/a | ] |

1073 | n/a | for x in samples: |

1074 | n/a | self.assertIsInstance(x, Container) |

1075 | n/a | self.assertTrue(issubclass(type(x), Container), repr(type(x))) |

1076 | n/a | self.validate_abstract_methods(Container, '__contains__') |

1077 | n/a | self.validate_isinstance(Container, '__contains__') |

1078 | n/a | |

1079 | n/a | def test_Callable(self): |

1080 | n/a | non_samples = [None, 42, 3.14, 1j, |

1081 | n/a | "", b"", (), [], {}, set(), |

1082 | n/a | _test_gen(), |

1083 | n/a | (x for x in []), |

1084 | n/a | ] |

1085 | n/a | for x in non_samples: |

1086 | n/a | self.assertNotIsInstance(x, Callable) |

1087 | n/a | self.assertFalse(issubclass(type(x), Callable), repr(type(x))) |

1088 | n/a | samples = [lambda: None, |

1089 | n/a | type, int, object, |

1090 | n/a | len, |

1091 | n/a | list.append, [].append, |

1092 | n/a | ] |

1093 | n/a | for x in samples: |

1094 | n/a | self.assertIsInstance(x, Callable) |

1095 | n/a | self.assertTrue(issubclass(type(x), Callable), repr(type(x))) |

1096 | n/a | self.validate_abstract_methods(Callable, '__call__') |

1097 | n/a | self.validate_isinstance(Callable, '__call__') |

1098 | n/a | |

1099 | n/a | def test_direct_subclassing(self): |

1100 | n/a | for B in Hashable, Iterable, Iterator, Reversible, Sized, Container, Callable: |

1101 | n/a | class C(B): |

1102 | n/a | pass |

1103 | n/a | self.assertTrue(issubclass(C, B)) |

1104 | n/a | self.assertFalse(issubclass(int, C)) |

1105 | n/a | |

1106 | n/a | def test_registration(self): |

1107 | n/a | for B in Hashable, Iterable, Iterator, Reversible, Sized, Container, Callable: |

1108 | n/a | class C: |

1109 | n/a | __hash__ = None # Make sure it isn't hashable by default |

1110 | n/a | self.assertFalse(issubclass(C, B), B.__name__) |

1111 | n/a | B.register(C) |

1112 | n/a | self.assertTrue(issubclass(C, B)) |

1113 | n/a | |

1114 | n/a | class WithSet(MutableSet): |

1115 | n/a | |

1116 | n/a | def __init__(self, it=()): |

1117 | n/a | self.data = set(it) |

1118 | n/a | |

1119 | n/a | def __len__(self): |

1120 | n/a | return len(self.data) |

1121 | n/a | |

1122 | n/a | def __iter__(self): |

1123 | n/a | return iter(self.data) |

1124 | n/a | |

1125 | n/a | def __contains__(self, item): |

1126 | n/a | return item in self.data |

1127 | n/a | |

1128 | n/a | def add(self, item): |

1129 | n/a | self.data.add(item) |

1130 | n/a | |

1131 | n/a | def discard(self, item): |

1132 | n/a | self.data.discard(item) |

1133 | n/a | |

1134 | n/a | class TestCollectionABCs(ABCTestCase): |

1135 | n/a | |

1136 | n/a | # XXX For now, we only test some virtual inheritance properties. |

1137 | n/a | # We should also test the proper behavior of the collection ABCs |

1138 | n/a | # as real base classes or mix-in classes. |

1139 | n/a | |

1140 | n/a | def test_Set(self): |

1141 | n/a | for sample in [set, frozenset]: |

1142 | n/a | self.assertIsInstance(sample(), Set) |

1143 | n/a | self.assertTrue(issubclass(sample, Set)) |

1144 | n/a | self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') |

1145 | n/a | class MySet(Set): |

1146 | n/a | def __contains__(self, x): |

1147 | n/a | return False |

1148 | n/a | def __len__(self): |

1149 | n/a | return 0 |

1150 | n/a | def __iter__(self): |

1151 | n/a | return iter([]) |

1152 | n/a | self.validate_comparison(MySet()) |

1153 | n/a | |

1154 | n/a | def test_hash_Set(self): |

1155 | n/a | class OneTwoThreeSet(Set): |

1156 | n/a | def __init__(self): |

1157 | n/a | self.contents = [1, 2, 3] |

1158 | n/a | def __contains__(self, x): |

1159 | n/a | return x in self.contents |

1160 | n/a | def __len__(self): |

1161 | n/a | return len(self.contents) |

1162 | n/a | def __iter__(self): |

1163 | n/a | return iter(self.contents) |

1164 | n/a | def __hash__(self): |

1165 | n/a | return self._hash() |

1166 | n/a | a, b = OneTwoThreeSet(), OneTwoThreeSet() |

1167 | n/a | self.assertTrue(hash(a) == hash(b)) |

1168 | n/a | |

1169 | n/a | def test_isdisjoint_Set(self): |

1170 | n/a | class MySet(Set): |

1171 | n/a | def __init__(self, itr): |

1172 | n/a | self.contents = itr |

1173 | n/a | def __contains__(self, x): |

1174 | n/a | return x in self.contents |

1175 | n/a | def __iter__(self): |

1176 | n/a | return iter(self.contents) |

1177 | n/a | def __len__(self): |

1178 | n/a | return len([x for x in self.contents]) |

1179 | n/a | s1 = MySet((1, 2, 3)) |

1180 | n/a | s2 = MySet((4, 5, 6)) |

1181 | n/a | s3 = MySet((1, 5, 6)) |

1182 | n/a | self.assertTrue(s1.isdisjoint(s2)) |

1183 | n/a | self.assertFalse(s1.isdisjoint(s3)) |

1184 | n/a | |

1185 | n/a | def test_equality_Set(self): |

1186 | n/a | class MySet(Set): |

1187 | n/a | def __init__(self, itr): |

1188 | n/a | self.contents = itr |

1189 | n/a | def __contains__(self, x): |

1190 | n/a | return x in self.contents |

1191 | n/a | def __iter__(self): |

1192 | n/a | return iter(self.contents) |

1193 | n/a | def __len__(self): |

1194 | n/a | return len([x for x in self.contents]) |

1195 | n/a | s1 = MySet((1,)) |

1196 | n/a | s2 = MySet((1, 2)) |

1197 | n/a | s3 = MySet((3, 4)) |

1198 | n/a | s4 = MySet((3, 4)) |

1199 | n/a | self.assertTrue(s2 > s1) |

1200 | n/a | self.assertTrue(s1 < s2) |

1201 | n/a | self.assertFalse(s2 <= s1) |

1202 | n/a | self.assertFalse(s2 <= s3) |

1203 | n/a | self.assertFalse(s1 >= s2) |

1204 | n/a | self.assertEqual(s3, s4) |

1205 | n/a | self.assertNotEqual(s2, s3) |

1206 | n/a | |

1207 | n/a | def test_arithmetic_Set(self): |

1208 | n/a | class MySet(Set): |

1209 | n/a | def __init__(self, itr): |

1210 | n/a | self.contents = itr |

1211 | n/a | def __contains__(self, x): |

1212 | n/a | return x in self.contents |

1213 | n/a | def __iter__(self): |

1214 | n/a | return iter(self.contents) |

1215 | n/a | def __len__(self): |

1216 | n/a | return len([x for x in self.contents]) |

1217 | n/a | s1 = MySet((1, 2, 3)) |

1218 | n/a | s2 = MySet((3, 4, 5)) |

1219 | n/a | s3 = s1 & s2 |

1220 | n/a | self.assertEqual(s3, MySet((3,))) |

1221 | n/a | |

1222 | n/a | def test_MutableSet(self): |

1223 | n/a | self.assertIsInstance(set(), MutableSet) |

1224 | n/a | self.assertTrue(issubclass(set, MutableSet)) |

1225 | n/a | self.assertNotIsInstance(frozenset(), MutableSet) |

1226 | n/a | self.assertFalse(issubclass(frozenset, MutableSet)) |

1227 | n/a | self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__', |

1228 | n/a | 'add', 'discard') |

1229 | n/a | |

1230 | n/a | def test_issue_5647(self): |

1231 | n/a | # MutableSet.__iand__ mutated the set during iteration |

1232 | n/a | s = WithSet('abcd') |

1233 | n/a | s &= WithSet('cdef') # This used to fail |

1234 | n/a | self.assertEqual(set(s), set('cd')) |

1235 | n/a | |

1236 | n/a | def test_issue_4920(self): |

1237 | n/a | # MutableSet.pop() method did not work |

1238 | n/a | class MySet(MutableSet): |

1239 | n/a | __slots__=['__s'] |

1240 | n/a | def __init__(self,items=None): |

1241 | n/a | if items is None: |

1242 | n/a | items=[] |

1243 | n/a | self.__s=set(items) |

1244 | n/a | def __contains__(self,v): |

1245 | n/a | return v in self.__s |

1246 | n/a | def __iter__(self): |

1247 | n/a | return iter(self.__s) |

1248 | n/a | def __len__(self): |

1249 | n/a | return len(self.__s) |

1250 | n/a | def add(self,v): |

1251 | n/a | result=v not in self.__s |

1252 | n/a | self.__s.add(v) |

1253 | n/a | return result |

1254 | n/a | def discard(self,v): |

1255 | n/a | result=v in self.__s |

1256 | n/a | self.__s.discard(v) |

1257 | n/a | return result |

1258 | n/a | def __repr__(self): |

1259 | n/a | return "MySet(%s)" % repr(list(self)) |

1260 | n/a | s = MySet([5,43,2,1]) |

1261 | n/a | self.assertEqual(s.pop(), 1) |

1262 | n/a | |

1263 | n/a | def test_issue8750(self): |

1264 | n/a | empty = WithSet() |

1265 | n/a | full = WithSet(range(10)) |

1266 | n/a | s = WithSet(full) |

1267 | n/a | s -= s |

1268 | n/a | self.assertEqual(s, empty) |

1269 | n/a | s = WithSet(full) |

1270 | n/a | s ^= s |

1271 | n/a | self.assertEqual(s, empty) |

1272 | n/a | s = WithSet(full) |

1273 | n/a | s &= s |

1274 | n/a | self.assertEqual(s, full) |

1275 | n/a | s |= s |

1276 | n/a | self.assertEqual(s, full) |

1277 | n/a | |

1278 | n/a | def test_issue16373(self): |

1279 | n/a | # Recursion error comparing comparable and noncomparable |

1280 | n/a | # Set instances |

1281 | n/a | class MyComparableSet(Set): |

1282 | n/a | def __contains__(self, x): |

1283 | n/a | return False |

1284 | n/a | def __len__(self): |

1285 | n/a | return 0 |

1286 | n/a | def __iter__(self): |

1287 | n/a | return iter([]) |

1288 | n/a | class MyNonComparableSet(Set): |

1289 | n/a | def __contains__(self, x): |

1290 | n/a | return False |

1291 | n/a | def __len__(self): |

1292 | n/a | return 0 |

1293 | n/a | def __iter__(self): |

1294 | n/a | return iter([]) |

1295 | n/a | def __le__(self, x): |

1296 | n/a | return NotImplemented |

1297 | n/a | def __lt__(self, x): |

1298 | n/a | return NotImplemented |

1299 | n/a | |

1300 | n/a | cs = MyComparableSet() |

1301 | n/a | ncs = MyNonComparableSet() |

1302 | n/a | self.assertFalse(ncs < cs) |

1303 | n/a | self.assertTrue(ncs <= cs) |

1304 | n/a | self.assertFalse(ncs > cs) |

1305 | n/a | self.assertTrue(ncs >= cs) |

1306 | n/a | |

1307 | n/a | def test_issue26915(self): |

1308 | n/a | # Container membership test should check identity first |

1309 | n/a | class CustomEqualObject: |

1310 | n/a | def __eq__(self, other): |

1311 | n/a | return False |

1312 | n/a | class CustomSequence(list): |

1313 | n/a | def __contains__(self, value): |

1314 | n/a | return Sequence.__contains__(self, value) |

1315 | n/a | |

1316 | n/a | nan = float('nan') |

1317 | n/a | obj = CustomEqualObject() |

1318 | n/a | containers = [ |

1319 | n/a | CustomSequence([nan, obj]), |

1320 | n/a | ItemsView({1: nan, 2: obj}), |

1321 | n/a | ValuesView({1: nan, 2: obj}) |

1322 | n/a | ] |

1323 | n/a | for container in containers: |

1324 | n/a | for elem in container: |

1325 | n/a | self.assertIn(elem, container) |

1326 | n/a | |

1327 | n/a | def assertSameSet(self, s1, s2): |

1328 | n/a | # coerce both to a real set then check equality |

1329 | n/a | self.assertSetEqual(set(s1), set(s2)) |

1330 | n/a | |

1331 | n/a | def test_Set_interoperability_with_real_sets(self): |

1332 | n/a | # Issue: 8743 |

1333 | n/a | class ListSet(Set): |

1334 | n/a | def __init__(self, elements=()): |

1335 | n/a | self.data = [] |

1336 | n/a | for elem in elements: |

1337 | n/a | if elem not in self.data: |

1338 | n/a | self.data.append(elem) |

1339 | n/a | def __contains__(self, elem): |

1340 | n/a | return elem in self.data |

1341 | n/a | def __iter__(self): |

1342 | n/a | return iter(self.data) |

1343 | n/a | def __len__(self): |

1344 | n/a | return len(self.data) |

1345 | n/a | def __repr__(self): |

1346 | n/a | return 'Set({!r})'.format(self.data) |

1347 | n/a | |

1348 | n/a | r1 = set('abc') |

1349 | n/a | r2 = set('bcd') |

1350 | n/a | r3 = set('abcde') |

1351 | n/a | f1 = ListSet('abc') |

1352 | n/a | f2 = ListSet('bcd') |

1353 | n/a | f3 = ListSet('abcde') |

1354 | n/a | l1 = list('abccba') |

1355 | n/a | l2 = list('bcddcb') |

1356 | n/a | l3 = list('abcdeedcba') |

1357 | n/a | |

1358 | n/a | target = r1 & r2 |

1359 | n/a | self.assertSameSet(f1 & f2, target) |

1360 | n/a | self.assertSameSet(f1 & r2, target) |

1361 | n/a | self.assertSameSet(r2 & f1, target) |

1362 | n/a | self.assertSameSet(f1 & l2, target) |

1363 | n/a | |

1364 | n/a | target = r1 | r2 |

1365 | n/a | self.assertSameSet(f1 | f2, target) |

1366 | n/a | self.assertSameSet(f1 | r2, target) |

1367 | n/a | self.assertSameSet(r2 | f1, target) |

1368 | n/a | self.assertSameSet(f1 | l2, target) |

1369 | n/a | |

1370 | n/a | fwd_target = r1 - r2 |

1371 | n/a | rev_target = r2 - r1 |

1372 | n/a | self.assertSameSet(f1 - f2, fwd_target) |

1373 | n/a | self.assertSameSet(f2 - f1, rev_target) |

1374 | n/a | self.assertSameSet(f1 - r2, fwd_target) |

1375 | n/a | self.assertSameSet(f2 - r1, rev_target) |

1376 | n/a | self.assertSameSet(r1 - f2, fwd_target) |

1377 | n/a | self.assertSameSet(r2 - f1, rev_target) |

1378 | n/a | self.assertSameSet(f1 - l2, fwd_target) |

1379 | n/a | self.assertSameSet(f2 - l1, rev_target) |

1380 | n/a | |

1381 | n/a | target = r1 ^ r2 |

1382 | n/a | self.assertSameSet(f1 ^ f2, target) |

1383 | n/a | self.assertSameSet(f1 ^ r2, target) |

1384 | n/a | self.assertSameSet(r2 ^ f1, target) |

1385 | n/a | self.assertSameSet(f1 ^ l2, target) |

1386 | n/a | |

1387 | n/a | # Don't change the following to use assertLess or other |

1388 | n/a | # "more specific" unittest assertions. The current |

1389 | n/a | # assertTrue/assertFalse style makes the pattern of test |

1390 | n/a | # case combinations clear and allows us to know for sure |

1391 | n/a | # the exact operator being invoked. |

1392 | n/a | |

1393 | n/a | # proper subset |

1394 | n/a | self.assertTrue(f1 < f3) |

1395 | n/a | self.assertFalse(f1 < f1) |

1396 | n/a | self.assertFalse(f1 < f2) |

1397 | n/a | self.assertTrue(r1 < f3) |

1398 | n/a | self.assertFalse(r1 < f1) |

1399 | n/a | self.assertFalse(r1 < f2) |

1400 | n/a | self.assertTrue(r1 < r3) |

1401 | n/a | self.assertFalse(r1 < r1) |

1402 | n/a | self.assertFalse(r1 < r2) |

1403 | n/a | with self.assertRaises(TypeError): |

1404 | n/a | f1 < l3 |

1405 | n/a | with self.assertRaises(TypeError): |

1406 | n/a | f1 < l1 |

1407 | n/a | with self.assertRaises(TypeError): |

1408 | n/a | f1 < l2 |

1409 | n/a | |

1410 | n/a | # any subset |

1411 | n/a | self.assertTrue(f1 <= f3) |

1412 | n/a | self.assertTrue(f1 <= f1) |

1413 | n/a | self.assertFalse(f1 <= f2) |

1414 | n/a | self.assertTrue(r1 <= f3) |

1415 | n/a | self.assertTrue(r1 <= f1) |

1416 | n/a | self.assertFalse(r1 <= f2) |

1417 | n/a | self.assertTrue(r1 <= r3) |

1418 | n/a | self.assertTrue(r1 <= r1) |

1419 | n/a | self.assertFalse(r1 <= r2) |

1420 | n/a | with self.assertRaises(TypeError): |

1421 | n/a | f1 <= l3 |

1422 | n/a | with self.assertRaises(TypeError): |

1423 | n/a | f1 <= l1 |

1424 | n/a | with self.assertRaises(TypeError): |

1425 | n/a | f1 <= l2 |

1426 | n/a | |

1427 | n/a | # proper superset |

1428 | n/a | self.assertTrue(f3 > f1) |

1429 | n/a | self.assertFalse(f1 > f1) |

1430 | n/a | self.assertFalse(f2 > f1) |

1431 | n/a | self.assertTrue(r3 > r1) |

1432 | n/a | self.assertFalse(f1 > r1) |

1433 | n/a | self.assertFalse(f2 > r1) |

1434 | n/a | self.assertTrue(r3 > r1) |

1435 | n/a | self.assertFalse(r1 > r1) |

1436 | n/a | self.assertFalse(r2 > r1) |

1437 | n/a | with self.assertRaises(TypeError): |

1438 | n/a | f1 > l3 |

1439 | n/a | with self.assertRaises(TypeError): |

1440 | n/a | f1 > l1 |

1441 | n/a | with self.assertRaises(TypeError): |

1442 | n/a | f1 > l2 |

1443 | n/a | |

1444 | n/a | # any superset |

1445 | n/a | self.assertTrue(f3 >= f1) |

1446 | n/a | self.assertTrue(f1 >= f1) |

1447 | n/a | self.assertFalse(f2 >= f1) |

1448 | n/a | self.assertTrue(r3 >= r1) |

1449 | n/a | self.assertTrue(f1 >= r1) |

1450 | n/a | self.assertFalse(f2 >= r1) |

1451 | n/a | self.assertTrue(r3 >= r1) |

1452 | n/a | self.assertTrue(r1 >= r1) |

1453 | n/a | self.assertFalse(r2 >= r1) |

1454 | n/a | with self.assertRaises(TypeError): |

1455 | n/a | f1 >= l3 |

1456 | n/a | with self.assertRaises(TypeError): |

1457 | n/a | f1 >=l1 |

1458 | n/a | with self.assertRaises(TypeError): |

1459 | n/a | f1 >= l2 |

1460 | n/a | |

1461 | n/a | # equality |

1462 | n/a | self.assertTrue(f1 == f1) |

1463 | n/a | self.assertTrue(r1 == f1) |

1464 | n/a | self.assertTrue(f1 == r1) |

1465 | n/a | self.assertFalse(f1 == f3) |

1466 | n/a | self.assertFalse(r1 == f3) |

1467 | n/a | self.assertFalse(f1 == r3) |

1468 | n/a | self.assertFalse(f1 == l3) |

1469 | n/a | self.assertFalse(f1 == l1) |

1470 | n/a | self.assertFalse(f1 == l2) |

1471 | n/a | |

1472 | n/a | # inequality |

1473 | n/a | self.assertFalse(f1 != f1) |

1474 | n/a | self.assertFalse(r1 != f1) |

1475 | n/a | self.assertFalse(f1 != r1) |

1476 | n/a | self.assertTrue(f1 != f3) |

1477 | n/a | self.assertTrue(r1 != f3) |

1478 | n/a | self.assertTrue(f1 != r3) |

1479 | n/a | self.assertTrue(f1 != l3) |

1480 | n/a | self.assertTrue(f1 != l1) |

1481 | n/a | self.assertTrue(f1 != l2) |

1482 | n/a | |

1483 | n/a | def test_Mapping(self): |

1484 | n/a | for sample in [dict]: |

1485 | n/a | self.assertIsInstance(sample(), Mapping) |

1486 | n/a | self.assertTrue(issubclass(sample, Mapping)) |

1487 | n/a | self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', |

1488 | n/a | '__getitem__') |

1489 | n/a | class MyMapping(Mapping): |

1490 | n/a | def __len__(self): |

1491 | n/a | return 0 |

1492 | n/a | def __getitem__(self, i): |

1493 | n/a | raise IndexError |

1494 | n/a | def __iter__(self): |

1495 | n/a | return iter(()) |

1496 | n/a | self.validate_comparison(MyMapping()) |

1497 | n/a | self.assertRaises(TypeError, reversed, MyMapping()) |

1498 | n/a | |

1499 | n/a | def test_MutableMapping(self): |

1500 | n/a | for sample in [dict]: |

1501 | n/a | self.assertIsInstance(sample(), MutableMapping) |

1502 | n/a | self.assertTrue(issubclass(sample, MutableMapping)) |

1503 | n/a | self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__', |

1504 | n/a | '__getitem__', '__setitem__', '__delitem__') |

1505 | n/a | |

1506 | n/a | def test_MutableMapping_subclass(self): |

1507 | n/a | # Test issue 9214 |

1508 | n/a | mymap = UserDict() |

1509 | n/a | mymap['red'] = 5 |

1510 | n/a | self.assertIsInstance(mymap.keys(), Set) |

1511 | n/a | self.assertIsInstance(mymap.keys(), KeysView) |

1512 | n/a | self.assertIsInstance(mymap.items(), Set) |

1513 | n/a | self.assertIsInstance(mymap.items(), ItemsView) |

1514 | n/a | |

1515 | n/a | mymap = UserDict() |

1516 | n/a | mymap['red'] = 5 |

1517 | n/a | z = mymap.keys() | {'orange'} |

1518 | n/a | self.assertIsInstance(z, set) |

1519 | n/a | list(z) |

1520 | n/a | mymap['blue'] = 7 # Shouldn't affect 'z' |

1521 | n/a | self.assertEqual(sorted(z), ['orange', 'red']) |

1522 | n/a | |

1523 | n/a | mymap = UserDict() |

1524 | n/a | mymap['red'] = 5 |

1525 | n/a | z = mymap.items() | {('orange', 3)} |

1526 | n/a | self.assertIsInstance(z, set) |

1527 | n/a | list(z) |

1528 | n/a | mymap['blue'] = 7 # Shouldn't affect 'z' |

1529 | n/a | self.assertEqual(sorted(z), [('orange', 3), ('red', 5)]) |

1530 | n/a | |

1531 | n/a | def test_Sequence(self): |

1532 | n/a | for sample in [tuple, list, bytes, str]: |

1533 | n/a | self.assertIsInstance(sample(), Sequence) |

1534 | n/a | self.assertTrue(issubclass(sample, Sequence)) |

1535 | n/a | self.assertIsInstance(range(10), Sequence) |

1536 | n/a | self.assertTrue(issubclass(range, Sequence)) |

1537 | n/a | self.assertIsInstance(memoryview(b""), Sequence) |

1538 | n/a | self.assertTrue(issubclass(memoryview, Sequence)) |

1539 | n/a | self.assertTrue(issubclass(str, Sequence)) |

1540 | n/a | self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', |

1541 | n/a | '__getitem__') |

1542 | n/a | |

1543 | n/a | def test_Sequence_mixins(self): |

1544 | n/a | class SequenceSubclass(Sequence): |

1545 | n/a | def __init__(self, seq=()): |

1546 | n/a | self.seq = seq |

1547 | n/a | |

1548 | n/a | def __getitem__(self, index): |

1549 | n/a | return self.seq[index] |

1550 | n/a | |

1551 | n/a | def __len__(self): |

1552 | n/a | return len(self.seq) |

1553 | n/a | |

1554 | n/a | # Compare Sequence.index() behavior to (list|str).index() behavior |

1555 | n/a | def assert_index_same(seq1, seq2, index_args): |

1556 | n/a | try: |

1557 | n/a | expected = seq1.index(*index_args) |

1558 | n/a | except ValueError: |

1559 | n/a | with self.assertRaises(ValueError): |

1560 | n/a | seq2.index(*index_args) |

1561 | n/a | else: |

1562 | n/a | actual = seq2.index(*index_args) |

1563 | n/a | self.assertEqual( |

1564 | n/a | actual, expected, '%r.index%s' % (seq1, index_args)) |

1565 | n/a | |

1566 | n/a | for ty in list, str: |

1567 | n/a | nativeseq = ty('abracadabra') |

1568 | n/a | indexes = [-10000, -9999] + list(range(-3, len(nativeseq) + 3)) |

1569 | n/a | seqseq = SequenceSubclass(nativeseq) |

1570 | n/a | for letter in set(nativeseq) | {'z'}: |

1571 | n/a | assert_index_same(nativeseq, seqseq, (letter,)) |

1572 | n/a | for start in range(-3, len(nativeseq) + 3): |

1573 | n/a | assert_index_same(nativeseq, seqseq, (letter, start)) |

1574 | n/a | for stop in range(-3, len(nativeseq) + 3): |

1575 | n/a | assert_index_same( |

1576 | n/a | nativeseq, seqseq, (letter, start, stop)) |

1577 | n/a | |

1578 | n/a | def test_ByteString(self): |

1579 | n/a | for sample in [bytes, bytearray]: |

1580 | n/a | self.assertIsInstance(sample(), ByteString) |

1581 | n/a | self.assertTrue(issubclass(sample, ByteString)) |

1582 | n/a | for sample in [str, list, tuple]: |

1583 | n/a | self.assertNotIsInstance(sample(), ByteString) |

1584 | n/a | self.assertFalse(issubclass(sample, ByteString)) |

1585 | n/a | self.assertNotIsInstance(memoryview(b""), ByteString) |

1586 | n/a | self.assertFalse(issubclass(memoryview, ByteString)) |

1587 | n/a | |

1588 | n/a | def test_MutableSequence(self): |

1589 | n/a | for sample in [tuple, str, bytes]: |

1590 | n/a | self.assertNotIsInstance(sample(), MutableSequence) |

1591 | n/a | self.assertFalse(issubclass(sample, MutableSequence)) |

1592 | n/a | for sample in [list, bytearray, deque]: |

1593 | n/a | self.assertIsInstance(sample(), MutableSequence) |

1594 | n/a | self.assertTrue(issubclass(sample, MutableSequence)) |

1595 | n/a | self.assertFalse(issubclass(str, MutableSequence)) |

1596 | n/a | self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', |

1597 | n/a | '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') |

1598 | n/a | |

1599 | n/a | def test_MutableSequence_mixins(self): |

1600 | n/a | # Test the mixins of MutableSequence by creating a miminal concrete |

1601 | n/a | # class inherited from it. |

1602 | n/a | class MutableSequenceSubclass(MutableSequence): |

1603 | n/a | def __init__(self): |

1604 | n/a | self.lst = [] |

1605 | n/a | |

1606 | n/a | def __setitem__(self, index, value): |

1607 | n/a | self.lst[index] = value |

1608 | n/a | |

1609 | n/a | def __getitem__(self, index): |

1610 | n/a | return self.lst[index] |

1611 | n/a | |

1612 | n/a | def __len__(self): |

1613 | n/a | return len(self.lst) |

1614 | n/a | |

1615 | n/a | def __delitem__(self, index): |

1616 | n/a | del self.lst[index] |

1617 | n/a | |

1618 | n/a | def insert(self, index, value): |

1619 | n/a | self.lst.insert(index, value) |

1620 | n/a | |

1621 | n/a | mss = MutableSequenceSubclass() |

1622 | n/a | mss.append(0) |

1623 | n/a | mss.extend((1, 2, 3, 4)) |

1624 | n/a | self.assertEqual(len(mss), 5) |

1625 | n/a | self.assertEqual(mss[3], 3) |

1626 | n/a | mss.reverse() |

1627 | n/a | self.assertEqual(mss[3], 1) |

1628 | n/a | mss.pop() |

1629 | n/a | self.assertEqual(len(mss), 4) |

1630 | n/a | mss.remove(3) |

1631 | n/a | self.assertEqual(len(mss), 3) |

1632 | n/a | mss += (10, 20, 30) |

1633 | n/a | self.assertEqual(len(mss), 6) |

1634 | n/a | self.assertEqual(mss[-1], 30) |

1635 | n/a | mss.clear() |

1636 | n/a | self.assertEqual(len(mss), 0) |

1637 | n/a | |

1638 | n/a | ################################################################################ |

1639 | n/a | ### Counter |

1640 | n/a | ################################################################################ |

1641 | n/a | |

1642 | n/a | class CounterSubclassWithSetItem(Counter): |

1643 | n/a | # Test a counter subclass that overrides __setitem__ |

1644 | n/a | def __init__(self, *args, **kwds): |

1645 | n/a | self.called = False |

1646 | n/a | Counter.__init__(self, *args, **kwds) |

1647 | n/a | def __setitem__(self, key, value): |

1648 | n/a | self.called = True |

1649 | n/a | Counter.__setitem__(self, key, value) |

1650 | n/a | |

1651 | n/a | class CounterSubclassWithGet(Counter): |

1652 | n/a | # Test a counter subclass that overrides get() |

1653 | n/a | def __init__(self, *args, **kwds): |

1654 | n/a | self.called = False |

1655 | n/a | Counter.__init__(self, *args, **kwds) |

1656 | n/a | def get(self, key, default): |

1657 | n/a | self.called = True |

1658 | n/a | return Counter.get(self, key, default) |

1659 | n/a | |

1660 | n/a | class TestCounter(unittest.TestCase): |

1661 | n/a | |

1662 | n/a | def test_basics(self): |

1663 | n/a | c = Counter('abcaba') |

1664 | n/a | self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) |

1665 | n/a | self.assertEqual(c, Counter(a=3, b=2, c=1)) |

1666 | n/a | self.assertIsInstance(c, dict) |

1667 | n/a | self.assertIsInstance(c, Mapping) |

1668 | n/a | self.assertTrue(issubclass(Counter, dict)) |

1669 | n/a | self.assertTrue(issubclass(Counter, Mapping)) |

1670 | n/a | self.assertEqual(len(c), 3) |

1671 | n/a | self.assertEqual(sum(c.values()), 6) |

1672 | n/a | self.assertEqual(sorted(c.values()), [1, 2, 3]) |

1673 | n/a | self.assertEqual(sorted(c.keys()), ['a', 'b', 'c']) |

1674 | n/a | self.assertEqual(sorted(c), ['a', 'b', 'c']) |

1675 | n/a | self.assertEqual(sorted(c.items()), |

1676 | n/a | [('a', 3), ('b', 2), ('c', 1)]) |

1677 | n/a | self.assertEqual(c['b'], 2) |

1678 | n/a | self.assertEqual(c['z'], 0) |

1679 | n/a | self.assertEqual(c.__contains__('c'), True) |

1680 | n/a | self.assertEqual(c.__contains__('z'), False) |

1681 | n/a | self.assertEqual(c.get('b', 10), 2) |

1682 | n/a | self.assertEqual(c.get('z', 10), 10) |

1683 | n/a | self.assertEqual(c, dict(a=3, b=2, c=1)) |

1684 | n/a | self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") |

1685 | n/a | self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)]) |

1686 | n/a | for i in range(5): |

1687 | n/a | self.assertEqual(c.most_common(i), |

1688 | n/a | [('a', 3), ('b', 2), ('c', 1)][:i]) |

1689 | n/a | self.assertEqual(''.join(sorted(c.elements())), 'aaabbc') |

1690 | n/a | c['a'] += 1 # increment an existing value |

1691 | n/a | c['b'] -= 2 # sub existing value to zero |

1692 | n/a | del c['c'] # remove an entry |

1693 | n/a | del c['c'] # make sure that del doesn't raise KeyError |

1694 | n/a | c['d'] -= 2 # sub from a missing value |

1695 | n/a | c['e'] = -5 # directly assign a missing value |

1696 | n/a | c['f'] += 4 # add to a missing value |

1697 | n/a | self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) |

1698 | n/a | self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') |

1699 | n/a | self.assertEqual(c.pop('f'), 4) |

1700 | n/a | self.assertNotIn('f', c) |

1701 | n/a | for i in range(3): |

1702 | n/a | elem, cnt = c.popitem() |

1703 | n/a | self.assertNotIn(elem, c) |

1704 | n/a | c.clear() |

1705 | n/a | self.assertEqual(c, {}) |

1706 | n/a | self.assertEqual(repr(c), 'Counter()') |

1707 | n/a | self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc') |

1708 | n/a | self.assertRaises(TypeError, hash, c) |

1709 | n/a | c.update(dict(a=5, b=3)) |

1710 | n/a | c.update(c=1) |

1711 | n/a | c.update(Counter('a' * 50 + 'b' * 30)) |

1712 | n/a | c.update() # test case with no args |

1713 | n/a | c.__init__('a' * 500 + 'b' * 300) |

1714 | n/a | c.__init__('cdc') |

1715 | n/a | c.__init__() |

1716 | n/a | self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) |

1717 | n/a | self.assertEqual(c.setdefault('d', 5), 1) |

1718 | n/a | self.assertEqual(c['d'], 1) |

1719 | n/a | self.assertEqual(c.setdefault('e', 5), 5) |

1720 | n/a | self.assertEqual(c['e'], 5) |

1721 | n/a | |

1722 | n/a | def test_init(self): |

1723 | n/a | self.assertEqual(list(Counter(self=42).items()), [('self', 42)]) |

1724 | n/a | self.assertEqual(list(Counter(iterable=42).items()), [('iterable', 42)]) |

1725 | n/a | self.assertEqual(list(Counter(iterable=None).items()), [('iterable', None)]) |

1726 | n/a | self.assertRaises(TypeError, Counter, 42) |

1727 | n/a | self.assertRaises(TypeError, Counter, (), ()) |

1728 | n/a | self.assertRaises(TypeError, Counter.__init__) |

1729 | n/a | |

1730 | n/a | def test_update(self): |

1731 | n/a | c = Counter() |

1732 | n/a | c.update(self=42) |

1733 | n/a | self.assertEqual(list(c.items()), [('self', 42)]) |

1734 | n/a | c = Counter() |

1735 | n/a | c.update(iterable=42) |

1736 | n/a | self.assertEqual(list(c.items()), [('iterable', 42)]) |

1737 | n/a | c = Counter() |

1738 | n/a | c.update(iterable=None) |

1739 | n/a | self.assertEqual(list(c.items()), [('iterable', None)]) |

1740 | n/a | self.assertRaises(TypeError, Counter().update, 42) |

1741 | n/a | self.assertRaises(TypeError, Counter().update, {}, {}) |

1742 | n/a | self.assertRaises(TypeError, Counter.update) |

1743 | n/a | |

1744 | n/a | def test_copying(self): |

1745 | n/a | # Check that counters are copyable, deepcopyable, picklable, and |

1746 | n/a | #have a repr/eval round-trip |

1747 | n/a | words = Counter('which witch had which witches wrist watch'.split()) |

1748 | n/a | def check(dup): |

1749 | n/a | msg = "\ncopy: %s\nwords: %s" % (dup, words) |

1750 | n/a | self.assertIsNot(dup, words, msg) |

1751 | n/a | self.assertEqual(dup, words) |

1752 | n/a | check(words.copy()) |

1753 | n/a | check(copy.copy(words)) |

1754 | n/a | check(copy.deepcopy(words)) |

1755 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |

1756 | n/a | with self.subTest(proto=proto): |

1757 | n/a | check(pickle.loads(pickle.dumps(words, proto))) |

1758 | n/a | check(eval(repr(words))) |

1759 | n/a | update_test = Counter() |

1760 | n/a | update_test.update(words) |

1761 | n/a | check(update_test) |

1762 | n/a | check(Counter(words)) |

1763 | n/a | |

1764 | n/a | def test_copy_subclass(self): |

1765 | n/a | class MyCounter(Counter): |

1766 | n/a | pass |

1767 | n/a | c = MyCounter('slartibartfast') |

1768 | n/a | d = c.copy() |

1769 | n/a | self.assertEqual(d, c) |

1770 | n/a | self.assertEqual(len(d), len(c)) |

1771 | n/a | self.assertEqual(type(d), type(c)) |

1772 | n/a | |

1773 | n/a | def test_conversions(self): |

1774 | n/a | # Convert to: set, list, dict |

1775 | n/a | s = 'she sells sea shells by the sea shore' |

1776 | n/a | self.assertEqual(sorted(Counter(s).elements()), sorted(s)) |

1777 | n/a | self.assertEqual(sorted(Counter(s)), sorted(set(s))) |

1778 | n/a | self.assertEqual(dict(Counter(s)), dict(Counter(s).items())) |

1779 | n/a | self.assertEqual(set(Counter(s)), set(s)) |

1780 | n/a | |

1781 | n/a | def test_invariant_for_the_in_operator(self): |

1782 | n/a | c = Counter(a=10, b=-2, c=0) |

1783 | n/a | for elem in c: |

1784 | n/a | self.assertTrue(elem in c) |

1785 | n/a | self.assertIn(elem, c) |

1786 | n/a | |

1787 | n/a | def test_multiset_operations(self): |

1788 | n/a | # Verify that adding a zero counter will strip zeros and negatives |

1789 | n/a | c = Counter(a=10, b=-2, c=0) + Counter() |

1790 | n/a | self.assertEqual(dict(c), dict(a=10)) |

1791 | n/a | |

1792 | n/a | elements = 'abcd' |

1793 | n/a | for i in range(1000): |

1794 | n/a | # test random pairs of multisets |

1795 | n/a | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |

1796 | n/a | p.update(e=1, f=-1, g=0) |

1797 | n/a | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |

1798 | n/a | q.update(h=1, i=-1, j=0) |

1799 | n/a | for counterop, numberop in [ |

1800 | n/a | (Counter.__add__, lambda x, y: max(0, x+y)), |

1801 | n/a | (Counter.__sub__, lambda x, y: max(0, x-y)), |

1802 | n/a | (Counter.__or__, lambda x, y: max(0,x,y)), |

1803 | n/a | (Counter.__and__, lambda x, y: max(0, min(x,y))), |

1804 | n/a | ]: |

1805 | n/a | result = counterop(p, q) |

1806 | n/a | for x in elements: |

1807 | n/a | self.assertEqual(numberop(p[x], q[x]), result[x], |

1808 | n/a | (counterop, x, p, q)) |

1809 | n/a | # verify that results exclude non-positive counts |

1810 | n/a | self.assertTrue(x>0 for x in result.values()) |

1811 | n/a | |

1812 | n/a | elements = 'abcdef' |

1813 | n/a | for i in range(100): |

1814 | n/a | # verify that random multisets with no repeats are exactly like sets |

1815 | n/a | p = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |

1816 | n/a | q = Counter(dict((elem, randrange(0, 2)) for elem in elements)) |

1817 | n/a | for counterop, setop in [ |

1818 | n/a | (Counter.__sub__, set.__sub__), |

1819 | n/a | (Counter.__or__, set.__or__), |

1820 | n/a | (Counter.__and__, set.__and__), |

1821 | n/a | ]: |

1822 | n/a | counter_result = counterop(p, q) |

1823 | n/a | set_result = setop(set(p.elements()), set(q.elements())) |

1824 | n/a | self.assertEqual(counter_result, dict.fromkeys(set_result, 1)) |

1825 | n/a | |

1826 | n/a | def test_inplace_operations(self): |

1827 | n/a | elements = 'abcd' |

1828 | n/a | for i in range(1000): |

1829 | n/a | # test random pairs of multisets |

1830 | n/a | p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |

1831 | n/a | p.update(e=1, f=-1, g=0) |

1832 | n/a | q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) |

1833 | n/a | q.update(h=1, i=-1, j=0) |

1834 | n/a | for inplace_op, regular_op in [ |

1835 | n/a | (Counter.__iadd__, Counter.__add__), |

1836 | n/a | (Counter.__isub__, Counter.__sub__), |

1837 | n/a | (Counter.__ior__, Counter.__or__), |

1838 | n/a | (Counter.__iand__, Counter.__and__), |

1839 | n/a | ]: |

1840 | n/a | c = p.copy() |

1841 | n/a | c_id = id(c) |

1842 | n/a | regular_result = regular_op(c, q) |

1843 | n/a | inplace_result = inplace_op(c, q) |

1844 | n/a | self.assertEqual(inplace_result, regular_result) |

1845 | n/a | self.assertEqual(id(inplace_result), c_id) |

1846 | n/a | |

1847 | n/a | def test_subtract(self): |

1848 | n/a | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |

1849 | n/a | c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50) |

1850 | n/a | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |

1851 | n/a | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |

1852 | n/a | c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)) |

1853 | n/a | self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) |

1854 | n/a | c = Counter('aaabbcd') |

1855 | n/a | c.subtract('aaaabbcce') |

1856 | n/a | self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1)) |

1857 | n/a | |

1858 | n/a | c = Counter() |

1859 | n/a | c.subtract(self=42) |

1860 | n/a | self.assertEqual(list(c.items()), [('self', -42)]) |

1861 | n/a | c = Counter() |

1862 | n/a | c.subtract(iterable=42) |

1863 | n/a | self.assertEqual(list(c.items()), [('iterable', -42)]) |

1864 | n/a | self.assertRaises(TypeError, Counter().subtract, 42) |

1865 | n/a | self.assertRaises(TypeError, Counter().subtract, {}, {}) |

1866 | n/a | self.assertRaises(TypeError, Counter.subtract) |

1867 | n/a | |

1868 | n/a | def test_unary(self): |

1869 | n/a | c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) |

1870 | n/a | self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40)) |

1871 | n/a | self.assertEqual(dict(-c), dict(a=5)) |

1872 | n/a | |

1873 | n/a | def test_repr_nonsortable(self): |

1874 | n/a | c = Counter(a=2, b=None) |

1875 | n/a | r = repr(c) |

1876 | n/a | self.assertIn("'a': 2", r) |

1877 | n/a | self.assertIn("'b': None", r) |

1878 | n/a | |

1879 | n/a | def test_helper_function(self): |

1880 | n/a | # two paths, one for real dicts and one for other mappings |

1881 | n/a | elems = list('abracadabra') |

1882 | n/a | |

1883 | n/a | d = dict() |

1884 | n/a | _count_elements(d, elems) |

1885 | n/a | self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) |

1886 | n/a | |

1887 | n/a | m = OrderedDict() |

1888 | n/a | _count_elements(m, elems) |

1889 | n/a | self.assertEqual(m, |

1890 | n/a | OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])) |

1891 | n/a | |

1892 | n/a | # test fidelity to the pure python version |

1893 | n/a | c = CounterSubclassWithSetItem('abracadabra') |

1894 | n/a | self.assertTrue(c.called) |

1895 | n/a | self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 }) |

1896 | n/a | c = CounterSubclassWithGet('abracadabra') |

1897 | n/a | self.assertTrue(c.called) |

1898 | n/a | self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 }) |

1899 | n/a | |

1900 | n/a | |

1901 | n/a | ################################################################################ |

1902 | n/a | ### Run tests |

1903 | n/a | ################################################################################ |

1904 | n/a | |

1905 | n/a | def test_main(verbose=None): |

1906 | n/a | NamedTupleDocs = doctest.DocTestSuite(module=collections) |

1907 | n/a | test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, |

1908 | n/a | TestCollectionABCs, TestCounter, TestChainMap, |

1909 | n/a | TestUserObjects, |

1910 | n/a | ] |

1911 | n/a | support.run_unittest(*test_classes) |

1912 | n/a | support.run_doctest(collections, verbose) |

1913 | n/a | |

1914 | n/a | |

1915 | n/a | if __name__ == "__main__": |

1916 | n/a | test_main(verbose=True) |