| 1 |
import builtins |
| 2 |
import collections |
| 3 |
import datetime |
| 4 |
import functools |
| 5 |
import importlib |
| 6 |
import inspect |
| 7 |
import io |
| 8 |
import linecache |
| 9 |
import os |
| 10 |
import dis |
| 11 |
from os.path import normcase |
| 12 |
import pickle |
| 13 |
try: |
| 14 |
import _pickle |
| 15 |
except ModuleNotFoundError: |
| 16 |
_pickle = pickle |
| 17 |
import shutil |
| 18 |
import sys |
| 19 |
import types |
| 20 |
import textwrap |
| 21 |
import unicodedata |
| 22 |
import unittest |
| 23 |
import unittest.mock |
| 24 |
import warnings |
| 25 |
|
| 26 |
try: |
| 27 |
from concurrent.futures import ThreadPoolExecutor |
| 28 |
except ImportError: |
| 29 |
ThreadPoolExecutor = None |
| 30 |
|
| 31 |
from test.support import cpython_only |
| 32 |
from test.support import MISSING_C_DOCSTRINGS, ALWAYS_EQ |
| 33 |
from test.support.import_helper import DirsOnSysPath, ready_to_import |
| 34 |
from test.support.os_helper import TESTFN |
| 35 |
from test.support.script_helper import assert_python_ok, assert_python_failure |
| 36 |
from test import support |
| 37 |
|
| 38 |
from test.test_inspect import inspect_fodder as mod |
| 39 |
from test.test_inspect import inspect_fodder2 as mod2 |
| 40 |
from test.test_inspect import inspect_stock_annotations |
| 41 |
from test.test_inspect import inspect_stringized_annotations |
| 42 |
from test.test_inspect import inspect_stringized_annotations_2 |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
modfile = mod.__file__ |
| 57 |
if modfile.endswith(('c', 'o')): |
| 58 |
modfile = modfile[:-1] |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
modfile = normcase(modfile) |
| 63 |
|
| 64 |
def revise(filename, *args): |
| 65 |
return (normcase(filename),) + args |
| 66 |
|
| 67 |
git = mod.StupidGit() |
| 68 |
|
| 69 |
|
| 70 |
def signatures_with_lexicographic_keyword_only_parameters(): |
| 71 |
""" |
| 72 |
Yields a whole bunch of functions with only keyword-only parameters, |
| 73 |
where those parameters are always in lexicographically sorted order. |
| 74 |
""" |
| 75 |
parameters = ['a', 'bar', 'c', 'delta', 'ephraim', 'magical', 'yoyo', 'z'] |
| 76 |
for i in range(1, 2**len(parameters)): |
| 77 |
p = [] |
| 78 |
bit = 1 |
| 79 |
for j in range(len(parameters)): |
| 80 |
if i & (bit << j): |
| 81 |
p.append(parameters[j]) |
| 82 |
fn_text = "def foo(*, " + ", ".join(p) + "): pass" |
| 83 |
symbols = {} |
| 84 |
exec(fn_text, symbols, symbols) |
| 85 |
yield symbols['foo'] |
| 86 |
|
| 87 |
|
| 88 |
def unsorted_keyword_only_parameters_fn(*, throw, out, the, baby, with_, |
| 89 |
the_, bathwater): |
| 90 |
pass |
| 91 |
|
| 92 |
unsorted_keyword_only_parameters = 'throw out the baby with_ the_ bathwater'.split() |
| 93 |
|
| 94 |
class IsTestBase(unittest.TestCase): |
| 95 |
predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, |
| 96 |
inspect.isframe, inspect.isfunction, inspect.ismethod, |
| 97 |
inspect.ismodule, inspect.istraceback, |
| 98 |
inspect.isgenerator, inspect.isgeneratorfunction, |
| 99 |
inspect.iscoroutine, inspect.iscoroutinefunction, |
| 100 |
inspect.isasyncgen, inspect.isasyncgenfunction, |
| 101 |
inspect.ismethodwrapper]) |
| 102 |
|
| 103 |
def istest(self, predicate, exp): |
| 104 |
obj = eval(exp) |
| 105 |
self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) |
| 106 |
|
| 107 |
for other in self.predicates - set([predicate]): |
| 108 |
if (predicate == inspect.isgeneratorfunction or \ |
| 109 |
predicate == inspect.isasyncgenfunction or \ |
| 110 |
predicate == inspect.iscoroutinefunction) and \ |
| 111 |
other == inspect.isfunction: |
| 112 |
continue |
| 113 |
self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) |
| 114 |
|
| 115 |
def test__all__(self): |
| 116 |
support.check__all__(self, inspect, not_exported=("modulesbyfile",)) |
| 117 |
|
| 118 |
def generator_function_example(self): |
| 119 |
for i in range(2): |
| 120 |
yield i |
| 121 |
|
| 122 |
async def async_generator_function_example(self): |
| 123 |
async for i in range(2): |
| 124 |
yield i |
| 125 |
|
| 126 |
async def coroutine_function_example(self): |
| 127 |
return 'spam' |
| 128 |
|
| 129 |
@types.coroutine |
| 130 |
def gen_coroutine_function_example(self): |
| 131 |
yield |
| 132 |
return 'spam' |
| 133 |
|
| 134 |
class TestPredicates(IsTestBase): |
| 135 |
|
| 136 |
def test_excluding_predicates(self): |
| 137 |
global tb |
| 138 |
self.istest(inspect.isbuiltin, 'sys.exit') |
| 139 |
self.istest(inspect.isbuiltin, '[].append') |
| 140 |
self.istest(inspect.iscode, 'mod.spam.__code__') |
| 141 |
try: |
| 142 |
1/0 |
| 143 |
except Exception as e: |
| 144 |
tb = e.__traceback__ |
| 145 |
self.istest(inspect.isframe, 'tb.tb_frame') |
| 146 |
self.istest(inspect.istraceback, 'tb') |
| 147 |
if hasattr(types, 'GetSetDescriptorType'): |
| 148 |
self.istest(inspect.isgetsetdescriptor, |
| 149 |
'type(tb.tb_frame).f_locals') |
| 150 |
else: |
| 151 |
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) |
| 152 |
finally: |
| 153 |
|
| 154 |
tb = None |
| 155 |
self.istest(inspect.isfunction, 'mod.spam') |
| 156 |
self.istest(inspect.isfunction, 'mod.StupidGit.abuse') |
| 157 |
self.istest(inspect.ismethod, 'git.argue') |
| 158 |
self.istest(inspect.ismethod, 'mod.custom_method') |
| 159 |
self.istest(inspect.ismodule, 'mod') |
| 160 |
self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory') |
| 161 |
self.istest(inspect.isgenerator, '(x for x in range(2))') |
| 162 |
self.istest(inspect.isgeneratorfunction, 'generator_function_example') |
| 163 |
self.istest(inspect.isasyncgen, |
| 164 |
'async_generator_function_example(1)') |
| 165 |
self.istest(inspect.isasyncgenfunction, |
| 166 |
'async_generator_function_example') |
| 167 |
|
| 168 |
with warnings.catch_warnings(): |
| 169 |
warnings.simplefilter("ignore") |
| 170 |
self.istest(inspect.iscoroutine, 'coroutine_function_example(1)') |
| 171 |
self.istest(inspect.iscoroutinefunction, 'coroutine_function_example') |
| 172 |
|
| 173 |
if hasattr(types, 'MemberDescriptorType') and isinstance(datetime.timedelta.days, types.MemberDescriptorType): |
| 174 |
self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') |
| 175 |
else: |
| 176 |
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) |
| 177 |
self.assertFalse(inspect.ismethodwrapper(type)) |
| 178 |
self.assertFalse(inspect.ismethodwrapper(int)) |
| 179 |
self.assertFalse(inspect.ismethodwrapper(type("AnyClass", (), {}))) |
| 180 |
|
| 181 |
@cpython_only |
| 182 |
def test_ismethodwrapper(self): |
| 183 |
self.istest(inspect.ismethodwrapper, "object().__str__") |
| 184 |
self.istest(inspect.ismethodwrapper, "object().__eq__") |
| 185 |
self.istest(inspect.ismethodwrapper, "object().__repr__") |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
def test_iscoroutine(self): |
| 190 |
async_gen_coro = async_generator_function_example(1) |
| 191 |
gen_coro = gen_coroutine_function_example(1) |
| 192 |
coro = coroutine_function_example(1) |
| 193 |
|
| 194 |
self.assertFalse( |
| 195 |
inspect.iscoroutinefunction(gen_coroutine_function_example)) |
| 196 |
self.assertFalse( |
| 197 |
inspect.iscoroutinefunction( |
| 198 |
functools.partial(functools.partial( |
| 199 |
gen_coroutine_function_example)))) |
| 200 |
self.assertFalse(inspect.iscoroutine(gen_coro)) |
| 201 |
|
| 202 |
self.assertTrue( |
| 203 |
inspect.isgeneratorfunction(gen_coroutine_function_example)) |
| 204 |
self.assertTrue( |
| 205 |
inspect.isgeneratorfunction( |
| 206 |
functools.partial(functools.partial( |
| 207 |
gen_coroutine_function_example)))) |
| 208 |
self.assertTrue(inspect.isgenerator(gen_coro)) |
| 209 |
|
| 210 |
self.assertFalse( |
| 211 |
inspect.iscoroutinefunction(unittest.mock.Mock())) |
| 212 |
self.assertTrue( |
| 213 |
inspect.iscoroutinefunction(unittest.mock.AsyncMock())) |
| 214 |
self.assertTrue( |
| 215 |
inspect.iscoroutinefunction(coroutine_function_example)) |
| 216 |
self.assertTrue( |
| 217 |
inspect.iscoroutinefunction( |
| 218 |
functools.partial(functools.partial( |
| 219 |
coroutine_function_example)))) |
| 220 |
self.assertTrue(inspect.iscoroutine(coro)) |
| 221 |
|
| 222 |
self.assertFalse( |
| 223 |
inspect.isgeneratorfunction(unittest.mock.Mock())) |
| 224 |
self.assertFalse( |
| 225 |
inspect.isgeneratorfunction(unittest.mock.AsyncMock())) |
| 226 |
self.assertFalse( |
| 227 |
inspect.isgeneratorfunction(coroutine_function_example)) |
| 228 |
self.assertFalse( |
| 229 |
inspect.isgeneratorfunction( |
| 230 |
functools.partial(functools.partial( |
| 231 |
coroutine_function_example)))) |
| 232 |
self.assertFalse(inspect.isgenerator(coro)) |
| 233 |
|
| 234 |
self.assertFalse( |
| 235 |
inspect.isasyncgenfunction(unittest.mock.Mock())) |
| 236 |
self.assertFalse( |
| 237 |
inspect.isasyncgenfunction(unittest.mock.AsyncMock())) |
| 238 |
self.assertFalse( |
| 239 |
inspect.isasyncgenfunction(coroutine_function_example)) |
| 240 |
self.assertTrue( |
| 241 |
inspect.isasyncgenfunction(async_generator_function_example)) |
| 242 |
self.assertTrue( |
| 243 |
inspect.isasyncgenfunction( |
| 244 |
functools.partial(functools.partial( |
| 245 |
async_generator_function_example)))) |
| 246 |
self.assertTrue(inspect.isasyncgen(async_gen_coro)) |
| 247 |
|
| 248 |
coro.close(); gen_coro.close(); |
| 249 |
|
| 250 |
def test_isawaitable(self): |
| 251 |
def gen(): yield |
| 252 |
self.assertFalse(inspect.isawaitable(gen())) |
| 253 |
|
| 254 |
coro = coroutine_function_example(1) |
| 255 |
gen_coro = gen_coroutine_function_example(1) |
| 256 |
|
| 257 |
self.assertTrue(inspect.isawaitable(coro)) |
| 258 |
self.assertTrue(inspect.isawaitable(gen_coro)) |
| 259 |
|
| 260 |
class Future: |
| 261 |
def __await__(): |
| 262 |
pass |
| 263 |
self.assertTrue(inspect.isawaitable(Future())) |
| 264 |
self.assertFalse(inspect.isawaitable(Future)) |
| 265 |
|
| 266 |
class NotFuture: pass |
| 267 |
not_fut = NotFuture() |
| 268 |
not_fut.__await__ = lambda: None |
| 269 |
self.assertFalse(inspect.isawaitable(not_fut)) |
| 270 |
|
| 271 |
coro.close(); gen_coro.close() |
| 272 |
|
| 273 |
def test_isroutine(self): |
| 274 |
|
| 275 |
self.assertTrue(inspect.isroutine(git.argue)) |
| 276 |
self.assertTrue(inspect.isroutine(mod.custom_method)) |
| 277 |
self.assertTrue(inspect.isroutine([].count)) |
| 278 |
|
| 279 |
self.assertTrue(inspect.isroutine(mod.spam)) |
| 280 |
self.assertTrue(inspect.isroutine(mod.StupidGit.abuse)) |
| 281 |
|
| 282 |
self.assertTrue(inspect.isroutine(object.__init__)) |
| 283 |
self.assertTrue(inspect.isroutine(object.__str__)) |
| 284 |
self.assertTrue(inspect.isroutine(object.__lt__)) |
| 285 |
self.assertTrue(inspect.isroutine(int.__lt__)) |
| 286 |
|
| 287 |
self.assertTrue(inspect.isroutine(object().__init__)) |
| 288 |
self.assertTrue(inspect.isroutine(object().__str__)) |
| 289 |
self.assertTrue(inspect.isroutine(object().__lt__)) |
| 290 |
self.assertTrue(inspect.isroutine((42).__lt__)) |
| 291 |
|
| 292 |
self.assertTrue(inspect.isroutine(str.join)) |
| 293 |
self.assertTrue(inspect.isroutine(list.append)) |
| 294 |
self.assertTrue(inspect.isroutine(''.join)) |
| 295 |
self.assertTrue(inspect.isroutine([].append)) |
| 296 |
|
| 297 |
self.assertFalse(inspect.isroutine(object)) |
| 298 |
self.assertFalse(inspect.isroutine(object())) |
| 299 |
self.assertFalse(inspect.isroutine(str())) |
| 300 |
|
| 301 |
self.assertFalse(inspect.isroutine(mod)) |
| 302 |
|
| 303 |
self.assertFalse(inspect.isroutine(type)) |
| 304 |
self.assertFalse(inspect.isroutine(int)) |
| 305 |
self.assertFalse(inspect.isroutine(type('some_class', (), {}))) |
| 306 |
|
| 307 |
def test_isclass(self): |
| 308 |
self.istest(inspect.isclass, 'mod.StupidGit') |
| 309 |
self.assertTrue(inspect.isclass(list)) |
| 310 |
|
| 311 |
class CustomGetattr(object): |
| 312 |
def __getattr__(self, attr): |
| 313 |
return None |
| 314 |
self.assertFalse(inspect.isclass(CustomGetattr())) |
| 315 |
|
| 316 |
def test_get_slot_members(self): |
| 317 |
class C(object): |
| 318 |
__slots__ = ("a", "b") |
| 319 |
x = C() |
| 320 |
x.a = 42 |
| 321 |
members = dict(inspect.getmembers(x)) |
| 322 |
self.assertIn('a', members) |
| 323 |
self.assertNotIn('b', members) |
| 324 |
|
| 325 |
def test_isabstract(self): |
| 326 |
from abc import ABCMeta, abstractmethod |
| 327 |
|
| 328 |
class AbstractClassExample(metaclass=ABCMeta): |
| 329 |
|
| 330 |
@abstractmethod |
| 331 |
def foo(self): |
| 332 |
pass |
| 333 |
|
| 334 |
class ClassExample(AbstractClassExample): |
| 335 |
def foo(self): |
| 336 |
pass |
| 337 |
|
| 338 |
a = ClassExample() |
| 339 |
|
| 340 |
|
| 341 |
self.assertTrue(inspect.isabstract(AbstractClassExample)) |
| 342 |
self.assertFalse(inspect.isabstract(ClassExample)) |
| 343 |
self.assertFalse(inspect.isabstract(a)) |
| 344 |
self.assertFalse(inspect.isabstract(int)) |
| 345 |
self.assertFalse(inspect.isabstract(5)) |
| 346 |
|
| 347 |
def test_isabstract_during_init_subclass(self): |
| 348 |
from abc import ABCMeta, abstractmethod |
| 349 |
isabstract_checks = [] |
| 350 |
class AbstractChecker(metaclass=ABCMeta): |
| 351 |
def __init_subclass__(cls): |
| 352 |
isabstract_checks.append(inspect.isabstract(cls)) |
| 353 |
class AbstractClassExample(AbstractChecker): |
| 354 |
@abstractmethod |
| 355 |
def foo(self): |
| 356 |
pass |
| 357 |
class ClassExample(AbstractClassExample): |
| 358 |
def foo(self): |
| 359 |
pass |
| 360 |
self.assertEqual(isabstract_checks, [True, False]) |
| 361 |
|
| 362 |
isabstract_checks.clear() |
| 363 |
class AbstractChild(AbstractClassExample): |
| 364 |
pass |
| 365 |
class AbstractGrandchild(AbstractChild): |
| 366 |
pass |
| 367 |
class ConcreteGrandchild(ClassExample): |
| 368 |
pass |
| 369 |
self.assertEqual(isabstract_checks, [True, True, False]) |
| 370 |
|
| 371 |
|
| 372 |
class TestInterpreterStack(IsTestBase): |
| 373 |
def __init__(self, *args, **kwargs): |
| 374 |
unittest.TestCase.__init__(self, *args, **kwargs) |
| 375 |
|
| 376 |
git.abuse(7, 8, 9) |
| 377 |
|
| 378 |
def test_abuse_done(self): |
| 379 |
self.istest(inspect.istraceback, 'git.ex[2]') |
| 380 |
self.istest(inspect.isframe, 'mod.fr') |
| 381 |
|
| 382 |
@cpython_only |
| 383 |
def test_stack(self): |
| 384 |
self.assertTrue(len(mod.st) >= 5) |
| 385 |
frame1, frame2, frame3, frame4, *_ = mod.st |
| 386 |
frameinfo = revise(*frame1[1:]) |
| 387 |
self.assertEqual(frameinfo, |
| 388 |
(modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) |
| 389 |
self.assertEqual(frame1.positions, dis.Positions(16, 16, 9, 24)) |
| 390 |
frameinfo = revise(*frame2[1:]) |
| 391 |
self.assertEqual(frameinfo, |
| 392 |
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
| 393 |
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22)) |
| 394 |
frameinfo = revise(*frame3[1:]) |
| 395 |
self.assertEqual(frameinfo, |
| 396 |
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
| 397 |
self.assertEqual(frame3.positions, dis.Positions(43, 43, 12, 25)) |
| 398 |
frameinfo = revise(*frame4[1:]) |
| 399 |
self.assertEqual(frameinfo, |
| 400 |
(modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0)) |
| 401 |
self.assertEqual(frame4.positions, dis.Positions(39, 39, 8, 27)) |
| 402 |
|
| 403 |
record = mod.st[0] |
| 404 |
self.assertIs(record.frame, mod.fr) |
| 405 |
self.assertEqual(record.lineno, 16) |
| 406 |
self.assertEqual(record.filename, mod.__file__) |
| 407 |
self.assertEqual(record.function, 'eggs') |
| 408 |
self.assertIn('inspect.stack()', record.code_context[0]) |
| 409 |
self.assertEqual(record.index, 0) |
| 410 |
|
| 411 |
def test_trace(self): |
| 412 |
self.assertEqual(len(git.tr), 3) |
| 413 |
frame1, frame2, frame3, = git.tr |
| 414 |
self.assertEqual(revise(*frame1[1:]), |
| 415 |
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
| 416 |
self.assertEqual(frame1.positions, dis.Positions(43, 43, 12, 25)) |
| 417 |
self.assertEqual(revise(*frame2[1:]), |
| 418 |
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
| 419 |
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22)) |
| 420 |
self.assertEqual(revise(*frame3[1:]), |
| 421 |
(modfile, 18, 'eggs', [' q = y / 0\n'], 0)) |
| 422 |
self.assertEqual(frame3.positions, dis.Positions(18, 18, 8, 13)) |
| 423 |
|
| 424 |
def test_frame(self): |
| 425 |
args, varargs, varkw, locals = inspect.getargvalues(mod.fr) |
| 426 |
self.assertEqual(args, ['x', 'y']) |
| 427 |
self.assertEqual(varargs, None) |
| 428 |
self.assertEqual(varkw, None) |
| 429 |
self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14}) |
| 430 |
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
| 431 |
'(x=11, y=14)') |
| 432 |
|
| 433 |
def test_previous_frame(self): |
| 434 |
args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) |
| 435 |
self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f']) |
| 436 |
self.assertEqual(varargs, 'g') |
| 437 |
self.assertEqual(varkw, 'h') |
| 438 |
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
| 439 |
'(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})') |
| 440 |
|
| 441 |
class GetSourceBase(unittest.TestCase): |
| 442 |
|
| 443 |
fodderModule = None |
| 444 |
|
| 445 |
def setUp(self): |
| 446 |
with open(inspect.getsourcefile(self.fodderModule), encoding="utf-8") as fp: |
| 447 |
self.source = fp.read() |
| 448 |
|
| 449 |
def sourcerange(self, top, bottom): |
| 450 |
lines = self.source.split("\n") |
| 451 |
return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "") |
| 452 |
|
| 453 |
def assertSourceEqual(self, obj, top, bottom): |
| 454 |
self.assertEqual(inspect.getsource(obj), |
| 455 |
self.sourcerange(top, bottom)) |
| 456 |
|
| 457 |
class SlotUser: |
| 458 |
'Docstrings for __slots__' |
| 459 |
__slots__ = {'power': 'measured in kilowatts', |
| 460 |
'distance': 'measured in kilometers'} |
| 461 |
|
| 462 |
class TestRetrievingSourceCode(GetSourceBase): |
| 463 |
fodderModule = mod |
| 464 |
|
| 465 |
def test_getclasses(self): |
| 466 |
classes = inspect.getmembers(mod, inspect.isclass) |
| 467 |
self.assertEqual(classes, |
| 468 |
[('FesteringGob', mod.FesteringGob), |
| 469 |
('MalodorousPervert', mod.MalodorousPervert), |
| 470 |
('ParrotDroppings', mod.ParrotDroppings), |
| 471 |
('StupidGit', mod.StupidGit), |
| 472 |
('Tit', mod.MalodorousPervert), |
| 473 |
('WhichComments', mod.WhichComments), |
| 474 |
]) |
| 475 |
tree = inspect.getclasstree([cls[1] for cls in classes]) |
| 476 |
self.assertEqual(tree, |
| 477 |
[(object, ()), |
| 478 |
[(mod.ParrotDroppings, (object,)), |
| 479 |
[(mod.FesteringGob, (mod.MalodorousPervert, |
| 480 |
mod.ParrotDroppings)) |
| 481 |
], |
| 482 |
(mod.StupidGit, (object,)), |
| 483 |
[(mod.MalodorousPervert, (mod.StupidGit,)), |
| 484 |
[(mod.FesteringGob, (mod.MalodorousPervert, |
| 485 |
mod.ParrotDroppings)) |
| 486 |
] |
| 487 |
], |
| 488 |
(mod.WhichComments, (object,),) |
| 489 |
] |
| 490 |
]) |
| 491 |
tree = inspect.getclasstree([cls[1] for cls in classes], True) |
| 492 |
self.assertEqual(tree, |
| 493 |
[(object, ()), |
| 494 |
[(mod.ParrotDroppings, (object,)), |
| 495 |
(mod.StupidGit, (object,)), |
| 496 |
[(mod.MalodorousPervert, (mod.StupidGit,)), |
| 497 |
[(mod.FesteringGob, (mod.MalodorousPervert, |
| 498 |
mod.ParrotDroppings)) |
| 499 |
] |
| 500 |
], |
| 501 |
(mod.WhichComments, (object,),) |
| 502 |
] |
| 503 |
]) |
| 504 |
|
| 505 |
def test_getfunctions(self): |
| 506 |
functions = inspect.getmembers(mod, inspect.isfunction) |
| 507 |
self.assertEqual(functions, [('eggs', mod.eggs), |
| 508 |
('lobbest', mod.lobbest), |
| 509 |
('spam', mod.spam)]) |
| 510 |
|
| 511 |
@unittest.skipIf(sys.flags.optimize >= 2, |
| 512 |
"Docstrings are omitted with -O2 and above") |
| 513 |
def test_getdoc(self): |
| 514 |
self.assertEqual(inspect.getdoc(mod), 'A module docstring.') |
| 515 |
self.assertEqual(inspect.getdoc(mod.StupidGit), |
| 516 |
'A longer,\n\nindented\n\ndocstring.') |
| 517 |
self.assertEqual(inspect.getdoc(git.abuse), |
| 518 |
'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 519 |
self.assertEqual(inspect.getdoc(SlotUser.power), |
| 520 |
'measured in kilowatts') |
| 521 |
self.assertEqual(inspect.getdoc(SlotUser.distance), |
| 522 |
'measured in kilometers') |
| 523 |
|
| 524 |
@unittest.skipIf(sys.flags.optimize >= 2, |
| 525 |
"Docstrings are omitted with -O2 and above") |
| 526 |
def test_getdoc_inherited(self): |
| 527 |
self.assertEqual(inspect.getdoc(mod.FesteringGob), |
| 528 |
'A longer,\n\nindented\n\ndocstring.') |
| 529 |
self.assertEqual(inspect.getdoc(mod.FesteringGob.abuse), |
| 530 |
'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 531 |
self.assertEqual(inspect.getdoc(mod.FesteringGob().abuse), |
| 532 |
'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 533 |
self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction), |
| 534 |
'The automatic gainsaying.') |
| 535 |
|
| 536 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings") |
| 537 |
def test_finddoc(self): |
| 538 |
finddoc = inspect._finddoc |
| 539 |
self.assertEqual(finddoc(int), int.__doc__) |
| 540 |
self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__) |
| 541 |
self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__) |
| 542 |
self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__) |
| 543 |
self.assertEqual(finddoc(int.real), int.real.__doc__) |
| 544 |
|
| 545 |
def test_cleandoc(self): |
| 546 |
self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'), |
| 547 |
'An\nindented\ndocstring.') |
| 548 |
|
| 549 |
def test_getcomments(self): |
| 550 |
self.assertEqual(inspect.getcomments(mod), '# line 1\n') |
| 551 |
self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') |
| 552 |
self.assertEqual(inspect.getcomments(mod2.cls160), '# line 159\n') |
| 553 |
|
| 554 |
co = compile('x=1', '_non_existing_filename.py', 'exec') |
| 555 |
self.assertIsNone(inspect.getcomments(co)) |
| 556 |
|
| 557 |
self.assertIsNone(inspect.getcomments(list)) |
| 558 |
|
| 559 |
def test_getmodule(self): |
| 560 |
|
| 561 |
self.assertEqual(inspect.getmodule(mod), mod) |
| 562 |
|
| 563 |
self.assertEqual(inspect.getmodule(mod.StupidGit), mod) |
| 564 |
|
| 565 |
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
| 566 |
|
| 567 |
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
| 568 |
|
| 569 |
self.assertEqual(inspect.getmodule(str), sys.modules["builtins"]) |
| 570 |
|
| 571 |
self.assertEqual(inspect.getmodule(None, modfile), mod) |
| 572 |
|
| 573 |
def test_getmodule_file_not_found(self): |
| 574 |
|
| 575 |
def _getabsfile(obj, _filename): |
| 576 |
raise FileNotFoundError('bad file') |
| 577 |
with unittest.mock.patch('inspect.getabsfile', _getabsfile): |
| 578 |
f = inspect.currentframe() |
| 579 |
self.assertIsNone(inspect.getmodule(f)) |
| 580 |
inspect.getouterframes(f) |
| 581 |
|
| 582 |
def test_getframeinfo_get_first_line(self): |
| 583 |
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50) |
| 584 |
self.assertEqual(frame_info.code_context[0], "# line 1\n") |
| 585 |
self.assertEqual(frame_info.code_context[1], "'A module docstring.'\n") |
| 586 |
|
| 587 |
def test_getsource(self): |
| 588 |
self.assertSourceEqual(git.abuse, 29, 39) |
| 589 |
self.assertSourceEqual(mod.StupidGit, 21, 51) |
| 590 |
self.assertSourceEqual(mod.lobbest, 75, 76) |
| 591 |
|
| 592 |
def test_getsourcefile(self): |
| 593 |
self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile) |
| 594 |
self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile) |
| 595 |
fn = "_non_existing_filename_used_for_sourcefile_test.py" |
| 596 |
co = compile("x=1", fn, "exec") |
| 597 |
self.assertEqual(inspect.getsourcefile(co), None) |
| 598 |
linecache.cache[co.co_filename] = (1, None, "None", co.co_filename) |
| 599 |
try: |
| 600 |
self.assertEqual(normcase(inspect.getsourcefile(co)), fn) |
| 601 |
finally: |
| 602 |
del linecache.cache[co.co_filename] |
| 603 |
|
| 604 |
def test_getfile(self): |
| 605 |
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) |
| 606 |
|
| 607 |
def test_getfile_builtin_module(self): |
| 608 |
with self.assertRaises(TypeError) as e: |
| 609 |
inspect.getfile(sys) |
| 610 |
self.assertTrue(str(e.exception).startswith('<module')) |
| 611 |
|
| 612 |
def test_getfile_builtin_class(self): |
| 613 |
with self.assertRaises(TypeError) as e: |
| 614 |
inspect.getfile(int) |
| 615 |
self.assertTrue(str(e.exception).startswith('<class')) |
| 616 |
|
| 617 |
def test_getfile_builtin_function_or_method(self): |
| 618 |
with self.assertRaises(TypeError) as e_abs: |
| 619 |
inspect.getfile(abs) |
| 620 |
self.assertIn('expected, got', str(e_abs.exception)) |
| 621 |
with self.assertRaises(TypeError) as e_append: |
| 622 |
inspect.getfile(list.append) |
| 623 |
self.assertIn('expected, got', str(e_append.exception)) |
| 624 |
|
| 625 |
def test_getfile_class_without_module(self): |
| 626 |
class CM(type): |
| 627 |
@property |
| 628 |
def __module__(cls): |
| 629 |
raise AttributeError |
| 630 |
class C(metaclass=CM): |
| 631 |
pass |
| 632 |
with self.assertRaises(TypeError): |
| 633 |
inspect.getfile(C) |
| 634 |
|
| 635 |
def test_getfile_broken_repr(self): |
| 636 |
class ErrorRepr: |
| 637 |
def __repr__(self): |
| 638 |
raise Exception('xyz') |
| 639 |
er = ErrorRepr() |
| 640 |
with self.assertRaises(TypeError): |
| 641 |
inspect.getfile(er) |
| 642 |
|
| 643 |
def test_getmodule_recursion(self): |
| 644 |
from types import ModuleType |
| 645 |
name = '__inspect_dummy' |
| 646 |
m = sys.modules[name] = ModuleType(name) |
| 647 |
m.__file__ = "<string>" |
| 648 |
m.__loader__ = "dummy" |
| 649 |
exec("def x(): pass", m.__dict__) |
| 650 |
self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>') |
| 651 |
del sys.modules[name] |
| 652 |
inspect.getmodule(compile('a=10','','single')) |
| 653 |
|
| 654 |
def test_proceed_with_fake_filename(self): |
| 655 |
'''doctest monkeypatches linecache to enable inspection''' |
| 656 |
fn, source = '<test>', 'def x(): pass\n' |
| 657 |
getlines = linecache.getlines |
| 658 |
def monkey(filename, module_globals=None): |
| 659 |
if filename == fn: |
| 660 |
return source.splitlines(keepends=True) |
| 661 |
else: |
| 662 |
return getlines(filename, module_globals) |
| 663 |
linecache.getlines = monkey |
| 664 |
try: |
| 665 |
ns = {} |
| 666 |
exec(compile(source, fn, 'single'), ns) |
| 667 |
inspect.getsource(ns["x"]) |
| 668 |
finally: |
| 669 |
linecache.getlines = getlines |
| 670 |
|
| 671 |
def test_getsource_on_code_object(self): |
| 672 |
self.assertSourceEqual(mod.eggs.__code__, 12, 18) |
| 673 |
|
| 674 |
class TestGetsourceInteractive(unittest.TestCase): |
| 675 |
def test_getclasses_interactive(self): |
| 676 |
|
| 677 |
|
| 678 |
code = "import sys, inspect; \ |
| 679 |
assert not hasattr(sys.modules['__main__'], '__file__'); \ |
| 680 |
A = type('A', (), {}); \ |
| 681 |
inspect.getsource(A)" |
| 682 |
_, _, stderr = assert_python_failure("-c", code, __isolated=True) |
| 683 |
self.assertIn(b'OSError: source code not available', stderr) |
| 684 |
|
| 685 |
class TestGettingSourceOfToplevelFrames(GetSourceBase): |
| 686 |
fodderModule = mod |
| 687 |
|
| 688 |
def test_range_toplevel_frame(self): |
| 689 |
self.maxDiff = None |
| 690 |
self.assertSourceEqual(mod.currentframe, 1, None) |
| 691 |
|
| 692 |
def test_range_traceback_toplevel_frame(self): |
| 693 |
self.assertSourceEqual(mod.tb, 1, None) |
| 694 |
|
| 695 |
class TestDecorators(GetSourceBase): |
| 696 |
fodderModule = mod2 |
| 697 |
|
| 698 |
def test_wrapped_decorator(self): |
| 699 |
self.assertSourceEqual(mod2.wrapped, 14, 17) |
| 700 |
|
| 701 |
def test_replacing_decorator(self): |
| 702 |
self.assertSourceEqual(mod2.gone, 9, 10) |
| 703 |
|
| 704 |
def test_getsource_unwrap(self): |
| 705 |
self.assertSourceEqual(mod2.real, 130, 132) |
| 706 |
|
| 707 |
def test_decorator_with_lambda(self): |
| 708 |
self.assertSourceEqual(mod2.func114, 113, 115) |
| 709 |
|
| 710 |
class TestOneliners(GetSourceBase): |
| 711 |
fodderModule = mod2 |
| 712 |
def test_oneline_lambda(self): |
| 713 |
|
| 714 |
self.assertSourceEqual(mod2.oll, 25, 25) |
| 715 |
|
| 716 |
def test_threeline_lambda(self): |
| 717 |
|
| 718 |
|
| 719 |
self.assertSourceEqual(mod2.tll, 28, 30) |
| 720 |
|
| 721 |
def test_twoline_indented_lambda(self): |
| 722 |
|
| 723 |
|
| 724 |
self.assertSourceEqual(mod2.tlli, 33, 34) |
| 725 |
|
| 726 |
def test_onelinefunc(self): |
| 727 |
|
| 728 |
self.assertSourceEqual(mod2.onelinefunc, 37, 37) |
| 729 |
|
| 730 |
def test_manyargs(self): |
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
self.assertSourceEqual(mod2.manyargs, 40, 41) |
| 735 |
|
| 736 |
def test_twolinefunc(self): |
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
self.assertSourceEqual(mod2.twolinefunc, 44, 45) |
| 741 |
|
| 742 |
def test_lambda_in_list(self): |
| 743 |
|
| 744 |
|
| 745 |
self.assertSourceEqual(mod2.a[1], 49, 49) |
| 746 |
|
| 747 |
def test_anonymous(self): |
| 748 |
|
| 749 |
|
| 750 |
self.assertSourceEqual(mod2.anonymous, 55, 55) |
| 751 |
|
| 752 |
class TestBlockComments(GetSourceBase): |
| 753 |
fodderModule = mod |
| 754 |
|
| 755 |
def test_toplevel_class(self): |
| 756 |
self.assertSourceEqual(mod.WhichComments, 96, 114) |
| 757 |
|
| 758 |
def test_class_method(self): |
| 759 |
self.assertSourceEqual(mod.WhichComments.f, 99, 104) |
| 760 |
|
| 761 |
def test_class_async_method(self): |
| 762 |
self.assertSourceEqual(mod.WhichComments.asyncf, 109, 112) |
| 763 |
|
| 764 |
class TestBuggyCases(GetSourceBase): |
| 765 |
fodderModule = mod2 |
| 766 |
|
| 767 |
def test_with_comment(self): |
| 768 |
self.assertSourceEqual(mod2.with_comment, 58, 59) |
| 769 |
|
| 770 |
def test_multiline_sig(self): |
| 771 |
self.assertSourceEqual(mod2.multiline_sig[0], 63, 64) |
| 772 |
|
| 773 |
def test_nested_class(self): |
| 774 |
self.assertSourceEqual(mod2.func69().func71, 71, 72) |
| 775 |
|
| 776 |
def test_one_liner_followed_by_non_name(self): |
| 777 |
self.assertSourceEqual(mod2.func77, 77, 77) |
| 778 |
|
| 779 |
def test_one_liner_dedent_non_name(self): |
| 780 |
self.assertSourceEqual(mod2.cls82.func83, 83, 83) |
| 781 |
|
| 782 |
def test_with_comment_instead_of_docstring(self): |
| 783 |
self.assertSourceEqual(mod2.func88, 88, 90) |
| 784 |
|
| 785 |
def test_method_in_dynamic_class(self): |
| 786 |
self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97) |
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
@unittest.skipIf(not hasattr(unicodedata, '__file__') or |
| 791 |
unicodedata.__file__.endswith('.py'), |
| 792 |
"unicodedata is not an external binary module") |
| 793 |
def test_findsource_binary(self): |
| 794 |
self.assertRaises(OSError, inspect.getsource, unicodedata) |
| 795 |
self.assertRaises(OSError, inspect.findsource, unicodedata) |
| 796 |
|
| 797 |
def test_findsource_code_in_linecache(self): |
| 798 |
lines = ["x=1"] |
| 799 |
co = compile(lines[0], "_dynamically_created_file", "exec") |
| 800 |
self.assertRaises(OSError, inspect.findsource, co) |
| 801 |
self.assertRaises(OSError, inspect.getsource, co) |
| 802 |
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) |
| 803 |
try: |
| 804 |
self.assertEqual(inspect.findsource(co), (lines,0)) |
| 805 |
self.assertEqual(inspect.getsource(co), lines[0]) |
| 806 |
finally: |
| 807 |
del linecache.cache[co.co_filename] |
| 808 |
|
| 809 |
def test_findsource_without_filename(self): |
| 810 |
for fname in ['', '<string>']: |
| 811 |
co = compile('x=1', fname, "exec") |
| 812 |
self.assertRaises(IOError, inspect.findsource, co) |
| 813 |
self.assertRaises(IOError, inspect.getsource, co) |
| 814 |
|
| 815 |
def test_findsource_with_out_of_bounds_lineno(self): |
| 816 |
mod_len = len(inspect.getsource(mod)) |
| 817 |
src = '\n' * 2* mod_len + "def f(): pass" |
| 818 |
co = compile(src, mod.__file__, "exec") |
| 819 |
g, l = {}, {} |
| 820 |
eval(co, g, l) |
| 821 |
func = l['f'] |
| 822 |
self.assertEqual(func.__code__.co_firstlineno, 1+2*mod_len) |
| 823 |
with self.assertRaisesRegex(IOError, "lineno is out of bounds"): |
| 824 |
inspect.findsource(func) |
| 825 |
|
| 826 |
def test_getsource_on_method(self): |
| 827 |
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119) |
| 828 |
|
| 829 |
def test_nested_func(self): |
| 830 |
self.assertSourceEqual(mod2.cls135.func136, 136, 139) |
| 831 |
|
| 832 |
def test_class_definition_in_multiline_string_definition(self): |
| 833 |
self.assertSourceEqual(mod2.cls149, 149, 152) |
| 834 |
|
| 835 |
def test_class_definition_in_multiline_comment(self): |
| 836 |
self.assertSourceEqual(mod2.cls160, 160, 163) |
| 837 |
|
| 838 |
def test_nested_class_definition_indented_string(self): |
| 839 |
self.assertSourceEqual(mod2.cls173.cls175, 175, 176) |
| 840 |
|
| 841 |
def test_nested_class_definition(self): |
| 842 |
self.assertSourceEqual(mod2.cls183, 183, 188) |
| 843 |
self.assertSourceEqual(mod2.cls183.cls185, 185, 188) |
| 844 |
|
| 845 |
def test_class_decorator(self): |
| 846 |
self.assertSourceEqual(mod2.cls196, 194, 201) |
| 847 |
self.assertSourceEqual(mod2.cls196.cls200, 198, 201) |
| 848 |
|
| 849 |
def test_class_inside_conditional(self): |
| 850 |
self.assertSourceEqual(mod2.cls238, 238, 240) |
| 851 |
self.assertSourceEqual(mod2.cls238.cls239, 239, 240) |
| 852 |
|
| 853 |
def test_multiple_children_classes(self): |
| 854 |
self.assertSourceEqual(mod2.cls203, 203, 209) |
| 855 |
self.assertSourceEqual(mod2.cls203.cls204, 204, 206) |
| 856 |
self.assertSourceEqual(mod2.cls203.cls204.cls205, 205, 206) |
| 857 |
self.assertSourceEqual(mod2.cls203.cls207, 207, 209) |
| 858 |
self.assertSourceEqual(mod2.cls203.cls207.cls205, 208, 209) |
| 859 |
|
| 860 |
def test_nested_class_definition_inside_function(self): |
| 861 |
self.assertSourceEqual(mod2.func212(), 213, 214) |
| 862 |
self.assertSourceEqual(mod2.cls213, 218, 222) |
| 863 |
self.assertSourceEqual(mod2.cls213().func219(), 220, 221) |
| 864 |
|
| 865 |
@unittest.skipIf( |
| 866 |
support.is_emscripten or support.is_wasi, |
| 867 |
"socket.accept is broken" |
| 868 |
) |
| 869 |
def test_nested_class_definition_inside_async_function(self): |
| 870 |
import asyncio |
| 871 |
self.addCleanup(asyncio.set_event_loop_policy, None) |
| 872 |
self.assertSourceEqual(asyncio.run(mod2.func225()), 226, 227) |
| 873 |
self.assertSourceEqual(mod2.cls226, 231, 235) |
| 874 |
self.assertSourceEqual(asyncio.run(mod2.cls226().func232()), 233, 234) |
| 875 |
|
| 876 |
class TestNoEOL(GetSourceBase): |
| 877 |
def setUp(self): |
| 878 |
self.tempdir = TESTFN + '_dir' |
| 879 |
os.mkdir(self.tempdir) |
| 880 |
with open(os.path.join(self.tempdir, 'inspect_fodder3%spy' % os.extsep), |
| 881 |
'w', encoding='utf-8') as f: |
| 882 |
f.write("class X:\n pass # No EOL") |
| 883 |
with DirsOnSysPath(self.tempdir): |
| 884 |
import inspect_fodder3 as mod3 |
| 885 |
self.fodderModule = mod3 |
| 886 |
super().setUp() |
| 887 |
|
| 888 |
def tearDown(self): |
| 889 |
shutil.rmtree(self.tempdir) |
| 890 |
|
| 891 |
def test_class(self): |
| 892 |
self.assertSourceEqual(self.fodderModule.X, 1, 2) |
| 893 |
|
| 894 |
|
| 895 |
class TestComplexDecorator(GetSourceBase): |
| 896 |
fodderModule = mod2 |
| 897 |
|
| 898 |
def test_parens_in_decorator(self): |
| 899 |
self.assertSourceEqual(self.fodderModule.complex_decorated, 273, 275) |
| 900 |
|
| 901 |
class _BrokenDataDescriptor(object): |
| 902 |
""" |
| 903 |
A broken data descriptor. See bug #1785. |
| 904 |
""" |
| 905 |
def __get__(*args): |
| 906 |
raise AttributeError("broken data descriptor") |
| 907 |
|
| 908 |
def __set__(*args): |
| 909 |
raise RuntimeError |
| 910 |
|
| 911 |
def __getattr__(*args): |
| 912 |
raise AttributeError("broken data descriptor") |
| 913 |
|
| 914 |
|
| 915 |
class _BrokenMethodDescriptor(object): |
| 916 |
""" |
| 917 |
A broken method descriptor. See bug #1785. |
| 918 |
""" |
| 919 |
def __get__(*args): |
| 920 |
raise AttributeError("broken method descriptor") |
| 921 |
|
| 922 |
def __getattr__(*args): |
| 923 |
raise AttributeError("broken method descriptor") |
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
def attrs_wo_objs(cls): |
| 928 |
return [t[:3] for t in inspect.classify_class_attrs(cls)] |
| 929 |
|
| 930 |
|
| 931 |
class TestClassesAndFunctions(unittest.TestCase): |
| 932 |
def test_newstyle_mro(self): |
| 933 |
|
| 934 |
class A(object): pass |
| 935 |
class B(A): pass |
| 936 |
class C(A): pass |
| 937 |
class D(B, C): pass |
| 938 |
|
| 939 |
expected = (D, B, C, A, object) |
| 940 |
got = inspect.getmro(D) |
| 941 |
self.assertEqual(expected, got) |
| 942 |
|
| 943 |
def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None, |
| 944 |
varkw_e=None, defaults_e=None, |
| 945 |
posonlyargs_e=[], kwonlyargs_e=[], |
| 946 |
kwonlydefaults_e=None, |
| 947 |
ann_e={}): |
| 948 |
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ |
| 949 |
inspect.getfullargspec(routine) |
| 950 |
self.assertEqual(args, args_e) |
| 951 |
self.assertEqual(varargs, varargs_e) |
| 952 |
self.assertEqual(varkw, varkw_e) |
| 953 |
self.assertEqual(defaults, defaults_e) |
| 954 |
self.assertEqual(kwonlyargs, kwonlyargs_e) |
| 955 |
self.assertEqual(kwonlydefaults, kwonlydefaults_e) |
| 956 |
self.assertEqual(ann, ann_e) |
| 957 |
|
| 958 |
def test_getfullargspec(self): |
| 959 |
self.assertFullArgSpecEquals(mod2.keyworded, [], varargs_e='arg1', |
| 960 |
kwonlyargs_e=['arg2'], |
| 961 |
kwonlydefaults_e={'arg2':1}) |
| 962 |
|
| 963 |
self.assertFullArgSpecEquals(mod2.annotated, ['arg1'], |
| 964 |
ann_e={'arg1' : list}) |
| 965 |
self.assertFullArgSpecEquals(mod2.keyword_only_arg, [], |
| 966 |
kwonlyargs_e=['arg']) |
| 967 |
|
| 968 |
self.assertFullArgSpecEquals(mod2.all_markers, ['a', 'b', 'c', 'd'], |
| 969 |
kwonlyargs_e=['e', 'f']) |
| 970 |
|
| 971 |
self.assertFullArgSpecEquals(mod2.all_markers_with_args_and_kwargs, |
| 972 |
['a', 'b', 'c', 'd'], |
| 973 |
varargs_e='args', |
| 974 |
varkw_e='kwargs', |
| 975 |
kwonlyargs_e=['e', 'f']) |
| 976 |
|
| 977 |
self.assertFullArgSpecEquals(mod2.all_markers_with_defaults, ['a', 'b', 'c', 'd'], |
| 978 |
defaults_e=(1,2,3), |
| 979 |
kwonlyargs_e=['e', 'f'], |
| 980 |
kwonlydefaults_e={'e': 4, 'f': 5}) |
| 981 |
|
| 982 |
def test_argspec_api_ignores_wrapped(self): |
| 983 |
|
| 984 |
@functools.wraps(mod.spam) |
| 985 |
def ham(x, y): |
| 986 |
pass |
| 987 |
|
| 988 |
self.assertFullArgSpecEquals(ham, ['x', 'y']) |
| 989 |
self.assertFullArgSpecEquals(functools.partial(ham), |
| 990 |
['x', 'y']) |
| 991 |
|
| 992 |
def test_getfullargspec_signature_attr(self): |
| 993 |
def test(): |
| 994 |
pass |
| 995 |
spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) |
| 996 |
test.__signature__ = inspect.Signature(parameters=(spam_param,)) |
| 997 |
|
| 998 |
self.assertFullArgSpecEquals(test, ['spam']) |
| 999 |
|
| 1000 |
def test_getfullargspec_signature_annos(self): |
| 1001 |
def test(a:'spam') -> 'ham': pass |
| 1002 |
spec = inspect.getfullargspec(test) |
| 1003 |
self.assertEqual(test.__annotations__, spec.annotations) |
| 1004 |
|
| 1005 |
def test(): pass |
| 1006 |
spec = inspect.getfullargspec(test) |
| 1007 |
self.assertEqual(test.__annotations__, spec.annotations) |
| 1008 |
|
| 1009 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1010 |
"Signature information for builtins requires docstrings") |
| 1011 |
def test_getfullargspec_builtin_methods(self): |
| 1012 |
self.assertFullArgSpecEquals(_pickle.Pickler.dump, ['self', 'obj']) |
| 1013 |
|
| 1014 |
self.assertFullArgSpecEquals(_pickle.Pickler(io.BytesIO()).dump, ['self', 'obj']) |
| 1015 |
|
| 1016 |
self.assertFullArgSpecEquals( |
| 1017 |
os.stat, |
| 1018 |
args_e=['path'], |
| 1019 |
kwonlyargs_e=['dir_fd', 'follow_symlinks'], |
| 1020 |
kwonlydefaults_e={'dir_fd': None, 'follow_symlinks': True}) |
| 1021 |
|
| 1022 |
@cpython_only |
| 1023 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1024 |
"Signature information for builtins requires docstrings") |
| 1025 |
def test_getfullargspec_builtin_func(self): |
| 1026 |
import _testcapi |
| 1027 |
builtin = _testcapi.docstring_with_signature_with_defaults |
| 1028 |
spec = inspect.getfullargspec(builtin) |
| 1029 |
self.assertEqual(spec.defaults[0], 'avocado') |
| 1030 |
|
| 1031 |
@cpython_only |
| 1032 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1033 |
"Signature information for builtins requires docstrings") |
| 1034 |
def test_getfullargspec_builtin_func_no_signature(self): |
| 1035 |
import _testcapi |
| 1036 |
builtin = _testcapi.docstring_no_signature |
| 1037 |
with self.assertRaises(TypeError): |
| 1038 |
inspect.getfullargspec(builtin) |
| 1039 |
|
| 1040 |
def test_getfullargspec_definition_order_preserved_on_kwonly(self): |
| 1041 |
for fn in signatures_with_lexicographic_keyword_only_parameters(): |
| 1042 |
signature = inspect.getfullargspec(fn) |
| 1043 |
l = list(signature.kwonlyargs) |
| 1044 |
sorted_l = sorted(l) |
| 1045 |
self.assertTrue(l) |
| 1046 |
self.assertEqual(l, sorted_l) |
| 1047 |
signature = inspect.getfullargspec(unsorted_keyword_only_parameters_fn) |
| 1048 |
l = list(signature.kwonlyargs) |
| 1049 |
self.assertEqual(l, unsorted_keyword_only_parameters) |
| 1050 |
|
| 1051 |
def test_classify_newstyle(self): |
| 1052 |
class A(object): |
| 1053 |
|
| 1054 |
def s(): pass |
| 1055 |
s = staticmethod(s) |
| 1056 |
|
| 1057 |
def c(cls): pass |
| 1058 |
c = classmethod(c) |
| 1059 |
|
| 1060 |
def getp(self): pass |
| 1061 |
p = property(getp) |
| 1062 |
|
| 1063 |
def m(self): pass |
| 1064 |
|
| 1065 |
def m1(self): pass |
| 1066 |
|
| 1067 |
datablob = '1' |
| 1068 |
|
| 1069 |
dd = _BrokenDataDescriptor() |
| 1070 |
md = _BrokenMethodDescriptor() |
| 1071 |
|
| 1072 |
attrs = attrs_wo_objs(A) |
| 1073 |
|
| 1074 |
self.assertIn(('__new__', 'static method', object), attrs, |
| 1075 |
'missing __new__') |
| 1076 |
self.assertIn(('__init__', 'method', object), attrs, 'missing __init__') |
| 1077 |
|
| 1078 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1079 |
self.assertIn(('c', 'class method', A), attrs, 'missing class method') |
| 1080 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1081 |
self.assertIn(('m', 'method', A), attrs, |
| 1082 |
'missing plain method: %r' % attrs) |
| 1083 |
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 1084 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1085 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1086 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1087 |
|
| 1088 |
class B(A): |
| 1089 |
|
| 1090 |
def m(self): pass |
| 1091 |
|
| 1092 |
attrs = attrs_wo_objs(B) |
| 1093 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1094 |
self.assertIn(('c', 'class method', A), attrs, 'missing class method') |
| 1095 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1096 |
self.assertIn(('m', 'method', B), attrs, 'missing plain method') |
| 1097 |
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 1098 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1099 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1100 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1101 |
|
| 1102 |
|
| 1103 |
class C(A): |
| 1104 |
|
| 1105 |
def m(self): pass |
| 1106 |
def c(self): pass |
| 1107 |
|
| 1108 |
attrs = attrs_wo_objs(C) |
| 1109 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1110 |
self.assertIn(('c', 'method', C), attrs, 'missing plain method') |
| 1111 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1112 |
self.assertIn(('m', 'method', C), attrs, 'missing plain method') |
| 1113 |
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 1114 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1115 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1116 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1117 |
|
| 1118 |
class D(B, C): |
| 1119 |
|
| 1120 |
def m1(self): pass |
| 1121 |
|
| 1122 |
attrs = attrs_wo_objs(D) |
| 1123 |
self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 1124 |
self.assertIn(('c', 'method', C), attrs, 'missing plain method') |
| 1125 |
self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 1126 |
self.assertIn(('m', 'method', B), attrs, 'missing plain method') |
| 1127 |
self.assertIn(('m1', 'method', D), attrs, 'missing plain method') |
| 1128 |
self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
| 1129 |
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 1130 |
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 1131 |
|
| 1132 |
def test_classify_builtin_types(self): |
| 1133 |
|
| 1134 |
|
| 1135 |
for name in dir(__builtins__): |
| 1136 |
builtin = getattr(__builtins__, name) |
| 1137 |
if isinstance(builtin, type): |
| 1138 |
inspect.classify_class_attrs(builtin) |
| 1139 |
|
| 1140 |
attrs = attrs_wo_objs(bool) |
| 1141 |
self.assertIn(('__new__', 'static method', bool), attrs, |
| 1142 |
'missing __new__') |
| 1143 |
self.assertIn(('from_bytes', 'class method', int), attrs, |
| 1144 |
'missing class method') |
| 1145 |
self.assertIn(('to_bytes', 'method', int), attrs, |
| 1146 |
'missing plain method') |
| 1147 |
self.assertIn(('__add__', 'method', int), attrs, |
| 1148 |
'missing plain method') |
| 1149 |
self.assertIn(('__and__', 'method', bool), attrs, |
| 1150 |
'missing plain method') |
| 1151 |
|
| 1152 |
def test_classify_DynamicClassAttribute(self): |
| 1153 |
class Meta(type): |
| 1154 |
def __getattr__(self, name): |
| 1155 |
if name == 'ham': |
| 1156 |
return 'spam' |
| 1157 |
return super().__getattr__(name) |
| 1158 |
class VA(metaclass=Meta): |
| 1159 |
@types.DynamicClassAttribute |
| 1160 |
def ham(self): |
| 1161 |
return 'eggs' |
| 1162 |
should_find_dca = inspect.Attribute('ham', 'data', VA, VA.__dict__['ham']) |
| 1163 |
self.assertIn(should_find_dca, inspect.classify_class_attrs(VA)) |
| 1164 |
should_find_ga = inspect.Attribute('ham', 'data', Meta, 'spam') |
| 1165 |
self.assertIn(should_find_ga, inspect.classify_class_attrs(VA)) |
| 1166 |
|
| 1167 |
def test_classify_overrides_bool(self): |
| 1168 |
class NoBool(object): |
| 1169 |
def __eq__(self, other): |
| 1170 |
return NoBool() |
| 1171 |
|
| 1172 |
def __bool__(self): |
| 1173 |
raise NotImplementedError( |
| 1174 |
"This object does not specify a boolean value") |
| 1175 |
|
| 1176 |
class HasNB(object): |
| 1177 |
dd = NoBool() |
| 1178 |
|
| 1179 |
should_find_attr = inspect.Attribute('dd', 'data', HasNB, HasNB.dd) |
| 1180 |
self.assertIn(should_find_attr, inspect.classify_class_attrs(HasNB)) |
| 1181 |
|
| 1182 |
def test_classify_metaclass_class_attribute(self): |
| 1183 |
class Meta(type): |
| 1184 |
fish = 'slap' |
| 1185 |
def __dir__(self): |
| 1186 |
return ['__class__', '__module__', '__name__', 'fish'] |
| 1187 |
class Class(metaclass=Meta): |
| 1188 |
pass |
| 1189 |
should_find = inspect.Attribute('fish', 'data', Meta, 'slap') |
| 1190 |
self.assertIn(should_find, inspect.classify_class_attrs(Class)) |
| 1191 |
|
| 1192 |
def test_classify_VirtualAttribute(self): |
| 1193 |
class Meta(type): |
| 1194 |
def __dir__(cls): |
| 1195 |
return ['__class__', '__module__', '__name__', 'BOOM'] |
| 1196 |
def __getattr__(self, name): |
| 1197 |
if name =='BOOM': |
| 1198 |
return 42 |
| 1199 |
return super().__getattr(name) |
| 1200 |
class Class(metaclass=Meta): |
| 1201 |
pass |
| 1202 |
should_find = inspect.Attribute('BOOM', 'data', Meta, 42) |
| 1203 |
self.assertIn(should_find, inspect.classify_class_attrs(Class)) |
| 1204 |
|
| 1205 |
def test_classify_VirtualAttribute_multi_classes(self): |
| 1206 |
class Meta1(type): |
| 1207 |
def __dir__(cls): |
| 1208 |
return ['__class__', '__module__', '__name__', 'one'] |
| 1209 |
def __getattr__(self, name): |
| 1210 |
if name =='one': |
| 1211 |
return 1 |
| 1212 |
return super().__getattr__(name) |
| 1213 |
class Meta2(type): |
| 1214 |
def __dir__(cls): |
| 1215 |
return ['__class__', '__module__', '__name__', 'two'] |
| 1216 |
def __getattr__(self, name): |
| 1217 |
if name =='two': |
| 1218 |
return 2 |
| 1219 |
return super().__getattr__(name) |
| 1220 |
class Meta3(Meta1, Meta2): |
| 1221 |
def __dir__(cls): |
| 1222 |
return list(sorted(set(['__class__', '__module__', '__name__', 'three'] + |
| 1223 |
Meta1.__dir__(cls) + Meta2.__dir__(cls)))) |
| 1224 |
def __getattr__(self, name): |
| 1225 |
if name =='three': |
| 1226 |
return 3 |
| 1227 |
return super().__getattr__(name) |
| 1228 |
class Class1(metaclass=Meta1): |
| 1229 |
pass |
| 1230 |
class Class2(Class1, metaclass=Meta3): |
| 1231 |
pass |
| 1232 |
|
| 1233 |
should_find1 = inspect.Attribute('one', 'data', Meta1, 1) |
| 1234 |
should_find2 = inspect.Attribute('two', 'data', Meta2, 2) |
| 1235 |
should_find3 = inspect.Attribute('three', 'data', Meta3, 3) |
| 1236 |
cca = inspect.classify_class_attrs(Class2) |
| 1237 |
for sf in (should_find1, should_find2, should_find3): |
| 1238 |
self.assertIn(sf, cca) |
| 1239 |
|
| 1240 |
def test_classify_class_attrs_with_buggy_dir(self): |
| 1241 |
class M(type): |
| 1242 |
def __dir__(cls): |
| 1243 |
return ['__class__', '__name__', 'missing'] |
| 1244 |
class C(metaclass=M): |
| 1245 |
pass |
| 1246 |
attrs = [a[0] for a in inspect.classify_class_attrs(C)] |
| 1247 |
self.assertNotIn('missing', attrs) |
| 1248 |
|
| 1249 |
def test_getmembers_descriptors(self): |
| 1250 |
class A(object): |
| 1251 |
dd = _BrokenDataDescriptor() |
| 1252 |
md = _BrokenMethodDescriptor() |
| 1253 |
|
| 1254 |
def pred_wrapper(pred): |
| 1255 |
|
| 1256 |
|
| 1257 |
class Empty(object): |
| 1258 |
pass |
| 1259 |
def wrapped(x): |
| 1260 |
if '__name__' in dir(x) and hasattr(Empty, x.__name__): |
| 1261 |
return False |
| 1262 |
return pred(x) |
| 1263 |
return wrapped |
| 1264 |
|
| 1265 |
ismethoddescriptor = pred_wrapper(inspect.ismethoddescriptor) |
| 1266 |
isdatadescriptor = pred_wrapper(inspect.isdatadescriptor) |
| 1267 |
|
| 1268 |
self.assertEqual(inspect.getmembers(A, ismethoddescriptor), |
| 1269 |
[('md', A.__dict__['md'])]) |
| 1270 |
self.assertEqual(inspect.getmembers(A, isdatadescriptor), |
| 1271 |
[('dd', A.__dict__['dd'])]) |
| 1272 |
|
| 1273 |
class B(A): |
| 1274 |
pass |
| 1275 |
|
| 1276 |
self.assertEqual(inspect.getmembers(B, ismethoddescriptor), |
| 1277 |
[('md', A.__dict__['md'])]) |
| 1278 |
self.assertEqual(inspect.getmembers(B, isdatadescriptor), |
| 1279 |
[('dd', A.__dict__['dd'])]) |
| 1280 |
|
| 1281 |
def test_getmembers_method(self): |
| 1282 |
class B: |
| 1283 |
def f(self): |
| 1284 |
pass |
| 1285 |
|
| 1286 |
self.assertIn(('f', B.f), inspect.getmembers(B)) |
| 1287 |
self.assertNotIn(('f', B.f), inspect.getmembers(B, inspect.ismethod)) |
| 1288 |
b = B() |
| 1289 |
self.assertIn(('f', b.f), inspect.getmembers(b)) |
| 1290 |
self.assertIn(('f', b.f), inspect.getmembers(b, inspect.ismethod)) |
| 1291 |
|
| 1292 |
def test_getmembers_VirtualAttribute(self): |
| 1293 |
class M(type): |
| 1294 |
def __getattr__(cls, name): |
| 1295 |
if name == 'eggs': |
| 1296 |
return 'scrambled' |
| 1297 |
return super().__getattr__(name) |
| 1298 |
class A(metaclass=M): |
| 1299 |
@types.DynamicClassAttribute |
| 1300 |
def eggs(self): |
| 1301 |
return 'spam' |
| 1302 |
class B: |
| 1303 |
def __getattr__(self, attribute): |
| 1304 |
return None |
| 1305 |
self.assertIn(('eggs', 'scrambled'), inspect.getmembers(A)) |
| 1306 |
self.assertIn(('eggs', 'spam'), inspect.getmembers(A())) |
| 1307 |
b = B() |
| 1308 |
self.assertIn(('__getattr__', b.__getattr__), inspect.getmembers(b)) |
| 1309 |
|
| 1310 |
def test_getmembers_static(self): |
| 1311 |
class A: |
| 1312 |
@property |
| 1313 |
def name(self): |
| 1314 |
raise NotImplementedError |
| 1315 |
@types.DynamicClassAttribute |
| 1316 |
def eggs(self): |
| 1317 |
raise NotImplementedError |
| 1318 |
|
| 1319 |
a = A() |
| 1320 |
instance_members = inspect.getmembers_static(a) |
| 1321 |
class_members = inspect.getmembers_static(A) |
| 1322 |
self.assertIn(('name', inspect.getattr_static(a, 'name')), instance_members) |
| 1323 |
self.assertIn(('eggs', inspect.getattr_static(a, 'eggs')), instance_members) |
| 1324 |
self.assertIn(('name', inspect.getattr_static(A, 'name')), class_members) |
| 1325 |
self.assertIn(('eggs', inspect.getattr_static(A, 'eggs')), class_members) |
| 1326 |
|
| 1327 |
def test_getmembers_with_buggy_dir(self): |
| 1328 |
class M(type): |
| 1329 |
def __dir__(cls): |
| 1330 |
return ['__class__', '__name__', 'missing'] |
| 1331 |
class C(metaclass=M): |
| 1332 |
pass |
| 1333 |
attrs = [a[0] for a in inspect.getmembers(C)] |
| 1334 |
self.assertNotIn('missing', attrs) |
| 1335 |
|
| 1336 |
def test_get_annotations_with_stock_annotations(self): |
| 1337 |
def foo(a:int, b:str): pass |
| 1338 |
self.assertEqual(inspect.get_annotations(foo), {'a': int, 'b': str}) |
| 1339 |
|
| 1340 |
foo.__annotations__ = {'a': 'foo', 'b':'str'} |
| 1341 |
self.assertEqual(inspect.get_annotations(foo), {'a': 'foo', 'b': 'str'}) |
| 1342 |
|
| 1343 |
self.assertEqual(inspect.get_annotations(foo, eval_str=True, locals=locals()), {'a': foo, 'b': str}) |
| 1344 |
self.assertEqual(inspect.get_annotations(foo, eval_str=True, globals=locals()), {'a': foo, 'b': str}) |
| 1345 |
|
| 1346 |
isa = inspect_stock_annotations |
| 1347 |
self.assertEqual(inspect.get_annotations(isa), {'a': int, 'b': str}) |
| 1348 |
self.assertEqual(inspect.get_annotations(isa.MyClass), {'a': int, 'b': str}) |
| 1349 |
self.assertEqual(inspect.get_annotations(isa.function), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1350 |
self.assertEqual(inspect.get_annotations(isa.function2), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass}) |
| 1351 |
self.assertEqual(inspect.get_annotations(isa.function3), {'a': 'int', 'b': 'str', 'c': 'MyClass'}) |
| 1352 |
self.assertEqual(inspect.get_annotations(inspect), {}) |
| 1353 |
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass), {}) |
| 1354 |
self.assertEqual(inspect.get_annotations(isa.unannotated_function), {}) |
| 1355 |
|
| 1356 |
self.assertEqual(inspect.get_annotations(isa, eval_str=True), {'a': int, 'b': str}) |
| 1357 |
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=True), {'a': int, 'b': str}) |
| 1358 |
self.assertEqual(inspect.get_annotations(isa.function, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1359 |
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=True), {'a': int, 'b': str, 'c': isa.MyClass, 'return': isa.MyClass}) |
| 1360 |
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=True), {'a': int, 'b': str, 'c': isa.MyClass}) |
| 1361 |
self.assertEqual(inspect.get_annotations(inspect, eval_str=True), {}) |
| 1362 |
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=True), {}) |
| 1363 |
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=True), {}) |
| 1364 |
|
| 1365 |
self.assertEqual(inspect.get_annotations(isa, eval_str=False), {'a': int, 'b': str}) |
| 1366 |
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=False), {'a': int, 'b': str}) |
| 1367 |
self.assertEqual(inspect.get_annotations(isa.function, eval_str=False), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1368 |
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=False), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass}) |
| 1369 |
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=False), {'a': 'int', 'b': 'str', 'c': 'MyClass'}) |
| 1370 |
self.assertEqual(inspect.get_annotations(inspect, eval_str=False), {}) |
| 1371 |
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=False), {}) |
| 1372 |
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=False), {}) |
| 1373 |
|
| 1374 |
def times_three(fn): |
| 1375 |
@functools.wraps(fn) |
| 1376 |
def wrapper(a, b): |
| 1377 |
return fn(a*3, b*3) |
| 1378 |
return wrapper |
| 1379 |
|
| 1380 |
wrapped = times_three(isa.function) |
| 1381 |
self.assertEqual(wrapped(1, 'x'), isa.MyClass(3, 'xxx')) |
| 1382 |
self.assertIsNot(wrapped.__globals__, isa.function.__globals__) |
| 1383 |
self.assertEqual(inspect.get_annotations(wrapped), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1384 |
self.assertEqual(inspect.get_annotations(wrapped, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1385 |
self.assertEqual(inspect.get_annotations(wrapped, eval_str=False), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1386 |
|
| 1387 |
def test_get_annotations_with_stringized_annotations(self): |
| 1388 |
isa = inspect_stringized_annotations |
| 1389 |
self.assertEqual(inspect.get_annotations(isa), {'a': 'int', 'b': 'str'}) |
| 1390 |
self.assertEqual(inspect.get_annotations(isa.MyClass), {'a': 'int', 'b': 'str'}) |
| 1391 |
self.assertEqual(inspect.get_annotations(isa.function), {'a': 'int', 'b': 'str', 'return': 'MyClass'}) |
| 1392 |
self.assertEqual(inspect.get_annotations(isa.function2), {'a': 'int', 'b': "'str'", 'c': 'MyClass', 'return': 'MyClass'}) |
| 1393 |
self.assertEqual(inspect.get_annotations(isa.function3), {'a': "'int'", 'b': "'str'", 'c': "'MyClass'"}) |
| 1394 |
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass), {}) |
| 1395 |
self.assertEqual(inspect.get_annotations(isa.unannotated_function), {}) |
| 1396 |
|
| 1397 |
self.assertEqual(inspect.get_annotations(isa, eval_str=True), {'a': int, 'b': str}) |
| 1398 |
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=True), {'a': int, 'b': str}) |
| 1399 |
self.assertEqual(inspect.get_annotations(isa.function, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1400 |
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=True), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass}) |
| 1401 |
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=True), {'a': 'int', 'b': 'str', 'c': 'MyClass'}) |
| 1402 |
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=True), {}) |
| 1403 |
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=True), {}) |
| 1404 |
|
| 1405 |
self.assertEqual(inspect.get_annotations(isa, eval_str=False), {'a': 'int', 'b': 'str'}) |
| 1406 |
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=False), {'a': 'int', 'b': 'str'}) |
| 1407 |
self.assertEqual(inspect.get_annotations(isa.function, eval_str=False), {'a': 'int', 'b': 'str', 'return': 'MyClass'}) |
| 1408 |
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=False), {'a': 'int', 'b': "'str'", 'c': 'MyClass', 'return': 'MyClass'}) |
| 1409 |
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=False), {'a': "'int'", 'b': "'str'", 'c': "'MyClass'"}) |
| 1410 |
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=False), {}) |
| 1411 |
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=False), {}) |
| 1412 |
|
| 1413 |
isa2 = inspect_stringized_annotations_2 |
| 1414 |
self.assertEqual(inspect.get_annotations(isa2), {}) |
| 1415 |
self.assertEqual(inspect.get_annotations(isa2, eval_str=True), {}) |
| 1416 |
self.assertEqual(inspect.get_annotations(isa2, eval_str=False), {}) |
| 1417 |
|
| 1418 |
def times_three(fn): |
| 1419 |
@functools.wraps(fn) |
| 1420 |
def wrapper(a, b): |
| 1421 |
return fn(a*3, b*3) |
| 1422 |
return wrapper |
| 1423 |
|
| 1424 |
wrapped = times_three(isa.function) |
| 1425 |
self.assertEqual(wrapped(1, 'x'), isa.MyClass(3, 'xxx')) |
| 1426 |
self.assertIsNot(wrapped.__globals__, isa.function.__globals__) |
| 1427 |
self.assertEqual(inspect.get_annotations(wrapped), {'a': 'int', 'b': 'str', 'return': 'MyClass'}) |
| 1428 |
self.assertEqual(inspect.get_annotations(wrapped, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass}) |
| 1429 |
self.assertEqual(inspect.get_annotations(wrapped, eval_str=False), {'a': 'int', 'b': 'str', 'return': 'MyClass'}) |
| 1430 |
|
| 1431 |
|
| 1432 |
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations), {'x': 'mytype'}) |
| 1433 |
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True), {'x': int}) |
| 1434 |
|
| 1435 |
|
| 1436 |
class TestFormatAnnotation(unittest.TestCase): |
| 1437 |
def test_typing_replacement(self): |
| 1438 |
from test.typinganndata.ann_module9 import ann, ann1 |
| 1439 |
self.assertEqual(inspect.formatannotation(ann), 'Union[List[str], int]') |
| 1440 |
self.assertEqual(inspect.formatannotation(ann1), 'Union[List[testModule.typing.A], int]') |
| 1441 |
|
| 1442 |
|
| 1443 |
class TestIsDataDescriptor(unittest.TestCase): |
| 1444 |
|
| 1445 |
def test_custom_descriptors(self): |
| 1446 |
class NonDataDescriptor: |
| 1447 |
def __get__(self, value, type=None): pass |
| 1448 |
class DataDescriptor0: |
| 1449 |
def __set__(self, name, value): pass |
| 1450 |
class DataDescriptor1: |
| 1451 |
def __delete__(self, name): pass |
| 1452 |
class DataDescriptor2: |
| 1453 |
__set__ = None |
| 1454 |
self.assertFalse(inspect.isdatadescriptor(NonDataDescriptor()), |
| 1455 |
'class with only __get__ not a data descriptor') |
| 1456 |
self.assertTrue(inspect.isdatadescriptor(DataDescriptor0()), |
| 1457 |
'class with __set__ is a data descriptor') |
| 1458 |
self.assertTrue(inspect.isdatadescriptor(DataDescriptor1()), |
| 1459 |
'class with __delete__ is a data descriptor') |
| 1460 |
self.assertTrue(inspect.isdatadescriptor(DataDescriptor2()), |
| 1461 |
'class with __set__ = None is a data descriptor') |
| 1462 |
|
| 1463 |
def test_slot(self): |
| 1464 |
class Slotted: |
| 1465 |
__slots__ = 'foo', |
| 1466 |
self.assertTrue(inspect.isdatadescriptor(Slotted.foo), |
| 1467 |
'a slot is a data descriptor') |
| 1468 |
|
| 1469 |
def test_property(self): |
| 1470 |
class Propertied: |
| 1471 |
@property |
| 1472 |
def a_property(self): |
| 1473 |
pass |
| 1474 |
self.assertTrue(inspect.isdatadescriptor(Propertied.a_property), |
| 1475 |
'a property is a data descriptor') |
| 1476 |
|
| 1477 |
def test_functions(self): |
| 1478 |
class Test(object): |
| 1479 |
def instance_method(self): pass |
| 1480 |
@classmethod |
| 1481 |
def class_method(cls): pass |
| 1482 |
@staticmethod |
| 1483 |
def static_method(): pass |
| 1484 |
def function(): |
| 1485 |
pass |
| 1486 |
a_lambda = lambda: None |
| 1487 |
self.assertFalse(inspect.isdatadescriptor(Test().instance_method), |
| 1488 |
'a instance method is not a data descriptor') |
| 1489 |
self.assertFalse(inspect.isdatadescriptor(Test().class_method), |
| 1490 |
'a class method is not a data descriptor') |
| 1491 |
self.assertFalse(inspect.isdatadescriptor(Test().static_method), |
| 1492 |
'a static method is not a data descriptor') |
| 1493 |
self.assertFalse(inspect.isdatadescriptor(function), |
| 1494 |
'a function is not a data descriptor') |
| 1495 |
self.assertFalse(inspect.isdatadescriptor(a_lambda), |
| 1496 |
'a lambda is not a data descriptor') |
| 1497 |
|
| 1498 |
|
| 1499 |
_global_ref = object() |
| 1500 |
class TestGetClosureVars(unittest.TestCase): |
| 1501 |
|
| 1502 |
def test_name_resolution(self): |
| 1503 |
|
| 1504 |
def f(nonlocal_ref): |
| 1505 |
def g(local_ref): |
| 1506 |
print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 1507 |
return g |
| 1508 |
_arg = object() |
| 1509 |
nonlocal_vars = {"nonlocal_ref": _arg} |
| 1510 |
global_vars = {"_global_ref": _global_ref} |
| 1511 |
builtin_vars = {"print": print} |
| 1512 |
unbound_names = {"unbound_ref"} |
| 1513 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 1514 |
builtin_vars, unbound_names) |
| 1515 |
self.assertEqual(inspect.getclosurevars(f(_arg)), expected) |
| 1516 |
|
| 1517 |
def test_generator_closure(self): |
| 1518 |
def f(nonlocal_ref): |
| 1519 |
def g(local_ref): |
| 1520 |
print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 1521 |
yield |
| 1522 |
return g |
| 1523 |
_arg = object() |
| 1524 |
nonlocal_vars = {"nonlocal_ref": _arg} |
| 1525 |
global_vars = {"_global_ref": _global_ref} |
| 1526 |
builtin_vars = {"print": print} |
| 1527 |
unbound_names = {"unbound_ref"} |
| 1528 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 1529 |
builtin_vars, unbound_names) |
| 1530 |
self.assertEqual(inspect.getclosurevars(f(_arg)), expected) |
| 1531 |
|
| 1532 |
def test_method_closure(self): |
| 1533 |
class C: |
| 1534 |
def f(self, nonlocal_ref): |
| 1535 |
def g(local_ref): |
| 1536 |
print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 1537 |
return g |
| 1538 |
_arg = object() |
| 1539 |
nonlocal_vars = {"nonlocal_ref": _arg} |
| 1540 |
global_vars = {"_global_ref": _global_ref} |
| 1541 |
builtin_vars = {"print": print} |
| 1542 |
unbound_names = {"unbound_ref"} |
| 1543 |
expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 1544 |
builtin_vars, unbound_names) |
| 1545 |
self.assertEqual(inspect.getclosurevars(C().f(_arg)), expected) |
| 1546 |
|
| 1547 |
def test_nonlocal_vars(self): |
| 1548 |
|
| 1549 |
def _nonlocal_vars(f): |
| 1550 |
return inspect.getclosurevars(f).nonlocals |
| 1551 |
|
| 1552 |
def make_adder(x): |
| 1553 |
def add(y): |
| 1554 |
return x + y |
| 1555 |
return add |
| 1556 |
|
| 1557 |
def curry(func, arg1): |
| 1558 |
return lambda arg2: func(arg1, arg2) |
| 1559 |
|
| 1560 |
def less_than(a, b): |
| 1561 |
return a < b |
| 1562 |
|
| 1563 |
|
| 1564 |
def Y(le): |
| 1565 |
def g(f): |
| 1566 |
return le(lambda x: f(f)(x)) |
| 1567 |
Y.g_ref = g |
| 1568 |
return g(g) |
| 1569 |
|
| 1570 |
def check_y_combinator(func): |
| 1571 |
self.assertEqual(_nonlocal_vars(func), {'f': Y.g_ref}) |
| 1572 |
|
| 1573 |
inc = make_adder(1) |
| 1574 |
add_two = make_adder(2) |
| 1575 |
greater_than_five = curry(less_than, 5) |
| 1576 |
|
| 1577 |
self.assertEqual(_nonlocal_vars(inc), {'x': 1}) |
| 1578 |
self.assertEqual(_nonlocal_vars(add_two), {'x': 2}) |
| 1579 |
self.assertEqual(_nonlocal_vars(greater_than_five), |
| 1580 |
{'arg1': 5, 'func': less_than}) |
| 1581 |
self.assertEqual(_nonlocal_vars((lambda x: lambda y: x + y)(3)), |
| 1582 |
{'x': 3}) |
| 1583 |
Y(check_y_combinator) |
| 1584 |
|
| 1585 |
def test_getclosurevars_empty(self): |
| 1586 |
def foo(): pass |
| 1587 |
_empty = inspect.ClosureVars({}, {}, {}, set()) |
| 1588 |
self.assertEqual(inspect.getclosurevars(lambda: True), _empty) |
| 1589 |
self.assertEqual(inspect.getclosurevars(foo), _empty) |
| 1590 |
|
| 1591 |
def test_getclosurevars_error(self): |
| 1592 |
class T: pass |
| 1593 |
self.assertRaises(TypeError, inspect.getclosurevars, 1) |
| 1594 |
self.assertRaises(TypeError, inspect.getclosurevars, list) |
| 1595 |
self.assertRaises(TypeError, inspect.getclosurevars, {}) |
| 1596 |
|
| 1597 |
def _private_globals(self): |
| 1598 |
code = """def f(): print(path)""" |
| 1599 |
ns = {} |
| 1600 |
exec(code, ns) |
| 1601 |
return ns["f"], ns |
| 1602 |
|
| 1603 |
def test_builtins_fallback(self): |
| 1604 |
f, ns = self._private_globals() |
| 1605 |
ns.pop("__builtins__", None) |
| 1606 |
expected = inspect.ClosureVars({}, {}, {"print":print}, {"path"}) |
| 1607 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 1608 |
|
| 1609 |
def test_builtins_as_dict(self): |
| 1610 |
f, ns = self._private_globals() |
| 1611 |
ns["__builtins__"] = {"path":1} |
| 1612 |
expected = inspect.ClosureVars({}, {}, {"path":1}, {"print"}) |
| 1613 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 1614 |
|
| 1615 |
def test_builtins_as_module(self): |
| 1616 |
f, ns = self._private_globals() |
| 1617 |
ns["__builtins__"] = os |
| 1618 |
expected = inspect.ClosureVars({}, {}, {"path":os.path}, {"print"}) |
| 1619 |
self.assertEqual(inspect.getclosurevars(f), expected) |
| 1620 |
|
| 1621 |
|
| 1622 |
class TestGetcallargsFunctions(unittest.TestCase): |
| 1623 |
|
| 1624 |
def assertEqualCallArgs(self, func, call_params_string, locs=None): |
| 1625 |
locs = dict(locs or {}, func=func) |
| 1626 |
r1 = eval('func(%s)' % call_params_string, None, locs) |
| 1627 |
r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None, |
| 1628 |
locs) |
| 1629 |
self.assertEqual(r1, r2) |
| 1630 |
|
| 1631 |
def assertEqualException(self, func, call_param_string, locs=None): |
| 1632 |
locs = dict(locs or {}, func=func) |
| 1633 |
try: |
| 1634 |
eval('func(%s)' % call_param_string, None, locs) |
| 1635 |
except Exception as e: |
| 1636 |
ex1 = e |
| 1637 |
else: |
| 1638 |
self.fail('Exception not raised') |
| 1639 |
try: |
| 1640 |
eval('inspect.getcallargs(func, %s)' % call_param_string, None, |
| 1641 |
locs) |
| 1642 |
except Exception as e: |
| 1643 |
ex2 = e |
| 1644 |
else: |
| 1645 |
self.fail('Exception not raised') |
| 1646 |
self.assertIs(type(ex1), type(ex2)) |
| 1647 |
self.assertEqual(str(ex1), str(ex2)) |
| 1648 |
del ex1, ex2 |
| 1649 |
|
| 1650 |
def makeCallable(self, signature): |
| 1651 |
"""Create a function that returns its locals()""" |
| 1652 |
code = "lambda %s: locals()" |
| 1653 |
return eval(code % signature) |
| 1654 |
|
| 1655 |
def test_plain(self): |
| 1656 |
f = self.makeCallable('a, b=1') |
| 1657 |
self.assertEqualCallArgs(f, '2') |
| 1658 |
self.assertEqualCallArgs(f, '2, 3') |
| 1659 |
self.assertEqualCallArgs(f, 'a=2') |
| 1660 |
self.assertEqualCallArgs(f, 'b=3, a=2') |
| 1661 |
self.assertEqualCallArgs(f, '2, b=3') |
| 1662 |
|
| 1663 |
self.assertEqualCallArgs(f, '*(2,)') |
| 1664 |
self.assertEqualCallArgs(f, '*[2]') |
| 1665 |
self.assertEqualCallArgs(f, '*(2, 3)') |
| 1666 |
self.assertEqualCallArgs(f, '*[2, 3]') |
| 1667 |
self.assertEqualCallArgs(f, '**{"a":2}') |
| 1668 |
self.assertEqualCallArgs(f, 'b=3, **{"a":2}') |
| 1669 |
self.assertEqualCallArgs(f, '2, **{"b":3}') |
| 1670 |
self.assertEqualCallArgs(f, '**{"b":3, "a":2}') |
| 1671 |
|
| 1672 |
self.assertEqualCallArgs(f, '*collections.UserList([2])') |
| 1673 |
self.assertEqualCallArgs(f, '*collections.UserList([2, 3])') |
| 1674 |
self.assertEqualCallArgs(f, '**collections.UserDict(a=2)') |
| 1675 |
self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)') |
| 1676 |
self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') |
| 1677 |
|
| 1678 |
def test_varargs(self): |
| 1679 |
f = self.makeCallable('a, b=1, *c') |
| 1680 |
self.assertEqualCallArgs(f, '2') |
| 1681 |
self.assertEqualCallArgs(f, '2, 3') |
| 1682 |
self.assertEqualCallArgs(f, '2, 3, 4') |
| 1683 |
self.assertEqualCallArgs(f, '*(2,3,4)') |
| 1684 |
self.assertEqualCallArgs(f, '2, *[3,4]') |
| 1685 |
self.assertEqualCallArgs(f, '2, 3, *collections.UserList([4])') |
| 1686 |
|
| 1687 |
def test_varkw(self): |
| 1688 |
f = self.makeCallable('a, b=1, **c') |
| 1689 |
self.assertEqualCallArgs(f, 'a=2') |
| 1690 |
self.assertEqualCallArgs(f, '2, b=3, c=4') |
| 1691 |
self.assertEqualCallArgs(f, 'b=3, a=2, c=4') |
| 1692 |
self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}') |
| 1693 |
self.assertEqualCallArgs(f, '2, c=4, **{"b":3}') |
| 1694 |
self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}') |
| 1695 |
self.assertEqualCallArgs(f, '**collections.UserDict(a=2, b=3, c=4)') |
| 1696 |
self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)') |
| 1697 |
self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3, c=4)') |
| 1698 |
|
| 1699 |
def test_varkw_only(self): |
| 1700 |
|
| 1701 |
f = self.makeCallable('**c') |
| 1702 |
self.assertEqualCallArgs(f, '') |
| 1703 |
self.assertEqualCallArgs(f, 'a=1') |
| 1704 |
self.assertEqualCallArgs(f, 'a=1, b=2') |
| 1705 |
self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}') |
| 1706 |
self.assertEqualCallArgs(f, '**collections.UserDict(a=1, b=2)') |
| 1707 |
self.assertEqualCallArgs(f, 'c=3, **collections.UserDict(a=1, b=2)') |
| 1708 |
|
| 1709 |
def test_keyword_only(self): |
| 1710 |
f = self.makeCallable('a=3, *, c, d=2') |
| 1711 |
self.assertEqualCallArgs(f, 'c=3') |
| 1712 |
self.assertEqualCallArgs(f, 'c=3, a=3') |
| 1713 |
self.assertEqualCallArgs(f, 'a=2, c=4') |
| 1714 |
self.assertEqualCallArgs(f, '4, c=4') |
| 1715 |
self.assertEqualException(f, '') |
| 1716 |
self.assertEqualException(f, '3') |
| 1717 |
self.assertEqualException(f, 'a=3') |
| 1718 |
self.assertEqualException(f, 'd=4') |
| 1719 |
|
| 1720 |
f = self.makeCallable('*, c, d=2') |
| 1721 |
self.assertEqualCallArgs(f, 'c=3') |
| 1722 |
self.assertEqualCallArgs(f, 'c=3, d=4') |
| 1723 |
self.assertEqualCallArgs(f, 'd=4, c=3') |
| 1724 |
|
| 1725 |
def test_multiple_features(self): |
| 1726 |
f = self.makeCallable('a, b=2, *f, **g') |
| 1727 |
self.assertEqualCallArgs(f, '2, 3, 7') |
| 1728 |
self.assertEqualCallArgs(f, '2, 3, x=8') |
| 1729 |
self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') |
| 1730 |
self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9') |
| 1731 |
self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9') |
| 1732 |
self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' |
| 1733 |
'[2, 3, (4,[5,6])]), **{"y":9, "z":10}') |
| 1734 |
self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' |
| 1735 |
'(4,[5,6])]), **collections.UserDict(' |
| 1736 |
'y=9, z=10)') |
| 1737 |
|
| 1738 |
f = self.makeCallable('a, b=2, *f, x, y=99, **g') |
| 1739 |
self.assertEqualCallArgs(f, '2, 3, x=8') |
| 1740 |
self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') |
| 1741 |
self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10') |
| 1742 |
self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10') |
| 1743 |
self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' |
| 1744 |
'[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}') |
| 1745 |
self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' |
| 1746 |
'(4,[5,6])]), q=0, **collections.UserDict(' |
| 1747 |
'y=9, z=10)') |
| 1748 |
|
| 1749 |
def test_errors(self): |
| 1750 |
f0 = self.makeCallable('') |
| 1751 |
f1 = self.makeCallable('a, b') |
| 1752 |
f2 = self.makeCallable('a, b=1') |
| 1753 |
|
| 1754 |
self.assertEqualException(f0, '1') |
| 1755 |
self.assertEqualException(f0, 'x=1') |
| 1756 |
self.assertEqualException(f0, '1,x=1') |
| 1757 |
|
| 1758 |
self.assertEqualException(f1, '') |
| 1759 |
self.assertEqualException(f1, '1') |
| 1760 |
self.assertEqualException(f1, 'a=2') |
| 1761 |
self.assertEqualException(f1, 'b=3') |
| 1762 |
|
| 1763 |
self.assertEqualException(f2, '') |
| 1764 |
self.assertEqualException(f2, 'b=3') |
| 1765 |
for f in f1, f2: |
| 1766 |
|
| 1767 |
self.assertEqualException(f, '2, 3, 4') |
| 1768 |
self.assertEqualException(f, '1, 2, 3, a=1') |
| 1769 |
self.assertEqualException(f, '2, 3, 4, c=5') |
| 1770 |
self.assertEqualException(f, '2, 3, 4, a=1, c=5') |
| 1771 |
|
| 1772 |
self.assertEqualException(f, 'c=2') |
| 1773 |
self.assertEqualException(f, '2, c=3') |
| 1774 |
self.assertEqualException(f, '2, 3, c=4') |
| 1775 |
self.assertEqualException(f, '2, c=4, b=3') |
| 1776 |
self.assertEqualException(f, '**{u"\u03c0\u03b9": 4}') |
| 1777 |
|
| 1778 |
self.assertEqualException(f, '1, a=2') |
| 1779 |
self.assertEqualException(f, '1, **{"a":2}') |
| 1780 |
self.assertEqualException(f, '1, 2, b=3') |
| 1781 |
|
| 1782 |
|
| 1783 |
|
| 1784 |
f3 = self.makeCallable('**c') |
| 1785 |
self.assertEqualException(f3, '1, 2') |
| 1786 |
self.assertEqualException(f3, '1, 2, a=1, b=2') |
| 1787 |
f4 = self.makeCallable('*, a, b=0') |
| 1788 |
self.assertEqualException(f4, '1, 2') |
| 1789 |
self.assertEqualException(f4, '1, 2, a=1, b=2') |
| 1790 |
|
| 1791 |
|
| 1792 |
self.assertEqualException(f4, 'a=1, c=3') |
| 1793 |
|
| 1794 |
|
| 1795 |
|
| 1796 |
|
| 1797 |
|
| 1798 |
|
| 1799 |
def f5(*, a): pass |
| 1800 |
with self.assertRaisesRegex(TypeError, |
| 1801 |
'missing 1 required keyword-only'): |
| 1802 |
inspect.getcallargs(f5) |
| 1803 |
|
| 1804 |
|
| 1805 |
|
| 1806 |
def f6(a, b, c): |
| 1807 |
pass |
| 1808 |
with self.assertRaisesRegex(TypeError, "'a', 'b' and 'c'"): |
| 1809 |
inspect.getcallargs(f6) |
| 1810 |
|
| 1811 |
|
| 1812 |
with self.assertRaisesRegex(ValueError, |
| 1813 |
'variadic keyword parameters cannot' |
| 1814 |
' have default values'): |
| 1815 |
inspect.Parameter("foo", kind=inspect.Parameter.VAR_KEYWORD, |
| 1816 |
default=42) |
| 1817 |
with self.assertRaisesRegex(ValueError, |
| 1818 |
"value 5 is not a valid Parameter.kind"): |
| 1819 |
inspect.Parameter("bar", kind=5, default=42) |
| 1820 |
|
| 1821 |
with self.assertRaisesRegex(TypeError, |
| 1822 |
'name must be a str, not a int'): |
| 1823 |
inspect.Parameter(123, kind=4) |
| 1824 |
|
| 1825 |
class TestGetcallargsMethods(TestGetcallargsFunctions): |
| 1826 |
|
| 1827 |
def setUp(self): |
| 1828 |
class Foo(object): |
| 1829 |
pass |
| 1830 |
self.cls = Foo |
| 1831 |
self.inst = Foo() |
| 1832 |
|
| 1833 |
def makeCallable(self, signature): |
| 1834 |
assert 'self' not in signature |
| 1835 |
mk = super(TestGetcallargsMethods, self).makeCallable |
| 1836 |
self.cls.method = mk('self, ' + signature) |
| 1837 |
return self.inst.method |
| 1838 |
|
| 1839 |
class TestGetcallargsUnboundMethods(TestGetcallargsMethods): |
| 1840 |
|
| 1841 |
def makeCallable(self, signature): |
| 1842 |
super(TestGetcallargsUnboundMethods, self).makeCallable(signature) |
| 1843 |
return self.cls.method |
| 1844 |
|
| 1845 |
def assertEqualCallArgs(self, func, call_params_string, locs=None): |
| 1846 |
return super(TestGetcallargsUnboundMethods, self).assertEqualCallArgs( |
| 1847 |
*self._getAssertEqualParams(func, call_params_string, locs)) |
| 1848 |
|
| 1849 |
def assertEqualException(self, func, call_params_string, locs=None): |
| 1850 |
return super(TestGetcallargsUnboundMethods, self).assertEqualException( |
| 1851 |
*self._getAssertEqualParams(func, call_params_string, locs)) |
| 1852 |
|
| 1853 |
def _getAssertEqualParams(self, func, call_params_string, locs=None): |
| 1854 |
assert 'inst' not in call_params_string |
| 1855 |
locs = dict(locs or {}, inst=self.inst) |
| 1856 |
return (func, 'inst,' + call_params_string, locs) |
| 1857 |
|
| 1858 |
|
| 1859 |
class TestGetattrStatic(unittest.TestCase): |
| 1860 |
|
| 1861 |
def test_basic(self): |
| 1862 |
class Thing(object): |
| 1863 |
x = object() |
| 1864 |
|
| 1865 |
thing = Thing() |
| 1866 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1867 |
self.assertEqual(inspect.getattr_static(thing, 'x', None), Thing.x) |
| 1868 |
with self.assertRaises(AttributeError): |
| 1869 |
inspect.getattr_static(thing, 'y') |
| 1870 |
|
| 1871 |
self.assertEqual(inspect.getattr_static(thing, 'y', 3), 3) |
| 1872 |
|
| 1873 |
def test_inherited(self): |
| 1874 |
class Thing(object): |
| 1875 |
x = object() |
| 1876 |
class OtherThing(Thing): |
| 1877 |
pass |
| 1878 |
|
| 1879 |
something = OtherThing() |
| 1880 |
self.assertEqual(inspect.getattr_static(something, 'x'), Thing.x) |
| 1881 |
|
| 1882 |
def test_instance_attr(self): |
| 1883 |
class Thing(object): |
| 1884 |
x = 2 |
| 1885 |
def __init__(self, x): |
| 1886 |
self.x = x |
| 1887 |
thing = Thing(3) |
| 1888 |
self.assertEqual(inspect.getattr_static(thing, 'x'), 3) |
| 1889 |
del thing.x |
| 1890 |
self.assertEqual(inspect.getattr_static(thing, 'x'), 2) |
| 1891 |
|
| 1892 |
def test_property(self): |
| 1893 |
class Thing(object): |
| 1894 |
@property |
| 1895 |
def x(self): |
| 1896 |
raise AttributeError("I'm pretending not to exist") |
| 1897 |
thing = Thing() |
| 1898 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1899 |
|
| 1900 |
def test_descriptor_raises_AttributeError(self): |
| 1901 |
class descriptor(object): |
| 1902 |
def __get__(*_): |
| 1903 |
raise AttributeError("I'm pretending not to exist") |
| 1904 |
desc = descriptor() |
| 1905 |
class Thing(object): |
| 1906 |
x = desc |
| 1907 |
thing = Thing() |
| 1908 |
self.assertEqual(inspect.getattr_static(thing, 'x'), desc) |
| 1909 |
|
| 1910 |
def test_classAttribute(self): |
| 1911 |
class Thing(object): |
| 1912 |
x = object() |
| 1913 |
|
| 1914 |
self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.x) |
| 1915 |
|
| 1916 |
def test_classVirtualAttribute(self): |
| 1917 |
class Thing(object): |
| 1918 |
@types.DynamicClassAttribute |
| 1919 |
def x(self): |
| 1920 |
return self._x |
| 1921 |
_x = object() |
| 1922 |
|
| 1923 |
self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.__dict__['x']) |
| 1924 |
|
| 1925 |
def test_inherited_classattribute(self): |
| 1926 |
class Thing(object): |
| 1927 |
x = object() |
| 1928 |
class OtherThing(Thing): |
| 1929 |
pass |
| 1930 |
|
| 1931 |
self.assertEqual(inspect.getattr_static(OtherThing, 'x'), Thing.x) |
| 1932 |
|
| 1933 |
def test_slots(self): |
| 1934 |
class Thing(object): |
| 1935 |
y = 'bar' |
| 1936 |
__slots__ = ['x'] |
| 1937 |
def __init__(self): |
| 1938 |
self.x = 'foo' |
| 1939 |
thing = Thing() |
| 1940 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1941 |
self.assertEqual(inspect.getattr_static(thing, 'y'), 'bar') |
| 1942 |
|
| 1943 |
del thing.x |
| 1944 |
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1945 |
|
| 1946 |
def test_metaclass(self): |
| 1947 |
class meta(type): |
| 1948 |
attr = 'foo' |
| 1949 |
class Thing(object, metaclass=meta): |
| 1950 |
pass |
| 1951 |
self.assertEqual(inspect.getattr_static(Thing, 'attr'), 'foo') |
| 1952 |
|
| 1953 |
class sub(meta): |
| 1954 |
pass |
| 1955 |
class OtherThing(object, metaclass=sub): |
| 1956 |
x = 3 |
| 1957 |
self.assertEqual(inspect.getattr_static(OtherThing, 'attr'), 'foo') |
| 1958 |
|
| 1959 |
class OtherOtherThing(OtherThing): |
| 1960 |
pass |
| 1961 |
|
| 1962 |
self.assertEqual(inspect.getattr_static(OtherOtherThing, 'x'), 3) |
| 1963 |
|
| 1964 |
def test_no_dict_no_slots(self): |
| 1965 |
self.assertEqual(inspect.getattr_static(1, 'foo', None), None) |
| 1966 |
self.assertNotEqual(inspect.getattr_static('foo', 'lower'), None) |
| 1967 |
|
| 1968 |
def test_no_dict_no_slots_instance_member(self): |
| 1969 |
|
| 1970 |
with open(__file__, encoding='utf-8') as handle: |
| 1971 |
self.assertEqual(inspect.getattr_static(handle, 'name'), type(handle).name) |
| 1972 |
|
| 1973 |
def test_inherited_slots(self): |
| 1974 |
|
| 1975 |
class Thing(object): |
| 1976 |
__slots__ = ['x'] |
| 1977 |
def __init__(self): |
| 1978 |
self.x = 'foo' |
| 1979 |
|
| 1980 |
class OtherThing(Thing): |
| 1981 |
pass |
| 1982 |
|
| 1983 |
|
| 1984 |
self.assertEqual(inspect.getattr_static(OtherThing(), 'x'), Thing.x) |
| 1985 |
|
| 1986 |
def test_descriptor(self): |
| 1987 |
class descriptor(object): |
| 1988 |
def __get__(self, instance, owner): |
| 1989 |
return 3 |
| 1990 |
class Foo(object): |
| 1991 |
d = descriptor() |
| 1992 |
|
| 1993 |
foo = Foo() |
| 1994 |
|
| 1995 |
|
| 1996 |
foo.__dict__['d'] = 1 |
| 1997 |
self.assertEqual(inspect.getattr_static(foo, 'd'), 1) |
| 1998 |
|
| 1999 |
|
| 2000 |
|
| 2001 |
descriptor.__set__ = lambda s, i, v: None |
| 2002 |
self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d']) |
| 2003 |
|
| 2004 |
del descriptor.__set__ |
| 2005 |
descriptor.__delete__ = lambda s, i, o: None |
| 2006 |
self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d']) |
| 2007 |
|
| 2008 |
def test_metaclass_with_descriptor(self): |
| 2009 |
class descriptor(object): |
| 2010 |
def __get__(self, instance, owner): |
| 2011 |
return 3 |
| 2012 |
class meta(type): |
| 2013 |
d = descriptor() |
| 2014 |
class Thing(object, metaclass=meta): |
| 2015 |
pass |
| 2016 |
self.assertEqual(inspect.getattr_static(Thing, 'd'), meta.__dict__['d']) |
| 2017 |
|
| 2018 |
|
| 2019 |
def test_class_as_property(self): |
| 2020 |
class Base(object): |
| 2021 |
foo = 3 |
| 2022 |
|
| 2023 |
class Something(Base): |
| 2024 |
executed = False |
| 2025 |
@property |
| 2026 |
def __class__(self): |
| 2027 |
self.executed = True |
| 2028 |
return object |
| 2029 |
|
| 2030 |
instance = Something() |
| 2031 |
self.assertEqual(inspect.getattr_static(instance, 'foo'), 3) |
| 2032 |
self.assertFalse(instance.executed) |
| 2033 |
self.assertEqual(inspect.getattr_static(Something, 'foo'), 3) |
| 2034 |
|
| 2035 |
def test_mro_as_property(self): |
| 2036 |
class Meta(type): |
| 2037 |
@property |
| 2038 |
def __mro__(self): |
| 2039 |
return (object,) |
| 2040 |
|
| 2041 |
class Base(object): |
| 2042 |
foo = 3 |
| 2043 |
|
| 2044 |
class Something(Base, metaclass=Meta): |
| 2045 |
pass |
| 2046 |
|
| 2047 |
self.assertEqual(inspect.getattr_static(Something(), 'foo'), 3) |
| 2048 |
self.assertEqual(inspect.getattr_static(Something, 'foo'), 3) |
| 2049 |
|
| 2050 |
def test_dict_as_property(self): |
| 2051 |
test = self |
| 2052 |
test.called = False |
| 2053 |
|
| 2054 |
class Foo(dict): |
| 2055 |
a = 3 |
| 2056 |
@property |
| 2057 |
def __dict__(self): |
| 2058 |
test.called = True |
| 2059 |
return {} |
| 2060 |
|
| 2061 |
foo = Foo() |
| 2062 |
foo.a = 4 |
| 2063 |
self.assertEqual(inspect.getattr_static(foo, 'a'), 3) |
| 2064 |
self.assertFalse(test.called) |
| 2065 |
|
| 2066 |
def test_custom_object_dict(self): |
| 2067 |
test = self |
| 2068 |
test.called = False |
| 2069 |
|
| 2070 |
class Custom(dict): |
| 2071 |
def get(self, key, default=None): |
| 2072 |
test.called = True |
| 2073 |
super().get(key, default) |
| 2074 |
|
| 2075 |
class Foo(object): |
| 2076 |
a = 3 |
| 2077 |
foo = Foo() |
| 2078 |
foo.__dict__ = Custom() |
| 2079 |
self.assertEqual(inspect.getattr_static(foo, 'a'), 3) |
| 2080 |
self.assertFalse(test.called) |
| 2081 |
|
| 2082 |
def test_metaclass_dict_as_property(self): |
| 2083 |
class Meta(type): |
| 2084 |
@property |
| 2085 |
def __dict__(self): |
| 2086 |
self.executed = True |
| 2087 |
|
| 2088 |
class Thing(metaclass=Meta): |
| 2089 |
executed = False |
| 2090 |
|
| 2091 |
def __init__(self): |
| 2092 |
self.spam = 42 |
| 2093 |
|
| 2094 |
instance = Thing() |
| 2095 |
self.assertEqual(inspect.getattr_static(instance, "spam"), 42) |
| 2096 |
self.assertFalse(Thing.executed) |
| 2097 |
|
| 2098 |
def test_module(self): |
| 2099 |
sentinel = object() |
| 2100 |
self.assertIsNot(inspect.getattr_static(sys, "version", sentinel), |
| 2101 |
sentinel) |
| 2102 |
|
| 2103 |
def test_metaclass_with_metaclass_with_dict_as_property(self): |
| 2104 |
class MetaMeta(type): |
| 2105 |
@property |
| 2106 |
def __dict__(self): |
| 2107 |
self.executed = True |
| 2108 |
return dict(spam=42) |
| 2109 |
|
| 2110 |
class Meta(type, metaclass=MetaMeta): |
| 2111 |
executed = False |
| 2112 |
|
| 2113 |
class Thing(metaclass=Meta): |
| 2114 |
pass |
| 2115 |
|
| 2116 |
with self.assertRaises(AttributeError): |
| 2117 |
inspect.getattr_static(Thing, "spam") |
| 2118 |
self.assertFalse(Thing.executed) |
| 2119 |
|
| 2120 |
def test_custom___getattr__(self): |
| 2121 |
test = self |
| 2122 |
test.called = False |
| 2123 |
|
| 2124 |
class Foo: |
| 2125 |
def __getattr__(self, attr): |
| 2126 |
test.called = True |
| 2127 |
return {} |
| 2128 |
|
| 2129 |
with self.assertRaises(AttributeError): |
| 2130 |
inspect.getattr_static(Foo(), 'whatever') |
| 2131 |
|
| 2132 |
self.assertFalse(test.called) |
| 2133 |
|
| 2134 |
def test_custom___getattribute__(self): |
| 2135 |
test = self |
| 2136 |
test.called = False |
| 2137 |
|
| 2138 |
class Foo: |
| 2139 |
def __getattribute__(self, attr): |
| 2140 |
test.called = True |
| 2141 |
return {} |
| 2142 |
|
| 2143 |
with self.assertRaises(AttributeError): |
| 2144 |
inspect.getattr_static(Foo(), 'really_could_be_anything') |
| 2145 |
|
| 2146 |
self.assertFalse(test.called) |
| 2147 |
|
| 2148 |
|
| 2149 |
class TestGetGeneratorState(unittest.TestCase): |
| 2150 |
|
| 2151 |
def setUp(self): |
| 2152 |
def number_generator(): |
| 2153 |
for number in range(5): |
| 2154 |
yield number |
| 2155 |
self.generator = number_generator() |
| 2156 |
|
| 2157 |
def _generatorstate(self): |
| 2158 |
return inspect.getgeneratorstate(self.generator) |
| 2159 |
|
| 2160 |
def test_created(self): |
| 2161 |
self.assertEqual(self._generatorstate(), inspect.GEN_CREATED) |
| 2162 |
|
| 2163 |
def test_suspended(self): |
| 2164 |
next(self.generator) |
| 2165 |
self.assertEqual(self._generatorstate(), inspect.GEN_SUSPENDED) |
| 2166 |
|
| 2167 |
def test_closed_after_exhaustion(self): |
| 2168 |
for i in self.generator: |
| 2169 |
pass |
| 2170 |
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 2171 |
|
| 2172 |
def test_closed_after_immediate_exception(self): |
| 2173 |
with self.assertRaises(RuntimeError): |
| 2174 |
self.generator.throw(RuntimeError) |
| 2175 |
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 2176 |
|
| 2177 |
def test_running(self): |
| 2178 |
|
| 2179 |
|
| 2180 |
|
| 2181 |
|
| 2182 |
def running_check_generator(): |
| 2183 |
for number in range(5): |
| 2184 |
self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING) |
| 2185 |
yield number |
| 2186 |
self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING) |
| 2187 |
self.generator = running_check_generator() |
| 2188 |
|
| 2189 |
next(self.generator) |
| 2190 |
|
| 2191 |
next(self.generator) |
| 2192 |
|
| 2193 |
def test_easy_debugging(self): |
| 2194 |
|
| 2195 |
names = 'GEN_CREATED GEN_RUNNING GEN_SUSPENDED GEN_CLOSED'.split() |
| 2196 |
for name in names: |
| 2197 |
state = getattr(inspect, name) |
| 2198 |
self.assertIn(name, repr(state)) |
| 2199 |
self.assertIn(name, str(state)) |
| 2200 |
|
| 2201 |
def test_getgeneratorlocals(self): |
| 2202 |
def each(lst, a=None): |
| 2203 |
b=(1, 2, 3) |
| 2204 |
for v in lst: |
| 2205 |
if v == 3: |
| 2206 |
c = 12 |
| 2207 |
yield v |
| 2208 |
|
| 2209 |
numbers = each([1, 2, 3]) |
| 2210 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2211 |
{'a': None, 'lst': [1, 2, 3]}) |
| 2212 |
next(numbers) |
| 2213 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2214 |
{'a': None, 'lst': [1, 2, 3], 'v': 1, |
| 2215 |
'b': (1, 2, 3)}) |
| 2216 |
next(numbers) |
| 2217 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2218 |
{'a': None, 'lst': [1, 2, 3], 'v': 2, |
| 2219 |
'b': (1, 2, 3)}) |
| 2220 |
next(numbers) |
| 2221 |
self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 2222 |
{'a': None, 'lst': [1, 2, 3], 'v': 3, |
| 2223 |
'b': (1, 2, 3), 'c': 12}) |
| 2224 |
try: |
| 2225 |
next(numbers) |
| 2226 |
except StopIteration: |
| 2227 |
pass |
| 2228 |
self.assertEqual(inspect.getgeneratorlocals(numbers), {}) |
| 2229 |
|
| 2230 |
def test_getgeneratorlocals_empty(self): |
| 2231 |
def yield_one(): |
| 2232 |
yield 1 |
| 2233 |
one = yield_one() |
| 2234 |
self.assertEqual(inspect.getgeneratorlocals(one), {}) |
| 2235 |
try: |
| 2236 |
next(one) |
| 2237 |
except StopIteration: |
| 2238 |
pass |
| 2239 |
self.assertEqual(inspect.getgeneratorlocals(one), {}) |
| 2240 |
|
| 2241 |
def test_getgeneratorlocals_error(self): |
| 2242 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, 1) |
| 2243 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, lambda x: True) |
| 2244 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, set) |
| 2245 |
self.assertRaises(TypeError, inspect.getgeneratorlocals, (2,3)) |
| 2246 |
|
| 2247 |
|
| 2248 |
class TestGetCoroutineState(unittest.TestCase): |
| 2249 |
|
| 2250 |
def setUp(self): |
| 2251 |
@types.coroutine |
| 2252 |
def number_coroutine(): |
| 2253 |
for number in range(5): |
| 2254 |
yield number |
| 2255 |
async def coroutine(): |
| 2256 |
await number_coroutine() |
| 2257 |
self.coroutine = coroutine() |
| 2258 |
|
| 2259 |
def tearDown(self): |
| 2260 |
self.coroutine.close() |
| 2261 |
|
| 2262 |
def _coroutinestate(self): |
| 2263 |
return inspect.getcoroutinestate(self.coroutine) |
| 2264 |
|
| 2265 |
def test_created(self): |
| 2266 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CREATED) |
| 2267 |
|
| 2268 |
def test_suspended(self): |
| 2269 |
self.coroutine.send(None) |
| 2270 |
self.assertEqual(self._coroutinestate(), inspect.CORO_SUSPENDED) |
| 2271 |
|
| 2272 |
def test_closed_after_exhaustion(self): |
| 2273 |
while True: |
| 2274 |
try: |
| 2275 |
self.coroutine.send(None) |
| 2276 |
except StopIteration: |
| 2277 |
break |
| 2278 |
|
| 2279 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 2280 |
|
| 2281 |
def test_closed_after_immediate_exception(self): |
| 2282 |
with self.assertRaises(RuntimeError): |
| 2283 |
self.coroutine.throw(RuntimeError) |
| 2284 |
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 2285 |
|
| 2286 |
def test_easy_debugging(self): |
| 2287 |
|
| 2288 |
names = 'CORO_CREATED CORO_RUNNING CORO_SUSPENDED CORO_CLOSED'.split() |
| 2289 |
for name in names: |
| 2290 |
state = getattr(inspect, name) |
| 2291 |
self.assertIn(name, repr(state)) |
| 2292 |
self.assertIn(name, str(state)) |
| 2293 |
|
| 2294 |
def test_getcoroutinelocals(self): |
| 2295 |
@types.coroutine |
| 2296 |
def gencoro(): |
| 2297 |
yield |
| 2298 |
|
| 2299 |
gencoro = gencoro() |
| 2300 |
async def func(a=None): |
| 2301 |
b = 'spam' |
| 2302 |
await gencoro |
| 2303 |
|
| 2304 |
coro = func() |
| 2305 |
self.assertEqual(inspect.getcoroutinelocals(coro), |
| 2306 |
{'a': None, 'gencoro': gencoro}) |
| 2307 |
coro.send(None) |
| 2308 |
self.assertEqual(inspect.getcoroutinelocals(coro), |
| 2309 |
{'a': None, 'gencoro': gencoro, 'b': 'spam'}) |
| 2310 |
|
| 2311 |
|
| 2312 |
class MySignature(inspect.Signature): |
| 2313 |
|
| 2314 |
|
| 2315 |
pass |
| 2316 |
|
| 2317 |
class MyParameter(inspect.Parameter): |
| 2318 |
|
| 2319 |
|
| 2320 |
pass |
| 2321 |
|
| 2322 |
|
| 2323 |
|
| 2324 |
class TestSignatureObject(unittest.TestCase): |
| 2325 |
@staticmethod |
| 2326 |
def signature(func, **kw): |
| 2327 |
sig = inspect.signature(func, **kw) |
| 2328 |
return (tuple((param.name, |
| 2329 |
(... if param.default is param.empty else param.default), |
| 2330 |
(... if param.annotation is param.empty |
| 2331 |
else param.annotation), |
| 2332 |
str(param.kind).lower()) |
| 2333 |
for param in sig.parameters.values()), |
| 2334 |
(... if sig.return_annotation is sig.empty |
| 2335 |
else sig.return_annotation)) |
| 2336 |
|
| 2337 |
def test_signature_object(self): |
| 2338 |
S = inspect.Signature |
| 2339 |
P = inspect.Parameter |
| 2340 |
|
| 2341 |
self.assertEqual(str(S()), '()') |
| 2342 |
self.assertEqual(repr(S().parameters), 'mappingproxy(OrderedDict())') |
| 2343 |
|
| 2344 |
def test(po, /, pk, pkd=100, *args, ko, kod=10, **kwargs): |
| 2345 |
pass |
| 2346 |
|
| 2347 |
sig = inspect.signature(test) |
| 2348 |
self.assertTrue(repr(sig).startswith('<Signature')) |
| 2349 |
self.assertTrue('(po, /, pk' in repr(sig)) |
| 2350 |
|
| 2351 |
|
| 2352 |
|
| 2353 |
def test2(pod=42, /): |
| 2354 |
pass |
| 2355 |
|
| 2356 |
sig2 = inspect.signature(test2) |
| 2357 |
self.assertTrue(repr(sig2).startswith('<Signature')) |
| 2358 |
self.assertTrue('(pod=42, /)' in repr(sig2)) |
| 2359 |
|
| 2360 |
po = sig.parameters['po'] |
| 2361 |
pod = sig2.parameters['pod'] |
| 2362 |
pk = sig.parameters['pk'] |
| 2363 |
pkd = sig.parameters['pkd'] |
| 2364 |
args = sig.parameters['args'] |
| 2365 |
ko = sig.parameters['ko'] |
| 2366 |
kod = sig.parameters['kod'] |
| 2367 |
kwargs = sig.parameters['kwargs'] |
| 2368 |
|
| 2369 |
S((po, pk, args, ko, kwargs)) |
| 2370 |
S((po, pk, ko, kod)) |
| 2371 |
S((po, pod, ko)) |
| 2372 |
S((po, pod, kod)) |
| 2373 |
S((pod, ko, kod)) |
| 2374 |
S((pod, kod)) |
| 2375 |
S((pod, args, kod, kwargs)) |
| 2376 |
|
| 2377 |
|
| 2378 |
S((kod, ko)) |
| 2379 |
S((kod, ko, kwargs)) |
| 2380 |
S((args, kod, ko)) |
| 2381 |
|
| 2382 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 2383 |
S((pk, po, args, ko, kwargs)) |
| 2384 |
|
| 2385 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 2386 |
S((po, args, pk, ko, kwargs)) |
| 2387 |
|
| 2388 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 2389 |
S((args, po, pk, ko, kwargs)) |
| 2390 |
|
| 2391 |
with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
| 2392 |
S((po, pk, args, kwargs, ko)) |
| 2393 |
|
| 2394 |
kwargs2 = kwargs.replace(name='args') |
| 2395 |
with self.assertRaisesRegex(ValueError, 'duplicate parameter name'): |
| 2396 |
S((po, pk, args, kwargs2, ko)) |
| 2397 |
|
| 2398 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 2399 |
S((pod, po)) |
| 2400 |
|
| 2401 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 2402 |
S((pod, pk)) |
| 2403 |
|
| 2404 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 2405 |
S((po, pod, pk)) |
| 2406 |
|
| 2407 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 2408 |
S((po, pkd, pk)) |
| 2409 |
|
| 2410 |
with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 2411 |
S((pkd, pk)) |
| 2412 |
|
| 2413 |
def test_signature_object_pickle(self): |
| 2414 |
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 2415 |
foo_partial = functools.partial(foo, a=1) |
| 2416 |
|
| 2417 |
sig = inspect.signature(foo_partial) |
| 2418 |
|
| 2419 |
for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 2420 |
with self.subTest(pickle_ver=ver, subclass=False): |
| 2421 |
sig_pickled = pickle.loads(pickle.dumps(sig, ver)) |
| 2422 |
self.assertEqual(sig, sig_pickled) |
| 2423 |
|
| 2424 |
|
| 2425 |
sig = inspect.signature(foo) |
| 2426 |
myparam = MyParameter(name='z', kind=inspect.Parameter.POSITIONAL_ONLY) |
| 2427 |
myparams = collections.OrderedDict(sig.parameters, a=myparam) |
| 2428 |
mysig = MySignature().replace(parameters=myparams.values(), |
| 2429 |
return_annotation=sig.return_annotation) |
| 2430 |
self.assertTrue(isinstance(mysig, MySignature)) |
| 2431 |
self.assertTrue(isinstance(mysig.parameters['z'], MyParameter)) |
| 2432 |
|
| 2433 |
for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 2434 |
with self.subTest(pickle_ver=ver, subclass=True): |
| 2435 |
sig_pickled = pickle.loads(pickle.dumps(mysig, ver)) |
| 2436 |
self.assertEqual(mysig, sig_pickled) |
| 2437 |
self.assertTrue(isinstance(sig_pickled, MySignature)) |
| 2438 |
self.assertTrue(isinstance(sig_pickled.parameters['z'], |
| 2439 |
MyParameter)) |
| 2440 |
|
| 2441 |
def test_signature_immutability(self): |
| 2442 |
def test(a): |
| 2443 |
pass |
| 2444 |
sig = inspect.signature(test) |
| 2445 |
|
| 2446 |
with self.assertRaises(AttributeError): |
| 2447 |
sig.foo = 'bar' |
| 2448 |
|
| 2449 |
with self.assertRaises(TypeError): |
| 2450 |
sig.parameters['a'] = None |
| 2451 |
|
| 2452 |
def test_signature_on_noarg(self): |
| 2453 |
def test(): |
| 2454 |
pass |
| 2455 |
self.assertEqual(self.signature(test), ((), ...)) |
| 2456 |
|
| 2457 |
def test_signature_on_wargs(self): |
| 2458 |
def test(a, b:'foo') -> 123: |
| 2459 |
pass |
| 2460 |
self.assertEqual(self.signature(test), |
| 2461 |
((('a', ..., ..., "positional_or_keyword"), |
| 2462 |
('b', ..., 'foo', "positional_or_keyword")), |
| 2463 |
123)) |
| 2464 |
|
| 2465 |
def test_signature_on_wkwonly(self): |
| 2466 |
def test(*, a:float, b:str) -> int: |
| 2467 |
pass |
| 2468 |
self.assertEqual(self.signature(test), |
| 2469 |
((('a', ..., float, "keyword_only"), |
| 2470 |
('b', ..., str, "keyword_only")), |
| 2471 |
int)) |
| 2472 |
|
| 2473 |
def test_signature_on_complex_args(self): |
| 2474 |
def test(a, b:'foo'=10, *args:'bar', spam:'baz', ham=123, **kwargs:int): |
| 2475 |
pass |
| 2476 |
self.assertEqual(self.signature(test), |
| 2477 |
((('a', ..., ..., "positional_or_keyword"), |
| 2478 |
('b', 10, 'foo', "positional_or_keyword"), |
| 2479 |
('args', ..., 'bar', "var_positional"), |
| 2480 |
('spam', ..., 'baz', "keyword_only"), |
| 2481 |
('ham', 123, ..., "keyword_only"), |
| 2482 |
('kwargs', ..., int, "var_keyword")), |
| 2483 |
...)) |
| 2484 |
|
| 2485 |
def test_signature_without_self(self): |
| 2486 |
def test_args_only(*args): |
| 2487 |
pass |
| 2488 |
|
| 2489 |
def test_args_kwargs_only(*args, **kwargs): |
| 2490 |
pass |
| 2491 |
|
| 2492 |
class A: |
| 2493 |
@classmethod |
| 2494 |
def test_classmethod(*args): |
| 2495 |
pass |
| 2496 |
|
| 2497 |
@staticmethod |
| 2498 |
def test_staticmethod(*args): |
| 2499 |
pass |
| 2500 |
|
| 2501 |
f1 = functools.partialmethod((test_classmethod), 1) |
| 2502 |
f2 = functools.partialmethod((test_args_only), 1) |
| 2503 |
f3 = functools.partialmethod((test_staticmethod), 1) |
| 2504 |
f4 = functools.partialmethod((test_args_kwargs_only),1) |
| 2505 |
|
| 2506 |
self.assertEqual(self.signature(test_args_only), |
| 2507 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 2508 |
self.assertEqual(self.signature(test_args_kwargs_only), |
| 2509 |
((('args', ..., ..., 'var_positional'), |
| 2510 |
('kwargs', ..., ..., 'var_keyword')), ...)) |
| 2511 |
self.assertEqual(self.signature(A.f1), |
| 2512 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 2513 |
self.assertEqual(self.signature(A.f2), |
| 2514 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 2515 |
self.assertEqual(self.signature(A.f3), |
| 2516 |
((('args', ..., ..., 'var_positional'),), ...)) |
| 2517 |
self.assertEqual(self.signature(A.f4), |
| 2518 |
((('args', ..., ..., 'var_positional'), |
| 2519 |
('kwargs', ..., ..., 'var_keyword')), ...)) |
| 2520 |
@cpython_only |
| 2521 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 2522 |
"Signature information for builtins requires docstrings") |
| 2523 |
def test_signature_on_builtins(self): |
| 2524 |
import _testcapi |
| 2525 |
|
| 2526 |
def test_unbound_method(o): |
| 2527 |
"""Use this to test unbound methods (things that should have a self)""" |
| 2528 |
signature = inspect.signature(o) |
| 2529 |
self.assertTrue(isinstance(signature, inspect.Signature)) |
| 2530 |
self.assertEqual(list(signature.parameters.values())[0].name, 'self') |
| 2531 |
return signature |
| 2532 |
|
| 2533 |
def test_callable(o): |
| 2534 |
"""Use this to test bound methods or normal callables (things that don't expect self)""" |
| 2535 |
signature = inspect.signature(o) |
| 2536 |
self.assertTrue(isinstance(signature, inspect.Signature)) |
| 2537 |
if signature.parameters: |
| 2538 |
self.assertNotEqual(list(signature.parameters.values())[0].name, 'self') |
| 2539 |
return signature |
| 2540 |
|
| 2541 |
signature = test_callable(_testcapi.docstring_with_signature_with_defaults) |
| 2542 |
def p(name): return signature.parameters[name].default |
| 2543 |
self.assertEqual(p('s'), 'avocado') |
| 2544 |
self.assertEqual(p('b'), b'bytes') |
| 2545 |
self.assertEqual(p('d'), 3.14) |
| 2546 |
self.assertEqual(p('i'), 35) |
| 2547 |
self.assertEqual(p('n'), None) |
| 2548 |
self.assertEqual(p('t'), True) |
| 2549 |
self.assertEqual(p('f'), False) |
| 2550 |
self.assertEqual(p('local'), 3) |
| 2551 |
self.assertEqual(p('sys'), sys.maxsize) |
| 2552 |
self.assertEqual(p('exp'), sys.maxsize - 1) |
| 2553 |
|
| 2554 |
test_callable(object) |
| 2555 |
|
| 2556 |
|
| 2557 |
|
| 2558 |
test_unbound_method(_pickle.Pickler.dump) |
| 2559 |
d = _pickle.Pickler(io.StringIO()) |
| 2560 |
test_callable(d.dump) |
| 2561 |
|
| 2562 |
|
| 2563 |
test_callable(bytes.maketrans) |
| 2564 |
test_callable(b'abc'.maketrans) |
| 2565 |
|
| 2566 |
|
| 2567 |
test_callable(dict.fromkeys) |
| 2568 |
test_callable({}.fromkeys) |
| 2569 |
|
| 2570 |
|
| 2571 |
test_unbound_method(type.__call__) |
| 2572 |
test_unbound_method(int.__add__) |
| 2573 |
test_callable((3).__add__) |
| 2574 |
|
| 2575 |
|
| 2576 |
|
| 2577 |
test_callable(min.__call__) |
| 2578 |
|
| 2579 |
|
| 2580 |
|
| 2581 |
class ThisWorksNow: |
| 2582 |
__call__ = type |
| 2583 |
|
| 2584 |
self.assertEqual(ThisWorksNow()(1), int) |
| 2585 |
self.assertEqual(ThisWorksNow()('A', (), {}).__name__, 'A') |
| 2586 |
with self.assertRaisesRegex(ValueError, "no signature found"): |
| 2587 |
test_callable(ThisWorksNow()) |
| 2588 |
|
| 2589 |
|
| 2590 |
test_unbound_method(dict.__delitem__) |
| 2591 |
test_unbound_method(property.__delete__) |
| 2592 |
|
| 2593 |
|
| 2594 |
test_callable(_testcapi.docstring_with_signature_but_no_doc) |
| 2595 |
|
| 2596 |
@cpython_only |
| 2597 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 2598 |
"Signature information for builtins requires docstrings") |
| 2599 |
def test_signature_on_decorated_builtins(self): |
| 2600 |
import _testcapi |
| 2601 |
func = _testcapi.docstring_with_signature_with_defaults |
| 2602 |
|
| 2603 |
def decorator(func): |
| 2604 |
@functools.wraps(func) |
| 2605 |
def wrapper(*args, **kwargs) -> int: |
| 2606 |
return func(*args, **kwargs) |
| 2607 |
return wrapper |
| 2608 |
|
| 2609 |
decorated_func = decorator(func) |
| 2610 |
|
| 2611 |
self.assertEqual(inspect.signature(func), |
| 2612 |
inspect.signature(decorated_func)) |
| 2613 |
|
| 2614 |
def wrapper_like(*args, **kwargs) -> int: pass |
| 2615 |
self.assertEqual(inspect.signature(decorated_func, |
| 2616 |
follow_wrapped=False), |
| 2617 |
inspect.signature(wrapper_like)) |
| 2618 |
|
| 2619 |
@cpython_only |
| 2620 |
def test_signature_on_builtins_no_signature(self): |
| 2621 |
import _testcapi |
| 2622 |
with self.assertRaisesRegex(ValueError, |
| 2623 |
'no signature found for builtin'): |
| 2624 |
inspect.signature(_testcapi.docstring_no_signature) |
| 2625 |
|
| 2626 |
with self.assertRaisesRegex(ValueError, |
| 2627 |
'no signature found for builtin'): |
| 2628 |
inspect.signature(str) |
| 2629 |
|
| 2630 |
def test_signature_on_non_function(self): |
| 2631 |
with self.assertRaisesRegex(TypeError, 'is not a callable object'): |
| 2632 |
inspect.signature(42) |
| 2633 |
|
| 2634 |
def test_signature_from_functionlike_object(self): |
| 2635 |
def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): |
| 2636 |
pass |
| 2637 |
|
| 2638 |
class funclike: |
| 2639 |
|
| 2640 |
|
| 2641 |
|
| 2642 |
|
| 2643 |
def __init__(self, func): |
| 2644 |
self.__name__ = func.__name__ |
| 2645 |
self.__code__ = func.__code__ |
| 2646 |
self.__annotations__ = func.__annotations__ |
| 2647 |
self.__defaults__ = func.__defaults__ |
| 2648 |
self.__kwdefaults__ = func.__kwdefaults__ |
| 2649 |
self.func = func |
| 2650 |
|
| 2651 |
def __call__(self, *args, **kwargs): |
| 2652 |
return self.func(*args, **kwargs) |
| 2653 |
|
| 2654 |
sig_func = inspect.Signature.from_callable(func) |
| 2655 |
|
| 2656 |
sig_funclike = inspect.Signature.from_callable(funclike(func)) |
| 2657 |
self.assertEqual(sig_funclike, sig_func) |
| 2658 |
|
| 2659 |
sig_funclike = inspect.signature(funclike(func)) |
| 2660 |
self.assertEqual(sig_funclike, sig_func) |
| 2661 |
|
| 2662 |
|
| 2663 |
|
| 2664 |
|
| 2665 |
fl = funclike(func) |
| 2666 |
del fl.__defaults__ |
| 2667 |
self.assertEqual(self.signature(fl), |
| 2668 |
((('args', ..., ..., "var_positional"), |
| 2669 |
('kwargs', ..., ..., "var_keyword")), |
| 2670 |
...)) |
| 2671 |
|
| 2672 |
|
| 2673 |
_orig_isdesc = inspect.ismethoddescriptor |
| 2674 |
def _isdesc(obj): |
| 2675 |
if hasattr(obj, '_builtinmock'): |
| 2676 |
return True |
| 2677 |
return _orig_isdesc(obj) |
| 2678 |
|
| 2679 |
with unittest.mock.patch('inspect.ismethoddescriptor', _isdesc): |
| 2680 |
builtin_func = funclike(func) |
| 2681 |
|
| 2682 |
self.assertFalse(inspect.ismethoddescriptor(builtin_func)) |
| 2683 |
builtin_func._builtinmock = True |
| 2684 |
self.assertTrue(inspect.ismethoddescriptor(builtin_func)) |
| 2685 |
self.assertEqual(inspect.signature(builtin_func), sig_func) |
| 2686 |
|
| 2687 |
def test_signature_functionlike_class(self): |
| 2688 |
|
| 2689 |
|
| 2690 |
|
| 2691 |
def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): |
| 2692 |
pass |
| 2693 |
|
| 2694 |
class funclike: |
| 2695 |
def __init__(self, marker): |
| 2696 |
pass |
| 2697 |
|
| 2698 |
__name__ = func.__name__ |
| 2699 |
__code__ = func.__code__ |
| 2700 |
__annotations__ = func.__annotations__ |
| 2701 |
__defaults__ = func.__defaults__ |
| 2702 |
__kwdefaults__ = func.__kwdefaults__ |
| 2703 |
|
| 2704 |
self.assertEqual(str(inspect.signature(funclike)), '(marker)') |
| 2705 |
|
| 2706 |
def test_signature_on_method(self): |
| 2707 |
class Test: |
| 2708 |
def __init__(*args): |
| 2709 |
pass |
| 2710 |
def m1(self, arg1, arg2=1) -> int: |
| 2711 |
pass |
| 2712 |
def m2(*args): |
| 2713 |
pass |
| 2714 |
def __call__(*, a): |
| 2715 |
pass |
| 2716 |
|
| 2717 |
self.assertEqual(self.signature(Test().m1), |
| 2718 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 2719 |
('arg2', 1, ..., "positional_or_keyword")), |
| 2720 |
int)) |
| 2721 |
|
| 2722 |
self.assertEqual(self.signature(Test().m2), |
| 2723 |
((('args', ..., ..., "var_positional"),), |
| 2724 |
...)) |
| 2725 |
|
| 2726 |
self.assertEqual(self.signature(Test), |
| 2727 |
((('args', ..., ..., "var_positional"),), |
| 2728 |
...)) |
| 2729 |
|
| 2730 |
with self.assertRaisesRegex(ValueError, 'invalid method signature'): |
| 2731 |
self.signature(Test()) |
| 2732 |
|
| 2733 |
def test_signature_wrapped_bound_method(self): |
| 2734 |
|
| 2735 |
class Test: |
| 2736 |
def m1(self, arg1, arg2=1) -> int: |
| 2737 |
pass |
| 2738 |
@functools.wraps(Test().m1) |
| 2739 |
def m1d(*args, **kwargs): |
| 2740 |
pass |
| 2741 |
self.assertEqual(self.signature(m1d), |
| 2742 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 2743 |
('arg2', 1, ..., "positional_or_keyword")), |
| 2744 |
int)) |
| 2745 |
|
| 2746 |
def test_signature_on_classmethod(self): |
| 2747 |
class Test: |
| 2748 |
@classmethod |
| 2749 |
def foo(cls, arg1, *, arg2=1): |
| 2750 |
pass |
| 2751 |
|
| 2752 |
meth = Test().foo |
| 2753 |
self.assertEqual(self.signature(meth), |
| 2754 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 2755 |
('arg2', 1, ..., "keyword_only")), |
| 2756 |
...)) |
| 2757 |
|
| 2758 |
meth = Test.foo |
| 2759 |
self.assertEqual(self.signature(meth), |
| 2760 |
((('arg1', ..., ..., "positional_or_keyword"), |
| 2761 |
('arg2', 1, ..., "keyword_only")), |
| 2762 |
...)) |
| 2763 |
|
| 2764 |
def test_signature_on_staticmethod(self): |
| 2765 |
class Test: |
| 2766 |
@staticmethod |
| 2767 |
def foo(cls, *, arg): |
| 2768 |
pass |
| 2769 |
|
| 2770 |
meth = Test().foo |
| 2771 |
self.assertEqual(self.signature(meth), |
| 2772 |
((('cls', ..., ..., "positional_or_keyword"), |
| 2773 |
('arg', ..., ..., "keyword_only")), |
| 2774 |
...)) |
| 2775 |
|
| 2776 |
meth = Test.foo |
| 2777 |
self.assertEqual(self.signature(meth), |
| 2778 |
((('cls', ..., ..., "positional_or_keyword"), |
| 2779 |
('arg', ..., ..., "keyword_only")), |
| 2780 |
...)) |
| 2781 |
|
| 2782 |
def test_signature_on_partial(self): |
| 2783 |
from functools import partial |
| 2784 |
|
| 2785 |
def test(): |
| 2786 |
pass |
| 2787 |
|
| 2788 |
self.assertEqual(self.signature(partial(test)), ((), ...)) |
| 2789 |
|
| 2790 |
with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 2791 |
inspect.signature(partial(test, 1)) |
| 2792 |
|
| 2793 |
with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 2794 |
inspect.signature(partial(test, a=1)) |
| 2795 |
|
| 2796 |
def test(a, b, *, c, d): |
| 2797 |
pass |
| 2798 |
|
| 2799 |
self.assertEqual(self.signature(partial(test)), |
| 2800 |
((('a', ..., ..., "positional_or_keyword"), |
| 2801 |
('b', ..., ..., "positional_or_keyword"), |
| 2802 |
('c', ..., ..., "keyword_only"), |
| 2803 |
('d', ..., ..., "keyword_only")), |
| 2804 |
...)) |
| 2805 |
|
| 2806 |
self.assertEqual(self.signature(partial(test, 1)), |
| 2807 |
((('b', ..., ..., "positional_or_keyword"), |
| 2808 |
('c', ..., ..., "keyword_only"), |
| 2809 |
('d', ..., ..., "keyword_only")), |
| 2810 |
...)) |
| 2811 |
|
| 2812 |
self.assertEqual(self.signature(partial(test, 1, c=2)), |
| 2813 |
((('b', ..., ..., "positional_or_keyword"), |
| 2814 |
('c', 2, ..., "keyword_only"), |
| 2815 |
('d', ..., ..., "keyword_only")), |
| 2816 |
...)) |
| 2817 |
|
| 2818 |
self.assertEqual(self.signature(partial(test, b=1, c=2)), |
| 2819 |
((('a', ..., ..., "positional_or_keyword"), |
| 2820 |
('b', 1, ..., "keyword_only"), |
| 2821 |
('c', 2, ..., "keyword_only"), |
| 2822 |
('d', ..., ..., "keyword_only")), |
| 2823 |
...)) |
| 2824 |
|
| 2825 |
self.assertEqual(self.signature(partial(test, 0, b=1, c=2)), |
| 2826 |
((('b', 1, ..., "keyword_only"), |
| 2827 |
('c', 2, ..., "keyword_only"), |
| 2828 |
('d', ..., ..., "keyword_only")), |
| 2829 |
...)) |
| 2830 |
|
| 2831 |
self.assertEqual(self.signature(partial(test, a=1)), |
| 2832 |
((('a', 1, ..., "keyword_only"), |
| 2833 |
('b', ..., ..., "keyword_only"), |
| 2834 |
('c', ..., ..., "keyword_only"), |
| 2835 |
('d', ..., ..., "keyword_only")), |
| 2836 |
...)) |
| 2837 |
|
| 2838 |
def test(a, *args, b, **kwargs): |
| 2839 |
pass |
| 2840 |
|
| 2841 |
self.assertEqual(self.signature(partial(test, 1)), |
| 2842 |
((('args', ..., ..., "var_positional"), |
| 2843 |
('b', ..., ..., "keyword_only"), |
| 2844 |
('kwargs', ..., ..., "var_keyword")), |
| 2845 |
...)) |
| 2846 |
|
| 2847 |
self.assertEqual(self.signature(partial(test, a=1)), |
| 2848 |
((('a', 1, ..., "keyword_only"), |
| 2849 |
('b', ..., ..., "keyword_only"), |
| 2850 |
('kwargs', ..., ..., "var_keyword")), |
| 2851 |
...)) |
| 2852 |
|
| 2853 |
self.assertEqual(self.signature(partial(test, 1, 2, 3)), |
| 2854 |
((('args', ..., ..., "var_positional"), |
| 2855 |
('b', ..., ..., "keyword_only"), |
| 2856 |
('kwargs', ..., ..., "var_keyword")), |
| 2857 |
...)) |
| 2858 |
|
| 2859 |
self.assertEqual(self.signature(partial(test, 1, 2, 3, test=True)), |
| 2860 |
((('args', ..., ..., "var_positional"), |
| 2861 |
('b', ..., ..., "keyword_only"), |
| 2862 |
('kwargs', ..., ..., "var_keyword")), |
| 2863 |
...)) |
| 2864 |
|
| 2865 |
self.assertEqual(self.signature(partial(test, 1, 2, 3, test=1, b=0)), |
| 2866 |
((('args', ..., ..., "var_positional"), |
| 2867 |
('b', 0, ..., "keyword_only"), |
| 2868 |
('kwargs', ..., ..., "var_keyword")), |
| 2869 |
...)) |
| 2870 |
|
| 2871 |
self.assertEqual(self.signature(partial(test, b=0)), |
| 2872 |
((('a', ..., ..., "positional_or_keyword"), |
| 2873 |
('args', ..., ..., "var_positional"), |
| 2874 |
('b', 0, ..., "keyword_only"), |
| 2875 |
('kwargs', ..., ..., "var_keyword")), |
| 2876 |
...)) |
| 2877 |
|
| 2878 |
self.assertEqual(self.signature(partial(test, b=0, test=1)), |
| 2879 |
((('a', ..., ..., "positional_or_keyword"), |
| 2880 |
('args', ..., ..., "var_positional"), |
| 2881 |
('b', 0, ..., "keyword_only"), |
| 2882 |
('kwargs', ..., ..., "var_keyword")), |
| 2883 |
...)) |
| 2884 |
|
| 2885 |
def test(a, b, c:int) -> 42: |
| 2886 |
pass |
| 2887 |
|
| 2888 |
sig = test.__signature__ = inspect.signature(test) |
| 2889 |
|
| 2890 |
self.assertEqual(self.signature(partial(partial(test, 1))), |
| 2891 |
((('b', ..., ..., "positional_or_keyword"), |
| 2892 |
('c', ..., int, "positional_or_keyword")), |
| 2893 |
42)) |
| 2894 |
|
| 2895 |
self.assertEqual(self.signature(partial(partial(test, 1), 2)), |
| 2896 |
((('c', ..., int, "positional_or_keyword"),), |
| 2897 |
42)) |
| 2898 |
|
| 2899 |
def foo(a): |
| 2900 |
return a |
| 2901 |
_foo = partial(partial(foo, a=10), a=20) |
| 2902 |
self.assertEqual(self.signature(_foo), |
| 2903 |
((('a', 20, ..., "keyword_only"),), |
| 2904 |
...)) |
| 2905 |
|
| 2906 |
|
| 2907 |
self.assertEqual(_foo(), 20) |
| 2908 |
|
| 2909 |
def foo(a, b, c): |
| 2910 |
return a, b, c |
| 2911 |
_foo = partial(partial(foo, 1, b=20), b=30) |
| 2912 |
|
| 2913 |
self.assertEqual(self.signature(_foo), |
| 2914 |
((('b', 30, ..., "keyword_only"), |
| 2915 |
('c', ..., ..., "keyword_only")), |
| 2916 |
...)) |
| 2917 |
self.assertEqual(_foo(c=10), (1, 30, 10)) |
| 2918 |
|
| 2919 |
def foo(a, b, c, *, d): |
| 2920 |
return a, b, c, d |
| 2921 |
_foo = partial(partial(foo, d=20, c=20), b=10, d=30) |
| 2922 |
self.assertEqual(self.signature(_foo), |
| 2923 |
((('a', ..., ..., "positional_or_keyword"), |
| 2924 |
('b', 10, ..., "keyword_only"), |
| 2925 |
('c', 20, ..., "keyword_only"), |
| 2926 |
('d', 30, ..., "keyword_only"), |
| 2927 |
), |
| 2928 |
...)) |
| 2929 |
ba = inspect.signature(_foo).bind(a=200, b=11) |
| 2930 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (200, 11, 20, 30)) |
| 2931 |
|
| 2932 |
def foo(a=1, b=2, c=3): |
| 2933 |
return a, b, c |
| 2934 |
_foo = partial(foo, c=13) |
| 2935 |
|
| 2936 |
ba = inspect.signature(_foo).bind(a=11) |
| 2937 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 2, 13)) |
| 2938 |
|
| 2939 |
ba = inspect.signature(_foo).bind(11, 12) |
| 2940 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) |
| 2941 |
|
| 2942 |
ba = inspect.signature(_foo).bind(11, b=12) |
| 2943 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) |
| 2944 |
|
| 2945 |
ba = inspect.signature(_foo).bind(b=12) |
| 2946 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (1, 12, 13)) |
| 2947 |
|
| 2948 |
_foo = partial(_foo, b=10, c=20) |
| 2949 |
ba = inspect.signature(_foo).bind(12) |
| 2950 |
self.assertEqual(_foo(*ba.args, **ba.kwargs), (12, 10, 20)) |
| 2951 |
|
| 2952 |
|
| 2953 |
def foo(a, b, /, c, d, **kwargs): |
| 2954 |
pass |
| 2955 |
sig = inspect.signature(foo) |
| 2956 |
self.assertEqual(str(sig), '(a, b, /, c, d, **kwargs)') |
| 2957 |
|
| 2958 |
self.assertEqual(self.signature(partial(foo, 1)), |
| 2959 |
((('b', ..., ..., 'positional_only'), |
| 2960 |
('c', ..., ..., 'positional_or_keyword'), |
| 2961 |
('d', ..., ..., 'positional_or_keyword'), |
| 2962 |
('kwargs', ..., ..., 'var_keyword')), |
| 2963 |
...)) |
| 2964 |
|
| 2965 |
self.assertEqual(self.signature(partial(foo, 1, 2)), |
| 2966 |
((('c', ..., ..., 'positional_or_keyword'), |
| 2967 |
('d', ..., ..., 'positional_or_keyword'), |
| 2968 |
('kwargs', ..., ..., 'var_keyword')), |
| 2969 |
...)) |
| 2970 |
|
| 2971 |
self.assertEqual(self.signature(partial(foo, 1, 2, 3)), |
| 2972 |
((('d', ..., ..., 'positional_or_keyword'), |
| 2973 |
('kwargs', ..., ..., 'var_keyword')), |
| 2974 |
...)) |
| 2975 |
|
| 2976 |
self.assertEqual(self.signature(partial(foo, 1, 2, c=3)), |
| 2977 |
((('c', 3, ..., 'keyword_only'), |
| 2978 |
('d', ..., ..., 'keyword_only'), |
| 2979 |
('kwargs', ..., ..., 'var_keyword')), |
| 2980 |
...)) |
| 2981 |
|
| 2982 |
self.assertEqual(self.signature(partial(foo, 1, c=3)), |
| 2983 |
((('b', ..., ..., 'positional_only'), |
| 2984 |
('c', 3, ..., 'keyword_only'), |
| 2985 |
('d', ..., ..., 'keyword_only'), |
| 2986 |
('kwargs', ..., ..., 'var_keyword')), |
| 2987 |
...)) |
| 2988 |
|
| 2989 |
def test_signature_on_partialmethod(self): |
| 2990 |
from functools import partialmethod |
| 2991 |
|
| 2992 |
class Spam: |
| 2993 |
def test(): |
| 2994 |
pass |
| 2995 |
ham = partialmethod(test) |
| 2996 |
|
| 2997 |
with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 2998 |
inspect.signature(Spam.ham) |
| 2999 |
|
| 3000 |
class Spam: |
| 3001 |
def test(it, a, *, c) -> 'spam': |
| 3002 |
pass |
| 3003 |
ham = partialmethod(test, c=1) |
| 3004 |
|
| 3005 |
self.assertEqual(self.signature(Spam.ham, eval_str=False), |
| 3006 |
((('it', ..., ..., 'positional_or_keyword'), |
| 3007 |
('a', ..., ..., 'positional_or_keyword'), |
| 3008 |
('c', 1, ..., 'keyword_only')), |
| 3009 |
'spam')) |
| 3010 |
|
| 3011 |
self.assertEqual(self.signature(Spam().ham, eval_str=False), |
| 3012 |
((('a', ..., ..., 'positional_or_keyword'), |
| 3013 |
('c', 1, ..., 'keyword_only')), |
| 3014 |
'spam')) |
| 3015 |
|
| 3016 |
class Spam: |
| 3017 |
def test(self: 'anno', x): |
| 3018 |
pass |
| 3019 |
|
| 3020 |
g = partialmethod(test, 1) |
| 3021 |
|
| 3022 |
self.assertEqual(self.signature(Spam.g, eval_str=False), |
| 3023 |
((('self', ..., 'anno', 'positional_or_keyword'),), |
| 3024 |
...)) |
| 3025 |
|
| 3026 |
def test_signature_on_fake_partialmethod(self): |
| 3027 |
def foo(a): pass |
| 3028 |
foo._partialmethod = 'spam' |
| 3029 |
self.assertEqual(str(inspect.signature(foo)), '(a)') |
| 3030 |
|
| 3031 |
def test_signature_on_decorated(self): |
| 3032 |
def decorator(func): |
| 3033 |
@functools.wraps(func) |
| 3034 |
def wrapper(*args, **kwargs) -> int: |
| 3035 |
return func(*args, **kwargs) |
| 3036 |
return wrapper |
| 3037 |
|
| 3038 |
class Foo: |
| 3039 |
@decorator |
| 3040 |
def bar(self, a, b): |
| 3041 |
pass |
| 3042 |
|
| 3043 |
bar = decorator(Foo().bar) |
| 3044 |
|
| 3045 |
self.assertEqual(self.signature(Foo.bar), |
| 3046 |
((('self', ..., ..., "positional_or_keyword"), |
| 3047 |
('a', ..., ..., "positional_or_keyword"), |
| 3048 |
('b', ..., ..., "positional_or_keyword")), |
| 3049 |
...)) |
| 3050 |
|
| 3051 |
self.assertEqual(self.signature(Foo().bar), |
| 3052 |
((('a', ..., ..., "positional_or_keyword"), |
| 3053 |
('b', ..., ..., "positional_or_keyword")), |
| 3054 |
...)) |
| 3055 |
|
| 3056 |
self.assertEqual(self.signature(Foo.bar, follow_wrapped=False), |
| 3057 |
((('args', ..., ..., "var_positional"), |
| 3058 |
('kwargs', ..., ..., "var_keyword")), |
| 3059 |
...)) |
| 3060 |
|
| 3061 |
|
| 3062 |
|
| 3063 |
self.assertEqual(self.signature(bar), |
| 3064 |
((('a', ..., ..., "positional_or_keyword"), |
| 3065 |
('b', ..., ..., "positional_or_keyword")), |
| 3066 |
...)) |
| 3067 |
|
| 3068 |
|
| 3069 |
def decorator(func): |
| 3070 |
@functools.wraps(func) |
| 3071 |
def wrapper(*args, **kwargs) -> int: |
| 3072 |
return func(42, *args, **kwargs) |
| 3073 |
sig = inspect.signature(func) |
| 3074 |
new_params = tuple(sig.parameters.values())[1:] |
| 3075 |
wrapper.__signature__ = sig.replace(parameters=new_params) |
| 3076 |
return wrapper |
| 3077 |
|
| 3078 |
class Foo: |
| 3079 |
@decorator |
| 3080 |
def __call__(self, a, b): |
| 3081 |
pass |
| 3082 |
|
| 3083 |
self.assertEqual(self.signature(Foo.__call__), |
| 3084 |
((('a', ..., ..., "positional_or_keyword"), |
| 3085 |
('b', ..., ..., "positional_or_keyword")), |
| 3086 |
...)) |
| 3087 |
|
| 3088 |
self.assertEqual(self.signature(Foo().__call__), |
| 3089 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3090 |
...)) |
| 3091 |
|
| 3092 |
|
| 3093 |
def wrapped_foo_call(): |
| 3094 |
pass |
| 3095 |
wrapped_foo_call.__wrapped__ = Foo.__call__ |
| 3096 |
|
| 3097 |
self.assertEqual(self.signature(wrapped_foo_call), |
| 3098 |
((('a', ..., ..., "positional_or_keyword"), |
| 3099 |
('b', ..., ..., "positional_or_keyword")), |
| 3100 |
...)) |
| 3101 |
|
| 3102 |
|
| 3103 |
def test_signature_on_class(self): |
| 3104 |
class C: |
| 3105 |
def __init__(self, a): |
| 3106 |
pass |
| 3107 |
|
| 3108 |
self.assertEqual(self.signature(C), |
| 3109 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3110 |
...)) |
| 3111 |
|
| 3112 |
class CM(type): |
| 3113 |
def __call__(cls, a): |
| 3114 |
pass |
| 3115 |
class C(metaclass=CM): |
| 3116 |
def __init__(self, b): |
| 3117 |
pass |
| 3118 |
|
| 3119 |
self.assertEqual(self.signature(C), |
| 3120 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3121 |
...)) |
| 3122 |
|
| 3123 |
with self.subTest('classmethod'): |
| 3124 |
class CM(type): |
| 3125 |
@classmethod |
| 3126 |
def __call__(cls, a): |
| 3127 |
return a |
| 3128 |
class C(metaclass=CM): |
| 3129 |
def __init__(self, b): |
| 3130 |
pass |
| 3131 |
|
| 3132 |
self.assertEqual(C(1), 1) |
| 3133 |
self.assertEqual(self.signature(C), |
| 3134 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3135 |
...)) |
| 3136 |
|
| 3137 |
with self.subTest('staticmethod'): |
| 3138 |
class CM(type): |
| 3139 |
@staticmethod |
| 3140 |
def __call__(a): |
| 3141 |
return a |
| 3142 |
class C(metaclass=CM): |
| 3143 |
def __init__(self, b): |
| 3144 |
pass |
| 3145 |
|
| 3146 |
self.assertEqual(C(1), 1) |
| 3147 |
self.assertEqual(self.signature(C), |
| 3148 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3149 |
...)) |
| 3150 |
|
| 3151 |
with self.subTest('MethodType'): |
| 3152 |
class A: |
| 3153 |
def call(self, a): |
| 3154 |
return a |
| 3155 |
class CM(type): |
| 3156 |
__call__ = A().call |
| 3157 |
class C(metaclass=CM): |
| 3158 |
def __init__(self, b): |
| 3159 |
pass |
| 3160 |
|
| 3161 |
self.assertEqual(C(1), 1) |
| 3162 |
self.assertEqual(self.signature(C), |
| 3163 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3164 |
...)) |
| 3165 |
|
| 3166 |
with self.subTest('partial'): |
| 3167 |
class CM(type): |
| 3168 |
__call__ = functools.partial(lambda x, a: (x, a), 2) |
| 3169 |
class C(metaclass=CM): |
| 3170 |
def __init__(self, b): |
| 3171 |
pass |
| 3172 |
|
| 3173 |
self.assertEqual(C(1), (2, 1)) |
| 3174 |
self.assertEqual(self.signature(C), |
| 3175 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3176 |
...)) |
| 3177 |
|
| 3178 |
with self.subTest('partialmethod'): |
| 3179 |
class CM(type): |
| 3180 |
__call__ = functools.partialmethod(lambda self, x, a: (x, a), 2) |
| 3181 |
class C(metaclass=CM): |
| 3182 |
def __init__(self, b): |
| 3183 |
pass |
| 3184 |
|
| 3185 |
self.assertEqual(C(1), (2, 1)) |
| 3186 |
self.assertEqual(self.signature(C), |
| 3187 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3188 |
...)) |
| 3189 |
|
| 3190 |
with self.subTest('BuiltinMethodType'): |
| 3191 |
class CM(type): |
| 3192 |
__call__ = ':'.join |
| 3193 |
class C(metaclass=CM): |
| 3194 |
def __init__(self, b): |
| 3195 |
pass |
| 3196 |
|
| 3197 |
self.assertEqual(C(['a', 'bc']), 'a:bc') |
| 3198 |
if '__pypy__' in sys.modules: |
| 3199 |
|
| 3200 |
self.assertEqual(self.signature(C), self.signature(''.join)) |
| 3201 |
else: |
| 3202 |
|
| 3203 |
with self.assertRaises(AssertionError): |
| 3204 |
self.assertEqual(self.signature(C), self.signature(''.join)) |
| 3205 |
|
| 3206 |
with self.subTest('MethodWrapperType'): |
| 3207 |
class CM(type): |
| 3208 |
__call__ = (2).__pow__ |
| 3209 |
class C(metaclass=CM): |
| 3210 |
def __init__(self, b): |
| 3211 |
pass |
| 3212 |
|
| 3213 |
self.assertEqual(C(3), 8) |
| 3214 |
self.assertEqual(C(3, 7), 1) |
| 3215 |
if '__pypy__' in sys.modules: |
| 3216 |
|
| 3217 |
self.assertEqual(self.signature(C), self.signature((0).__pow__)) |
| 3218 |
else: |
| 3219 |
|
| 3220 |
with self.assertRaises(AssertionError): |
| 3221 |
self.assertEqual(self.signature(C), self.signature((0).__pow__)) |
| 3222 |
|
| 3223 |
class CM(type): |
| 3224 |
def __new__(mcls, name, bases, dct, *, foo=1): |
| 3225 |
return super().__new__(mcls, name, bases, dct) |
| 3226 |
class C(metaclass=CM): |
| 3227 |
def __init__(self, b): |
| 3228 |
pass |
| 3229 |
|
| 3230 |
self.assertEqual(self.signature(C), |
| 3231 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3232 |
...)) |
| 3233 |
|
| 3234 |
self.assertEqual(self.signature(CM), |
| 3235 |
((('name', ..., ..., "positional_or_keyword"), |
| 3236 |
('bases', ..., ..., "positional_or_keyword"), |
| 3237 |
('dct', ..., ..., "positional_or_keyword"), |
| 3238 |
('foo', 1, ..., "keyword_only")), |
| 3239 |
...)) |
| 3240 |
|
| 3241 |
class CMM(type): |
| 3242 |
def __new__(mcls, name, bases, dct, *, foo=1): |
| 3243 |
return super().__new__(mcls, name, bases, dct) |
| 3244 |
def __call__(cls, nm, bs, dt): |
| 3245 |
return type(nm, bs, dt) |
| 3246 |
class CM(type, metaclass=CMM): |
| 3247 |
def __new__(mcls, name, bases, dct, *, bar=2): |
| 3248 |
return super().__new__(mcls, name, bases, dct) |
| 3249 |
class C(metaclass=CM): |
| 3250 |
def __init__(self, b): |
| 3251 |
pass |
| 3252 |
|
| 3253 |
self.assertEqual(self.signature(CMM), |
| 3254 |
((('name', ..., ..., "positional_or_keyword"), |
| 3255 |
('bases', ..., ..., "positional_or_keyword"), |
| 3256 |
('dct', ..., ..., "positional_or_keyword"), |
| 3257 |
('foo', 1, ..., "keyword_only")), |
| 3258 |
...)) |
| 3259 |
|
| 3260 |
self.assertEqual(self.signature(CM), |
| 3261 |
((('nm', ..., ..., "positional_or_keyword"), |
| 3262 |
('bs', ..., ..., "positional_or_keyword"), |
| 3263 |
('dt', ..., ..., "positional_or_keyword")), |
| 3264 |
...)) |
| 3265 |
|
| 3266 |
self.assertEqual(self.signature(C), |
| 3267 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3268 |
...)) |
| 3269 |
|
| 3270 |
class CM(type): |
| 3271 |
def __init__(cls, name, bases, dct, *, bar=2): |
| 3272 |
return super().__init__(name, bases, dct) |
| 3273 |
class C(metaclass=CM): |
| 3274 |
def __init__(self, b): |
| 3275 |
pass |
| 3276 |
|
| 3277 |
self.assertEqual(self.signature(CM), |
| 3278 |
((('name', ..., ..., "positional_or_keyword"), |
| 3279 |
('bases', ..., ..., "positional_or_keyword"), |
| 3280 |
('dct', ..., ..., "positional_or_keyword"), |
| 3281 |
('bar', 2, ..., "keyword_only")), |
| 3282 |
...)) |
| 3283 |
|
| 3284 |
def test_signature_on_class_with_init(self): |
| 3285 |
class C: |
| 3286 |
def __init__(self, b): |
| 3287 |
pass |
| 3288 |
|
| 3289 |
C(1) |
| 3290 |
self.assertEqual(self.signature(C), |
| 3291 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3292 |
...)) |
| 3293 |
|
| 3294 |
with self.subTest('classmethod'): |
| 3295 |
class C: |
| 3296 |
@classmethod |
| 3297 |
def __init__(cls, b): |
| 3298 |
pass |
| 3299 |
|
| 3300 |
C(1) |
| 3301 |
self.assertEqual(self.signature(C), |
| 3302 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3303 |
...)) |
| 3304 |
|
| 3305 |
with self.subTest('staticmethod'): |
| 3306 |
class C: |
| 3307 |
@staticmethod |
| 3308 |
def __init__(b): |
| 3309 |
pass |
| 3310 |
|
| 3311 |
C(1) |
| 3312 |
self.assertEqual(self.signature(C), |
| 3313 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3314 |
...)) |
| 3315 |
|
| 3316 |
with self.subTest('MethodType'): |
| 3317 |
class A: |
| 3318 |
def call(self, a): |
| 3319 |
pass |
| 3320 |
class C: |
| 3321 |
__init__ = A().call |
| 3322 |
|
| 3323 |
C(1) |
| 3324 |
self.assertEqual(self.signature(C), |
| 3325 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3326 |
...)) |
| 3327 |
|
| 3328 |
with self.subTest('partial'): |
| 3329 |
class C: |
| 3330 |
__init__ = functools.partial(lambda x, a: None, 2) |
| 3331 |
|
| 3332 |
C(1) |
| 3333 |
self.assertEqual(self.signature(C), |
| 3334 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3335 |
...)) |
| 3336 |
|
| 3337 |
with self.subTest('partialmethod'): |
| 3338 |
class C: |
| 3339 |
def _init(self, x, a): |
| 3340 |
self.a = (x, a) |
| 3341 |
__init__ = functools.partialmethod(_init, 2) |
| 3342 |
|
| 3343 |
self.assertEqual(C(1).a, (2, 1)) |
| 3344 |
self.assertEqual(self.signature(C), |
| 3345 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3346 |
...)) |
| 3347 |
|
| 3348 |
def test_signature_on_class_with_new(self): |
| 3349 |
with self.subTest('FunctionType'): |
| 3350 |
class C: |
| 3351 |
def __new__(cls, a): |
| 3352 |
return a |
| 3353 |
|
| 3354 |
self.assertEqual(C(1), 1) |
| 3355 |
self.assertEqual(self.signature(C), |
| 3356 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3357 |
...)) |
| 3358 |
|
| 3359 |
with self.subTest('classmethod'): |
| 3360 |
class C: |
| 3361 |
@classmethod |
| 3362 |
def __new__(cls, cls2, a): |
| 3363 |
return a |
| 3364 |
|
| 3365 |
self.assertEqual(C(1), 1) |
| 3366 |
self.assertEqual(self.signature(C), |
| 3367 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3368 |
...)) |
| 3369 |
|
| 3370 |
with self.subTest('staticmethod'): |
| 3371 |
class C: |
| 3372 |
@staticmethod |
| 3373 |
def __new__(cls, a): |
| 3374 |
return a |
| 3375 |
|
| 3376 |
self.assertEqual(C(1), 1) |
| 3377 |
self.assertEqual(self.signature(C), |
| 3378 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3379 |
...)) |
| 3380 |
|
| 3381 |
with self.subTest('MethodType'): |
| 3382 |
class A: |
| 3383 |
def call(self, cls, a): |
| 3384 |
return a |
| 3385 |
class C: |
| 3386 |
__new__ = A().call |
| 3387 |
|
| 3388 |
self.assertEqual(C(1), 1) |
| 3389 |
self.assertEqual(self.signature(C), |
| 3390 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3391 |
...)) |
| 3392 |
|
| 3393 |
with self.subTest('partial'): |
| 3394 |
class C: |
| 3395 |
__new__ = functools.partial(lambda x, cls, a: (x, a), 2) |
| 3396 |
|
| 3397 |
self.assertEqual(C(1), (2, 1)) |
| 3398 |
self.assertEqual(self.signature(C), |
| 3399 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3400 |
...)) |
| 3401 |
|
| 3402 |
with self.subTest('partialmethod'): |
| 3403 |
class C: |
| 3404 |
__new__ = functools.partialmethod(lambda cls, x, a: (x, a), 2) |
| 3405 |
|
| 3406 |
self.assertEqual(C(1), (2, 1)) |
| 3407 |
self.assertEqual(self.signature(C), |
| 3408 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3409 |
...)) |
| 3410 |
|
| 3411 |
with self.subTest('BuiltinMethodType'): |
| 3412 |
class C: |
| 3413 |
__new__ = str.__subclasscheck__ |
| 3414 |
|
| 3415 |
self.assertEqual(C(), False) |
| 3416 |
|
| 3417 |
|
| 3418 |
|
| 3419 |
|
| 3420 |
|
| 3421 |
with self.subTest('MethodWrapperType'): |
| 3422 |
class C: |
| 3423 |
__new__ = type.__or__.__get__(int, type) |
| 3424 |
|
| 3425 |
self.assertEqual(C(), C | int) |
| 3426 |
|
| 3427 |
|
| 3428 |
|
| 3429 |
|
| 3430 |
|
| 3431 |
|
| 3432 |
|
| 3433 |
with self.subTest('MethodDescriptorType'): |
| 3434 |
class C: |
| 3435 |
__new__ = type.__dict__['__subclasscheck__'] |
| 3436 |
|
| 3437 |
self.assertEqual(C(C), True) |
| 3438 |
self.assertEqual(self.signature(C), self.signature(C.__subclasscheck__)) |
| 3439 |
|
| 3440 |
with self.subTest('WrapperDescriptorType'): |
| 3441 |
class C: |
| 3442 |
__new__ = type.__or__ |
| 3443 |
|
| 3444 |
self.assertEqual(C(int), C | int) |
| 3445 |
|
| 3446 |
|
| 3447 |
|
| 3448 |
|
| 3449 |
|
| 3450 |
def test_signature_on_subclass(self): |
| 3451 |
class A: |
| 3452 |
def __new__(cls, a=1, *args, **kwargs): |
| 3453 |
return object.__new__(cls) |
| 3454 |
class B(A): |
| 3455 |
def __init__(self, b): |
| 3456 |
pass |
| 3457 |
class C(A): |
| 3458 |
def __new__(cls, a=1, b=2, *args, **kwargs): |
| 3459 |
return object.__new__(cls) |
| 3460 |
class D(A): |
| 3461 |
pass |
| 3462 |
|
| 3463 |
self.assertEqual(self.signature(B), |
| 3464 |
((('b', ..., ..., "positional_or_keyword"),), |
| 3465 |
...)) |
| 3466 |
self.assertEqual(self.signature(C), |
| 3467 |
((('a', 1, ..., 'positional_or_keyword'), |
| 3468 |
('b', 2, ..., 'positional_or_keyword'), |
| 3469 |
('args', ..., ..., 'var_positional'), |
| 3470 |
('kwargs', ..., ..., 'var_keyword')), |
| 3471 |
...)) |
| 3472 |
self.assertEqual(self.signature(D), |
| 3473 |
((('a', 1, ..., 'positional_or_keyword'), |
| 3474 |
('args', ..., ..., 'var_positional'), |
| 3475 |
('kwargs', ..., ..., 'var_keyword')), |
| 3476 |
...)) |
| 3477 |
|
| 3478 |
def test_signature_on_generic_subclass(self): |
| 3479 |
from typing import Generic, TypeVar |
| 3480 |
|
| 3481 |
T = TypeVar('T') |
| 3482 |
|
| 3483 |
class A(Generic[T]): |
| 3484 |
def __init__(self, *, a: int) -> None: |
| 3485 |
pass |
| 3486 |
|
| 3487 |
self.assertEqual(self.signature(A), |
| 3488 |
((('a', ..., int, 'keyword_only'),), |
| 3489 |
None)) |
| 3490 |
|
| 3491 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3492 |
"Signature information for builtins requires docstrings") |
| 3493 |
def test_signature_on_class_without_init(self): |
| 3494 |
|
| 3495 |
class C: pass |
| 3496 |
self.assertEqual(str(inspect.signature(C)), '()') |
| 3497 |
class D(C): pass |
| 3498 |
self.assertEqual(str(inspect.signature(D)), '()') |
| 3499 |
|
| 3500 |
|
| 3501 |
class C(type): pass |
| 3502 |
class D(C): pass |
| 3503 |
self.assertEqual(C('A', (), {}).__name__, 'A') |
| 3504 |
|
| 3505 |
with self.assertRaisesRegex(ValueError, "callable.*is not supported"): |
| 3506 |
self.assertEqual(inspect.signature(C), None) |
| 3507 |
self.assertEqual(D('A', (), {}).__name__, 'A') |
| 3508 |
with self.assertRaisesRegex(ValueError, "callable.*is not supported"): |
| 3509 |
self.assertEqual(inspect.signature(D), None) |
| 3510 |
|
| 3511 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3512 |
"Signature information for builtins requires docstrings") |
| 3513 |
def test_signature_on_builtin_class(self): |
| 3514 |
|
| 3515 |
expected = '(initial_bytes=None, /)' |
| 3516 |
self.assertEqual(str(inspect.signature(io.BytesIO)), expected) |
| 3517 |
|
| 3518 |
class P(io.BytesIO): pass |
| 3519 |
class EmptyTrait: pass |
| 3520 |
class P2(EmptyTrait, P): pass |
| 3521 |
self.assertEqual(str(inspect.signature(P)), expected) |
| 3522 |
self.assertEqual(str(inspect.signature(P2)), expected) |
| 3523 |
|
| 3524 |
class P3(P2): |
| 3525 |
def __init__(self, spam): |
| 3526 |
pass |
| 3527 |
self.assertEqual(str(inspect.signature(P3)), '(spam)') |
| 3528 |
|
| 3529 |
class MetaP(type): |
| 3530 |
def __call__(cls, foo, bar): |
| 3531 |
pass |
| 3532 |
class P4(P2, metaclass=MetaP): |
| 3533 |
pass |
| 3534 |
self.assertEqual(str(inspect.signature(P4)), '(foo, bar)') |
| 3535 |
|
| 3536 |
def test_signature_on_callable_objects(self): |
| 3537 |
class Foo: |
| 3538 |
def __call__(self, a): |
| 3539 |
pass |
| 3540 |
|
| 3541 |
self.assertEqual(self.signature(Foo()), |
| 3542 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3543 |
...)) |
| 3544 |
|
| 3545 |
class Spam: |
| 3546 |
pass |
| 3547 |
with self.assertRaisesRegex(TypeError, "is not a callable object"): |
| 3548 |
inspect.signature(Spam()) |
| 3549 |
|
| 3550 |
class Bar(Spam, Foo): |
| 3551 |
pass |
| 3552 |
|
| 3553 |
self.assertEqual(self.signature(Bar()), |
| 3554 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3555 |
...)) |
| 3556 |
|
| 3557 |
with self.subTest('classmethod'): |
| 3558 |
class C: |
| 3559 |
@classmethod |
| 3560 |
def __call__(cls, a): |
| 3561 |
pass |
| 3562 |
|
| 3563 |
self.assertEqual(self.signature(C()), |
| 3564 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3565 |
...)) |
| 3566 |
|
| 3567 |
with self.subTest('staticmethod'): |
| 3568 |
class C: |
| 3569 |
@staticmethod |
| 3570 |
def __call__(a): |
| 3571 |
pass |
| 3572 |
|
| 3573 |
self.assertEqual(self.signature(C()), |
| 3574 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3575 |
...)) |
| 3576 |
|
| 3577 |
with self.subTest('MethodType'): |
| 3578 |
class A: |
| 3579 |
def call(self, a): |
| 3580 |
return a |
| 3581 |
class C: |
| 3582 |
__call__ = A().call |
| 3583 |
|
| 3584 |
self.assertEqual(C()(1), 1) |
| 3585 |
self.assertEqual(self.signature(C()), |
| 3586 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3587 |
...)) |
| 3588 |
|
| 3589 |
with self.subTest('partial'): |
| 3590 |
class C: |
| 3591 |
__call__ = functools.partial(lambda x, a: (x, a), 2) |
| 3592 |
|
| 3593 |
self.assertEqual(C()(1), (2, 1)) |
| 3594 |
self.assertEqual(self.signature(C()), |
| 3595 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3596 |
...)) |
| 3597 |
|
| 3598 |
with self.subTest('partialmethod'): |
| 3599 |
class C: |
| 3600 |
__call__ = functools.partialmethod(lambda self, x, a: (x, a), 2) |
| 3601 |
|
| 3602 |
self.assertEqual(C()(1), (2, 1)) |
| 3603 |
self.assertEqual(self.signature(C()), |
| 3604 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3605 |
...)) |
| 3606 |
|
| 3607 |
with self.subTest('BuiltinMethodType'): |
| 3608 |
class C: |
| 3609 |
__call__ = ':'.join |
| 3610 |
|
| 3611 |
self.assertEqual(C()(['a', 'bc']), 'a:bc') |
| 3612 |
self.assertEqual(self.signature(C()), self.signature(''.join)) |
| 3613 |
|
| 3614 |
with self.subTest('MethodWrapperType'): |
| 3615 |
class C: |
| 3616 |
__call__ = (2).__pow__ |
| 3617 |
|
| 3618 |
self.assertEqual(C()(3), 8) |
| 3619 |
self.assertEqual(self.signature(C()), self.signature((0).__pow__)) |
| 3620 |
|
| 3621 |
with self.subTest('ClassMethodDescriptorType'): |
| 3622 |
class C(dict): |
| 3623 |
__call__ = dict.__dict__['fromkeys'] |
| 3624 |
|
| 3625 |
res = C()([1, 2], 3) |
| 3626 |
self.assertEqual(res, {1: 3, 2: 3}) |
| 3627 |
self.assertEqual(type(res), C) |
| 3628 |
self.assertEqual(self.signature(C()), self.signature(dict.fromkeys)) |
| 3629 |
|
| 3630 |
with self.subTest('MethodDescriptorType'): |
| 3631 |
class C(str): |
| 3632 |
__call__ = str.join |
| 3633 |
|
| 3634 |
self.assertEqual(C(':')(['a', 'bc']), 'a:bc') |
| 3635 |
self.assertEqual(self.signature(C()), self.signature(''.join)) |
| 3636 |
|
| 3637 |
with self.subTest('WrapperDescriptorType'): |
| 3638 |
class C(int): |
| 3639 |
__call__ = int.__pow__ |
| 3640 |
|
| 3641 |
self.assertEqual(C(2)(3), 8) |
| 3642 |
self.assertEqual(self.signature(C()), self.signature((0).__pow__)) |
| 3643 |
|
| 3644 |
with self.subTest('MemberDescriptorType'): |
| 3645 |
class C: |
| 3646 |
__slots__ = '__call__' |
| 3647 |
c = C() |
| 3648 |
c.__call__ = lambda a: a |
| 3649 |
self.assertEqual(c(1), 1) |
| 3650 |
self.assertEqual(self.signature(c), |
| 3651 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3652 |
...)) |
| 3653 |
|
| 3654 |
def test_signature_on_wrapper(self): |
| 3655 |
class Wrapper: |
| 3656 |
def __call__(self, b): |
| 3657 |
pass |
| 3658 |
wrapper = Wrapper() |
| 3659 |
wrapper.__wrapped__ = lambda a: None |
| 3660 |
self.assertEqual(self.signature(wrapper), |
| 3661 |
((('a', ..., ..., "positional_or_keyword"),), |
| 3662 |
...)) |
| 3663 |
|
| 3664 |
wrapper = Wrapper() |
| 3665 |
wrapper.__wrapped__ = wrapper |
| 3666 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 3667 |
self.signature(wrapper) |
| 3668 |
|
| 3669 |
def test_signature_on_lambdas(self): |
| 3670 |
self.assertEqual(self.signature((lambda a=10: a)), |
| 3671 |
((('a', 10, ..., "positional_or_keyword"),), |
| 3672 |
...)) |
| 3673 |
|
| 3674 |
def test_signature_on_mocks(self): |
| 3675 |
|
| 3676 |
for mock in ( |
| 3677 |
unittest.mock.Mock(), |
| 3678 |
unittest.mock.AsyncMock(), |
| 3679 |
unittest.mock.MagicMock(), |
| 3680 |
): |
| 3681 |
with self.subTest(mock=mock): |
| 3682 |
self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)') |
| 3683 |
|
| 3684 |
def test_signature_on_noncallable_mocks(self): |
| 3685 |
for mock in ( |
| 3686 |
unittest.mock.NonCallableMock(), |
| 3687 |
unittest.mock.NonCallableMagicMock(), |
| 3688 |
): |
| 3689 |
with self.subTest(mock=mock): |
| 3690 |
with self.assertRaises(TypeError): |
| 3691 |
inspect.signature(mock) |
| 3692 |
|
| 3693 |
def test_signature_equality(self): |
| 3694 |
def foo(a, *, b:int) -> float: pass |
| 3695 |
self.assertFalse(inspect.signature(foo) == 42) |
| 3696 |
self.assertTrue(inspect.signature(foo) != 42) |
| 3697 |
self.assertTrue(inspect.signature(foo) == ALWAYS_EQ) |
| 3698 |
self.assertFalse(inspect.signature(foo) != ALWAYS_EQ) |
| 3699 |
|
| 3700 |
def bar(a, *, b:int) -> float: pass |
| 3701 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 3702 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 3703 |
self.assertEqual( |
| 3704 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3705 |
|
| 3706 |
def bar(a, *, b:int) -> int: pass |
| 3707 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 3708 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 3709 |
self.assertNotEqual( |
| 3710 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3711 |
|
| 3712 |
def bar(a, *, b:int): pass |
| 3713 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 3714 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 3715 |
self.assertNotEqual( |
| 3716 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3717 |
|
| 3718 |
def bar(a, *, b:int=42) -> float: pass |
| 3719 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 3720 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 3721 |
self.assertNotEqual( |
| 3722 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3723 |
|
| 3724 |
def bar(a, *, c) -> float: pass |
| 3725 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 3726 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 3727 |
self.assertNotEqual( |
| 3728 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3729 |
|
| 3730 |
def bar(a, b:int) -> float: pass |
| 3731 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 3732 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 3733 |
self.assertNotEqual( |
| 3734 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3735 |
def spam(b:int, a) -> float: pass |
| 3736 |
self.assertFalse(inspect.signature(spam) == inspect.signature(bar)) |
| 3737 |
self.assertTrue(inspect.signature(spam) != inspect.signature(bar)) |
| 3738 |
self.assertNotEqual( |
| 3739 |
hash(inspect.signature(spam)), hash(inspect.signature(bar))) |
| 3740 |
|
| 3741 |
def foo(*, a, b, c): pass |
| 3742 |
def bar(*, c, b, a): pass |
| 3743 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 3744 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 3745 |
self.assertEqual( |
| 3746 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3747 |
|
| 3748 |
def foo(*, a=1, b, c): pass |
| 3749 |
def bar(*, c, b, a=1): pass |
| 3750 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 3751 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 3752 |
self.assertEqual( |
| 3753 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3754 |
|
| 3755 |
def foo(pos, *, a=1, b, c): pass |
| 3756 |
def bar(pos, *, c, b, a=1): pass |
| 3757 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 3758 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 3759 |
self.assertEqual( |
| 3760 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3761 |
|
| 3762 |
def foo(pos, *, a, b, c): pass |
| 3763 |
def bar(pos, *, c, b, a=1): pass |
| 3764 |
self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 3765 |
self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
| 3766 |
self.assertNotEqual( |
| 3767 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3768 |
|
| 3769 |
def foo(pos, *args, a=42, b, c, **kwargs:int): pass |
| 3770 |
def bar(pos, *args, c, b, a=42, **kwargs:int): pass |
| 3771 |
self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 3772 |
self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
| 3773 |
self.assertEqual( |
| 3774 |
hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
| 3775 |
|
| 3776 |
def test_signature_hashable(self): |
| 3777 |
S = inspect.Signature |
| 3778 |
P = inspect.Parameter |
| 3779 |
|
| 3780 |
def foo(a): pass |
| 3781 |
foo_sig = inspect.signature(foo) |
| 3782 |
|
| 3783 |
manual_sig = S(parameters=[P('a', P.POSITIONAL_OR_KEYWORD)]) |
| 3784 |
|
| 3785 |
self.assertEqual(hash(foo_sig), hash(manual_sig)) |
| 3786 |
self.assertNotEqual(hash(foo_sig), |
| 3787 |
hash(manual_sig.replace(return_annotation='spam'))) |
| 3788 |
|
| 3789 |
def bar(a) -> 1: pass |
| 3790 |
self.assertNotEqual(hash(foo_sig), hash(inspect.signature(bar))) |
| 3791 |
|
| 3792 |
def foo(a={}): pass |
| 3793 |
with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 3794 |
hash(inspect.signature(foo)) |
| 3795 |
|
| 3796 |
def foo(a) -> {}: pass |
| 3797 |
with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 3798 |
hash(inspect.signature(foo)) |
| 3799 |
|
| 3800 |
def test_signature_str(self): |
| 3801 |
def foo(a:int=1, *, b, c=None, **kwargs) -> 42: |
| 3802 |
pass |
| 3803 |
self.assertEqual(str(inspect.signature(foo)), |
| 3804 |
'(a: int = 1, *, b, c=None, **kwargs) -> 42') |
| 3805 |
|
| 3806 |
def foo(a:int=1, *args, b, c=None, **kwargs) -> 42: |
| 3807 |
pass |
| 3808 |
self.assertEqual(str(inspect.signature(foo)), |
| 3809 |
'(a: int = 1, *args, b, c=None, **kwargs) -> 42') |
| 3810 |
|
| 3811 |
def foo(): |
| 3812 |
pass |
| 3813 |
self.assertEqual(str(inspect.signature(foo)), '()') |
| 3814 |
|
| 3815 |
def foo(a: list[str]) -> tuple[str, float]: |
| 3816 |
pass |
| 3817 |
self.assertEqual(str(inspect.signature(foo)), |
| 3818 |
'(a: list[str]) -> tuple[str, float]') |
| 3819 |
|
| 3820 |
from typing import Tuple |
| 3821 |
def foo(a: list[str]) -> Tuple[str, float]: |
| 3822 |
pass |
| 3823 |
self.assertEqual(str(inspect.signature(foo)), |
| 3824 |
'(a: list[str]) -> Tuple[str, float]') |
| 3825 |
|
| 3826 |
def test_signature_str_positional_only(self): |
| 3827 |
P = inspect.Parameter |
| 3828 |
S = inspect.Signature |
| 3829 |
|
| 3830 |
def test(a_po, /, *, b, **kwargs): |
| 3831 |
return a_po, kwargs |
| 3832 |
|
| 3833 |
self.assertEqual(str(inspect.signature(test)), |
| 3834 |
'(a_po, /, *, b, **kwargs)') |
| 3835 |
|
| 3836 |
self.assertEqual(str(S(parameters=[P('foo', P.POSITIONAL_ONLY)])), |
| 3837 |
'(foo, /)') |
| 3838 |
|
| 3839 |
self.assertEqual(str(S(parameters=[ |
| 3840 |
P('foo', P.POSITIONAL_ONLY), |
| 3841 |
P('bar', P.VAR_KEYWORD)])), |
| 3842 |
'(foo, /, **bar)') |
| 3843 |
|
| 3844 |
self.assertEqual(str(S(parameters=[ |
| 3845 |
P('foo', P.POSITIONAL_ONLY), |
| 3846 |
P('bar', P.VAR_POSITIONAL)])), |
| 3847 |
'(foo, /, *bar)') |
| 3848 |
|
| 3849 |
def test_signature_replace_anno(self): |
| 3850 |
def test() -> 42: |
| 3851 |
pass |
| 3852 |
|
| 3853 |
sig = inspect.signature(test) |
| 3854 |
sig = sig.replace(return_annotation=None) |
| 3855 |
self.assertIs(sig.return_annotation, None) |
| 3856 |
sig = sig.replace(return_annotation=sig.empty) |
| 3857 |
self.assertIs(sig.return_annotation, sig.empty) |
| 3858 |
sig = sig.replace(return_annotation=42) |
| 3859 |
self.assertEqual(sig.return_annotation, 42) |
| 3860 |
self.assertEqual(sig, inspect.signature(test)) |
| 3861 |
|
| 3862 |
def test_signature_replaced(self): |
| 3863 |
def test(): |
| 3864 |
pass |
| 3865 |
|
| 3866 |
spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) |
| 3867 |
sig = test.__signature__ = inspect.Signature(parameters=(spam_param,)) |
| 3868 |
self.assertEqual(sig, inspect.signature(test)) |
| 3869 |
|
| 3870 |
def test_signature_on_mangled_parameters(self): |
| 3871 |
class Spam: |
| 3872 |
def foo(self, __p1:1=2, *, __p2:2=3): |
| 3873 |
pass |
| 3874 |
class Ham(Spam): |
| 3875 |
pass |
| 3876 |
|
| 3877 |
self.assertEqual(self.signature(Spam.foo), |
| 3878 |
((('self', ..., ..., "positional_or_keyword"), |
| 3879 |
('_Spam__p1', 2, 1, "positional_or_keyword"), |
| 3880 |
('_Spam__p2', 3, 2, "keyword_only")), |
| 3881 |
...)) |
| 3882 |
|
| 3883 |
self.assertEqual(self.signature(Spam.foo), |
| 3884 |
self.signature(Ham.foo)) |
| 3885 |
|
| 3886 |
def test_signature_from_callable_python_obj(self): |
| 3887 |
class MySignature(inspect.Signature): pass |
| 3888 |
def foo(a, *, b:1): pass |
| 3889 |
foo_sig = MySignature.from_callable(foo) |
| 3890 |
self.assertIsInstance(foo_sig, MySignature) |
| 3891 |
|
| 3892 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3893 |
"Signature information for builtins requires docstrings") |
| 3894 |
def test_signature_from_callable_class(self): |
| 3895 |
|
| 3896 |
class MySignature(inspect.Signature): pass |
| 3897 |
class foo: pass |
| 3898 |
foo_sig = MySignature.from_callable(foo) |
| 3899 |
self.assertIsInstance(foo_sig, MySignature) |
| 3900 |
|
| 3901 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3902 |
"Signature information for builtins requires docstrings") |
| 3903 |
def test_signature_from_callable_builtin_obj(self): |
| 3904 |
class MySignature(inspect.Signature): pass |
| 3905 |
sig = MySignature.from_callable(_pickle.Pickler) |
| 3906 |
self.assertIsInstance(sig, MySignature) |
| 3907 |
|
| 3908 |
def test_signature_definition_order_preserved_on_kwonly(self): |
| 3909 |
for fn in signatures_with_lexicographic_keyword_only_parameters(): |
| 3910 |
signature = inspect.signature(fn) |
| 3911 |
l = list(signature.parameters) |
| 3912 |
sorted_l = sorted(l) |
| 3913 |
self.assertTrue(l) |
| 3914 |
self.assertEqual(l, sorted_l) |
| 3915 |
signature = inspect.signature(unsorted_keyword_only_parameters_fn) |
| 3916 |
l = list(signature.parameters) |
| 3917 |
self.assertEqual(l, unsorted_keyword_only_parameters) |
| 3918 |
|
| 3919 |
def test_signater_parameters_is_ordered(self): |
| 3920 |
p1 = inspect.signature(lambda x, y: None).parameters |
| 3921 |
p2 = inspect.signature(lambda y, x: None).parameters |
| 3922 |
self.assertNotEqual(p1, p2) |
| 3923 |
|
| 3924 |
def test_signature_annotations_with_local_namespaces(self): |
| 3925 |
class Foo: ... |
| 3926 |
def func(foo: Foo) -> int: pass |
| 3927 |
def func2(foo: Foo, bar: 'Bar') -> int: pass |
| 3928 |
|
| 3929 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 3930 |
with self.subTest(signature_func = signature_func): |
| 3931 |
sig1 = signature_func(func) |
| 3932 |
self.assertEqual(sig1.return_annotation, int) |
| 3933 |
self.assertEqual(sig1.parameters['foo'].annotation, Foo) |
| 3934 |
|
| 3935 |
sig2 = signature_func(func, locals=locals()) |
| 3936 |
self.assertEqual(sig2.return_annotation, int) |
| 3937 |
self.assertEqual(sig2.parameters['foo'].annotation, Foo) |
| 3938 |
|
| 3939 |
sig3 = signature_func(func2, globals={'Bar': int}, locals=locals()) |
| 3940 |
self.assertEqual(sig3.return_annotation, int) |
| 3941 |
self.assertEqual(sig3.parameters['foo'].annotation, Foo) |
| 3942 |
self.assertEqual(sig3.parameters['bar'].annotation, 'Bar') |
| 3943 |
|
| 3944 |
def test_signature_eval_str(self): |
| 3945 |
isa = inspect_stringized_annotations |
| 3946 |
sig = inspect.Signature |
| 3947 |
par = inspect.Parameter |
| 3948 |
PORK = inspect.Parameter.POSITIONAL_OR_KEYWORD |
| 3949 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 3950 |
with self.subTest(signature_func = signature_func): |
| 3951 |
self.assertEqual( |
| 3952 |
signature_func(isa.MyClass), |
| 3953 |
sig( |
| 3954 |
parameters=( |
| 3955 |
par('a', PORK), |
| 3956 |
par('b', PORK), |
| 3957 |
))) |
| 3958 |
self.assertEqual( |
| 3959 |
signature_func(isa.function), |
| 3960 |
sig( |
| 3961 |
return_annotation='MyClass', |
| 3962 |
parameters=( |
| 3963 |
par('a', PORK, annotation='int'), |
| 3964 |
par('b', PORK, annotation='str'), |
| 3965 |
))) |
| 3966 |
self.assertEqual( |
| 3967 |
signature_func(isa.function2), |
| 3968 |
sig( |
| 3969 |
return_annotation='MyClass', |
| 3970 |
parameters=( |
| 3971 |
par('a', PORK, annotation='int'), |
| 3972 |
par('b', PORK, annotation="'str'"), |
| 3973 |
par('c', PORK, annotation="MyClass"), |
| 3974 |
))) |
| 3975 |
self.assertEqual( |
| 3976 |
signature_func(isa.function3), |
| 3977 |
sig( |
| 3978 |
parameters=( |
| 3979 |
par('a', PORK, annotation="'int'"), |
| 3980 |
par('b', PORK, annotation="'str'"), |
| 3981 |
par('c', PORK, annotation="'MyClass'"), |
| 3982 |
))) |
| 3983 |
|
| 3984 |
if not MISSING_C_DOCSTRINGS: |
| 3985 |
self.assertEqual(signature_func(isa.UnannotatedClass), sig()) |
| 3986 |
self.assertEqual(signature_func(isa.unannotated_function), |
| 3987 |
sig( |
| 3988 |
parameters=( |
| 3989 |
par('a', PORK), |
| 3990 |
par('b', PORK), |
| 3991 |
par('c', PORK), |
| 3992 |
))) |
| 3993 |
|
| 3994 |
self.assertEqual( |
| 3995 |
signature_func(isa.MyClass, eval_str=True), |
| 3996 |
sig( |
| 3997 |
parameters=( |
| 3998 |
par('a', PORK), |
| 3999 |
par('b', PORK), |
| 4000 |
))) |
| 4001 |
self.assertEqual( |
| 4002 |
signature_func(isa.function, eval_str=True), |
| 4003 |
sig( |
| 4004 |
return_annotation=isa.MyClass, |
| 4005 |
parameters=( |
| 4006 |
par('a', PORK, annotation=int), |
| 4007 |
par('b', PORK, annotation=str), |
| 4008 |
))) |
| 4009 |
self.assertEqual( |
| 4010 |
signature_func(isa.function2, eval_str=True), |
| 4011 |
sig( |
| 4012 |
return_annotation=isa.MyClass, |
| 4013 |
parameters=( |
| 4014 |
par('a', PORK, annotation=int), |
| 4015 |
par('b', PORK, annotation='str'), |
| 4016 |
par('c', PORK, annotation=isa.MyClass), |
| 4017 |
))) |
| 4018 |
self.assertEqual( |
| 4019 |
signature_func(isa.function3, eval_str=True), |
| 4020 |
sig( |
| 4021 |
parameters=( |
| 4022 |
par('a', PORK, annotation='int'), |
| 4023 |
par('b', PORK, annotation='str'), |
| 4024 |
par('c', PORK, annotation='MyClass'), |
| 4025 |
))) |
| 4026 |
|
| 4027 |
globalns = {'int': float, 'str': complex} |
| 4028 |
localns = {'str': tuple, 'MyClass': dict} |
| 4029 |
with self.assertRaises(NameError): |
| 4030 |
signature_func(isa.function, eval_str=True, globals=globalns) |
| 4031 |
|
| 4032 |
self.assertEqual( |
| 4033 |
signature_func(isa.function, eval_str=True, locals=localns), |
| 4034 |
sig( |
| 4035 |
return_annotation=dict, |
| 4036 |
parameters=( |
| 4037 |
par('a', PORK, annotation=int), |
| 4038 |
par('b', PORK, annotation=tuple), |
| 4039 |
))) |
| 4040 |
|
| 4041 |
self.assertEqual( |
| 4042 |
signature_func(isa.function, eval_str=True, globals=globalns, locals=localns), |
| 4043 |
sig( |
| 4044 |
return_annotation=dict, |
| 4045 |
parameters=( |
| 4046 |
par('a', PORK, annotation=float), |
| 4047 |
par('b', PORK, annotation=tuple), |
| 4048 |
))) |
| 4049 |
|
| 4050 |
def test_signature_none_annotation(self): |
| 4051 |
class funclike: |
| 4052 |
|
| 4053 |
|
| 4054 |
|
| 4055 |
|
| 4056 |
def __init__(self, func): |
| 4057 |
self.__name__ = func.__name__ |
| 4058 |
self.__code__ = func.__code__ |
| 4059 |
self.__annotations__ = func.__annotations__ |
| 4060 |
self.__defaults__ = func.__defaults__ |
| 4061 |
self.__kwdefaults__ = func.__kwdefaults__ |
| 4062 |
self.func = func |
| 4063 |
|
| 4064 |
def __call__(self, *args, **kwargs): |
| 4065 |
return self.func(*args, **kwargs) |
| 4066 |
|
| 4067 |
def foo(): pass |
| 4068 |
foo = funclike(foo) |
| 4069 |
foo.__annotations__ = None |
| 4070 |
for signature_func in (inspect.signature, inspect.Signature.from_callable): |
| 4071 |
with self.subTest(signature_func = signature_func): |
| 4072 |
self.assertEqual(signature_func(foo), inspect.Signature()) |
| 4073 |
self.assertEqual(inspect.get_annotations(foo), {}) |
| 4074 |
|
| 4075 |
def test_signature_on_derived_classes(self): |
| 4076 |
|
| 4077 |
|
| 4078 |
class B: |
| 4079 |
def __new__(self, *args, **kwargs): |
| 4080 |
return super().__new__(self) |
| 4081 |
def __init__(self, value): |
| 4082 |
self.value = value |
| 4083 |
|
| 4084 |
class D1(B): |
| 4085 |
def __init__(self, value): |
| 4086 |
super().__init__(value) |
| 4087 |
|
| 4088 |
class D2(D1): |
| 4089 |
pass |
| 4090 |
|
| 4091 |
self.assertEqual(inspect.signature(D2), inspect.signature(D1)) |
| 4092 |
|
| 4093 |
|
| 4094 |
class TestParameterObject(unittest.TestCase): |
| 4095 |
def test_signature_parameter_kinds(self): |
| 4096 |
P = inspect.Parameter |
| 4097 |
self.assertTrue(P.POSITIONAL_ONLY < P.POSITIONAL_OR_KEYWORD < \ |
| 4098 |
P.VAR_POSITIONAL < P.KEYWORD_ONLY < P.VAR_KEYWORD) |
| 4099 |
|
| 4100 |
self.assertEqual(str(P.POSITIONAL_ONLY), 'POSITIONAL_ONLY') |
| 4101 |
self.assertTrue('POSITIONAL_ONLY' in repr(P.POSITIONAL_ONLY)) |
| 4102 |
|
| 4103 |
def test_signature_parameter_object(self): |
| 4104 |
p = inspect.Parameter('foo', default=10, |
| 4105 |
kind=inspect.Parameter.POSITIONAL_ONLY) |
| 4106 |
self.assertEqual(p.name, 'foo') |
| 4107 |
self.assertEqual(p.default, 10) |
| 4108 |
self.assertIs(p.annotation, p.empty) |
| 4109 |
self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) |
| 4110 |
|
| 4111 |
with self.assertRaisesRegex(ValueError, "value '123' is " |
| 4112 |
"not a valid Parameter.kind"): |
| 4113 |
inspect.Parameter('foo', default=10, kind='123') |
| 4114 |
|
| 4115 |
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): |
| 4116 |
inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD) |
| 4117 |
|
| 4118 |
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): |
| 4119 |
inspect.Parameter('from', kind=inspect.Parameter.VAR_KEYWORD) |
| 4120 |
|
| 4121 |
with self.assertRaisesRegex(TypeError, 'name must be a str'): |
| 4122 |
inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD) |
| 4123 |
|
| 4124 |
with self.assertRaisesRegex(ValueError, |
| 4125 |
'is not a valid parameter name'): |
| 4126 |
inspect.Parameter('$', kind=inspect.Parameter.VAR_KEYWORD) |
| 4127 |
|
| 4128 |
with self.assertRaisesRegex(ValueError, |
| 4129 |
'is not a valid parameter name'): |
| 4130 |
inspect.Parameter('.a', kind=inspect.Parameter.VAR_KEYWORD) |
| 4131 |
|
| 4132 |
with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
| 4133 |
inspect.Parameter('a', default=42, |
| 4134 |
kind=inspect.Parameter.VAR_KEYWORD) |
| 4135 |
|
| 4136 |
with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
| 4137 |
inspect.Parameter('a', default=42, |
| 4138 |
kind=inspect.Parameter.VAR_POSITIONAL) |
| 4139 |
|
| 4140 |
p = inspect.Parameter('a', default=42, |
| 4141 |
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) |
| 4142 |
with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
| 4143 |
p.replace(kind=inspect.Parameter.VAR_POSITIONAL) |
| 4144 |
|
| 4145 |
self.assertTrue(repr(p).startswith('<Parameter')) |
| 4146 |
self.assertTrue('"a=42"' in repr(p)) |
| 4147 |
|
| 4148 |
def test_signature_parameter_hashable(self): |
| 4149 |
P = inspect.Parameter |
| 4150 |
foo = P('foo', kind=P.POSITIONAL_ONLY) |
| 4151 |
self.assertEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY))) |
| 4152 |
self.assertNotEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY, |
| 4153 |
default=42))) |
| 4154 |
self.assertNotEqual(hash(foo), |
| 4155 |
hash(foo.replace(kind=P.VAR_POSITIONAL))) |
| 4156 |
|
| 4157 |
def test_signature_parameter_equality(self): |
| 4158 |
P = inspect.Parameter |
| 4159 |
p = P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) |
| 4160 |
|
| 4161 |
self.assertTrue(p == p) |
| 4162 |
self.assertFalse(p != p) |
| 4163 |
self.assertFalse(p == 42) |
| 4164 |
self.assertTrue(p != 42) |
| 4165 |
self.assertTrue(p == ALWAYS_EQ) |
| 4166 |
self.assertFalse(p != ALWAYS_EQ) |
| 4167 |
|
| 4168 |
self.assertTrue(p == P('foo', default=42, |
| 4169 |
kind=inspect.Parameter.KEYWORD_ONLY)) |
| 4170 |
self.assertFalse(p != P('foo', default=42, |
| 4171 |
kind=inspect.Parameter.KEYWORD_ONLY)) |
| 4172 |
|
| 4173 |
def test_signature_parameter_replace(self): |
| 4174 |
p = inspect.Parameter('foo', default=42, |
| 4175 |
kind=inspect.Parameter.KEYWORD_ONLY) |
| 4176 |
|
| 4177 |
self.assertIsNot(p, p.replace()) |
| 4178 |
self.assertEqual(p, p.replace()) |
| 4179 |
|
| 4180 |
p2 = p.replace(annotation=1) |
| 4181 |
self.assertEqual(p2.annotation, 1) |
| 4182 |
p2 = p2.replace(annotation=p2.empty) |
| 4183 |
self.assertEqual(p, p2) |
| 4184 |
|
| 4185 |
p2 = p2.replace(name='bar') |
| 4186 |
self.assertEqual(p2.name, 'bar') |
| 4187 |
self.assertNotEqual(p2, p) |
| 4188 |
|
| 4189 |
with self.assertRaisesRegex(ValueError, |
| 4190 |
'name is a required attribute'): |
| 4191 |
p2 = p2.replace(name=p2.empty) |
| 4192 |
|
| 4193 |
p2 = p2.replace(name='foo', default=None) |
| 4194 |
self.assertIs(p2.default, None) |
| 4195 |
self.assertNotEqual(p2, p) |
| 4196 |
|
| 4197 |
p2 = p2.replace(name='foo', default=p2.empty) |
| 4198 |
self.assertIs(p2.default, p2.empty) |
| 4199 |
|
| 4200 |
|
| 4201 |
p2 = p2.replace(default=42, kind=p2.POSITIONAL_OR_KEYWORD) |
| 4202 |
self.assertEqual(p2.kind, p2.POSITIONAL_OR_KEYWORD) |
| 4203 |
self.assertNotEqual(p2, p) |
| 4204 |
|
| 4205 |
with self.assertRaisesRegex(ValueError, |
| 4206 |
"value <class 'inspect._empty'> " |
| 4207 |
"is not a valid Parameter.kind"): |
| 4208 |
p2 = p2.replace(kind=p2.empty) |
| 4209 |
|
| 4210 |
p2 = p2.replace(kind=p2.KEYWORD_ONLY) |
| 4211 |
self.assertEqual(p2, p) |
| 4212 |
|
| 4213 |
def test_signature_parameter_positional_only(self): |
| 4214 |
with self.assertRaisesRegex(TypeError, 'name must be a str'): |
| 4215 |
inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY) |
| 4216 |
|
| 4217 |
@cpython_only |
| 4218 |
def test_signature_parameter_implicit(self): |
| 4219 |
with self.assertRaisesRegex(ValueError, |
| 4220 |
'implicit arguments must be passed as ' |
| 4221 |
'positional or keyword arguments, ' |
| 4222 |
'not positional-only'): |
| 4223 |
inspect.Parameter('.0', kind=inspect.Parameter.POSITIONAL_ONLY) |
| 4224 |
|
| 4225 |
param = inspect.Parameter( |
| 4226 |
'.0', kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) |
| 4227 |
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_ONLY) |
| 4228 |
self.assertEqual(param.name, 'implicit0') |
| 4229 |
|
| 4230 |
def test_signature_parameter_immutability(self): |
| 4231 |
p = inspect.Parameter('spam', kind=inspect.Parameter.KEYWORD_ONLY) |
| 4232 |
|
| 4233 |
with self.assertRaises(AttributeError): |
| 4234 |
p.foo = 'bar' |
| 4235 |
|
| 4236 |
with self.assertRaises(AttributeError): |
| 4237 |
p.kind = 123 |
| 4238 |
|
| 4239 |
|
| 4240 |
class TestSignatureBind(unittest.TestCase): |
| 4241 |
@staticmethod |
| 4242 |
def call(func, *args, **kwargs): |
| 4243 |
sig = inspect.signature(func) |
| 4244 |
ba = sig.bind(*args, **kwargs) |
| 4245 |
return func(*ba.args, **ba.kwargs) |
| 4246 |
|
| 4247 |
def test_signature_bind_empty(self): |
| 4248 |
def test(): |
| 4249 |
return 42 |
| 4250 |
|
| 4251 |
self.assertEqual(self.call(test), 42) |
| 4252 |
with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
| 4253 |
self.call(test, 1) |
| 4254 |
with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
| 4255 |
self.call(test, 1, spam=10) |
| 4256 |
with self.assertRaisesRegex( |
| 4257 |
TypeError, "got an unexpected keyword argument 'spam'"): |
| 4258 |
|
| 4259 |
self.call(test, spam=1) |
| 4260 |
|
| 4261 |
def test_signature_bind_var(self): |
| 4262 |
def test(*args, **kwargs): |
| 4263 |
return args, kwargs |
| 4264 |
|
| 4265 |
self.assertEqual(self.call(test), ((), {})) |
| 4266 |
self.assertEqual(self.call(test, 1), ((1,), {})) |
| 4267 |
self.assertEqual(self.call(test, 1, 2), ((1, 2), {})) |
| 4268 |
self.assertEqual(self.call(test, foo='bar'), ((), {'foo': 'bar'})) |
| 4269 |
self.assertEqual(self.call(test, 1, foo='bar'), ((1,), {'foo': 'bar'})) |
| 4270 |
self.assertEqual(self.call(test, args=10), ((), {'args': 10})) |
| 4271 |
self.assertEqual(self.call(test, 1, 2, foo='bar'), |
| 4272 |
((1, 2), {'foo': 'bar'})) |
| 4273 |
|
| 4274 |
def test_signature_bind_just_args(self): |
| 4275 |
def test(a, b, c): |
| 4276 |
return a, b, c |
| 4277 |
|
| 4278 |
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 4279 |
|
| 4280 |
with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
| 4281 |
self.call(test, 1, 2, 3, 4) |
| 4282 |
|
| 4283 |
with self.assertRaisesRegex(TypeError, |
| 4284 |
"missing a required argument: 'b'"): |
| 4285 |
self.call(test, 1) |
| 4286 |
|
| 4287 |
with self.assertRaisesRegex(TypeError, |
| 4288 |
"missing a required argument: 'a'"): |
| 4289 |
self.call(test) |
| 4290 |
|
| 4291 |
def test(a, b, c=10): |
| 4292 |
return a, b, c |
| 4293 |
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 4294 |
self.assertEqual(self.call(test, 1, 2), (1, 2, 10)) |
| 4295 |
|
| 4296 |
def test(a=1, b=2, c=3): |
| 4297 |
return a, b, c |
| 4298 |
self.assertEqual(self.call(test, a=10, c=13), (10, 2, 13)) |
| 4299 |
self.assertEqual(self.call(test, a=10), (10, 2, 3)) |
| 4300 |
self.assertEqual(self.call(test, b=10), (1, 10, 3)) |
| 4301 |
|
| 4302 |
def test_signature_bind_varargs_order(self): |
| 4303 |
def test(*args): |
| 4304 |
return args |
| 4305 |
|
| 4306 |
self.assertEqual(self.call(test), ()) |
| 4307 |
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 4308 |
|
| 4309 |
def test_signature_bind_args_and_varargs(self): |
| 4310 |
def test(a, b, c=3, *args): |
| 4311 |
return a, b, c, args |
| 4312 |
|
| 4313 |
self.assertEqual(self.call(test, 1, 2, 3, 4, 5), (1, 2, 3, (4, 5))) |
| 4314 |
self.assertEqual(self.call(test, 1, 2), (1, 2, 3, ())) |
| 4315 |
self.assertEqual(self.call(test, b=1, a=2), (2, 1, 3, ())) |
| 4316 |
self.assertEqual(self.call(test, 1, b=2), (1, 2, 3, ())) |
| 4317 |
|
| 4318 |
with self.assertRaisesRegex(TypeError, |
| 4319 |
"multiple values for argument 'c'"): |
| 4320 |
self.call(test, 1, 2, 3, c=4) |
| 4321 |
|
| 4322 |
def test_signature_bind_just_kwargs(self): |
| 4323 |
def test(**kwargs): |
| 4324 |
return kwargs |
| 4325 |
|
| 4326 |
self.assertEqual(self.call(test), {}) |
| 4327 |
self.assertEqual(self.call(test, foo='bar', spam='ham'), |
| 4328 |
{'foo': 'bar', 'spam': 'ham'}) |
| 4329 |
|
| 4330 |
def test_signature_bind_args_and_kwargs(self): |
| 4331 |
def test(a, b, c=3, **kwargs): |
| 4332 |
return a, b, c, kwargs |
| 4333 |
|
| 4334 |
self.assertEqual(self.call(test, 1, 2), (1, 2, 3, {})) |
| 4335 |
self.assertEqual(self.call(test, 1, 2, foo='bar', spam='ham'), |
| 4336 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 4337 |
self.assertEqual(self.call(test, b=2, a=1, foo='bar', spam='ham'), |
| 4338 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 4339 |
self.assertEqual(self.call(test, a=1, b=2, foo='bar', spam='ham'), |
| 4340 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 4341 |
self.assertEqual(self.call(test, 1, b=2, foo='bar', spam='ham'), |
| 4342 |
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 4343 |
self.assertEqual(self.call(test, 1, b=2, c=4, foo='bar', spam='ham'), |
| 4344 |
(1, 2, 4, {'foo': 'bar', 'spam': 'ham'})) |
| 4345 |
self.assertEqual(self.call(test, 1, 2, 4, foo='bar'), |
| 4346 |
(1, 2, 4, {'foo': 'bar'})) |
| 4347 |
self.assertEqual(self.call(test, c=5, a=4, b=3), |
| 4348 |
(4, 3, 5, {})) |
| 4349 |
|
| 4350 |
def test_signature_bind_kwonly(self): |
| 4351 |
def test(*, foo): |
| 4352 |
return foo |
| 4353 |
with self.assertRaisesRegex(TypeError, |
| 4354 |
'too many positional arguments'): |
| 4355 |
self.call(test, 1) |
| 4356 |
self.assertEqual(self.call(test, foo=1), 1) |
| 4357 |
|
| 4358 |
def test(a, *, foo=1, bar): |
| 4359 |
return foo |
| 4360 |
with self.assertRaisesRegex(TypeError, |
| 4361 |
"missing a required argument: 'bar'"): |
| 4362 |
self.call(test, 1) |
| 4363 |
|
| 4364 |
def test(foo, *, bar): |
| 4365 |
return foo, bar |
| 4366 |
self.assertEqual(self.call(test, 1, bar=2), (1, 2)) |
| 4367 |
self.assertEqual(self.call(test, bar=2, foo=1), (1, 2)) |
| 4368 |
|
| 4369 |
with self.assertRaisesRegex( |
| 4370 |
TypeError, "got an unexpected keyword argument 'spam'"): |
| 4371 |
|
| 4372 |
self.call(test, bar=2, foo=1, spam=10) |
| 4373 |
|
| 4374 |
with self.assertRaisesRegex(TypeError, |
| 4375 |
'too many positional arguments'): |
| 4376 |
self.call(test, 1, 2) |
| 4377 |
|
| 4378 |
with self.assertRaisesRegex(TypeError, |
| 4379 |
'too many positional arguments'): |
| 4380 |
self.call(test, 1, 2, bar=2) |
| 4381 |
|
| 4382 |
with self.assertRaisesRegex( |
| 4383 |
TypeError, "got an unexpected keyword argument 'spam'"): |
| 4384 |
|
| 4385 |
self.call(test, 1, bar=2, spam='ham') |
| 4386 |
|
| 4387 |
with self.assertRaisesRegex(TypeError, |
| 4388 |
"missing a required argument: 'bar'"): |
| 4389 |
self.call(test, 1) |
| 4390 |
|
| 4391 |
def test(foo, *, bar, **bin): |
| 4392 |
return foo, bar, bin |
| 4393 |
self.assertEqual(self.call(test, 1, bar=2), (1, 2, {})) |
| 4394 |
self.assertEqual(self.call(test, foo=1, bar=2), (1, 2, {})) |
| 4395 |
self.assertEqual(self.call(test, 1, bar=2, spam='ham'), |
| 4396 |
(1, 2, {'spam': 'ham'})) |
| 4397 |
self.assertEqual(self.call(test, spam='ham', foo=1, bar=2), |
| 4398 |
(1, 2, {'spam': 'ham'})) |
| 4399 |
with self.assertRaisesRegex(TypeError, |
| 4400 |
"missing a required argument: 'foo'"): |
| 4401 |
self.call(test, spam='ham', bar=2) |
| 4402 |
self.assertEqual(self.call(test, 1, bar=2, bin=1, spam=10), |
| 4403 |
(1, 2, {'bin': 1, 'spam': 10})) |
| 4404 |
|
| 4405 |
def test_signature_bind_arguments(self): |
| 4406 |
def test(a, *args, b, z=100, **kwargs): |
| 4407 |
pass |
| 4408 |
sig = inspect.signature(test) |
| 4409 |
ba = sig.bind(10, 20, b=30, c=40, args=50, kwargs=60) |
| 4410 |
|
| 4411 |
|
| 4412 |
self.assertEqual(tuple(ba.arguments.items()), |
| 4413 |
(('a', 10), ('args', (20,)), ('b', 30), |
| 4414 |
('kwargs', {'c': 40, 'args': 50, 'kwargs': 60}))) |
| 4415 |
self.assertEqual(ba.kwargs, |
| 4416 |
{'b': 30, 'c': 40, 'args': 50, 'kwargs': 60}) |
| 4417 |
self.assertEqual(ba.args, (10, 20)) |
| 4418 |
|
| 4419 |
def test_signature_bind_positional_only(self): |
| 4420 |
def test(a_po, b_po, c_po=3, /, foo=42, *, bar=50, **kwargs): |
| 4421 |
return a_po, b_po, c_po, foo, bar, kwargs |
| 4422 |
|
| 4423 |
self.assertEqual(self.call(test, 1, 2, 4, 5, bar=6), |
| 4424 |
(1, 2, 4, 5, 6, {})) |
| 4425 |
|
| 4426 |
self.assertEqual(self.call(test, 1, 2), |
| 4427 |
(1, 2, 3, 42, 50, {})) |
| 4428 |
|
| 4429 |
self.assertEqual(self.call(test, 1, 2, foo=4, bar=5), |
| 4430 |
(1, 2, 3, 4, 5, {})) |
| 4431 |
|
| 4432 |
with self.assertRaisesRegex(TypeError, "but was passed as a keyword"): |
| 4433 |
self.call(test, 1, 2, foo=4, bar=5, c_po=10) |
| 4434 |
|
| 4435 |
with self.assertRaisesRegex(TypeError, "parameter is positional only"): |
| 4436 |
self.call(test, 1, 2, c_po=4) |
| 4437 |
|
| 4438 |
with self.assertRaisesRegex(TypeError, "parameter is positional only"): |
| 4439 |
self.call(test, a_po=1, b_po=2) |
| 4440 |
|
| 4441 |
def test_signature_bind_with_self_arg(self): |
| 4442 |
|
| 4443 |
def test(a, self, b): |
| 4444 |
pass |
| 4445 |
sig = inspect.signature(test) |
| 4446 |
ba = sig.bind(1, 2, 3) |
| 4447 |
self.assertEqual(ba.args, (1, 2, 3)) |
| 4448 |
ba = sig.bind(1, self=2, b=3) |
| 4449 |
self.assertEqual(ba.args, (1, 2, 3)) |
| 4450 |
|
| 4451 |
def test_signature_bind_vararg_name(self): |
| 4452 |
def test(a, *args): |
| 4453 |
return a, args |
| 4454 |
sig = inspect.signature(test) |
| 4455 |
|
| 4456 |
with self.assertRaisesRegex( |
| 4457 |
TypeError, "got an unexpected keyword argument 'args'"): |
| 4458 |
|
| 4459 |
sig.bind(a=0, args=1) |
| 4460 |
|
| 4461 |
def test(*args, **kwargs): |
| 4462 |
return args, kwargs |
| 4463 |
self.assertEqual(self.call(test, args=1), ((), {'args': 1})) |
| 4464 |
|
| 4465 |
sig = inspect.signature(test) |
| 4466 |
ba = sig.bind(args=1) |
| 4467 |
self.assertEqual(ba.arguments, {'kwargs': {'args': 1}}) |
| 4468 |
|
| 4469 |
@cpython_only |
| 4470 |
def test_signature_bind_implicit_arg(self): |
| 4471 |
|
| 4472 |
def make_set(): |
| 4473 |
return {z * z for z in range(5)} |
| 4474 |
setcomp_code = make_set.__code__.co_consts[1] |
| 4475 |
setcomp_func = types.FunctionType(setcomp_code, {}) |
| 4476 |
|
| 4477 |
iterator = iter(range(5)) |
| 4478 |
self.assertEqual(self.call(setcomp_func, iterator), {0, 1, 4, 9, 16}) |
| 4479 |
|
| 4480 |
def test_signature_bind_posonly_kwargs(self): |
| 4481 |
def foo(bar, /, **kwargs): |
| 4482 |
return bar, kwargs.get(bar) |
| 4483 |
|
| 4484 |
sig = inspect.signature(foo) |
| 4485 |
result = sig.bind("pos-only", bar="keyword") |
| 4486 |
|
| 4487 |
self.assertEqual(result.kwargs, {"bar": "keyword"}) |
| 4488 |
self.assertIn(("bar", "pos-only"), result.arguments.items()) |
| 4489 |
|
| 4490 |
|
| 4491 |
class TestBoundArguments(unittest.TestCase): |
| 4492 |
def test_signature_bound_arguments_unhashable(self): |
| 4493 |
def foo(a): pass |
| 4494 |
ba = inspect.signature(foo).bind(1) |
| 4495 |
|
| 4496 |
with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 4497 |
hash(ba) |
| 4498 |
|
| 4499 |
def test_signature_bound_arguments_equality(self): |
| 4500 |
def foo(a): pass |
| 4501 |
ba = inspect.signature(foo).bind(1) |
| 4502 |
self.assertTrue(ba == ba) |
| 4503 |
self.assertFalse(ba != ba) |
| 4504 |
self.assertTrue(ba == ALWAYS_EQ) |
| 4505 |
self.assertFalse(ba != ALWAYS_EQ) |
| 4506 |
|
| 4507 |
ba2 = inspect.signature(foo).bind(1) |
| 4508 |
self.assertTrue(ba == ba2) |
| 4509 |
self.assertFalse(ba != ba2) |
| 4510 |
|
| 4511 |
ba3 = inspect.signature(foo).bind(2) |
| 4512 |
self.assertFalse(ba == ba3) |
| 4513 |
self.assertTrue(ba != ba3) |
| 4514 |
ba3.arguments['a'] = 1 |
| 4515 |
self.assertTrue(ba == ba3) |
| 4516 |
self.assertFalse(ba != ba3) |
| 4517 |
|
| 4518 |
def bar(b): pass |
| 4519 |
ba4 = inspect.signature(bar).bind(1) |
| 4520 |
self.assertFalse(ba == ba4) |
| 4521 |
self.assertTrue(ba != ba4) |
| 4522 |
|
| 4523 |
def foo(*, a, b): pass |
| 4524 |
sig = inspect.signature(foo) |
| 4525 |
ba1 = sig.bind(a=1, b=2) |
| 4526 |
ba2 = sig.bind(b=2, a=1) |
| 4527 |
self.assertTrue(ba1 == ba2) |
| 4528 |
self.assertFalse(ba1 != ba2) |
| 4529 |
|
| 4530 |
def test_signature_bound_arguments_pickle(self): |
| 4531 |
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 4532 |
sig = inspect.signature(foo) |
| 4533 |
ba = sig.bind(20, 30, z={}) |
| 4534 |
|
| 4535 |
for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 4536 |
with self.subTest(pickle_ver=ver): |
| 4537 |
ba_pickled = pickle.loads(pickle.dumps(ba, ver)) |
| 4538 |
self.assertEqual(ba, ba_pickled) |
| 4539 |
|
| 4540 |
def test_signature_bound_arguments_repr(self): |
| 4541 |
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 4542 |
sig = inspect.signature(foo) |
| 4543 |
ba = sig.bind(20, 30, z={}) |
| 4544 |
self.assertRegex(repr(ba), r'<BoundArguments \(a=20,.*\}\}\)>') |
| 4545 |
|
| 4546 |
def test_signature_bound_arguments_apply_defaults(self): |
| 4547 |
def foo(a, b=1, *args, c:1={}, **kw): pass |
| 4548 |
sig = inspect.signature(foo) |
| 4549 |
|
| 4550 |
ba = sig.bind(20) |
| 4551 |
ba.apply_defaults() |
| 4552 |
self.assertEqual( |
| 4553 |
list(ba.arguments.items()), |
| 4554 |
[('a', 20), ('b', 1), ('args', ()), ('c', {}), ('kw', {})]) |
| 4555 |
|
| 4556 |
|
| 4557 |
|
| 4558 |
ba = sig.bind(10, 20, 30, d=1) |
| 4559 |
ba.apply_defaults() |
| 4560 |
self.assertEqual( |
| 4561 |
list(ba.arguments.items()), |
| 4562 |
[('a', 10), ('b', 20), ('args', (30,)), ('c', {}), ('kw', {'d':1})]) |
| 4563 |
|
| 4564 |
|
| 4565 |
|
| 4566 |
def foo(a, b): pass |
| 4567 |
sig = inspect.signature(foo) |
| 4568 |
ba = sig.bind_partial(20) |
| 4569 |
ba.apply_defaults() |
| 4570 |
self.assertEqual( |
| 4571 |
list(ba.arguments.items()), |
| 4572 |
[('a', 20)]) |
| 4573 |
|
| 4574 |
|
| 4575 |
def foo(): pass |
| 4576 |
sig = inspect.signature(foo) |
| 4577 |
ba = sig.bind() |
| 4578 |
ba.apply_defaults() |
| 4579 |
self.assertEqual(list(ba.arguments.items()), []) |
| 4580 |
|
| 4581 |
|
| 4582 |
def foo(a='spam'): pass |
| 4583 |
sig = inspect.signature(foo) |
| 4584 |
ba = sig.bind() |
| 4585 |
ba.apply_defaults() |
| 4586 |
self.assertEqual(list(ba.arguments.items()), [('a', 'spam')]) |
| 4587 |
|
| 4588 |
def test_signature_bound_arguments_arguments_type(self): |
| 4589 |
def foo(a): pass |
| 4590 |
ba = inspect.signature(foo).bind(1) |
| 4591 |
self.assertIs(type(ba.arguments), dict) |
| 4592 |
|
| 4593 |
class TestSignaturePrivateHelpers(unittest.TestCase): |
| 4594 |
def _strip_non_python_syntax(self, input, |
| 4595 |
clean_signature, self_parameter, last_positional_only): |
| 4596 |
computed_clean_signature, \ |
| 4597 |
computed_self_parameter, \ |
| 4598 |
computed_last_positional_only = \ |
| 4599 |
inspect._signature_strip_non_python_syntax(input) |
| 4600 |
self.assertEqual(computed_clean_signature, clean_signature) |
| 4601 |
self.assertEqual(computed_self_parameter, self_parameter) |
| 4602 |
self.assertEqual(computed_last_positional_only, last_positional_only) |
| 4603 |
|
| 4604 |
def test_signature_strip_non_python_syntax(self): |
| 4605 |
self._strip_non_python_syntax( |
| 4606 |
"($module, /, path, mode, *, dir_fd=None, " + |
| 4607 |
"effective_ids=False,\n follow_symlinks=True)", |
| 4608 |
"(module, path, mode, *, dir_fd=None, " + |
| 4609 |
"effective_ids=False, follow_symlinks=True)", |
| 4610 |
0, |
| 4611 |
0) |
| 4612 |
|
| 4613 |
self._strip_non_python_syntax( |
| 4614 |
"($module, word, salt, /)", |
| 4615 |
"(module, word, salt)", |
| 4616 |
0, |
| 4617 |
2) |
| 4618 |
|
| 4619 |
self._strip_non_python_syntax( |
| 4620 |
"(x, y=None, z=None, /)", |
| 4621 |
"(x, y=None, z=None)", |
| 4622 |
None, |
| 4623 |
2) |
| 4624 |
|
| 4625 |
self._strip_non_python_syntax( |
| 4626 |
"(x, y=None, z=None)", |
| 4627 |
"(x, y=None, z=None)", |
| 4628 |
None, |
| 4629 |
None) |
| 4630 |
|
| 4631 |
self._strip_non_python_syntax( |
| 4632 |
"(x,\n y=None,\n z = None )", |
| 4633 |
"(x, y=None, z=None)", |
| 4634 |
None, |
| 4635 |
None) |
| 4636 |
|
| 4637 |
self._strip_non_python_syntax( |
| 4638 |
"", |
| 4639 |
"", |
| 4640 |
None, |
| 4641 |
None) |
| 4642 |
|
| 4643 |
self._strip_non_python_syntax( |
| 4644 |
None, |
| 4645 |
None, |
| 4646 |
None, |
| 4647 |
None) |
| 4648 |
|
| 4649 |
class TestSignatureDefinitions(unittest.TestCase): |
| 4650 |
|
| 4651 |
|
| 4652 |
|
| 4653 |
@cpython_only |
| 4654 |
@unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 4655 |
"Signature information for builtins requires docstrings") |
| 4656 |
def test_builtins_have_signatures(self): |
| 4657 |
|
| 4658 |
|
| 4659 |
|
| 4660 |
|
| 4661 |
|
| 4662 |
|
| 4663 |
|
| 4664 |
|
| 4665 |
no_signature = set() |
| 4666 |
|
| 4667 |
needs_groups = {"range", "slice", "dir", "getattr", |
| 4668 |
"next", "iter", "vars"} |
| 4669 |
no_signature |= needs_groups |
| 4670 |
|
| 4671 |
needs_null = {"anext"} |
| 4672 |
no_signature |= needs_null |
| 4673 |
|
| 4674 |
needs_varargs = {"breakpoint", "min", "max", "__build_class__"} |
| 4675 |
no_signature |= needs_varargs |
| 4676 |
|
| 4677 |
types_with_signatures = { |
| 4678 |
'complex', 'enumerate', 'float', 'list', 'memoryview', 'object', |
| 4679 |
'property', 'reversed', 'tuple', |
| 4680 |
} |
| 4681 |
|
| 4682 |
ns = vars(builtins) |
| 4683 |
for name, obj in sorted(ns.items()): |
| 4684 |
if not callable(obj): |
| 4685 |
continue |
| 4686 |
|
| 4687 |
if isinstance(obj, type) and (name not in types_with_signatures): |
| 4688 |
|
| 4689 |
no_signature.add(name) |
| 4690 |
if (name in no_signature): |
| 4691 |
|
| 4692 |
continue |
| 4693 |
with self.subTest(builtin=name): |
| 4694 |
self.assertIsNotNone(inspect.signature(obj)) |
| 4695 |
|
| 4696 |
|
| 4697 |
|
| 4698 |
|
| 4699 |
for name in no_signature - needs_null: |
| 4700 |
with self.subTest(builtin=name): |
| 4701 |
self.assertIsNone(ns[name].__text_signature__) |
| 4702 |
|
| 4703 |
def test_python_function_override_signature(self): |
| 4704 |
def func(*args, **kwargs): |
| 4705 |
pass |
| 4706 |
func.__text_signature__ = '($self, a, b=1, *args, c, d=2, **kwargs)' |
| 4707 |
sig = inspect.signature(func) |
| 4708 |
self.assertIsNotNone(sig) |
| 4709 |
self.assertEqual(str(sig), '(self, /, a, b=1, *args, c, d=2, **kwargs)') |
| 4710 |
|
| 4711 |
func.__text_signature__ = '($self, a, b=1, /, *args, c, d=2, **kwargs)' |
| 4712 |
sig = inspect.signature(func) |
| 4713 |
self.assertEqual(str(sig), '(self, a, b=1, /, *args, c, d=2, **kwargs)') |
| 4714 |
|
| 4715 |
func.__text_signature__ = '(self, a=1+2, b=4-3, c=1 | 3 | 16)' |
| 4716 |
sig = inspect.signature(func) |
| 4717 |
self.assertEqual(str(sig), '(self, a=3, b=1, c=19)') |
| 4718 |
|
| 4719 |
func.__text_signature__ = '(self, a=1,\nb=2,\n\n\n c=3)' |
| 4720 |
sig = inspect.signature(func) |
| 4721 |
self.assertEqual(str(sig), '(self, a=1, b=2, c=3)') |
| 4722 |
|
| 4723 |
func.__text_signature__ = '(self, x=does_not_exist)' |
| 4724 |
with self.assertRaises(ValueError): |
| 4725 |
inspect.signature(func) |
| 4726 |
func.__text_signature__ = '(self, x=sys, y=inspect)' |
| 4727 |
with self.assertRaises(ValueError): |
| 4728 |
inspect.signature(func) |
| 4729 |
func.__text_signature__ = '(self, 123)' |
| 4730 |
with self.assertRaises(ValueError): |
| 4731 |
inspect.signature(func) |
| 4732 |
|
| 4733 |
def test_base_class_have_text_signature(self): |
| 4734 |
|
| 4735 |
from test.typinganndata.ann_module7 import BufferedReader |
| 4736 |
class MyBufferedReader(BufferedReader): |
| 4737 |
"""buffer reader class.""" |
| 4738 |
|
| 4739 |
text_signature = BufferedReader.__text_signature__ |
| 4740 |
self.assertEqual(text_signature, '(raw, buffer_size=DEFAULT_BUFFER_SIZE)') |
| 4741 |
sig = inspect.signature(MyBufferedReader) |
| 4742 |
self.assertEqual(str(sig), '(raw, buffer_size=8192)') |
| 4743 |
|
| 4744 |
|
| 4745 |
class NTimesUnwrappable: |
| 4746 |
def __init__(self, n): |
| 4747 |
self.n = n |
| 4748 |
self._next = None |
| 4749 |
|
| 4750 |
@property |
| 4751 |
def __wrapped__(self): |
| 4752 |
if self.n <= 0: |
| 4753 |
raise Exception("Unwrapped too many times") |
| 4754 |
if self._next is None: |
| 4755 |
self._next = NTimesUnwrappable(self.n - 1) |
| 4756 |
return self._next |
| 4757 |
|
| 4758 |
class TestUnwrap(unittest.TestCase): |
| 4759 |
|
| 4760 |
def test_unwrap_one(self): |
| 4761 |
def func(a, b): |
| 4762 |
return a + b |
| 4763 |
wrapper = functools.lru_cache(maxsize=20)(func) |
| 4764 |
self.assertIs(inspect.unwrap(wrapper), func) |
| 4765 |
|
| 4766 |
def test_unwrap_several(self): |
| 4767 |
def func(a, b): |
| 4768 |
return a + b |
| 4769 |
wrapper = func |
| 4770 |
for __ in range(10): |
| 4771 |
@functools.wraps(wrapper) |
| 4772 |
def wrapper(): |
| 4773 |
pass |
| 4774 |
self.assertIsNot(wrapper.__wrapped__, func) |
| 4775 |
self.assertIs(inspect.unwrap(wrapper), func) |
| 4776 |
|
| 4777 |
def test_stop(self): |
| 4778 |
def func1(a, b): |
| 4779 |
return a + b |
| 4780 |
@functools.wraps(func1) |
| 4781 |
def func2(): |
| 4782 |
pass |
| 4783 |
@functools.wraps(func2) |
| 4784 |
def wrapper(): |
| 4785 |
pass |
| 4786 |
func2.stop_here = 1 |
| 4787 |
unwrapped = inspect.unwrap(wrapper, |
| 4788 |
stop=(lambda f: hasattr(f, "stop_here"))) |
| 4789 |
self.assertIs(unwrapped, func2) |
| 4790 |
|
| 4791 |
def test_cycle(self): |
| 4792 |
def func1(): pass |
| 4793 |
func1.__wrapped__ = func1 |
| 4794 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 4795 |
inspect.unwrap(func1) |
| 4796 |
|
| 4797 |
def func2(): pass |
| 4798 |
func2.__wrapped__ = func1 |
| 4799 |
func1.__wrapped__ = func2 |
| 4800 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 4801 |
inspect.unwrap(func1) |
| 4802 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 4803 |
inspect.unwrap(func2) |
| 4804 |
|
| 4805 |
def test_unhashable(self): |
| 4806 |
def func(): pass |
| 4807 |
func.__wrapped__ = None |
| 4808 |
class C: |
| 4809 |
__hash__ = None |
| 4810 |
__wrapped__ = func |
| 4811 |
self.assertIsNone(inspect.unwrap(C())) |
| 4812 |
|
| 4813 |
def test_recursion_limit(self): |
| 4814 |
obj = NTimesUnwrappable(sys.getrecursionlimit() + 1) |
| 4815 |
with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 4816 |
inspect.unwrap(obj) |
| 4817 |
|
| 4818 |
def test_wrapped_descriptor(self): |
| 4819 |
self.assertIs(inspect.unwrap(NTimesUnwrappable), NTimesUnwrappable) |
| 4820 |
self.assertIs(inspect.unwrap(staticmethod), staticmethod) |
| 4821 |
self.assertIs(inspect.unwrap(classmethod), classmethod) |
| 4822 |
self.assertIs(inspect.unwrap(staticmethod(classmethod)), classmethod) |
| 4823 |
self.assertIs(inspect.unwrap(classmethod(staticmethod)), staticmethod) |
| 4824 |
|
| 4825 |
|
| 4826 |
class TestMain(unittest.TestCase): |
| 4827 |
def test_only_source(self): |
| 4828 |
module = importlib.import_module('unittest') |
| 4829 |
rc, out, err = assert_python_ok('-m', 'inspect', |
| 4830 |
'unittest') |
| 4831 |
lines = out.decode().splitlines() |
| 4832 |
|
| 4833 |
self.assertEqual(lines[:-1], inspect.getsource(module).splitlines()) |
| 4834 |
self.assertEqual(err, b'') |
| 4835 |
|
| 4836 |
def test_custom_getattr(self): |
| 4837 |
def foo(): |
| 4838 |
pass |
| 4839 |
foo.__signature__ = 42 |
| 4840 |
with self.assertRaises(TypeError): |
| 4841 |
inspect.signature(foo) |
| 4842 |
|
| 4843 |
@unittest.skipIf(ThreadPoolExecutor is None, |
| 4844 |
'threads required to test __qualname__ for source files') |
| 4845 |
def test_qualname_source(self): |
| 4846 |
rc, out, err = assert_python_ok('-m', 'inspect', |
| 4847 |
'concurrent.futures:ThreadPoolExecutor') |
| 4848 |
lines = out.decode().splitlines() |
| 4849 |
|
| 4850 |
self.assertEqual(lines[:-1], |
| 4851 |
inspect.getsource(ThreadPoolExecutor).splitlines()) |
| 4852 |
self.assertEqual(err, b'') |
| 4853 |
|
| 4854 |
def test_builtins(self): |
| 4855 |
_, out, err = assert_python_failure('-m', 'inspect', |
| 4856 |
'sys') |
| 4857 |
lines = err.decode().splitlines() |
| 4858 |
self.assertEqual(lines, ["Can't get info for builtin modules."]) |
| 4859 |
|
| 4860 |
def test_details(self): |
| 4861 |
module = importlib.import_module('unittest') |
| 4862 |
args = support.optim_args_from_interpreter_flags() |
| 4863 |
rc, out, err = assert_python_ok(*args, '-m', 'inspect', |
| 4864 |
'unittest', '--details') |
| 4865 |
output = out.decode() |
| 4866 |
|
| 4867 |
self.assertIn(module.__name__, output) |
| 4868 |
self.assertIn(module.__file__, output) |
| 4869 |
self.assertIn(module.__cached__, output) |
| 4870 |
self.assertEqual(err, b'') |
| 4871 |
|
| 4872 |
|
| 4873 |
class TestReload(unittest.TestCase): |
| 4874 |
|
| 4875 |
src_before = textwrap.dedent("""\ |
| 4876 |
def foo(): |
| 4877 |
print("Bla") |
| 4878 |
""") |
| 4879 |
|
| 4880 |
src_after = textwrap.dedent("""\ |
| 4881 |
def foo(): |
| 4882 |
print("Oh no!") |
| 4883 |
""") |
| 4884 |
|
| 4885 |
def assertInspectEqual(self, path, source): |
| 4886 |
inspected_src = inspect.getsource(source) |
| 4887 |
with open(path, encoding='utf-8') as src: |
| 4888 |
self.assertEqual( |
| 4889 |
src.read().splitlines(True), |
| 4890 |
inspected_src.splitlines(True) |
| 4891 |
) |
| 4892 |
|
| 4893 |
def test_getsource_reload(self): |
| 4894 |
|
| 4895 |
with ready_to_import('reload_bug', self.src_before) as (name, path): |
| 4896 |
module = importlib.import_module(name) |
| 4897 |
self.assertInspectEqual(path, module) |
| 4898 |
with open(path, 'w', encoding='utf-8') as src: |
| 4899 |
src.write(self.src_after) |
| 4900 |
self.assertInspectEqual(path, module) |
| 4901 |
|
| 4902 |
|
| 4903 |
if __name__ == "__main__": |
| 4904 |
unittest.main() |