Debian Codegraph @

lib-python/3/test/test_types.py

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