| 1 |
from annotationlib import Format, ForwardRef |
| 2 |
import asyncio |
| 3 |
import builtins |
| 4 |
import collections |
| 5 |
import copy |
| 6 |
import datetime |
| 7 |
import functools |
| 8 |
import gc |
| 9 |
import importlib |
| 10 |
import inspect |
| 11 |
import io |
| 12 |
import linecache |
| 13 |
import os |
| 14 |
import dis |
| 15 |
from os.path import normcase |
| 16 |
import _pickle |
| 17 |
import pickle |
| 18 |
import shutil |
| 19 |
import stat |
| 20 |
import sys |
| 21 |
import subprocess |
| 22 |
import time |
| 23 |
import types |
| 24 |
import tempfile |
| 25 |
import textwrap |
| 26 |
import unicodedata |
| 27 |
import unittest |
| 28 |
import unittest.mock |
| 29 |
import warnings |
| 30 |
import weakref |
| 31 |
|
| 32 |
|
| 33 |
try: |
| 34 |
from concurrent.futures import ThreadPoolExecutor |
| 35 |
except ImportError: |
| 36 |
ThreadPoolExecutor = None |
| 37 |
|
| 38 |
from test.support import cpython_only, import_helper |
| 39 |
from test.support import MISSING_C_DOCSTRINGS, ALWAYS_EQ |
| 40 |
from test.support import run_no_yield_async_fn, EqualToForwardRef |
| 41 |
from test.support.import_helper import DirsOnSysPath, ready_to_import |
| 42 |
from test.support.os_helper import TESTFN, temp_cwd |
| 43 |
from test.support.script_helper import assert_python_ok, assert_python_failure, kill_python |
| 44 |
from test.support import has_subprocess_support |
| 45 |
from test import support |
| 46 |
|
| 47 |
from test.test_inspect import inspect_fodder as mod |
| 48 |
from test.test_inspect import inspect_fodder2 as mod2 |
| 49 |
from test.test_inspect import inspect_stringized_annotations |
| 50 |
from test.test_inspect import inspect_deferred_annotations |
| 51 |
|
| 52 |
|
| 53 |
# Functions tested in this suite: |
| 54 |
# ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, |
| 55 |
# isbuiltin, isroutine, isgenerator, ispackage, isgeneratorfunction, getmembers, |
| 56 |
# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource, |
| 57 |
# getclasstree, getargvalues, formatargvalues, currentframe, |
| 58 |
# stack, trace, ismethoddescriptor, isdatadescriptor, ismethodwrapper |
| 59 |
|
| 60 |
# NOTE: There are some additional tests relating to interaction with |
| 61 |
# zipimport in the test_zipimport_support test module. |
| 62 |
|
| 63 |
modfile = mod.__file__ |
| 64 |
if modfile.endswith(('c', 'o')): |
| 65 |
modfile = modfile[:-1] |
| 66 |
|
| 67 |
# Normalize file names: on Windows, the case of file names of compiled |
| 68 |
# modules depends on the path used to start the python executable. |
| 69 |
modfile = normcase(modfile) |
| 70 |
|
| 71 |
def revise(filename, *args): |
| 72 |
return (normcase(filename),) + args |
| 73 |
|
| 74 |
git = mod.StupidGit() |
| 75 |
|
| 76 |
|
| 77 |
def signatures_with_lexicographic_keyword_only_parameters(): |
| 78 |
""" |
| 79 |
Yields a whole bunch of functions with only keyword-only parameters, |
| 80 |
where those parameters are always in lexicographically sorted order. |
| 81 |
""" |
| 82 |
parameters = ['a', 'bar', 'c', 'delta', 'ephraim', 'magical', 'yoyo', 'z'] |
| 83 |
for i in range(1, 2**len(parameters)): |
| 84 |
p = [] |
| 85 |
bit = 1 |
| 86 |
for j in range(len(parameters)): |
| 87 |
if i & (bit << j): |
| 88 |
p.append(parameters[j]) |
| 89 |
fn_text = "def foo(*, " + ", ".join(p) + "): pass" |
| 90 |
symbols = {} |
| 91 |
exec(fn_text, symbols, symbols) |
| 92 |
yield symbols['foo'] |
| 93 |
|
| 94 |
|
| 95 |
def unsorted_keyword_only_parameters_fn(*, throw, out, the, baby, with_, |
| 96 |
the_, bathwater): |
| 97 |
pass |
| 98 |
|
| 99 |
unsorted_keyword_only_parameters = 'throw out the baby with_ the_ bathwater'.split() |
| 100 |
|
| 101 |
class IsTestBase(unittest.TestCase): |
| 102 |
predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, |
| 103 |
inspect.isframe, inspect.isfunction, inspect.ismethod, |
| 104 |
inspect.ismodule, inspect.istraceback, inspect.ispackage, |
| 105 |
inspect.isgenerator, inspect.isgeneratorfunction, |
| 106 |
inspect.iscoroutine, inspect.iscoroutinefunction, |
| 107 |
inspect.isasyncgen, inspect.isasyncgenfunction, |
| 108 |
inspect.ismethodwrapper]) |
| 109 |
|
| 110 |
def istest(self, predicate, exp): |
| 111 |
obj = eval(exp) |
| 112 |
self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) |
| 113 |
|
| 114 |
for other in self.predicates - set([predicate]): |
| 115 |
if (predicate == inspect.isgeneratorfunction or \ |
| 116 |
predicate == inspect.isasyncgenfunction or \ |
| 117 |
predicate == inspect.iscoroutinefunction) and \ |
| 118 |
other == inspect.isfunction: |
| 119 |
continue |
| 120 |
if predicate == inspect.ispackage and other == inspect.ismodule: |
| 121 |
self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) |
| 122 |
else: |
| 123 |
self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) |
| 124 |
|
| 125 |
def test__all__(self): |
| 126 |
support.check__all__(self, inspect, not_exported=("modulesbyfile",), extra=("get_annotations",)) |
| 127 |
|
| 128 |
def generator_function_example(self): |
| 129 |
for i in range(2): |
| 130 |
yield i |
| 131 |
|
| 132 |
async def async_generator_function_example(self): |
| 133 |
async for i in range(2): |
| 134 |
yield i |
| 135 |
|
| 136 |
async def coroutine_function_example(self): |
| 137 |
return 'spam' |
| 138 |
|
| 139 |
@types.coroutine |
| 140 |
def gen_coroutine_function_example(self): |
| 141 |
yield |
| 142 |
return 'spam' |
| 143 |
|
| 144 |
def meth_noargs(): pass |
| 145 |
def meth_o(object, /): pass |
| 146 |
def meth_self_noargs(self, /): pass |
| 147 |
def meth_self_o(self, object, /): pass |
| 148 |
def meth_type_noargs(type, /): pass |
| 149 |
def meth_type_o(type, object, /): pass |
| 150 |
|
| 151 |
# Decorator decorator that returns a simple wrapped function |
| 152 |
def identity_wrapper(func): |
| 153 |
@functools.wraps(func) |
| 154 |
def wrapped(*args, **kwargs): |
| 155 |
return func(*args, **kwargs) |
| 156 |
return wrapped |
| 157 |
|
| 158 |
# Original signature of the simple wrapped function returned by |
| 159 |
# identity_wrapper(). |
| 160 |
varargs_signature = ( |
| 161 |
(('args', ..., ..., 'var_positional'), |
| 162 |
('kwargs', ..., ..., 'var_keyword')), |
| 163 |
..., |
| 164 |
) |
| 165 |
|
| 166 |
# Decorator decorator that returns a simple descriptor |
| 167 |
class custom_descriptor: |
| 168 |
def __init__(self, func): |
| 169 |
self.func = func |
| 170 |
|
| 171 |
def __get__(self, instance, owner): |
| 172 |
return self.func.__get__(instance, owner) |
| 173 |
|
| 174 |
|
| 175 |
class TestPredicates(IsTestBase): |
| 176 |
|
| 177 |
def test_excluding_predicates(self): |
| 178 |
global tb |
| 179 |
self.istest(inspect.isbuiltin, 'sys.exit') |
| 180 |
self.istest(inspect.isbuiltin, '[].append') |
| 181 |
self.istest(inspect.iscode, 'mod.spam.__code__') |
| 182 |
try: |
| 183 |
1/0 |
| 184 |
except Exception as e: |
| 185 |
tb = e.__traceback__ |
| 186 |
self.istest(inspect.isframe, 'tb.tb_frame') |
| 187 |
self.istest(inspect.istraceback, 'tb') |
| 188 |
if hasattr(types, 'GetSetDescriptorType'): |
| 189 |
self.istest(inspect.isgetsetdescriptor, |
| 190 |
'type(tb.tb_frame).f_locals') |
| 191 |
else: |
| 192 |
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) |
| 193 |
finally: |
| 194 |
# Clear traceback and all the frames and local variables hanging to it. |
| 195 |
tb = None |
| 196 |
self.istest(inspect.isfunction, 'mod.spam') |
| 197 |
self.istest(inspect.isfunction, 'mod.StupidGit.abuse') |
| 198 |
self.istest(inspect.ismethod, 'git.argue') |
| 199 |
self.istest(inspect.ismethod, 'mod.custom_method') |
| 200 |
self.istest(inspect.ismodule, 'mod') |
| 201 |
self.istest(inspect.ismethoddescriptor, 'int.__add__') |
| 202 |
self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory') |
| 203 |
self.istest(inspect.isgenerator, '(x for x in range(2))') |
| 204 |
self.istest(inspect.isgeneratorfunction, 'generator_function_example') |
| 205 |
self.istest(inspect.isasyncgen, |
| 206 |
'async_generator_function_example(1)') |
| 207 |
self.istest(inspect.isasyncgenfunction, |
| 208 |
'async_generator_function_example') |
| 209 |
|
| 210 |
with warnings.catch_warnings(): |
| 211 |
warnings.simplefilter("ignore") |
| 212 |
self.istest(inspect.iscoroutine, 'coroutine_function_example(1)') |
| 213 |
self.istest(inspect.iscoroutinefunction, 'coroutine_function_example') |
| 214 |
|
| 215 |
if hasattr(types, 'MemberDescriptorType'): |
| 216 |
self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') |
| 217 |
else: |
| 218 |
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) |
| 219 |
self.istest(inspect.ismethodwrapper, "object().__str__") |
| 220 |
self.istest(inspect.ismethodwrapper, "object().__eq__") |
| 221 |
self.istest(inspect.ismethodwrapper, "object().__repr__") |
| 222 |
self.assertFalse(inspect.ismethodwrapper(type)) |
| 223 |
self.assertFalse(inspect.ismethodwrapper(int)) |
| 224 |
self.assertFalse(inspect.ismethodwrapper(type("AnyClass", (), {}))) |
| 225 |
|
| 226 |
def test_ispackage(self): |
| 227 |
self.istest(inspect.ispackage, 'unittest') |
| 228 |
self.istest(inspect.ispackage, 'importlib') |
| 229 |
self.assertFalse(inspect.ispackage(inspect)) |
| 230 |
self.assertFalse(inspect.ispackage(mod)) |
| 231 |
self.assertFalse(inspect.ispackage(':)')) |
| 232 |
|
| 233 |
class FakePackage: |
| 234 |
__path__ = None |
| 235 |
|
| 236 |
self.assertFalse(inspect.ispackage(FakePackage())) |
| 237 |
|
| 238 |
def test_iscoroutine(self): |
| 239 |
async_gen_coro = async_generator_function_example(1) |
| 240 |
gen_coro = gen_coroutine_function_example(1) |
| 241 |
coro = coroutine_function_example(1) |
| 242 |
|
| 243 |
class PMClass: |
| 244 |
async_generator_partialmethod_example = functools.partialmethod( |
| 245 |
async_generator_function_example) |
| 246 |
coroutine_partialmethod_example = functools.partialmethod( |
| 247 |
coroutine_function_example) |
| 248 |
gen_coroutine_partialmethod_example = functools.partialmethod( |
| 249 |
gen_coroutine_function_example) |
| 250 |
|
| 251 |
# partialmethods on the class, bound to an instance |
| 252 |
pm_instance = PMClass() |
| 253 |
async_gen_coro_pmi = pm_instance.async_generator_partialmethod_example |
| 254 |
gen_coro_pmi = pm_instance.gen_coroutine_partialmethod_example |
| 255 |
coro_pmi = pm_instance.coroutine_partialmethod_example |
| 256 |
|
| 257 |
# partialmethods on the class, unbound but accessed via the class |
| 258 |
async_gen_coro_pmc = PMClass.async_generator_partialmethod_example |
| 259 |
gen_coro_pmc = PMClass.gen_coroutine_partialmethod_example |
| 260 |
coro_pmc = PMClass.coroutine_partialmethod_example |
| 261 |
|
| 262 |
self.assertFalse( |
| 263 |
inspect.iscoroutinefunction(gen_coroutine_function_example)) |
| 264 |
self.assertFalse( |
| 265 |
inspect.iscoroutinefunction( |
| 266 |
functools.partial(functools.partial( |
| 267 |
gen_coroutine_function_example)))) |
| 268 |
self.assertFalse(inspect.iscoroutinefunction(gen_coro_pmi)) |
| 269 |
self.assertFalse(inspect.iscoroutinefunction(gen_coro_pmc)) |
| 270 |
self.assertFalse(inspect.iscoroutinefunction(inspect)) |
| 271 |
self.assertFalse(inspect.iscoroutine(gen_coro)) |
| 272 |
|
| 273 |
self.assertTrue( |
| 274 |
inspect.isgeneratorfunction(gen_coroutine_function_example)) |
| 275 |
self.assertTrue( |
| 276 |
inspect.isgeneratorfunction( |
| 277 |
functools.partial(functools.partial( |
| 278 |
gen_coroutine_function_example)))) |
| 279 |
self.assertTrue(inspect.isgeneratorfunction(gen_coro_pmi)) |
| 280 |
self.assertTrue(inspect.isgeneratorfunction(gen_coro_pmc)) |
| 281 |
self.assertTrue(inspect.isgenerator(gen_coro)) |
| 282 |
|
| 283 |
async def _fn3(): |
| 284 |
pass |
| 285 |
|
| 286 |
@inspect.markcoroutinefunction |
| 287 |
def fn3(): |
| 288 |
return _fn3() |
| 289 |
|
| 290 |
self.assertTrue(inspect.iscoroutinefunction(fn3)) |
| 291 |
self.assertTrue( |
| 292 |
inspect.iscoroutinefunction( |
| 293 |
inspect.markcoroutinefunction(lambda: _fn3()) |
| 294 |
) |
| 295 |
) |
| 296 |
|
| 297 |
class Cl: |
| 298 |
async def __call__(self): |
| 299 |
pass |
| 300 |
|
| 301 |
self.assertFalse(inspect.iscoroutinefunction(Cl)) |
| 302 |
# instances with async def __call__ are NOT recognised. |
| 303 |
self.assertFalse(inspect.iscoroutinefunction(Cl())) |
| 304 |
# unless explicitly marked. |
| 305 |
self.assertTrue(inspect.iscoroutinefunction( |
| 306 |
inspect.markcoroutinefunction(Cl()) |
| 307 |
)) |
| 308 |
|
| 309 |
class Cl2: |
| 310 |
@inspect.markcoroutinefunction |
| 311 |
def __call__(self): |
| 312 |
pass |
| 313 |
|
| 314 |
self.assertFalse(inspect.iscoroutinefunction(Cl2)) |
| 315 |
# instances with marked __call__ are NOT recognised. |
| 316 |
self.assertFalse(inspect.iscoroutinefunction(Cl2())) |
| 317 |
# unless explicitly marked. |
| 318 |
self.assertTrue(inspect.iscoroutinefunction( |
| 319 |
inspect.markcoroutinefunction(Cl2()) |
| 320 |
)) |
| 321 |
|
| 322 |
class Cl3: |
| 323 |
@inspect.markcoroutinefunction |
| 324 |
@classmethod |
| 325 |
def do_something_classy(cls): |
| 326 |
pass |
| 327 |
|
| 328 |
@inspect.markcoroutinefunction |
| 329 |
@staticmethod |
| 330 |
def do_something_static(): |
| 331 |
pass |
| 332 |
|
| 333 |
self.assertTrue(inspect.iscoroutinefunction(Cl3.do_something_classy)) |
| 334 |
self.assertTrue(inspect.iscoroutinefunction(Cl3.do_something_static)) |
| 335 |
|
| 336 |
self.assertFalse( |
| 337 |
inspect.iscoroutinefunction(unittest.mock.Mock())) |
| 338 |
self.assertTrue( |
| 339 |
inspect.iscoroutinefunction(unittest.mock.AsyncMock())) |
| 340 |
self.assertTrue( |
| 341 |
inspect.iscoroutinefunction(coroutine_function_example)) |
| 342 |
self.assertTrue( |
| 343 |
inspect.iscoroutinefunction( |
| 344 |
functools.partial(functools.partial( |
| 345 |
coroutine_function_example)))) |
| 346 |
self.assertTrue(inspect.iscoroutinefunction(coro_pmi)) |
| 347 |
self.assertTrue(inspect.iscoroutinefunction(coro_pmc)) |
| 348 |
self.assertTrue(inspect.iscoroutine(coro)) |
| 349 |
|
| 350 |
self.assertFalse( |
| 351 |
inspect.isgeneratorfunction(unittest.mock.Mock())) |
| 352 |
self.assertFalse( |
| 353 |
inspect.isgeneratorfunction(unittest.mock.AsyncMock())) |
| 354 |
self.assertFalse( |
| 355 |
inspect.isgeneratorfunction(coroutine_function_example)) |
| 356 |
self.assertFalse( |
| 357 |
inspect.isgeneratorfunction( |
| 358 |
functools.partial(functools.partial( |
| 359 |
coroutine_function_example)))) |
| 360 |
self.assertFalse(inspect.isgeneratorfunction(coro_pmi)) |
| 361 |
self.assertFalse(inspect.isgeneratorfunction(coro_pmc)) |
| 362 |
self.assertFalse(inspect.isgenerator(coro)) |
| 363 |
|
| 364 |
self.assertFalse( |
| 365 |
inspect.isasyncgenfunction(unittest.mock.Mock())) |
| 366 |
self.assertFalse( |
| 367 |
inspect.isasyncgenfunction(unittest.mock.AsyncMock())) |
| 368 |
self.assertFalse( |
| 369 |
inspect.isasyncgenfunction(coroutine_function_example)) |
| 370 |
self.assertTrue( |
| 371 |
inspect.isasyncgenfunction(async_generator_function_example)) |
| 372 |
self.assertTrue( |
| 373 |
inspect.isasyncgenfunction( |
| 374 |
functools.partial(functools.partial( |
| 375 |
async_generator_function_example)))) |
| 376 |
self.assertTrue(inspect.isasyncgenfunction(async_gen_coro_pmi)) |
| 377 |
self.assertTrue(inspect.isasyncgenfunction(async_gen_coro_pmc)) |
| 378 |
self.assertTrue(inspect.isasyncgen(async_gen_coro)) |
| 379 |
|
| 380 |
coro.close(); gen_coro.close(); # silence warnings |
| 381 |
|
| 382 |
def test_isawaitable(self): |
| 383 |
def gen(): yield |
| 384 |
self.assertFalse(inspect.isawaitable(gen())) |
| 385 |
|
| 386 |
coro = coroutine_function_example(1) |
| 387 |
gen_coro = gen_coroutine_function_example(1) |
| 388 |
|
| 389 |
self.assertTrue(inspect.isawaitable(coro)) |
| 390 |
self.assertTrue(inspect.isawaitable(gen_coro)) |
| 391 |
|
| 392 |
class Future: |
| 393 |
def __await__(): |
| 394 |
pass |
| 395 |
self.assertTrue(inspect.isawaitable(Future())) |
| 396 |
self.assertFalse(inspect.isawaitable(Future)) |
| 397 |
|
| 398 |
class NotFuture: pass |
| 399 |
not_fut = NotFuture() |
| 400 |
not_fut.__await__ = lambda: None |
| 401 |
self.assertFalse(inspect.isawaitable(not_fut)) |
| 402 |
|
| 403 |
coro.close(); gen_coro.close() # silence warnings |
| 404 |
|
| 405 |
def test_isroutine(self): |
| 406 |
# method |
| 407 |
self.assertTrue(inspect.isroutine(git.argue)) |
| 408 |
self.assertTrue(inspect.isroutine(mod.custom_method)) |
| 409 |
self.assertTrue(inspect.isroutine([].count)) |
| 410 |
# function |
| 411 |
self.assertTrue(inspect.isroutine(mod.spam)) |
| 412 |
self.assertTrue(inspect.isroutine(mod.StupidGit.abuse)) |
| 413 |
# slot-wrapper |
| 414 |
self.assertTrue(inspect.isroutine(object.__init__)) |
| 415 |
self.assertTrue(inspect.isroutine(object.__str__)) |
| 416 |
self.assertTrue(inspect.isroutine(object.__lt__)) |
| 417 |
self.assertTrue(inspect.isroutine(int.__lt__)) |
| 418 |
# method-wrapper |
| 419 |
self.assertTrue(inspect.isroutine(object().__init__)) |
| 420 |
self.assertTrue(inspect.isroutine(object().__str__)) |
| 421 |
self.assertTrue(inspect.isroutine(object().__lt__)) |
| 422 |
self.assertTrue(inspect.isroutine((42).__lt__)) |
| 423 |
# method-descriptor |
| 424 |
self.assertTrue(inspect.isroutine(str.join)) |
| 425 |
self.assertTrue(inspect.isroutine(list.append)) |
| 426 |
self.assertTrue(inspect.isroutine(''.join)) |
| 427 |
self.assertTrue(inspect.isroutine([].append)) |
| 428 |
# object |
| 429 |
self.assertFalse(inspect.isroutine(object)) |
| 430 |
self.assertFalse(inspect.isroutine(object())) |
| 431 |
self.assertFalse(inspect.isroutine(str())) |
| 432 |
# module |
| 433 |
self.assertFalse(inspect.isroutine(mod)) |
| 434 |
# type |
| 435 |
self.assertFalse(inspect.isroutine(type)) |
| 436 |
self.assertFalse(inspect.isroutine(int)) |
| 437 |
self.assertFalse(inspect.isroutine(type('some_class', (), {}))) |
| 438 |
# partial |
| 439 |
self.assertTrue(inspect.isroutine(functools.partial(mod.spam))) |
| 440 |
|
| 441 |
def test_isroutine_singledispatch(self): |
| 442 |
self.assertTrue(inspect.isroutine(functools.singledispatch(mod.spam))) |
| 443 |
|
| 444 |
class A: |
| 445 |
@functools.singledispatchmethod |
| 446 |
def method(self, arg): |
| 447 |
pass |
| 448 |
@functools.singledispatchmethod |
| 449 |
@classmethod |
| 450 |
def class_method(cls, arg): |
| 451 |
pass |
| 452 |
@functools.singledispatchmethod |
| 453 |
@staticmethod |
| 454 |
def static_method(arg): |
| 455 |
pass |
| 456 |
|
| 457 |
self.assertTrue(inspect.isroutine(A.method)) |
| 458 |
self.assertTrue(inspect.isroutine(A().method)) |
| 459 |
self.assertTrue(inspect.isroutine(A.static_method)) |
| 460 |
self.assertTrue(inspect.isroutine(A.class_method)) |
| 461 |
|
| 462 |
def test_isclass(self): |
| 463 |
self.istest(inspect.isclass, 'mod.StupidGit') |
| 464 |
self.assertTrue(inspect.isclass(list)) |
| 465 |
|
| 466 |
class CustomGetattr(object): |
| 467 |
def __getattr__(self, attr): |
| 468 |
return None |
| 469 |
self.assertFalse(inspect.isclass(CustomGetattr())) |
| 470 |
|
| 471 |
def test_get_slot_members(self): |
| 472 |
class C(object): |
| 473 |
__slots__ = ("a", "b") |
| 474 |
x = C() |
| 475 |
x.a = 42 |
| 476 |
members = dict(inspect.getmembers(x)) |
| 477 |
self.assertIn('a', members) |
| 478 |
self.assertNotIn('b', members) |
| 479 |
|
| 480 |
def test_isabstract(self): |
| 481 |
from abc import ABCMeta, abstractmethod |
| 482 |
|
| 483 |
class AbstractClassExample(metaclass=ABCMeta): |
| 484 |
|
| 485 |
@abstractmethod |
| 486 |
def foo(self): |
| 487 |
pass |
| 488 |
|
| 489 |
class ClassExample(AbstractClassExample): |
| 490 |
def foo(self): |
| 491 |
pass |
| 492 |
|
| 493 |
a = ClassExample() |
| 494 |
|
| 495 |
# Test general behaviour. |
| 496 |
self.assertTrue(inspect.isabstract(AbstractClassExample)) |
| 497 |
self.assertFalse(inspect.isabstract(ClassExample)) |
| 498 |
self.assertFalse(inspect.isabstract(a)) |
| 499 |
self.assertFalse(inspect.isabstract(int)) |
| 500 |
self.assertFalse(inspect.isabstract(5)) |
| 501 |
|
| 502 |
def test_isabstract_during_init_subclass(self): |
| 503 |
from abc import ABCMeta, abstractmethod |
| 504 |
isabstract_checks = [] |
| 505 |
class AbstractChecker(metaclass=ABCMeta): |
| 506 |
def __init_subclass__(cls): |
| 507 |
isabstract_checks.append(inspect.isabstract(cls)) |
| 508 |
class AbstractClassExample(AbstractChecker): |
| 509 |
@abstractmethod |
| 510 |
def foo(self): |
| 511 |
pass |
| 512 |
class ClassExample(AbstractClassExample): |
| 513 |
def foo(self): |
| 514 |
pass |
| 515 |
self.assertEqual(isabstract_checks, [True, False]) |
| 516 |
|
| 517 |
isabstract_checks.clear() |
| 518 |
class AbstractChild(AbstractClassExample): |
| 519 |
pass |
| 520 |
class AbstractGrandchild(AbstractChild): |
| 521 |
pass |
| 522 |
class ConcreteGrandchild(ClassExample): |
| 523 |
pass |
| 524 |
self.assertEqual(isabstract_checks, [True, True, False]) |
| 525 |
|
| 526 |
|
| 527 |
class TestInterpreterStack(IsTestBase): |
| 528 |
def __init__(self, *args, **kwargs): |
| 529 |
unittest.TestCase.__init__(self, *args, **kwargs) |
| 530 |
|
| 531 |
git.abuse(7, 8, 9) |
| 532 |
|
| 533 |
def test_abuse_done(self): |
| 534 |
self.istest(inspect.istraceback, 'git.ex.__traceback__') |
| 535 |
self.istest(inspect.isframe, 'mod.fr') |
| 536 |
|
| 537 |
def test_stack(self): |
| 538 |
self.assertTrue(len(mod.st) >= 5) |
| 539 |
frame1, frame2, frame3, frame4, *_ = mod.st |
| 540 |
frameinfo = revise(*frame1[1:]) |
| 541 |
self.assertEqual(frameinfo, |
| 542 |
(modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) |
| 543 |
self.assertEqual(frame1.positions, dis.Positions(16, 16, 9, 24)) |
| 544 |
frameinfo = revise(*frame2[1:]) |
| 545 |
self.assertEqual(frameinfo, |
| 546 |
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
| 547 |
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22)) |
| 548 |
frameinfo = revise(*frame3[1:]) |
| 549 |
self.assertEqual(frameinfo, |
| 550 |
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
| 551 |
self.assertEqual(frame3.positions, dis.Positions(43, 43, 12, 25)) |
| 552 |
frameinfo = revise(*frame4[1:]) |
| 553 |
self.assertEqual(frameinfo, |
| 554 |
(modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0)) |
| 555 |
self.assertEqual(frame4.positions, dis.Positions(39, 39, 8, 27)) |
| 556 |
# Test named tuple fields |
| 557 |
record = mod.st[0] |
| 558 |
self.assertIs(record.frame, mod.fr) |
| 559 |
self.assertEqual(record.lineno, 16) |
| 560 |
self.assertEqual(record.filename, mod.__file__) |
| 561 |
self.assertEqual(record.function, 'eggs') |
| 562 |
self.assertIn('inspect.stack()', record.code_context[0]) |
| 563 |
self.assertEqual(record.index, 0) |
| 564 |
|
| 565 |
def test_trace(self): |
| 566 |
self.assertEqual(len(git.tr), 3) |
| 567 |
frame1, frame2, frame3, = git.tr |
| 568 |
self.assertEqual(revise(*frame1[1:]), |
| 569 |
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
| 570 |
self.assertEqual(frame1.positions, dis.Positions(43, 43, 12, 25)) |
| 571 |
self.assertEqual(revise(*frame2[1:]), |
| 572 |
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
| 573 |
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22)) |
| 574 |
self.assertEqual(revise(*frame3[1:]), |
| 575 |
(modfile, 18, 'eggs', [' q = y / 0\n'], 0)) |
| 576 |
self.assertEqual(frame3.positions, dis.Positions(18, 18, 8, 13)) |
| 577 |
|
| 578 |
def test_frame(self): |
| 579 |
args, varargs, varkw, locals = inspect.getargvalues(mod.fr) |
| 580 |
self.assertEqual(args, ['x', 'y']) |
| 581 |
self.assertEqual(varargs, None) |
| 582 |
self.assertEqual(varkw, None) |
| 583 |
self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14}) |
| 584 |
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
| 585 |
'(x=11, y=14)') |
| 586 |
|
| 587 |
def test_previous_frame(self): |
| 588 |
args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) |
| 589 |
self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f']) |
| 590 |
self.assertEqual(varargs, 'g') |
| 591 |
self.assertEqual(varkw, 'h') |
| 592 |
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
| 593 |
'(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})') |
| 594 |
|
| 595 |
class GetSourceBase(unittest.TestCase): |
| 596 |
# Subclasses must override. |
| 597 |
fodderModule = None |
| 598 |
|
| 599 |
def setUp(self): |
| 600 |
with open(inspect.getsourcefile(self.fodderModule), encoding="utf-8") as fp: |
| 601 |
self.source = fp.read() |
| 602 |
|
| 603 |
def sourcerange(self, top, bottom): |
| 604 |
lines = self.source.split("\n") |
| 605 |
return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "") |
| 606 |
|
| 607 |
def assertSourceEqual(self, obj, top, bottom): |
| 608 |
self.assertEqual(inspect.getsource(obj), |
| 609 |
self.sourcerange(top, bottom)) |
| 610 |
|
| 611 |
class SlotUser: |
| 612 |
'Docstrings for __slots__' |
| 613 |
__slots__ = {'power': 'measured in kilowatts', |
| 614 |
'distance': 'measured in kilometers'} |
| 615 |
|
| 616 |
class TestRetrievingSourceCode(GetSourceBase): |
| 617 |
fodderModule = mod |
| 618 |
|
| 619 |
def test_getclasses(self): |
| 620 |
classes = inspect.getmembers(mod, inspect.isclass) |
| 621 |
self.assertEqual(classes, |
| 622 |
[('FesteringGob', mod.FesteringGob), |
| 623 |
('MalodorousPervert', mod.MalodorousPervert), |
| 624 |
('ParrotDroppings', mod.ParrotDroppings), |
| 625 |
('StupidGit', mod.StupidGit), |
| 626 |
('Tit', mod.MalodorousPervert), |
| 627 |
('WhichComments', mod.WhichComments), |
| 628 |
]) |
| 629 |
tree = inspect.getclasstree([cls[1] for cls in classes]) |
| 630 |
self.assertEqual(tree, |
| 631 |
[(object, ()), |
| 632 |
[(mod.ParrotDroppings, (object,)), |
| 633 |
[(mod.FesteringGob, (mod.MalodorousPervert, |
| 634 |
mod.ParrotDroppings)) |
| 635 |
], |
| 636 |
(mod.StupidGit, (object,)), |
| 637 |
[(mod.MalodorousPervert, (mod.StupidGit,)), |
| 638 |
[(mod.FesteringGob, (mod.MalodorousPervert, |
| 639 |
mod.ParrotDroppings)) |
| 640 |
] |
| 641 |
], |
| 642 |
(mod.WhichComments, (object,),) |
| 643 |
] |
| 644 |
]) |
| 645 |
tree = inspect.getclasstree([cls[1] for cls in classes], True) |
| 646 |
self.assertEqual(tree, |
| 647 |
[(object, ()), |
| 648 |
[(mod.ParrotDroppings, (object,)), |
| 649 |
(mod.StupidGit, (object,)), |
| 650 |
[(mod.MalodorousPervert, (mod.StupidGit,)), |
| 651 |
[(mod.FesteringGob, (mod.MalodorousPervert, |
| 652 |
mod.ParrotDroppings)) |
| 653 |
] |
| 654 |
], |
| 655 |
(mod.WhichComments, (object,),) |
| 656 |
] |
| 657 |
]) |
| 658 |
|
| 659 |
def test_getfunctions(self): |
| 660 |
functions = inspect.getmembers(mod, inspect.isfunction) |
| 661 |
self.assertEqual(functions, [('after_closing', mod.after_closing), |
| 662 |
('eggs', mod.eggs), |
| 663 |
('lobbest', mod.lobbest), |
| 664 |
('spam', mod.spam)]) |
| 665 |
|
| 666 |
@unittest.skipIf(sys.flags.optimize >= 2, |
| 667 |
"Docstrings are omitted with -O2 and above") |
| 668 |
def test_getdoc(self): |
| 669 |
self.assertEqual(inspect.getdoc(mod), 'A module docstring.') |
| 670 |
self.assertEqual(inspect.getdoc(mod.StupidGit), |
| 671 |
'A longer,\n\nindented\n\ndocstring.') |
| 672 |
self.assertEqual(inspect.getdoc(git.abuse), |
| 673 |
'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 674 |
self.assertEqual(inspect.getdoc(SlotUser.power), |
| 675 |
'measured in kilowatts') |
| 676 |
self.assertEqual(inspect.getdoc(SlotUser.distance), |
| 677 |
'measured in kilometers') |
| 678 |
|
| 679 |
@unittest.skipIf(sys.flags.optimize >= 2, |
| 680 |
"Docstrings are omitted with -O2 and above") |
| 681 |
def test_getdoc_inherited(self): |
| 682 |
self.assertEqual(inspect.getdoc(mod.FesteringGob), |
| 683 |
'A longer,\n\nindented\n\ndocstring.') |
| 684 |
self.assertEqual(inspect.getdoc(mod.FesteringGob.abuse), |
| 685 |
'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 686 |
self.assertEqual(inspect.getdoc(mod.FesteringGob().abuse), |
| 687 |
'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 688 |
self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction), |
| 689 |
'The automatic gainsaying.') |
| 690 |
|
| 691 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings") |
| 692 |
def test_finddoc(self): |
| 693 |
finddoc = inspect._finddoc |
| 694 |
self.assertEqual(finddoc(int), int.__doc__) |
| 695 |
self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__) |
| 696 |
self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__) |
| 697 |
self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__) |
| 698 |
self.assertEqual(finddoc(int.real), int.real.__doc__) |
| 699 |
|
| 700 |
cleandoc_testdata = [ |
| 701 |
# first line should have different margin |
| 702 |
(' An\n indented\n docstring.', 'An\nindented\n docstring.'), |
| 703 |
# trailing whitespace are not removed. |
| 704 |
(' An \n \n indented \n docstring. ', |
| 705 |
'An \n \nindented \n docstring. '), |
| 706 |
# NUL is not termination. |
| 707 |
('doc\0string\n\n second\0line\n third\0line\0', |
| 708 |
'doc\0string\n\nsecond\0line\nthird\0line\0'), |
| 709 |
# first line is lstrip()-ped. other lines are kept when no margin.[w: |
| 710 |
(' ', ''), |
| 711 |
# compiler.cleandoc() doesn't strip leading/trailing newlines |
| 712 |
# to keep maximum backward compatibility. |
| 713 |
# inspect.cleandoc() removes them. |
| 714 |
('\n\n\n first paragraph\n\n second paragraph\n\n', |
| 715 |
'\n\n\nfirst paragraph\n\n second paragraph\n\n'), |
| 716 |
(' \n \n \n ', '\n \n \n '), |
| 717 |
] |
| 718 |
|
| 719 |
def test_cleandoc(self): |
| 720 |
func = inspect.cleandoc |
| 721 |
for i, (input, expected) in enumerate(self.cleandoc_testdata): |
| 722 |
# only inspect.cleandoc() strip \n |
| 723 |
expected = expected.strip('\n') |
| 724 |
with self.subTest(i=i): |
| 725 |
self.assertEqual(func(input), expected) |
| 726 |
|
| 727 |
@cpython_only |
| 728 |
def test_c_cleandoc(self): |
| 729 |
try: |
| 730 |
import _testinternalcapi |
| 731 |
except ImportError: |
| 732 |
return unittest.skip("requires _testinternalcapi") |
| 733 |
func = _testinternalcapi.compiler_cleandoc |
| 734 |
for i, (input, expected) in enumerate(self.cleandoc_testdata): |
| 735 |
with self.subTest(i=i): |
| 736 |
self.assertEqual(func(input), expected) |
| 737 |
|
| 738 |
def test_getcomments(self): |
| 739 |
self.assertEqual(inspect.getcomments(mod), '# line 1\n') |
| 740 |
self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') |
| 741 |
self.assertEqual(inspect.getcomments(mod2.cls160), '# line 159\n') |
| 742 |
# If the object source file is not available, return None. |
| 743 |
co = compile('x=1', '_non_existing_filename.py', 'exec') |
| 744 |
self.assertIsNone(inspect.getcomments(co)) |
| 745 |
# If the object has been defined in C, return None. |
| 746 |
self.assertIsNone(inspect.getcomments(list)) |
| 747 |
|
| 748 |
def test_getmodule(self): |
| 749 |
# Check actual module |
| 750 |
self.assertEqual(inspect.getmodule(mod), mod) |
| 751 |
# Check class (uses __module__ attribute) |
| 752 |
self.assertEqual(inspect.getmodule(mod.StupidGit), mod) |
| 753 |
# Check a method (no __module__ attribute, falls back to filename) |
| 754 |
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
| 755 |
# Do it again (check the caching isn't broken) |
| 756 |
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
| 757 |
# Check a builtin |
| 758 |
self.assertEqual(inspect.getmodule(str), sys.modules["builtins"]) |
| 759 |
# Check filename override |
| 760 |
self.assertEqual(inspect.getmodule(None, modfile), mod) |
| 761 |
|
| 762 |
def test_getmodule_file_not_found(self): |
| 763 |
# See bpo-45406 |
| 764 |
def _getabsfile(obj, _filename): |
| 765 |
raise FileNotFoundError('bad file') |
| 766 |
with unittest.mock.patch('inspect.getabsfile', _getabsfile): |
| 767 |
f = inspect.currentframe() |
| 768 |
self.assertIsNone(inspect.getmodule(f)) |
| 769 |
inspect.getouterframes(f) # smoke test |
| 770 |
|
| 771 |
def test_getframeinfo_get_first_line(self): |
| 772 |
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50) |
| 773 |
self.assertEqual(frame_info.code_context[0], "# line 1\n") |
| 774 |
self.assertEqual(frame_info.code_context[1], "'A module docstring.'\n") |
| 775 |
|
| 776 |
def test_getsource(self): |
| 777 |
self.assertSourceEqual(git.abuse, 29, 39) |
| 778 |
self.assertSourceEqual(mod.StupidGit, 21, 51) |
| 779 |
self.assertSourceEqual(mod.lobbest, 75, 76) |
| 780 |
self.assertSourceEqual(mod.after_closing, 120, 120) |
| 781 |
|
| 782 |
def test_getsourcefile(self): |
| 783 |
self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile) |
| 784 |
self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile) |
| 785 |
fn = "_non_existing_filename_used_for_sourcefile_test.py" |
| 786 |
co = compile("x=1", fn, "exec") |
| 787 |
self.assertEqual(inspect.getsourcefile(co), None) |
| 788 |
linecache.cache[co.co_filename] = (1, None, "None", co.co_filename) |
| 789 |
try: |
| 790 |
self.assertEqual(normcase(inspect.getsourcefile(co)), fn) |
| 791 |
finally: |
| 792 |
del linecache.cache[co.co_filename] |
| 793 |
|
| 794 |
def test_getsource_empty_file(self): |
| 795 |
with temp_cwd() as cwd: |
| 796 |
with open('empty_file.py', 'w'): |
| 797 |
pass |
| 798 |
sys.path.insert(0, cwd) |
| 799 |
try: |
| 800 |
import empty_file |
| 801 |
self.assertEqual(inspect.getsource(empty_file), '\n') |
| 802 |
self.assertEqual(inspect.getsourcelines(empty_file), (['\n'], 0)) |
| 803 |
finally: |
| 804 |
sys.path.remove(cwd) |
| 805 |
|
| 806 |
def test_getfile(self): |
| 807 |
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) |
| 808 |
|
| 809 |
def test_getfile_builtin_module(self): |
| 810 |
with self.assertRaises(TypeError) as e: |
| 811 |
inspect.getfile(sys) |
| 812 |
self.assertStartsWith(str(e.exception), '<module') |
| 813 |
|
| 814 |
def test_getfile_builtin_class(self): |
| 815 |
with self.assertRaises(TypeError) as e: |
| 816 |
inspect.getfile(int) |
| 817 |
self.assertStartsWith(str(e.exception), '<class') |
| 818 |
|
| 819 |
def test_getfile_builtin_function_or_method(self): |
| 820 |
with self.assertRaises(TypeError) as e_abs: |
| 821 |
inspect.getfile(abs) |
| 822 |
self.assertIn('expected, got', str(e_abs.exception)) |
| 823 |
with self.assertRaises(TypeError) as e_append: |
| 824 |
inspect.getfile(list.append) |
| 825 |
self.assertIn('expected, got', str(e_append.exception)) |
| 826 |
|
| 827 |
def test_getfile_class_without_module(self): |
| 828 |
class CM(type): |
| 829 |
@property |
| 830 |
def __module__(cls): |
| 831 |
raise AttributeError |
| 832 |
class C(metaclass=CM): |
| 833 |
pass |
| 834 |
with self.assertRaises(TypeError): |
| 835 |
inspect.getfile(C) |
| 836 |
|
| 837 |
def test_getfile_broken_repr(self): |
| 838 |
class ErrorRepr: |
| 839 |
def __repr__(self): |
| 840 |
raise Exception('xyz') |
| 841 |
er = ErrorRepr() |
| 842 |
with self.assertRaises(TypeError): |
| 843 |
inspect.getfile(er) |
| 844 |
|
| 845 |
def test_getmodule_recursion(self): |
| 846 |
from types import ModuleType |
| 847 |
name = '__inspect_dummy' |
| 848 |
m = sys.modules[name] = ModuleType(name) |
| 849 |
m.__file__ = "<string>" # hopefully not a real filename... |
| 850 |
m.__loader__ = "dummy" # pretend the filename is understood by a loader |
| 851 |
exec("def x(): pass", m.__dict__) |
| 852 |
self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>') |
| 853 |
del sys.modules[name] |
| 854 |
inspect.getmodule(compile('a=10','','single')) |
| 855 |
|
| 856 |
def test_proceed_with_fake_filename(self): |
| 857 |
'''doctest monkeypatches linecache to enable inspection''' |
| 858 |
fn, source = '<test>', 'def x(): pass\n' |
| 859 |
getlines = linecache.getlines |
| 860 |
def monkey(filename, module_globals=None): |
| 861 |
if filename == fn: |
| 862 |
return source.splitlines(keepends=True) |
| 863 |
else: |
| 864 |
return getlines(filename, module_globals) |
| 865 |
linecache.getlines = monkey |
| 866 |
try: |
| 867 |
ns = {} |
| 868 |
exec(compile(source, fn, 'single'), ns) |
| 869 |
inspect.getsource(ns["x"]) |
| 870 |
finally: |
| 871 |
linecache.getlines = getlines |
| 872 |
|
| 873 |
def test_getsource_on_code_object(self): |
| 874 |
self.assertSourceEqual(mod.eggs.__code__, 12, 18) |
| 875 |
|
| 876 |
def test_getsource_on_generated_class(self): |
| 877 |
A = type('A', (unittest.TestCase,), {}) |
| 878 |
self.assertEqual(inspect.getsourcefile(A), __file__) |
| 879 |
self.assertEqual(inspect.getfile(A), __file__) |
| 880 |
self.assertIs(inspect.getmodule(A), sys.modules[__name__]) |
| 881 |
self.assertRaises(OSError, inspect.getsource, A) |
| 882 |
self.assertRaises(OSError, inspect.getsourcelines, A) |
| 883 |
self.assertIsNone(inspect.getcomments(A)) |
| 884 |
|
| 885 |
def test_getsource_on_class_without_firstlineno(self): |
| 886 |
__firstlineno__ = 1 |
| 887 |
class C: |
| 888 |
nonlocal __firstlineno__ |
| 889 |
self.assertRaises(OSError, inspect.getsource, C) |
| 890 |
|
| 891 |
class TestGetsourceStdlib(unittest.TestCase): |
| 892 |
# Test Python implementations of the stdlib modules |
| 893 |
|
| 894 |
def test_getsource_stdlib_collections_abc(self): |
| 895 |
import collections.abc |
| 896 |
lines, lineno = inspect.getsourcelines(collections.abc.Sequence) |
| 897 |
self.assertEqual(lines[0], 'class Sequence(Reversible, Collection):\n') |
| 898 |
src = inspect.getsource(collections.abc.Sequence) |
| 899 |
self.assertEqual(src.splitlines(True), lines) |
| 900 |
|
| 901 |
def test_getsource_stdlib_tomllib(self): |
| 902 |
import tomllib |
| 903 |
self.assertRaises(OSError, inspect.getsource, tomllib.TOMLDecodeError) |
| 904 |
self.assertRaises(OSError, inspect.getsourcelines, tomllib.TOMLDecodeError) |
| 905 |
|
| 906 |
def test_getsource_stdlib_abc(self): |
| 907 |
# Pure Python implementation |
| 908 |
abc = import_helper.import_fresh_module('abc', blocked=['_abc']) |
| 909 |
with support.swap_item(sys.modules, 'abc', abc): |
| 910 |
self.assertRaises(OSError, inspect.getsource, abc.ABCMeta) |
| 911 |
self.assertRaises(OSError, inspect.getsourcelines, abc.ABCMeta) |
| 912 |
# With C acceleration |
| 913 |
import abc |
| 914 |
try: |
| 915 |
src = inspect.getsource(abc.ABCMeta) |
| 916 |
lines, lineno = inspect.getsourcelines(abc.ABCMeta) |
| 917 |
except OSError: |
| 918 |
pass |
| 919 |
else: |
| 920 |
self.assertEqual(lines[0], ' class ABCMeta(type):\n') |
| 921 |
self.assertEqual(src.splitlines(True), lines) |
| 922 |
|
| 923 |
def test_getsource_stdlib_decimal(self): |
| 924 |
# Pure Python implementation |
| 925 |
decimal = import_helper.import_fresh_module('decimal', blocked=['_decimal']) |
| 926 |
with support.swap_item(sys.modules, 'decimal', decimal): |
| 927 |
src = inspect.getsource(decimal.Decimal) |
| 928 |
lines, lineno = inspect.getsourcelines(decimal.Decimal) |
| 929 |
self.assertEqual(lines[0], 'class Decimal(object):\n') |
| 930 |
self.assertEqual(src.splitlines(True), lines) |
| 931 |
|
| 932 |
class TestGetsourceInteractive(unittest.TestCase): |
| 933 |
@support.force_not_colorized |
| 934 |
def test_getclasses_interactive(self): |
| 935 |
# bpo-44648: simulate a REPL session; |
| 936 |
# there is no `__file__` in the __main__ module |
| 937 |
code = "import sys, inspect; \ |
| 938 |
assert not hasattr(sys.modules['__main__'], '__file__'); \ |
| 939 |
A = type('A', (), {}); \ |
| 940 |
inspect.getsource(A)" |
| 941 |
_, _, stderr = assert_python_failure("-c", code, __isolated=True) |
| 942 |
self.assertIn(b'OSError: source code not available', stderr) |
| 943 |
|
| 944 |
class TestGettingSourceOfToplevelFrames(GetSourceBase): |
| 945 |
fodderModule = mod |
| 946 |
|
| 947 |
def test_range_toplevel_frame(self): |
| 948 |
self.maxDiff = None |
| 949 |
self.assertSourceEqual(mod.currentframe, 1, None) |
| 950 |
|
| 951 |
def test_range_traceback_toplevel_frame(self): |
| 952 |
self.assertSourceEqual(mod.tb, 1, None) |
| 953 |
|
| 954 |
class TestDecorators(GetSourceBase): |
| 955 |
fodderModule = mod2 |
| 956 |
|
| 957 |
def test_wrapped_decorator(self): |
| 958 |
self.assertSourceEqual(mod2.wrapped, 14, 17) |
| 959 |
|
| 960 |
def test_replacing_decorator(self): |
| 961 |
self.assertSourceEqual(mod2.gone, 9, 10) |
| 962 |
|
| 963 |
def test_getsource_unwrap(self): |
| 964 |
self.assertSourceEqual(mod2.real, 130, 132) |
| 965 |
|
| 966 |
def test_decorator_with_lambda(self): |
| 967 |
self.assertSourceEqual(mod2.func114, 113, 115) |
| 968 |
|
| 969 |
class TestOneliners(GetSourceBase): |
| 970 |
fodderModule = mod2 |
| 971 |
def test_oneline_lambda(self): |
| 972 |
# Test inspect.getsource with a one-line lambda function. |
| 973 |
self.assertSourceEqual(mod2.oll, 25, 25) |
| 974 |
|
| 975 |
def test_threeline_lambda(self): |
| 976 |
# Test inspect.getsource with a three-line lambda function, |
| 977 |
# where the second and third lines are _not_ indented. |
| 978 |
self.assertSourceEqual(mod2.tll, 28, 30) |
| 979 |
|
| 980 |
def test_twoline_indented_lambda(self): |
| 981 |
# Test inspect.getsource with a two-line lambda function, |
| 982 |
# where the second line _is_ indented. |
| 983 |
self.assertSourceEqual(mod2.tlli, 33, 34) |
| 984 |
|
| 985 |
def test_parenthesized_multiline_lambda(self): |
| 986 |
# Test inspect.getsource with a parenthesized multi-line lambda |
| 987 |
# function. |
| 988 |
self.assertSourceEqual(mod2.parenthesized_lambda, 279, 279) |
| 989 |
self.assertSourceEqual(mod2.parenthesized_lambda2, 281, 281) |
| 990 |
self.assertSourceEqual(mod2.parenthesized_lambda3, 283, 283) |
| 991 |
|
| 992 |
def test_post_line_parenthesized_lambda(self): |
| 993 |
# Test inspect.getsource with a parenthesized multi-line lambda |
| 994 |
# function. |
| 995 |
self.assertSourceEqual(mod2.post_line_parenthesized_lambda1, 286, 287) |
| 996 |
|
| 997 |
def test_nested_lambda(self): |
| 998 |
# Test inspect.getsource with a nested lambda function. |
| 999 |
self.assertSourceEqual(mod2.nested_lambda, 291, 292) |
| 1000 |
|
| 1001 |
def test_onelinefunc(self): |
| 1002 |
# Test inspect.getsource with a regular one-line function. |
| 1003 |
self.assertSourceEqual(mod2.onelinefunc, 37, 37) |
| 1004 |
|
| 1005 |
def test_manyargs(self): |
| 1006 |
# Test inspect.getsource with a regular function where |
| 1007 |
# the arguments are on two lines and _not_ indented and |
| 1008 |
# the body on the second line with the last arguments. |
| 1009 |
self.assertSourceEqual(mod2.manyargs, 40, 41) |
| 1010 |
|
| 1011 |
def test_twolinefunc(self): |
| 1012 |
# Test inspect.getsource with a regular function where |
| 1013 |
# the body is on two lines, following the argument list and |
| 1014 |
# continued on the next line by a \\. |
| 1015 |
self.assertSourceEqual(mod2.twolinefunc, 44, 45) |
| 1016 |
|
| 1017 |
def test_lambda_in_list(self): |
| 1018 |
# Test inspect.getsource with a one-line lambda function |
| 1019 |
# defined in a list, indented. |
| 1020 |
self.assertSourceEqual(mod2.a[1], 49, 49) |
| 1021 |
|
| 1022 |
def test_anonymous(self): |
| 1023 |
# Test inspect.getsource with a lambda function defined |
| 1024 |
# as argument to another function. |
| 1025 |
self.assertSourceEqual(mod2.anonymous, 55, 55) |
| 1026 |
|
| 1027 |
def test_enum(self): |
| 1028 |
self.assertSourceEqual(mod2.enum322, 322, 323) |
| 1029 |
self.assertSourceEqual(mod2.enum326, 326, 327) |
| 1030 |
self.assertSourceEqual(mod2.flag330, 330, 331) |
| 1031 |
self.assertSourceEqual(mod2.flag334, 334, 335) |
| 1032 |
self.assertRaises(OSError, inspect.getsource, mod2.simple_enum338) |
| 1033 |
self.assertRaises(OSError, inspect.getsource, mod2.simple_enum339) |
| 1034 |
self.assertRaises(OSError, inspect.getsource, mod2.simple_flag340) |
| 1035 |
self.assertRaises(OSError, inspect.getsource, mod2.simple_flag341) |
| 1036 |
|
| 1037 |
def test_namedtuple(self): |
| 1038 |
self.assertSourceEqual(mod2.nt346, 346, 348) |
| 1039 |
self.assertRaises(OSError, inspect.getsource, mod2.nt351) |
| 1040 |
|
| 1041 |
def test_typeddict(self): |
| 1042 |
self.assertSourceEqual(mod2.td354, 354, 356) |
| 1043 |
self.assertRaises(OSError, inspect.getsource, mod2.td359) |
| 1044 |
|
| 1045 |
def test_dataclass(self): |
| 1046 |
self.assertSourceEqual(mod2.dc364, 364, 367) |
| 1047 |
self.assertRaises(OSError, inspect.getsource, mod2.dc370) |
| 1048 |
self.assertRaises(OSError, inspect.getsource, mod2.dc371) |
| 1049 |
|
| 1050 |
class TestBlockComments(GetSourceBase): |
| 1051 |
fodderModule = mod |
| 1052 |
|
| 1053 |
def test_toplevel_class(self): |
| 1054 |
self.assertSourceEqual(mod.WhichComments, 96, 114) |
| 1055 |
|
| 1056 |
def test_class_method(self): |
| 1057 |
self.assertSourceEqual(mod.WhichComments.f, 99, 104) |
| 1058 |
|
| 1059 |
def test_class_async_method(self): |
| 1060 |
self.assertSourceEqual(mod.WhichComments.asyncf, 109, 112) |
| 1061 |
|
| 1062 |
class TestBuggyCases(GetSourceBase): |
| 1063 |
fodderModule = mod2 |
| 1064 |
|
| 1065 |
def test_with_comment(self): |
| 1066 |
self.assertSourceEqual(mod2.with_comment, 58, 59) |
| 1067 |
|
| 1068 |
def test_multiline_sig(self): |
| 1069 |
self.assertSourceEqual(mod2.multiline_sig[0], 63, 64) |
| 1070 |
|
| 1071 |
def test_nested_class(self): |
| 1072 |
self.assertSourceEqual(mod2.func69().func71, 71, 72) |
| 1073 |
|
| 1074 |
def test_one_liner_followed_by_non_name(self): |
| 1075 |
self.assertSourceEqual(mod2.func77, 77, 77) |
| 1076 |
|
| 1077 |
def test_one_liner_dedent_non_name(self): |
| 1078 |
self.assertSourceEqual(mod2.cls82.func83, 83, 83) |
| 1079 |
|
| 1080 |
def test_with_comment_instead_of_docstring(self): |
| 1081 |
self.assertSourceEqual(mod2.func88, 88, 90) |
| 1082 |
|
| 1083 |
def test_method_in_dynamic_class(self): |
| 1084 |
self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97) |
| 1085 |
|
| 1086 |
# This should not skip for CPython, but might on a repackaged python where |
| 1087 |
# unicodedata is not an external module, or on pypy. |
| 1088 |
@unittest.skipIf(not hasattr(unicodedata, '__file__') or |
| 1089 |
unicodedata.__file__.endswith('.py'), |
| 1090 |
"unicodedata is not an external binary module") |
| 1091 |
def test_findsource_binary(self): |
| 1092 |
self.assertRaises(OSError, inspect.getsource, unicodedata) |
| 1093 |
self.assertRaises(OSError, inspect.findsource, unicodedata) |
| 1094 |
|
| 1095 |
def test_findsource_code_in_linecache(self): |
| 1096 |
lines = ["x=1"] |
| 1097 |
co = compile(lines[0], "_dynamically_created_file", "exec") |
| 1098 |
self.assertRaises(OSError, inspect.findsource, co) |
| 1099 |
self.assertRaises(OSError, inspect.getsource, co) |
| 1100 |
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) |
| 1101 |
try: |
| 1102 |
self.assertEqual(inspect.findsource(co), (lines,0)) |
| 1103 |
self.assertEqual(inspect.getsource(co), lines[0]) |
| 1104 |
finally: |
| 1105 |
del linecache.cache[co.co_filename] |
| 1106 |
|
| 1107 |
def test_findsource_without_filename(self): |
| 1108 |
for fname in ['', '<string>']: |
| 1109 |
co = compile('x=1', fname, "exec") |
| 1110 |
self.assertRaises(IOError, inspect.findsource, co) |
| 1111 |
self.assertRaises(IOError, inspect.getsource, co) |
| 1112 |
|
| 1113 |
def test_findsource_on_func_with_out_of_bounds_lineno(self): |
| 1114 |
mod_len = len(inspect.getsource(mod)) |
| 1115 |
src = '\n' * 2* mod_len + "def f(): pass" |
| 1116 |
co = compile(src, mod.__file__, "exec") |
| 1117 |
g, l = {}, {} |
| 1118 |
eval(co, g, l) |
| 1119 |
func = l['f'] |
| 1120 |
self.assertEqual(func.__code__.co_firstlineno, 1+2*mod_len) |
| 1121 |
with self.assertRaisesRegex(OSError, "lineno is out of bounds"): |
| 1122 |
inspect.findsource(func) |
| 1123 |
|
| 1124 |
def test_findsource_on_class_with_out_of_bounds_lineno(self): |
| 1125 |
mod_len = len(inspect.getsource(mod)) |
| 1126 |
src = '\n' * 2* mod_len + "class A: pass" |
| 1127 |
co = compile(src, mod.__file__, "exec") |
| 1128 |
g, l = {'__name__': mod.__name__}, {} |
| 1129 |
eval(co, g, l) |
| 1130 |
cls = l['A'] |
| 1131 |
self.assertEqual(cls.__firstlineno__, 1+2*mod_len) |
| 1132 |
with self.assertRaisesRegex(OSError, "lineno is out of bounds"): |
| 1133 |
inspect.findsource(cls) |
| 1134 |
|
| 1135 |
def test_getsource_on_method(self): |
| 1136 |
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119) |
| 1137 |
|
| 1138 |
def test_getsource_on_class_code_object(self): |
| 1139 |
self.assertSourceEqual(mod2.ClassWithCodeObject.code, 315, 317) |
| 1140 |
|
| 1141 |
def test_nested_func(self): |
| 1142 |
self.assertSourceEqual(mod2.cls135.func136, 136, 139) |
| 1143 |
|
| 1144 |
def test_class_definition_in_multiline_string_definition(self): |
| 1145 |
self.assertSourceEqual(mod2.cls149, 149, 152) |
| 1146 |
|
| 1147 |
def test_class_definition_in_multiline_comment(self): |
| 1148 |
self.assertSourceEqual(mod2.cls160, 160, 163) |
| 1149 |
|
| 1150 |
def test_nested_class_definition_indented_string(self): |
| 1151 |
self.assertSourceEqual(mod2.cls173.cls175, 175, 176) |
| 1152 |
|
| 1153 |
def test_nested_class_definition(self): |
| 1154 |
self.assertSourceEqual(mod2.cls183, 183, 188) |
| 1155 |
self.assertSourceEqual(mod2.cls183.cls185, 185, 188) |
| 1156 |
|
| 1157 |
def test_class_decorator(self): |
| 1158 |
self.assertSourceEqual(mod2.cls196, 194, 201) |
| 1159 |
self.assertSourceEqual(mod2.cls196.cls200, 198, 201) |
| 1160 |
|
| 1161 |
@support.requires_docstrings |
| 1162 |
def test_class_inside_conditional(self): |
| 1163 |
# We skip this test when docstrings are not present, |
| 1164 |
# because docstrings are one of the main factors of |
| 1165 |
# finding the correct class in the source code. |
| 1166 |
self.assertSourceEqual(mod2.cls238.cls239, 239, 240) |
| 1167 |
|
| 1168 |
def test_multiple_children_classes(self): |
| 1169 |
self.assertSourceEqual(mod2.cls203, 203, 209) |
| 1170 |
self.assertSourceEqual(mod2.cls203.cls204, 204, 206) |
| 1171 |
self.assertSourceEqual(mod2.cls203.cls204.cls205, 205, 206) |
| 1172 |
self.assertSourceEqual(mod2.cls203.cls207, 207, 209) |
| 1173 |
self.assertSourceEqual(mod2.cls203.cls207.cls205, 208, 209) |
| 1174 |
|
| 1175 |
def test_nested_class_definition_inside_function(self): |
| 1176 |
self.assertSourceEqual(mod2.func212(), 213, 214) |
| 1177 |
self.assertSourceEqual(mod2.cls213, 218, 222) |
| 1178 |
self.assertSourceEqual(mod2.cls213().func219(), 220, 221) |
| 1179 |
|
| 1180 |
def test_class_with_method_from_other_module(self): |
| 1181 |
with tempfile.TemporaryDirectory() as tempdir: |
| 1182 |
with open(os.path.join(tempdir, 'inspect_actual%spy' % os.extsep), |
| 1183 |
'w', encoding='utf-8') as f: |
| 1184 |
f.write(textwrap.dedent(""" |
| 1185 |
import inspect_other |
| 1186 |
class A: |
| 1187 |
def f(self): |
| 1188 |
pass |
| 1189 |
class A: |
| 1190 |
def f(self): |
| 1191 |
pass # correct one |
| 1192 |
A.f = inspect_other.A.f |
| 1193 |
""")) |
| 1194 |
|
| 1195 |
with open(os.path.join(tempdir, 'inspect_other%spy' % os.extsep), |
| 1196 |
'w', encoding='utf-8') as f: |
| 1197 |
f.write(textwrap.dedent(""" |
| 1198 |
class A: |
| 1199 |
def f(self): |
| 1200 |
pass |
| 1201 |
""")) |
| 1202 |
|
| 1203 |
with DirsOnSysPath(tempdir): |
| 1204 |
import inspect_actual |
| 1205 |
self.assertIn("correct", inspect.getsource(inspect_actual.A)) |
| 1206 |
# Remove the module from sys.modules to force it to be reloaded. |
| 1207 |
# This is necessary when the test is run multiple times. |
| 1208 |
sys.modules.pop("inspect_actual") |
| 1209 |
|
| 1210 |
def test_nested_class_definition_inside_async_function(self): |
| 1211 |
run = run_no_yield_async_fn |
| 1212 |
|
| 1213 |
self.assertSourceEqual(run(mod2.func225), 226, 227) |
| 1214 |
self.assertSourceEqual(mod2.cls226, 231, 235) |
| 1215 |
self.assertSourceEqual(mod2.cls226.func232, 232, 235) |
| 1216 |
self.assertSourceEqual(run(mod2.cls226().func232), 233, 234) |
| 1217 |
|
| 1218 |
def test_class_definition_same_name_diff_methods(self): |
| 1219 |
self.assertSourceEqual(mod2.cls296, 296, 298) |
| 1220 |
self.assertSourceEqual(mod2.cls310, 310, 312) |
| 1221 |
|
| 1222 |
def test_generator_expression(self): |
| 1223 |
self.assertSourceEqual(next(mod2.ge377), 377, 380) |
| 1224 |
self.assertSourceEqual(next(mod2.func383()), 385, 388) |
| 1225 |
|
| 1226 |
def test_comment_or_empty_line_after_decorator(self): |
| 1227 |
self.assertSourceEqual(mod2.func394, 392, 395) |
| 1228 |
self.assertSourceEqual(mod2.func400, 398, 401) |
| 1229 |
|
| 1230 |
|
| 1231 |
class TestNoEOL(GetSourceBase): |
| 1232 |
def setUp(self): |
| 1233 |
self.tempdir = TESTFN + '_dir' |
| 1234 |
os.mkdir(self.tempdir) |
| 1235 |
with open(os.path.join(self.tempdir, 'inspect_fodder3%spy' % os.extsep), |
| 1236 |
'w', encoding='utf-8') as f: |
| 1237 |
f.write("class X:\n pass # No EOL") |
| 1238 |
with DirsOnSysPath(self.tempdir): |
| 1239 |
import inspect_fodder3 as mod3 |
| 1240 |
self.fodderModule = mod3 |
| 1241 |
super().setUp() |
| 1242 |
|
| 1243 |
def tearDown(self): |
| 1244 |
shutil.rmtree(self.tempdir) |
| 1245 |
|
| 1246 |
def test_class(self): |
| 1247 |
self.assertSourceEqual(self.fodderModule.X, 1, 2) |
| 1248 |
|
| 1249 |
|
| 1250 |
class TestComplexDecorator(GetSourceBase): |
| 1251 |
fodderModule = mod2 |
| 1252 |
|
| 1253 |
def test_parens_in_decorator(self): |
| 1254 |
self.assertSourceEqual(self.fodderModule.complex_decorated, 273, 275) |
| 1255 |
|
| 1256 |
class _BrokenDataDescriptor(object): |
| 1257 |
""" |
| 1258 |
A broken data descriptor. See bug #1785. |
| 1259 |
""" |
| 1260 |
def __get__(*args): |
| 1261 |
raise AttributeError("broken data descriptor") |
| 1262 |
|
| 1263 |
def __set__(*args): |
| 1264 |
raise RuntimeError |
| 1265 |
|
| 1266 |
def __getattr__(*args): |
| 1267 |
raise AttributeError("broken data descriptor") |
| 1268 |
|
| 1269 |
|
| 1270 |
class _BrokenMethodDescriptor(object): |
| 1271 |
""" |
| 1272 |
A broken method descriptor. See bug #1785. |
| 1273 |
""" |
| 1274 |
def __get__(*args): |
| 1275 |
raise AttributeError("broken method descriptor") |
| 1276 |
|
| 1277 |
def __getattr__(*args): |
| 1278 |
raise AttributeError("broken method descriptor") |
| 1279 |
|
| 1280 |
|
| 1281 |
# Helper for testing classify_class_attrs. |
| 1282 |
def attrs_wo_objs(cls): |
| 1283 |
return [t[:3] for t in inspect.classify_class_attrs(cls)] |
| 1284 |
|
| 1285 |
|
| 1286 |
class TestClassesAndFunctions(unittest.TestCase): |
| 1287 |
def test_newstyle_mro(self): |
| 1288 |
# The same w/ new-class MRO. |
| 1289 |
class A(object): pass |
| 1290 |
class B(A): pass |
| 1291 |
class C(A): pass |
| 1292 |
class D(B, C): pass |
| 1293 |
|
| 1294 |
expected = (D, B, C, A, object) |
| 1295 |
got = inspect.getmro(D) |
| 1296 |
self.assertEqual(expected, got) |
| 1297 |
|
| 1298 |
def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None, |
| 1299 |
varkw_e=None, defaults_e=None, |
| 1300 |
posonlyargs_e=[], kwonlyargs_e=[], |
| 1301 |
kwonlydefaults_e=None, |
| 1302 |
ann_e={}): |
| 1303 |
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ |
| 1304 |
inspect.getfullargspec(routine) |
| 1305 |
self.assertEqual(args, args_e) |
| 1306 |
self.assertEqual(varargs, varargs_e) |
| 1307 |
self.assertEqual(varkw, varkw_e) |
| 1308 |
self.assertEqual(defaults, defaults_e) |
| 1309 |
self.assertEqual(kwonlyargs, kwonlyargs_e) |
| 1310 |
self.assertEqual(kwonlydefaults, kwonlydefaults_e) |
| 1311 |
self.assertEqual(ann, ann_e) |
| 1312 |
|
| 1313 |
def test_getfullargspec(self): |
| 1314 |
self.assertFullArgSpecEquals(mod2.keyworded, [], varargs_e='arg1', |
| 1315 |
kwonlyargs_e=['arg2'], |
| 1316 |
kwonlydefaults_e={'arg2':1}) |
| 1317 |
|
| 1318 |
self.assertFullArgSpecEquals(mod2.annotated, ['arg1'], |
| 1319 |
ann_e={'arg1' : list}) |
| 1320 |
self.assertFullArgSpecEquals(mod2.keyword_only_arg, [], |
| 1321 |
kwonlyargs_e=['arg']) |
| 1322 |
|
| 1323 |
self.assertFullArgSpecEquals(mod2.all_markers, ['a', 'b', 'c', 'd'], |
| 1324 |
kwonlyargs_e=['e', 'f']) |
| 1325 |
|
| 1326 |
self.assertFullArgSpecEquals(mod2.all_markers_with_args_and_kwargs, |
| 1327 |
['a', 'b', 'c', 'd'], |
| 1328 |
varargs_e='args', |
| 1329 |
varkw_e='kwargs', |
| 1330 |
kwonlyargs_e=['e', 'f']) |
| 1331 |
|
| 1332 |
self.assertFullArgSpecEquals(mod2.all_markers_with_defaults, ['a', 'b', 'c', 'd'], |
| 1333 |
defaults_e=(1,2,3), |
| 1334 |
kwonlyargs_e=['e', 'f'], |
| 1335 |
kwonlydefaults_e={'e': 4, 'f': 5}) |
| 1336 |
|
| 1337 |
def test_argspec_api_ignores_wrapped(self): |
| 1338 |
# Issue 20684: low level introspection API must ignore __wrapped__ |
| 1339 |
@functools.wraps(mod.spam) |
| 1340 |
def ham(x, y): |
| 1341 |
pass |
| 1342 |
# Basic check |
| 1343 |
self.assertFullArgSpecEquals(ham, ['x', 'y']) |
| 1344 |
self.assertFullArgSpecEquals(functools.partial(ham), |
| 1345 |
['x', 'y']) |
| 1346 |
|
| 1347 |
def test_getfullargspec_signature_attr(self): |
| 1348 |
def test(): |
| 1349 |
pass |
| 1350 |
spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) |
| 1351 |
test.__signature__ = inspect.Signature(parameters=(spam_param,)) |
| 1352 |
|
| 1353 |
self.assertFullArgSpecEquals(test, ['spam']) |
| 1354 |
|
| 1355 |
def test_getfullargspec_signature_annos(self): |
| 1356 |
def test(a:'spam') -> 'ham': pass |
| 1357 |
spec = inspect.getfullargspec(test) |
| 1358 |
self.assertEqual(test.__annotations__, spec.annotations) |
| 1359 |
|
| 1360 |
def test(): pass |
| 1361 |
spec = inspect.getfullargspec(test) |
| 1362 |
self.assertEqual(test.__annotations__, spec.annotations) |
| 1363 |
|
| 1364 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1365 |
"Signature information for builtins requires docstrings") |
| 1366 |
def test_getfullargspec_builtin_methods(self): |
| 1367 |
self.assertFullArgSpecEquals(_pickle.Pickler.dump, ['self', 'obj']) |
| 1368 |
|
| 1369 |
self.assertFullArgSpecEquals(_pickle.Pickler(io.BytesIO()).dump, ['self', 'obj']) |
| 1370 |
|
| 1371 |
self.assertFullArgSpecEquals( |
| 1372 |
os.stat, |
| 1373 |
args_e=['path'], |
| 1374 |
kwonlyargs_e=['dir_fd', 'follow_symlinks'], |
| 1375 |
kwonlydefaults_e={'dir_fd': None, 'follow_symlinks': True}) |
| 1376 |
|
| 1377 |
@cpython_only |
| 1378 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1379 |
"Signature information for builtins requires docstrings") |
| 1380 |
def test_getfullargspec_builtin_func(self): |
| 1381 |
_testcapi = import_helper.import_module("_testcapi") |
| 1382 |
builtin = _testcapi.docstring_with_signature_with_defaults |
| 1383 |
spec = inspect.getfullargspec(builtin) |
| 1384 |
self.assertEqual(spec.defaults[0], 'avocado') |
| 1385 |
|
| 1386 |
@cpython_only |
| 1387 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1388 |
"Signature information for builtins requires docstrings") |
| 1389 |
def test_getfullargspec_builtin_func_no_signature(self): |
| 1390 |
_testcapi = import_helper.import_module("_testcapi") |
| 1391 |
builtin = _testcapi.docstring_no_signature |
| 1392 |
with self.assertRaises(TypeError): |
| 1393 |
inspect.getfullargspec(builtin) |
| 1394 |
|
| 1395 |
cls = _testcapi.DocStringNoSignatureTest |
| 1396 |
obj = _testcapi.DocStringNoSignatureTest() |
| 1397 |
tests = [ |
| 1398 |
(_testcapi.docstring_no_signature_noargs, meth_noargs), |
| 1399 |
(_testcapi.docstring_no_signature_o, meth_o), |
| 1400 |
(cls.meth_noargs, meth_self_noargs), |
| 1401 |
(cls.meth_o, meth_self_o), |
| 1402 |
(obj.meth_noargs, meth_self_noargs), |
| 1403 |
(obj.meth_o, meth_self_o), |
| 1404 |
(cls.meth_noargs_class, meth_type_noargs), |
| 1405 |
(cls.meth_o_class, meth_type_o), |
| 1406 |
(cls.meth_noargs_static, meth_noargs), |
| 1407 |
(cls.meth_o_static, meth_o), |
| 1408 |
(cls.meth_noargs_coexist, meth_self_noargs), |
| 1409 |
(cls.meth_o_coexist, meth_self_o), |
| 1410 |
|
| 1411 |
(time.time, meth_noargs), |
| 1412 |
(str.lower, meth_self_noargs), |
| 1413 |
(''.lower, meth_self_noargs), |
| 1414 |
(set.add, meth_self_o), |
| 1415 |
(set().add, meth_self_o), |
| 1416 |
(set.__contains__, meth_self_o), |
| 1417 |
(set().__contains__, meth_self_o), |
| 1418 |
(datetime.datetime.__dict__['utcnow'], meth_type_noargs), |
| 1419 |
(datetime.datetime.utcnow, meth_type_noargs), |
| 1420 |
(dict.__dict__['__class_getitem__'], meth_type_o), |
| 1421 |
(dict.__class_getitem__, meth_type_o), |
| 1422 |
] |
| 1423 |
try: |
| 1424 |
import _stat # noqa: F401 |
| 1425 |
except ImportError: |
| 1426 |
# if the _stat extension is not available, stat.S_IMODE() is |
| 1427 |
# implemented in Python, not in C |
| 1428 |
pass |
| 1429 |
else: |
| 1430 |
tests.append((stat.S_IMODE, meth_o)) |
| 1431 |
for builtin, template in tests: |
| 1432 |
with self.subTest(builtin): |
| 1433 |
self.assertEqual(inspect.getfullargspec(builtin), |
| 1434 |
inspect.getfullargspec(template)) |
| 1435 |
|
| 1436 |
def test_getfullargspec_definition_order_preserved_on_kwonly(self): |
| 1437 |
for fn in signatures_with_lexicographic_keyword_only_parameters(): |
| 1438 |
signature = inspect.getfullargspec(fn) |
| 1439 |
l = list(signature.kwonlyargs) |
| 1440 |
sorted_l = sorted(l) |
| 1441 |
self.assertTrue(l) |
| 1442 |
self.assertEqual(l, sorted_l) |
| 1443 |
signature = inspect.getfullargspec(unsorted_keyword_only_parameters_fn) |
| 1444 |
l = list(signature.kwonlyargs) |
| 1445 |
self.assertEqual(l, unsorted_keyword_only_parameters) |
| 1446 |
|
| 1447 |
def test_classify_newstyle(self): |
| 1448 |
class A(object): |
| 1449 |
|
| 1450 |
def s(): pass |
| 1451 |
s = staticmethod(s) |
| 1452 |
|
| 1453 |
def c(cls): pass |
| 1454 |
c = classmethod(c) |
| 1455 |
|
| 1456 |
def getp(self): pass |
| 1457 |
p = property(getp) |
| 1458 |
|
| 1459 |
def m(self): pass |
| 1460 |
|
| 1461 |
def m1(self): pass |
| 1462 |
|
| 1463 |
datablob = '1' |
| 1464 |
|
| 1465 |
dd = _BrokenDataDescriptor() |
| 1466 |
md = _BrokenMethodDescriptor() |
| 1467 |
|
| 1468 |
attrs = attrs_wo_objs(A) |
| 1469 |
|
| 1470 |
self.assertIn(('__new__', 'static method', object), attrs, |
| 1471 |
'missing __new__') |
| 1472 |
self.assertIn(('__init__', 'method', object), attrs, 'missing __init__') |
| 1473 |
|
| 1474 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1475 |
self.assertIn(('c', 'class method', A), attrs, 'missing class method') |
| 1476 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1477 |
self.assertIn(('m', 'method', A), attrs, |
| 1478 |
'missing plain method: %r' % attrs) |
| 1479 |
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 1480 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1481 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1482 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1483 |
|
| 1484 |
class B(A): |
| 1485 |
|
| 1486 |
def m(self): pass |
| 1487 |
|
| 1488 |
attrs = attrs_wo_objs(B) |
| 1489 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1490 |
self.assertIn(('c', 'class method', A), attrs, 'missing class method') |
| 1491 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1492 |
self.assertIn(('m', 'method', B), attrs, 'missing plain method') |
| 1493 |
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 1494 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1495 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1496 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1497 |
|
| 1498 |
|
| 1499 |
class C(A): |
| 1500 |
|
| 1501 |
def m(self): pass |
| 1502 |
def c(self): pass |
| 1503 |
|
| 1504 |
attrs = attrs_wo_objs(C) |
| 1505 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1506 |
self.assertIn(('c', 'method', C), attrs, 'missing plain method') |
| 1507 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1508 |
self.assertIn(('m', 'method', C), attrs, 'missing plain method') |
| 1509 |
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 1510 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1511 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1512 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1513 |
|
| 1514 |
class D(B, C): |
| 1515 |
|
| 1516 |
def m1(self): pass |
| 1517 |
|
| 1518 |
attrs = attrs_wo_objs(D) |
| 1519 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1520 |
self.assertIn(('c', 'method', C), attrs, 'missing plain method') |
| 1521 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1522 |
self.assertIn(('m', 'method', B), attrs, 'missing plain method') |
| 1523 |
self.assertIn(('m1', 'method', D), attrs, 'missing plain method') |
| 1524 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1525 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1526 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1527 |
|
| 1528 |
def test_classify_builtin_types(self): |
| 1529 |
# Simple sanity check that all built-in types can have their |
| 1530 |
# attributes classified. |
| 1531 |
for name in dir(__builtins__): |
| 1532 |
builtin = getattr(__builtins__, name) |
| 1533 |
if isinstance(builtin, type): |
| 1534 |
inspect.classify_class_attrs(builtin) |
| 1535 |
|
| 1536 |
attrs = attrs_wo_objs(bool) |
| 1537 |
self.assertIn(('__new__', 'static method', bool), attrs, |
| 1538 |
'missing __new__') |
| 1539 |
self.assertIn(('from_bytes', 'class method', int), attrs, |
| 1540 |
'missing class method') |
| 1541 |
self.assertIn(('to_bytes', 'method', int), attrs, |
| 1542 |
'missing plain method') |
| 1543 |
self.assertIn(('__add__', 'method', int), attrs, |
| 1544 |
'missing plain method') |
| 1545 |
self.assertIn(('__and__', 'method', bool), attrs, |
| 1546 |
'missing plain method') |
| 1547 |
|
| 1548 |
def test_classify_DynamicClassAttribute(self): |
| 1549 |
class Meta(type): |
| 1550 |
def __getattr__(self, name): |
| 1551 |
if name == 'ham': |
| 1552 |
return 'spam' |
| 1553 |
return super().__getattr__(name) |
| 1554 |
class VA(metaclass=Meta): |
| 1555 |
@types.DynamicClassAttribute |
| 1556 |
def ham(self): |
| 1557 |
return 'eggs' |
| 1558 |
should_find_dca = inspect.Attribute('ham', 'data', VA, VA.__dict__['ham']) |
| 1559 |
self.assertIn(should_find_dca, inspect.classify_class_attrs(VA)) |
| 1560 |
should_find_ga = inspect.Attribute('ham', 'data', Meta, 'spam') |
| 1561 |
self.assertIn(should_find_ga, inspect.classify_class_attrs(VA)) |
| 1562 |
|
| 1563 |
def test_classify_overrides_bool(self): |
| 1564 |
class NoBool(object): |
| 1565 |
def __eq__(self, other): |
| 1566 |
return NoBool() |
| 1567 |
|
| 1568 |
def __bool__(self): |
| 1569 |
raise NotImplementedError( |
| 1570 |
"This object does not specify a boolean value") |
| 1571 |
|
| 1572 |
class HasNB(object): |
| 1573 |
dd = NoBool() |
| 1574 |
|
| 1575 |
should_find_attr = inspect.Attribute('dd', 'data', HasNB, HasNB.dd) |
| 1576 |
self.assertIn(should_find_attr, inspect.classify_class_attrs(HasNB)) |
| 1577 |
|
| 1578 |
def test_classify_metaclass_class_attribute(self): |
| 1579 |
class Meta(type): |
| 1580 |
fish = 'slap' |
| 1581 |
def __dir__(self): |
| 1582 |
return ['__class__', '__module__', '__name__', 'fish'] |
| 1583 |
class Class(metaclass=Meta): |
| 1584 |
pass |
| 1585 |
should_find = inspect.Attribute('fish', 'data', Meta, 'slap') |
| 1586 |
self.assertIn(should_find, inspect.classify_class_attrs(Class)) |
| 1587 |
|
| 1588 |
def test_classify_VirtualAttribute(self): |
| 1589 |
class Meta(type): |
| 1590 |
def __dir__(cls): |
| 1591 |
return ['__class__', '__module__', '__name__', 'BOOM'] |
| 1592 |
def __getattr__(self, name): |
| 1593 |
if name =='BOOM': |
| 1594 |
return 42 |
| 1595 |
return super().__getattr(name) |
| 1596 |
class Class(metaclass=Meta): |
| 1597 |
pass |
| 1598 |
should_find = inspect.Attribute('BOOM', 'data', Meta, 42) |
| 1599 |
self.assertIn(should_find, inspect.classify_class_attrs(Class)) |
| 1600 |
|
| 1601 |
def test_classify_VirtualAttribute_multi_classes(self): |
| 1602 |
class Meta1(type): |
| 1603 |
def __dir__(cls): |
| 1604 |
return ['__class__', '__module__', '__name__', 'one'] |
| 1605 |
def __getattr__(self, name): |
| 1606 |
if name =='one': |
| 1607 |
return 1 |
| 1608 |
return super().__getattr__(name) |
| 1609 |
class Meta2(type): |
| 1610 |
def __dir__(cls): |
| 1611 |
return ['__class__', '__module__', '__name__', 'two'] |
| 1612 |
def __getattr__(self, name): |
| 1613 |
if name =='two': |
| 1614 |
return 2 |
| 1615 |
return super().__getattr__(name) |
| 1616 |
class Meta3(Meta1, Meta2): |
| 1617 |
def __dir__(cls): |
| 1618 |
return list(sorted(set(['__class__', '__module__', '__name__', 'three'] + |
| 1619 |
Meta1.__dir__(cls) + Meta2.__dir__(cls)))) |
| 1620 |
def __getattr__(self, name): |
| 1621 |
if name =='three': |
| 1622 |
return 3 |
| 1623 |
return super().__getattr__(name) |
| 1624 |
class Class1(metaclass=Meta1): |
| 1625 |
pass |
| 1626 |
class Class2(Class1, metaclass=Meta3): |
| 1627 |
pass |
| 1628 |
|
| 1629 |
should_find1 = inspect.Attribute('one', 'data', Meta1, 1) |
| 1630 |
should_find2 = inspect.Attribute('two', 'data', Meta2, 2) |
| 1631 |
should_find3 = inspect.Attribute('three', 'data', Meta3, 3) |
| 1632 |
cca = inspect.classify_class_attrs(Class2) |
| 1633 |
for sf in (should_find1, should_find2, should_find3): |
| 1634 |
self.assertIn(sf, cca) |
| 1635 |
|
| 1636 |
def test_classify_class_attrs_with_buggy_dir(self): |
| 1637 |
class M(type): |
| 1638 |
def __dir__(cls): |
| 1639 |
return ['__class__', '__name__', 'missing'] |
| 1640 |
class C(metaclass=M): |
| 1641 |
pass |
| 1642 |
attrs = [a[0] for a in inspect.classify_class_attrs(C)] |
| 1643 |
self.assertNotIn('missing', attrs) |
| 1644 |
|
| 1645 |
def test_getmembers_descriptors(self): |
| 1646 |
class A(object): |
| 1647 |
dd = _BrokenDataDescriptor() |
| 1648 |
md = _BrokenMethodDescriptor() |
| 1649 |
|
| 1650 |
def pred_wrapper(pred): |
| 1651 |
# A quick'n'dirty way to discard standard attributes of new-style |
| 1652 |
# classes. |
| 1653 |
class Empty(object): |
| 1654 |
pass |
| 1655 |
def wrapped(x): |
| 1656 |
if '__name__' in dir(x) and hasattr(Empty, x.__name__): |
| 1657 |
return False |
| 1658 |
return pred(x) |
| 1659 |
return wrapped |
| 1660 |
|
| 1661 |
ismethoddescriptor = pred_wrapper(inspect.ismethoddescriptor) |
| 1662 |
isdatadescriptor = pred_wrapper(inspect.isdatadescriptor) |
| 1663 |
|
| 1664 |
self.assertEqual(inspect.getmembers(A, ismethoddescriptor), |
| 1665 |
[('md', A.__dict__['md'])]) |
| 1666 |
self.assertEqual(inspect.getmembers(A, isdatadescriptor), |
| 1667 |
[('dd', A.__dict__['dd'])]) |
| 1668 |
|
| 1669 |
class B(A): |
| 1670 |
pass |
| 1671 |
|
| 1672 |
self.assertEqual(inspect.getmembers(B, ismethoddescriptor), |
| 1673 |
[('md', A.__dict__['md'])]) |
| 1674 |
self.assertEqual(inspect.getmembers(B, isdatadescriptor), |
| 1675 |
[('dd', A.__dict__['dd'])]) |
| 1676 |
|
| 1677 |
def test_getmembers_method(self): |
| 1678 |
class B: |
| 1679 |
def f(self): |
| 1680 |
pass |
| 1681 |
|
| 1682 |
self.assertIn(('f', B.f), inspect.getmembers(B)) |
| 1683 |
self.assertNotIn(('f', B.f), inspect.getmembers(B, inspect.ismethod)) |
| 1684 |
b = B() |
| 1685 |
self.assertIn(('f', b.f), inspect.getmembers(b)) |
| 1686 |
self.assertIn(('f', b.f), inspect.getmembers(b, inspect.ismethod)) |
| 1687 |
|
| 1688 |
def test_getmembers_custom_dir(self): |
| 1689 |
class CorrectDir: |
| 1690 |
def __init__(self, attr): |
| 1691 |
self.attr = attr |
| 1692 |
def method(self): |
| 1693 |
return self.attr + 1 |
| 1694 |
def __dir__(self): |
| 1695 |
return ['attr', 'method'] |
| 1696 |
|
| 1697 |
cd = CorrectDir(5) |
| 1698 |
self.assertEqual(inspect.getmembers(cd), [ |
| 1699 |
('attr', 5), |
| 1700 |
('method', cd.method), |
| 1701 |
]) |
| 1702 |
self.assertEqual(inspect.getmembers(cd, inspect.ismethod), [ |
| 1703 |
('method', cd.method), |
| 1704 |
]) |
| 1705 |
|
| 1706 |
def test_getmembers_custom_broken_dir(self): |
| 1707 |
# inspect.getmembers calls `dir()` on the passed object inside. |
| 1708 |
# if `__dir__` mentions some non-existent attribute, |
| 1709 |
# we still need to return others correctly. |
| 1710 |
class BrokenDir: |
| 1711 |
existing = 1 |
| 1712 |
def method(self): |
| 1713 |
return self.existing + 1 |
| 1714 |
def __dir__(self): |
| 1715 |
return ['method', 'missing', 'existing'] |
| 1716 |
|
| 1717 |
bd = BrokenDir() |
| 1718 |
self.assertEqual(inspect.getmembers(bd), [ |
| 1719 |
('existing', 1), |
| 1720 |
('method', bd.method), |
| 1721 |
]) |
| 1722 |
self.assertEqual(inspect.getmembers(bd, inspect.ismethod), [ |
| 1723 |
('method', bd.method), |
| 1724 |
]) |
| 1725 |
|
| 1726 |
def test_getmembers_custom_duplicated_dir(self): |
| 1727 |
# Duplicates in `__dir__` must not fail and return just one result. |
| 1728 |
class DuplicatedDir: |
| 1729 |
attr = 1 |
| 1730 |
def __dir__(self): |
| 1731 |
return ['attr', 'attr'] |
| 1732 |
|
| 1733 |
dd = DuplicatedDir() |
| 1734 |
self.assertEqual(inspect.getmembers(dd), [ |
| 1735 |
('attr', 1), |
| 1736 |
]) |
| 1737 |
|
| 1738 |
def test_getmembers_VirtualAttribute(self): |
| 1739 |
class M(type): |
| 1740 |
def __getattr__(cls, name): |
| 1741 |
if name == 'eggs': |
| 1742 |
return 'scrambled' |
| 1743 |
return super().__getattr__(name) |
| 1744 |
class A(metaclass=M): |
| 1745 |
@types.DynamicClassAttribute |
| 1746 |
def eggs(self): |
| 1747 |
return 'spam' |
| 1748 |
class B: |
| 1749 |
def __getattr__(self, attribute): |
| 1750 |
return None |
| 1751 |
self.assertIn(('eggs', 'scrambled'), inspect.getmembers(A)) |
| 1752 |
self.assertIn(('eggs', 'spam'), inspect.getmembers(A())) |
| 1753 |
b = B() |
| 1754 |
self.assertIn(('__getattr__', b.__getattr__), inspect.getmembers(b)) |
| 1755 |
|
| 1756 |
def test_getmembers_static(self): |
| 1757 |
class A: |
| 1758 |
@property |
| 1759 |
def name(self): |
| 1760 |
raise NotImplementedError |
| 1761 |
@types.DynamicClassAttribute |
| 1762 |
def eggs(self): |
| 1763 |
raise NotImplementedError |
| 1764 |
|
| 1765 |
a = A() |
| 1766 |
instance_members = inspect.getmembers_static(a) |
| 1767 |
class_members = inspect.getmembers_static(A) |
| 1768 |
self.assertIn(('name', inspect.getattr_static(a, 'name')), instance_members) |
| 1769 |
self.assertIn(('eggs', inspect.getattr_static(a, 'eggs')), instance_members) |
| 1770 |
self.assertIn(('name', inspect.getattr_static(A, 'name')), class_members) |
| 1771 |
self.assertIn(('eggs', inspect.getattr_static(A, 'eggs')), class_members) |
| 1772 |
|
| 1773 |
def test_getmembers_with_buggy_dir(self): |
| 1774 |
class M(type): |
| 1775 |
def __dir__(cls): |
| 1776 |
return ['__class__', '__name__', 'missing'] |
| 1777 |
class C(metaclass=M): |
| 1778 |
pass |
| 1779 |
attrs = [a[0] for a in inspect.getmembers(C)] |
| 1780 |
self.assertNotIn('missing', attrs) |
| 1781 |
|
| 1782 |
|
| 1783 |
class TestFormatAnnotation(unittest.TestCase): |
| 1784 |
def test_typing_replacement(self): |
| 1785 |
from test.typinganndata.ann_module9 import A, ann, ann1 |
| 1786 |
self.assertEqual(inspect.formatannotation(ann), 'List[str] | int') |
| 1787 |
self.assertEqual(inspect.formatannotation(ann1), 'List[testModule.typing.A] | int') |
| 1788 |
|
| 1789 |
self.assertEqual(inspect.formatannotation(A, 'testModule.typing'), 'A') |
| 1790 |
self.assertEqual(inspect.formatannotation(A, 'other'), 'testModule.typing.A') |
| 1791 |
self.assertEqual( |
| 1792 |
inspect.formatannotation(ann1, 'testModule.typing'), |
| 1793 |
'List[testModule.typing.A] | int', |
| 1794 |
) |
| 1795 |
|
| 1796 |
def test_forwardref(self): |
| 1797 |
fwdref = ForwardRef('fwdref') |
| 1798 |
self.assertEqual(inspect.formatannotation(fwdref), 'fwdref') |
| 1799 |
|
| 1800 |
def test_formatannotationrelativeto(self): |
| 1801 |
from test.typinganndata.ann_module9 import A, ann1 |
| 1802 |
|
| 1803 |
# Builtin types: |
| 1804 |
self.assertEqual( |
| 1805 |
inspect.formatannotationrelativeto(object)(type), |
| 1806 |
'type', |
| 1807 |
) |
| 1808 |
|
| 1809 |
# Custom types: |
| 1810 |
self.assertEqual( |
| 1811 |
inspect.formatannotationrelativeto(None)(A), |
| 1812 |
'testModule.typing.A', |
| 1813 |
) |
| 1814 |
|
| 1815 |
class B: ... |
| 1816 |
B.__module__ = 'testModule.typing' |
| 1817 |
|
| 1818 |
self.assertEqual( |
| 1819 |
inspect.formatannotationrelativeto(B)(A), |
| 1820 |
'A', |
| 1821 |
) |
| 1822 |
|
| 1823 |
self.assertEqual( |
| 1824 |
inspect.formatannotationrelativeto(object)(A), |
| 1825 |
'testModule.typing.A', |
| 1826 |
) |
| 1827 |
|
| 1828 |
# Not an instance of "type": |
| 1829 |
self.assertEqual( |
| 1830 |
inspect.formatannotationrelativeto(A)(ann1), |
| 1831 |
'List[testModule.typing.A] | int', |
| 1832 |
) |
| 1833 |
|
| 1834 |
|
| 1835 |
class TestIsMethodDescriptor(unittest.TestCase): |
| 1836 |
|
| 1837 |
def test_custom_descriptors(self): |
| 1838 |
class MethodDescriptor: |
| 1839 |
def __get__(self, *_): pass |
| 1840 |
class MethodDescriptorSub(MethodDescriptor): |
| 1841 |
pass |
| 1842 |
class DataDescriptorWithNoGet: |
| 1843 |
def __set__(self, *_): pass |
| 1844 |
class DataDescriptorWithGetSet: |
| 1845 |
def __get__(self, *_): pass |
| 1846 |
def __set__(self, *_): pass |
| 1847 |
class DataDescriptorWithGetDelete: |
| 1848 |
def __get__(self, *_): pass |
| 1849 |
def __delete__(self, *_): pass |
| 1850 |
class DataDescriptorSub(DataDescriptorWithNoGet, |
| 1851 |
DataDescriptorWithGetDelete): |
| 1852 |
pass |
| 1853 |
|
| 1854 |
# Custom method descriptors: |
| 1855 |
self.assertTrue( |
| 1856 |
inspect.ismethoddescriptor(MethodDescriptor()), |
| 1857 |
'__get__ and no __set__/__delete__ => method descriptor') |
| 1858 |
self.assertTrue( |
| 1859 |
inspect.ismethoddescriptor(MethodDescriptorSub()), |
| 1860 |
'__get__ (inherited) and no __set__/__delete__' |
| 1861 |
' => method descriptor') |
| 1862 |
|
| 1863 |
# Custom data descriptors: |
| 1864 |
self.assertFalse( |
| 1865 |
inspect.ismethoddescriptor(DataDescriptorWithNoGet()), |
| 1866 |
'__set__ (and no __get__) => not a method descriptor') |
| 1867 |
self.assertFalse( |
| 1868 |
inspect.ismethoddescriptor(DataDescriptorWithGetSet()), |
| 1869 |
'__get__ and __set__ => not a method descriptor') |
| 1870 |
self.assertFalse( |
| 1871 |
inspect.ismethoddescriptor(DataDescriptorWithGetDelete()), |
| 1872 |
'__get__ and __delete__ => not a method descriptor') |
| 1873 |
self.assertFalse( |
| 1874 |
inspect.ismethoddescriptor(DataDescriptorSub()), |
| 1875 |
'__get__, __set__ and __delete__ => not a method descriptor') |
| 1876 |
|
| 1877 |
# Classes of descriptors (are *not* descriptors themselves): |
| 1878 |
self.assertFalse(inspect.ismethoddescriptor(MethodDescriptor)) |
| 1879 |
self.assertFalse(inspect.ismethoddescriptor(MethodDescriptorSub)) |
| 1880 |
self.assertFalse(inspect.ismethoddescriptor(DataDescriptorSub)) |
| 1881 |
|
| 1882 |
def test_builtin_descriptors(self): |
| 1883 |
builtin_slot_wrapper = int.__add__ # This one is mentioned in docs. |
| 1884 |
class Owner: |
| 1885 |
def instance_method(self): pass |
| 1886 |
@classmethod |
| 1887 |
def class_method(cls): pass |
| 1888 |
@staticmethod |
| 1889 |
def static_method(): pass |
| 1890 |
@property |
| 1891 |
def a_property(self): pass |
| 1892 |
class Slotermeyer: |
| 1893 |
__slots__ = 'a_slot', |
| 1894 |
def function(): |
| 1895 |
pass |
| 1896 |
a_lambda = lambda: None |
| 1897 |
|
| 1898 |
# Example builtin method descriptors: |
| 1899 |
self.assertTrue( |
| 1900 |
inspect.ismethoddescriptor(builtin_slot_wrapper), |
| 1901 |
'a builtin slot wrapper is a method descriptor') |
| 1902 |
self.assertTrue( |
| 1903 |
inspect.ismethoddescriptor(Owner.__dict__['class_method']), |
| 1904 |
'a classmethod object is a method descriptor') |
| 1905 |
self.assertTrue( |
| 1906 |
inspect.ismethoddescriptor(Owner.__dict__['static_method']), |
| 1907 |
'a staticmethod object is a method descriptor') |
| 1908 |
|
| 1909 |
# Example builtin data descriptors: |
| 1910 |
self.assertFalse( |
| 1911 |
inspect.ismethoddescriptor(Owner.__dict__['a_property']), |
| 1912 |
'a property is not a method descriptor') |
| 1913 |
self.assertFalse( |
| 1914 |
inspect.ismethoddescriptor(Slotermeyer.__dict__['a_slot']), |
| 1915 |
'a slot is not a method descriptor') |
| 1916 |
|
| 1917 |
# `types.MethodType`/`types.FunctionType` instances (they *are* |
| 1918 |
# method descriptors, but `ismethoddescriptor()` explicitly |
| 1919 |
# excludes them): |
| 1920 |
self.assertFalse(inspect.ismethoddescriptor(Owner().instance_method)) |
| 1921 |
self.assertFalse(inspect.ismethoddescriptor(Owner().class_method)) |
| 1922 |
self.assertFalse(inspect.ismethoddescriptor(Owner().static_method)) |
| 1923 |
self.assertFalse(inspect.ismethoddescriptor(Owner.instance_method)) |
| 1924 |
self.assertFalse(inspect.ismethoddescriptor(Owner.class_method)) |
| 1925 |
self.assertFalse(inspect.ismethoddescriptor(Owner.static_method)) |
| 1926 |
self.assertFalse(inspect.ismethoddescriptor(function)) |
| 1927 |
self.assertFalse(inspect.ismethoddescriptor(a_lambda)) |
| 1928 |
self.assertTrue(inspect.ismethoddescriptor(functools.partial(function))) |
| 1929 |
|
| 1930 |
def test_descriptor_being_a_class(self): |
| 1931 |
class MethodDescriptorMeta(type): |
| 1932 |
def __get__(self, *_): pass |
| 1933 |
class ClassBeingMethodDescriptor(metaclass=MethodDescriptorMeta): |
| 1934 |
pass |
| 1935 |
# `ClassBeingMethodDescriptor` itself *is* a method descriptor, |
| 1936 |
# but it is *also* a class, and `ismethoddescriptor()` explicitly |
| 1937 |
# excludes classes. |
| 1938 |
self.assertFalse( |
| 1939 |
inspect.ismethoddescriptor(ClassBeingMethodDescriptor), |
| 1940 |
'classes (instances of type) are explicitly excluded') |
| 1941 |
|
| 1942 |
def test_non_descriptors(self): |
| 1943 |
class Test: |
| 1944 |
pass |
| 1945 |
self.assertFalse(inspect.ismethoddescriptor(Test())) |
| 1946 |
self.assertFalse(inspect.ismethoddescriptor(Test)) |
| 1947 |
self.assertFalse(inspect.ismethoddescriptor([42])) |
| 1948 |
self.assertFalse(inspect.ismethoddescriptor(42)) |
| 1949 |
|
| 1950 |
|
| 1951 |
class TestIsDataDescriptor(unittest.TestCase): |
| 1952 |
|
| 1953 |
def test_custom_descriptors(self): |
| 1954 |
class NonDataDescriptor: |
| 1955 |
def __get__(self, value, type=None): pass |
| 1956 |
class DataDescriptor0: |
| 1957 |
def __set__(self, name, value): pass |
| 1958 |
class DataDescriptor1: |
| 1959 |
def __delete__(self, name): pass |
| 1960 |
class DataDescriptor2: |
| 1961 |
__set__ = None |
| 1962 |
self.assertFalse(inspect.isdatadescriptor(NonDataDescriptor()), |
| 1963 |
'class with only __get__ not a data descriptor') |
| 1964 |
self.assertTrue(inspect.isdatadescriptor(DataDescriptor0()), |
| 1965 |
'class with __set__ is a data descriptor') |
| 1966 |
self.assertTrue(inspect.isdatadescriptor(DataDescriptor1()), |
| 1967 |
'class with __delete__ is a data descriptor') |
| 1968 |
self.assertTrue(inspect.isdatadescriptor(DataDescriptor2()), |
| 1969 |
'class with __set__ = None is a data descriptor') |
| 1970 |
|
| 1971 |
def test_slot(self): |
| 1972 |
class Slotted: |
| 1973 |
__slots__ = 'foo', |
| 1974 |
self.assertTrue(inspect.isdatadescriptor(Slotted.foo), |
| 1975 |
'a slot is a data descriptor') |
| 1976 |
|
| 1977 |
def test_property(self): |
| 1978 |
class Propertied: |
| 1979 |
@property |
| 1980 |
def a_property(self): |
| 1981 |
pass |
| 1982 |
self.assertTrue(inspect.isdatadescriptor(Propertied.a_property), |
| 1983 |
'a property is a data descriptor') |
| 1984 |
|
| 1985 |
def test_functions(self): |
| 1986 |
class Test(object): |
| 1987 |
def instance_method(self): pass |
| 1988 |
@classmethod |
| 1989 |
def class_method(cls): pass |
| 1990 |
@staticmethod |
| 1991 |
def static_method(): pass |
| 1992 |
def function(): |
| 1993 |
pass |
| 1994 |
a_lambda = lambda: None |
| 1995 |
self.assertFalse(inspect.isdatadescriptor(Test().instance_method), |
| 1996 |
'a instance method is not a data descriptor') |
| 1997 |
self.assertFalse(inspect.isdatadescriptor(Test().class_method), |
| 1998 |
'a class method is not a data descriptor') |
| 1999 |
self.assertFalse(inspect.isdatadescriptor(Test().static_method), |
| 2000 |
'a static method is not a data descriptor') |
| 2001 |
self.assertFalse(inspect.isdatadescriptor(function), |
| 2002 |
'a function is not a data descriptor') |
| 2003 |
self.assertFalse(inspect.isdatadescriptor(a_lambda), |
| 2004 |
'a lambda is not a data descriptor') |
| 2005 |
|
| 2006 |
|
| 2007 |
_global_ref = object() |
| 2008 |
class TestGetClosureVars(unittest.TestCase): |
| 2009 |
|
| 2010 |
def test_name_resolution(self): |
| 2011 |
# Basic test of the 4 different resolution mechanisms |
| 2012 |
def f(nonlocal_ref): |
| 2013 |
def g(local_ref): |
| 2014 |
print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 2015 |
return g |
| 2016 |
_arg = object() |
| 2017 |
nonlocal_vars = {"nonlocal_ref": _arg} |
| 2018 |
global_vars = {"_global_ref": _global_ref} |
| 2019 |
builtin_vars = {"print": print} |
| 2020 |
unbound_names = {"unbound_ref"} |
| 2021 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 2022 |
builtin_vars, unbound_names) |
| 2023 |
self.assertEqual(inspect.getclosurevars(f(_arg)), expected) |
| 2024 |
|
| 2025 |
def test_generator_closure(self): |
| 2026 |
def f(nonlocal_ref): |
| 2027 |
def g(local_ref): |
| 2028 |
print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 2029 |
yield |
| 2030 |
return g |
| 2031 |
_arg = object() |
| 2032 |
nonlocal_vars = {"nonlocal_ref": _arg} |
| 2033 |
global_vars = {"_global_ref": _global_ref} |
| 2034 |
builtin_vars = {"print": print} |
| 2035 |
unbound_names = {"unbound_ref"} |
| 2036 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 2037 |
builtin_vars, unbound_names) |
| 2038 |
self.assertEqual(inspect.getclosurevars(f(_arg)), expected) |
| 2039 |
|
| 2040 |
def test_method_closure(self): |
| 2041 |
class C: |
| 2042 |
def f(self, nonlocal_ref): |
| 2043 |
def g(local_ref): |
| 2044 |
print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 2045 |
return g |
| 2046 |
_arg = object() |
| 2047 |
nonlocal_vars = {"nonlocal_ref": _arg} |
| 2048 |
global_vars = {"_global_ref": _global_ref} |
| 2049 |
builtin_vars = {"print": print} |
| 2050 |
unbound_names = {"unbound_ref"} |
| 2051 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 2052 |
builtin_vars, unbound_names) |
| 2053 |
self.assertEqual(inspect.getclosurevars(C().f(_arg)), expected) |
| 2054 |
|
| 2055 |
def test_attribute_same_name_as_global_var(self): |
| 2056 |
class C: |
| 2057 |
_global_ref = object() |
| 2058 |
def f(): |
| 2059 |
print(C._global_ref, _global_ref) |
| 2060 |
nonlocal_vars = {"C": C} |
| 2061 |
global_vars = {"_global_ref": _global_ref} |
| 2062 |
builtin_vars = {"print": print} |
| 2063 |
unbound_names = {"_global_ref"} |
| 2064 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 2065 |
builtin_vars, unbound_names) |
| 2066 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 2067 |
|
| 2068 |
def test_nonlocal_vars(self): |
| 2069 |
# More complex tests of nonlocal resolution |
| 2070 |
def _nonlocal_vars(f): |
| 2071 |
return inspect.getclosurevars(f).nonlocals |
| 2072 |
|
| 2073 |
def make_adder(x): |
| 2074 |
def add(y): |
| 2075 |
return x + y |
| 2076 |
return add |
| 2077 |
|
| 2078 |
def curry(func, arg1): |
| 2079 |
return lambda arg2: func(arg1, arg2) |
| 2080 |
|
| 2081 |
def less_than(a, b): |
| 2082 |
return a < b |
| 2083 |
|
| 2084 |
# The infamous Y combinator. |
| 2085 |
def Y(le): |
| 2086 |
def g(f): |
| 2087 |
return le(lambda x: f(f)(x)) |
| 2088 |
Y.g_ref = g |
| 2089 |
return g(g) |
| 2090 |
|
| 2091 |
def check_y_combinator(func): |
| 2092 |
self.assertEqual(_nonlocal_vars(func), {'f': Y.g_ref}) |
| 2093 |
|
| 2094 |
inc = make_adder(1) |
| 2095 |
add_two = make_adder(2) |
| 2096 |
greater_than_five = curry(less_than, 5) |
| 2097 |
|
| 2098 |
self.assertEqual(_nonlocal_vars(inc), {'x': 1}) |
| 2099 |
self.assertEqual(_nonlocal_vars(add_two), {'x': 2}) |
| 2100 |
self.assertEqual(_nonlocal_vars(greater_than_five), |
| 2101 |
{'arg1': 5, 'func': less_than}) |
| 2102 |
self.assertEqual(_nonlocal_vars((lambda x: lambda y: x + y)(3)), |
| 2103 |
{'x': 3}) |
| 2104 |
Y(check_y_combinator) |
| 2105 |
|
| 2106 |
def test_getclosurevars_empty(self): |
| 2107 |
def foo(): pass |
| 2108 |
_empty = inspect.ClosureVars({}, {}, {}, set()) |
| 2109 |
self.assertEqual(inspect.getclosurevars(lambda: True), _empty) |
| 2110 |
self.assertEqual(inspect.getclosurevars(foo), _empty) |
| 2111 |
|
| 2112 |
def test_getclosurevars_error(self): |
| 2113 |
class T: pass |
| 2114 |
self.assertRaises(TypeError, inspect.getclosurevars, 1) |
| 2115 |
self.assertRaises(TypeError, inspect.getclosurevars, list) |
| 2116 |
self.assertRaises(TypeError, inspect.getclosurevars, {}) |
| 2117 |
|
| 2118 |
def _private_globals(self): |
| 2119 |
code = """def f(): print(path)""" |
| 2120 |
ns = {} |
| 2121 |
exec(code, ns) |
| 2122 |
return ns["f"], ns |
| 2123 |
|
| 2124 |
def test_builtins_fallback(self): |
| 2125 |
f, ns = self._private_globals() |
| 2126 |
ns.pop("__builtins__", None) |
| 2127 |
expected = inspect.ClosureVars({}, {}, {"print":print}, {"path"}) |
| 2128 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 2129 |
|
| 2130 |
def test_builtins_as_dict(self): |
| 2131 |
f, ns = self._private_globals() |
| 2132 |
ns["__builtins__"] = {"path":1} |
| 2133 |
expected = inspect.ClosureVars({}, {}, {"path":1}, {"print"}) |
| 2134 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 2135 |
|
| 2136 |
def test_builtins_as_module(self): |
| 2137 |
f, ns = self._private_globals() |
| 2138 |
ns["__builtins__"] = os |
| 2139 |
expected = inspect.ClosureVars({}, {}, {"path":os.path}, {"print"}) |
| 2140 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 2141 |
|
| 2142 |
|
| 2143 |
class TestGetcallargsFunctions(unittest.TestCase): |
| 2144 |
|
| 2145 |
def assertEqualCallArgs(self, func, call_params_string, locs=None): |
| 2146 |
locs = dict(locs or {}, func=func) |
| 2147 |
r1 = eval('func(%s)' % call_params_string, None, locs) |
| 2148 |
r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None, |
| 2149 |
locs) |
| 2150 |
self.assertEqual(r1, r2) |
| 2151 |
|
| 2152 |
def assertEqualException(self, func, call_param_string, locs=None): |
| 2153 |
locs = dict(locs or {}, func=func) |
| 2154 |
try: |
| 2155 |
eval('func(%s)' % call_param_string, None, locs) |
| 2156 |
except Exception as e: |
| 2157 |
ex1 = e |
| 2158 |
else: |
| 2159 |
self.fail('Exception not raised') |
| 2160 |
try: |
| 2161 |
eval('inspect.getcallargs(func, %s)' % call_param_string, None, |
| 2162 |
locs) |
| 2163 |
except Exception as e: |
| 2164 |
ex2 = e |
| 2165 |
else: |
| 2166 |
self.fail('Exception not raised') |
| 2167 |
self.assertIs(type(ex1), type(ex2)) |
| 2168 |
self.assertEqual(str(ex1), str(ex2)) |
| 2169 |
del ex1, ex2 |
| 2170 |
|
| 2171 |
def makeCallable(self, signature): |
| 2172 |
"""Create a function that returns its locals()""" |
| 2173 |
code = "lambda %s: locals()" |
| 2174 |
return eval(code % signature) |
| 2175 |
|
| 2176 |
def test_plain(self): |
| 2177 |
f = self.makeCallable('a, b=1') |
| 2178 |
self.assertEqualCallArgs(f, '2') |
| 2179 |
self.assertEqualCallArgs(f, '2, 3') |
| 2180 |
self.assertEqualCallArgs(f, 'a=2') |
| 2181 |
self.assertEqualCallArgs(f, 'b=3, a=2') |
| 2182 |
self.assertEqualCallArgs(f, '2, b=3') |
| 2183 |
# expand *iterable / **mapping |
| 2184 |
self.assertEqualCallArgs(f, '*(2,)') |
| 2185 |
self.assertEqualCallArgs(f, '*[2]') |
| 2186 |
self.assertEqualCallArgs(f, '*(2, 3)') |
| 2187 |
self.assertEqualCallArgs(f, '*[2, 3]') |
| 2188 |
self.assertEqualCallArgs(f, '**{"a":2}') |
| 2189 |
self.assertEqualCallArgs(f, 'b=3, **{"a":2}') |
| 2190 |
self.assertEqualCallArgs(f, '2, **{"b":3}') |
| 2191 |
self.assertEqualCallArgs(f, '**{"b":3, "a":2}') |
| 2192 |
# expand UserList / UserDict |
| 2193 |
self.assertEqualCallArgs(f, '*collections.UserList([2])') |
| 2194 |
self.assertEqualCallArgs(f, '*collections.UserList([2, 3])') |
| 2195 |
self.assertEqualCallArgs(f, '**collections.UserDict(a=2)') |
| 2196 |
self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)') |
| 2197 |
self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') |
| 2198 |
|
| 2199 |
def test_varargs(self): |
| 2200 |
f = self.makeCallable('a, b=1, *c') |
| 2201 |
self.assertEqualCallArgs(f, '2') |
| 2202 |
self.assertEqualCallArgs(f, '2, 3') |
| 2203 |
self.assertEqualCallArgs(f, '2, 3, 4') |
| 2204 |
self.assertEqualCallArgs(f, '*(2,3,4)') |
| 2205 |
self.assertEqualCallArgs(f, '2, *[3,4]') |
| 2206 |
self.assertEqualCallArgs(f, '2, 3, *collections.UserList([4])') |
| 2207 |
|
| 2208 |
def test_varkw(self): |
| 2209 |
f = self.makeCallable('a, b=1, **c') |
| 2210 |
self.assertEqualCallArgs(f, 'a=2') |
| 2211 |
self.assertEqualCallArgs(f, '2, b=3, c=4') |
| 2212 |
self.assertEqualCallArgs(f, 'b=3, a=2, c=4') |
| 2213 |
self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}') |
| 2214 |
self.assertEqualCallArgs(f, '2, c=4, **{"b":3}') |
| 2215 |
self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}') |
| 2216 |
self.assertEqualCallArgs(f, '**collections.UserDict(a=2, b=3, c=4)') |
| 2217 |
self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)') |
| 2218 |
self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3, c=4)') |
| 2219 |
|
| 2220 |
def test_varkw_only(self): |
| 2221 |
# issue11256: |
| 2222 |
f = self.makeCallable('**c') |
| 2223 |
self.assertEqualCallArgs(f, '') |
| 2224 |
self.assertEqualCallArgs(f, 'a=1') |
| 2225 |
self.assertEqualCallArgs(f, 'a=1, b=2') |
| 2226 |
self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}') |
| 2227 |
self.assertEqualCallArgs(f, '**collections.UserDict(a=1, b=2)') |
| 2228 |
self.assertEqualCallArgs(f, 'c=3, **collections.UserDict(a=1, b=2)') |
| 2229 |
|
| 2230 |
def test_keyword_only(self): |
| 2231 |
f = self.makeCallable('a=3, *, c, d=2') |
| 2232 |
self.assertEqualCallArgs(f, 'c=3') |
| 2233 |
self.assertEqualCallArgs(f, 'c=3, a=3') |
| 2234 |
self.assertEqualCallArgs(f, 'a=2, c=4') |
| 2235 |
self.assertEqualCallArgs(f, '4, c=4') |
| 2236 |
self.assertEqualException(f, '') |
| 2237 |
self.assertEqualException(f, '3') |
| 2238 |
self.assertEqualException(f, 'a=3') |
| 2239 |
self.assertEqualException(f, 'd=4') |
| 2240 |
|
| 2241 |
f = self.makeCallable('*, c, d=2') |
| 2242 |
self.assertEqualCallArgs(f, 'c=3') |
| 2243 |
self.assertEqualCallArgs(f, 'c=3, d=4') |
| 2244 |
self.assertEqualCallArgs(f, 'd=4, c=3') |
| 2245 |
|
| 2246 |
def test_multiple_features(self): |
| 2247 |
f = self.makeCallable('a, b=2, *f, **g') |
| 2248 |
self.assertEqualCallArgs(f, '2, 3, 7') |
| 2249 |
self.assertEqualCallArgs(f, '2, 3, x=8') |
| 2250 |
self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') |
| 2251 |
self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9') |
| 2252 |
self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9') |
| 2253 |
self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' |
| 2254 |
'[2, 3, (4,[5,6])]), **{"y":9, "z":10}') |
| 2255 |
self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' |
| 2256 |
'(4,[5,6])]), **collections.UserDict(' |
| 2257 |
'y=9, z=10)') |
| 2258 |
|
| 2259 |
f = self.makeCallable('a, b=2, *f, x, y=99, **g') |
| 2260 |
self.assertEqualCallArgs(f, '2, 3, x=8') |
| 2261 |
self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') |
| 2262 |
self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10') |
| 2263 |
self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10') |
| 2264 |
self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' |
| 2265 |
'[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}') |
| 2266 |
self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' |
| 2267 |
'(4,[5,6])]), q=0, **collections.UserDict(' |
| 2268 |
'y=9, z=10)') |
| 2269 |
|
| 2270 |
def test_errors(self): |
| 2271 |
f0 = self.makeCallable('') |
| 2272 |
f1 = self.makeCallable('a, b') |
| 2273 |
f2 = self.makeCallable('a, b=1') |
| 2274 |
# f0 takes no arguments |
| 2275 |
self.assertEqualException(f0, '1') |
| 2276 |
self.assertEqualException(f0, 'x=1') |
| 2277 |
self.assertEqualException(f0, '1,x=1') |
| 2278 |
# f1 takes exactly 2 arguments |
| 2279 |
self.assertEqualException(f1, '') |
| 2280 |
self.assertEqualException(f1, '1') |
| 2281 |
self.assertEqualException(f1, 'a=2') |
| 2282 |
self.assertEqualException(f1, 'b=3') |
| 2283 |
# f2 takes at least 1 argument |
| 2284 |
self.assertEqualException(f2, '') |
| 2285 |
self.assertEqualException(f2, 'b=3') |
| 2286 |
for f in f1, f2: |
| 2287 |
# f1/f2 takes exactly/at most 2 arguments |
| 2288 |
self.assertEqualException(f, '2, 3, 4') |
| 2289 |
self.assertEqualException(f, '1, 2, 3, a=1') |
| 2290 |
self.assertEqualException(f, '2, 3, 4, c=5') |
| 2291 |
self.assertEqualException(f, '2, 3, 4, a=1, c=5') |
| 2292 |
# f got an unexpected keyword argument |
| 2293 |
self.assertEqualException(f, 'c=2') |
| 2294 |
self.assertEqualException(f, '2, c=3') |
| 2295 |
self.assertEqualException(f, '2, 3, c=4') |
| 2296 |
self.assertEqualException(f, '2, c=4, b=3') |
| 2297 |
self.assertEqualException(f, '**{u"\u03c0\u03b9": 4}') |
| 2298 |
# f got multiple values for keyword argument |
| 2299 |
self.assertEqualException(f, '1, a=2') |
| 2300 |
self.assertEqualException(f, '1, **{"a":2}') |
| 2301 |
self.assertEqualException(f, '1, 2, b=3') |
| 2302 |
self.assertEqualException(f, '1, c=3, a=2') |
| 2303 |
# issue11256: |
| 2304 |
f3 = self.makeCallable('**c') |
| 2305 |
self.assertEqualException(f3, '1, 2') |
| 2306 |
self.assertEqualException(f3, '1, 2, a=1, b=2') |
| 2307 |
f4 = self.makeCallable('*, a, b=0') |
| 2308 |
self.assertEqualException(f4, '1, 2') |
| 2309 |
self.assertEqualException(f4, '1, 2, a=1, b=2') |
| 2310 |
self.assertEqualException(f4, 'a=1, a=3') |
| 2311 |
self.assertEqualException(f4, 'a=1, c=3') |
| 2312 |
self.assertEqualException(f4, 'a=1, a=3, b=4') |
| 2313 |
self.assertEqualException(f4, 'a=1, b=2, a=3, b=4') |
| 2314 |
self.assertEqualException(f4, 'a=1, a=2, a=3, b=4') |
| 2315 |
|
| 2316 |
# issue #20816: getcallargs() fails to iterate over non-existent |
| 2317 |
# kwonlydefaults and raises a wrong TypeError |
| 2318 |
def f5(*, a): pass |
| 2319 |
with self.assertRaisesRegex(TypeError, |
| 2320 |
'missing 1 required keyword-only'): |
| 2321 |
inspect.getcallargs(f5) |
| 2322 |
|
| 2323 |
|
| 2324 |
# issue20817: |
| 2325 |
def f6(a, b, c): |
| 2326 |
pass |
| 2327 |
with self.assertRaisesRegex(TypeError, "'a', 'b' and 'c'"): |
| 2328 |
inspect.getcallargs(f6) |
| 2329 |
|
| 2330 |
# bpo-33197 |
| 2331 |
with self.assertRaisesRegex(ValueError, |
| 2332 |
'variadic keyword parameters cannot' |
| 2333 |
' have default values'): |
| 2334 |
inspect.Parameter("foo", kind=inspect.Parameter.VAR_KEYWORD, |
| 2335 |
default=42) |
| 2336 |
with self.assertRaisesRegex(ValueError, |
| 2337 |
"value 5 is not a valid Parameter.kind"): |
| 2338 |
inspect.Parameter("bar", kind=5, default=42) |
| 2339 |
|
| 2340 |
with self.assertRaisesRegex(TypeError, |
| 2341 |
'name must be a str, not a int'): |
| 2342 |
inspect.Parameter(123, kind=4) |
| 2343 |
|
| 2344 |
class TestGetcallargsMethods(TestGetcallargsFunctions): |
| 2345 |
|
| 2346 |
def setUp(self): |
| 2347 |
class Foo(object): |
| 2348 |
pass |
| 2349 |
self.cls = Foo |
| 2350 |
self.inst = Foo() |
| 2351 |
|
| 2352 |
def makeCallable(self, signature): |
| 2353 |
assert 'self' not in signature |
| 2354 |
mk = super(TestGetcallargsMethods, self).makeCallable |
| 2355 |
self.cls.method = mk('self, ' + signature) |
| 2356 |
return self.inst.method |
| 2357 |
|
| 2358 |
class TestGetcallargsUnboundMethods(TestGetcallargsMethods): |
| 2359 |
|
| 2360 |
def makeCallable(self, signature): |
| 2361 |
super(TestGetcallargsUnboundMethods, self).makeCallable(signature) |
| 2362 |
return self.cls.method |
| 2363 |
|
| 2364 |
def assertEqualCallArgs(self, func, call_params_string, locs=None): |
| 2365 |
return super(TestGetcallargsUnboundMethods, self).assertEqualCallArgs( |
| 2366 |
*self._getAssertEqualParams(func, call_params_string, locs)) |
| 2367 |
|
| 2368 |
def assertEqualException(self, func, call_params_string, locs=None): |
| 2369 |
return super(TestGetcallargsUnboundMethods, self).assertEqualException( |
| 2370 |
*self._getAssertEqualParams(func, call_params_string, locs)) |
| 2371 |
|
| 2372 |
def _getAssertEqualParams(self, func, call_params_string, locs=None): |
| 2373 |
assert 'inst' not in call_params_string |
| 2374 |
locs = dict(locs or {}, inst=self.inst) |
| 2375 |
return (func, 'inst,' + call_params_string, locs) |
| 2376 |
|
| 2377 |
|
| 2378 |
class TestGetattrStatic(unittest.TestCase): |
| 2379 |
|
| 2380 |
def test_basic(self): |
| 2381 |
class Thing(object): |
| 2382 |
x = object() |
| 2383 |
|
| 2384 |
thing = Thing() |
| 2385 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 2386 |
self.assertEqual(inspect.getattr_static(thing, 'x', None), Thing.x) |
| 2387 |
with self.assertRaises(AttributeError): |
| 2388 |
inspect.getattr_static(thing, 'y') |
| 2389 |
|
| 2390 |
self.assertEqual(inspect.getattr_static(thing, 'y', 3), 3) |
| 2391 |
|
| 2392 |
def test_inherited(self): |
| 2393 |
class Thing(object): |
| 2394 |
x = object() |
| 2395 |
class OtherThing(Thing): |
| 2396 |
pass |
| 2397 |
|
| 2398 |
something = OtherThing() |
| 2399 |
self.assertEqual(inspect.getattr_static(something, 'x'), Thing.x) |
| 2400 |
|
| 2401 |
def test_instance_attr(self): |
| 2402 |
class Thing(object): |
| 2403 |
x = 2 |
| 2404 |
def __init__(self, x): |
| 2405 |
self.x = x |
| 2406 |
thing = Thing(3) |
| 2407 |
self.assertEqual(inspect.getattr_static(thing, 'x'), 3) |
| 2408 |
del thing.x |
| 2409 |
self.assertEqual(inspect.getattr_static(thing, 'x'), 2) |
| 2410 |
|
| 2411 |
def test_property(self): |
| 2412 |
class Thing(object): |
| 2413 |
@property |
| 2414 |
def x(self): |
| 2415 |
raise AttributeError("I'm pretending not to exist") |
| 2416 |
thing = Thing() |
| 2417 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 2418 |
|
| 2419 |
def test_descriptor_raises_AttributeError(self): |
| 2420 |
class descriptor(object): |
| 2421 |
def __get__(*_): |
| 2422 |
raise AttributeError("I'm pretending not to exist") |
| 2423 |
desc = descriptor() |
| 2424 |
class Thing(object): |
| 2425 |
x = desc |
| 2426 |
thing = Thing() |
| 2427 |
self.assertEqual(inspect.getattr_static(thing, 'x'), desc) |
| 2428 |
|
| 2429 |
def test_classAttribute(self): |
| 2430 |
class Thing(object): |
| 2431 |
x = object() |
| 2432 |
|
| 2433 |
self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.x) |
| 2434 |
|
| 2435 |
def test_classVirtualAttribute(self): |
| 2436 |
class Thing(object): |
| 2437 |
@types.DynamicClassAttribute |
| 2438 |
def x(self): |
| 2439 |
return self._x |
| 2440 |
_x = object() |
| 2441 |
|
| 2442 |
self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.__dict__['x']) |
| 2443 |
|
| 2444 |
def test_inherited_classattribute(self): |
| 2445 |
class Thing(object): |
| 2446 |
x = object() |
| 2447 |
class OtherThing(Thing): |
| 2448 |
pass |
| 2449 |
|
| 2450 |
self.assertEqual(inspect.getattr_static(OtherThing, 'x'), Thing.x) |
| 2451 |
|
| 2452 |
def test_slots(self): |
| 2453 |
class Thing(object): |
| 2454 |
y = 'bar' |
| 2455 |
__slots__ = ['x'] |
| 2456 |
def __init__(self): |
| 2457 |
self.x = 'foo' |
| 2458 |
thing = Thing() |
| 2459 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 2460 |
self.assertEqual(inspect.getattr_static(thing, 'y'), 'bar') |
| 2461 |
|
| 2462 |
del thing.x |
| 2463 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 2464 |
|
| 2465 |
def test_metaclass(self): |
| 2466 |
class meta(type): |
| 2467 |
attr = 'foo' |
| 2468 |
class Thing(object, metaclass=meta): |
| 2469 |
pass |
| 2470 |
self.assertEqual(inspect.getattr_static(Thing, 'attr'), 'foo') |
| 2471 |
|
| 2472 |
class sub(meta): |
| 2473 |
pass |
| 2474 |
class OtherThing(object, metaclass=sub): |
| 2475 |
x = 3 |
| 2476 |
self.assertEqual(inspect.getattr_static(OtherThing, 'attr'), 'foo') |
| 2477 |
|
| 2478 |
class OtherOtherThing(OtherThing): |
| 2479 |
pass |
| 2480 |
# this test is odd, but it was added as it exposed a bug |
| 2481 |
self.assertEqual(inspect.getattr_static(OtherOtherThing, 'x'), 3) |
| 2482 |
|
| 2483 |
def test_no_dict_no_slots(self): |
| 2484 |
self.assertEqual(inspect.getattr_static(1, 'foo', None), None) |
| 2485 |
self.assertNotEqual(inspect.getattr_static('foo', 'lower'), None) |
| 2486 |
|
| 2487 |
def test_no_dict_no_slots_instance_member(self): |
| 2488 |
# returns descriptor |
| 2489 |
with open(__file__, encoding='utf-8') as handle: |
| 2490 |
self.assertEqual(inspect.getattr_static(handle, 'name'), type(handle).name) |
| 2491 |
|
| 2492 |
def test_inherited_slots(self): |
| 2493 |
# returns descriptor |
| 2494 |
class Thing(object): |
| 2495 |
__slots__ = ['x'] |
| 2496 |
def __init__(self): |
| 2497 |
self.x = 'foo' |
| 2498 |
|
| 2499 |
class OtherThing(Thing): |
| 2500 |
pass |
| 2501 |
# it would be nice if this worked... |
| 2502 |
# we get the descriptor instead of the instance attribute |
| 2503 |
self.assertEqual(inspect.getattr_static(OtherThing(), 'x'), Thing.x) |
| 2504 |
|
| 2505 |
def test_descriptor(self): |
| 2506 |
class descriptor(object): |
| 2507 |
def __get__(self, instance, owner): |
| 2508 |
return 3 |
| 2509 |
class Foo(object): |
| 2510 |
d = descriptor() |
| 2511 |
|
| 2512 |
foo = Foo() |
| 2513 |
|
| 2514 |
# for a non data descriptor we return the instance attribute |
| 2515 |
foo.__dict__['d'] = 1 |
| 2516 |
self.assertEqual(inspect.getattr_static(foo, 'd'), 1) |
| 2517 |
|
| 2518 |
# if the descriptor is a data-descriptor we should return the |
| 2519 |
# descriptor |
| 2520 |
descriptor.__set__ = lambda s, i, v: None |
| 2521 |
self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d']) |
| 2522 |
|
| 2523 |
del descriptor.__set__ |
| 2524 |
descriptor.__delete__ = lambda s, i, o: None |
| 2525 |
self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d']) |
| 2526 |
|
| 2527 |
def test_metaclass_with_descriptor(self): |
| 2528 |
class descriptor(object): |
| 2529 |
def __get__(self, instance, owner): |
| 2530 |
return 3 |
| 2531 |
class meta(type): |
| 2532 |
d = descriptor() |
| 2533 |
class Thing(object, metaclass=meta): |
| 2534 |
pass |
| 2535 |
self.assertEqual(inspect.getattr_static(Thing, 'd'), meta.__dict__['d']) |
| 2536 |
|
| 2537 |
|
| 2538 |
def test_class_as_property(self): |
| 2539 |
class Base(object): |
| 2540 |
foo = 3 |
| 2541 |
|
| 2542 |
class Something(Base): |
| 2543 |
executed = False |
| 2544 |
@property |
| 2545 |
def __class__(self): |
| 2546 |
self.executed = True |
| 2547 |
return object |
| 2548 |
|
| 2549 |
instance = Something() |
| 2550 |
self.assertEqual(inspect.getattr_static(instance, 'foo'), 3) |
| 2551 |
self.assertFalse(instance.executed) |
| 2552 |
self.assertEqual(inspect.getattr_static(Something, 'foo'), 3) |
| 2553 |
|
| 2554 |
def test_mro_as_property(self): |
| 2555 |
class Meta(type): |
| 2556 |
@property |
| 2557 |
def __mro__(self): |
| 2558 |
return (object,) |
| 2559 |
|
| 2560 |
class Base(object): |
| 2561 |
foo = 3 |
| 2562 |
|
| 2563 |
class Something(Base, metaclass=Meta): |
| 2564 |
pass |
| 2565 |
|
| 2566 |
self.assertEqual(inspect.getattr_static(Something(), 'foo'), 3) |
| 2567 |
self.assertEqual(inspect.getattr_static(Something, 'foo'), 3) |
| 2568 |
|
| 2569 |
def test_dict_as_property(self): |
| 2570 |
test = self |
| 2571 |
test.called = False |
| 2572 |
|
| 2573 |
class Foo(dict): |
| 2574 |
a = 3 |
| 2575 |
@property |
| 2576 |
def __dict__(self): |
| 2577 |
test.called = True |
| 2578 |
return {} |
| 2579 |
|
| 2580 |
foo = Foo() |
| 2581 |
foo.a = 4 |
| 2582 |
self.assertEqual(inspect.getattr_static(foo, 'a'), 3) |
| 2583 |
self.assertFalse(test.called) |
| 2584 |
|
| 2585 |
class Bar(Foo): pass |
| 2586 |
|
| 2587 |
bar = Bar() |
| 2588 |
bar.a = 5 |
| 2589 |
self.assertEqual(inspect.getattr_static(bar, 'a'), 3) |
| 2590 |
self.assertFalse(test.called) |
| 2591 |
|
| 2592 |
def test_mutated_mro(self): |
| 2593 |
test = self |
| 2594 |
test.called = False |
| 2595 |
|
| 2596 |
class Foo(dict): |
| 2597 |
a = 3 |
| 2598 |
@property |
| 2599 |
def __dict__(self): |
| 2600 |
test.called = True |
| 2601 |
return {} |
| 2602 |
|
| 2603 |
class Bar(dict): |
| 2604 |
a = 4 |
| 2605 |
|
| 2606 |
class Baz(Bar): pass |
| 2607 |
|
| 2608 |
baz = Baz() |
| 2609 |
self.assertEqual(inspect.getattr_static(baz, 'a'), 4) |
| 2610 |
Baz.__bases__ = (Foo,) |
| 2611 |
self.assertEqual(inspect.getattr_static(baz, 'a'), 3) |
| 2612 |
self.assertFalse(test.called) |
| 2613 |
|
| 2614 |
def test_custom_object_dict(self): |
| 2615 |
test = self |
| 2616 |
test.called = False |
| 2617 |
|
| 2618 |
class Custom(dict): |
| 2619 |
def get(self, key, default=None): |
| 2620 |
test.called = True |
| 2621 |
super().get(key, default) |
| 2622 |
|
| 2623 |
class Foo(object): |
| 2624 |
a = 3 |
| 2625 |
foo = Foo() |
| 2626 |
foo.__dict__ = Custom() |
| 2627 |
self.assertEqual(inspect.getattr_static(foo, 'a'), 3) |
| 2628 |
self.assertFalse(test.called) |
| 2629 |
|
| 2630 |
def test_metaclass_dict_as_property(self): |
| 2631 |
class Meta(type): |
| 2632 |
@property |
| 2633 |
def __dict__(self): |
| 2634 |
self.executed = True |
| 2635 |
|
| 2636 |
class Thing(metaclass=Meta): |
| 2637 |
executed = False |
| 2638 |
|
| 2639 |
def __init__(self): |
| 2640 |
self.spam = 42 |
| 2641 |
|
| 2642 |
instance = Thing() |
| 2643 |
self.assertEqual(inspect.getattr_static(instance, "spam"), 42) |
| 2644 |
self.assertFalse(Thing.executed) |
| 2645 |
|
| 2646 |
def test_module(self): |
| 2647 |
sentinel = object() |
| 2648 |
self.assertIsNot(inspect.getattr_static(sys, "version", sentinel), |
| 2649 |
sentinel) |
| 2650 |
|
| 2651 |
def test_metaclass_with_metaclass_with_dict_as_property(self): |
| 2652 |
class MetaMeta(type): |
| 2653 |
@property |
| 2654 |
def __dict__(self): |
| 2655 |
self.executed = True |
| 2656 |
return dict(spam=42) |
| 2657 |
|
| 2658 |
class Meta(type, metaclass=MetaMeta): |
| 2659 |
executed = False |
| 2660 |
|
| 2661 |
class Thing(metaclass=Meta): |
| 2662 |
pass |
| 2663 |
|
| 2664 |
with self.assertRaises(AttributeError): |
| 2665 |
inspect.getattr_static(Thing, "spam") |
| 2666 |
self.assertFalse(Thing.executed) |
| 2667 |
|
| 2668 |
def test_custom___getattr__(self): |
| 2669 |
test = self |
| 2670 |
test.called = False |
| 2671 |
|
| 2672 |
class Foo: |
| 2673 |
def __getattr__(self, attr): |
| 2674 |
test.called = True |
| 2675 |
return {} |
| 2676 |
|
| 2677 |
with self.assertRaises(AttributeError): |
| 2678 |
inspect.getattr_static(Foo(), 'whatever') |
| 2679 |
|
| 2680 |
self.assertFalse(test.called) |
| 2681 |
|
| 2682 |
def test_custom___getattribute__(self): |
| 2683 |
test = self |
| 2684 |
test.called = False |
| 2685 |
|
| 2686 |
class Foo: |
| 2687 |
def __getattribute__(self, attr): |
| 2688 |
test.called = True |
| 2689 |
return {} |
| 2690 |
|
| 2691 |
with self.assertRaises(AttributeError): |
| 2692 |
inspect.getattr_static(Foo(), 'really_could_be_anything') |
| 2693 |
|
| 2694 |
self.assertFalse(test.called) |
| 2695 |
|
| 2696 |
def test_cache_does_not_cause_classes_to_persist(self): |
| 2697 |
# regression test for gh-118013: |
| 2698 |
# check that the internal _shadowed_dict cache does not cause |
| 2699 |
# dynamically created classes to have extended lifetimes even |
| 2700 |
# when no other strong references to those classes remain. |
| 2701 |
# Since these classes can themselves hold strong references to |
| 2702 |
# other objects, this can cause unexpected memory consumption. |
| 2703 |
class Foo: pass |
| 2704 |
Foo.instance = Foo() |
| 2705 |
weakref_to_class = weakref.ref(Foo) |
| 2706 |
inspect.getattr_static(Foo.instance, 'whatever', 'irrelevant') |
| 2707 |
del Foo |
| 2708 |
gc.collect() |
| 2709 |
self.assertIsNone(weakref_to_class()) |
| 2710 |
|
| 2711 |
|
| 2712 |
class TestGetGeneratorState(unittest.TestCase): |
| 2713 |
|
| 2714 |
def setUp(self): |
| 2715 |
def number_generator(): |
| 2716 |
for number in range(5): |
| 2717 |
yield number |
| 2718 |
self.generator = number_generator() |
| 2719 |
|
| 2720 |
def _generatorstate(self): |
| 2721 |
return inspect.getgeneratorstate(self.generator) |
| 2722 |
|
| 2723 |
def test_created(self): |
| 2724 |
self.assertEqual(self._generatorstate(), inspect.GEN_CREATED) |
| 2725 |
|
| 2726 |
def test_suspended(self): |
| 2727 |
next(self.generator) |
| 2728 |
self.assertEqual(self._generatorstate(), inspect.GEN_SUSPENDED) |
| 2729 |
|
| 2730 |
def test_closed_after_exhaustion(self): |
| 2731 |
for i in self.generator: |
| 2732 |
pass |
| 2733 |
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 2734 |
|
| 2735 |
def test_closed_after_immediate_exception(self): |
| 2736 |
with self.assertRaises(RuntimeError): |
| 2737 |
self.generator.throw(RuntimeError) |
| 2738 |
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 2739 |
|
| 2740 |
def test_closed_after_close(self): |
| 2741 |
self.generator.close() |
| 2742 |
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 2743 |
|
| 2744 |
def test_running(self): |
| 2745 |
# As mentioned on issue #10220, checking for the RUNNING state only |
| 2746 |
# makes sense inside the generator itself. |
| 2747 |
# The following generator checks for this by using the closure's |
| 2748 |
# reference to self and the generator state checking helper method |
| 2749 |
def running_check_generator(): |
| 2750 |
for number in range(5): |
| 2751 |
self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING) |
| 2752 |
yield number |
| 2753 |
self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING) |
| 2754 |
self.generator = running_check_generator() |
| 2755 |
# Running up to the first yield |
| 2756 |
next(self.generator) |
| 2757 |
# Running after the first yield |
| 2758 |
next(self.generator) |
| 2759 |
|
| 2760 |
def test_types_coroutine_wrapper_state(self): |
| 2761 |
def gen(): |
| 2762 |
yield 1 |
| 2763 |
yield 2 |
| 2764 |
|
| 2765 |
@types.coroutine |
| 2766 |
def wrapped_generator_coro(): |
| 2767 |
# return a generator iterator so types.coroutine |
| 2768 |
# wraps it into types._GeneratorWrapper. |
| 2769 |
return gen() |
| 2770 |
|
| 2771 |
g = wrapped_generator_coro() |
| 2772 |
self.addCleanup(g.close) |
| 2773 |
self.assertIs(type(g), types._GeneratorWrapper) |
| 2774 |
|
| 2775 |
# _GeneratorWrapper must provide gi_suspended/cr_suspended |
| 2776 |
# so inspect.get*state() doesn't raise AttributeError. |
| 2777 |
self.assertEqual(inspect.getgeneratorstate(g), inspect.GEN_CREATED) |
| 2778 |
self.assertEqual(inspect.getcoroutinestate(g), inspect.CORO_CREATED) |
| 2779 |
|
| 2780 |
next(g) |
| 2781 |
self.assertEqual(inspect.getgeneratorstate(g), inspect.GEN_SUSPENDED) |
| 2782 |
self.assertEqual(inspect.getcoroutinestate(g), inspect.CORO_SUSPENDED) |
| 2783 |
|
| 2784 |
def test_easy_debugging(self): |
| 2785 |
# repr() and str() of a generator state should contain the state name |
| 2786 |
names = 'GEN_CREATED GEN_RUNNING GEN_SUSPENDED GEN_CLOSED'.split() |
| 2787 |
for name in names: |
| 2788 |
state = getattr(inspect, name) |
| 2789 |
self.assertIn(name, repr(state)) |
| 2790 |
self.assertIn(name, str(state)) |
| 2791 |
|
| 2792 |
def test_getgeneratorlocals(self): |
| 2793 |
def each(lst, a=None): |
| 2794 |
b=(1, 2, 3) |
| 2795 |
for v in lst: |
| 2796 |
if v == 3: |
| 2797 |
c = 12 |
| 2798 |
yield v |
| 2799 |
|
| 2800 |
numbers = each([1, 2, 3]) |
| 2801 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2802 |
{'a': None, 'lst': [1, 2, 3]}) |
| 2803 |
next(numbers) |
| 2804 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2805 |
{'a': None, 'lst': [1, 2, 3], 'v': 1, |
| 2806 |
'b': (1, 2, 3)}) |
| 2807 |
next(numbers) |
| 2808 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2809 |
{'a': None, 'lst': [1, 2, 3], 'v': 2, |
| 2810 |
'b': (1, 2, 3)}) |
| 2811 |
next(numbers) |
| 2812 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2813 |
{'a': None, 'lst': [1, 2, 3], 'v': 3, |
| 2814 |
'b': (1, 2, 3), 'c': 12}) |
| 2815 |
try: |
| 2816 |
next(numbers) |
| 2817 |
except StopIteration: |
| 2818 |
pass |
| 2819 |
self.assertEqual(inspect.getgeneratorlocals(numbers), {}) |
| 2820 |
|
| 2821 |
def test_getgeneratorlocals_empty(self): |
| 2822 |
def yield_one(): |
| 2823 |
yield 1 |
| 2824 |
one = yield_one() |
| 2825 |
self.assertEqual(inspect.getgeneratorlocals(one), {}) |
| 2826 |
try: |
| 2827 |
next(one) |
| 2828 |
except StopIteration: |
| 2829 |
pass |
| 2830 |
self.assertEqual(inspect.getgeneratorlocals(one), {}) |
| 2831 |
|
| 2832 |
def test_getgeneratorlocals_error(self): |
| 2833 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, 1) |
| 2834 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, lambda x: True) |
| 2835 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, set) |
| 2836 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, (2,3)) |
| 2837 |
|
| 2838 |
|
| 2839 |
class TestGetCoroutineState(unittest.TestCase): |
| 2840 |
|
| 2841 |
def setUp(self): |
| 2842 |
@types.coroutine |
| 2843 |
def number_coroutine(): |
| 2844 |
for number in range(5): |
| 2845 |
yield number |
| 2846 |
async def coroutine(): |
| 2847 |
await number_coroutine() |
| 2848 |
self.coroutine = coroutine() |
| 2849 |
|
| 2850 |
def tearDown(self): |
| 2851 |
self.coroutine.close() |
| 2852 |
|
| 2853 |
def _coroutinestate(self): |
| 2854 |
return inspect.getcoroutinestate(self.coroutine) |
| 2855 |
|
| 2856 |
def test_created(self): |
| 2857 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CREATED) |
| 2858 |
|
| 2859 |
def test_suspended(self): |
| 2860 |
self.coroutine.send(None) |
| 2861 |
self.assertEqual(self._coroutinestate(), inspect.CORO_SUSPENDED) |
| 2862 |
|
| 2863 |
def test_closed_after_exhaustion(self): |
| 2864 |
while True: |
| 2865 |
try: |
| 2866 |
self.coroutine.send(None) |
| 2867 |
except StopIteration: |
| 2868 |
break |
| 2869 |
|
| 2870 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 2871 |
|
| 2872 |
def test_closed_after_immediate_exception(self): |
| 2873 |
with self.assertRaises(RuntimeError): |
| 2874 |
self.coroutine.throw(RuntimeError) |
| 2875 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 2876 |
|
| 2877 |
def test_closed_after_close(self): |
| 2878 |
self.coroutine.close() |
| 2879 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 2880 |
|
| 2881 |
def test_easy_debugging(self): |
| 2882 |
# repr() and str() of a coroutine state should contain the state name |
| 2883 |
names = 'CORO_CREATED CORO_RUNNING CORO_SUSPENDED CORO_CLOSED'.split() |
| 2884 |
for name in names: |
| 2885 |
state = getattr(inspect, name) |
| 2886 |
self.assertIn(name, repr(state)) |
| 2887 |
self.assertIn(name, str(state)) |
| 2888 |
|
| 2889 |
def test_getcoroutinelocals(self): |
| 2890 |
@types.coroutine |
| 2891 |
def gencoro(): |
| 2892 |
yield |
| 2893 |
|
| 2894 |
gencoro = gencoro() |
| 2895 |
async def func(a=None): |
| 2896 |
b = 'spam' |
| 2897 |
await gencoro |
| 2898 |
|
| 2899 |
coro = func() |
| 2900 |
self.assertEqual(inspect.getcoroutinelocals(coro), |
| 2901 |
{'a': None, 'gencoro': gencoro}) |
| 2902 |
coro.send(None) |
| 2903 |
self.assertEqual(inspect.getcoroutinelocals(coro), |
| 2904 |
{'a': None, 'gencoro': gencoro, 'b': 'spam'}) |
| 2905 |
|
| 2906 |
|
| 2907 |
@support.requires_working_socket() |
| 2908 |
class TestGetAsyncGenState(unittest.IsolatedAsyncioTestCase): |
| 2909 |
|
| 2910 |
def setUp(self): |
| 2911 |
async def number_asyncgen(): |
| 2912 |
for number in range(5): |
| 2913 |
yield number |
| 2914 |
self.asyncgen = number_asyncgen() |
| 2915 |
|
| 2916 |
async def asyncTearDown(self): |
| 2917 |
await self.asyncgen.aclose() |
| 2918 |
|
| 2919 |
@classmethod |
| 2920 |
def tearDownClass(cls): |
| 2921 |
asyncio.events._set_event_loop_policy(None) |
| 2922 |
|
| 2923 |
def _asyncgenstate(self): |
| 2924 |
return inspect.getasyncgenstate(self.asyncgen) |
| 2925 |
|
| 2926 |
def test_created(self): |
| 2927 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_CREATED) |
| 2928 |
|
| 2929 |
async def test_suspended(self): |
| 2930 |
value = await anext(self.asyncgen) |
| 2931 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_SUSPENDED) |
| 2932 |
self.assertEqual(value, 0) |
| 2933 |
|
| 2934 |
async def test_closed_after_exhaustion(self): |
| 2935 |
countdown = 7 |
| 2936 |
with self.assertRaises(StopAsyncIteration): |
| 2937 |
while countdown := countdown - 1: |
| 2938 |
await anext(self.asyncgen) |
| 2939 |
self.assertEqual(countdown, 1) |
| 2940 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_CLOSED) |
| 2941 |
|
| 2942 |
async def test_closed_after_immediate_exception(self): |
| 2943 |
with self.assertRaises(RuntimeError): |
| 2944 |
await self.asyncgen.athrow(RuntimeError) |
| 2945 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_CLOSED) |
| 2946 |
|
| 2947 |
async def test_running(self): |
| 2948 |
async def running_check_asyncgen(): |
| 2949 |
for number in range(5): |
| 2950 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_RUNNING) |
| 2951 |
yield number |
| 2952 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_RUNNING) |
| 2953 |
self.asyncgen = running_check_asyncgen() |
| 2954 |
# Running up to the first yield |
| 2955 |
await anext(self.asyncgen) |
| 2956 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_SUSPENDED) |
| 2957 |
# Running after the first yield |
| 2958 |
await anext(self.asyncgen) |
| 2959 |
self.assertEqual(self._asyncgenstate(), inspect.AGEN_SUSPENDED) |
| 2960 |
|
| 2961 |
def test_easy_debugging(self): |
| 2962 |
# repr() and str() of a asyncgen state should contain the state name |
| 2963 |
names = 'AGEN_CREATED AGEN_RUNNING AGEN_SUSPENDED AGEN_CLOSED'.split() |
| 2964 |
for name in names: |
| 2965 |
state = getattr(inspect, name) |
| 2966 |
self.assertIn(name, repr(state)) |
| 2967 |
self.assertIn(name, str(state)) |
| 2968 |
|
| 2969 |
async def test_getasyncgenlocals(self): |
| 2970 |
async def each(lst, a=None): |
| 2971 |
b=(1, 2, 3) |
| 2972 |
for v in lst: |
| 2973 |
if v == 3: |
| 2974 |
c = 12 |
| 2975 |
yield v |
| 2976 |
|
| 2977 |
numbers = each([1, 2, 3]) |
| 2978 |
self.assertEqual(inspect.getasyncgenlocals(numbers), |
| 2979 |
{'a': None, 'lst': [1, 2, 3]}) |
| 2980 |
await anext(numbers) |
| 2981 |
self.assertEqual(inspect.getasyncgenlocals(numbers), |
| 2982 |
{'a': None, 'lst': [1, 2, 3], 'v': 1, |
| 2983 |
'b': (1, 2, 3)}) |
| 2984 |
await anext(numbers) |
| 2985 |
self.assertEqual(inspect.getasyncgenlocals(numbers), |
| 2986 |
{'a': None, 'lst': [1, 2, 3], 'v': 2, |
| 2987 |
'b': (1, 2, 3)}) |
| 2988 |
await anext(numbers) |
| 2989 |
self.assertEqual(inspect.getasyncgenlocals(numbers), |
| 2990 |
{'a': None, 'lst': [1, 2, 3], 'v': 3, |
| 2991 |
'b': (1, 2, 3), 'c': 12}) |
| 2992 |
with self.assertRaises(StopAsyncIteration): |
| 2993 |
await anext(numbers) |
| 2994 |
self.assertEqual(inspect.getasyncgenlocals(numbers), {}) |
| 2995 |
|
| 2996 |
async def test_getasyncgenlocals_empty(self): |
| 2997 |
async def yield_one(): |
| 2998 |
yield 1 |
| 2999 |
one = yield_one() |
| 3000 |
self.assertEqual(inspect.getasyncgenlocals(one), {}) |
| 3001 |
await anext(one) |
| 3002 |
self.assertEqual(inspect.getasyncgenlocals(one), {}) |
| 3003 |
with self.assertRaises(StopAsyncIteration): |
| 3004 |
await anext(one) |
| 3005 |
self.assertEqual(inspect.getasyncgenlocals(one), {}) |
| 3006 |
|
| 3007 |
def test_getasyncgenlocals_error(self): |
| 3008 |
self.assertRaises(TypeError, inspect.getasyncgenlocals, 1) |
| 3009 |
self.assertRaises(TypeError, inspect.getasyncgenlocals, lambda x: True) |
| 3010 |
self.assertRaises(TypeError, inspect.getasyncgenlocals, set) |
| 3011 |
self.assertRaises(TypeError, inspect.getasyncgenlocals, (2,3)) |
| 3012 |
|
| 3013 |
|
| 3014 |
class MySignature(inspect.Signature): |
| 3015 |
# Top-level to make it picklable; |
| 3016 |
# used in test_signature_object_pickle |
| 3017 |
pass |
| 3018 |
|
| 3019 |
class MyParameter(inspect.Parameter): |
| 3020 |
# Top-level to make it picklable; |
| 3021 |
# used in test_signature_object_pickle |
| 3022 |
pass |
| 3023 |
|
| 3024 |
|
| 3025 |
|
| 3026 |
class TestSignatureObject(unittest.TestCase): |
| 3027 |
@staticmethod |
| 3028 |
def signature(func, **kw): |
| 3029 |
sig = inspect.signature(func, **kw) |
| 3030 |
return (tuple((param.name, |
| 3031 |
(... if param.default is param.empty else param.default), |
| 3032 |
(... if param.annotation is param.empty |
| 3033 |
else param.annotation), |
| 3034 |
str(param.kind).lower()) |
| 3035 |
for param in sig.parameters.values()), |
| 3036 |
(... if sig.return_annotation is sig.empty |
| 3037 |
else sig.return_annotation)) |
| 3038 |
|
| 3039 |
def test_signature_object(self): |
| 3040 |
S = inspect.Signature |
| 3041 |
P = inspect.Parameter |
| 3042 |
|
| 3043 |
self.assertEqual(str(S()), '()') |
| 3044 |
self.assertEqual(repr(S().parameters), 'mappingproxy(OrderedDict())') |
| 3045 |
|
| 3046 |
def test(po, /, pk, pkd=100, *args, ko, kod=10, **kwargs): |
| 3047 |
pass |
| 3048 |
|
| 3049 |
sig = inspect.signature(test) |
| 3050 |
self.assertStartsWith(repr(sig), '<Signature') |
| 3051 |
self.assertTrue('(po, /, pk' in repr(sig)) |
| 3052 |
|
| 3053 |
# We need two functions, because it is impossible to represent |
| 3054 |
# all param kinds in a single one. |
| 3055 |
def test2(pod=42, /): |
| 3056 |
pass |
| 3057 |
|
| 3058 |
sig2 = inspect.signature(test2) |
| 3059 |
self.assertStartsWith(repr(sig2), '<Signature') |
| 3060 |
self.assertTrue('(pod=42, /)' in repr(sig2)) |
| 3061 |
|
| 3062 |
po = sig.parameters['po'] |
| 3063 |
pod = sig2.parameters['pod'] |
| 3064 |
pk = sig.parameters['pk'] |
| 3065 |
pkd = sig.parameters['pkd'] |
| 3066 |
args = sig.parameters['args'] |
| 3067 |
ko = sig.parameters['ko'] |
| 3068 |
kod = sig.parameters['kod'] |
| 3069 |
kwargs = sig.parameters['kwargs'] |
| 3070 |
|
| 3071 |
S((po, pk, args, ko, kwargs)) |
| 3072 |
S((po, pk, ko, kod)) |
| 3073 |
S((po, pod, ko)) |
| 3074 |
S((po, pod, kod)) |
| 3075 |
S((pod, ko, kod)) |
| 3076 |
S((pod, kod)) |
| 3077 |
S((pod, args, kod, kwargs)) |
| 3078 |
# keyword-only parameters without default values |
| 3079 |
# can follow keyword-only parameters with default values: |
| 3080 |
S((kod, ko)) |
| 3081 |
S((kod, ko, kwargs)) |
| 3082 |
S((args, kod, ko)) |
| 3083 |
|
| 3084 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 3085 |
S((pk, po, args, ko, kwargs)) |
| 3086 |
|
| 3087 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 3088 |
S((po, args, pk, ko, kwargs)) |
| 3089 |
|
| 3090 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 3091 |
S((args, po, pk, ko, kwargs)) |
| 3092 |
|
| 3093 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 3094 |
S((po, pk, args, kwargs, ko)) |
| 3095 |
|
| 3096 |
kwargs2 = kwargs.replace(name='args') |
| 3097 |
with self.assertRaisesRegex(ValueError, 'duplicate parameter name'): |
| 3098 |
S((po, pk, args, kwargs2, ko)) |
| 3099 |
|
| 3100 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 3101 |
S((pod, po)) |
| 3102 |
|
| 3103 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 3104 |
S((pod, pk)) |
| 3105 |
|
| 3106 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 3107 |
S((po, pod, pk)) |
| 3108 |
|
| 3109 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 3110 |
S((po, pkd, pk)) |
| 3111 |
|
| 3112 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 3113 |
S((pkd, pk)) |
| 3114 |
|
| 3115 |
second_args = args.replace(name="second_args") |
| 3116 |
with self.assertRaisesRegex(ValueError, 'more than one variadic positional parameter'): |
| 3117 |
S((args, second_args)) |
| 3118 |
|
| 3119 |
with self.assertRaisesRegex(ValueError, 'more than one variadic positional parameter'): |
| 3120 |
S((args, ko, second_args)) |
| 3121 |
|
| 3122 |
second_kwargs = kwargs.replace(name="second_kwargs") |
| 3123 |
with self.assertRaisesRegex(ValueError, 'more than one variadic keyword parameter'): |
| 3124 |
S((kwargs, second_kwargs)) |
| 3125 |
|
| 3126 |
def test_signature_object_pickle(self): |
| 3127 |
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 3128 |
foo_partial = functools.partial(foo, a=1) |
| 3129 |
|
| 3130 |
sig = inspect.signature(foo_partial) |
| 3131 |
|
| 3132 |
for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 3133 |
with self.subTest(pickle_ver=ver, subclass=False): |
| 3134 |
sig_pickled = pickle.loads(pickle.dumps(sig, ver)) |
| 3135 |
self.assertEqual(sig, sig_pickled) |
| 3136 |
|
| 3137 |
# Test that basic sub-classing works |
| 3138 |
sig = inspect.signature(foo) |
| 3139 |
myparam = MyParameter(name='z', kind=inspect.Parameter.POSITIONAL_ONLY) |
| 3140 |
myparams = collections.OrderedDict(sig.parameters, a=myparam) |
| 3141 |
mysig = MySignature().replace(parameters=myparams.values(), |
| 3142 |
return_annotation=sig.return_annotation) |
| 3143 |
self.assertTrue(isinstance(mysig, MySignature)) |
| 3144 |
self.assertTrue(isinstance(mysig.parameters['z'], MyParameter)) |
| 3145 |
|
| 3146 |
for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 3147 |
with self.subTest(pickle_ver=ver, subclass=True): |
| 3148 |
sig_pickled = pickle.loads(pickle.dumps(mysig, ver)) |
| 3149 |
self.assertEqual(mysig, sig_pickled) |
| 3150 |
self.assertTrue(isinstance(sig_pickled, MySignature)) |
| 3151 |
self.assertTrue(isinstance(sig_pickled.parameters['z'], |
| 3152 |
MyParameter)) |
| 3153 |
|
| 3154 |
def test_signature_immutability(self): |
| 3155 |
def test(a): |
| 3156 |
pass |
| 3157 |
sig = inspect.signature(test) |
| 3158 |
|
| 3159 |
with self.assertRaises(AttributeError): |
| 3160 |
sig.foo = 'bar' |
| 3161 |
|
| 3162 |
with self.assertRaises(TypeError): |
| 3163 |
sig.parameters['a'] = None |
| 3164 |
|
| 3165 |
def test_signature_on_noarg(self): |
| 3166 |
def test(): |
| 3167 |
pass |
| 3168 |
self.assertEqual(self.signature(test), ((), ...)) |
| 3169 |
|
| 3170 |
def test_signature_on_wargs(self): |
| 3171 |
def test(a, b:'foo') -> 123: |
| 3172 |
pass |
| 3173 |
self.assertEqual(self.signature(test), |
| 3174 |
((('a', ..., ..., "positional_or_keyword"), |
| 3175 |
('b', ..., 'foo', "positional_or_keyword")), |
| 3176 |
123)) |
| 3177 |
|
| 3178 |
def test_signature_on_wkwonly(self): |
| 3179 |
def test(*, a:float, b:str) -> int: |
| 3180 |
pass |
| 3181 |
self.assertEqual(self.signature(test), |
| 3182 |
((('a', ..., float, "keyword_only"), |
| 3183 |
('b', ..., str, "keyword_only")), |
| 3184 |
int)) |
| 3185 |
|
| 3186 |
def test_signature_on_complex_args(self): |
| 3187 |
def test(a, b:'foo'=10, *args:'bar', spam:'baz', ham=123, **kwargs:int): |
| 3188 |
pass |
| 3189 |
self.assertEqual(self.signature(test), |
| 3190 |
((('a', ..., ..., "positional_or_keyword"), |
| 3191 |
('b', 10, 'foo', "positional_or_keyword"), |
| 3192 |
('args', ..., 'bar', "var_positional"), |
| 3193 |
('spam', ..., 'baz', "keyword_only"), |
| 3194 |
('ham', 123, ..., "keyword_only"), |
| 3195 |
('kwargs', ..., int, "var_keyword")), |
| 3196 |
...)) |
| 3197 |
|
| 3198 |
def test_signature_without_self(self): |
| 3199 |
def test_args_only(*args): # NOQA |
| 3200 |
pass |
| 3201 |
|
| 3202 |
def test_args_kwargs_only(*args, **kwargs): # NOQA |
| 3203 |
pass |
| 3204 |
|
| 3205 |
class A: |
| 3206 |
@classmethod |
| 3207 |
def test_classmethod(*args): # NOQA |
| 3208 |
pass |
| 3209 |
|
| 3210 |
@staticmethod |
| 3211 |
def test_staticmethod(*args): # NOQA |
| 3212 |
pass |
| 3213 |
|
| 3214 |
f1 = functools.partialmethod((test_classmethod), 1) |
| 3215 |
f2 = functools.partialmethod((test_args_only), 1) |
| 3216 |
f3 = functools.partialmethod((test_staticmethod), 1) |
| 3217 |
f4 = functools.partialmethod((test_args_kwargs_only),1) |
| 3218 |
|
| 3219 |
self.assertEqual(self.signature(test_args_only), |
| 3220 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 3221 |
self.assertEqual(self.signature(test_args_kwargs_only), |
| 3222 |
((('args', ..., ..., 'var_positional'), |
| 3223 |
('kwargs', ..., ..., 'var_keyword')), ...)) |
| 3224 |
self.assertEqual(self.signature(A.f1), |
| 3225 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 3226 |
self.assertEqual(self.signature(A.f2), |
| 3227 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 3228 |
self.assertEqual(self.signature(A.f3), |
| 3229 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 3230 |
self.assertEqual(self.signature(A.f4), |
| 3231 |
((('args', ..., ..., 'var_positional'), |
| 3232 |
('kwargs', ..., ..., 'var_keyword')), ...)) |
| 3233 |
@cpython_only |
| 3234 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3235 |
"Signature information for builtins requires docstrings") |
| 3236 |
def test_signature_on_builtins(self): |
| 3237 |
_testcapi = import_helper.import_module("_testcapi") |
| 3238 |
|
| 3239 |
def test_unbound_method(o): |
| 3240 |
"""Use this to test unbound methods (things that should have a self)""" |
| 3241 |
signature = inspect.signature(o) |
| 3242 |
self.assertTrue(isinstance(signature, inspect.Signature)) |
| 3243 |
self.assertEqual(list(signature.parameters.values())[0].name, 'self') |
| 3244 |
return signature |
| 3245 |
|
| 3246 |
def test_callable(o): |
| 3247 |
"""Use this to test bound methods or normal callables (things that don't expect self)""" |
| 3248 |
signature = inspect.signature(o) |
| 3249 |
self.assertTrue(isinstance(signature, inspect.Signature)) |
| 3250 |
if signature.parameters: |
| 3251 |
self.assertNotEqual(list(signature.parameters.values())[0].name, 'self') |
| 3252 |
return signature |
| 3253 |
|
| 3254 |
signature = test_callable(_testcapi.docstring_with_signature_with_defaults) |
| 3255 |
def p(name): return signature.parameters[name].default |
| 3256 |
self.assertEqual(p('s'), 'avocado') |
| 3257 |
self.assertEqual(p('b'), b'bytes') |
| 3258 |
self.assertEqual(p('d'), 3.14) |
| 3259 |
self.assertEqual(p('i'), 35) |
| 3260 |
self.assertEqual(p('n'), None) |
| 3261 |
self.assertEqual(p('t'), True) |
| 3262 |
self.assertEqual(p('f'), False) |
| 3263 |
self.assertEqual(p('local'), 3) |
| 3264 |
self.assertEqual(p('sys'), sys.maxsize) |
| 3265 |
self.assertEqual(p('exp'), sys.maxsize - 1) |
| 3266 |
|
| 3267 |
test_callable(object) |
| 3268 |
|
| 3269 |
# normal method |
| 3270 |
# (PyMethodDescr_Type, "method_descriptor") |
| 3271 |
test_unbound_method(_pickle.Pickler.dump) |
| 3272 |
d = _pickle.Pickler(io.StringIO()) |
| 3273 |
test_callable(d.dump) |
| 3274 |
|
| 3275 |
# static method |
| 3276 |
test_callable(bytes.maketrans) |
| 3277 |
test_callable(b'abc'.maketrans) |
| 3278 |
|
| 3279 |
# class method |
| 3280 |
test_callable(dict.fromkeys) |
| 3281 |
test_callable({}.fromkeys) |
| 3282 |
|
| 3283 |
# wrapper around slot (PyWrapperDescr_Type, "wrapper_descriptor") |
| 3284 |
test_unbound_method(type.__call__) |
| 3285 |
test_unbound_method(int.__add__) |
| 3286 |
test_callable((3).__add__) |
| 3287 |
|
| 3288 |
# _PyMethodWrapper_Type |
| 3289 |
# support for 'method-wrapper' |
| 3290 |
test_callable(min.__call__) |
| 3291 |
|
| 3292 |
# This doesn't work now. |
| 3293 |
# (We don't have a valid signature for "type" in 3.4) |
| 3294 |
class ThisWorksNow: |
| 3295 |
__call__ = type |
| 3296 |
# TODO: Support type. |
| 3297 |
self.assertEqual(ThisWorksNow()(1), int) |
| 3298 |
self.assertEqual(ThisWorksNow()('A', (), {}).__name__, 'A') |
| 3299 |
with self.assertRaisesRegex(ValueError, "no signature found"): |
| 3300 |
test_callable(ThisWorksNow()) |
| 3301 |
|
| 3302 |
# Regression test for issue #20786 |
| 3303 |
test_unbound_method(dict.__delitem__) |
| 3304 |
test_unbound_method(property.__delete__) |
| 3305 |
|
| 3306 |
# Regression test for issue #20586 |
| 3307 |
test_callable(_testcapi.docstring_with_signature_but_no_doc) |
| 3308 |
|
| 3309 |
# Regression test for gh-104955 |
| 3310 |
method = bytearray.__release_buffer__ |
| 3311 |
sig = test_unbound_method(method) |
| 3312 |
self.assertEqual(list(sig.parameters), ['self', 'buffer']) |
| 3313 |
|
| 3314 |
@cpython_only |
| 3315 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3316 |
"Signature information for builtins requires docstrings") |
| 3317 |
def test_signature_on_decorated_builtins(self): |
| 3318 |
_testcapi = import_helper.import_module("_testcapi") |
| 3319 |
func = _testcapi.docstring_with_signature_with_defaults |
| 3320 |
|
| 3321 |
def decorator(func): |
| 3322 |
@functools.wraps(func) |
| 3323 |
def wrapper(*args, **kwargs) -> int: |
| 3324 |
return func(*args, **kwargs) |
| 3325 |
return wrapper |
| 3326 |
|
| 3327 |
decorated_func = decorator(func) |
| 3328 |
|
| 3329 |
self.assertEqual(inspect.signature(func), |
| 3330 |
inspect.signature(decorated_func)) |
| 3331 |
|
| 3332 |
def wrapper_like(*args, **kwargs) -> int: pass |
| 3333 |
self.assertEqual(inspect.signature(decorated_func, |
| 3334 |
follow_wrapped=False), |
| 3335 |
inspect.signature(wrapper_like)) |
| 3336 |
|
| 3337 |
@cpython_only |
| 3338 |
def test_signature_on_builtins_no_signature(self): |
| 3339 |
_testcapi = import_helper.import_module("_testcapi") |
| 3340 |
with self.assertRaisesRegex(ValueError, |
| 3341 |
'no signature found for builtin'): |
| 3342 |
inspect.signature(_testcapi.docstring_no_signature) |
| 3343 |
|
| 3344 |
with self.assertRaisesRegex(ValueError, |
| 3345 |
'no signature found for builtin'): |
| 3346 |
inspect.signature(str) |
| 3347 |
|
| 3348 |
cls = _testcapi.DocStringNoSignatureTest |
| 3349 |
obj = _testcapi.DocStringNoSignatureTest() |
| 3350 |
tests = [ |
| 3351 |
(_testcapi.docstring_no_signature_noargs, meth_noargs), |
| 3352 |
(_testcapi.docstring_no_signature_o, meth_o), |
| 3353 |
(cls.meth_noargs, meth_self_noargs), |
| 3354 |
(cls.meth_o, meth_self_o), |
| 3355 |
(obj.meth_noargs, meth_noargs), |
| 3356 |
(obj.meth_o, meth_o), |
| 3357 |
(cls.meth_noargs_class, meth_noargs), |
| 3358 |
(cls.meth_o_class, meth_o), |
| 3359 |
(cls.meth_noargs_static, meth_noargs), |
| 3360 |
(cls.meth_o_static, meth_o), |
| 3361 |
(cls.meth_noargs_coexist, meth_self_noargs), |
| 3362 |
(cls.meth_o_coexist, meth_self_o), |
| 3363 |
|
| 3364 |
(time.time, meth_noargs), |
| 3365 |
(str.lower, meth_self_noargs), |
| 3366 |
(''.lower, meth_noargs), |
| 3367 |
(set.add, meth_self_o), |
| 3368 |
(set().add, meth_o), |
| 3369 |
(set.__contains__, meth_self_o), |
| 3370 |
(set().__contains__, meth_o), |
| 3371 |
(datetime.datetime.__dict__['utcnow'], meth_type_noargs), |
| 3372 |
(datetime.datetime.utcnow, meth_noargs), |
| 3373 |
(dict.__dict__['__class_getitem__'], meth_type_o), |
| 3374 |
(dict.__class_getitem__, meth_o), |
| 3375 |
] |
| 3376 |
try: |
| 3377 |
import _stat # noqa: F401 |
| 3378 |
except ImportError: |
| 3379 |
# if the _stat extension is not available, stat.S_IMODE() is |
| 3380 |
# implemented in Python, not in C |
| 3381 |
pass |
| 3382 |
else: |
| 3383 |
tests.append((stat.S_IMODE, meth_o)) |
| 3384 |
for builtin, template in tests: |
| 3385 |
with self.subTest(builtin): |
| 3386 |
self.assertEqual(inspect.signature(builtin), |
| 3387 |
inspect.signature(template)) |
| 3388 |
|
| 3389 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3390 |
"Signature information for builtins requires docstrings") |
| 3391 |
def test_signature_parsing_with_defaults(self): |
| 3392 |
_testcapi = import_helper.import_module("_testcapi") |
| 3393 |
meth = _testcapi.DocStringUnrepresentableSignatureTest.with_default |
| 3394 |
self.assertEqual(str(inspect.signature(meth)), '(self, /, x=1)') |
| 3395 |
|
| 3396 |
def test_signature_on_non_function(self): |
| 3397 |
with self.assertRaisesRegex(TypeError, 'is not a callable object'): |
| 3398 |
inspect.signature(42) |
| 3399 |
|
| 3400 |
def test_signature_from_functionlike_object(self): |
| 3401 |
def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): |
| 3402 |
pass |
| 3403 |
|
| 3404 |
class funclike: |
| 3405 |
# Has to be callable, and have correct |
| 3406 |
# __code__, __annotations__, __defaults__, __name__, |
| 3407 |
# and __kwdefaults__ attributes |
| 3408 |
|
| 3409 |
def __init__(self, func): |
| 3410 |
self.__name__ = func.__name__ |
| 3411 |
self.__code__ = func.__code__ |
| 3412 |
self.__annotations__ = func.__annotations__ |
| 3413 |
self.__defaults__ = func.__defaults__ |
| 3414 |
self.__kwdefaults__ = func.__kwdefaults__ |
| 3415 |
self.func = func |
| 3416 |
|
| 3417 |
def __call__(self, *args, **kwargs): |
| 3418 |
return self.func(*args, **kwargs) |
| 3419 |
|
| 3420 |
sig_func = inspect.Signature.from_callable(func) |
| 3421 |
|
| 3422 |
sig_funclike = inspect.Signature.from_callable(funclike(func)) |
| 3423 |
self.assertEqual(sig_funclike, sig_func) |
| 3424 |
|
| 3425 |
sig_funclike = inspect.signature(funclike(func)) |
| 3426 |
self.assertEqual(sig_funclike, sig_func) |
| 3427 |
|
| 3428 |
# If object is not a duck type of function, then |
| 3429 |
# signature will try to get a signature for its '__call__' |
| 3430 |
# method |
| 3431 |
fl = funclike(func) |
| 3432 |
del fl.__defaults__ |
| 3433 |
self.assertEqual(self.signature(fl), |
| 3434 |
((('args', ..., ..., "var_positional"), |
| 3435 |
('kwargs', ..., ..., "var_keyword")), |
| 3436 |
...)) |
| 3437 |
|
| 3438 |
# Test with cython-like builtins: |
| 3439 |
_orig_isdesc = inspect.ismethoddescriptor |
| 3440 |
def _isdesc(obj): |
| 3441 |
if hasattr(obj, '_builtinmock'): |
| 3442 |
return True |
| 3443 |
return _orig_isdesc(obj) |
| 3444 |
|
| 3445 |
with unittest.mock.patch('inspect.ismethoddescriptor', _isdesc): |
| 3446 |
builtin_func = funclike(func) |
| 3447 |
# Make sure that our mock setup is working |
| 3448 |
self.assertFalse(inspect.ismethoddescriptor(builtin_func)) |
| 3449 |
builtin_func._builtinmock = True |
| 3450 |
self.assertTrue(inspect.ismethoddescriptor(builtin_func)) |
| 3451 |
self.assertEqual(inspect.signature(builtin_func), sig_func) |
| 3452 |
|
| 3453 |
def test_signature_functionlike_class(self): |
| 3454 |
# We only want to duck type function-like objects, |
| 3455 |
# not classes. |
| 3456 |
|
| 3457 |
def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): |
| 3458 |
pass |
| 3459 |
|
| 3460 |
class funclike: |
| 3461 |
def __init__(self, marker): |
| 3462 |
pass |
| 3463 |
|
| 3464 |
__name__ = func.__name__ |
| 3465 |
__code__ = func.__code__ |
| 3466 |
__annotations__ = func.__annotations__ |
| 3467 |
__defaults__ = func.__defaults__ |
| 3468 |
__kwdefaults__ = func.__kwdefaults__ |
| 3469 |
|
| 3470 |
self.assertEqual(str(inspect.signature(funclike)), '(marker)') |
| 3471 |
|
| 3472 |
def test_signature_on_method(self): |
| 3473 |
class Test: |
| 3474 |
def __init__(*args): |
| 3475 |
pass |
| 3476 |
def m1(self, arg1, arg2=1) -> int: |
| 3477 |
pass |
| 3478 |
def m2(*args): |
| 3479 |
pass |
| 3480 |
def __call__(*, a): |
| 3481 |
pass |
| 3482 |
|
| 3483 |
self.assertEqual(self.signature(Test().m1), |
| 3484 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 3485 |
('arg2', 1, ..., "positional_or_keyword")), |
| 3486 |
int)) |
| 3487 |
|
| 3488 |
self.assertEqual(self.signature(Test().m2), |
| 3489 |
((('args', ..., ..., "var_positional"),), |
| 3490 |
...)) |
| 3491 |
|
| 3492 |
self.assertEqual(self.signature(Test), |
| 3493 |
((('args', ..., ..., "var_positional"),), |
| 3494 |
...)) |
| 3495 |
|
| 3496 |
with self.assertRaisesRegex(ValueError, 'invalid method signature'): |
| 3497 |
self.signature(Test()) |
| 3498 |
|
| 3499 |
def test_signature_wrapped_bound_method(self): |
| 3500 |
# Issue 24298 |
| 3501 |
class Test: |
| 3502 |
def m1(self, arg1, arg2=1) -> int: |
| 3503 |
pass |
| 3504 |
@functools.wraps(Test().m1) |
| 3505 |
def m1d(*args, **kwargs): |
| 3506 |
pass |
| 3507 |
self.assertEqual(self.signature(m1d), |
| 3508 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 3509 |
('arg2', 1, ..., "positional_or_keyword")), |
| 3510 |
int)) |
| 3511 |
|
| 3512 |
def test_signature_on_classmethod(self): |
| 3513 |
if not support.MISSING_C_DOCSTRINGS: |
| 3514 |
self.assertEqual(self.signature(classmethod), |
| 3515 |
((('function', ..., ..., "positional_only"),), |
| 3516 |
...)) |
| 3517 |
|
| 3518 |
class Test: |
| 3519 |
@classmethod |
| 3520 |
def foo(cls, arg1, *, arg2=1): |
| 3521 |
pass |
| 3522 |
|
| 3523 |
meth = Test().foo |
| 3524 |
self.assertEqual(self.signature(meth), |
| 3525 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 3526 |
('arg2', 1, ..., "keyword_only")), |
| 3527 |
...)) |
| 3528 |
|
| 3529 |
meth = Test.foo |
| 3530 |
self.assertEqual(self.signature(meth), |
| 3531 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 3532 |
('arg2', 1, ..., "keyword_only")), |
| 3533 |
...)) |
| 3534 |
|
| 3535 |
def test_signature_on_staticmethod(self): |
| 3536 |
if not support.MISSING_C_DOCSTRINGS: |
| 3537 |
self.assertEqual(self.signature(staticmethod), |
| 3538 |
((('function', ..., ..., "positional_only"),), |
| 3539 |
...)) |
| 3540 |
|
| 3541 |
class Test: |
| 3542 |
@staticmethod |
| 3543 |
def foo(cls, *, arg): |
| 3544 |
pass |
| 3545 |
|
| 3546 |
meth = Test().foo |
| 3547 |
self.assertEqual(self.signature(meth), |
| 3548 |
((('cls', ..., ..., "positional_or_keyword"), |
| 3549 |
('arg', ..., ..., "keyword_only")), |
| 3550 |
...)) |
| 3551 |
|
| 3552 |
meth = Test.foo |
| 3553 |
self.assertEqual(self.signature(meth), |
| 3554 |
((('cls', ..., ..., "positional_or_keyword"), |
| 3555 |
('arg', ..., ..., "keyword_only")), |
| 3556 |
...)) |
| 3557 |
|
| 3558 |
def test_signature_on_partial(self): |
| 3559 |
from functools import partial, Placeholder |
| 3560 |
|
| 3561 |
def test(): |
| 3562 |
pass |
| 3563 |
|
| 3564 |
self.assertEqual(self.signature(partial(test)), ((), ...)) |
| 3565 |
|
| 3566 |
with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 3567 |
inspect.signature(partial(test, 1)) |
| 3568 |
|
| 3569 |
with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 3570 |
inspect.signature(partial(test, a=1)) |
| 3571 |
|
| 3572 |
def test(a, b, *, c, d): |
| 3573 |
pass |
| 3574 |
|
| 3575 |
self.assertEqual(self.signature(partial(test)), |
| 3576 |
((('a', ..., ..., "positional_or_keyword"), |
| 3577 |
('b', ..., ..., "positional_or_keyword"), |
| 3578 |
('c', ..., ..., "keyword_only"), |
| 3579 |
('d', ..., ..., "keyword_only")), |
| 3580 |
...)) |
| 3581 |
|
| 3582 |
self.assertEqual(self.signature(partial(test, 1)), |
| 3583 |
((('b', ..., ..., "positional_or_keyword"), |
| 3584 |
('c', ..., ..., "keyword_only"), |
| 3585 |
('d', ..., ..., "keyword_only")), |
| 3586 |
...)) |
| 3587 |
|
| 3588 |
self.assertEqual(self.signature(partial(test, 1, c=2)), |
| 3589 |
((('b', ..., ..., "positional_or_keyword"), |
| 3590 |
('c', 2, ..., "keyword_only"), |
| 3591 |
('d', ..., ..., "keyword_only")), |
| 3592 |
...)) |
| 3593 |
|
| 3594 |
self.assertEqual(self.signature(partial(test, b=1, c=2)), |
| 3595 |
((('a', ..., ..., "positional_or_keyword"), |
| 3596 |
('b', 1, ..., "keyword_only"), |
| 3597 |
('c', 2, ..., "keyword_only"), |
| 3598 |
('d', ..., ..., "keyword_only")), |
| 3599 |
...)) |
| 3600 |
|
| 3601 |
self.assertEqual(self.signature(partial(test, 0, b=1, c=2)), |
| 3602 |
((('b', 1, ..., "keyword_only"), |
| 3603 |
('c', 2, ..., "keyword_only"), |
| 3604 |
('d', ..., ..., "keyword_only")), |
| 3605 |
...)) |
| 3606 |
|
| 3607 |
self.assertEqual(self.signature(partial(test, a=1)), |
| 3608 |
((('a', 1, ..., "keyword_only"), |
| 3609 |
('b', ..., ..., "keyword_only"), |
| 3610 |
('c', ..., ..., "keyword_only"), |
| 3611 |
('d', ..., ..., "keyword_only")), |
| 3612 |
...)) |
| 3613 |
|
| 3614 |
# With Placeholder |
| 3615 |
self.assertEqual(self.signature(partial(test, Placeholder, 1)), |
| 3616 |
((('a', ..., ..., "positional_only"), |
| 3617 |
('c', ..., ..., "keyword_only"), |
| 3618 |
('d', ..., ..., "keyword_only")), |
| 3619 |
...)) |
| 3620 |
|
| 3621 |
self.assertEqual(self.signature(partial(test, Placeholder, 1, c=2)), |
| 3622 |
((('a', ..., ..., "positional_only"), |
| 3623 |
('c', 2, ..., "keyword_only"), |
| 3624 |
('d', ..., ..., "keyword_only")), |
| 3625 |
...)) |
| 3626 |
|
| 3627 |
# Ensure unittest.mock.ANY & similar do not get picked up as a Placeholder |
| 3628 |
self.assertEqual(self.signature(partial(test, unittest.mock.ANY, 1, c=2)), |
| 3629 |
((('c', 2, ..., "keyword_only"), |
| 3630 |
('d', ..., ..., "keyword_only")), |
| 3631 |
...)) |
| 3632 |
|
| 3633 |
def test(a, *args, b, **kwargs): |
| 3634 |
pass |
| 3635 |
|
| 3636 |
self.assertEqual(self.signature(partial(test, 1)), |
| 3637 |
((('args', ..., ..., "var_positional"), |
| 3638 |
('b', ..., ..., "keyword_only"), |
| 3639 |
('kwargs', ..., ..., "var_keyword")), |
| 3640 |
...)) |
| 3641 |
|
| 3642 |
self.assertEqual(self.signature(partial(test, a=1)), |
| 3643 |
((('a', 1, ..., "keyword_only"), |
| 3644 |
('b', ..., ..., "keyword_only"), |
| 3645 |
('kwargs', ..., ..., "var_keyword")), |
| 3646 |
...)) |
| 3647 |
|
| 3648 |
self.assertEqual(self.signature(partial(test, 1, 2, 3)), |
| 3649 |
((('args', ..., ..., "var_positional"), |
| 3650 |
('b', ..., ..., "keyword_only"), |
| 3651 |
('kwargs', ..., ..., "var_keyword")), |
| 3652 |
...)) |
| 3653 |
|
| 3654 |
self.assertEqual(self.signature(partial(test, 1, 2, 3, test=True)), |
| 3655 |
((('args', ..., ..., "var_positional"), |
| 3656 |
('b', ..., ..., "keyword_only"), |
| 3657 |
('kwargs', ..., ..., "var_keyword")), |
| 3658 |
...)) |
| 3659 |
|
| 3660 |
self.assertEqual(self.signature(partial(test, 1, 2, 3, test=1, b=0)), |
| 3661 |
((('args', ..., ..., "var_positional"), |
| 3662 |
('b', 0, ..., "keyword_only"), |
| 3663 |
('kwargs', ..., ..., "var_keyword")), |
| 3664 |
...)) |
| 3665 |
|
| 3666 |
self.assertEqual(self.signature(partial(test, b=0)), |
| 3667 |
((('a', ..., ..., "positional_or_keyword"), |
| 3668 |
('args', ..., ..., "var_positional"), |
| 3669 |
('b', 0, ..., "keyword_only"), |
| 3670 |
('kwargs', ..., ..., "var_keyword")), |
| 3671 |
...)) |
| 3672 |
|
| 3673 |
self.assertEqual(self.signature(partial(test, b=0, test=1)), |
| 3674 |
((('a', ..., ..., "positional_or_keyword"), |
| 3675 |
('args', ..., ..., "var_positional"), |
| 3676 |
('b', 0, ..., "keyword_only"), |
| 3677 |
('kwargs', ..., ..., "var_keyword")), |
| 3678 |
...)) |
| 3679 |
|
| 3680 |
# With Placeholder |
| 3681 |
p = partial(test, Placeholder, Placeholder, 1, b=0, test=1) |
| 3682 |
self.assertEqual(self.signature(p), |
| 3683 |
((('a', ..., ..., "positional_only"), |
| 3684 |
('args', ..., ..., "var_positional"), |
| 3685 |
('b', 0, ..., "keyword_only"), |
| 3686 |
('kwargs', ..., ..., "var_keyword")), |
| 3687 |
...)) |
| 3688 |
|
| 3689 |
def test(a, b, c:int) -> 42: |
| 3690 |
pass |
| 3691 |
|
| 3692 |
sig = test.__signature__ = inspect.signature(test) |
| 3693 |
|
| 3694 |
self.assertEqual(self.signature(partial(partial(test, 1))), |
| 3695 |
((('b', ..., ..., "positional_or_keyword"), |
| 3696 |
('c', ..., int, "positional_or_keyword")), |
| 3697 |
42)) |
| 3698 |
|
| 3699 |
self.assertEqual(self.signature(partial(partial(test, 1), 2)), |
| 3700 |
((('c', ..., int, "positional_or_keyword"),), |
| 3701 |
42)) |
| 3702 |
|
| 3703 |
def foo(a): |
| 3704 |
return a |
| 3705 |
_foo = partial(partial(foo, a=10), a=20) |
| 3706 |
self.assertEqual(self.signature(_foo), |
| 3707 |
((('a', 20, ..., "keyword_only"),), |
| 3708 |
...)) |
| 3709 |
# check that we don't have any side-effects in signature(), |
| 3710 |
# and the partial object is still functioning |
| 3711 |
self.assertEqual(_foo(), 20) |
| 3712 |
|
| 3713 |
def foo(a, b, c): |
| 3714 |
return a, b, c |
| 3715 |
_foo = partial(partial(foo, 1, b=20), b=30) |
| 3716 |
|
| 3717 |
self.assertEqual(self.signature(_foo), |
| 3718 |
((('b', 30, ..., "keyword_only"), |
| 3719 |
('c', ..., ..., "keyword_only")), |
| 3720 |
...)) |
| 3721 |
self.assertEqual(_foo(c=10), (1, 30, 10)) |
| 3722 |
|
| 3723 |
def foo(a, b, c, *, d): |
| 3724 |
return a, b, c, d |
| 3725 |
_foo = partial(partial(foo, d=20, c=20), b=10, d=30) |
| 3726 |
self.assertEqual(self.signature(_foo), |
| 3727 |
((('a', ..., ..., "positional_or_keyword"), |
| 3728 |
('b', 10, ..., "keyword_only"), |
| 3729 |
('c', 20, ..., "keyword_only"), |
| 3730 |
('d', 30, ..., "keyword_only"), |
| 3731 |
), |
| 3732 |
...)) |
| 3733 |
ba = inspect.signature(_foo).bind(a=200, b=11) |
| 3734 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (200, 11, 20, 30)) |
| 3735 |
|
| 3736 |
def foo(a=1, b=2, c=3): |
| 3737 |
return a, b, c |
| 3738 |
_foo = partial(foo, c=13) # (a=1, b=2, *, c=13) |
| 3739 |
|
| 3740 |
ba = inspect.signature(_foo).bind(a=11) |
| 3741 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 2, 13)) |
| 3742 |
|
| 3743 |
ba = inspect.signature(_foo).bind(11, 12) |
| 3744 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) |
| 3745 |
|
| 3746 |
ba = inspect.signature(_foo).bind(11, b=12) |
| 3747 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) |
| 3748 |
|
| 3749 |
ba = inspect.signature(_foo).bind(b=12) |
| 3750 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (1, 12, 13)) |
| 3751 |
|
| 3752 |
_foo = partial(_foo, b=10, c=20) |
| 3753 |
ba = inspect.signature(_foo).bind(12) |
| 3754 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (12, 10, 20)) |
| 3755 |
|
| 3756 |
|
| 3757 |
def foo(a, b, /, c, d, **kwargs): |
| 3758 |
pass |
| 3759 |
sig = inspect.signature(foo) |
| 3760 |
self.assertEqual(str(sig), '(a, b, /, c, d, **kwargs)') |
| 3761 |
|
| 3762 |
self.assertEqual(self.signature(partial(foo, 1)), |
| 3763 |
((('b', ..., ..., 'positional_only'), |
| 3764 |
('c', ..., ..., 'positional_or_keyword'), |
| 3765 |
('d', ..., ..., 'positional_or_keyword'), |
| 3766 |
('kwargs', ..., ..., 'var_keyword')), |
| 3767 |
...)) |
| 3768 |
|
| 3769 |
self.assertEqual(self.signature(partial(foo, 1, 2)), |
| 3770 |
((('c', ..., ..., 'positional_or_keyword'), |
| 3771 |
('d', ..., ..., 'positional_or_keyword'), |
| 3772 |
('kwargs', ..., ..., 'var_keyword')), |
| 3773 |
...)) |
| 3774 |
|
| 3775 |
self.assertEqual(self.signature(partial(foo, 1, 2, 3)), |
| 3776 |
((('d', ..., ..., 'positional_or_keyword'), |
| 3777 |
('kwargs', ..., ..., 'var_keyword')), |
| 3778 |
...)) |
| 3779 |
|
| 3780 |
self.assertEqual(self.signature(partial(foo, 1, 2, c=3)), |
| 3781 |
((('c', 3, ..., 'keyword_only'), |
| 3782 |
('d', ..., ..., 'keyword_only'), |
| 3783 |
('kwargs', ..., ..., 'var_keyword')), |
| 3784 |
...)) |
| 3785 |
|
| 3786 |
self.assertEqual(self.signature(partial(foo, 1, c=3)), |
| 3787 |
((('b', ..., ..., 'positional_only'), |
| 3788 |
('c', 3, ..., 'keyword_only'), |
| 3789 |
('d', ..., ..., 'keyword_only'), |
| 3790 |
('kwargs', ..., ..., 'var_keyword')), |
| 3791 |
...)) |
| 3792 |
|
| 3793 |
# Positional only With Placeholder |
| 3794 |
p = partial(foo, Placeholder, 1, c=0, d=1) |
| 3795 |
self.assertEqual(self.signature(p), |
| 3796 |
((('a', ..., ..., "positional_only"), |
| 3797 |
('c', 0, ..., "keyword_only"), |
| 3798 |
('d', 1, ..., "keyword_only"), |
| 3799 |
('kwargs', ..., ..., "var_keyword")), |
| 3800 |
...)) |
| 3801 |
|
| 3802 |
# Optionals Positional With Placeholder |
| 3803 |
def foo(a=0, b=1, /, c=2, d=3): |
| 3804 |
pass |
| 3805 |
|
| 3806 |
# Positional |
| 3807 |
p = partial(foo, Placeholder, 1, c=0, d=1) |
| 3808 |
self.assertEqual(self.signature(p), |
| 3809 |
((('a', ..., ..., "positional_only"), |
| 3810 |
('c', 0, ..., "keyword_only"), |
| 3811 |
('d', 1, ..., "keyword_only")), |
| 3812 |
...)) |
| 3813 |
|
| 3814 |
# Positional or Keyword - transformed to positional |
| 3815 |
p = partial(foo, Placeholder, 1, Placeholder, 1) |
| 3816 |
self.assertEqual(self.signature(p), |
| 3817 |
((('a', ..., ..., "positional_only"), |
| 3818 |
('c', ..., ..., "positional_only")), |
| 3819 |
...)) |
| 3820 |
|
| 3821 |
def test_signature_on_partialmethod(self): |
| 3822 |
from functools import partialmethod |
| 3823 |
|
| 3824 |
class Spam: |
| 3825 |
def test(): |
| 3826 |
pass |
| 3827 |
ham = partialmethod(test) |
| 3828 |
|
| 3829 |
with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 3830 |
inspect.signature(Spam.ham) |
| 3831 |
|
| 3832 |
class Spam: |
| 3833 |
def test(it, a, b, *, c) -> 'spam': |
| 3834 |
pass |
| 3835 |
ham = partialmethod(test, c=1) |
| 3836 |
bar = partialmethod(test, functools.Placeholder, 1, c=1) |
| 3837 |
|
| 3838 |
self.assertEqual(self.signature(Spam.ham, eval_str=False), |
| 3839 |
((('it', ..., ..., 'positional_or_keyword'), |
| 3840 |
('a', ..., ..., 'positional_or_keyword'), |
| 3841 |
('b', ..., ..., 'positional_or_keyword'), |
| 3842 |
('c', 1, ..., 'keyword_only')), |
| 3843 |
'spam')) |
| 3844 |
|
| 3845 |
self.assertEqual(self.signature(Spam().ham, eval_str=False), |
| 3846 |
((('a', ..., ..., 'positional_or_keyword'), |
| 3847 |
('b', ..., ..., 'positional_or_keyword'), |
| 3848 |
('c', 1, ..., 'keyword_only')), |
| 3849 |
'spam')) |
| 3850 |
|
| 3851 |
# With Placeholder |
| 3852 |
self.assertEqual(self.signature(Spam.bar, eval_str=False), |
| 3853 |
((('it', ..., ..., 'positional_only'), |
| 3854 |
('a', ..., ..., 'positional_only'), |
| 3855 |
('c', 1, ..., 'keyword_only')), |
| 3856 |
'spam')) |
| 3857 |
self.assertEqual(self.signature(Spam().bar, eval_str=False), |
| 3858 |
((('a', ..., ..., 'positional_only'), |
| 3859 |
('c', 1, ..., 'keyword_only')), |
| 3860 |
'spam')) |
| 3861 |
|
| 3862 |
class Spam: |
| 3863 |
def test(self: 'anno', x): |
| 3864 |
pass |
| 3865 |
|
| 3866 |
g = partialmethod(test, 1) |
| 3867 |
|
| 3868 |
self.assertEqual(self.signature(Spam.g, eval_str=False), |
| 3869 |
((('self', ..., 'anno', 'positional_or_keyword'),), |
| 3870 |
...)) |
| 3871 |
|
| 3872 |
def test_signature_on_fake_partialmethod(self): |
| 3873 |
def foo(a): pass |
| 3874 |
foo.__partialmethod__ = 'spam' |
| 3875 |
self.assertEqual(str(inspect.signature(foo)), '(a)') |
| 3876 |
|
| 3877 |
def test_signature_on_decorated(self): |
| 3878 |
def decorator(func): |
| 3879 |
@functools.wraps(func) |
| 3880 |
def wrapper(*args, **kwargs) -> int: |
| 3881 |
return func(*args, **kwargs) |
| 3882 |
return wrapper |
| 3883 |
|
| 3884 |
class Foo: |
| 3885 |
@decorator |
| 3886 |
def bar(self, a, b): |
| 3887 |
pass |
| 3888 |
|
| 3889 |
bar = decorator(Foo().bar) |
| 3890 |
|
| 3891 |
self.assertEqual(self.signature(Foo.bar), |
| 3892 |
((('self', ..., ..., "positional_or_keyword"), |
| 3893 |
('a', ..., ..., "positional_or_keyword"), |
| 3894 |
('b', ..., ..., "positional_or_keyword")), |
| 3895 |
...)) |
| 3896 |
|
| 3897 |
self.assertEqual(self.signature(Foo().bar), |
| 3898 |
((('a', ..., ..., "positional_or_keyword"), |
| 3899 |
('b', ..., ..., "positional_or_keyword")), |
| 3900 |
...)) |
| 3901 |
|
| 3902 |
self.assertEqual(self.signature(Foo.bar, follow_wrapped=False), |
| 3903 |
((('args', ..., ..., "var_positional"), |
| 3904 |
('kwargs', ..., ..., "var_keyword")), |
| 3905 |
...)) # functools.wraps will copy __annotations__ |
| 3906 |
# from "func" to "wrapper", hence no |
| 3907 |
# return_annotation |
| 3908 |
|
| 3909 |
self.assertEqual(self.signature(bar), |
| 3910 |
((('a', ..., ..., "positional_or_keyword"), |
| 3911 |
('b', ..., ..., "positional_or_keyword")), |
| 3912 |
...)) |
| 3913 |
|
| 3914 |
# Test that we handle method wrappers correctly |
| 3915 |
def decorator(func): |
| 3916 |
@functools.wraps(func) |
| 3917 |
def wrapper(*args, **kwargs) -> int: |
| 3918 |
return func(42, *args, **kwargs) |
| 3919 |
sig = inspect.signature(func) |
| 3920 |
new_params = tuple(sig.parameters.values())[1:] |
| 3921 |
wrapper.__signature__ = sig.replace(parameters=new_params) |
| 3922 |
return wrapper |
| 3923 |
|
| 3924 |
class Foo: |
| 3925 |
@decorator |
| 3926 |
def __call__(self, a, b): |
| 3927 |
pass |
| 3928 |
|
| 3929 |
self.assertEqual(self.signature(Foo.__call__), |
| 3930 |
((('a', ..., ..., "positional_or_keyword"), |
| 3931 |
('b', ..., ..., "positional_or_keyword")), |
| 3932 |
...)) |
| 3933 |
|
| 3934 |
self.assertEqual(self.signature(Foo().__call__), |
| 3935 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3936 |
...)) |
| 3937 |
|
| 3938 |
# Test we handle __signature__ partway down the wrapper stack |
| 3939 |
def wrapped_foo_call(): |
| 3940 |
pass |
| 3941 |
wrapped_foo_call.__wrapped__ = Foo.__call__ |
| 3942 |
|
| 3943 |
self.assertEqual(self.signature(wrapped_foo_call), |
| 3944 |
((('a', ..., ..., "positional_or_keyword"), |
| 3945 |
('b', ..., ..., "positional_or_keyword")), |
| 3946 |
...)) |
| 3947 |
|
| 3948 |
def test_signature_on_class(self): |
| 3949 |
class C: |
| 3950 |
def __init__(self, a): |
| 3951 |
pass |
| 3952 |
|
| 3953 |
self.assertEqual(self.signature(C), |
| 3954 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3955 |
...)) |
| 3956 |
|
| 3957 |
class CM(type): |
| 3958 |
def __call__(cls, a): |
| 3959 |
pass |
| 3960 |
class C(metaclass=CM): |
| 3961 |
def __init__(self, b): |
| 3962 |
pass |
| 3963 |
|
| 3964 |
self.assertEqual(self.signature(C), |
| 3965 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3966 |
...)) |
| 3967 |
|
| 3968 |
with self.subTest('classmethod'): |
| 3969 |
class CM(type): |
| 3970 |
@classmethod |
| 3971 |
def __call__(cls, a): |
| 3972 |
return a |
| 3973 |
class C(metaclass=CM): |
| 3974 |
def __init__(self, b): |
| 3975 |
pass |
| 3976 |
|
| 3977 |
self.assertEqual(C(1), 1) |
| 3978 |
self.assertEqual(self.signature(C), |
| 3979 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3980 |
...)) |
| 3981 |
|
| 3982 |
with self.subTest('staticmethod'): |
| 3983 |
class CM(type): |
| 3984 |
@staticmethod |
| 3985 |
def __call__(a): |
| 3986 |
return a |
| 3987 |
class C(metaclass=CM): |
| 3988 |
def __init__(self, b): |
| 3989 |
pass |
| 3990 |
|
| 3991 |
self.assertEqual(C(1), 1) |
| 3992 |
self.assertEqual(self.signature(C), |
| 3993 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3994 |
...)) |
| 3995 |
|
| 3996 |
with self.subTest('MethodType'): |
| 3997 |
class A: |
| 3998 |
def call(self, a): |
| 3999 |
return a |
| 4000 |
class CM(type): |
| 4001 |
__call__ = A().call |
| 4002 |
class C(metaclass=CM): |
| 4003 |
def __init__(self, b): |
| 4004 |
pass |
| 4005 |
|
| 4006 |
self.assertEqual(C(1), 1) |
| 4007 |
self.assertEqual(self.signature(C), |
| 4008 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4009 |
...)) |
| 4010 |
|
| 4011 |
with self.subTest('partial'): |
| 4012 |
class CM(type): |
| 4013 |
__call__ = functools.partial(lambda x, a, b: (x, a, b), 2) |
| 4014 |
class C(metaclass=CM): |
| 4015 |
def __init__(self, c): |
| 4016 |
pass |
| 4017 |
|
| 4018 |
self.assertEqual(C(1), (2, C, 1)) |
| 4019 |
self.assertEqual(self.signature(C), |
| 4020 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4021 |
...)) |
| 4022 |
|
| 4023 |
with self.subTest('partialmethod'): |
| 4024 |
class CM(type): |
| 4025 |
__call__ = functools.partialmethod(lambda self, x, a: (x, a), 2) |
| 4026 |
class C(metaclass=CM): |
| 4027 |
def __init__(self, b): |
| 4028 |
pass |
| 4029 |
|
| 4030 |
self.assertEqual(C(1), (2, 1)) |
| 4031 |
self.assertEqual(self.signature(C), |
| 4032 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4033 |
...)) |
| 4034 |
|
| 4035 |
with self.subTest('BuiltinMethodType'): |
| 4036 |
class CM(type): |
| 4037 |
__call__ = ':'.join |
| 4038 |
class C(metaclass=CM): |
| 4039 |
def __init__(self, b): |
| 4040 |
pass |
| 4041 |
|
| 4042 |
self.assertEqual(C(['a', 'bc']), 'a:bc') |
| 4043 |
# BUG: Returns '<Signature (b)>' |
| 4044 |
with self.assertRaises(AssertionError): |
| 4045 |
self.assertEqual(self.signature(C), self.signature(''.join)) |
| 4046 |
|
| 4047 |
with self.subTest('MethodWrapperType'): |
| 4048 |
class CM(type): |
| 4049 |
__call__ = (2).__pow__ |
| 4050 |
class C(metaclass=CM): |
| 4051 |
def __init__(self, b): |
| 4052 |
pass |
| 4053 |
|
| 4054 |
self.assertEqual(C(3), 8) |
| 4055 |
self.assertEqual(C(3, 7), 1) |
| 4056 |
if not support.MISSING_C_DOCSTRINGS: |
| 4057 |
# BUG: Returns '<Signature (b)>' |
| 4058 |
with self.assertRaises(AssertionError): |
| 4059 |
self.assertEqual(self.signature(C), self.signature((0).__pow__)) |
| 4060 |
|
| 4061 |
class CM(type): |
| 4062 |
def __new__(mcls, name, bases, dct, *, foo=1): |
| 4063 |
return super().__new__(mcls, name, bases, dct) |
| 4064 |
class C(metaclass=CM): |
| 4065 |
def __init__(self, b): |
| 4066 |
pass |
| 4067 |
|
| 4068 |
self.assertEqual(self.signature(C), |
| 4069 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4070 |
...)) |
| 4071 |
|
| 4072 |
self.assertEqual(self.signature(CM), |
| 4073 |
((('name', ..., ..., "positional_or_keyword"), |
| 4074 |
('bases', ..., ..., "positional_or_keyword"), |
| 4075 |
('dct', ..., ..., "positional_or_keyword"), |
| 4076 |
('foo', 1, ..., "keyword_only")), |
| 4077 |
...)) |
| 4078 |
|
| 4079 |
class CMM(type): |
| 4080 |
def __new__(mcls, name, bases, dct, *, foo=1): |
| 4081 |
return super().__new__(mcls, name, bases, dct) |
| 4082 |
def __call__(cls, nm, bs, dt): |
| 4083 |
return type(nm, bs, dt) |
| 4084 |
class CM(type, metaclass=CMM): |
| 4085 |
def __new__(mcls, name, bases, dct, *, bar=2): |
| 4086 |
return super().__new__(mcls, name, bases, dct) |
| 4087 |
class C(metaclass=CM): |
| 4088 |
def __init__(self, b): |
| 4089 |
pass |
| 4090 |
|
| 4091 |
self.assertEqual(self.signature(CMM), |
| 4092 |
((('name', ..., ..., "positional_or_keyword"), |
| 4093 |
('bases', ..., ..., "positional_or_keyword"), |
| 4094 |
('dct', ..., ..., "positional_or_keyword"), |
| 4095 |
('foo', 1, ..., "keyword_only")), |
| 4096 |
...)) |
| 4097 |
|
| 4098 |
self.assertEqual(self.signature(CM), |
| 4099 |
((('nm', ..., ..., "positional_or_keyword"), |
| 4100 |
('bs', ..., ..., "positional_or_keyword"), |
| 4101 |
('dt', ..., ..., "positional_or_keyword")), |
| 4102 |
...)) |
| 4103 |
|
| 4104 |
self.assertEqual(self.signature(C), |
| 4105 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4106 |
...)) |
| 4107 |
|
| 4108 |
class CM(type): |
| 4109 |
def __init__(cls, name, bases, dct, *, bar=2): |
| 4110 |
return super().__init__(name, bases, dct) |
| 4111 |
class C(metaclass=CM): |
| 4112 |
def __init__(self, b): |
| 4113 |
pass |
| 4114 |
|
| 4115 |
self.assertEqual(self.signature(CM), |
| 4116 |
((('name', ..., ..., "positional_or_keyword"), |
| 4117 |
('bases', ..., ..., "positional_or_keyword"), |
| 4118 |
('dct', ..., ..., "positional_or_keyword"), |
| 4119 |
('bar', 2, ..., "keyword_only")), |
| 4120 |
...)) |
| 4121 |
|
| 4122 |
def test_signature_on_class_with_wrapped_metaclass_call(self): |
| 4123 |
class CM(type): |
| 4124 |
@identity_wrapper |
| 4125 |
def __call__(cls, a): |
| 4126 |
pass |
| 4127 |
class C(metaclass=CM): |
| 4128 |
def __init__(self, b): |
| 4129 |
pass |
| 4130 |
|
| 4131 |
self.assertEqual(self.signature(C), |
| 4132 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4133 |
...)) |
| 4134 |
|
| 4135 |
with self.subTest('classmethod'): |
| 4136 |
class CM(type): |
| 4137 |
@classmethod |
| 4138 |
@identity_wrapper |
| 4139 |
def __call__(cls, a): |
| 4140 |
return a |
| 4141 |
class C(metaclass=CM): |
| 4142 |
def __init__(self, b): |
| 4143 |
pass |
| 4144 |
|
| 4145 |
self.assertEqual(C(1), 1) |
| 4146 |
self.assertEqual(self.signature(C), |
| 4147 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4148 |
...)) |
| 4149 |
|
| 4150 |
with self.subTest('staticmethod'): |
| 4151 |
class CM(type): |
| 4152 |
@staticmethod |
| 4153 |
@identity_wrapper |
| 4154 |
def __call__(a): |
| 4155 |
return a |
| 4156 |
class C(metaclass=CM): |
| 4157 |
def __init__(self, b): |
| 4158 |
pass |
| 4159 |
|
| 4160 |
self.assertEqual(C(1), 1) |
| 4161 |
self.assertEqual(self.signature(C), |
| 4162 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4163 |
...)) |
| 4164 |
|
| 4165 |
with self.subTest('MethodType'): |
| 4166 |
class A: |
| 4167 |
@identity_wrapper |
| 4168 |
def call(self, a): |
| 4169 |
return a |
| 4170 |
class CM(type): |
| 4171 |
__call__ = A().call |
| 4172 |
class C(metaclass=CM): |
| 4173 |
def __init__(self, b): |
| 4174 |
pass |
| 4175 |
|
| 4176 |
self.assertEqual(C(1), 1) |
| 4177 |
self.assertEqual(self.signature(C), |
| 4178 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4179 |
...)) |
| 4180 |
|
| 4181 |
with self.subTest('descriptor'): |
| 4182 |
class CM(type): |
| 4183 |
@custom_descriptor |
| 4184 |
@identity_wrapper |
| 4185 |
def __call__(self, a): |
| 4186 |
return a |
| 4187 |
class C(metaclass=CM): |
| 4188 |
def __init__(self, b): |
| 4189 |
pass |
| 4190 |
|
| 4191 |
self.assertEqual(C(1), 1) |
| 4192 |
self.assertEqual(self.signature(C), |
| 4193 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4194 |
...)) |
| 4195 |
self.assertEqual(self.signature(C.__call__), |
| 4196 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4197 |
...)) |
| 4198 |
|
| 4199 |
self.assertEqual(self.signature(C, follow_wrapped=False), |
| 4200 |
varargs_signature) |
| 4201 |
self.assertEqual(self.signature(C.__call__, follow_wrapped=False), |
| 4202 |
varargs_signature) |
| 4203 |
|
| 4204 |
def test_signature_on_class_with_wrapped_init(self): |
| 4205 |
class C: |
| 4206 |
@identity_wrapper |
| 4207 |
def __init__(self, b): |
| 4208 |
pass |
| 4209 |
|
| 4210 |
C(1) # does not raise |
| 4211 |
self.assertEqual(self.signature(C), |
| 4212 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4213 |
...)) |
| 4214 |
|
| 4215 |
with self.subTest('classmethod'): |
| 4216 |
class C: |
| 4217 |
@classmethod |
| 4218 |
@identity_wrapper |
| 4219 |
def __init__(cls, b): |
| 4220 |
pass |
| 4221 |
|
| 4222 |
C(1) # does not raise |
| 4223 |
self.assertEqual(self.signature(C), |
| 4224 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4225 |
...)) |
| 4226 |
|
| 4227 |
with self.subTest('staticmethod'): |
| 4228 |
class C: |
| 4229 |
@staticmethod |
| 4230 |
@identity_wrapper |
| 4231 |
def __init__(b): |
| 4232 |
pass |
| 4233 |
|
| 4234 |
C(1) # does not raise |
| 4235 |
self.assertEqual(self.signature(C), |
| 4236 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4237 |
...)) |
| 4238 |
|
| 4239 |
with self.subTest('MethodType'): |
| 4240 |
class A: |
| 4241 |
@identity_wrapper |
| 4242 |
def call(self, a): |
| 4243 |
pass |
| 4244 |
|
| 4245 |
class C: |
| 4246 |
__init__ = A().call |
| 4247 |
|
| 4248 |
C(1) # does not raise |
| 4249 |
self.assertEqual(self.signature(C), |
| 4250 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4251 |
...)) |
| 4252 |
|
| 4253 |
with self.subTest('partial'): |
| 4254 |
class C: |
| 4255 |
__init__ = functools.partial(identity_wrapper(lambda x, a, b: None), 2) |
| 4256 |
|
| 4257 |
C(1) # does not raise |
| 4258 |
self.assertEqual(self.signature(C), |
| 4259 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4260 |
...)) |
| 4261 |
|
| 4262 |
with self.subTest('partialmethod'): |
| 4263 |
class C: |
| 4264 |
@identity_wrapper |
| 4265 |
def _init(self, x, a): |
| 4266 |
self.a = (x, a) |
| 4267 |
__init__ = functools.partialmethod(_init, 2) |
| 4268 |
|
| 4269 |
self.assertEqual(C(1).a, (2, 1)) |
| 4270 |
self.assertEqual(self.signature(C), |
| 4271 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4272 |
...)) |
| 4273 |
|
| 4274 |
with self.subTest('descriptor'): |
| 4275 |
class C: |
| 4276 |
@custom_descriptor |
| 4277 |
@identity_wrapper |
| 4278 |
def __init__(self, a): |
| 4279 |
pass |
| 4280 |
|
| 4281 |
C(1) # does not raise |
| 4282 |
self.assertEqual(self.signature(C), |
| 4283 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4284 |
...)) |
| 4285 |
self.assertEqual(self.signature(C.__init__), |
| 4286 |
((('self', ..., ..., "positional_or_keyword"), |
| 4287 |
('a', ..., ..., "positional_or_keyword")), |
| 4288 |
...)) |
| 4289 |
|
| 4290 |
self.assertEqual(self.signature(C, follow_wrapped=False), |
| 4291 |
varargs_signature) |
| 4292 |
if support.MISSING_C_DOCSTRINGS: |
| 4293 |
self.assertRaisesRegex( |
| 4294 |
ValueError, "no signature found", |
| 4295 |
self.signature, C.__new__, follow_wrapped=False, |
| 4296 |
) |
| 4297 |
else: |
| 4298 |
self.assertEqual(self.signature(C.__new__, follow_wrapped=False), |
| 4299 |
varargs_signature) |
| 4300 |
|
| 4301 |
def test_signature_on_class_with_wrapped_new(self): |
| 4302 |
with self.subTest('FunctionType'): |
| 4303 |
class C: |
| 4304 |
@identity_wrapper |
| 4305 |
def __new__(cls, a): |
| 4306 |
return a |
| 4307 |
|
| 4308 |
self.assertEqual(C(1), 1) |
| 4309 |
self.assertEqual(self.signature(C), |
| 4310 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4311 |
...)) |
| 4312 |
|
| 4313 |
with self.subTest('classmethod'): |
| 4314 |
class C: |
| 4315 |
@classmethod |
| 4316 |
@identity_wrapper |
| 4317 |
def __new__(cls, cls2, a): |
| 4318 |
return a |
| 4319 |
|
| 4320 |
self.assertEqual(C(1), 1) |
| 4321 |
self.assertEqual(self.signature(C), |
| 4322 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4323 |
...)) |
| 4324 |
|
| 4325 |
with self.subTest('staticmethod'): |
| 4326 |
class C: |
| 4327 |
@staticmethod |
| 4328 |
@identity_wrapper |
| 4329 |
def __new__(cls, a): |
| 4330 |
return a |
| 4331 |
|
| 4332 |
self.assertEqual(C(1), 1) |
| 4333 |
self.assertEqual(self.signature(C), |
| 4334 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4335 |
...)) |
| 4336 |
|
| 4337 |
with self.subTest('MethodType'): |
| 4338 |
class A: |
| 4339 |
@identity_wrapper |
| 4340 |
def call(self, cls, a): |
| 4341 |
return a |
| 4342 |
class C: |
| 4343 |
__new__ = A().call |
| 4344 |
|
| 4345 |
self.assertEqual(C(1), 1) |
| 4346 |
self.assertEqual(self.signature(C), |
| 4347 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4348 |
...)) |
| 4349 |
|
| 4350 |
with self.subTest('partial'): |
| 4351 |
class C: |
| 4352 |
__new__ = functools.partial(identity_wrapper(lambda x, cls, a: (x, a)), 2) |
| 4353 |
|
| 4354 |
self.assertEqual(C(1), (2, 1)) |
| 4355 |
self.assertEqual(self.signature(C), |
| 4356 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4357 |
...)) |
| 4358 |
|
| 4359 |
with self.subTest('partialmethod'): |
| 4360 |
class C: |
| 4361 |
__new__ = functools.partialmethod(identity_wrapper(lambda cls, x, a: (x, a)), 2) |
| 4362 |
|
| 4363 |
self.assertEqual(C(1), (2, 1)) |
| 4364 |
self.assertEqual(self.signature(C), |
| 4365 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4366 |
...)) |
| 4367 |
|
| 4368 |
with self.subTest('descriptor'): |
| 4369 |
class C: |
| 4370 |
@custom_descriptor |
| 4371 |
@identity_wrapper |
| 4372 |
def __new__(cls, a): |
| 4373 |
return a |
| 4374 |
|
| 4375 |
self.assertEqual(C(1), 1) |
| 4376 |
self.assertEqual(self.signature(C), |
| 4377 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4378 |
...)) |
| 4379 |
self.assertEqual(self.signature(C.__new__), |
| 4380 |
((('cls', ..., ..., "positional_or_keyword"), |
| 4381 |
('a', ..., ..., "positional_or_keyword")), |
| 4382 |
...)) |
| 4383 |
|
| 4384 |
self.assertEqual(self.signature(C, follow_wrapped=False), |
| 4385 |
varargs_signature) |
| 4386 |
self.assertEqual(self.signature(C.__new__, follow_wrapped=False), |
| 4387 |
varargs_signature) |
| 4388 |
|
| 4389 |
def test_signature_on_class_with_init(self): |
| 4390 |
class C: |
| 4391 |
def __init__(self, b): |
| 4392 |
pass |
| 4393 |
|
| 4394 |
C(1) # does not raise |
| 4395 |
self.assertEqual(self.signature(C), |
| 4396 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4397 |
...)) |
| 4398 |
|
| 4399 |
with self.subTest('classmethod'): |
| 4400 |
class C: |
| 4401 |
@classmethod |
| 4402 |
def __init__(cls, b): |
| 4403 |
pass |
| 4404 |
|
| 4405 |
C(1) # does not raise |
| 4406 |
self.assertEqual(self.signature(C), |
| 4407 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4408 |
...)) |
| 4409 |
|
| 4410 |
with self.subTest('staticmethod'): |
| 4411 |
class C: |
| 4412 |
@staticmethod |
| 4413 |
def __init__(b): |
| 4414 |
pass |
| 4415 |
|
| 4416 |
C(1) # does not raise |
| 4417 |
self.assertEqual(self.signature(C), |
| 4418 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4419 |
...)) |
| 4420 |
|
| 4421 |
with self.subTest('MethodType'): |
| 4422 |
class A: |
| 4423 |
def call(self, a): |
| 4424 |
pass |
| 4425 |
class C: |
| 4426 |
__init__ = A().call |
| 4427 |
|
| 4428 |
C(1) # does not raise |
| 4429 |
self.assertEqual(self.signature(C), |
| 4430 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4431 |
...)) |
| 4432 |
|
| 4433 |
with self.subTest('partial'): |
| 4434 |
class C: |
| 4435 |
__init__ = functools.partial(lambda x, a, b: None, 2) |
| 4436 |
|
| 4437 |
C(1) # does not raise |
| 4438 |
self.assertEqual(self.signature(C), |
| 4439 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4440 |
...)) |
| 4441 |
|
| 4442 |
with self.subTest('partialmethod'): |
| 4443 |
class C: |
| 4444 |
def _init(self, x, a): |
| 4445 |
self.a = (x, a) |
| 4446 |
__init__ = functools.partialmethod(_init, 2) |
| 4447 |
|
| 4448 |
self.assertEqual(C(1).a, (2, 1)) |
| 4449 |
self.assertEqual(self.signature(C), |
| 4450 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4451 |
...)) |
| 4452 |
|
| 4453 |
def test_signature_on_class_with_new(self): |
| 4454 |
with self.subTest('FunctionType'): |
| 4455 |
class C: |
| 4456 |
def __new__(cls, a): |
| 4457 |
return a |
| 4458 |
|
| 4459 |
self.assertEqual(C(1), 1) |
| 4460 |
self.assertEqual(self.signature(C), |
| 4461 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4462 |
...)) |
| 4463 |
|
| 4464 |
with self.subTest('classmethod'): |
| 4465 |
class C: |
| 4466 |
@classmethod |
| 4467 |
def __new__(cls, cls2, a): |
| 4468 |
return a |
| 4469 |
|
| 4470 |
self.assertEqual(C(1), 1) |
| 4471 |
self.assertEqual(self.signature(C), |
| 4472 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4473 |
...)) |
| 4474 |
|
| 4475 |
with self.subTest('staticmethod'): |
| 4476 |
class C: |
| 4477 |
@staticmethod |
| 4478 |
def __new__(cls, a): |
| 4479 |
return a |
| 4480 |
|
| 4481 |
self.assertEqual(C(1), 1) |
| 4482 |
self.assertEqual(self.signature(C), |
| 4483 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4484 |
...)) |
| 4485 |
|
| 4486 |
with self.subTest('MethodType'): |
| 4487 |
class A: |
| 4488 |
def call(self, cls, a): |
| 4489 |
return a |
| 4490 |
class C: |
| 4491 |
__new__ = A().call |
| 4492 |
|
| 4493 |
self.assertEqual(C(1), 1) |
| 4494 |
self.assertEqual(self.signature(C), |
| 4495 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4496 |
...)) |
| 4497 |
|
| 4498 |
with self.subTest('partial'): |
| 4499 |
class C: |
| 4500 |
__new__ = functools.partial(lambda x, cls, a: (x, a), 2) |
| 4501 |
|
| 4502 |
self.assertEqual(C(1), (2, 1)) |
| 4503 |
self.assertEqual(self.signature(C), |
| 4504 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4505 |
...)) |
| 4506 |
|
| 4507 |
with self.subTest('partialmethod'): |
| 4508 |
class C: |
| 4509 |
__new__ = functools.partialmethod(lambda cls, x, a: (x, a), 2) |
| 4510 |
|
| 4511 |
self.assertEqual(C(1), (2, 1)) |
| 4512 |
self.assertEqual(self.signature(C), |
| 4513 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4514 |
...)) |
| 4515 |
|
| 4516 |
with self.subTest('BuiltinMethodType'): |
| 4517 |
class C: |
| 4518 |
__new__ = str.__subclasscheck__ |
| 4519 |
|
| 4520 |
self.assertEqual(C(), False) |
| 4521 |
# TODO: Support BuiltinMethodType |
| 4522 |
# self.assertEqual(self.signature(C), ((), ...)) |
| 4523 |
self.assertRaises(ValueError, self.signature, C) |
| 4524 |
|
| 4525 |
with self.subTest('MethodWrapperType'): |
| 4526 |
class C: |
| 4527 |
__new__ = type.__or__.__get__(int, type) |
| 4528 |
|
| 4529 |
self.assertEqual(C(), C | int) |
| 4530 |
# TODO: Support MethodWrapperType |
| 4531 |
# self.assertEqual(self.signature(C), ((), ...)) |
| 4532 |
self.assertRaises(ValueError, self.signature, C) |
| 4533 |
|
| 4534 |
# TODO: Test ClassMethodDescriptorType |
| 4535 |
|
| 4536 |
with self.subTest('MethodDescriptorType'): |
| 4537 |
class C: |
| 4538 |
__new__ = type.__dict__['__subclasscheck__'] |
| 4539 |
|
| 4540 |
self.assertEqual(C(C), True) |
| 4541 |
self.assertEqual(self.signature(C), self.signature(C.__subclasscheck__)) |
| 4542 |
|
| 4543 |
with self.subTest('WrapperDescriptorType'): |
| 4544 |
class C: |
| 4545 |
__new__ = type.__or__ |
| 4546 |
|
| 4547 |
self.assertEqual(C(int), C | int) |
| 4548 |
# TODO: Support WrapperDescriptorType |
| 4549 |
# self.assertEqual(self.signature(C), self.signature(C.__or__)) |
| 4550 |
self.assertRaises(ValueError, self.signature, C) |
| 4551 |
|
| 4552 |
def test_signature_on_subclass(self): |
| 4553 |
class A: |
| 4554 |
def __new__(cls, a=1, *args, **kwargs): |
| 4555 |
return object.__new__(cls) |
| 4556 |
class B(A): |
| 4557 |
def __init__(self, b): |
| 4558 |
pass |
| 4559 |
class C(A): |
| 4560 |
def __new__(cls, a=1, b=2, *args, **kwargs): |
| 4561 |
return object.__new__(cls) |
| 4562 |
class D(A): |
| 4563 |
pass |
| 4564 |
|
| 4565 |
self.assertEqual(self.signature(B), |
| 4566 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4567 |
...)) |
| 4568 |
self.assertEqual(self.signature(C), |
| 4569 |
((('a', 1, ..., 'positional_or_keyword'), |
| 4570 |
('b', 2, ..., 'positional_or_keyword'), |
| 4571 |
('args', ..., ..., 'var_positional'), |
| 4572 |
('kwargs', ..., ..., 'var_keyword')), |
| 4573 |
...)) |
| 4574 |
self.assertEqual(self.signature(D), |
| 4575 |
((('a', 1, ..., 'positional_or_keyword'), |
| 4576 |
('args', ..., ..., 'var_positional'), |
| 4577 |
('kwargs', ..., ..., 'var_keyword')), |
| 4578 |
...)) |
| 4579 |
|
| 4580 |
def test_signature_on_generic_subclass(self): |
| 4581 |
from typing import Generic, TypeVar |
| 4582 |
|
| 4583 |
T = TypeVar('T') |
| 4584 |
|
| 4585 |
class A(Generic[T]): |
| 4586 |
def __init__(self, *, a: int) -> None: |
| 4587 |
pass |
| 4588 |
|
| 4589 |
self.assertEqual(self.signature(A), |
| 4590 |
((('a', ..., int, 'keyword_only'),), |
| 4591 |
None)) |
| 4592 |
|
| 4593 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 4594 |
"Signature information for builtins requires docstrings") |
| 4595 |
def test_signature_on_class_without_init(self): |
| 4596 |
# Test classes without user-defined __init__ or __new__ |
| 4597 |
class C: pass |
| 4598 |
self.assertEqual(str(inspect.signature(C)), '()') |
| 4599 |
class D(C): pass |
| 4600 |
self.assertEqual(str(inspect.signature(D)), '()') |
| 4601 |
|
| 4602 |
# Test meta-classes without user-defined __init__ or __new__ |
| 4603 |
class C(type): pass |
| 4604 |
class D(C): pass |
| 4605 |
self.assertEqual(C('A', (), {}).__name__, 'A') |
| 4606 |
# TODO: Support type. |
| 4607 |
with self.assertRaisesRegex(ValueError, "callable.*is not supported"): |
| 4608 |
self.assertEqual(inspect.signature(C), None) |
| 4609 |
self.assertEqual(D('A', (), {}).__name__, 'A') |
| 4610 |
with self.assertRaisesRegex(ValueError, "callable.*is not supported"): |
| 4611 |
self.assertEqual(inspect.signature(D), None) |
| 4612 |
|
| 4613 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 4614 |
"Signature information for builtins requires docstrings") |
| 4615 |
def test_signature_on_builtin_class(self): |
| 4616 |
expected = ('(file, protocol=None, fix_imports=True, ' |
| 4617 |
'buffer_callback=None)') |
| 4618 |
self.assertEqual(str(inspect.signature(_pickle.Pickler)), expected) |
| 4619 |
|
| 4620 |
class P(_pickle.Pickler): pass |
| 4621 |
class EmptyTrait: pass |
| 4622 |
class P2(EmptyTrait, P): pass |
| 4623 |
self.assertEqual(str(inspect.signature(P)), expected) |
| 4624 |
self.assertEqual(str(inspect.signature(P2)), expected) |
| 4625 |
|
| 4626 |
class P3(P2): |
| 4627 |
def __init__(self, spam): |
| 4628 |
pass |
| 4629 |
self.assertEqual(str(inspect.signature(P3)), '(spam)') |
| 4630 |
|
| 4631 |
class MetaP(type): |
| 4632 |
def __call__(cls, foo, bar): |
| 4633 |
pass |
| 4634 |
class P4(P2, metaclass=MetaP): |
| 4635 |
pass |
| 4636 |
self.assertEqual(str(inspect.signature(P4)), '(foo, bar)') |
| 4637 |
|
| 4638 |
def test_signature_on_callable_objects(self): |
| 4639 |
class Foo: |
| 4640 |
def __call__(self, a): |
| 4641 |
pass |
| 4642 |
|
| 4643 |
self.assertEqual(self.signature(Foo()), |
| 4644 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4645 |
...)) |
| 4646 |
|
| 4647 |
class Spam: |
| 4648 |
pass |
| 4649 |
with self.assertRaisesRegex(TypeError, "is not a callable object"): |
| 4650 |
inspect.signature(Spam()) |
| 4651 |
|
| 4652 |
class Bar(Spam, Foo): |
| 4653 |
pass |
| 4654 |
|
| 4655 |
self.assertEqual(self.signature(Bar()), |
| 4656 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4657 |
...)) |
| 4658 |
|
| 4659 |
with self.subTest('classmethod'): |
| 4660 |
class C: |
| 4661 |
@classmethod |
| 4662 |
def __call__(cls, a): |
| 4663 |
pass |
| 4664 |
|
| 4665 |
self.assertEqual(self.signature(C()), |
| 4666 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4667 |
...)) |
| 4668 |
|
| 4669 |
with self.subTest('staticmethod'): |
| 4670 |
class C: |
| 4671 |
@staticmethod |
| 4672 |
def __call__(a): |
| 4673 |
pass |
| 4674 |
|
| 4675 |
self.assertEqual(self.signature(C()), |
| 4676 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4677 |
...)) |
| 4678 |
|
| 4679 |
with self.subTest('MethodType'): |
| 4680 |
class A: |
| 4681 |
def call(self, a): |
| 4682 |
return a |
| 4683 |
class C: |
| 4684 |
__call__ = A().call |
| 4685 |
|
| 4686 |
self.assertEqual(C()(1), 1) |
| 4687 |
self.assertEqual(self.signature(C()), |
| 4688 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4689 |
...)) |
| 4690 |
|
| 4691 |
with self.subTest('partial'): |
| 4692 |
class C: |
| 4693 |
__call__ = functools.partial(lambda x, a, b: (x, a, b), 2) |
| 4694 |
|
| 4695 |
c = C() |
| 4696 |
self.assertEqual(c(1), (2, c, 1)) |
| 4697 |
self.assertEqual(self.signature(C()), |
| 4698 |
((('b', ..., ..., "positional_or_keyword"),), |
| 4699 |
...)) |
| 4700 |
|
| 4701 |
with self.subTest('partialmethod'): |
| 4702 |
class C: |
| 4703 |
__call__ = functools.partialmethod(lambda self, x, a: (x, a), 2) |
| 4704 |
|
| 4705 |
self.assertEqual(C()(1), (2, 1)) |
| 4706 |
self.assertEqual(self.signature(C()), |
| 4707 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4708 |
...)) |
| 4709 |
|
| 4710 |
with self.subTest('BuiltinMethodType'): |
| 4711 |
class C: |
| 4712 |
__call__ = ':'.join |
| 4713 |
|
| 4714 |
self.assertEqual(C()(['a', 'bc']), 'a:bc') |
| 4715 |
self.assertEqual(self.signature(C()), self.signature(''.join)) |
| 4716 |
|
| 4717 |
with self.subTest('MethodWrapperType'): |
| 4718 |
class C: |
| 4719 |
__call__ = (2).__pow__ |
| 4720 |
|
| 4721 |
self.assertEqual(C()(3), 8) |
| 4722 |
if not support.MISSING_C_DOCSTRINGS: |
| 4723 |
self.assertEqual(self.signature(C()), self.signature((0).__pow__)) |
| 4724 |
|
| 4725 |
with self.subTest('ClassMethodDescriptorType'): |
| 4726 |
class C(dict): |
| 4727 |
__call__ = dict.__dict__['fromkeys'] |
| 4728 |
|
| 4729 |
res = C()([1, 2], 3) |
| 4730 |
self.assertEqual(res, {1: 3, 2: 3}) |
| 4731 |
self.assertEqual(type(res), C) |
| 4732 |
if not support.MISSING_C_DOCSTRINGS: |
| 4733 |
self.assertEqual(self.signature(C()), self.signature(dict.fromkeys)) |
| 4734 |
|
| 4735 |
with self.subTest('MethodDescriptorType'): |
| 4736 |
class C(str): |
| 4737 |
__call__ = str.join |
| 4738 |
|
| 4739 |
self.assertEqual(C(':')(['a', 'bc']), 'a:bc') |
| 4740 |
self.assertEqual(self.signature(C()), self.signature(''.join)) |
| 4741 |
|
| 4742 |
with self.subTest('WrapperDescriptorType'): |
| 4743 |
class C(int): |
| 4744 |
__call__ = int.__pow__ |
| 4745 |
|
| 4746 |
self.assertEqual(C(2)(3), 8) |
| 4747 |
if not support.MISSING_C_DOCSTRINGS: |
| 4748 |
self.assertEqual(self.signature(C()), self.signature((0).__pow__)) |
| 4749 |
|
| 4750 |
with self.subTest('MemberDescriptorType'): |
| 4751 |
class C: |
| 4752 |
__slots__ = '__call__' |
| 4753 |
c = C() |
| 4754 |
c.__call__ = lambda a: a |
| 4755 |
self.assertEqual(c(1), 1) |
| 4756 |
self.assertEqual(self.signature(c), |
| 4757 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4758 |
...)) |
| 4759 |
|
| 4760 |
def test_signature_on_callable_objects_with_text_signature_attr(self): |
| 4761 |
class C: |
| 4762 |
__text_signature__ = '(a, /, b, c=True)' |
| 4763 |
def __call__(self, *args, **kwargs): |
| 4764 |
pass |
| 4765 |
|
| 4766 |
if not support.MISSING_C_DOCSTRINGS: |
| 4767 |
self.assertEqual(self.signature(C), ((), ...)) |
| 4768 |
self.assertEqual(self.signature(C()), |
| 4769 |
((('a', ..., ..., "positional_only"), |
| 4770 |
('b', ..., ..., "positional_or_keyword"), |
| 4771 |
('c', True, ..., "positional_or_keyword"), |
| 4772 |
), |
| 4773 |
...)) |
| 4774 |
|
| 4775 |
c = C() |
| 4776 |
c.__text_signature__ = '(x, y)' |
| 4777 |
self.assertEqual(self.signature(c), |
| 4778 |
((('x', ..., ..., "positional_or_keyword"), |
| 4779 |
('y', ..., ..., "positional_or_keyword"), |
| 4780 |
), |
| 4781 |
...)) |
| 4782 |
|
| 4783 |
def test_signature_on_wrapper(self): |
| 4784 |
class Wrapper: |
| 4785 |
def __call__(self, b): |
| 4786 |
pass |
| 4787 |
wrapper = Wrapper() |
| 4788 |
wrapper.__wrapped__ = lambda a: None |
| 4789 |
self.assertEqual(self.signature(wrapper), |
| 4790 |
((('a', ..., ..., "positional_or_keyword"),), |
| 4791 |
...)) |
| 4792 |
# wrapper loop: |
| 4793 |
wrapper = Wrapper() |
| 4794 |
wrapper.__wrapped__ = wrapper |
| 4795 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 4796 |
self.signature(wrapper) |
| 4797 |
|
| 4798 |
def test_signature_on_lambdas(self): |
| 4799 |
self.assertEqual(self.signature((lambda a=10: a)), |
| 4800 |
((('a', 10, ..., "positional_or_keyword"),), |
| 4801 |
...)) |
| 4802 |
|
| 4803 |
def test_signature_on_mocks(self): |
| 4804 |
# https://github.com/python/cpython/issues/96127 |
| 4805 |
for mock in ( |
| 4806 |
unittest.mock.Mock(), |
| 4807 |
unittest.mock.AsyncMock(), |
| 4808 |
unittest.mock.MagicMock(), |
| 4809 |
): |
| 4810 |
with self.subTest(mock=mock): |
| 4811 |
self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)') |
| 4812 |
|
| 4813 |
def test_signature_on_noncallable_mocks(self): |
| 4814 |
for mock in ( |
| 4815 |
unittest.mock.NonCallableMock(), |
| 4816 |
unittest.mock.NonCallableMagicMock(), |
| 4817 |
): |
| 4818 |
with self.subTest(mock=mock): |
| 4819 |
with self.assertRaises(TypeError): |
| 4820 |
inspect.signature(mock) |
| 4821 |
|
| 4822 |
def test_signature_equality(self): |
| 4823 |
def foo(a, *, b:int) -> float: pass |
| 4824 |
self.assertFalse(inspect.signature(foo) == 42) |
| 4825 |
self.assertTrue(inspect.signature(foo) != 42) |
| 4826 |
self.assertTrue(inspect.signature(foo) == ALWAYS_EQ) |
| 4827 |
self.assertFalse(inspect.signature(foo) != ALWAYS_EQ) |
| 4828 |
|
| 4829 |
def bar(a, *, b:int) -> float: pass |
| 4830 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 4831 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 4832 |
self.assertEqual( |
| 4833 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4834 |
|
| 4835 |
def bar(a, *, b:int) -> int: pass |
| 4836 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 4837 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 4838 |
self.assertNotEqual( |
| 4839 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4840 |
|
| 4841 |
def bar(a, *, b:int): pass |
| 4842 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 4843 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 4844 |
self.assertNotEqual( |
| 4845 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4846 |
|
| 4847 |
def bar(a, *, b:int=42) -> float: pass |
| 4848 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 4849 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 4850 |
self.assertNotEqual( |
| 4851 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4852 |
|
| 4853 |
def bar(a, *, c) -> float: pass |
| 4854 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 4855 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 4856 |
self.assertNotEqual( |
| 4857 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4858 |
|
| 4859 |
def bar(a, b:int) -> float: pass |
| 4860 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 4861 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 4862 |
self.assertNotEqual( |
| 4863 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4864 |
def spam(b:int, a) -> float: pass |
| 4865 |
self.assertFalse(inspect.signature(spam) == inspect.signature(bar)) |
| 4866 |
self.assertTrue(inspect.signature(spam) != inspect.signature(bar)) |
| 4867 |
self.assertNotEqual( |
| 4868 |
hash(inspect.signature(spam)), hash(inspect.signature(bar))) |
| 4869 |
|
| 4870 |
def foo(*, a, b, c): pass |
| 4871 |
def bar(*, c, b, a): pass |
| 4872 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 4873 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 4874 |
self.assertEqual( |
| 4875 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4876 |
|
| 4877 |
def foo(*, a=1, b, c): pass |
| 4878 |
def bar(*, c, b, a=1): pass |
| 4879 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 4880 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 4881 |
self.assertEqual( |
| 4882 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4883 |
|
| 4884 |
def foo(pos, *, a=1, b, c): pass |
| 4885 |
def bar(pos, *, c, b, a=1): pass |
| 4886 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 4887 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 4888 |
self.assertEqual( |
| 4889 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4890 |
|
| 4891 |
def foo(pos, *, a, b, c): pass |
| 4892 |
def bar(pos, *, c, b, a=1): pass |
| 4893 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 4894 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 4895 |
self.assertNotEqual( |
| 4896 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4897 |
|
| 4898 |
def foo(pos, *args, a=42, b, c, **kwargs:int): pass |
| 4899 |
def bar(pos, *args, c, b, a=42, **kwargs:int): pass |
| 4900 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 4901 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 4902 |
self.assertEqual( |
| 4903 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 4904 |
|
| 4905 |
def test_signature_hashable(self): |
| 4906 |
S = inspect.Signature |
| 4907 |
P = inspect.Parameter |
| 4908 |
|
| 4909 |
def foo(a): pass |
| 4910 |
foo_sig = inspect.signature(foo) |
| 4911 |
|
| 4912 |
manual_sig = S(parameters=[P('a', P.POSITIONAL_OR_KEYWORD)]) |
| 4913 |
|
| 4914 |
self.assertEqual(hash(foo_sig), hash(manual_sig)) |
| 4915 |
self.assertNotEqual(hash(foo_sig), |
| 4916 |
hash(manual_sig.replace(return_annotation='spam'))) |
| 4917 |
|
| 4918 |
def bar(a) -> 1: pass |
| 4919 |
self.assertNotEqual(hash(foo_sig), hash(inspect.signature(bar))) |
| 4920 |
|
| 4921 |
def foo(a={}): pass |
| 4922 |
with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 4923 |
hash(inspect.signature(foo)) |
| 4924 |
|
| 4925 |
def foo(a) -> {}: pass |
| 4926 |
with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 4927 |
hash(inspect.signature(foo)) |
| 4928 |
|
| 4929 |
def test_signature_str(self): |
| 4930 |
def foo(a:int=1, *, b, c=None, **kwargs) -> 42: |
| 4931 |
pass |
| 4932 |
self.assertEqual(str(inspect.signature(foo)), |
| 4933 |
'(a: int = 1, *, b, c=None, **kwargs) -> 42') |
| 4934 |
self.assertEqual(str(inspect.signature(foo)), |
| 4935 |
inspect.signature(foo).format()) |
| 4936 |
|
| 4937 |
def foo(a:int=1, *args, b, c=None, **kwargs) -> 42: |
| 4938 |
pass |
| 4939 |
self.assertEqual(str(inspect.signature(foo)), |
| 4940 |
'(a: int = 1, *args, b, c=None, **kwargs) -> 42') |
| 4941 |
self.assertEqual(str(inspect.signature(foo)), |
| 4942 |
inspect.signature(foo).format()) |
| 4943 |
|
| 4944 |
def foo(): |
| 4945 |
pass |
| 4946 |
self.assertEqual(str(inspect.signature(foo)), '()') |
| 4947 |
self.assertEqual(str(inspect.signature(foo)), |
| 4948 |
inspect.signature(foo).format()) |
| 4949 |
|
| 4950 |
def foo(a: list[str]) -> tuple[str, float]: |
| 4951 |
pass |
| 4952 |
self.assertEqual(str(inspect.signature(foo)), |
| 4953 |
'(a: list[str]) -> tuple[str, float]') |
| 4954 |
self.assertEqual(str(inspect.signature(foo)), |
| 4955 |
inspect.signature(foo).format()) |
| 4956 |
|
| 4957 |
from typing import Tuple |
| 4958 |
def foo(a: list[str]) -> Tuple[str, float]: |
| 4959 |
pass |
| 4960 |
self.assertEqual(str(inspect.signature(foo)), |
| 4961 |
'(a: list[str]) -> Tuple[str, float]') |
| 4962 |
self.assertEqual(str(inspect.signature(foo)), |
| 4963 |
inspect.signature(foo).format()) |
| 4964 |
|
| 4965 |
def foo(x: undef): |
| 4966 |
pass |
| 4967 |
sig = inspect.signature(foo, annotation_format=Format.FORWARDREF) |
| 4968 |
self.assertEqual(str(sig), '(x: undef)') |
| 4969 |
|
| 4970 |
def test_signature_str_positional_only(self): |
| 4971 |
P = inspect.Parameter |
| 4972 |
S = inspect.Signature |
| 4973 |
|
| 4974 |
def test(a_po, /, *, b, **kwargs): |
| 4975 |
return a_po, kwargs |
| 4976 |
|
| 4977 |
self.assertEqual(str(inspect.signature(test)), |
| 4978 |
'(a_po, /, *, b, **kwargs)') |
| 4979 |
self.assertEqual(str(inspect.signature(test)), |
| 4980 |
inspect.signature(test).format()) |
| 4981 |
|
| 4982 |
test = S(parameters=[P('foo', P.POSITIONAL_ONLY)]) |
| 4983 |
self.assertEqual(str(test), '(foo, /)') |
| 4984 |
self.assertEqual(str(test), test.format()) |
| 4985 |
|
| 4986 |
test = S(parameters=[P('foo', P.POSITIONAL_ONLY), |
| 4987 |
P('bar', P.VAR_KEYWORD)]) |
| 4988 |
self.assertEqual(str(test), '(foo, /, **bar)') |
| 4989 |
self.assertEqual(str(test), test.format()) |
| 4990 |
|
| 4991 |
test = S(parameters=[P('foo', P.POSITIONAL_ONLY), |
| 4992 |
P('bar', P.VAR_POSITIONAL)]) |
| 4993 |
self.assertEqual(str(test), '(foo, /, *bar)') |
| 4994 |
self.assertEqual(str(test), test.format()) |
| 4995 |
|
| 4996 |
def test_signature_format(self): |
| 4997 |
from typing import Annotated, Literal |
| 4998 |
|
| 4999 |
def func(x: Annotated[int, 'meta'], y: Literal['a', 'b'], z: 'LiteralString'): |
| 5000 |
pass |
| 5001 |
|
| 5002 |
expected_singleline = "(x: Annotated[int, 'meta'], y: Literal['a', 'b'], z: 'LiteralString')" |
| 5003 |
expected_multiline = """( |
| 5004 |
x: Annotated[int, 'meta'], |
| 5005 |
y: Literal['a', 'b'], |
| 5006 |
z: 'LiteralString' |
| 5007 |
)""" |
| 5008 |
self.assertEqual( |
| 5009 |
inspect.signature(func).format(), |
| 5010 |
expected_singleline, |
| 5011 |
) |
| 5012 |
self.assertEqual( |
| 5013 |
inspect.signature(func).format(max_width=None), |
| 5014 |
expected_singleline, |
| 5015 |
) |
| 5016 |
self.assertEqual( |
| 5017 |
inspect.signature(func).format(max_width=len(expected_singleline)), |
| 5018 |
expected_singleline, |
| 5019 |
) |
| 5020 |
self.assertEqual( |
| 5021 |
inspect.signature(func).format(max_width=len(expected_singleline) - 1), |
| 5022 |
expected_multiline, |
| 5023 |
) |
| 5024 |
self.assertEqual( |
| 5025 |
inspect.signature(func).format(max_width=0), |
| 5026 |
expected_multiline, |
| 5027 |
) |
| 5028 |
self.assertEqual( |
| 5029 |
inspect.signature(func).format(max_width=-1), |
| 5030 |
expected_multiline, |
| 5031 |
) |
| 5032 |
|
| 5033 |
def test_signature_format_all_arg_types(self): |
| 5034 |
from typing import Annotated, Literal |
| 5035 |
|
| 5036 |
def func( |
| 5037 |
x: Annotated[int, 'meta'], |
| 5038 |
/, |
| 5039 |
y: Literal['a', 'b'], |
| 5040 |
*, |
| 5041 |
z: 'LiteralString', |
| 5042 |
**kwargs: object, |
| 5043 |
) -> None: |
| 5044 |
pass |
| 5045 |
|
| 5046 |
expected_multiline = """( |
| 5047 |
x: Annotated[int, 'meta'], |
| 5048 |
/, |
| 5049 |
y: Literal['a', 'b'], |
| 5050 |
*, |
| 5051 |
z: 'LiteralString', |
| 5052 |
**kwargs: object |
| 5053 |
) -> None""" |
| 5054 |
self.assertEqual( |
| 5055 |
inspect.signature(func).format(max_width=-1), |
| 5056 |
expected_multiline, |
| 5057 |
) |
| 5058 |
|
| 5059 |
def test_signature_format_unquote(self): |
| 5060 |
def func(x: 'int') -> 'str': ... |
| 5061 |
|
| 5062 |
self.assertEqual( |
| 5063 |
inspect.signature(func).format(), |
| 5064 |
"(x: 'int') -> 'str'" |
| 5065 |
) |
| 5066 |
self.assertEqual( |
| 5067 |
inspect.signature(func).format(quote_annotation_strings=False), |
| 5068 |
"(x: int) -> str" |
| 5069 |
) |
| 5070 |
|
| 5071 |
def test_signature_replace_parameters(self): |
| 5072 |
def test(a, b) -> 42: |
| 5073 |
pass |
| 5074 |
|
| 5075 |
sig = inspect.signature(test) |
| 5076 |
parameters = sig.parameters |
| 5077 |
sig = sig.replace(parameters=list(parameters.values())[1:]) |
| 5078 |
self.assertEqual(list(sig.parameters), ['b']) |
| 5079 |
self.assertEqual(sig.parameters['b'], parameters['b']) |
| 5080 |
self.assertEqual(sig.return_annotation, 42) |
| 5081 |
sig = sig.replace(parameters=()) |
| 5082 |
self.assertEqual(dict(sig.parameters), {}) |
| 5083 |
|
| 5084 |
sig = inspect.signature(test) |
| 5085 |
parameters = sig.parameters |
| 5086 |
sig = copy.replace(sig, parameters=list(parameters.values())[1:]) |
| 5087 |
self.assertEqual(list(sig.parameters), ['b']) |
| 5088 |
self.assertEqual(sig.parameters['b'], parameters['b']) |
| 5089 |
self.assertEqual(sig.return_annotation, 42) |
| 5090 |
sig = copy.replace(sig, parameters=()) |
| 5091 |
self.assertEqual(dict(sig.parameters), {}) |
| 5092 |
|
| 5093 |
def test_signature_replace_anno(self): |
| 5094 |
def test() -> 42: |
| 5095 |
pass |
| 5096 |
|
| 5097 |
sig = inspect.signature(test) |
| 5098 |
sig = sig.replace(return_annotation=None) |
| 5099 |
self.assertIs(sig.return_annotation, None) |
| 5100 |
sig = sig.replace(return_annotation=sig.empty) |
| 5101 |
self.assertIs(sig.return_annotation, sig.empty) |
| 5102 |
sig = sig.replace(return_annotation=42) |
| 5103 |
self.assertEqual(sig.return_annotation, 42) |
| 5104 |
self.assertEqual(sig, inspect.signature(test)) |
| 5105 |
|
| 5106 |
sig = inspect.signature(test) |
| 5107 |
sig = copy.replace(sig, return_annotation=None) |
| 5108 |
self.assertIs(sig.return_annotation, None) |
| 5109 |
sig = copy.replace(sig, return_annotation=sig.empty) |
| 5110 |
self.assertIs(sig.return_annotation, sig.empty) |
| 5111 |
sig = copy.replace(sig, return_annotation=42) |
| 5112 |
self.assertEqual(sig.return_annotation, 42) |
| 5113 |
self.assertEqual(sig, inspect.signature(test)) |
| 5114 |
|
| 5115 |
def test_signature_replaced(self): |
| 5116 |
def test(): |
| 5117 |
pass |
| 5118 |
|
| 5119 |
spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) |
| 5120 |
sig = test.__signature__ = inspect.Signature(parameters=(spam_param,)) |
| 5121 |
self.assertEqual(sig, inspect.signature(test)) |
| 5122 |
|
| 5123 |
def test_signature_on_mangled_parameters(self): |
| 5124 |
class Spam: |
| 5125 |
def foo(self, __p1:1=2, *, __p2:2=3): |
| 5126 |
pass |
| 5127 |
class Ham(Spam): |
| 5128 |
pass |
| 5129 |
|
| 5130 |
self.assertEqual(self.signature(Spam.foo), |
| 5131 |
((('self', ..., ..., "positional_or_keyword"), |
| 5132 |
('_Spam__p1', 2, 1, "positional_or_keyword"), |
| 5133 |
('_Spam__p2', 3, 2, "keyword_only")), |
| 5134 |
...)) |
| 5135 |
|
| 5136 |
self.assertEqual(self.signature(Spam.foo), |
| 5137 |
self.signature(Ham.foo)) |
| 5138 |
|
| 5139 |
def test_signature_from_callable_python_obj(self): |
| 5140 |
class MySignature(inspect.Signature): pass |
| 5141 |
def foo(a, *, b:1): pass |
| 5142 |
foo_sig = MySignature.from_callable(foo) |
| 5143 |
self.assertIsInstance(foo_sig, MySignature) |
| 5144 |
|
| 5145 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 5146 |
"Signature information for builtins requires docstrings") |
| 5147 |
def test_signature_from_callable_class(self): |
| 5148 |
# A regression test for a class inheriting its signature from `object`. |
| 5149 |
class MySignature(inspect.Signature): pass |
| 5150 |
class foo: pass |
| 5151 |
foo_sig = MySignature.from_callable(foo) |
| 5152 |
self.assertIsInstance(foo_sig, MySignature) |
| 5153 |
|
| 5154 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 5155 |
"Signature information for builtins requires docstrings") |
| 5156 |
def test_signature_from_callable_builtin_obj(self): |
| 5157 |
class MySignature(inspect.Signature): pass |
| 5158 |
sig = MySignature.from_callable(_pickle.Pickler) |
| 5159 |
self.assertIsInstance(sig, MySignature) |
| 5160 |
|
| 5161 |
def test_signature_definition_order_preserved_on_kwonly(self): |
| 5162 |
for fn in signatures_with_lexicographic_keyword_only_parameters(): |
| 5163 |
signature = inspect.signature(fn) |
| 5164 |
l = list(signature.parameters) |
| 5165 |
sorted_l = sorted(l) |
| 5166 |
self.assertTrue(l) |
| 5167 |
self.assertEqual(l, sorted_l) |
| 5168 |
signature = inspect.signature(unsorted_keyword_only_parameters_fn) |
| 5169 |
l = list(signature.parameters) |
| 5170 |
self.assertEqual(l, unsorted_keyword_only_parameters) |
| 5171 |
|
| 5172 |
def test_signater_parameters_is_ordered(self): |
| 5173 |
p1 = inspect.signature(lambda x, y: None).parameters |
| 5174 |
p2 = inspect.signature(lambda y, x: None).parameters |
| 5175 |
self.assertNotEqual(p1, p2) |
| 5176 |
|
| 5177 |
def test_signature_annotations_with_local_namespaces(self): |
| 5178 |
class Foo: ... |
| 5179 |
def func(foo: Foo) -> int: pass |
| 5180 |
def func2(foo: Foo, bar: 'Bar') -> int: pass |
| 5181 |
|
| 5182 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 5183 |
with self.subTest(signature_func = signature_func): |
| 5184 |
sig1 = signature_func(func) |
| 5185 |
self.assertEqual(sig1.return_annotation, int) |
| 5186 |
self.assertEqual(sig1.parameters['foo'].annotation, Foo) |
| 5187 |
|
| 5188 |
sig2 = signature_func(func, locals=locals()) |
| 5189 |
self.assertEqual(sig2.return_annotation, int) |
| 5190 |
self.assertEqual(sig2.parameters['foo'].annotation, Foo) |
| 5191 |
|
| 5192 |
sig3 = signature_func(func2, globals={'Bar': int}, locals=locals()) |
| 5193 |
self.assertEqual(sig3.return_annotation, int) |
| 5194 |
self.assertEqual(sig3.parameters['foo'].annotation, Foo) |
| 5195 |
self.assertEqual(sig3.parameters['bar'].annotation, 'Bar') |
| 5196 |
|
| 5197 |
def test_signature_eval_str(self): |
| 5198 |
isa = inspect_stringized_annotations |
| 5199 |
sig = inspect.Signature |
| 5200 |
par = inspect.Parameter |
| 5201 |
PORK = inspect.Parameter.POSITIONAL_OR_KEYWORD |
| 5202 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 5203 |
with self.subTest(signature_func = signature_func): |
| 5204 |
self.assertEqual( |
| 5205 |
signature_func(isa.MyClass), |
| 5206 |
sig( |
| 5207 |
parameters=( |
| 5208 |
par('a', PORK), |
| 5209 |
par('b', PORK), |
| 5210 |
))) |
| 5211 |
self.assertEqual( |
| 5212 |
signature_func(isa.function), |
| 5213 |
sig( |
| 5214 |
return_annotation='MyClass', |
| 5215 |
parameters=( |
| 5216 |
par('a', PORK, annotation='int'), |
| 5217 |
par('b', PORK, annotation='str'), |
| 5218 |
))) |
| 5219 |
self.assertEqual( |
| 5220 |
signature_func(isa.function2), |
| 5221 |
sig( |
| 5222 |
return_annotation='MyClass', |
| 5223 |
parameters=( |
| 5224 |
par('a', PORK, annotation='int'), |
| 5225 |
par('b', PORK, annotation="'str'"), |
| 5226 |
par('c', PORK, annotation="MyClass"), |
| 5227 |
))) |
| 5228 |
self.assertEqual( |
| 5229 |
signature_func(isa.function3), |
| 5230 |
sig( |
| 5231 |
parameters=( |
| 5232 |
par('a', PORK, annotation="'int'"), |
| 5233 |
par('b', PORK, annotation="'str'"), |
| 5234 |
par('c', PORK, annotation="'MyClass'"), |
| 5235 |
))) |
| 5236 |
|
| 5237 |
if not MISSING_C_DOCSTRINGS: |
| 5238 |
self.assertEqual(signature_func(isa.UnannotatedClass), sig()) |
| 5239 |
self.assertEqual(signature_func(isa.unannotated_function), |
| 5240 |
sig( |
| 5241 |
parameters=( |
| 5242 |
par('a', PORK), |
| 5243 |
par('b', PORK), |
| 5244 |
par('c', PORK), |
| 5245 |
))) |
| 5246 |
|
| 5247 |
self.assertEqual( |
| 5248 |
signature_func(isa.MyClass, eval_str=True), |
| 5249 |
sig( |
| 5250 |
parameters=( |
| 5251 |
par('a', PORK), |
| 5252 |
par('b', PORK), |
| 5253 |
))) |
| 5254 |
self.assertEqual( |
| 5255 |
signature_func(isa.function, eval_str=True), |
| 5256 |
sig( |
| 5257 |
return_annotation=isa.MyClass, |
| 5258 |
parameters=( |
| 5259 |
par('a', PORK, annotation=int), |
| 5260 |
par('b', PORK, annotation=str), |
| 5261 |
))) |
| 5262 |
self.assertEqual( |
| 5263 |
signature_func(isa.function2, eval_str=True), |
| 5264 |
sig( |
| 5265 |
return_annotation=isa.MyClass, |
| 5266 |
parameters=( |
| 5267 |
par('a', PORK, annotation=int), |
| 5268 |
par('b', PORK, annotation='str'), |
| 5269 |
par('c', PORK, annotation=isa.MyClass), |
| 5270 |
))) |
| 5271 |
self.assertEqual( |
| 5272 |
signature_func(isa.function3, eval_str=True), |
| 5273 |
sig( |
| 5274 |
parameters=( |
| 5275 |
par('a', PORK, annotation='int'), |
| 5276 |
par('b', PORK, annotation='str'), |
| 5277 |
par('c', PORK, annotation='MyClass'), |
| 5278 |
))) |
| 5279 |
|
| 5280 |
globalns = {'int': float, 'str': complex} |
| 5281 |
localns = {'str': tuple, 'MyClass': dict} |
| 5282 |
with self.assertRaises(NameError): |
| 5283 |
signature_func(isa.function, eval_str=True, globals=globalns) |
| 5284 |
|
| 5285 |
self.assertEqual( |
| 5286 |
signature_func(isa.function, eval_str=True, locals=localns), |
| 5287 |
sig( |
| 5288 |
return_annotation=dict, |
| 5289 |
parameters=( |
| 5290 |
par('a', PORK, annotation=int), |
| 5291 |
par('b', PORK, annotation=tuple), |
| 5292 |
))) |
| 5293 |
|
| 5294 |
self.assertEqual( |
| 5295 |
signature_func(isa.function, eval_str=True, globals=globalns, locals=localns), |
| 5296 |
sig( |
| 5297 |
return_annotation=dict, |
| 5298 |
parameters=( |
| 5299 |
par('a', PORK, annotation=float), |
| 5300 |
par('b', PORK, annotation=tuple), |
| 5301 |
))) |
| 5302 |
|
| 5303 |
def test_signature_annotation_format(self): |
| 5304 |
ida = inspect_deferred_annotations |
| 5305 |
sig = inspect.Signature |
| 5306 |
par = inspect.Parameter |
| 5307 |
PORK = inspect.Parameter.POSITIONAL_OR_KEYWORD |
| 5308 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 5309 |
with self.subTest(signature_func=signature_func): |
| 5310 |
self.assertEqual( |
| 5311 |
signature_func(ida.f, annotation_format=Format.STRING), |
| 5312 |
sig([par("x", PORK, annotation="undefined")]) |
| 5313 |
) |
| 5314 |
s1 = signature_func(ida.f, annotation_format=Format.FORWARDREF) |
| 5315 |
s2 = sig([par("x", PORK, annotation=EqualToForwardRef("undefined", owner=ida.f))]) |
| 5316 |
#breakpoint() |
| 5317 |
self.assertEqual( |
| 5318 |
signature_func(ida.f, annotation_format=Format.FORWARDREF), |
| 5319 |
sig([par("x", PORK, annotation=EqualToForwardRef("undefined", owner=ida.f))]) |
| 5320 |
) |
| 5321 |
with self.assertRaisesRegex(NameError, "undefined"): |
| 5322 |
signature_func(ida.f, annotation_format=Format.VALUE) |
| 5323 |
with self.assertRaisesRegex(NameError, "undefined"): |
| 5324 |
signature_func(ida.f) |
| 5325 |
|
| 5326 |
def test_signature_deferred_annotations(self): |
| 5327 |
def f(x: undef): |
| 5328 |
pass |
| 5329 |
|
| 5330 |
class C: |
| 5331 |
x: undef |
| 5332 |
|
| 5333 |
def __init__(self, x: undef): |
| 5334 |
self.x = x |
| 5335 |
|
| 5336 |
sig = inspect.signature(f, annotation_format=Format.FORWARDREF) |
| 5337 |
self.assertEqual(list(sig.parameters), ['x']) |
| 5338 |
sig = inspect.signature(C, annotation_format=Format.FORWARDREF) |
| 5339 |
self.assertEqual(list(sig.parameters), ['x']) |
| 5340 |
|
| 5341 |
class CallableWrapper: |
| 5342 |
def __init__(self, func): |
| 5343 |
self.func = func |
| 5344 |
self.__annotate__ = func.__annotate__ |
| 5345 |
|
| 5346 |
def __call__(self, *args, **kwargs): |
| 5347 |
return self.func(*args, **kwargs) |
| 5348 |
|
| 5349 |
@property |
| 5350 |
def __annotations__(self): |
| 5351 |
return self.__annotate__(Format.VALUE) |
| 5352 |
|
| 5353 |
cw = CallableWrapper(f) |
| 5354 |
sig = inspect.signature(cw, annotation_format=Format.FORWARDREF) |
| 5355 |
self.assertEqual(list(sig.parameters), ['args', 'kwargs']) |
| 5356 |
|
| 5357 |
def test_signature_none_annotation(self): |
| 5358 |
class funclike: |
| 5359 |
# Has to be callable, and have correct |
| 5360 |
# __code__, __annotations__, __defaults__, __name__, |
| 5361 |
# and __kwdefaults__ attributes |
| 5362 |
|
| 5363 |
def __init__(self, func): |
| 5364 |
self.__name__ = func.__name__ |
| 5365 |
self.__code__ = func.__code__ |
| 5366 |
self.__annotations__ = func.__annotations__ |
| 5367 |
self.__defaults__ = func.__defaults__ |
| 5368 |
self.__kwdefaults__ = func.__kwdefaults__ |
| 5369 |
self.func = func |
| 5370 |
|
| 5371 |
def __call__(self, *args, **kwargs): |
| 5372 |
return self.func(*args, **kwargs) |
| 5373 |
|
| 5374 |
def foo(): pass |
| 5375 |
foo = funclike(foo) |
| 5376 |
foo.__annotations__ = None |
| 5377 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 5378 |
with self.subTest(signature_func = signature_func): |
| 5379 |
self.assertEqual(signature_func(foo), inspect.Signature()) |
| 5380 |
self.assertEqual(inspect.get_annotations(foo), {}) |
| 5381 |
|
| 5382 |
def test_signature_on_derived_classes(self): |
| 5383 |
# gh-105080: Make sure that signatures are consistent on derived classes |
| 5384 |
|
| 5385 |
class B: |
| 5386 |
def __new__(self, *args, **kwargs): |
| 5387 |
return super().__new__(self) |
| 5388 |
def __init__(self, value): |
| 5389 |
self.value = value |
| 5390 |
|
| 5391 |
class D1(B): |
| 5392 |
def __init__(self, value): |
| 5393 |
super().__init__(value) |
| 5394 |
|
| 5395 |
class D2(D1): |
| 5396 |
pass |
| 5397 |
|
| 5398 |
self.assertEqual(inspect.signature(D2), inspect.signature(D1)) |
| 5399 |
|
| 5400 |
def test_signature_on_non_comparable(self): |
| 5401 |
class NoncomparableCallable: |
| 5402 |
def __call__(self, a): |
| 5403 |
pass |
| 5404 |
def __eq__(self, other): |
| 5405 |
1/0 |
| 5406 |
self.assertEqual(self.signature(NoncomparableCallable()), |
| 5407 |
((('a', ..., ..., 'positional_or_keyword'),), |
| 5408 |
...)) |
| 5409 |
|
| 5410 |
|
| 5411 |
class TestParameterObject(unittest.TestCase): |
| 5412 |
def test_signature_parameter_kinds(self): |
| 5413 |
P = inspect.Parameter |
| 5414 |
self.assertTrue(P.POSITIONAL_ONLY < P.POSITIONAL_OR_KEYWORD < \ |
| 5415 |
P.VAR_POSITIONAL < P.KEYWORD_ONLY < P.VAR_KEYWORD) |
| 5416 |
|
| 5417 |
self.assertEqual(str(P.POSITIONAL_ONLY), 'POSITIONAL_ONLY') |
| 5418 |
self.assertTrue('POSITIONAL_ONLY' in repr(P.POSITIONAL_ONLY)) |
| 5419 |
|
| 5420 |
def test_signature_parameter_object(self): |
| 5421 |
p = inspect.Parameter('foo', default=10, |
| 5422 |
kind=inspect.Parameter.POSITIONAL_ONLY) |
| 5423 |
self.assertEqual(p.name, 'foo') |
| 5424 |
self.assertEqual(p.default, 10) |
| 5425 |
self.assertIs(p.annotation, p.empty) |
| 5426 |
self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) |
| 5427 |
|
| 5428 |
with self.assertRaisesRegex(ValueError, "value '123' is " |
| 5429 |
"not a valid Parameter.kind"): |
| 5430 |
inspect.Parameter('foo', default=10, kind='123') |
| 5431 |
|
| 5432 |
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): |
| 5433 |
inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD) |
| 5434 |
|
| 5435 |
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): |
| 5436 |
inspect.Parameter('from', kind=inspect.Parameter.VAR_KEYWORD) |
| 5437 |
|
| 5438 |
with self.assertRaisesRegex(TypeError, 'name must be a str'): |
| 5439 |
inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD) |
| 5440 |
|
| 5441 |
with self.assertRaisesRegex(ValueError, |
| 5442 |
'is not a valid parameter name'): |
| 5443 |
inspect.Parameter('$', kind=inspect.Parameter.VAR_KEYWORD) |
| 5444 |
|
| 5445 |
with self.assertRaisesRegex(ValueError, |
| 5446 |
'is not a valid parameter name'): |
| 5447 |
inspect.Parameter('.a', kind=inspect.Parameter.VAR_KEYWORD) |
| 5448 |
|
| 5449 |
with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
| 5450 |
inspect.Parameter('a', default=42, |
| 5451 |
kind=inspect.Parameter.VAR_KEYWORD) |
| 5452 |
|
| 5453 |
with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
| 5454 |
inspect.Parameter('a', default=42, |
| 5455 |
kind=inspect.Parameter.VAR_POSITIONAL) |
| 5456 |
|
| 5457 |
p = inspect.Parameter('a', default=42, |
| 5458 |
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) |
| 5459 |
with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
| 5460 |
p.replace(kind=inspect.Parameter.VAR_POSITIONAL) |
| 5461 |
|
| 5462 |
self.assertStartsWith(repr(p), '<Parameter') |
| 5463 |
self.assertTrue('"a=42"' in repr(p)) |
| 5464 |
|
| 5465 |
def test_signature_parameter_hashable(self): |
| 5466 |
P = inspect.Parameter |
| 5467 |
foo = P('foo', kind=P.POSITIONAL_ONLY) |
| 5468 |
self.assertEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY))) |
| 5469 |
self.assertNotEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY, |
| 5470 |
default=42))) |
| 5471 |
self.assertNotEqual(hash(foo), |
| 5472 |
hash(foo.replace(kind=P.VAR_POSITIONAL))) |
| 5473 |
|
| 5474 |
def test_signature_parameter_equality(self): |
| 5475 |
P = inspect.Parameter |
| 5476 |
p = P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) |
| 5477 |
|
| 5478 |
self.assertTrue(p == p) |
| 5479 |
self.assertFalse(p != p) |
| 5480 |
self.assertFalse(p == 42) |
| 5481 |
self.assertTrue(p != 42) |
| 5482 |
self.assertTrue(p == ALWAYS_EQ) |
| 5483 |
self.assertFalse(p != ALWAYS_EQ) |
| 5484 |
|
| 5485 |
self.assertTrue(p == P('foo', default=42, |
| 5486 |
kind=inspect.Parameter.KEYWORD_ONLY)) |
| 5487 |
self.assertFalse(p != P('foo', default=42, |
| 5488 |
kind=inspect.Parameter.KEYWORD_ONLY)) |
| 5489 |
|
| 5490 |
def test_signature_parameter_replace(self): |
| 5491 |
p = inspect.Parameter('foo', default=42, |
| 5492 |
kind=inspect.Parameter.KEYWORD_ONLY) |
| 5493 |
|
| 5494 |
self.assertIsNot(p.replace(), p) |
| 5495 |
self.assertEqual(p.replace(), p) |
| 5496 |
self.assertIsNot(copy.replace(p), p) |
| 5497 |
self.assertEqual(copy.replace(p), p) |
| 5498 |
|
| 5499 |
p2 = p.replace(annotation=1) |
| 5500 |
self.assertEqual(p2.annotation, 1) |
| 5501 |
p2 = p2.replace(annotation=p2.empty) |
| 5502 |
self.assertEqual(p2, p) |
| 5503 |
p3 = copy.replace(p, annotation=1) |
| 5504 |
self.assertEqual(p3.annotation, 1) |
| 5505 |
p3 = copy.replace(p3, annotation=p3.empty) |
| 5506 |
self.assertEqual(p3, p) |
| 5507 |
|
| 5508 |
p2 = p2.replace(name='bar') |
| 5509 |
self.assertEqual(p2.name, 'bar') |
| 5510 |
self.assertNotEqual(p2, p) |
| 5511 |
p3 = copy.replace(p3, name='bar') |
| 5512 |
self.assertEqual(p3.name, 'bar') |
| 5513 |
self.assertNotEqual(p3, p) |
| 5514 |
|
| 5515 |
with self.assertRaisesRegex(ValueError, |
| 5516 |
'name is a required attribute'): |
| 5517 |
p2 = p2.replace(name=p2.empty) |
| 5518 |
with self.assertRaisesRegex(ValueError, |
| 5519 |
'name is a required attribute'): |
| 5520 |
p3 = copy.replace(p3, name=p3.empty) |
| 5521 |
|
| 5522 |
p2 = p2.replace(name='foo', default=None) |
| 5523 |
self.assertIs(p2.default, None) |
| 5524 |
self.assertNotEqual(p2, p) |
| 5525 |
p3 = copy.replace(p3, name='foo', default=None) |
| 5526 |
self.assertIs(p3.default, None) |
| 5527 |
self.assertNotEqual(p3, p) |
| 5528 |
|
| 5529 |
p2 = p2.replace(name='foo', default=p2.empty) |
| 5530 |
self.assertIs(p2.default, p2.empty) |
| 5531 |
p3 = copy.replace(p3, name='foo', default=p3.empty) |
| 5532 |
self.assertIs(p3.default, p3.empty) |
| 5533 |
|
| 5534 |
p2 = p2.replace(default=42, kind=p2.POSITIONAL_OR_KEYWORD) |
| 5535 |
self.assertEqual(p2.kind, p2.POSITIONAL_OR_KEYWORD) |
| 5536 |
self.assertNotEqual(p2, p) |
| 5537 |
p3 = copy.replace(p3, default=42, kind=p3.POSITIONAL_OR_KEYWORD) |
| 5538 |
self.assertEqual(p3.kind, p3.POSITIONAL_OR_KEYWORD) |
| 5539 |
self.assertNotEqual(p3, p) |
| 5540 |
|
| 5541 |
with self.assertRaisesRegex(ValueError, |
| 5542 |
"value <class 'inspect._empty'> " |
| 5543 |
"is not a valid Parameter.kind"): |
| 5544 |
p2 = p2.replace(kind=p2.empty) |
| 5545 |
with self.assertRaisesRegex(ValueError, |
| 5546 |
"value <class 'inspect._empty'> " |
| 5547 |
"is not a valid Parameter.kind"): |
| 5548 |
p3 = copy.replace(p3, kind=p3.empty) |
| 5549 |
|
| 5550 |
p2 = p2.replace(kind=p2.KEYWORD_ONLY) |
| 5551 |
self.assertEqual(p2, p) |
| 5552 |
p3 = copy.replace(p3, kind=p3.KEYWORD_ONLY) |
| 5553 |
self.assertEqual(p3, p) |
| 5554 |
|
| 5555 |
def test_signature_parameter_positional_only(self): |
| 5556 |
with self.assertRaisesRegex(TypeError, 'name must be a str'): |
| 5557 |
inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY) |
| 5558 |
|
| 5559 |
@cpython_only |
| 5560 |
def test_signature_parameter_implicit(self): |
| 5561 |
with self.assertRaisesRegex(ValueError, |
| 5562 |
'implicit arguments must be passed as ' |
| 5563 |
'positional or keyword arguments, ' |
| 5564 |
'not positional-only'): |
| 5565 |
inspect.Parameter('.0', kind=inspect.Parameter.POSITIONAL_ONLY) |
| 5566 |
|
| 5567 |
param = inspect.Parameter( |
| 5568 |
'.0', kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) |
| 5569 |
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_ONLY) |
| 5570 |
self.assertEqual(param.name, 'implicit0') |
| 5571 |
|
| 5572 |
def test_signature_parameter_immutability(self): |
| 5573 |
p = inspect.Parameter('spam', kind=inspect.Parameter.KEYWORD_ONLY) |
| 5574 |
|
| 5575 |
with self.assertRaises(AttributeError): |
| 5576 |
p.foo = 'bar' |
| 5577 |
|
| 5578 |
with self.assertRaises(AttributeError): |
| 5579 |
p.kind = 123 |
| 5580 |
|
| 5581 |
|
| 5582 |
class TestSignatureBind(unittest.TestCase): |
| 5583 |
@staticmethod |
| 5584 |
def call(func, *args, **kwargs): |
| 5585 |
sig = inspect.signature(func) |
| 5586 |
ba = sig.bind(*args, **kwargs) |
| 5587 |
# Prevent unexpected success of assertRaises(TypeError, ...) |
| 5588 |
try: |
| 5589 |
return func(*ba.args, **ba.kwargs) |
| 5590 |
except TypeError as e: |
| 5591 |
raise AssertionError from e |
| 5592 |
|
| 5593 |
def test_signature_bind_empty(self): |
| 5594 |
def test(): |
| 5595 |
return 42 |
| 5596 |
|
| 5597 |
self.assertEqual(self.call(test), 42) |
| 5598 |
with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
| 5599 |
self.call(test, 1) |
| 5600 |
with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
| 5601 |
self.call(test, 1, spam=10) |
| 5602 |
with self.assertRaisesRegex( |
| 5603 |
TypeError, "got an unexpected keyword argument 'spam'"): |
| 5604 |
|
| 5605 |
self.call(test, spam=1) |
| 5606 |
|
| 5607 |
def test_signature_bind_var(self): |
| 5608 |
def test(*args, **kwargs): |
| 5609 |
return args, kwargs |
| 5610 |
|
| 5611 |
self.assertEqual(self.call(test), ((), {})) |
| 5612 |
self.assertEqual(self.call(test, 1), ((1,), {})) |
| 5613 |
self.assertEqual(self.call(test, 1, 2), ((1, 2), {})) |
| 5614 |
self.assertEqual(self.call(test, foo='bar'), ((), {'foo': 'bar'})) |
| 5615 |
self.assertEqual(self.call(test, 1, foo='bar'), ((1,), {'foo': 'bar'})) |
| 5616 |
self.assertEqual(self.call(test, args=10), ((), {'args': 10})) |
| 5617 |
self.assertEqual(self.call(test, 1, 2, foo='bar'), |
| 5618 |
((1, 2), {'foo': 'bar'})) |
| 5619 |
|
| 5620 |
def test_signature_bind_just_args(self): |
| 5621 |
def test(a, b, c): |
| 5622 |
return a, b, c |
| 5623 |
|
| 5624 |
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 5625 |
|
| 5626 |
with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
| 5627 |
self.call(test, 1, 2, 3, 4) |
| 5628 |
|
| 5629 |
with self.assertRaisesRegex(TypeError, |
| 5630 |
"missing a required argument: 'b'"): |
| 5631 |
self.call(test, 1) |
| 5632 |
|
| 5633 |
with self.assertRaisesRegex(TypeError, |
| 5634 |
"missing a required argument: 'a'"): |
| 5635 |
self.call(test) |
| 5636 |
|
| 5637 |
def test(a, b, c=10): |
| 5638 |
return a, b, c |
| 5639 |
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 5640 |
self.assertEqual(self.call(test, 1, 2), (1, 2, 10)) |
| 5641 |
|
| 5642 |
def test(a=1, b=2, c=3): |
| 5643 |
return a, b, c |
| 5644 |
self.assertEqual(self.call(test, a=10, c=13), (10, 2, 13)) |
| 5645 |
self.assertEqual(self.call(test, a=10), (10, 2, 3)) |
| 5646 |
self.assertEqual(self.call(test, b=10), (1, 10, 3)) |
| 5647 |
|
| 5648 |
def test_signature_bind_varargs_order(self): |
| 5649 |
def test(*args): |
| 5650 |
return args |
| 5651 |
|
| 5652 |
self.assertEqual(self.call(test), ()) |
| 5653 |
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 5654 |
|
| 5655 |
def test_signature_bind_args_and_varargs(self): |
| 5656 |
def test(a, b, c=3, *args): |
| 5657 |
return a, b, c, args |
| 5658 |
|
| 5659 |
self.assertEqual(self.call(test, 1, 2, 3, 4, 5), (1, 2, 3, (4, 5))) |
| 5660 |
self.assertEqual(self.call(test, 1, 2), (1, 2, 3, ())) |
| 5661 |
self.assertEqual(self.call(test, b=1, a=2), (2, 1, 3, ())) |
| 5662 |
self.assertEqual(self.call(test, 1, b=2), (1, 2, 3, ())) |
| 5663 |
|
| 5664 |
with self.assertRaisesRegex(TypeError, |
| 5665 |
"multiple values for argument 'c'"): |
| 5666 |
self.call(test, 1, 2, 3, c=4) |
| 5667 |
|
| 5668 |
def test_signature_bind_just_kwargs(self): |
| 5669 |
def test(**kwargs): |
| 5670 |
return kwargs |
| 5671 |
|
| 5672 |
self.assertEqual(self.call(test), {}) |
| 5673 |
self.assertEqual(self.call(test, foo='bar', spam='ham'), |
| 5674 |
{'foo': 'bar', 'spam': 'ham'}) |
| 5675 |
|
| 5676 |
def test_signature_bind_args_and_kwargs(self): |
| 5677 |
def test(a, b, c=3, **kwargs): |
| 5678 |
return a, b, c, kwargs |
| 5679 |
|
| 5680 |
self.assertEqual(self.call(test, 1, 2), (1, 2, 3, {})) |
| 5681 |
self.assertEqual(self.call(test, 1, 2, foo='bar', spam='ham'), |
| 5682 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 5683 |
self.assertEqual(self.call(test, b=2, a=1, foo='bar', spam='ham'), |
| 5684 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 5685 |
self.assertEqual(self.call(test, a=1, b=2, foo='bar', spam='ham'), |
| 5686 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 5687 |
self.assertEqual(self.call(test, 1, b=2, foo='bar', spam='ham'), |
| 5688 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 5689 |
self.assertEqual(self.call(test, 1, b=2, c=4, foo='bar', spam='ham'), |
| 5690 |
(1, 2, 4, {'foo': 'bar', 'spam': 'ham'})) |
| 5691 |
self.assertEqual(self.call(test, 1, 2, 4, foo='bar'), |
| 5692 |
(1, 2, 4, {'foo': 'bar'})) |
| 5693 |
self.assertEqual(self.call(test, c=5, a=4, b=3), |
| 5694 |
(4, 3, 5, {})) |
| 5695 |
|
| 5696 |
def test_signature_bind_kwonly(self): |
| 5697 |
def test(*, foo): |
| 5698 |
return foo |
| 5699 |
with self.assertRaisesRegex(TypeError, |
| 5700 |
'too many positional arguments'): |
| 5701 |
self.call(test, 1) |
| 5702 |
self.assertEqual(self.call(test, foo=1), 1) |
| 5703 |
|
| 5704 |
def test(a, *, foo=1, bar): |
| 5705 |
return foo |
| 5706 |
with self.assertRaisesRegex(TypeError, |
| 5707 |
"missing a required argument: 'bar'"): |
| 5708 |
self.call(test, 1) |
| 5709 |
|
| 5710 |
def test(foo, *, bar): |
| 5711 |
return foo, bar |
| 5712 |
self.assertEqual(self.call(test, 1, bar=2), (1, 2)) |
| 5713 |
self.assertEqual(self.call(test, bar=2, foo=1), (1, 2)) |
| 5714 |
|
| 5715 |
with self.assertRaisesRegex( |
| 5716 |
TypeError, "got an unexpected keyword argument 'spam'"): |
| 5717 |
|
| 5718 |
self.call(test, bar=2, foo=1, spam=10) |
| 5719 |
|
| 5720 |
with self.assertRaisesRegex(TypeError, |
| 5721 |
'too many positional arguments'): |
| 5722 |
self.call(test, 1, 2) |
| 5723 |
|
| 5724 |
with self.assertRaisesRegex(TypeError, |
| 5725 |
'too many positional arguments'): |
| 5726 |
self.call(test, 1, 2, bar=2) |
| 5727 |
|
| 5728 |
with self.assertRaisesRegex( |
| 5729 |
TypeError, "got an unexpected keyword argument 'spam'"): |
| 5730 |
|
| 5731 |
self.call(test, 1, bar=2, spam='ham') |
| 5732 |
|
| 5733 |
with self.assertRaisesRegex(TypeError, |
| 5734 |
"missing a required keyword-only " |
| 5735 |
"argument: 'bar'"): |
| 5736 |
self.call(test, 1) |
| 5737 |
|
| 5738 |
def test(foo, *, bar, **bin): |
| 5739 |
return foo, bar, bin |
| 5740 |
self.assertEqual(self.call(test, 1, bar=2), (1, 2, {})) |
| 5741 |
self.assertEqual(self.call(test, foo=1, bar=2), (1, 2, {})) |
| 5742 |
self.assertEqual(self.call(test, 1, bar=2, spam='ham'), |
| 5743 |
(1, 2, {'spam': 'ham'})) |
| 5744 |
self.assertEqual(self.call(test, spam='ham', foo=1, bar=2), |
| 5745 |
(1, 2, {'spam': 'ham'})) |
| 5746 |
with self.assertRaisesRegex(TypeError, |
| 5747 |
"missing a required argument: 'foo'"): |
| 5748 |
self.call(test, spam='ham', bar=2) |
| 5749 |
self.assertEqual(self.call(test, 1, bar=2, bin=1, spam=10), |
| 5750 |
(1, 2, {'bin': 1, 'spam': 10})) |
| 5751 |
|
| 5752 |
def test_signature_bind_arguments(self): |
| 5753 |
def test(a, *args, b, z=100, **kwargs): |
| 5754 |
pass |
| 5755 |
sig = inspect.signature(test) |
| 5756 |
ba = sig.bind(10, 20, b=30, c=40, args=50, kwargs=60) |
| 5757 |
# we won't have 'z' argument in the bound arguments object, as we didn't |
| 5758 |
# pass it to the 'bind' |
| 5759 |
self.assertEqual(tuple(ba.arguments.items()), |
| 5760 |
(('a', 10), ('args', (20,)), ('b', 30), |
| 5761 |
('kwargs', {'c': 40, 'args': 50, 'kwargs': 60}))) |
| 5762 |
self.assertEqual(ba.kwargs, |
| 5763 |
{'b': 30, 'c': 40, 'args': 50, 'kwargs': 60}) |
| 5764 |
self.assertEqual(ba.args, (10, 20)) |
| 5765 |
|
| 5766 |
def test_signature_bind_positional_only(self): |
| 5767 |
def test(a_po, b_po, c_po=3, /, foo=42, *, bar=50, **kwargs): |
| 5768 |
return a_po, b_po, c_po, foo, bar, kwargs |
| 5769 |
|
| 5770 |
self.assertEqual(self.call(test, 1, 2, 4, 5, bar=6), |
| 5771 |
(1, 2, 4, 5, 6, {})) |
| 5772 |
|
| 5773 |
self.assertEqual(self.call(test, 1, 2), |
| 5774 |
(1, 2, 3, 42, 50, {})) |
| 5775 |
|
| 5776 |
self.assertEqual(self.call(test, 1, 2, foo=4, bar=5), |
| 5777 |
(1, 2, 3, 4, 5, {})) |
| 5778 |
|
| 5779 |
self.assertEqual(self.call(test, 1, 2, foo=4, bar=5, c_po=10), |
| 5780 |
(1, 2, 3, 4, 5, {'c_po': 10})) |
| 5781 |
|
| 5782 |
self.assertEqual(self.call(test, 1, 2, 30, c_po=31, foo=4, bar=5), |
| 5783 |
(1, 2, 30, 4, 5, {'c_po': 31})) |
| 5784 |
|
| 5785 |
self.assertEqual(self.call(test, 1, 2, 30, foo=4, bar=5, c_po=31), |
| 5786 |
(1, 2, 30, 4, 5, {'c_po': 31})) |
| 5787 |
|
| 5788 |
self.assertEqual(self.call(test, 1, 2, c_po=4), |
| 5789 |
(1, 2, 3, 42, 50, {'c_po': 4})) |
| 5790 |
|
| 5791 |
with self.assertRaisesRegex(TypeError, "missing a required positional-only argument: 'a_po'"): |
| 5792 |
self.call(test, a_po=1, b_po=2) |
| 5793 |
|
| 5794 |
def without_var_kwargs(c_po=3, d_po=4, /): |
| 5795 |
return c_po, d_po |
| 5796 |
|
| 5797 |
with self.assertRaisesRegex( |
| 5798 |
TypeError, |
| 5799 |
"positional-only arguments passed as keyword arguments: 'c_po, d_po'", |
| 5800 |
): |
| 5801 |
self.call(without_var_kwargs, c_po=33, d_po=44) |
| 5802 |
|
| 5803 |
def test_signature_bind_with_self_arg(self): |
| 5804 |
# Issue #17071: one of the parameters is named "self |
| 5805 |
def test(a, self, b): |
| 5806 |
pass |
| 5807 |
sig = inspect.signature(test) |
| 5808 |
ba = sig.bind(1, 2, 3) |
| 5809 |
self.assertEqual(ba.args, (1, 2, 3)) |
| 5810 |
ba = sig.bind(1, self=2, b=3) |
| 5811 |
self.assertEqual(ba.args, (1, 2, 3)) |
| 5812 |
|
| 5813 |
def test_signature_bind_vararg_name(self): |
| 5814 |
def test(a, *args): |
| 5815 |
return a, args |
| 5816 |
sig = inspect.signature(test) |
| 5817 |
|
| 5818 |
with self.assertRaisesRegex( |
| 5819 |
TypeError, "got an unexpected keyword argument 'args'"): |
| 5820 |
|
| 5821 |
sig.bind(a=0, args=1) |
| 5822 |
|
| 5823 |
def test(*args, **kwargs): |
| 5824 |
return args, kwargs |
| 5825 |
self.assertEqual(self.call(test, args=1), ((), {'args': 1})) |
| 5826 |
|
| 5827 |
sig = inspect.signature(test) |
| 5828 |
ba = sig.bind(args=1) |
| 5829 |
self.assertEqual(ba.arguments, {'kwargs': {'args': 1}}) |
| 5830 |
|
| 5831 |
@cpython_only |
| 5832 |
def test_signature_bind_implicit_arg(self): |
| 5833 |
# Issue #19611: getcallargs should work with comprehensions |
| 5834 |
def make_set(): |
| 5835 |
return set(z * z for z in range(5)) |
| 5836 |
gencomp_code = make_set.__code__.co_consts[0] |
| 5837 |
gencomp_func = types.FunctionType(gencomp_code, {}) |
| 5838 |
|
| 5839 |
iterator = iter(range(5)) |
| 5840 |
self.assertEqual(set(self.call(gencomp_func, iterator)), {0, 1, 4, 9, 16}) |
| 5841 |
|
| 5842 |
def test_signature_bind_posonly_kwargs(self): |
| 5843 |
def foo(bar, /, **kwargs): |
| 5844 |
return bar, kwargs.get(bar) |
| 5845 |
|
| 5846 |
sig = inspect.signature(foo) |
| 5847 |
result = sig.bind("pos-only", bar="keyword") |
| 5848 |
|
| 5849 |
self.assertEqual(result.kwargs, {"bar": "keyword"}) |
| 5850 |
self.assertIn(("bar", "pos-only"), result.arguments.items()) |
| 5851 |
|
| 5852 |
|
| 5853 |
class TestBoundArguments(unittest.TestCase): |
| 5854 |
def test_signature_bound_arguments_unhashable(self): |
| 5855 |
def foo(a): pass |
| 5856 |
ba = inspect.signature(foo).bind(1) |
| 5857 |
|
| 5858 |
with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 5859 |
hash(ba) |
| 5860 |
|
| 5861 |
def test_signature_bound_arguments_equality(self): |
| 5862 |
def foo(a): pass |
| 5863 |
ba = inspect.signature(foo).bind(1) |
| 5864 |
self.assertTrue(ba == ba) |
| 5865 |
self.assertFalse(ba != ba) |
| 5866 |
self.assertTrue(ba == ALWAYS_EQ) |
| 5867 |
self.assertFalse(ba != ALWAYS_EQ) |
| 5868 |
|
| 5869 |
ba2 = inspect.signature(foo).bind(1) |
| 5870 |
self.assertTrue(ba == ba2) |
| 5871 |
self.assertFalse(ba != ba2) |
| 5872 |
|
| 5873 |
ba3 = inspect.signature(foo).bind(2) |
| 5874 |
self.assertFalse(ba == ba3) |
| 5875 |
self.assertTrue(ba != ba3) |
| 5876 |
ba3.arguments['a'] = 1 |
| 5877 |
self.assertTrue(ba == ba3) |
| 5878 |
self.assertFalse(ba != ba3) |
| 5879 |
|
| 5880 |
def bar(b): pass |
| 5881 |
ba4 = inspect.signature(bar).bind(1) |
| 5882 |
self.assertFalse(ba == ba4) |
| 5883 |
self.assertTrue(ba != ba4) |
| 5884 |
|
| 5885 |
def foo(*, a, b): pass |
| 5886 |
sig = inspect.signature(foo) |
| 5887 |
ba1 = sig.bind(a=1, b=2) |
| 5888 |
ba2 = sig.bind(b=2, a=1) |
| 5889 |
self.assertTrue(ba1 == ba2) |
| 5890 |
self.assertFalse(ba1 != ba2) |
| 5891 |
|
| 5892 |
def test_signature_bound_arguments_pickle(self): |
| 5893 |
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 5894 |
sig = inspect.signature(foo) |
| 5895 |
ba = sig.bind(20, 30, z={}) |
| 5896 |
|
| 5897 |
for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 5898 |
with self.subTest(pickle_ver=ver): |
| 5899 |
ba_pickled = pickle.loads(pickle.dumps(ba, ver)) |
| 5900 |
self.assertEqual(ba, ba_pickled) |
| 5901 |
|
| 5902 |
def test_signature_bound_arguments_repr(self): |
| 5903 |
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 5904 |
sig = inspect.signature(foo) |
| 5905 |
ba = sig.bind(20, 30, z={}) |
| 5906 |
self.assertRegex(repr(ba), r'<BoundArguments \(a=20,.*\}\}\)>') |
| 5907 |
|
| 5908 |
def test_signature_bound_arguments_apply_defaults(self): |
| 5909 |
def foo(a, b=1, *args, c:1={}, **kw): pass |
| 5910 |
sig = inspect.signature(foo) |
| 5911 |
|
| 5912 |
ba = sig.bind(20) |
| 5913 |
ba.apply_defaults() |
| 5914 |
self.assertEqual( |
| 5915 |
list(ba.arguments.items()), |
| 5916 |
[('a', 20), ('b', 1), ('args', ()), ('c', {}), ('kw', {})]) |
| 5917 |
|
| 5918 |
# Make sure that we preserve the order: |
| 5919 |
# i.e. 'c' should be *before* 'kw'. |
| 5920 |
ba = sig.bind(10, 20, 30, d=1) |
| 5921 |
ba.apply_defaults() |
| 5922 |
self.assertEqual( |
| 5923 |
list(ba.arguments.items()), |
| 5924 |
[('a', 10), ('b', 20), ('args', (30,)), ('c', {}), ('kw', {'d':1})]) |
| 5925 |
|
| 5926 |
# Make sure that BoundArguments produced by bind_partial() |
| 5927 |
# are supported. |
| 5928 |
def foo(a, b): pass |
| 5929 |
sig = inspect.signature(foo) |
| 5930 |
ba = sig.bind_partial(20) |
| 5931 |
ba.apply_defaults() |
| 5932 |
self.assertEqual( |
| 5933 |
list(ba.arguments.items()), |
| 5934 |
[('a', 20)]) |
| 5935 |
|
| 5936 |
# Test no args |
| 5937 |
def foo(): pass |
| 5938 |
sig = inspect.signature(foo) |
| 5939 |
ba = sig.bind() |
| 5940 |
ba.apply_defaults() |
| 5941 |
self.assertEqual(list(ba.arguments.items()), []) |
| 5942 |
|
| 5943 |
# Make sure a no-args binding still acquires proper defaults. |
| 5944 |
def foo(a='spam'): pass |
| 5945 |
sig = inspect.signature(foo) |
| 5946 |
ba = sig.bind() |
| 5947 |
ba.apply_defaults() |
| 5948 |
self.assertEqual(list(ba.arguments.items()), [('a', 'spam')]) |
| 5949 |
|
| 5950 |
def test_signature_bound_arguments_arguments_type(self): |
| 5951 |
def foo(a): pass |
| 5952 |
ba = inspect.signature(foo).bind(1) |
| 5953 |
self.assertIs(type(ba.arguments), dict) |
| 5954 |
|
| 5955 |
class TestSignaturePrivateHelpers(unittest.TestCase): |
| 5956 |
def _strip_non_python_syntax(self, input, |
| 5957 |
clean_signature, self_parameter): |
| 5958 |
computed_clean_signature, \ |
| 5959 |
computed_self_parameter = \ |
| 5960 |
inspect._signature_strip_non_python_syntax(input) |
| 5961 |
self.assertEqual(computed_clean_signature, clean_signature) |
| 5962 |
self.assertEqual(computed_self_parameter, self_parameter) |
| 5963 |
|
| 5964 |
def test_signature_strip_non_python_syntax(self): |
| 5965 |
self._strip_non_python_syntax( |
| 5966 |
"($module, /, path, mode, *, dir_fd=None, " + |
| 5967 |
"effective_ids=False,\n follow_symlinks=True)", |
| 5968 |
"(module, /, path, mode, *, dir_fd=None, " + |
| 5969 |
"effective_ids=False, follow_symlinks=True)", |
| 5970 |
0) |
| 5971 |
|
| 5972 |
self._strip_non_python_syntax( |
| 5973 |
"($module, word, salt, /)", |
| 5974 |
"(module, word, salt, /)", |
| 5975 |
0) |
| 5976 |
|
| 5977 |
self._strip_non_python_syntax( |
| 5978 |
"(x, y=None, z=None, /)", |
| 5979 |
"(x, y=None, z=None, /)", |
| 5980 |
None) |
| 5981 |
|
| 5982 |
self._strip_non_python_syntax( |
| 5983 |
"(x, y=None, z=None)", |
| 5984 |
"(x, y=None, z=None)", |
| 5985 |
None) |
| 5986 |
|
| 5987 |
self._strip_non_python_syntax( |
| 5988 |
"(x,\n y=None,\n z = None )", |
| 5989 |
"(x, y=None, z=None)", |
| 5990 |
None) |
| 5991 |
|
| 5992 |
self._strip_non_python_syntax( |
| 5993 |
"", |
| 5994 |
"", |
| 5995 |
None) |
| 5996 |
|
| 5997 |
self._strip_non_python_syntax( |
| 5998 |
None, |
| 5999 |
None, |
| 6000 |
None) |
| 6001 |
|
| 6002 |
class TestSignatureDefinitions(unittest.TestCase): |
| 6003 |
# This test case provides a home for checking that particular APIs |
| 6004 |
# have signatures available for introspection |
| 6005 |
|
| 6006 |
@staticmethod |
| 6007 |
def is_public(name): |
| 6008 |
return not name.startswith('_') or name.startswith('__') and name.endswith('__') |
| 6009 |
|
| 6010 |
@cpython_only |
| 6011 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 6012 |
"Signature information for builtins requires docstrings") |
| 6013 |
def _test_module_has_signatures(self, module, |
| 6014 |
no_signature=(), unsupported_signature=(), |
| 6015 |
methods_no_signature={}, methods_unsupported_signature={}, |
| 6016 |
good_exceptions=()): |
| 6017 |
# This checks all builtin callables in CPython have signatures |
| 6018 |
# A few have signatures Signature can't yet handle, so we skip those |
| 6019 |
# since they will have to wait until PEP 457 adds the required |
| 6020 |
# introspection support to the inspect module |
| 6021 |
# Some others also haven't been converted yet for various other |
| 6022 |
# reasons, so we also skip those for the time being, but design |
| 6023 |
# the test to fail in order to indicate when it needs to be |
| 6024 |
# updated. |
| 6025 |
no_signature = no_signature or set() |
| 6026 |
# Check the signatures we expect to be there |
| 6027 |
ns = vars(module) |
| 6028 |
try: |
| 6029 |
names = set(module.__all__) |
| 6030 |
except AttributeError: |
| 6031 |
names = set(name for name in ns if self.is_public(name)) |
| 6032 |
for name, obj in sorted(ns.items()): |
| 6033 |
if name not in names: |
| 6034 |
continue |
| 6035 |
if not callable(obj): |
| 6036 |
continue |
| 6037 |
if (isinstance(obj, type) and |
| 6038 |
issubclass(obj, BaseException) and |
| 6039 |
name not in good_exceptions): |
| 6040 |
no_signature.add(name) |
| 6041 |
if name not in no_signature and name not in unsupported_signature: |
| 6042 |
with self.subTest('supported', builtin=name): |
| 6043 |
self.assertIsNotNone(inspect.signature(obj)) |
| 6044 |
if isinstance(obj, type): |
| 6045 |
with self.subTest(type=name): |
| 6046 |
self._test_builtin_methods_have_signatures(obj, |
| 6047 |
methods_no_signature.get(name, ()), |
| 6048 |
methods_unsupported_signature.get(name, ())) |
| 6049 |
# Check callables that haven't been converted don't claim a signature |
| 6050 |
# This ensures this test will start failing as more signatures are |
| 6051 |
# added, so the affected items can be moved into the scope of the |
| 6052 |
# regression test above |
| 6053 |
for name in no_signature: |
| 6054 |
with self.subTest('none', builtin=name): |
| 6055 |
obj = ns[name] |
| 6056 |
self.assertIsNone(obj.__text_signature__) |
| 6057 |
self.assertRaises(ValueError, inspect.signature, obj) |
| 6058 |
for name in unsupported_signature: |
| 6059 |
with self.subTest('unsupported', builtin=name): |
| 6060 |
obj = ns[name] |
| 6061 |
self.assertIsNotNone(obj.__text_signature__) |
| 6062 |
self.assertRaises(ValueError, inspect.signature, obj) |
| 6063 |
|
| 6064 |
def _test_builtin_methods_have_signatures(self, cls, no_signature, unsupported_signature): |
| 6065 |
ns = vars(cls) |
| 6066 |
for name in ns: |
| 6067 |
obj = getattr(cls, name, None) |
| 6068 |
if not callable(obj) or isinstance(obj, type): |
| 6069 |
continue |
| 6070 |
if name not in no_signature and name not in unsupported_signature: |
| 6071 |
with self.subTest('supported', method=name): |
| 6072 |
self.assertIsNotNone(inspect.signature(obj)) |
| 6073 |
for name in no_signature: |
| 6074 |
with self.subTest('none', method=name): |
| 6075 |
self.assertIsNone(getattr(cls, name).__text_signature__) |
| 6076 |
self.assertRaises(ValueError, inspect.signature, getattr(cls, name)) |
| 6077 |
for name in unsupported_signature: |
| 6078 |
with self.subTest('unsupported', method=name): |
| 6079 |
self.assertIsNotNone(getattr(cls, name).__text_signature__) |
| 6080 |
self.assertRaises(ValueError, inspect.signature, getattr(cls, name)) |
| 6081 |
|
| 6082 |
def test_builtins_have_signatures(self): |
| 6083 |
no_signature = {'type', 'super', 'bytearray', 'bytes', 'dict', 'int', 'str'} |
| 6084 |
# These need PEP 457 groups |
| 6085 |
needs_groups = {"range", "slice", "dir", "getattr", |
| 6086 |
"next", "iter", "vars"} |
| 6087 |
no_signature |= needs_groups |
| 6088 |
# These have unrepresentable parameter default values of NULL |
| 6089 |
unsupported_signature = {"anext"} |
| 6090 |
# These need *args support in Argument Clinic |
| 6091 |
needs_varargs = {"min", "max", "__build_class__"} |
| 6092 |
no_signature |= needs_varargs |
| 6093 |
|
| 6094 |
methods_no_signature = { |
| 6095 |
'dict': {'update'}, |
| 6096 |
'object': {'__class__'}, |
| 6097 |
} |
| 6098 |
methods_unsupported_signature = { |
| 6099 |
'bytearray': {'count', 'endswith', 'find', 'hex', 'index', 'rfind', 'rindex', 'startswith'}, |
| 6100 |
'bytes': {'count', 'endswith', 'find', 'hex', 'index', 'rfind', 'rindex', 'startswith'}, |
| 6101 |
'dict': {'pop'}, |
| 6102 |
'memoryview': {'cast', 'hex'}, |
| 6103 |
'str': {'count', 'endswith', 'find', 'index', 'maketrans', 'rfind', 'rindex', 'startswith'}, |
| 6104 |
} |
| 6105 |
self._test_module_has_signatures(builtins, |
| 6106 |
no_signature, unsupported_signature, |
| 6107 |
methods_no_signature, methods_unsupported_signature) |
| 6108 |
|
| 6109 |
def test_types_module_has_signatures(self): |
| 6110 |
unsupported_signature = {'CellType'} |
| 6111 |
methods_no_signature = { |
| 6112 |
'AsyncGeneratorType': {'athrow'}, |
| 6113 |
'CoroutineType': {'throw'}, |
| 6114 |
'GeneratorType': {'throw'}, |
| 6115 |
} |
| 6116 |
self._test_module_has_signatures(types, |
| 6117 |
unsupported_signature=unsupported_signature, |
| 6118 |
methods_no_signature=methods_no_signature) |
| 6119 |
|
| 6120 |
def test_sys_module_has_signatures(self): |
| 6121 |
no_signature = {'getsizeof', 'set_asyncgen_hooks'} |
| 6122 |
no_signature |= {name for name in ['getobjects'] |
| 6123 |
if hasattr(sys, name)} |
| 6124 |
self._test_module_has_signatures(sys, no_signature) |
| 6125 |
|
| 6126 |
def test_abc_module_has_signatures(self): |
| 6127 |
import abc |
| 6128 |
self._test_module_has_signatures(abc) |
| 6129 |
|
| 6130 |
def test_atexit_module_has_signatures(self): |
| 6131 |
import atexit |
| 6132 |
self._test_module_has_signatures(atexit) |
| 6133 |
|
| 6134 |
def test_codecs_module_has_signatures(self): |
| 6135 |
import codecs |
| 6136 |
methods_no_signature = {'StreamReader': {'charbuffertype'}} |
| 6137 |
self._test_module_has_signatures(codecs, |
| 6138 |
methods_no_signature=methods_no_signature) |
| 6139 |
|
| 6140 |
def test_collections_module_has_signatures(self): |
| 6141 |
no_signature = {'OrderedDict', 'defaultdict'} |
| 6142 |
unsupported_signature = {'deque'} |
| 6143 |
methods_no_signature = { |
| 6144 |
'OrderedDict': {'update'}, |
| 6145 |
} |
| 6146 |
methods_unsupported_signature = { |
| 6147 |
'deque': {'index'}, |
| 6148 |
'OrderedDict': {'pop'}, |
| 6149 |
'UserString': {'maketrans'}, |
| 6150 |
} |
| 6151 |
self._test_module_has_signatures(collections, |
| 6152 |
no_signature, unsupported_signature, |
| 6153 |
methods_no_signature, methods_unsupported_signature) |
| 6154 |
|
| 6155 |
def test_collections_abc_module_has_signatures(self): |
| 6156 |
import collections.abc |
| 6157 |
self._test_module_has_signatures(collections.abc) |
| 6158 |
|
| 6159 |
def test_errno_module_has_signatures(self): |
| 6160 |
import errno |
| 6161 |
self._test_module_has_signatures(errno) |
| 6162 |
|
| 6163 |
def test_faulthandler_module_has_signatures(self): |
| 6164 |
import faulthandler |
| 6165 |
unsupported_signature = {'dump_traceback', 'dump_traceback_later', 'enable', 'dump_c_stack'} |
| 6166 |
unsupported_signature |= {name for name in ['register'] |
| 6167 |
if hasattr(faulthandler, name)} |
| 6168 |
self._test_module_has_signatures(faulthandler, unsupported_signature=unsupported_signature) |
| 6169 |
|
| 6170 |
def test_functools_module_has_signatures(self): |
| 6171 |
unsupported_signature = {"reduce"} |
| 6172 |
self._test_module_has_signatures(functools, unsupported_signature=unsupported_signature) |
| 6173 |
|
| 6174 |
def test_gc_module_has_signatures(self): |
| 6175 |
import gc |
| 6176 |
no_signature = {'set_threshold'} |
| 6177 |
self._test_module_has_signatures(gc, no_signature) |
| 6178 |
|
| 6179 |
def test_io_module_has_signatures(self): |
| 6180 |
methods_no_signature = { |
| 6181 |
'BufferedRWPair': {'read', 'peek', 'read1', 'readinto', 'readinto1', 'write'}, |
| 6182 |
} |
| 6183 |
self._test_module_has_signatures(io, |
| 6184 |
methods_no_signature=methods_no_signature) |
| 6185 |
|
| 6186 |
def test_itertools_module_has_signatures(self): |
| 6187 |
import itertools |
| 6188 |
no_signature = {'islice', 'repeat'} |
| 6189 |
self._test_module_has_signatures(itertools, no_signature) |
| 6190 |
|
| 6191 |
def test_locale_module_has_signatures(self): |
| 6192 |
import locale |
| 6193 |
self._test_module_has_signatures(locale) |
| 6194 |
|
| 6195 |
def test_marshal_module_has_signatures(self): |
| 6196 |
import marshal |
| 6197 |
self._test_module_has_signatures(marshal) |
| 6198 |
|
| 6199 |
def test_operator_module_has_signatures(self): |
| 6200 |
import operator |
| 6201 |
self._test_module_has_signatures(operator) |
| 6202 |
|
| 6203 |
def test_os_module_has_signatures(self): |
| 6204 |
unsupported_signature = {'chmod', 'utime'} |
| 6205 |
unsupported_signature |= {name for name in |
| 6206 |
['get_terminal_size', 'link', 'register_at_fork', 'startfile'] |
| 6207 |
if hasattr(os, name)} |
| 6208 |
self._test_module_has_signatures(os, unsupported_signature=unsupported_signature) |
| 6209 |
|
| 6210 |
def test_pwd_module_has_signatures(self): |
| 6211 |
pwd = import_helper.import_module('pwd') |
| 6212 |
self._test_module_has_signatures(pwd) |
| 6213 |
|
| 6214 |
def test_re_module_has_signatures(self): |
| 6215 |
import re |
| 6216 |
methods_no_signature = {'Match': {'group'}} |
| 6217 |
self._test_module_has_signatures(re, |
| 6218 |
methods_no_signature=methods_no_signature, |
| 6219 |
good_exceptions={'error', 'PatternError'}) |
| 6220 |
|
| 6221 |
def test_signal_module_has_signatures(self): |
| 6222 |
import signal |
| 6223 |
self._test_module_has_signatures(signal) |
| 6224 |
|
| 6225 |
def test_stat_module_has_signatures(self): |
| 6226 |
import stat |
| 6227 |
self._test_module_has_signatures(stat) |
| 6228 |
|
| 6229 |
def test_string_module_has_signatures(self): |
| 6230 |
import string |
| 6231 |
self._test_module_has_signatures(string) |
| 6232 |
|
| 6233 |
def test_symtable_module_has_signatures(self): |
| 6234 |
import symtable |
| 6235 |
self._test_module_has_signatures(symtable) |
| 6236 |
|
| 6237 |
def test_sysconfig_module_has_signatures(self): |
| 6238 |
import sysconfig |
| 6239 |
self._test_module_has_signatures(sysconfig) |
| 6240 |
|
| 6241 |
def test_threading_module_has_signatures(self): |
| 6242 |
import threading |
| 6243 |
self._test_module_has_signatures(threading) |
| 6244 |
self.assertIsNotNone(inspect.signature(threading.__excepthook__)) |
| 6245 |
|
| 6246 |
def test_thread_module_has_signatures(self): |
| 6247 |
import _thread |
| 6248 |
no_signature = {'RLock'} |
| 6249 |
self._test_module_has_signatures(_thread, no_signature) |
| 6250 |
|
| 6251 |
def test_time_module_has_signatures(self): |
| 6252 |
no_signature = { |
| 6253 |
'asctime', 'ctime', 'get_clock_info', 'gmtime', 'localtime', |
| 6254 |
'strftime', 'strptime' |
| 6255 |
} |
| 6256 |
no_signature |= {name for name in |
| 6257 |
['clock_getres', 'clock_settime', 'clock_settime_ns', |
| 6258 |
'pthread_getcpuclockid'] |
| 6259 |
if hasattr(time, name)} |
| 6260 |
self._test_module_has_signatures(time, no_signature) |
| 6261 |
|
| 6262 |
def test_tokenize_module_has_signatures(self): |
| 6263 |
import tokenize |
| 6264 |
self._test_module_has_signatures(tokenize) |
| 6265 |
|
| 6266 |
def test_tracemalloc_module_has_signatures(self): |
| 6267 |
import tracemalloc |
| 6268 |
self._test_module_has_signatures(tracemalloc) |
| 6269 |
|
| 6270 |
def test_typing_module_has_signatures(self): |
| 6271 |
import typing |
| 6272 |
no_signature = {'ParamSpec', 'ParamSpecArgs', 'ParamSpecKwargs', |
| 6273 |
'Text', 'TypeAliasType', 'TypeVar', 'TypeVarTuple'} |
| 6274 |
methods_no_signature = { |
| 6275 |
'Generic': {'__class_getitem__', '__init_subclass__'}, |
| 6276 |
} |
| 6277 |
methods_unsupported_signature = { |
| 6278 |
'Text': {'count', 'find', 'index', 'rfind', 'rindex', 'startswith', 'endswith', 'maketrans'}, |
| 6279 |
} |
| 6280 |
self._test_module_has_signatures(typing, no_signature, |
| 6281 |
methods_no_signature=methods_no_signature, |
| 6282 |
methods_unsupported_signature=methods_unsupported_signature) |
| 6283 |
|
| 6284 |
def test_warnings_module_has_signatures(self): |
| 6285 |
unsupported_signature = {'warn', 'warn_explicit'} |
| 6286 |
self._test_module_has_signatures(warnings, unsupported_signature=unsupported_signature) |
| 6287 |
|
| 6288 |
def test_weakref_module_has_signatures(self): |
| 6289 |
import weakref |
| 6290 |
no_signature = {'ReferenceType', 'ref'} |
| 6291 |
self._test_module_has_signatures(weakref, no_signature) |
| 6292 |
|
| 6293 |
def test_python_function_override_signature(self): |
| 6294 |
def func(*args, **kwargs): |
| 6295 |
pass |
| 6296 |
func.__text_signature__ = '($self, a, b=1, *args, c, d=2, **kwargs)' |
| 6297 |
sig = inspect.signature(func) |
| 6298 |
self.assertIsNotNone(sig) |
| 6299 |
self.assertEqual(str(sig), '(self, /, a, b=1, *args, c, d=2, **kwargs)') |
| 6300 |
|
| 6301 |
func.__text_signature__ = '($self, a, b=1, /, *args, c, d=2, **kwargs)' |
| 6302 |
sig = inspect.signature(func) |
| 6303 |
self.assertEqual(str(sig), '(self, a, b=1, /, *args, c, d=2, **kwargs)') |
| 6304 |
|
| 6305 |
func.__text_signature__ = '(self, a=1+2, b=4-3, c=1 | 3 | 16)' |
| 6306 |
sig = inspect.signature(func) |
| 6307 |
self.assertEqual(str(sig), '(self, a=3, b=1, c=19)') |
| 6308 |
|
| 6309 |
func.__text_signature__ = '(self, a=1,\nb=2,\n\n\n c=3)' |
| 6310 |
sig = inspect.signature(func) |
| 6311 |
self.assertEqual(str(sig), '(self, a=1, b=2, c=3)') |
| 6312 |
|
| 6313 |
func.__text_signature__ = '(self, x=does_not_exist)' |
| 6314 |
with self.assertRaises(ValueError): |
| 6315 |
inspect.signature(func) |
| 6316 |
func.__text_signature__ = '(self, x=sys, y=inspect)' |
| 6317 |
with self.assertRaises(ValueError): |
| 6318 |
inspect.signature(func) |
| 6319 |
func.__text_signature__ = '(self, 123)' |
| 6320 |
with self.assertRaises(ValueError): |
| 6321 |
inspect.signature(func) |
| 6322 |
|
| 6323 |
@support.requires_docstrings |
| 6324 |
def test_base_class_have_text_signature(self): |
| 6325 |
# see issue 43118 |
| 6326 |
from test.typinganndata.ann_module7 import BufferedReader |
| 6327 |
class MyBufferedReader(BufferedReader): |
| 6328 |
"""buffer reader class.""" |
| 6329 |
|
| 6330 |
text_signature = BufferedReader.__text_signature__ |
| 6331 |
self.assertEqual(text_signature, '(raw, buffer_size=DEFAULT_BUFFER_SIZE)') |
| 6332 |
sig = inspect.signature(MyBufferedReader) |
| 6333 |
self.assertEqual(str(sig), '(raw, buffer_size=8192)') |
| 6334 |
|
| 6335 |
|
| 6336 |
class NTimesUnwrappable: |
| 6337 |
def __init__(self, n): |
| 6338 |
self.n = n |
| 6339 |
self._next = None |
| 6340 |
|
| 6341 |
@property |
| 6342 |
def __wrapped__(self): |
| 6343 |
if self.n <= 0: |
| 6344 |
raise Exception("Unwrapped too many times") |
| 6345 |
if self._next is None: |
| 6346 |
self._next = NTimesUnwrappable(self.n - 1) |
| 6347 |
return self._next |
| 6348 |
|
| 6349 |
class TestUnwrap(unittest.TestCase): |
| 6350 |
|
| 6351 |
def test_unwrap_one(self): |
| 6352 |
def func(a, b): |
| 6353 |
return a + b |
| 6354 |
wrapper = functools.lru_cache(maxsize=20)(func) |
| 6355 |
self.assertIs(inspect.unwrap(wrapper), func) |
| 6356 |
|
| 6357 |
def test_unwrap_several(self): |
| 6358 |
def func(a, b): |
| 6359 |
return a + b |
| 6360 |
wrapper = func |
| 6361 |
for __ in range(10): |
| 6362 |
@functools.wraps(wrapper) |
| 6363 |
def wrapper(): |
| 6364 |
pass |
| 6365 |
self.assertIsNot(wrapper.__wrapped__, func) |
| 6366 |
self.assertIs(inspect.unwrap(wrapper), func) |
| 6367 |
|
| 6368 |
def test_stop(self): |
| 6369 |
def func1(a, b): |
| 6370 |
return a + b |
| 6371 |
@functools.wraps(func1) |
| 6372 |
def func2(): |
| 6373 |
pass |
| 6374 |
@functools.wraps(func2) |
| 6375 |
def wrapper(): |
| 6376 |
pass |
| 6377 |
func2.stop_here = 1 |
| 6378 |
unwrapped = inspect.unwrap(wrapper, |
| 6379 |
stop=(lambda f: hasattr(f, "stop_here"))) |
| 6380 |
self.assertIs(unwrapped, func2) |
| 6381 |
|
| 6382 |
def test_cycle(self): |
| 6383 |
def func1(): pass |
| 6384 |
func1.__wrapped__ = func1 |
| 6385 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 6386 |
inspect.unwrap(func1) |
| 6387 |
|
| 6388 |
def func2(): pass |
| 6389 |
func2.__wrapped__ = func1 |
| 6390 |
func1.__wrapped__ = func2 |
| 6391 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 6392 |
inspect.unwrap(func1) |
| 6393 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 6394 |
inspect.unwrap(func2) |
| 6395 |
|
| 6396 |
def test_unhashable(self): |
| 6397 |
def func(): pass |
| 6398 |
func.__wrapped__ = None |
| 6399 |
class C: |
| 6400 |
__hash__ = None |
| 6401 |
__wrapped__ = func |
| 6402 |
self.assertIsNone(inspect.unwrap(C())) |
| 6403 |
|
| 6404 |
def test_recursion_limit(self): |
| 6405 |
obj = NTimesUnwrappable(sys.getrecursionlimit() + 1) |
| 6406 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 6407 |
inspect.unwrap(obj) |
| 6408 |
|
| 6409 |
def test_wrapped_descriptor(self): |
| 6410 |
self.assertIs(inspect.unwrap(NTimesUnwrappable), NTimesUnwrappable) |
| 6411 |
self.assertIs(inspect.unwrap(staticmethod), staticmethod) |
| 6412 |
self.assertIs(inspect.unwrap(classmethod), classmethod) |
| 6413 |
self.assertIs(inspect.unwrap(staticmethod(classmethod)), classmethod) |
| 6414 |
self.assertIs(inspect.unwrap(classmethod(staticmethod)), staticmethod) |
| 6415 |
|
| 6416 |
|
| 6417 |
class TestMain(unittest.TestCase): |
| 6418 |
def test_only_source(self): |
| 6419 |
module = importlib.import_module('unittest') |
| 6420 |
rc, out, err = assert_python_ok('-m', 'inspect', |
| 6421 |
'unittest') |
| 6422 |
lines = out.decode().splitlines() |
| 6423 |
# ignore the final newline |
| 6424 |
self.assertEqual(lines[:-1], inspect.getsource(module).splitlines()) |
| 6425 |
self.assertEqual(err, b'') |
| 6426 |
|
| 6427 |
def test_custom_getattr(self): |
| 6428 |
def foo(): |
| 6429 |
pass |
| 6430 |
foo.__signature__ = 42 |
| 6431 |
with self.assertRaises(TypeError): |
| 6432 |
inspect.signature(foo) |
| 6433 |
|
| 6434 |
@unittest.skipIf(ThreadPoolExecutor is None, |
| 6435 |
'threads required to test __qualname__ for source files') |
| 6436 |
def test_qualname_source(self): |
| 6437 |
rc, out, err = assert_python_ok('-m', 'inspect', |
| 6438 |
'concurrent.futures:ThreadPoolExecutor') |
| 6439 |
lines = out.decode().splitlines() |
| 6440 |
# ignore the final newline |
| 6441 |
self.assertEqual(lines[:-1], |
| 6442 |
inspect.getsource(ThreadPoolExecutor).splitlines()) |
| 6443 |
self.assertEqual(err, b'') |
| 6444 |
|
| 6445 |
def test_builtins(self): |
| 6446 |
_, out, err = assert_python_failure('-m', 'inspect', |
| 6447 |
'sys') |
| 6448 |
lines = err.decode().splitlines() |
| 6449 |
self.assertEqual(lines, ["Can't get info for builtin modules."]) |
| 6450 |
|
| 6451 |
def test_details(self): |
| 6452 |
module = importlib.import_module('unittest') |
| 6453 |
args = support.optim_args_from_interpreter_flags() |
| 6454 |
rc, out, err = assert_python_ok(*args, '-m', 'inspect', |
| 6455 |
'unittest', '--details') |
| 6456 |
output = out.decode() |
| 6457 |
# Just a quick sanity check on the output |
| 6458 |
self.assertIn(module.__spec__.name, output) |
| 6459 |
self.assertIn(module.__name__, output) |
| 6460 |
self.assertIn(module.__spec__.origin, output) |
| 6461 |
self.assertIn(module.__file__, output) |
| 6462 |
self.assertIn(module.__spec__.cached, output) |
| 6463 |
self.assertIn(module.__cached__, output) |
| 6464 |
self.assertEqual(err, b'') |
| 6465 |
|
| 6466 |
|
| 6467 |
class TestReload(unittest.TestCase): |
| 6468 |
|
| 6469 |
src_before = textwrap.dedent("""\ |
| 6470 |
def foo(): |
| 6471 |
print("Bla") |
| 6472 |
""") |
| 6473 |
|
| 6474 |
src_after = textwrap.dedent("""\ |
| 6475 |
def foo(): |
| 6476 |
print("Oh no!") |
| 6477 |
""") |
| 6478 |
|
| 6479 |
def assertInspectEqual(self, path, source): |
| 6480 |
inspected_src = inspect.getsource(source) |
| 6481 |
with open(path, encoding='utf-8') as src: |
| 6482 |
self.assertEqual( |
| 6483 |
src.read().splitlines(True), |
| 6484 |
inspected_src.splitlines(True) |
| 6485 |
) |
| 6486 |
|
| 6487 |
def test_getsource_reload(self): |
| 6488 |
# see issue 1218234 |
| 6489 |
with ready_to_import('reload_bug', self.src_before) as (name, path): |
| 6490 |
module = importlib.import_module(name) |
| 6491 |
self.assertInspectEqual(path, module) |
| 6492 |
with open(path, 'w', encoding='utf-8') as src: |
| 6493 |
src.write(self.src_after) |
| 6494 |
self.assertInspectEqual(path, module) |
| 6495 |
|
| 6496 |
|
| 6497 |
class TestRepl(unittest.TestCase): |
| 6498 |
|
| 6499 |
def spawn_repl(self, *args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw): |
| 6500 |
"""Run the Python REPL with the given arguments. |
| 6501 |
|
| 6502 |
kw is extra keyword args to pass to subprocess.Popen. Returns a Popen |
| 6503 |
object. |
| 6504 |
""" |
| 6505 |
|
| 6506 |
# To run the REPL without using a terminal, spawn python with the command |
| 6507 |
# line option '-i' and the process name set to '<stdin>'. |
| 6508 |
# The directory of argv[0] must match the directory of the Python |
| 6509 |
# executable for the Popen() call to python to succeed as the directory |
| 6510 |
# path may be used by Py_GetPath() to build the default module search |
| 6511 |
# path. |
| 6512 |
stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>") |
| 6513 |
cmd_line = [stdin_fname, '-E', '-i'] |
| 6514 |
cmd_line.extend(args) |
| 6515 |
|
| 6516 |
# Set TERM=vt100, for the rationale see the comments in spawn_python() of |
| 6517 |
# test.support.script_helper. |
| 6518 |
env = kw.setdefault('env', dict(os.environ)) |
| 6519 |
env['TERM'] = 'vt100' |
| 6520 |
return subprocess.Popen(cmd_line, |
| 6521 |
executable=sys.executable, |
| 6522 |
text=True, |
| 6523 |
stdin=subprocess.PIPE, |
| 6524 |
stdout=stdout, stderr=stderr, |
| 6525 |
**kw) |
| 6526 |
|
| 6527 |
def run_on_interactive_mode(self, source): |
| 6528 |
"""Spawn a new Python interpreter, pass the given |
| 6529 |
input source code from the stdin and return the |
| 6530 |
result back. If the interpreter exits non-zero, it |
| 6531 |
raises a ValueError.""" |
| 6532 |
|
| 6533 |
process = self.spawn_repl() |
| 6534 |
process.stdin.write(source) |
| 6535 |
output = kill_python(process) |
| 6536 |
|
| 6537 |
if process.returncode != 0: |
| 6538 |
raise ValueError("Process didn't exit properly.") |
| 6539 |
return output |
| 6540 |
|
| 6541 |
@unittest.skipIf(not has_subprocess_support, "test requires subprocess") |
| 6542 |
def test_getsource(self): |
| 6543 |
output = self.run_on_interactive_mode(textwrap.dedent("""\ |
| 6544 |
def f(): |
| 6545 |
print(0) |
| 6546 |
return 1 + 2 |
| 6547 |
|
| 6548 |
import inspect |
| 6549 |
print(f"The source is: <<<{inspect.getsource(f)}>>>") |
| 6550 |
""")) |
| 6551 |
|
| 6552 |
expected = "The source is: <<<def f():\n print(0)\n return 1 + 2\n>>>" |
| 6553 |
self.assertIn(expected, output) |
| 6554 |
|
| 6555 |
|
| 6556 |
|
| 6557 |
|
| 6558 |
if __name__ == "__main__": |
| 6559 |
unittest.main() |