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