Debian Codegraph @

Lib/test/test_types.py

raw
1 # Python test set -- part 6, built-in types
2
3 from test.support import (
4 run_with_locale, is_apple_mobile, cpython_only,
5 iter_builtin_types, iter_slot_wrappers,
6 MISSING_C_DOCSTRINGS,
7 )
8 from test.test_import import no_rerun
9 from test.support.script_helper import assert_python_ok
10 from test.support.import_helper import import_fresh_module
11
12 import collections.abc
13 from collections import namedtuple, UserDict
14 import copy
15 import _datetime
16 import gc
17 import inspect
18 import pickle
19 import locale
20 import sys
21 import textwrap
22 import types
23 import unittest.mock
24 import weakref
25 import typing
26
27
28 T = typing.TypeVar("T")
29
30 class Example:
31 pass
32
33 class Forward: ...
34
35 def clear_typing_caches():
36 for f in typing._cleanups:
37 f()
38
39
40 class TypesTests(unittest.TestCase):
41
42 def test_truth_values(self):
43 if None: self.fail('None is true instead of false')
44 if 0: self.fail('0 is true instead of false')
45 if 0.0: self.fail('0.0 is true instead of false')
46 if '': self.fail('\'\' is true instead of false')
47 if not 1: self.fail('1 is false instead of true')
48 if not 1.0: self.fail('1.0 is false instead of true')
49 if not 'x': self.fail('\'x\' is false instead of true')
50 if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true')
51 def f(): pass
52 class C: pass
53 x = C()
54 if not f: self.fail('f is false instead of true')
55 if not C: self.fail('C is false instead of true')
56 if not sys: self.fail('sys is false instead of true')
57 if not x: self.fail('x is false instead of true')
58
59 def test_boolean_ops(self):
60 if 0 or 0: self.fail('0 or 0 is true instead of false')
61 if 1 and 1: pass
62 else: self.fail('1 and 1 is false instead of true')
63 if not 1: self.fail('not 1 is true instead of false')
64
65 def test_comparisons(self):
66 if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
67 else: self.fail('int comparisons failed')
68 if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass
69 else: self.fail('float comparisons failed')
70 if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass
71 else: self.fail('string comparisons failed')
72 if None is None: pass
73 else: self.fail('identity test failed')
74
75 def test_float_constructor(self):
76 self.assertRaises(ValueError, float, '')
77 self.assertRaises(ValueError, float, '5\0')
78 self.assertRaises(ValueError, float, '5_5\0')
79
80 def test_zero_division(self):
81 try: 5.0 / 0.0
82 except ZeroDivisionError: pass
83 else: self.fail("5.0 / 0.0 didn't raise ZeroDivisionError")
84
85 try: 5.0 // 0.0
86 except ZeroDivisionError: pass
87 else: self.fail("5.0 // 0.0 didn't raise ZeroDivisionError")
88
89 try: 5.0 % 0.0
90 except ZeroDivisionError: pass
91 else: self.fail("5.0 % 0.0 didn't raise ZeroDivisionError")
92
93 try: 5 / 0
94 except ZeroDivisionError: pass
95 else: self.fail("5 / 0 didn't raise ZeroDivisionError")
96
97 try: 5 // 0
98 except ZeroDivisionError: pass
99 else: self.fail("5 // 0 didn't raise ZeroDivisionError")
100
101 try: 5 % 0
102 except ZeroDivisionError: pass
103 else: self.fail("5 % 0 didn't raise ZeroDivisionError")
104
105 def test_numeric_types(self):
106 if 0 != 0.0 or 1 != 1.0 or -1 != -1.0:
107 self.fail('int/float value not equal')
108 # calling built-in types without argument must return 0
109 if int() != 0: self.fail('int() does not return 0')
110 if float() != 0.0: self.fail('float() does not return 0.0')
111 if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
112 else: self.fail('int() does not round properly')
113 if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
114 else: self.fail('float() does not work properly')
115
116 def test_float_to_string(self):
117 def test(f, result):
118 self.assertEqual(f.__format__('e'), result)
119 self.assertEqual('%e' % f, result)
120
121 # test all 2 digit exponents, both with __format__ and with
122 # '%' formatting
123 for i in range(-99, 100):
124 test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i))
125
126 # test some 3 digit exponents
127 self.assertEqual(1.5e100.__format__('e'), '1.500000e+100')
128 self.assertEqual('%e' % 1.5e100, '1.500000e+100')
129
130 self.assertEqual(1.5e101.__format__('e'), '1.500000e+101')
131 self.assertEqual('%e' % 1.5e101, '1.500000e+101')
132
133 self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100')
134 self.assertEqual('%e' % 1.5e-100, '1.500000e-100')
135
136 self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101')
137 self.assertEqual('%e' % 1.5e-101, '1.500000e-101')
138
139 self.assertEqual('%g' % 1.0, '1')
140 self.assertEqual('%#g' % 1.0, '1.00000')
141
142 def test_normal_integers(self):
143 # Ensure the first 256 integers are shared
144 a = 256
145 b = 128*2
146 if a is not b: self.fail('256 is not shared')
147 if 12 + 24 != 36: self.fail('int op')
148 if 12 + (-24) != -12: self.fail('int op')
149 if (-12) + 24 != 12: self.fail('int op')
150 if (-12) + (-24) != -36: self.fail('int op')
151 if not 12 < 24: self.fail('int op')
152 if not -24 < -12: self.fail('int op')
153 # Test for a particular bug in integer multiply
154 xsize, ysize, zsize = 238, 356, 4
155 if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912):
156 self.fail('int mul commutativity')
157 # And another.
158 m = -sys.maxsize - 1
159 for divisor in 1, 2, 4, 8, 16, 32:
160 j = m // divisor
161 prod = divisor * j
162 if prod != m:
163 self.fail("%r * %r == %r != %r" % (divisor, j, prod, m))
164 if type(prod) is not int:
165 self.fail("expected type(prod) to be int, not %r" %
166 type(prod))
167 # Check for unified integral type
168 for divisor in 1, 2, 4, 8, 16, 32:
169 j = m // divisor - 1
170 prod = divisor * j
171 if type(prod) is not int:
172 self.fail("expected type(%r) to be int, not %r" %
173 (prod, type(prod)))
174 # Check for unified integral type
175 m = sys.maxsize
176 for divisor in 1, 2, 4, 8, 16, 32:
177 j = m // divisor + 1
178 prod = divisor * j
179 if type(prod) is not int:
180 self.fail("expected type(%r) to be int, not %r" %
181 (prod, type(prod)))
182
183 x = sys.maxsize
184 self.assertIsInstance(x + 1, int,
185 "(sys.maxsize + 1) should have returned int")
186 self.assertIsInstance(-x - 1, int,
187 "(-sys.maxsize - 1) should have returned int")
188 self.assertIsInstance(-x - 2, int,
189 "(-sys.maxsize - 2) should have returned int")
190
191 try: 5 << -5
192 except ValueError: pass
193 else: self.fail('int negative shift <<')
194
195 try: 5 >> -5
196 except ValueError: pass
197 else: self.fail('int negative shift >>')
198
199 def test_floats(self):
200 if 12.0 + 24.0 != 36.0: self.fail('float op')
201 if 12.0 + (-24.0) != -12.0: self.fail('float op')
202 if (-12.0) + 24.0 != 12.0: self.fail('float op')
203 if (-12.0) + (-24.0) != -36.0: self.fail('float op')
204 if not 12.0 < 24.0: self.fail('float op')
205 if not -24.0 < -12.0: self.fail('float op')
206
207 def test_strings(self):
208 if len('') != 0: self.fail('len(\'\')')
209 if len('a') != 1: self.fail('len(\'a\')')
210 if len('abcdef') != 6: self.fail('len(\'abcdef\')')
211 if 'xyz' + 'abcde' != 'xyzabcde': self.fail('string concatenation')
212 if 'xyz'*3 != 'xyzxyzxyz': self.fail('string repetition *3')
213 if 0*'abcde' != '': self.fail('string repetition 0*')
214 if min('abc') != 'a' or max('abc') != 'c': self.fail('min/max string')
215 if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass
216 else: self.fail('in/not in string')
217 x = 'x'*103
218 if '%s!'%x != x+'!': self.fail('nasty string formatting bug')
219
220 #extended slices for strings
221 a = '0123456789'
222 self.assertEqual(a[::], a)
223 self.assertEqual(a[::2], '02468')
224 self.assertEqual(a[1::2], '13579')
225 self.assertEqual(a[::-1],'9876543210')
226 self.assertEqual(a[::-2], '97531')
227 self.assertEqual(a[3::-2], '31')
228 self.assertEqual(a[-100:100:], a)
229 self.assertEqual(a[100:-100:-1], a[::-1])
230 self.assertEqual(a[-100:100:2], '02468')
231
232 def test_type_function(self):
233 self.assertRaises(TypeError, type, 1, 2)
234 self.assertRaises(TypeError, type, 1, 2, 3, 4)
235
236 def test_int__format__(self):
237 def test(i, format_spec, result):
238 # just make sure we have the unified type for integers
239 self.assertIs(type(i), int)
240 self.assertIs(type(format_spec), str)
241 self.assertEqual(i.__format__(format_spec), result)
242
243 test(123456789, 'd', '123456789')
244 test(123456789, 'd', '123456789')
245
246 test(1, 'c', '\01')
247
248 # sign and aligning are interdependent
249 test(1, "-", '1')
250 test(-1, "-", '-1')
251 test(1, "-3", ' 1')
252 test(-1, "-3", ' -1')
253 test(1, "+3", ' +1')
254 test(-1, "+3", ' -1')
255 test(1, " 3", ' 1')
256 test(-1, " 3", ' -1')
257 test(1, " ", ' 1')
258 test(-1, " ", '-1')
259
260 # hex
261 test(3, "x", "3")
262 test(3, "X", "3")
263 test(1234, "x", "4d2")
264 test(-1234, "x", "-4d2")
265 test(1234, "8x", " 4d2")
266 test(-1234, "8x", " -4d2")
267 test(1234, "x", "4d2")
268 test(-1234, "x", "-4d2")
269 test(-3, "x", "-3")
270 test(-3, "X", "-3")
271 test(int('be', 16), "x", "be")
272 test(int('be', 16), "X", "BE")
273 test(-int('be', 16), "x", "-be")
274 test(-int('be', 16), "X", "-BE")
275
276 # octal
277 test(3, "o", "3")
278 test(-3, "o", "-3")
279 test(65, "o", "101")
280 test(-65, "o", "-101")
281 test(1234, "o", "2322")
282 test(-1234, "o", "-2322")
283 test(1234, "-o", "2322")
284 test(-1234, "-o", "-2322")
285 test(1234, " o", " 2322")
286 test(-1234, " o", "-2322")
287 test(1234, "+o", "+2322")
288 test(-1234, "+o", "-2322")
289
290 # binary
291 test(3, "b", "11")
292 test(-3, "b", "-11")
293 test(1234, "b", "10011010010")
294 test(-1234, "b", "-10011010010")
295 test(1234, "-b", "10011010010")
296 test(-1234, "-b", "-10011010010")
297 test(1234, " b", " 10011010010")
298 test(-1234, " b", "-10011010010")
299 test(1234, "+b", "+10011010010")
300 test(-1234, "+b", "-10011010010")
301
302 # alternate (#) formatting
303 test(0, "#b", '0b0')
304 test(0, "-#b", '0b0')
305 test(1, "-#b", '0b1')
306 test(-1, "-#b", '-0b1')
307 test(-1, "-#5b", ' -0b1')
308 test(1, "+#5b", ' +0b1')
309 test(100, "+#b", '+0b1100100')
310 test(100, "#012b", '0b0001100100')
311 test(-100, "#012b", '-0b001100100')
312
313 test(0, "#o", '0o0')
314 test(0, "-#o", '0o0')
315 test(1, "-#o", '0o1')
316 test(-1, "-#o", '-0o1')
317 test(-1, "-#5o", ' -0o1')
318 test(1, "+#5o", ' +0o1')
319 test(100, "+#o", '+0o144')
320 test(100, "#012o", '0o0000000144')
321 test(-100, "#012o", '-0o000000144')
322
323 test(0, "#x", '0x0')
324 test(0, "-#x", '0x0')
325 test(1, "-#x", '0x1')
326 test(-1, "-#x", '-0x1')
327 test(-1, "-#5x", ' -0x1')
328 test(1, "+#5x", ' +0x1')
329 test(100, "+#x", '+0x64')
330 test(100, "#012x", '0x0000000064')
331 test(-100, "#012x", '-0x000000064')
332 test(123456, "#012x", '0x000001e240')
333 test(-123456, "#012x", '-0x00001e240')
334
335 test(0, "#X", '0X0')
336 test(0, "-#X", '0X0')
337 test(1, "-#X", '0X1')
338 test(-1, "-#X", '-0X1')
339 test(-1, "-#5X", ' -0X1')
340 test(1, "+#5X", ' +0X1')
341 test(100, "+#X", '+0X64')
342 test(100, "#012X", '0X0000000064')
343 test(-100, "#012X", '-0X000000064')
344 test(123456, "#012X", '0X000001E240')
345 test(-123456, "#012X", '-0X00001E240')
346
347 test(123, ',', '123')
348 test(-123, ',', '-123')
349 test(1234, ',', '1,234')
350 test(-1234, ',', '-1,234')
351 test(123456, ',', '123,456')
352 test(-123456, ',', '-123,456')
353 test(1234567, ',', '1,234,567')
354 test(-1234567, ',', '-1,234,567')
355
356 # issue 5782, commas with no specifier type
357 test(1234, '010,', '00,001,234')
358
359 # Unified type for integers
360 test(10**100, 'd', '1' + '0' * 100)
361 test(10**100+100, 'd', '1' + '0' * 97 + '100')
362
363 # make sure these are errors
364
365 # precision disallowed
366 self.assertRaises(ValueError, 3 .__format__, "1.3")
367 # sign not allowed with 'c'
368 self.assertRaises(ValueError, 3 .__format__, "+c")
369 # format spec must be string
370 self.assertRaises(TypeError, 3 .__format__, None)
371 self.assertRaises(TypeError, 3 .__format__, 0)
372 # can't have ',' with 'n'
373 self.assertRaises(ValueError, 3 .__format__, ",n")
374 # can't have ',' with 'c'
375 self.assertRaises(ValueError, 3 .__format__, ",c")
376 # can't have '#' with 'c'
377 self.assertRaises(ValueError, 3 .__format__, "#c")
378
379 # ensure that only int and float type specifiers work
380 for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
381 [chr(x) for x in range(ord('A'), ord('Z')+1)]):
382 if not format_spec in 'bcdoxXeEfFgGn%':
383 self.assertRaises(ValueError, 0 .__format__, format_spec)
384 self.assertRaises(ValueError, 1 .__format__, format_spec)
385 self.assertRaises(ValueError, (-1) .__format__, format_spec)
386
387 # ensure that float type specifiers work; format converts
388 # the int to a float
389 for format_spec in 'eEfFgG%':
390 for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
391 self.assertEqual(value.__format__(format_spec),
392 float(value).__format__(format_spec))
393
394 # Issue 6902
395 test(123456, "0<20", '12345600000000000000')
396 test(123456, "1<20", '12345611111111111111')
397 test(123456, "*<20", '123456**************')
398 test(123456, "0>20", '00000000000000123456')
399 test(123456, "1>20", '11111111111111123456')
400 test(123456, "*>20", '**************123456')
401 test(123456, "0=20", '00000000000000123456')
402 test(123456, "1=20", '11111111111111123456')
403 test(123456, "*=20", '**************123456')
404
405 @run_with_locale('LC_NUMERIC', 'en_US.UTF8', '')
406 def test_float__format__locale(self):
407 # test locale support for __format__ code 'n'
408
409 for i in range(-10, 10):
410 x = 1234567890.0 * (10.0 ** i)
411 self.assertEqual(locale.format_string('%g', x, grouping=True), format(x, 'n'))
412 self.assertEqual(locale.format_string('%.10g', x, grouping=True), format(x, '.10n'))
413
414 @run_with_locale('LC_NUMERIC', 'en_US.UTF8', '')
415 def test_int__format__locale(self):
416 # test locale support for __format__ code 'n' for integers
417
418 x = 123456789012345678901234567890
419 for i in range(0, 30):
420 self.assertEqual(locale.format_string('%d', x, grouping=True), format(x, 'n'))
421
422 # move to the next integer to test
423 x = x // 10
424
425 rfmt = ">20n"
426 lfmt = "<20n"
427 cfmt = "^20n"
428 for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900):
429 self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt)))
430 self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt)))
431 self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
432
433 def test_float__format__(self):
434 def test(f, format_spec, result):
435 self.assertEqual(f.__format__(format_spec), result)
436 self.assertEqual(format(f, format_spec), result)
437
438 test(0.0, 'f', '0.000000')
439
440 # the default is 'g', except for empty format spec
441 test(0.0, '', '0.0')
442 test(0.01, '', '0.01')
443 test(0.01, 'g', '0.01')
444
445 # test for issue 3411
446 test(1.23, '1', '1.23')
447 test(-1.23, '1', '-1.23')
448 test(1.23, '1g', '1.23')
449 test(-1.23, '1g', '-1.23')
450
451 test( 1.0, ' g', ' 1')
452 test(-1.0, ' g', '-1')
453 test( 1.0, '+g', '+1')
454 test(-1.0, '+g', '-1')
455 test(1.1234e200, 'g', '1.1234e+200')
456 test(1.1234e200, 'G', '1.1234E+200')
457
458
459 test(1.0, 'f', '1.000000')
460
461 test(-1.0, 'f', '-1.000000')
462
463 test( 1.0, ' f', ' 1.000000')
464 test(-1.0, ' f', '-1.000000')
465 test( 1.0, '+f', '+1.000000')
466 test(-1.0, '+f', '-1.000000')
467
468 # Python versions <= 3.0 switched from 'f' to 'g' formatting for
469 # values larger than 1e50. No longer.
470 f = 1.1234e90
471 for fmt in 'f', 'F':
472 # don't do a direct equality check, since on some
473 # platforms only the first few digits of dtoa
474 # will be reliable
475 result = f.__format__(fmt)
476 self.assertEqual(len(result), 98)
477 self.assertEqual(result[-7], '.')
478 self.assertIn(result[:12], ('112340000000', '112339999999'))
479 f = 1.1234e200
480 for fmt in 'f', 'F':
481 result = f.__format__(fmt)
482 self.assertEqual(len(result), 208)
483 self.assertEqual(result[-7], '.')
484 self.assertIn(result[:12], ('112340000000', '112339999999'))
485
486
487 test( 1.0, 'e', '1.000000e+00')
488 test(-1.0, 'e', '-1.000000e+00')
489 test( 1.0, 'E', '1.000000E+00')
490 test(-1.0, 'E', '-1.000000E+00')
491 test(1.1234e20, 'e', '1.123400e+20')
492 test(1.1234e20, 'E', '1.123400E+20')
493
494 # No format code means use g, but must have a decimal
495 # and a number after the decimal. This is tricky, because
496 # a totally empty format specifier means something else.
497 # So, just use a sign flag
498 test(1.25e200, '+g', '+1.25e+200')
499 test(1.25e200, '+', '+1.25e+200')
500
501 test(1.1e200, '+g', '+1.1e+200')
502 test(1.1e200, '+', '+1.1e+200')
503
504 # 0 padding
505 test(1234., '010f', '1234.000000')
506 test(1234., '011f', '1234.000000')
507 test(1234., '012f', '01234.000000')
508 test(-1234., '011f', '-1234.000000')
509 test(-1234., '012f', '-1234.000000')
510 test(-1234., '013f', '-01234.000000')
511 test(-1234.12341234, '013f', '-01234.123412')
512 test(-123456.12341234, '011.2f', '-0123456.12')
513
514 # issue 5782, commas with no specifier type
515 test(1.2, '010,.2', '0,000,001.2')
516
517 # 0 padding with commas
518 test(1234., '011,f', '1,234.000000')
519 test(1234., '012,f', '1,234.000000')
520 test(1234., '013,f', '01,234.000000')
521 test(-1234., '012,f', '-1,234.000000')
522 test(-1234., '013,f', '-1,234.000000')
523 test(-1234., '014,f', '-01,234.000000')
524 test(-12345., '015,f', '-012,345.000000')
525 test(-123456., '016,f', '-0,123,456.000000')
526 test(-123456., '017,f', '-0,123,456.000000')
527 test(-123456.12341234, '017,f', '-0,123,456.123412')
528 test(-123456.12341234, '013,.2f', '-0,123,456.12')
529
530 # % formatting
531 test(-1.0, '%', '-100.000000%')
532
533 # format spec must be string
534 self.assertRaises(TypeError, 3.0.__format__, None)
535 self.assertRaises(TypeError, 3.0.__format__, 0)
536
537 # confirm format options expected to fail on floats, such as integer
538 # presentation types
539 for format_spec in 'sbcdoxX':
540 self.assertRaises(ValueError, format, 0.0, format_spec)
541 self.assertRaises(ValueError, format, 1.0, format_spec)
542 self.assertRaises(ValueError, format, -1.0, format_spec)
543 self.assertRaises(ValueError, format, 1e100, format_spec)
544 self.assertRaises(ValueError, format, -1e100, format_spec)
545 self.assertRaises(ValueError, format, 1e-100, format_spec)
546 self.assertRaises(ValueError, format, -1e-100, format_spec)
547
548 # Alternate float formatting
549 test(1.0, '.0e', '1e+00')
550 test(1.0, '#.0e', '1.e+00')
551 test(1.0, '.0f', '1')
552 test(1.0, '#.0f', '1.')
553 test(1.1, 'g', '1.1')
554 test(1.1, '#g', '1.10000')
555 test(1.0, '.0%', '100%')
556 test(1.0, '#.0%', '100.%')
557
558 # Issue 7094: Alternate formatting (specified by #)
559 test(1.0, '0e', '1.000000e+00')
560 test(1.0, '#0e', '1.000000e+00')
561 test(1.0, '0f', '1.000000' )
562 test(1.0, '#0f', '1.000000')
563 test(1.0, '.1e', '1.0e+00')
564 test(1.0, '#.1e', '1.0e+00')
565 test(1.0, '.1f', '1.0')
566 test(1.0, '#.1f', '1.0')
567 test(1.0, '.1%', '100.0%')
568 test(1.0, '#.1%', '100.0%')
569
570 # Issue 6902
571 test(12345.6, "0<20", '12345.60000000000000')
572 test(12345.6, "1<20", '12345.61111111111111')
573 test(12345.6, "*<20", '12345.6*************')
574 test(12345.6, "0>20", '000000000000012345.6')
575 test(12345.6, "1>20", '111111111111112345.6')
576 test(12345.6, "*>20", '*************12345.6')
577 test(12345.6, "0=20", '000000000000012345.6')
578 test(12345.6, "1=20", '111111111111112345.6')
579 test(12345.6, "*=20", '*************12345.6')
580
581 def test_format_spec_errors(self):
582 # int, float, and string all share the same format spec
583 # mini-language parser.
584
585 # Check that we can't ask for too many digits. This is
586 # probably a CPython specific test. It tries to put the width
587 # into a C long.
588 self.assertRaises(ValueError, format, 0, '1'*10000 + 'd')
589
590 # Similar with the precision.
591 self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd')
592
593 # And may as well test both.
594 self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd')
595
596 # Make sure commas aren't allowed with various type codes
597 for code in 'xXobns':
598 self.assertRaises(ValueError, format, 0, ',' + code)
599
600 def test_internal_sizes(self):
601 self.assertGreater(object.__basicsize__, 0)
602 self.assertGreater(tuple.__itemsize__, 0)
603
604 def test_slot_wrapper_types(self):
605 self.assertIsInstance(object.__init__, types.WrapperDescriptorType)
606 self.assertIsInstance(object.__str__, types.WrapperDescriptorType)
607 self.assertIsInstance(object.__lt__, types.WrapperDescriptorType)
608 self.assertIsInstance(int.__lt__, types.WrapperDescriptorType)
609
610 @unittest.skipIf(MISSING_C_DOCSTRINGS,
611 "Signature information for builtins requires docstrings")
612 def test_dunder_get_signature(self):
613 sig = inspect.signature(object.__init__.__get__)
614 self.assertEqual(list(sig.parameters), ["instance", "owner"])
615 # gh-93021: Second parameter is optional
616 self.assertIs(sig.parameters["owner"].default, None)
617
618 def test_method_wrapper_types(self):
619 self.assertIsInstance(object().__init__, types.MethodWrapperType)
620 self.assertIsInstance(object().__str__, types.MethodWrapperType)
621 self.assertIsInstance(object().__lt__, types.MethodWrapperType)
622 self.assertIsInstance((42).__lt__, types.MethodWrapperType)
623
624 def test_method_descriptor_types(self):
625 self.assertIsInstance(str.join, types.MethodDescriptorType)
626 self.assertIsInstance(list.append, types.MethodDescriptorType)
627 self.assertIsInstance(''.join, types.BuiltinMethodType)
628 self.assertIsInstance([].append, types.BuiltinMethodType)
629
630 self.assertIsInstance(int.__dict__['from_bytes'], types.ClassMethodDescriptorType)
631 self.assertIsInstance(int.from_bytes, types.BuiltinMethodType)
632 self.assertIsInstance(int.__new__, types.BuiltinMethodType)
633
634 def test_method_descriptor_crash(self):
635 # gh-132747: The default __get__() implementation in C was unable
636 # to handle a second argument of None when called from Python
637 import _io
638 import io
639 import _queue
640
641 to_check = [
642 # (method, instance)
643 (_io._TextIOBase.read, io.StringIO()),
644 (_queue.SimpleQueue.put, _queue.SimpleQueue()),
645 (str.capitalize, "nobody expects the spanish inquisition")
646 ]
647
648 for method, instance in to_check:
649 with self.subTest(method=method, instance=instance):
650 bound = method.__get__(instance)
651 self.assertIsInstance(bound, types.BuiltinMethodType)
652
653 def test_ellipsis_type(self):
654 self.assertIsInstance(Ellipsis, types.EllipsisType)
655
656 def test_notimplemented_type(self):
657 self.assertIsInstance(NotImplemented, types.NotImplementedType)
658
659 def test_none_type(self):
660 self.assertIsInstance(None, types.NoneType)
661
662 def test_traceback_and_frame_types(self):
663 try:
664 raise OSError
665 except OSError as e:
666 exc = e
667 self.assertIsInstance(exc.__traceback__, types.TracebackType)
668 self.assertIsInstance(exc.__traceback__.tb_frame, types.FrameType)
669
670 def test_capsule_type(self):
671 self.assertIsInstance(_datetime.datetime_CAPI, types.CapsuleType)
672
673 def test_call_unbound_crash(self):
674 # GH-131998: The specialized instruction would get tricked into dereferencing
675 # a bound "self" that didn't exist if subsequently called unbound.
676 code = """if True:
677
678 def call(part):
679 [] + ([] + [])
680 part.pop()
681
682 for _ in range(3):
683 call(['a'])
684 try:
685 call(list)
686 except TypeError:
687 pass
688 """
689 assert_python_ok("-c", code)
690
691
692 class UnionTests(unittest.TestCase):
693
694 def test_or_types_operator(self):
695 self.assertEqual(int | str, typing.Union[int, str])
696 self.assertNotEqual(int | list, typing.Union[int, str])
697 self.assertEqual(str | int, typing.Union[int, str])
698 self.assertEqual(int | None, typing.Union[int, None])
699 self.assertEqual(None | int, typing.Union[int, None])
700 self.assertEqual(int | type(None), int | None)
701 self.assertEqual(type(None) | int, None | int)
702 self.assertEqual(int | str | list, typing.Union[int, str, list])
703 self.assertEqual(int | (str | list), typing.Union[int, str, list])
704 self.assertEqual(str | (int | list), typing.Union[int, str, list])
705 self.assertEqual(typing.List | typing.Tuple, typing.Union[typing.List, typing.Tuple])
706 self.assertEqual(typing.List[int] | typing.Tuple[int], typing.Union[typing.List[int], typing.Tuple[int]])
707 self.assertEqual(typing.List[int] | None, typing.Union[typing.List[int], None])
708 self.assertEqual(None | typing.List[int], typing.Union[None, typing.List[int]])
709 self.assertEqual(str | float | int | complex | int, (int | str) | (float | complex))
710 self.assertEqual(typing.Union[str, int, typing.List[int]], str | int | typing.List[int])
711 self.assertIs(int | int, int)
712 self.assertEqual(
713 BaseException |
714 bool |
715 bytes |
716 complex |
717 float |
718 int |
719 list |
720 map |
721 set,
722 typing.Union[
723 BaseException,
724 bool,
725 bytes,
726 complex,
727 float,
728 int,
729 list,
730 map,
731 set,
732 ])
733 with self.assertRaises(TypeError):
734 int | 3
735 with self.assertRaises(TypeError):
736 3 | int
737 with self.assertRaises(TypeError):
738 Example() | int
739 x = int | str
740 self.assertEqual(x, int | str)
741 self.assertEqual(x, str | int)
742 self.assertNotEqual(x, {}) # should not raise exception
743 with self.assertRaises(TypeError):
744 x < x
745 with self.assertRaises(TypeError):
746 x <= x
747 y = typing.Union[str, int]
748 with self.assertRaises(TypeError):
749 x < y
750 y = int | bool
751 with self.assertRaises(TypeError):
752 x < y
753 # Check that we don't crash if typing.Union does not have a tuple in __args__
754 y = typing.Union[str, int]
755 y.__args__ = [str, int]
756 self.assertEqual(x, y)
757
758 def test_hash(self):
759 self.assertEqual(hash(int | str), hash(str | int))
760 self.assertEqual(hash(int | str), hash(typing.Union[int, str]))
761
762 def test_union_of_unhashable(self):
763 class UnhashableMeta(type):
764 __hash__ = None
765
766 class A(metaclass=UnhashableMeta): ...
767 class B(metaclass=UnhashableMeta): ...
768
769 self.assertEqual((A | B).__args__, (A, B))
770 union1 = A | B
771 with self.assertRaises(TypeError):
772 hash(union1)
773
774 union2 = int | B
775 with self.assertRaises(TypeError):
776 hash(union2)
777
778 union3 = A | int
779 with self.assertRaises(TypeError):
780 hash(union3)
781
782 def test_instancecheck_and_subclasscheck(self):
783 for x in (int | str, typing.Union[int, str]):
784 with self.subTest(x=x):
785 self.assertIsInstance(1, x)
786 self.assertIsInstance(True, x)
787 self.assertIsInstance('a', x)
788 self.assertNotIsInstance(None, x)
789 self.assertTrue(issubclass(int, x))
790 self.assertTrue(issubclass(bool, x))
791 self.assertTrue(issubclass(str, x))
792 self.assertFalse(issubclass(type(None), x))
793
794 for x in (int | None, typing.Union[int, None]):
795 with self.subTest(x=x):
796 self.assertIsInstance(None, x)
797 self.assertTrue(issubclass(type(None), x))
798
799 for x in (
800 int | collections.abc.Mapping,
801 typing.Union[int, collections.abc.Mapping],
802 ):
803 with self.subTest(x=x):
804 self.assertIsInstance({}, x)
805 self.assertNotIsInstance((), x)
806 self.assertTrue(issubclass(dict, x))
807 self.assertFalse(issubclass(list, x))
808
809 def test_instancecheck_and_subclasscheck_order(self):
810 T = typing.TypeVar('T')
811
812 will_resolve = (
813 int | T,
814 typing.Union[int, T],
815 )
816 for x in will_resolve:
817 with self.subTest(x=x):
818 self.assertIsInstance(1, x)
819 self.assertTrue(issubclass(int, x))
820
821 wont_resolve = (
822 T | int,
823 typing.Union[T, int],
824 )
825 for x in wont_resolve:
826 with self.subTest(x=x):
827 with self.assertRaises(TypeError):
828 issubclass(int, x)
829 with self.assertRaises(TypeError):
830 isinstance(1, x)
831
832 for x in (*will_resolve, *wont_resolve):
833 with self.subTest(x=x):
834 with self.assertRaises(TypeError):
835 issubclass(object, x)
836 with self.assertRaises(TypeError):
837 isinstance(object(), x)
838
839 def test_bad_instancecheck(self):
840 class BadMeta(type):
841 def __instancecheck__(cls, inst):
842 1/0
843 x = int | BadMeta('A', (), {})
844 self.assertTrue(isinstance(1, x))
845 self.assertRaises(ZeroDivisionError, isinstance, [], x)
846
847 def test_bad_subclasscheck(self):
848 class BadMeta(type):
849 def __subclasscheck__(cls, sub):
850 1/0
851 x = int | BadMeta('A', (), {})
852 self.assertTrue(issubclass(int, x))
853 self.assertRaises(ZeroDivisionError, issubclass, list, x)
854
855 def test_or_type_operator_with_TypeVar(self):
856 TV = typing.TypeVar('T')
857 self.assertEqual(TV | str, typing.Union[TV, str])
858 self.assertEqual(str | TV, typing.Union[str, TV])
859 self.assertIs((int | TV)[int], int)
860 self.assertIs((TV | int)[int], int)
861
862 def test_union_args(self):
863 def check(arg, expected):
864 clear_typing_caches()
865 self.assertEqual(arg.__args__, expected)
866
867 check(int | str, (int, str))
868 check((int | str) | list, (int, str, list))
869 check(int | (str | list), (int, str, list))
870 check((int | str) | int, (int, str))
871 check(int | (str | int), (int, str))
872 check((int | str) | (str | int), (int, str))
873 check(typing.Union[int, str] | list, (int, str, list))
874 check(int | typing.Union[str, list], (int, str, list))
875 check((int | str) | (list | int), (int, str, list))
876 check((int | str) | typing.Union[list, int], (int, str, list))
877 check(typing.Union[int, str] | (list | int), (int, str, list))
878 check((str | int) | (int | list), (str, int, list))
879 check((str | int) | typing.Union[int, list], (str, int, list))
880 check(typing.Union[str, int] | (int | list), (str, int, list))
881 check(int | type(None), (int, type(None)))
882 check(type(None) | int, (type(None), int))
883
884 args = (int, list[int], typing.List[int],
885 typing.Tuple[int, int], typing.Callable[[int], int],
886 typing.Hashable, typing.TypeVar('T'))
887 for x in args:
888 with self.subTest(x):
889 check(x | None, (x, type(None)))
890 check(None | x, (type(None), x))
891
892 def test_union_parameter_chaining(self):
893 T = typing.TypeVar("T")
894 S = typing.TypeVar("S")
895
896 self.assertEqual((float | list[T])[int], float | list[int])
897 self.assertEqual(list[int | list[T]].__parameters__, (T,))
898 self.assertEqual(list[int | list[T]][str], list[int | list[str]])
899 self.assertEqual((list[T] | list[S]).__parameters__, (T, S))
900 self.assertEqual((list[T] | list[S])[int, T], list[int] | list[T])
901 self.assertEqual((list[T] | list[S])[int, int], list[int])
902
903 def test_union_parameter_substitution(self):
904 def eq(actual, expected, typed=True):
905 self.assertEqual(actual, expected)
906 if typed:
907 self.assertIs(type(actual), type(expected))
908
909 T = typing.TypeVar('T')
910 S = typing.TypeVar('S')
911 NT = typing.NewType('NT', str)
912 x = int | T | bytes
913
914 eq(x[str], int | str | bytes, typed=False)
915 eq(x[list[int]], int | list[int] | bytes, typed=False)
916 eq(x[typing.List], int | typing.List | bytes)
917 eq(x[typing.List[int]], int | typing.List[int] | bytes)
918 eq(x[typing.Hashable], int | typing.Hashable | bytes)
919 eq(x[collections.abc.Hashable],
920 int | collections.abc.Hashable | bytes, typed=False)
921 eq(x[typing.Callable[[int], str]],
922 int | typing.Callable[[int], str] | bytes)
923 eq(x[collections.abc.Callable[[int], str]],
924 int | collections.abc.Callable[[int], str] | bytes, typed=False)
925 eq(x[typing.Tuple[int, str]], int | typing.Tuple[int, str] | bytes)
926 eq(x[typing.Literal['none']], int | typing.Literal['none'] | bytes)
927 eq(x[str | list], int | str | list | bytes, typed=False)
928 eq(x[typing.Union[str, list]], typing.Union[int, str, list, bytes])
929 eq(x[str | int], int | str | bytes, typed=False)
930 eq(x[typing.Union[str, int]], typing.Union[int, str, bytes])
931 eq(x[NT], int | NT | bytes)
932 eq(x[S], int | S | bytes)
933
934 def test_union_pickle(self):
935 orig = list[T] | int
936 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
937 s = pickle.dumps(orig, proto)
938 loaded = pickle.loads(s)
939 self.assertEqual(loaded, orig)
940 self.assertEqual(loaded.__args__, orig.__args__)
941 self.assertEqual(loaded.__parameters__, orig.__parameters__)
942
943 def test_union_copy(self):
944 orig = list[T] | int
945 for copied in (copy.copy(orig), copy.deepcopy(orig)):
946 self.assertEqual(copied, orig)
947 self.assertEqual(copied.__args__, orig.__args__)
948 self.assertEqual(copied.__parameters__, orig.__parameters__)
949
950 def test_union_parameter_substitution_errors(self):
951 T = typing.TypeVar("T")
952 x = int | T
953 with self.assertRaises(TypeError):
954 x[int, str]
955
956 def test_or_type_operator_with_forward(self):
957 T = typing.TypeVar('T')
958 ForwardAfter = T | 'Forward'
959 ForwardBefore = 'Forward' | T
960 def forward_after(x: ForwardAfter[int]) -> None: ...
961 def forward_before(x: ForwardBefore[int]) -> None: ...
962 self.assertEqual(typing.get_args(typing.get_type_hints(forward_after)['x']),
963 (int, Forward))
964 self.assertEqual(typing.get_args(typing.get_type_hints(forward_before)['x']),
965 (int, Forward))
966
967 def test_or_type_operator_with_Protocol(self):
968 class Proto(typing.Protocol):
969 def meth(self) -> int:
970 ...
971 self.assertEqual(Proto | str, typing.Union[Proto, str])
972
973 def test_or_type_operator_with_Alias(self):
974 self.assertEqual(list | str, typing.Union[list, str])
975 self.assertEqual(typing.List | str, typing.Union[typing.List, str])
976
977 def test_or_type_operator_with_NamedTuple(self):
978 NT = namedtuple('A', ['B', 'C', 'D'])
979 self.assertEqual(NT | str, typing.Union[NT, str])
980
981 def test_or_type_operator_with_TypedDict(self):
982 class Point2D(typing.TypedDict):
983 x: int
984 y: int
985 label: str
986 self.assertEqual(Point2D | str, typing.Union[Point2D, str])
987
988 def test_or_type_operator_with_NewType(self):
989 UserId = typing.NewType('UserId', int)
990 self.assertEqual(UserId | str, typing.Union[UserId, str])
991
992 def test_or_type_operator_with_IO(self):
993 self.assertEqual(typing.IO | str, typing.Union[typing.IO, str])
994
995 def test_or_type_operator_with_SpecialForm(self):
996 self.assertEqual(typing.Any | str, typing.Union[typing.Any, str])
997 self.assertEqual(typing.NoReturn | str, typing.Union[typing.NoReturn, str])
998 self.assertEqual(typing.Optional[int] | str, typing.Union[typing.Optional[int], str])
999 self.assertEqual(typing.Optional[int] | str, typing.Union[int, str, None])
1000 self.assertEqual(typing.Union[int, bool] | str, typing.Union[int, bool, str])
1001
1002 def test_or_type_operator_with_Literal(self):
1003 Literal = typing.Literal
1004 self.assertEqual((Literal[1] | Literal[2]).__args__,
1005 (Literal[1], Literal[2]))
1006
1007 self.assertEqual((Literal[0] | Literal[False]).__args__,
1008 (Literal[0], Literal[False]))
1009 self.assertEqual((Literal[1] | Literal[True]).__args__,
1010 (Literal[1], Literal[True]))
1011
1012 self.assertEqual(Literal[1] | Literal[1], Literal[1])
1013 self.assertEqual(Literal['a'] | Literal['a'], Literal['a'])
1014
1015 import enum
1016 class Ints(enum.IntEnum):
1017 A = 0
1018 B = 1
1019
1020 self.assertEqual(Literal[Ints.A] | Literal[Ints.A], Literal[Ints.A])
1021 self.assertEqual(Literal[Ints.B] | Literal[Ints.B], Literal[Ints.B])
1022
1023 self.assertEqual((Literal[Ints.B] | Literal[Ints.A]).__args__,
1024 (Literal[Ints.B], Literal[Ints.A]))
1025
1026 self.assertEqual((Literal[0] | Literal[Ints.A]).__args__,
1027 (Literal[0], Literal[Ints.A]))
1028 self.assertEqual((Literal[1] | Literal[Ints.B]).__args__,
1029 (Literal[1], Literal[Ints.B]))
1030
1031 def test_or_type_repr(self):
1032 self.assertEqual(repr(int | str), "int | str")
1033 self.assertEqual(repr((int | str) | list), "int | str | list")
1034 self.assertEqual(repr(int | (str | list)), "int | str | list")
1035 self.assertEqual(repr(int | None), "int | None")
1036 self.assertEqual(repr(int | type(None)), "int | None")
1037 self.assertEqual(repr(int | typing.GenericAlias(list, int)), "int | list[int]")
1038
1039 def test_or_type_operator_with_genericalias(self):
1040 a = list[int]
1041 b = list[str]
1042 c = dict[float, str]
1043 class SubClass(types.GenericAlias): ...
1044 d = SubClass(list, float)
1045 # equivalence with typing.Union
1046 self.assertEqual(a | b | c | d, typing.Union[a, b, c, d])
1047 # de-duplicate
1048 self.assertEqual(a | c | b | b | a | c | d | d, a | b | c | d)
1049 # order shouldn't matter
1050 self.assertEqual(a | b | d, b | a | d)
1051 self.assertEqual(repr(a | b | c | d),
1052 "list[int] | list[str] | dict[float, str] | list[float]")
1053
1054 class BadType(type):
1055 def __eq__(self, other):
1056 return 1 / 0
1057
1058 bt = BadType('bt', (), {})
1059 # Comparison should fail and errors should propagate out for bad types.
1060 with self.assertRaises(ZeroDivisionError):
1061 list[int] | list[bt]
1062
1063 union_ga = (list[str] | int, collections.abc.Callable[..., str] | int,
1064 d | int)
1065 # Raise error when isinstance(type, genericalias | type)
1066 for type_ in union_ga:
1067 with self.subTest(f"check isinstance/issubclass is invalid for {type_}"):
1068 with self.assertRaises(TypeError):
1069 isinstance(1, type_)
1070 with self.assertRaises(TypeError):
1071 issubclass(int, type_)
1072
1073 def test_or_type_operator_with_bad_module(self):
1074 class BadMeta(type):
1075 __qualname__ = 'TypeVar'
1076 @property
1077 def __module__(self):
1078 1 / 0
1079 TypeVar = BadMeta('TypeVar', (), {})
1080 _SpecialForm = BadMeta('_SpecialForm', (), {})
1081 # Crashes in Issue44483
1082 with self.assertRaises((TypeError, ZeroDivisionError)):
1083 str | TypeVar()
1084 with self.assertRaises((TypeError, ZeroDivisionError)):
1085 str | _SpecialForm()
1086
1087 @cpython_only
1088 def test_or_type_operator_reference_cycle(self):
1089 if not hasattr(sys, 'gettotalrefcount'):
1090 self.skipTest('Cannot get total reference count.')
1091 gc.collect()
1092 before = sys.gettotalrefcount()
1093 for _ in range(30):
1094 T = typing.TypeVar('T')
1095 U = int | list[T]
1096 T.blah = U
1097 del T
1098 del U
1099 gc.collect()
1100 leeway = 15
1101 self.assertLessEqual(sys.gettotalrefcount() - before, leeway,
1102 msg='Check for union reference leak.')
1103
1104
1105 class MappingProxyTests(unittest.TestCase):
1106 mappingproxy = types.MappingProxyType
1107
1108 def test_constructor(self):
1109 class userdict(dict):
1110 pass
1111
1112 mapping = {'x': 1, 'y': 2}
1113 self.assertEqual(self.mappingproxy(mapping), mapping)
1114 mapping = userdict(x=1, y=2)
1115 self.assertEqual(self.mappingproxy(mapping), mapping)
1116 mapping = collections.ChainMap({'x': 1}, {'y': 2})
1117 self.assertEqual(self.mappingproxy(mapping), mapping)
1118
1119 self.assertRaises(TypeError, self.mappingproxy, 10)
1120 self.assertRaises(TypeError, self.mappingproxy, ("a", "tuple"))
1121 self.assertRaises(TypeError, self.mappingproxy, ["a", "list"])
1122
1123 def test_methods(self):
1124 attrs = set(dir(self.mappingproxy({}))) - set(dir(object()))
1125 self.assertEqual(attrs, {
1126 '__contains__',
1127 '__getitem__',
1128 '__class_getitem__',
1129 '__ior__',
1130 '__iter__',
1131 '__len__',
1132 '__or__',
1133 '__reversed__',
1134 '__ror__',
1135 'copy',
1136 'get',
1137 'items',
1138 'keys',
1139 'values',
1140 })
1141
1142 def test_get(self):
1143 view = self.mappingproxy({'a': 'A', 'b': 'B'})
1144 self.assertEqual(view['a'], 'A')
1145 self.assertEqual(view['b'], 'B')
1146 self.assertRaises(KeyError, view.__getitem__, 'xxx')
1147 self.assertEqual(view.get('a'), 'A')
1148 self.assertIsNone(view.get('xxx'))
1149 self.assertEqual(view.get('xxx', 42), 42)
1150
1151 def test_missing(self):
1152 class dictmissing(dict):
1153 def __missing__(self, key):
1154 return "missing=%s" % key
1155
1156 view = self.mappingproxy(dictmissing(x=1))
1157 self.assertEqual(view['x'], 1)
1158 self.assertEqual(view['y'], 'missing=y')
1159 self.assertEqual(view.get('x'), 1)
1160 self.assertEqual(view.get('y'), None)
1161 self.assertEqual(view.get('y', 42), 42)
1162 self.assertTrue('x' in view)
1163 self.assertFalse('y' in view)
1164
1165 def test_customdict(self):
1166 class customdict(dict):
1167 def __contains__(self, key):
1168 if key == 'magic':
1169 return True
1170 else:
1171 return dict.__contains__(self, key)
1172
1173 def __iter__(self):
1174 return iter(('iter',))
1175
1176 def __len__(self):
1177 return 500
1178
1179 def copy(self):
1180 return 'copy'
1181
1182 def keys(self):
1183 return 'keys'
1184
1185 def items(self):
1186 return 'items'
1187
1188 def values(self):
1189 return 'values'
1190
1191 def __getitem__(self, key):
1192 return "getitem=%s" % dict.__getitem__(self, key)
1193
1194 def get(self, key, default=None):
1195 return "get=%s" % dict.get(self, key, 'default=%r' % default)
1196
1197 custom = customdict({'key': 'value'})
1198 view = self.mappingproxy(custom)
1199 self.assertTrue('key' in view)
1200 self.assertTrue('magic' in view)
1201 self.assertFalse('xxx' in view)
1202 self.assertEqual(view['key'], 'getitem=value')
1203 self.assertRaises(KeyError, view.__getitem__, 'xxx')
1204 self.assertEqual(tuple(view), ('iter',))
1205 self.assertEqual(len(view), 500)
1206 self.assertEqual(view.copy(), 'copy')
1207 self.assertEqual(view.get('key'), 'get=value')
1208 self.assertEqual(view.get('xxx'), 'get=default=None')
1209 self.assertEqual(view.items(), 'items')
1210 self.assertEqual(view.keys(), 'keys')
1211 self.assertEqual(view.values(), 'values')
1212
1213 def test_chainmap(self):
1214 d1 = {'x': 1}
1215 d2 = {'y': 2}
1216 mapping = collections.ChainMap(d1, d2)
1217 view = self.mappingproxy(mapping)
1218 self.assertTrue('x' in view)
1219 self.assertTrue('y' in view)
1220 self.assertFalse('z' in view)
1221 self.assertEqual(view['x'], 1)
1222 self.assertEqual(view['y'], 2)
1223 self.assertRaises(KeyError, view.__getitem__, 'z')
1224 self.assertEqual(tuple(sorted(view)), ('x', 'y'))
1225 self.assertEqual(len(view), 2)
1226 copy = view.copy()
1227 self.assertIsNot(copy, mapping)
1228 self.assertIsInstance(copy, collections.ChainMap)
1229 self.assertEqual(copy, mapping)
1230 self.assertEqual(view.get('x'), 1)
1231 self.assertEqual(view.get('y'), 2)
1232 self.assertIsNone(view.get('z'))
1233 self.assertEqual(tuple(sorted(view.items())), (('x', 1), ('y', 2)))
1234 self.assertEqual(tuple(sorted(view.keys())), ('x', 'y'))
1235 self.assertEqual(tuple(sorted(view.values())), (1, 2))
1236
1237 def test_contains(self):
1238 view = self.mappingproxy(dict.fromkeys('abc'))
1239 self.assertTrue('a' in view)
1240 self.assertTrue('b' in view)
1241 self.assertTrue('c' in view)
1242 self.assertFalse('xxx' in view)
1243
1244 def test_views(self):
1245 mapping = {}
1246 view = self.mappingproxy(mapping)
1247 keys = view.keys()
1248 values = view.values()
1249 items = view.items()
1250 self.assertEqual(list(keys), [])
1251 self.assertEqual(list(values), [])
1252 self.assertEqual(list(items), [])
1253 mapping['key'] = 'value'
1254 self.assertEqual(list(keys), ['key'])
1255 self.assertEqual(list(values), ['value'])
1256 self.assertEqual(list(items), [('key', 'value')])
1257
1258 def test_len(self):
1259 for expected in range(6):
1260 data = dict.fromkeys('abcde'[:expected])
1261 self.assertEqual(len(data), expected)
1262 view = self.mappingproxy(data)
1263 self.assertEqual(len(view), expected)
1264
1265 def test_iterators(self):
1266 keys = ('x', 'y')
1267 values = (1, 2)
1268 items = tuple(zip(keys, values))
1269 view = self.mappingproxy(dict(items))
1270 self.assertEqual(set(view), set(keys))
1271 self.assertEqual(set(view.keys()), set(keys))
1272 self.assertEqual(set(view.values()), set(values))
1273 self.assertEqual(set(view.items()), set(items))
1274
1275 def test_reversed(self):
1276 d = {'a': 1, 'b': 2, 'foo': 0, 'c': 3, 'd': 4}
1277 mp = self.mappingproxy(d)
1278 del d['foo']
1279 r = reversed(mp)
1280 self.assertEqual(list(r), list('dcba'))
1281 self.assertRaises(StopIteration, next, r)
1282
1283 def test_copy(self):
1284 original = {'key1': 27, 'key2': 51, 'key3': 93}
1285 view = self.mappingproxy(original)
1286 copy = view.copy()
1287 self.assertEqual(type(copy), dict)
1288 self.assertEqual(copy, original)
1289 original['key1'] = 70
1290 self.assertEqual(view['key1'], 70)
1291 self.assertEqual(copy['key1'], 27)
1292
1293 def test_union(self):
1294 mapping = {'a': 0, 'b': 1, 'c': 2}
1295 view = self.mappingproxy(mapping)
1296 with self.assertRaises(TypeError):
1297 view | [('r', 2), ('d', 2)]
1298 with self.assertRaises(TypeError):
1299 [('r', 2), ('d', 2)] | view
1300 with self.assertRaises(TypeError):
1301 view |= [('r', 2), ('d', 2)]
1302 other = {'c': 3, 'p': 0}
1303 self.assertDictEqual(view | other, {'a': 0, 'b': 1, 'c': 3, 'p': 0})
1304 self.assertDictEqual(other | view, {'c': 2, 'p': 0, 'a': 0, 'b': 1})
1305 self.assertEqual(view, {'a': 0, 'b': 1, 'c': 2})
1306 self.assertDictEqual(mapping, {'a': 0, 'b': 1, 'c': 2})
1307 self.assertDictEqual(other, {'c': 3, 'p': 0})
1308
1309 def test_hash(self):
1310 class HashableDict(dict):
1311 def __hash__(self):
1312 return 3844817361
1313 view = self.mappingproxy({'a': 1, 'b': 2})
1314 self.assertRaises(TypeError, hash, view)
1315 mapping = HashableDict({'a': 1, 'b': 2})
1316 view = self.mappingproxy(mapping)
1317 self.assertEqual(hash(view), hash(mapping))
1318
1319
1320 class ClassCreationTests(unittest.TestCase):
1321
1322 class Meta(type):
1323 def __init__(cls, name, bases, ns, **kw):
1324 super().__init__(name, bases, ns)
1325 @staticmethod
1326 def __new__(mcls, name, bases, ns, **kw):
1327 return super().__new__(mcls, name, bases, ns)
1328 @classmethod
1329 def __prepare__(mcls, name, bases, **kw):
1330 ns = super().__prepare__(name, bases)
1331 ns["y"] = 1
1332 ns.update(kw)
1333 return ns
1334
1335 def test_new_class_basics(self):
1336 C = types.new_class("C")
1337 self.assertEqual(C.__name__, "C")
1338 self.assertEqual(C.__bases__, (object,))
1339
1340 def test_new_class_subclass(self):
1341 C = types.new_class("C", (int,))
1342 self.assertTrue(issubclass(C, int))
1343
1344 def test_new_class_meta(self):
1345 Meta = self.Meta
1346 settings = {"metaclass": Meta, "z": 2}
1347 # We do this twice to make sure the passed in dict isn't mutated
1348 for i in range(2):
1349 C = types.new_class("C" + str(i), (), settings)
1350 self.assertIsInstance(C, Meta)
1351 self.assertEqual(C.y, 1)
1352 self.assertEqual(C.z, 2)
1353
1354 def test_new_class_exec_body(self):
1355 Meta = self.Meta
1356 def func(ns):
1357 ns["x"] = 0
1358 C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func)
1359 self.assertIsInstance(C, Meta)
1360 self.assertEqual(C.x, 0)
1361 self.assertEqual(C.y, 1)
1362 self.assertEqual(C.z, 2)
1363
1364 def test_new_class_metaclass_keywords(self):
1365 #Test that keywords are passed to the metaclass:
1366 def meta_func(name, bases, ns, **kw):
1367 return name, bases, ns, kw
1368 res = types.new_class("X",
1369 (int, object),
1370 dict(metaclass=meta_func, x=0))
1371 self.assertEqual(res, ("X", (int, object), {}, {"x": 0}))
1372
1373 def test_new_class_defaults(self):
1374 # Test defaults/keywords:
1375 C = types.new_class("C", (), {}, None)
1376 self.assertEqual(C.__name__, "C")
1377 self.assertEqual(C.__bases__, (object,))
1378
1379 def test_new_class_meta_with_base(self):
1380 Meta = self.Meta
1381 def func(ns):
1382 ns["x"] = 0
1383 C = types.new_class(name="C",
1384 bases=(int,),
1385 kwds=dict(metaclass=Meta, z=2),
1386 exec_body=func)
1387 self.assertTrue(issubclass(C, int))
1388 self.assertIsInstance(C, Meta)
1389 self.assertEqual(C.x, 0)
1390 self.assertEqual(C.y, 1)
1391 self.assertEqual(C.z, 2)
1392
1393 def test_new_class_with_mro_entry(self):
1394 class A: pass
1395 class C:
1396 def __mro_entries__(self, bases):
1397 return (A,)
1398 c = C()
1399 D = types.new_class('D', (c,), {})
1400 self.assertEqual(D.__bases__, (A,))
1401 self.assertEqual(D.__orig_bases__, (c,))
1402 self.assertEqual(D.__mro__, (D, A, object))
1403
1404 def test_new_class_with_mro_entry_genericalias(self):
1405 L1 = types.new_class('L1', (typing.List[int],), {})
1406 self.assertEqual(L1.__bases__, (list, typing.Generic))
1407 self.assertEqual(L1.__orig_bases__, (typing.List[int],))
1408 self.assertEqual(L1.__mro__, (L1, list, typing.Generic, object))
1409
1410 L2 = types.new_class('L2', (list[int],), {})
1411 self.assertEqual(L2.__bases__, (list,))
1412 self.assertEqual(L2.__orig_bases__, (list[int],))
1413 self.assertEqual(L2.__mro__, (L2, list, object))
1414
1415 def test_new_class_with_mro_entry_none(self):
1416 class A: pass
1417 class B: pass
1418 class C:
1419 def __mro_entries__(self, bases):
1420 return ()
1421 c = C()
1422 D = types.new_class('D', (A, c, B), {})
1423 self.assertEqual(D.__bases__, (A, B))
1424 self.assertEqual(D.__orig_bases__, (A, c, B))
1425 self.assertEqual(D.__mro__, (D, A, B, object))
1426
1427 def test_new_class_with_mro_entry_error(self):
1428 class A: pass
1429 class C:
1430 def __mro_entries__(self, bases):
1431 return A
1432 c = C()
1433 with self.assertRaises(TypeError):
1434 types.new_class('D', (c,), {})
1435
1436 def test_new_class_with_mro_entry_multiple(self):
1437 class A1: pass
1438 class A2: pass
1439 class B1: pass
1440 class B2: pass
1441 class A:
1442 def __mro_entries__(self, bases):
1443 return (A1, A2)
1444 class B:
1445 def __mro_entries__(self, bases):
1446 return (B1, B2)
1447 D = types.new_class('D', (A(), B()), {})
1448 self.assertEqual(D.__bases__, (A1, A2, B1, B2))
1449
1450 def test_new_class_with_mro_entry_multiple_2(self):
1451 class A1: pass
1452 class A2: pass
1453 class A3: pass
1454 class B1: pass
1455 class B2: pass
1456 class A:
1457 def __mro_entries__(self, bases):
1458 return (A1, A2, A3)
1459 class B:
1460 def __mro_entries__(self, bases):
1461 return (B1, B2)
1462 class C: pass
1463 D = types.new_class('D', (A(), C, B()), {})
1464 self.assertEqual(D.__bases__, (A1, A2, A3, C, B1, B2))
1465
1466 def test_get_original_bases(self):
1467 T = typing.TypeVar('T')
1468 class A: pass
1469 class B(typing.Generic[T]): pass
1470 class C(B[int]): pass
1471 class D(B[str], float): pass
1472
1473 self.assertEqual(types.get_original_bases(A), (object,))
1474 self.assertEqual(types.get_original_bases(B), (typing.Generic[T],))
1475 self.assertEqual(types.get_original_bases(C), (B[int],))
1476 self.assertEqual(types.get_original_bases(int), (object,))
1477 self.assertEqual(types.get_original_bases(D), (B[str], float))
1478
1479 class E(list[T]): pass
1480 class F(list[int]): pass
1481
1482 self.assertEqual(types.get_original_bases(E), (list[T],))
1483 self.assertEqual(types.get_original_bases(F), (list[int],))
1484
1485 class FirstBase(typing.Generic[T]): pass
1486 class SecondBase(typing.Generic[T]): pass
1487 class First(FirstBase[int]): pass
1488 class Second(SecondBase[int]): pass
1489 class G(First, Second): pass
1490 self.assertEqual(types.get_original_bases(G), (First, Second))
1491
1492 class First_(typing.Generic[T]): pass
1493 class Second_(typing.Generic[T]): pass
1494 class H(First_, Second_): pass
1495 self.assertEqual(types.get_original_bases(H), (First_, Second_))
1496
1497 class ClassBasedNamedTuple(typing.NamedTuple):
1498 x: int
1499
1500 class GenericNamedTuple(typing.NamedTuple, typing.Generic[T]):
1501 x: T
1502
1503 CallBasedNamedTuple = typing.NamedTuple("CallBasedNamedTuple", [("x", int)])
1504
1505 self.assertIs(
1506 types.get_original_bases(ClassBasedNamedTuple)[0], typing.NamedTuple
1507 )
1508 self.assertEqual(
1509 types.get_original_bases(GenericNamedTuple),
1510 (typing.NamedTuple, typing.Generic[T])
1511 )
1512 self.assertIs(
1513 types.get_original_bases(CallBasedNamedTuple)[0], typing.NamedTuple
1514 )
1515
1516 class ClassBasedTypedDict(typing.TypedDict):
1517 x: int
1518
1519 class GenericTypedDict(typing.TypedDict, typing.Generic[T]):
1520 x: T
1521
1522 CallBasedTypedDict = typing.TypedDict("CallBasedTypedDict", {"x": int})
1523
1524 self.assertIs(
1525 types.get_original_bases(ClassBasedTypedDict)[0],
1526 typing.TypedDict
1527 )
1528 self.assertEqual(
1529 types.get_original_bases(GenericTypedDict),
1530 (typing.TypedDict, typing.Generic[T])
1531 )
1532 self.assertIs(
1533 types.get_original_bases(CallBasedTypedDict)[0],
1534 typing.TypedDict
1535 )
1536
1537 with self.assertRaisesRegex(TypeError, "Expected an instance of type"):
1538 types.get_original_bases(object())
1539
1540 # Many of the following tests are derived from test_descr.py
1541 def test_prepare_class(self):
1542 # Basic test of metaclass derivation
1543 expected_ns = {}
1544 class A(type):
1545 def __new__(*args, **kwargs):
1546 return type.__new__(*args, **kwargs)
1547
1548 def __prepare__(*args):
1549 return expected_ns
1550
1551 B = types.new_class("B", (object,))
1552 C = types.new_class("C", (object,), {"metaclass": A})
1553
1554 # The most derived metaclass of D is A rather than type.
1555 meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
1556 self.assertIs(meta, A)
1557 self.assertIs(ns, expected_ns)
1558 self.assertEqual(len(kwds), 0)
1559
1560 def test_bad___prepare__(self):
1561 # __prepare__() must return a mapping.
1562 class BadMeta(type):
1563 @classmethod
1564 def __prepare__(*args):
1565 return None
1566 with self.assertRaisesRegex(TypeError,
1567 r'^BadMeta\.__prepare__\(\) must '
1568 r'return a mapping, not NoneType$'):
1569 class Foo(metaclass=BadMeta):
1570 pass
1571 # Also test the case in which the metaclass is not a type.
1572 class BadMeta:
1573 @classmethod
1574 def __prepare__(*args):
1575 return None
1576 with self.assertRaisesRegex(TypeError,
1577 r'^<metaclass>\.__prepare__\(\) must '
1578 r'return a mapping, not NoneType$'):
1579 class Bar(metaclass=BadMeta()):
1580 pass
1581
1582 def test_resolve_bases(self):
1583 class A: pass
1584 class B: pass
1585 class C:
1586 def __mro_entries__(self, bases):
1587 if A in bases:
1588 return ()
1589 return (A,)
1590 c = C()
1591 self.assertEqual(types.resolve_bases(()), ())
1592 self.assertEqual(types.resolve_bases((c,)), (A,))
1593 self.assertEqual(types.resolve_bases((C,)), (C,))
1594 self.assertEqual(types.resolve_bases((A, C)), (A, C))
1595 self.assertEqual(types.resolve_bases((c, A)), (A,))
1596 self.assertEqual(types.resolve_bases((A, c)), (A,))
1597 x = (A,)
1598 y = (C,)
1599 z = (A, C)
1600 t = (A, C, B)
1601 for bases in [x, y, z, t]:
1602 self.assertIs(types.resolve_bases(bases), bases)
1603
1604 def test_resolve_bases_with_mro_entry(self):
1605 self.assertEqual(types.resolve_bases((typing.List[int],)),
1606 (list, typing.Generic))
1607 self.assertEqual(types.resolve_bases((list[int],)), (list,))
1608
1609 def test_metaclass_derivation(self):
1610 # issue1294232: correct metaclass calculation
1611 new_calls = [] # to check the order of __new__ calls
1612 class AMeta(type):
1613 def __new__(mcls, name, bases, ns):
1614 new_calls.append('AMeta')
1615 return super().__new__(mcls, name, bases, ns)
1616 @classmethod
1617 def __prepare__(mcls, name, bases):
1618 return {}
1619
1620 class BMeta(AMeta):
1621 def __new__(mcls, name, bases, ns):
1622 new_calls.append('BMeta')
1623 return super().__new__(mcls, name, bases, ns)
1624 @classmethod
1625 def __prepare__(mcls, name, bases):
1626 ns = super().__prepare__(name, bases)
1627 ns['BMeta_was_here'] = True
1628 return ns
1629
1630 A = types.new_class("A", (), {"metaclass": AMeta})
1631 self.assertEqual(new_calls, ['AMeta'])
1632 new_calls.clear()
1633
1634 B = types.new_class("B", (), {"metaclass": BMeta})
1635 # BMeta.__new__ calls AMeta.__new__ with super:
1636 self.assertEqual(new_calls, ['BMeta', 'AMeta'])
1637 new_calls.clear()
1638
1639 C = types.new_class("C", (A, B))
1640 # The most derived metaclass is BMeta:
1641 self.assertEqual(new_calls, ['BMeta', 'AMeta'])
1642 new_calls.clear()
1643 # BMeta.__prepare__ should've been called:
1644 self.assertIn('BMeta_was_here', C.__dict__)
1645
1646 # The order of the bases shouldn't matter:
1647 C2 = types.new_class("C2", (B, A))
1648 self.assertEqual(new_calls, ['BMeta', 'AMeta'])
1649 new_calls.clear()
1650 self.assertIn('BMeta_was_here', C2.__dict__)
1651
1652 # Check correct metaclass calculation when a metaclass is declared:
1653 D = types.new_class("D", (C,), {"metaclass": type})
1654 self.assertEqual(new_calls, ['BMeta', 'AMeta'])
1655 new_calls.clear()
1656 self.assertIn('BMeta_was_here', D.__dict__)
1657
1658 E = types.new_class("E", (C,), {"metaclass": AMeta})
1659 self.assertEqual(new_calls, ['BMeta', 'AMeta'])
1660 new_calls.clear()
1661 self.assertIn('BMeta_was_here', E.__dict__)
1662
1663 def test_metaclass_override_function(self):
1664 # Special case: the given metaclass isn't a class,
1665 # so there is no metaclass calculation.
1666 class A(metaclass=self.Meta):
1667 pass
1668
1669 marker = object()
1670 def func(*args, **kwargs):
1671 return marker
1672
1673 X = types.new_class("X", (), {"metaclass": func})
1674 Y = types.new_class("Y", (object,), {"metaclass": func})
1675 Z = types.new_class("Z", (A,), {"metaclass": func})
1676 self.assertIs(marker, X)
1677 self.assertIs(marker, Y)
1678 self.assertIs(marker, Z)
1679
1680 def test_metaclass_override_callable(self):
1681 # The given metaclass is a class,
1682 # but not a descendant of type.
1683 new_calls = [] # to check the order of __new__ calls
1684 prepare_calls = [] # to track __prepare__ calls
1685 class ANotMeta:
1686 def __new__(mcls, *args, **kwargs):
1687 new_calls.append('ANotMeta')
1688 return super().__new__(mcls)
1689 @classmethod
1690 def __prepare__(mcls, name, bases):
1691 prepare_calls.append('ANotMeta')
1692 return {}
1693
1694 class BNotMeta(ANotMeta):
1695 def __new__(mcls, *args, **kwargs):
1696 new_calls.append('BNotMeta')
1697 return super().__new__(mcls)
1698 @classmethod
1699 def __prepare__(mcls, name, bases):
1700 prepare_calls.append('BNotMeta')
1701 return super().__prepare__(name, bases)
1702
1703 A = types.new_class("A", (), {"metaclass": ANotMeta})
1704 self.assertIs(ANotMeta, type(A))
1705 self.assertEqual(prepare_calls, ['ANotMeta'])
1706 prepare_calls.clear()
1707 self.assertEqual(new_calls, ['ANotMeta'])
1708 new_calls.clear()
1709
1710 B = types.new_class("B", (), {"metaclass": BNotMeta})
1711 self.assertIs(BNotMeta, type(B))
1712 self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta'])
1713 prepare_calls.clear()
1714 self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta'])
1715 new_calls.clear()
1716
1717 C = types.new_class("C", (A, B))
1718 self.assertIs(BNotMeta, type(C))
1719 self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta'])
1720 prepare_calls.clear()
1721 self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta'])
1722 new_calls.clear()
1723
1724 C2 = types.new_class("C2", (B, A))
1725 self.assertIs(BNotMeta, type(C2))
1726 self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta'])
1727 prepare_calls.clear()
1728 self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta'])
1729 new_calls.clear()
1730
1731 # This is a TypeError, because of a metaclass conflict:
1732 # BNotMeta is neither a subclass, nor a superclass of type
1733 with self.assertRaises(TypeError):
1734 D = types.new_class("D", (C,), {"metaclass": type})
1735
1736 E = types.new_class("E", (C,), {"metaclass": ANotMeta})
1737 self.assertIs(BNotMeta, type(E))
1738 self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta'])
1739 prepare_calls.clear()
1740 self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta'])
1741 new_calls.clear()
1742
1743 F = types.new_class("F", (object(), C))
1744 self.assertIs(BNotMeta, type(F))
1745 self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta'])
1746 prepare_calls.clear()
1747 self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta'])
1748 new_calls.clear()
1749
1750 F2 = types.new_class("F2", (C, object()))
1751 self.assertIs(BNotMeta, type(F2))
1752 self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta'])
1753 prepare_calls.clear()
1754 self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta'])
1755 new_calls.clear()
1756
1757 # TypeError: BNotMeta is neither a
1758 # subclass, nor a superclass of int
1759 with self.assertRaises(TypeError):
1760 X = types.new_class("X", (C, int()))
1761 with self.assertRaises(TypeError):
1762 X = types.new_class("X", (int(), C))
1763
1764 def test_one_argument_type(self):
1765 expected_message = 'type.__new__() takes exactly 3 arguments (1 given)'
1766
1767 # Only type itself can use the one-argument form (#27157)
1768 self.assertIs(type(5), int)
1769
1770 class M(type):
1771 pass
1772 with self.assertRaises(TypeError) as cm:
1773 M(5)
1774 self.assertEqual(str(cm.exception), expected_message)
1775
1776 class N(type, metaclass=M):
1777 pass
1778 with self.assertRaises(TypeError) as cm:
1779 N(5)
1780 self.assertEqual(str(cm.exception), expected_message)
1781
1782 def test_metaclass_new_error(self):
1783 # bpo-44232: The C function type_new() must properly report the
1784 # exception when a metaclass constructor raises an exception and the
1785 # winner class is not the metaclass.
1786 class ModelBase(type):
1787 def __new__(cls, name, bases, attrs):
1788 super_new = super().__new__
1789 new_class = super_new(cls, name, bases, {})
1790 if name != "Model":
1791 raise RuntimeWarning(f"{name=}")
1792 return new_class
1793
1794 class Model(metaclass=ModelBase):
1795 pass
1796
1797 with self.assertRaises(RuntimeWarning):
1798 type("SouthPonies", (Model,), {})
1799
1800 def test_tuple_subclass_as_bases(self):
1801 # gh-132176: it used to crash on using
1802 # tuple subclass for as base classes.
1803 class TupleSubclass(tuple): pass
1804
1805 typ = type("typ", TupleSubclass((int, object)), {})
1806 self.assertEqual(typ.__bases__, (int, object))
1807 self.assertEqual(type(typ.__bases__), TupleSubclass)
1808
1809
1810 class SimpleNamespaceTests(unittest.TestCase):
1811
1812 def test_constructor(self):
1813 def check(ns, expected):
1814 self.assertEqual(len(ns.__dict__), len(expected))
1815 self.assertEqual(vars(ns), expected)
1816 # check order
1817 self.assertEqual(list(vars(ns).items()), list(expected.items()))
1818 for name in expected:
1819 self.assertEqual(getattr(ns, name), expected[name])
1820
1821 check(types.SimpleNamespace(), {})
1822 check(types.SimpleNamespace(x=1, y=2), {'x': 1, 'y': 2})
1823 check(types.SimpleNamespace(**dict(x=1, y=2)), {'x': 1, 'y': 2})
1824 check(types.SimpleNamespace({'x': 1, 'y': 2}, x=4, z=3),
1825 {'x': 4, 'y': 2, 'z': 3})
1826 check(types.SimpleNamespace([['x', 1], ['y', 2]], x=4, z=3),
1827 {'x': 4, 'y': 2, 'z': 3})
1828 check(types.SimpleNamespace(UserDict({'x': 1, 'y': 2}), x=4, z=3),
1829 {'x': 4, 'y': 2, 'z': 3})
1830 check(types.SimpleNamespace({'x': 1, 'y': 2}), {'x': 1, 'y': 2})
1831 check(types.SimpleNamespace([['x', 1], ['y', 2]]), {'x': 1, 'y': 2})
1832 check(types.SimpleNamespace([], x=4, z=3), {'x': 4, 'z': 3})
1833 check(types.SimpleNamespace({}, x=4, z=3), {'x': 4, 'z': 3})
1834 check(types.SimpleNamespace([]), {})
1835 check(types.SimpleNamespace({}), {})
1836
1837 with self.assertRaises(TypeError):
1838 types.SimpleNamespace([], []) # too many positional arguments
1839 with self.assertRaises(TypeError):
1840 types.SimpleNamespace(1) # not a mapping or iterable
1841 with self.assertRaises(TypeError):
1842 types.SimpleNamespace([1]) # non-iterable
1843 with self.assertRaises(ValueError):
1844 types.SimpleNamespace([['x']]) # not a pair
1845 with self.assertRaises(ValueError):
1846 types.SimpleNamespace([['x', 'y', 'z']])
1847 with self.assertRaises(TypeError):
1848 types.SimpleNamespace(**{1: 2}) # non-string key
1849 with self.assertRaises(TypeError):
1850 types.SimpleNamespace({1: 2})
1851 with self.assertRaises(TypeError):
1852 types.SimpleNamespace([[1, 2]])
1853 with self.assertRaises(TypeError):
1854 types.SimpleNamespace(UserDict({1: 2}))
1855 with self.assertRaises(TypeError):
1856 types.SimpleNamespace([[[], 2]]) # non-hashable key
1857
1858 def test_unbound(self):
1859 ns1 = vars(types.SimpleNamespace())
1860 ns2 = vars(types.SimpleNamespace(x=1, y=2))
1861
1862 self.assertEqual(ns1, {})
1863 self.assertEqual(ns2, {'y': 2, 'x': 1})
1864
1865 def test_underlying_dict(self):
1866 ns1 = types.SimpleNamespace()
1867 ns2 = types.SimpleNamespace(x=1, y=2)
1868 ns3 = types.SimpleNamespace(a=True, b=False)
1869 mapping = ns3.__dict__
1870 del ns3
1871
1872 self.assertEqual(ns1.__dict__, {})
1873 self.assertEqual(ns2.__dict__, {'y': 2, 'x': 1})
1874 self.assertEqual(mapping, dict(a=True, b=False))
1875
1876 def test_attrget(self):
1877 ns = types.SimpleNamespace(x=1, y=2, w=3)
1878
1879 self.assertEqual(ns.x, 1)
1880 self.assertEqual(ns.y, 2)
1881 self.assertEqual(ns.w, 3)
1882 with self.assertRaises(AttributeError):
1883 ns.z
1884
1885 def test_attrset(self):
1886 ns1 = types.SimpleNamespace()
1887 ns2 = types.SimpleNamespace(x=1, y=2, w=3)
1888 ns1.a = 'spam'
1889 ns1.b = 'ham'
1890 ns2.z = 4
1891 ns2.theta = None
1892
1893 self.assertEqual(ns1.__dict__, dict(a='spam', b='ham'))
1894 self.assertEqual(ns2.__dict__, dict(x=1, y=2, w=3, z=4, theta=None))
1895
1896 def test_attrdel(self):
1897 ns1 = types.SimpleNamespace()
1898 ns2 = types.SimpleNamespace(x=1, y=2, w=3)
1899
1900 with self.assertRaises(AttributeError):
1901 del ns1.spam
1902 with self.assertRaises(AttributeError):
1903 del ns2.spam
1904
1905 del ns2.y
1906 self.assertEqual(vars(ns2), dict(w=3, x=1))
1907 ns2.y = 'spam'
1908 self.assertEqual(vars(ns2), dict(w=3, x=1, y='spam'))
1909 del ns2.y
1910 self.assertEqual(vars(ns2), dict(w=3, x=1))
1911
1912 ns1.spam = 5
1913 self.assertEqual(vars(ns1), dict(spam=5))
1914 del ns1.spam
1915 self.assertEqual(vars(ns1), {})
1916
1917 def test_repr(self):
1918 ns1 = types.SimpleNamespace(x=1, y=2, w=3)
1919 ns2 = types.SimpleNamespace()
1920 ns2.x = "spam"
1921 ns2._y = 5
1922 name = "namespace"
1923
1924 self.assertEqual(repr(ns1), "{name}(x=1, y=2, w=3)".format(name=name))
1925 self.assertEqual(repr(ns2), "{name}(x='spam', _y=5)".format(name=name))
1926
1927 def test_equal(self):
1928 ns1 = types.SimpleNamespace(x=1)
1929 ns2 = types.SimpleNamespace()
1930 ns2.x = 1
1931
1932 self.assertEqual(types.SimpleNamespace(), types.SimpleNamespace())
1933 self.assertEqual(ns1, ns2)
1934 self.assertNotEqual(ns2, types.SimpleNamespace())
1935
1936 def test_nested(self):
1937 ns1 = types.SimpleNamespace(a=1, b=2)
1938 ns2 = types.SimpleNamespace()
1939 ns3 = types.SimpleNamespace(x=ns1)
1940 ns2.spam = ns1
1941 ns2.ham = '?'
1942 ns2.spam = ns3
1943
1944 self.assertEqual(vars(ns1), dict(a=1, b=2))
1945 self.assertEqual(vars(ns2), dict(spam=ns3, ham='?'))
1946 self.assertEqual(ns2.spam, ns3)
1947 self.assertEqual(vars(ns3), dict(x=ns1))
1948 self.assertEqual(ns3.x.a, 1)
1949
1950 def test_recursive(self):
1951 ns1 = types.SimpleNamespace(c='cookie')
1952 ns2 = types.SimpleNamespace()
1953 ns3 = types.SimpleNamespace(x=1)
1954 ns1.spam = ns1
1955 ns2.spam = ns3
1956 ns3.spam = ns2
1957
1958 self.assertEqual(ns1.spam, ns1)
1959 self.assertEqual(ns1.spam.spam, ns1)
1960 self.assertEqual(ns1.spam.spam, ns1.spam)
1961 self.assertEqual(ns2.spam, ns3)
1962 self.assertEqual(ns3.spam, ns2)
1963 self.assertEqual(ns2.spam.spam, ns2)
1964
1965 def test_recursive_repr(self):
1966 ns1 = types.SimpleNamespace(c='cookie')
1967 ns2 = types.SimpleNamespace()
1968 ns3 = types.SimpleNamespace(x=1)
1969 ns1.spam = ns1
1970 ns2.spam = ns3
1971 ns3.spam = ns2
1972 name = "namespace"
1973 repr1 = "{name}(c='cookie', spam={name}(...))".format(name=name)
1974 repr2 = "{name}(spam={name}(x=1, spam={name}(...)))".format(name=name)
1975
1976 self.assertEqual(repr(ns1), repr1)
1977 self.assertEqual(repr(ns2), repr2)
1978
1979 def test_as_dict(self):
1980 ns = types.SimpleNamespace(spam='spamspamspam')
1981
1982 with self.assertRaises(TypeError):
1983 len(ns)
1984 with self.assertRaises(TypeError):
1985 iter(ns)
1986 with self.assertRaises(TypeError):
1987 'spam' in ns
1988 with self.assertRaises(TypeError):
1989 ns['spam']
1990
1991 def test_subclass(self):
1992 class Spam(types.SimpleNamespace):
1993 pass
1994
1995 spam = Spam(ham=8, eggs=9)
1996
1997 self.assertIs(type(spam), Spam)
1998 self.assertEqual(vars(spam), {'ham': 8, 'eggs': 9})
1999
2000 def test_pickle(self):
2001 ns = types.SimpleNamespace(breakfast="spam", lunch="spam")
2002
2003 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
2004 pname = "protocol {}".format(protocol)
2005 try:
2006 ns_pickled = pickle.dumps(ns, protocol)
2007 except TypeError as e:
2008 raise TypeError(pname) from e
2009 ns_roundtrip = pickle.loads(ns_pickled)
2010
2011 self.assertEqual(ns, ns_roundtrip, pname)
2012
2013 def test_replace(self):
2014 ns = types.SimpleNamespace(x=11, y=22)
2015
2016 ns2 = copy.replace(ns)
2017 self.assertEqual(ns2, ns)
2018 self.assertIsNot(ns2, ns)
2019 self.assertIs(type(ns2), types.SimpleNamespace)
2020 self.assertEqual(vars(ns2), {'x': 11, 'y': 22})
2021 ns2.x = 3
2022 self.assertEqual(ns.x, 11)
2023 ns.x = 4
2024 self.assertEqual(ns2.x, 3)
2025
2026 self.assertEqual(vars(copy.replace(ns, x=1)), {'x': 1, 'y': 22})
2027 self.assertEqual(vars(copy.replace(ns, y=2)), {'x': 4, 'y': 2})
2028 self.assertEqual(vars(copy.replace(ns, x=1, y=2)), {'x': 1, 'y': 2})
2029
2030 def test_replace_subclass(self):
2031 class Spam(types.SimpleNamespace):
2032 pass
2033
2034 spam = Spam(ham=8, eggs=9)
2035 spam2 = copy.replace(spam, ham=5)
2036
2037 self.assertIs(type(spam2), Spam)
2038 self.assertEqual(vars(spam2), {'ham': 5, 'eggs': 9})
2039
2040 def test_fake_namespace_compare(self):
2041 # Issue #24257: Incorrect use of PyObject_IsInstance() caused
2042 # SystemError.
2043 class FakeSimpleNamespace(str):
2044 __class__ = types.SimpleNamespace
2045 self.assertFalse(types.SimpleNamespace() == FakeSimpleNamespace())
2046 self.assertTrue(types.SimpleNamespace() != FakeSimpleNamespace())
2047 with self.assertRaises(TypeError):
2048 types.SimpleNamespace() < FakeSimpleNamespace()
2049 with self.assertRaises(TypeError):
2050 types.SimpleNamespace() <= FakeSimpleNamespace()
2051 with self.assertRaises(TypeError):
2052 types.SimpleNamespace() > FakeSimpleNamespace()
2053 with self.assertRaises(TypeError):
2054 types.SimpleNamespace() >= FakeSimpleNamespace()
2055
2056
2057 class CoroutineTests(unittest.TestCase):
2058 def test_wrong_args(self):
2059 samples = [None, 1, object()]
2060 for sample in samples:
2061 with self.assertRaisesRegex(TypeError,
2062 'types.coroutine.*expects a callable'):
2063 types.coroutine(sample)
2064
2065 def test_non_gen_values(self):
2066 @types.coroutine
2067 def foo():
2068 return 'spam'
2069 self.assertEqual(foo(), 'spam')
2070
2071 class Awaitable:
2072 def __await__(self):
2073 return ()
2074 aw = Awaitable()
2075 @types.coroutine
2076 def foo():
2077 return aw
2078 self.assertIs(aw, foo())
2079
2080 # decorate foo second time
2081 foo = types.coroutine(foo)
2082 self.assertIs(aw, foo())
2083
2084 def test_async_def(self):
2085 # Test that types.coroutine passes 'async def' coroutines
2086 # without modification
2087
2088 async def foo(): pass
2089 foo_code = foo.__code__
2090 foo_flags = foo.__code__.co_flags
2091 decorated_foo = types.coroutine(foo)
2092 self.assertIs(foo, decorated_foo)
2093 self.assertEqual(foo.__code__.co_flags, foo_flags)
2094 self.assertIs(decorated_foo.__code__, foo_code)
2095
2096 foo_coro = foo()
2097 def bar(): return foo_coro
2098 for _ in range(2):
2099 bar = types.coroutine(bar)
2100 coro = bar()
2101 self.assertIs(foo_coro, coro)
2102 self.assertEqual(coro.cr_code.co_flags, foo_flags)
2103 coro.close()
2104
2105 def test_duck_coro(self):
2106 class CoroLike:
2107 def send(self): pass
2108 def throw(self): pass
2109 def close(self): pass
2110 def __await__(self): return self
2111
2112 coro = CoroLike()
2113 @types.coroutine
2114 def foo():
2115 return coro
2116 self.assertIs(foo(), coro)
2117 self.assertIs(foo().__await__(), coro)
2118
2119 def test_duck_corogen(self):
2120 class CoroGenLike:
2121 def send(self): pass
2122 def throw(self): pass
2123 def close(self): pass
2124 def __await__(self): return self
2125 def __iter__(self): return self
2126 def __next__(self): pass
2127
2128 coro = CoroGenLike()
2129 @types.coroutine
2130 def foo():
2131 return coro
2132 self.assertIs(foo(), coro)
2133 self.assertIs(foo().__await__(), coro)
2134
2135 def test_duck_gen(self):
2136 class GenLike:
2137 def send(self): pass
2138 def throw(self): pass
2139 def close(self): pass
2140 def __iter__(self): pass
2141 def __next__(self): pass
2142
2143 # Setup generator mock object
2144 gen = unittest.mock.MagicMock(GenLike)
2145 gen.__iter__ = lambda gen: gen
2146 gen.__name__ = 'gen'
2147 gen.__qualname__ = 'test.gen'
2148 self.assertIsInstance(gen, collections.abc.Generator)
2149 self.assertIs(gen, iter(gen))
2150
2151 @types.coroutine
2152 def foo(): return gen
2153
2154 wrapper = foo()
2155 self.assertIsInstance(wrapper, types._GeneratorWrapper)
2156 self.assertIs(wrapper.__await__(), wrapper)
2157 # Wrapper proxies duck generators completely:
2158 self.assertIs(iter(wrapper), wrapper)
2159
2160 self.assertIsInstance(wrapper, collections.abc.Coroutine)
2161 self.assertIsInstance(wrapper, collections.abc.Awaitable)
2162
2163 self.assertIs(wrapper.__qualname__, gen.__qualname__)
2164 self.assertIs(wrapper.__name__, gen.__name__)
2165
2166 # Test AttributeErrors
2167 for name in {'gi_running', 'gi_frame', 'gi_code', 'gi_yieldfrom', 'gi_suspended',
2168 'cr_running', 'cr_frame', 'cr_code', 'cr_await', 'cr_suspended'}:
2169 with self.assertRaises(AttributeError):
2170 getattr(wrapper, name)
2171
2172 # Test attributes pass-through
2173 gen.gi_running = object()
2174 gen.gi_frame = object()
2175 gen.gi_code = object()
2176 gen.gi_yieldfrom = object()
2177 gen.gi_suspended = object()
2178 self.assertIs(wrapper.gi_running, gen.gi_running)
2179 self.assertIs(wrapper.gi_frame, gen.gi_frame)
2180 self.assertIs(wrapper.gi_code, gen.gi_code)
2181 self.assertIs(wrapper.gi_yieldfrom, gen.gi_yieldfrom)
2182 self.assertIs(wrapper.gi_suspended, gen.gi_suspended)
2183 self.assertIs(wrapper.cr_running, gen.gi_running)
2184 self.assertIs(wrapper.cr_frame, gen.gi_frame)
2185 self.assertIs(wrapper.cr_code, gen.gi_code)
2186 self.assertIs(wrapper.cr_await, gen.gi_yieldfrom)
2187 self.assertIs(wrapper.cr_suspended, gen.gi_suspended)
2188
2189 wrapper.close()
2190 gen.close.assert_called_once_with()
2191
2192 wrapper.send(1)
2193 gen.send.assert_called_once_with(1)
2194 gen.reset_mock()
2195
2196 next(wrapper)
2197 gen.__next__.assert_called_once_with()
2198 gen.reset_mock()
2199
2200 wrapper.throw(1, 2, 3)
2201 gen.throw.assert_called_once_with(1, 2, 3)
2202 gen.reset_mock()
2203
2204 wrapper.throw(1, 2)
2205 gen.throw.assert_called_once_with(1, 2)
2206 gen.reset_mock()
2207
2208 wrapper.throw(1)
2209 gen.throw.assert_called_once_with(1)
2210 gen.reset_mock()
2211
2212 # Test exceptions propagation
2213 error = Exception()
2214 gen.throw.side_effect = error
2215 try:
2216 wrapper.throw(1)
2217 except Exception as ex:
2218 self.assertIs(ex, error)
2219 else:
2220 self.fail('wrapper did not propagate an exception')
2221
2222 # Test invalid args
2223 gen.reset_mock()
2224 with self.assertRaises(TypeError):
2225 wrapper.throw()
2226 self.assertFalse(gen.throw.called)
2227 with self.assertRaises(TypeError):
2228 wrapper.close(1)
2229 self.assertFalse(gen.close.called)
2230 with self.assertRaises(TypeError):
2231 wrapper.send()
2232 self.assertFalse(gen.send.called)
2233
2234 # Test that we do not double wrap
2235 @types.coroutine
2236 def bar(): return wrapper
2237 self.assertIs(wrapper, bar())
2238
2239 # Test weakrefs support
2240 ref = weakref.ref(wrapper)
2241 self.assertIs(ref(), wrapper)
2242
2243 def test_duck_functional_gen(self):
2244 class Generator:
2245 """Emulates the following generator (very clumsy):
2246
2247 def gen(fut):
2248 result = yield fut
2249 return result * 2
2250 """
2251 def __init__(self, fut):
2252 self._i = 0
2253 self._fut = fut
2254 def __iter__(self):
2255 return self
2256 def __next__(self):
2257 return self.send(None)
2258 def send(self, v):
2259 try:
2260 if self._i == 0:
2261 assert v is None
2262 return self._fut
2263 if self._i == 1:
2264 raise StopIteration(v * 2)
2265 if self._i > 1:
2266 raise StopIteration
2267 finally:
2268 self._i += 1
2269 def throw(self, tp, *exc):
2270 self._i = 100
2271 if tp is not GeneratorExit:
2272 raise tp
2273 def close(self):
2274 self.throw(GeneratorExit)
2275
2276 @types.coroutine
2277 def foo(): return Generator('spam')
2278
2279 wrapper = foo()
2280 self.assertIsInstance(wrapper, types._GeneratorWrapper)
2281
2282 async def corofunc():
2283 return await foo() + 100
2284 coro = corofunc()
2285
2286 self.assertEqual(coro.send(None), 'spam')
2287 try:
2288 coro.send(20)
2289 except StopIteration as ex:
2290 self.assertEqual(ex.args[0], 140)
2291 else:
2292 self.fail('StopIteration was expected')
2293
2294 def test_gen(self):
2295 def gen_func():
2296 yield 1
2297 return (yield 2)
2298 gen = gen_func()
2299 @types.coroutine
2300 def foo(): return gen
2301 wrapper = foo()
2302 self.assertIsInstance(wrapper, types._GeneratorWrapper)
2303 self.assertIs(wrapper.__await__(), gen)
2304
2305 for name in ('__name__', '__qualname__', 'gi_code',
2306 'gi_running', 'gi_frame', 'gi_suspended'):
2307 self.assertIs(getattr(foo(), name),
2308 getattr(gen, name))
2309 self.assertIs(foo().cr_code, gen.gi_code)
2310
2311 self.assertEqual(next(wrapper), 1)
2312 self.assertEqual(wrapper.send(None), 2)
2313 with self.assertRaisesRegex(StopIteration, 'spam'):
2314 wrapper.send('spam')
2315
2316 gen = gen_func()
2317 wrapper = foo()
2318 wrapper.send(None)
2319 with self.assertRaisesRegex(Exception, 'ham'):
2320 wrapper.throw(Exception('ham'))
2321
2322 # decorate foo second time
2323 foo = types.coroutine(foo)
2324 self.assertIs(foo().__await__(), gen)
2325
2326 def test_returning_itercoro(self):
2327 @types.coroutine
2328 def gen():
2329 yield
2330
2331 gencoro = gen()
2332
2333 @types.coroutine
2334 def foo():
2335 return gencoro
2336
2337 self.assertIs(foo(), gencoro)
2338
2339 # decorate foo second time
2340 foo = types.coroutine(foo)
2341 self.assertIs(foo(), gencoro)
2342
2343 def test_genfunc(self):
2344 def gen(): yield
2345 self.assertIs(types.coroutine(gen), gen)
2346 self.assertIs(types.coroutine(types.coroutine(gen)), gen)
2347
2348 self.assertTrue(gen.__code__.co_flags & inspect.CO_ITERABLE_COROUTINE)
2349 self.assertFalse(gen.__code__.co_flags & inspect.CO_COROUTINE)
2350
2351 g = gen()
2352 self.assertTrue(g.gi_code.co_flags & inspect.CO_ITERABLE_COROUTINE)
2353 self.assertFalse(g.gi_code.co_flags & inspect.CO_COROUTINE)
2354
2355 self.assertIs(types.coroutine(gen), gen)
2356
2357 def test_wrapper_object(self):
2358 def gen():
2359 yield
2360 @types.coroutine
2361 def coro():
2362 return gen()
2363
2364 wrapper = coro()
2365 self.assertIn('GeneratorWrapper', repr(wrapper))
2366 self.assertEqual(repr(wrapper), str(wrapper))
2367 self.assertTrue(set(dir(wrapper)).issuperset({
2368 '__await__', '__iter__', '__next__', 'cr_code', 'cr_running',
2369 'cr_frame', 'cr_suspended', 'gi_code', 'gi_frame', 'gi_running',
2370 'gi_suspended', 'send', 'close', 'throw'}))
2371
2372
2373 class FunctionTests(unittest.TestCase):
2374 def test_function_type_defaults(self):
2375 def ex(a, /, b, *, c):
2376 return a + b + c
2377
2378 func = types.FunctionType(
2379 ex.__code__, {}, "func", (1, 2), None, {'c': 3},
2380 )
2381
2382 self.assertEqual(func(), 6)
2383 self.assertEqual(func.__defaults__, (1, 2))
2384 self.assertEqual(func.__kwdefaults__, {'c': 3})
2385
2386 func = types.FunctionType(
2387 ex.__code__, {}, "func", None, None, None,
2388 )
2389 self.assertEqual(func.__defaults__, None)
2390 self.assertEqual(func.__kwdefaults__, None)
2391
2392 def test_function_type_wrong_defaults(self):
2393 def ex(a, /, b, *, c):
2394 return a + b + c
2395
2396 with self.assertRaisesRegex(TypeError, 'arg 4'):
2397 types.FunctionType(
2398 ex.__code__, {}, "func", 1, None, {'c': 3},
2399 )
2400 with self.assertRaisesRegex(TypeError, 'arg 6'):
2401 types.FunctionType(
2402 ex.__code__, {}, "func", None, None, 3,
2403 )
2404
2405
2406 class SubinterpreterTests(unittest.TestCase):
2407
2408 @classmethod
2409 def setUpClass(cls):
2410 global interpreters
2411 try:
2412 from test.support import interpreters
2413 except ModuleNotFoundError:
2414 raise unittest.SkipTest('subinterpreters required')
2415 import test.support.interpreters.channels
2416
2417 @cpython_only
2418 @no_rerun('channels (and queues) might have a refleak; see gh-122199')
2419 def test_static_types_inherited_slots(self):
2420 rch, sch = interpreters.channels.create()
2421
2422 slots = []
2423 script = ''
2424 for cls in iter_builtin_types():
2425 for slot, own in iter_slot_wrappers(cls):
2426 slots.append((cls, slot, own))
2427 script += textwrap.dedent(f"""
2428 text = repr({cls.__name__}.{slot})
2429 sch.send_nowait(({cls.__name__!r}, {slot!r}, text))
2430 """)
2431
2432 exec(script)
2433 all_expected = []
2434 for cls, slot, _ in slots:
2435 result = rch.recv()
2436 assert result == (cls.__name__, slot, result[-1]), (cls, slot, result)
2437 all_expected.append(result)
2438
2439 interp = interpreters.create()
2440 interp.exec('from test.support import interpreters')
2441 interp.prepare_main(sch=sch)
2442 interp.exec(script)
2443
2444 for i, (cls, slot, _) in enumerate(slots):
2445 with self.subTest(cls=cls, slot=slot):
2446 expected = all_expected[i]
2447 result = rch.recv()
2448 self.assertEqual(result, expected)
2449
2450
2451 if __name__ == '__main__':
2452 unittest.main()