| 1 |
import textwrap |
| 2 |
import types |
| 3 |
import typing |
| 4 |
import unittest |
| 5 |
import warnings |
| 6 |
from test import support |
| 7 |
|
| 8 |
|
| 9 |
def global_function(): |
| 10 |
def inner_function(): |
| 11 |
class LocalClass: |
| 12 |
pass |
| 13 |
global inner_global_function |
| 14 |
def inner_global_function(): |
| 15 |
def inner_function2(): |
| 16 |
pass |
| 17 |
return inner_function2 |
| 18 |
return LocalClass |
| 19 |
return lambda: inner_function |
| 20 |
|
| 21 |
|
| 22 |
class FuncAttrsTest(unittest.TestCase): |
| 23 |
def setUp(self): |
| 24 |
class F: |
| 25 |
def a(self): |
| 26 |
pass |
| 27 |
def b(): |
| 28 |
return 3 |
| 29 |
self.fi = F() |
| 30 |
self.F = F |
| 31 |
self.b = b |
| 32 |
|
| 33 |
def cannot_set_attr(self, obj, name, value, exceptions): |
| 34 |
try: |
| 35 |
setattr(obj, name, value) |
| 36 |
except exceptions: |
| 37 |
pass |
| 38 |
else: |
| 39 |
self.fail("shouldn't be able to set %s to %r" % (name, value)) |
| 40 |
try: |
| 41 |
delattr(obj, name) |
| 42 |
except exceptions: |
| 43 |
pass |
| 44 |
else: |
| 45 |
self.fail("shouldn't be able to del %s" % name) |
| 46 |
|
| 47 |
|
| 48 |
class FunctionPropertiesTest(FuncAttrsTest): |
| 49 |
# Include the external setUp method that is common to all tests |
| 50 |
def test_module(self): |
| 51 |
self.assertEqual(self.b.__module__, __name__) |
| 52 |
|
| 53 |
def test_dir_includes_correct_attrs(self): |
| 54 |
self.b.known_attr = 7 |
| 55 |
self.assertIn('known_attr', dir(self.b), |
| 56 |
"set attributes not in dir listing of method") |
| 57 |
# Test on underlying function object of method |
| 58 |
self.F.a.known_attr = 7 |
| 59 |
self.assertIn('known_attr', dir(self.fi.a), "set attribute on function " |
| 60 |
"implementations, should show up in next dir") |
| 61 |
|
| 62 |
def test_duplicate_function_equality(self): |
| 63 |
# Body of `duplicate' is the exact same as self.b |
| 64 |
def duplicate(): |
| 65 |
'my docstring' |
| 66 |
return 3 |
| 67 |
self.assertNotEqual(self.b, duplicate) |
| 68 |
|
| 69 |
def test_copying___code__(self): |
| 70 |
def test(): pass |
| 71 |
self.assertEqual(test(), None) |
| 72 |
test.__code__ = self.b.__code__ |
| 73 |
self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily |
| 74 |
|
| 75 |
def test_invalid___code___assignment(self): |
| 76 |
def A(): pass |
| 77 |
def B(): yield |
| 78 |
async def C(): yield |
| 79 |
async def D(x): await x |
| 80 |
|
| 81 |
for src in [A, B, C, D]: |
| 82 |
for dst in [A, B, C, D]: |
| 83 |
if src == dst: |
| 84 |
continue |
| 85 |
|
| 86 |
assert src.__code__.co_flags != dst.__code__.co_flags |
| 87 |
prev = dst.__code__ |
| 88 |
try: |
| 89 |
with self.assertWarnsRegex(DeprecationWarning, 'code object of non-matching type'): |
| 90 |
dst.__code__ = src.__code__ |
| 91 |
finally: |
| 92 |
with warnings.catch_warnings(): |
| 93 |
warnings.filterwarnings('ignore', '', DeprecationWarning) |
| 94 |
dst.__code__ = prev |
| 95 |
|
| 96 |
def test___globals__(self): |
| 97 |
self.assertIs(self.b.__globals__, globals()) |
| 98 |
self.cannot_set_attr(self.b, '__globals__', 2, |
| 99 |
(AttributeError, TypeError)) |
| 100 |
|
| 101 |
def test___builtins__(self): |
| 102 |
if __name__ == "__main__": |
| 103 |
builtins_dict = __builtins__.__dict__ |
| 104 |
else: |
| 105 |
builtins_dict = __builtins__ |
| 106 |
|
| 107 |
self.assertIs(self.b.__builtins__, builtins_dict) |
| 108 |
self.cannot_set_attr(self.b, '__builtins__', 2, |
| 109 |
(AttributeError, TypeError)) |
| 110 |
|
| 111 |
# bpo-42990: If globals is specified and has no "__builtins__" key, |
| 112 |
# a function inherits the current builtins namespace. |
| 113 |
def func(s): return len(s) |
| 114 |
ns = {} |
| 115 |
func2 = type(func)(func.__code__, ns) |
| 116 |
self.assertIs(func2.__globals__, ns) |
| 117 |
self.assertIs(func2.__builtins__, builtins_dict) |
| 118 |
|
| 119 |
# Make sure that the function actually works. |
| 120 |
self.assertEqual(func2("abc"), 3) |
| 121 |
self.assertEqual(ns, {}) |
| 122 |
|
| 123 |
# Define functions using exec() with different builtins, |
| 124 |
# and test inheritance when globals has no "__builtins__" key |
| 125 |
code = textwrap.dedent(""" |
| 126 |
def func3(s): pass |
| 127 |
func4 = type(func3)(func3.__code__, {}) |
| 128 |
""") |
| 129 |
safe_builtins = {'None': None} |
| 130 |
ns = {'type': type, '__builtins__': safe_builtins} |
| 131 |
exec(code, ns) |
| 132 |
self.assertIs(ns['func3'].__builtins__, safe_builtins) |
| 133 |
self.assertIs(ns['func4'].__builtins__, safe_builtins) |
| 134 |
self.assertIs(ns['func3'].__globals__['__builtins__'], safe_builtins) |
| 135 |
self.assertNotIn('__builtins__', ns['func4'].__globals__) |
| 136 |
|
| 137 |
def test___closure__(self): |
| 138 |
a = 12 |
| 139 |
def f(): print(a) |
| 140 |
c = f.__closure__ |
| 141 |
self.assertIsInstance(c, tuple) |
| 142 |
self.assertEqual(len(c), 1) |
| 143 |
# don't have a type object handy |
| 144 |
self.assertEqual(c[0].__class__.__name__, "cell") |
| 145 |
self.cannot_set_attr(f, "__closure__", c, AttributeError) |
| 146 |
|
| 147 |
def test_cell_new(self): |
| 148 |
cell_obj = types.CellType(1) |
| 149 |
self.assertEqual(cell_obj.cell_contents, 1) |
| 150 |
|
| 151 |
cell_obj = types.CellType() |
| 152 |
msg = "shouldn't be able to read an empty cell" |
| 153 |
with self.assertRaises(ValueError, msg=msg): |
| 154 |
cell_obj.cell_contents |
| 155 |
|
| 156 |
def test_empty_cell(self): |
| 157 |
def f(): print(a) |
| 158 |
try: |
| 159 |
f.__closure__[0].cell_contents |
| 160 |
except ValueError: |
| 161 |
pass |
| 162 |
else: |
| 163 |
self.fail("shouldn't be able to read an empty cell") |
| 164 |
a = 12 |
| 165 |
|
| 166 |
def test_set_cell(self): |
| 167 |
a = 12 |
| 168 |
def f(): return a |
| 169 |
c = f.__closure__ |
| 170 |
c[0].cell_contents = 9 |
| 171 |
self.assertEqual(c[0].cell_contents, 9) |
| 172 |
self.assertEqual(f(), 9) |
| 173 |
self.assertEqual(a, 9) |
| 174 |
del c[0].cell_contents |
| 175 |
try: |
| 176 |
c[0].cell_contents |
| 177 |
except ValueError: |
| 178 |
pass |
| 179 |
else: |
| 180 |
self.fail("shouldn't be able to read an empty cell") |
| 181 |
with self.assertRaises(NameError): |
| 182 |
f() |
| 183 |
with self.assertRaises(UnboundLocalError): |
| 184 |
print(a) |
| 185 |
|
| 186 |
def test___name__(self): |
| 187 |
self.assertEqual(self.b.__name__, 'b') |
| 188 |
self.b.__name__ = 'c' |
| 189 |
self.assertEqual(self.b.__name__, 'c') |
| 190 |
self.b.__name__ = 'd' |
| 191 |
self.assertEqual(self.b.__name__, 'd') |
| 192 |
# __name__ and __name__ must be a string |
| 193 |
self.cannot_set_attr(self.b, '__name__', 7, TypeError) |
| 194 |
# __name__ must be available when in restricted mode. Exec will raise |
| 195 |
# AttributeError if __name__ is not available on f. |
| 196 |
s = """def f(): pass\nf.__name__""" |
| 197 |
exec(s, {'__builtins__': {}}) |
| 198 |
# Test on methods, too |
| 199 |
self.assertEqual(self.fi.a.__name__, 'a') |
| 200 |
self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError) |
| 201 |
|
| 202 |
def test___qualname__(self): |
| 203 |
# PEP 3155 |
| 204 |
self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b') |
| 205 |
self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp') |
| 206 |
self.assertEqual(global_function.__qualname__, 'global_function') |
| 207 |
self.assertEqual(global_function().__qualname__, |
| 208 |
'global_function.<locals>.<lambda>') |
| 209 |
self.assertEqual(global_function()().__qualname__, |
| 210 |
'global_function.<locals>.inner_function') |
| 211 |
self.assertEqual(global_function()()().__qualname__, |
| 212 |
'global_function.<locals>.inner_function.<locals>.LocalClass') |
| 213 |
self.assertEqual(inner_global_function.__qualname__, 'inner_global_function') |
| 214 |
self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2') |
| 215 |
self.b.__qualname__ = 'c' |
| 216 |
self.assertEqual(self.b.__qualname__, 'c') |
| 217 |
self.b.__qualname__ = 'd' |
| 218 |
self.assertEqual(self.b.__qualname__, 'd') |
| 219 |
# __qualname__ must be a string |
| 220 |
self.cannot_set_attr(self.b, '__qualname__', 7, TypeError) |
| 221 |
|
| 222 |
def test___type_params__(self): |
| 223 |
def generic[T](): pass |
| 224 |
def not_generic(): pass |
| 225 |
lambda_ = lambda: ... |
| 226 |
T, = generic.__type_params__ |
| 227 |
self.assertIsInstance(T, typing.TypeVar) |
| 228 |
self.assertEqual(generic.__type_params__, (T,)) |
| 229 |
for func in (not_generic, lambda_): |
| 230 |
with self.subTest(func=func): |
| 231 |
self.assertEqual(func.__type_params__, ()) |
| 232 |
with self.assertRaises(TypeError): |
| 233 |
del func.__type_params__ |
| 234 |
with self.assertRaises(TypeError): |
| 235 |
func.__type_params__ = 42 |
| 236 |
func.__type_params__ = (T,) |
| 237 |
self.assertEqual(func.__type_params__, (T,)) |
| 238 |
|
| 239 |
def test___code__(self): |
| 240 |
num_one, num_two = 7, 8 |
| 241 |
def a(): pass |
| 242 |
def b(): return 12 |
| 243 |
def c(): return num_one |
| 244 |
def d(): return num_two |
| 245 |
def e(): return num_one, num_two |
| 246 |
for func in [a, b, c, d, e]: |
| 247 |
self.assertEqual(type(func.__code__), types.CodeType) |
| 248 |
self.assertEqual(c(), 7) |
| 249 |
self.assertEqual(d(), 8) |
| 250 |
d.__code__ = c.__code__ |
| 251 |
self.assertEqual(c.__code__, d.__code__) |
| 252 |
self.assertEqual(c(), 7) |
| 253 |
# self.assertEqual(d(), 7) |
| 254 |
try: |
| 255 |
b.__code__ = c.__code__ |
| 256 |
except ValueError: |
| 257 |
pass |
| 258 |
else: |
| 259 |
self.fail("__code__ with different numbers of free vars should " |
| 260 |
"not be possible") |
| 261 |
try: |
| 262 |
e.__code__ = d.__code__ |
| 263 |
except ValueError: |
| 264 |
pass |
| 265 |
else: |
| 266 |
self.fail("__code__ with different numbers of free vars should " |
| 267 |
"not be possible") |
| 268 |
|
| 269 |
def test_blank_func_defaults(self): |
| 270 |
self.assertEqual(self.b.__defaults__, None) |
| 271 |
del self.b.__defaults__ |
| 272 |
self.assertEqual(self.b.__defaults__, None) |
| 273 |
|
| 274 |
def test_func_default_args(self): |
| 275 |
def first_func(a, b): |
| 276 |
return a+b |
| 277 |
def second_func(a=1, b=2): |
| 278 |
return a+b |
| 279 |
self.assertEqual(first_func.__defaults__, None) |
| 280 |
self.assertEqual(second_func.__defaults__, (1, 2)) |
| 281 |
first_func.__defaults__ = (1, 2) |
| 282 |
self.assertEqual(first_func.__defaults__, (1, 2)) |
| 283 |
self.assertEqual(first_func(), 3) |
| 284 |
self.assertEqual(first_func(3), 5) |
| 285 |
self.assertEqual(first_func(3, 5), 8) |
| 286 |
del second_func.__defaults__ |
| 287 |
self.assertEqual(second_func.__defaults__, None) |
| 288 |
try: |
| 289 |
second_func() |
| 290 |
except TypeError: |
| 291 |
pass |
| 292 |
else: |
| 293 |
self.fail("__defaults__ does not update; deleting it does not " |
| 294 |
"remove requirement") |
| 295 |
|
| 296 |
|
| 297 |
class InstancemethodAttrTest(FuncAttrsTest): |
| 298 |
|
| 299 |
def test___class__(self): |
| 300 |
self.assertEqual(self.fi.a.__self__.__class__, self.F) |
| 301 |
self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError) |
| 302 |
|
| 303 |
def test___func__(self): |
| 304 |
self.assertEqual(self.fi.a.__func__, self.F.a) |
| 305 |
self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError) |
| 306 |
|
| 307 |
def test___self__(self): |
| 308 |
self.assertEqual(self.fi.a.__self__, self.fi) |
| 309 |
self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError) |
| 310 |
|
| 311 |
def test___func___non_method(self): |
| 312 |
# Behavior should be the same when a method is added via an attr |
| 313 |
# assignment |
| 314 |
self.fi.id = types.MethodType(id, self.fi) |
| 315 |
self.assertEqual(self.fi.id(), id(self.fi)) |
| 316 |
# Test usage |
| 317 |
try: |
| 318 |
self.fi.id.unknown_attr |
| 319 |
except AttributeError: |
| 320 |
pass |
| 321 |
else: |
| 322 |
self.fail("using unknown attributes should raise AttributeError") |
| 323 |
# Test assignment and deletion |
| 324 |
self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError) |
| 325 |
|
| 326 |
|
| 327 |
class ArbitraryFunctionAttrTest(FuncAttrsTest): |
| 328 |
def test_set_attr(self): |
| 329 |
self.b.known_attr = 7 |
| 330 |
self.assertEqual(self.b.known_attr, 7) |
| 331 |
try: |
| 332 |
self.fi.a.known_attr = 7 |
| 333 |
except AttributeError: |
| 334 |
pass |
| 335 |
else: |
| 336 |
self.fail("setting attributes on methods should raise error") |
| 337 |
|
| 338 |
def test_delete_unknown_attr(self): |
| 339 |
try: |
| 340 |
del self.b.unknown_attr |
| 341 |
except AttributeError: |
| 342 |
pass |
| 343 |
else: |
| 344 |
self.fail("deleting unknown attribute should raise TypeError") |
| 345 |
|
| 346 |
def test_unset_attr(self): |
| 347 |
for func in [self.b, self.fi.a]: |
| 348 |
try: |
| 349 |
func.non_existent_attr |
| 350 |
except AttributeError: |
| 351 |
pass |
| 352 |
else: |
| 353 |
self.fail("using unknown attributes should raise " |
| 354 |
"AttributeError") |
| 355 |
|
| 356 |
|
| 357 |
class FunctionDictsTest(FuncAttrsTest): |
| 358 |
def test_setting_dict_to_invalid(self): |
| 359 |
self.cannot_set_attr(self.b, '__dict__', None, TypeError) |
| 360 |
from collections import UserDict |
| 361 |
d = UserDict({'known_attr': 7}) |
| 362 |
self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError) |
| 363 |
|
| 364 |
def test_setting_dict_to_valid(self): |
| 365 |
d = {'known_attr': 7} |
| 366 |
self.b.__dict__ = d |
| 367 |
# Test assignment |
| 368 |
self.assertIs(d, self.b.__dict__) |
| 369 |
# ... and on all the different ways of referencing the method's func |
| 370 |
self.F.a.__dict__ = d |
| 371 |
self.assertIs(d, self.fi.a.__func__.__dict__) |
| 372 |
self.assertIs(d, self.fi.a.__dict__) |
| 373 |
# Test value |
| 374 |
self.assertEqual(self.b.known_attr, 7) |
| 375 |
self.assertEqual(self.b.__dict__['known_attr'], 7) |
| 376 |
# ... and again, on all the different method's names |
| 377 |
self.assertEqual(self.fi.a.__func__.known_attr, 7) |
| 378 |
self.assertEqual(self.fi.a.known_attr, 7) |
| 379 |
|
| 380 |
def test_delete___dict__(self): |
| 381 |
try: |
| 382 |
del self.b.__dict__ |
| 383 |
except TypeError: |
| 384 |
pass |
| 385 |
else: |
| 386 |
self.fail("deleting function dictionary should raise TypeError") |
| 387 |
|
| 388 |
def test_unassigned_dict(self): |
| 389 |
self.assertEqual(self.b.__dict__, {}) |
| 390 |
|
| 391 |
def test_func_as_dict_key(self): |
| 392 |
value = "Some string" |
| 393 |
d = {} |
| 394 |
d[self.b] = value |
| 395 |
self.assertEqual(d[self.b], value) |
| 396 |
|
| 397 |
|
| 398 |
class FunctionDocstringTest(FuncAttrsTest): |
| 399 |
def test_set_docstring_attr(self): |
| 400 |
self.assertEqual(self.b.__doc__, None) |
| 401 |
docstr = "A test method that does nothing" |
| 402 |
self.b.__doc__ = docstr |
| 403 |
self.F.a.__doc__ = docstr |
| 404 |
self.assertEqual(self.b.__doc__, docstr) |
| 405 |
self.assertEqual(self.fi.a.__doc__, docstr) |
| 406 |
self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError) |
| 407 |
|
| 408 |
def test_delete_docstring(self): |
| 409 |
self.b.__doc__ = "The docstring" |
| 410 |
del self.b.__doc__ |
| 411 |
self.assertEqual(self.b.__doc__, None) |
| 412 |
|
| 413 |
|
| 414 |
def cell(value): |
| 415 |
"""Create a cell containing the given value.""" |
| 416 |
def f(): |
| 417 |
print(a) |
| 418 |
a = value |
| 419 |
return f.__closure__[0] |
| 420 |
|
| 421 |
def empty_cell(empty=True): |
| 422 |
"""Create an empty cell.""" |
| 423 |
def f(): |
| 424 |
print(a) |
| 425 |
# the intent of the following line is simply "if False:"; it's |
| 426 |
# spelt this way to avoid the danger that a future optimization |
| 427 |
# might simply remove an "if False:" code block. |
| 428 |
if not empty: |
| 429 |
a = 1729 |
| 430 |
return f.__closure__[0] |
| 431 |
|
| 432 |
|
| 433 |
class CellTest(unittest.TestCase): |
| 434 |
def test_comparison(self): |
| 435 |
# These tests are here simply to exercise the comparison code; |
| 436 |
# their presence should not be interpreted as providing any |
| 437 |
# guarantees about the semantics (or even existence) of cell |
| 438 |
# comparisons in future versions of CPython. |
| 439 |
self.assertTrue(cell(2) < cell(3)) |
| 440 |
self.assertTrue(empty_cell() < cell('saturday')) |
| 441 |
self.assertTrue(empty_cell() == empty_cell()) |
| 442 |
self.assertTrue(cell(-36) == cell(-36.0)) |
| 443 |
self.assertTrue(cell(True) > empty_cell()) |
| 444 |
|
| 445 |
|
| 446 |
class StaticMethodAttrsTest(unittest.TestCase): |
| 447 |
def test_func_attribute(self): |
| 448 |
def f(): |
| 449 |
pass |
| 450 |
|
| 451 |
c = classmethod(f) |
| 452 |
self.assertTrue(c.__func__ is f) |
| 453 |
|
| 454 |
s = staticmethod(f) |
| 455 |
self.assertTrue(s.__func__ is f) |
| 456 |
|
| 457 |
|
| 458 |
class BuiltinFunctionPropertiesTest(unittest.TestCase): |
| 459 |
# XXX Not sure where this should really go since I can't find a |
| 460 |
# test module specifically for builtin_function_or_method. |
| 461 |
|
| 462 |
def test_builtin__qualname__(self): |
| 463 |
import time |
| 464 |
|
| 465 |
# builtin function: |
| 466 |
self.assertEqual(len.__qualname__, 'len') |
| 467 |
self.assertEqual(time.time.__qualname__, 'time') |
| 468 |
|
| 469 |
# builtin classmethod: |
| 470 |
self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys') |
| 471 |
self.assertEqual(float.__getformat__.__qualname__, |
| 472 |
'float.__getformat__') |
| 473 |
|
| 474 |
# builtin staticmethod: |
| 475 |
self.assertEqual(str.maketrans.__qualname__, 'str.maketrans') |
| 476 |
self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans') |
| 477 |
|
| 478 |
# builtin bound instance method: |
| 479 |
self.assertEqual([1, 2, 3].append.__qualname__, 'list.append') |
| 480 |
self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop') |
| 481 |
|
| 482 |
@support.cpython_only |
| 483 |
def test_builtin__self__(self): |
| 484 |
# See https://github.com/python/cpython/issues/58211. |
| 485 |
import builtins |
| 486 |
import time |
| 487 |
|
| 488 |
# builtin function: |
| 489 |
self.assertIs(len.__self__, builtins) |
| 490 |
self.assertIs(time.sleep.__self__, time) |
| 491 |
|
| 492 |
# builtin classmethod: |
| 493 |
self.assertIs(dict.fromkeys.__self__, dict) |
| 494 |
self.assertIs(float.__getformat__.__self__, float) |
| 495 |
|
| 496 |
# builtin staticmethod: |
| 497 |
self.assertIsNone(str.maketrans.__self__) |
| 498 |
self.assertIsNone(bytes.maketrans.__self__) |
| 499 |
|
| 500 |
# builtin bound instance method: |
| 501 |
l = [1, 2, 3] |
| 502 |
self.assertIs(l.append.__self__, l) |
| 503 |
|
| 504 |
d = {'foo': 'bar'} |
| 505 |
self.assertEqual(d.pop.__self__, d) |
| 506 |
|
| 507 |
self.assertIsNone(None.__repr__.__self__) |
| 508 |
|
| 509 |
|
| 510 |
if __name__ == "__main__": |
| 511 |
unittest.main() |