| 1 |
"""Tests util.inspect functions.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import ast |
| 6 |
import datetime |
| 7 |
import enum |
| 8 |
import functools |
| 9 |
import types |
| 10 |
from inspect import Parameter |
| 11 |
from typing import Callable, List, Optional, Union # NoQA: UP035 |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
from sphinx.util import inspect |
| 16 |
from sphinx.util.inspect import ( |
| 17 |
TypeAliasForwardRef, |
| 18 |
TypeAliasNamespace, |
| 19 |
stringify_signature, |
| 20 |
) |
| 21 |
from sphinx.util.typing import stringify_annotation |
| 22 |
|
| 23 |
|
| 24 |
class Base: |
| 25 |
def meth(self): |
| 26 |
pass |
| 27 |
|
| 28 |
@staticmethod |
| 29 |
def staticmeth(): |
| 30 |
pass |
| 31 |
|
| 32 |
@classmethod |
| 33 |
def classmeth(cls): |
| 34 |
pass |
| 35 |
|
| 36 |
@property |
| 37 |
def prop(self): |
| 38 |
pass |
| 39 |
|
| 40 |
partialmeth = functools.partialmethod(meth) |
| 41 |
|
| 42 |
async def coroutinemeth(self): |
| 43 |
pass |
| 44 |
|
| 45 |
partial_coroutinemeth = functools.partialmethod(coroutinemeth) |
| 46 |
|
| 47 |
@classmethod |
| 48 |
async def coroutineclassmeth(cls): |
| 49 |
"""A documented coroutine classmethod""" |
| 50 |
pass |
| 51 |
|
| 52 |
|
| 53 |
class Inherited(Base): |
| 54 |
pass |
| 55 |
|
| 56 |
|
| 57 |
class MyInt(int): |
| 58 |
@classmethod |
| 59 |
def classmeth(cls): |
| 60 |
pass |
| 61 |
|
| 62 |
|
| 63 |
class MyIntOverride(MyInt): |
| 64 |
@classmethod |
| 65 |
def from_bytes(cls, *a, **kw): |
| 66 |
return super().from_bytes(*a, **kw) |
| 67 |
|
| 68 |
def conjugate(self): |
| 69 |
return super().conjugate() |
| 70 |
|
| 71 |
|
| 72 |
def func(): |
| 73 |
pass |
| 74 |
|
| 75 |
|
| 76 |
async def coroutinefunc(): |
| 77 |
pass |
| 78 |
|
| 79 |
|
| 80 |
async def asyncgenerator(): # NoQA: RUF029 |
| 81 |
yield |
| 82 |
|
| 83 |
|
| 84 |
partial_func = functools.partial(func) |
| 85 |
partial_coroutinefunc = functools.partial(coroutinefunc) |
| 86 |
|
| 87 |
builtin_func = print |
| 88 |
partial_builtin_func = functools.partial(print) |
| 89 |
|
| 90 |
|
| 91 |
class Descriptor: |
| 92 |
def __get__(self, obj, typ=None): |
| 93 |
pass |
| 94 |
|
| 95 |
|
| 96 |
class _Callable: |
| 97 |
def __call__(self): |
| 98 |
pass |
| 99 |
|
| 100 |
|
| 101 |
def _decorator(f): |
| 102 |
@functools.wraps(f) |
| 103 |
def wrapper(): |
| 104 |
return f() |
| 105 |
|
| 106 |
return wrapper |
| 107 |
|
| 108 |
|
| 109 |
def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # noqa: F821 |
| 110 |
pass |
| 111 |
|
| 112 |
|
| 113 |
def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # noqa: F821 |
| 114 |
pass |
| 115 |
|
| 116 |
|
| 117 |
def test_TypeAliasForwardRef(): |
| 118 |
alias = TypeAliasForwardRef('example') |
| 119 |
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') |
| 120 |
assert sig_str == "TypeAliasForwardRef('example')" |
| 121 |
|
| 122 |
alias = Optional[alias] # NoQA: UP045 |
| 123 |
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') |
| 124 |
assert sig_str == "TypeAliasForwardRef('example') | None" |
| 125 |
|
| 126 |
alias = alias | None |
| 127 |
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') |
| 128 |
assert sig_str == "TypeAliasForwardRef('example') | None" |
| 129 |
|
| 130 |
alias = None | alias # NoQA: RUF036 |
| 131 |
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing') |
| 132 |
assert sig_str == "None | TypeAliasForwardRef('example')" |
| 133 |
|
| 134 |
|
| 135 |
def test_TypeAliasNamespace() -> None: |
| 136 |
import logging.config |
| 137 |
|
| 138 |
type_alias = TypeAliasNamespace({ |
| 139 |
'logging.Filter': 'MyFilter', |
| 140 |
'logging.Handler': 'MyHandler', |
| 141 |
'logging.handlers.SyslogHandler': 'MySyslogHandler', |
| 142 |
}) |
| 143 |
|
| 144 |
assert type_alias['logging'].Filter == 'MyFilter' |
| 145 |
assert type_alias['logging'].Handler == 'MyHandler' |
| 146 |
assert type_alias['logging'].handlers.SyslogHandler == 'MySyslogHandler' |
| 147 |
assert type_alias['logging'].Logger == logging.Logger |
| 148 |
assert type_alias['logging'].config == logging.config |
| 149 |
|
| 150 |
with pytest.raises(KeyError): |
| 151 |
assert type_alias['log'] |
| 152 |
|
| 153 |
with pytest.raises(KeyError): |
| 154 |
assert type_alias['unknown'] |
| 155 |
|
| 156 |
|
| 157 |
def test_signature() -> None: |
| 158 |
# literals |
| 159 |
with pytest.raises(TypeError): |
| 160 |
inspect.signature(1) # type: ignore[arg-type] |
| 161 |
|
| 162 |
with pytest.raises(TypeError): |
| 163 |
inspect.signature('') # type: ignore[arg-type] |
| 164 |
|
| 165 |
# builtins are supported on a case-by-case basis, depending on whether |
| 166 |
# they define __text_signature__ |
| 167 |
if getattr(list, '__text_signature__', None): |
| 168 |
sig = inspect.stringify_signature(inspect.signature(list)) |
| 169 |
assert sig == '(iterable=(), /)' |
| 170 |
else: |
| 171 |
with pytest.raises(ValueError, match='no signature found for builtin type'): |
| 172 |
inspect.signature(list) |
| 173 |
with pytest.raises(ValueError, match='no signature found for builtin type'): |
| 174 |
inspect.signature(range) |
| 175 |
|
| 176 |
# normal function |
| 177 |
def func(a, b, c=1, d=2, *e, **f): |
| 178 |
pass |
| 179 |
|
| 180 |
sig = inspect.stringify_signature(inspect.signature(func)) |
| 181 |
assert sig == '(a, b, c=1, d=2, *e, **f)' |
| 182 |
|
| 183 |
# forward references |
| 184 |
sig = inspect.stringify_signature(inspect.signature(forward_reference_in_args)) |
| 185 |
assert sig == '(x: Foo) -> None' |
| 186 |
|
| 187 |
sig = inspect.stringify_signature(inspect.signature(forward_reference_in_return)) |
| 188 |
assert sig == '() -> Foo' |
| 189 |
|
| 190 |
|
| 191 |
def test_signature_partial() -> None: |
| 192 |
def fun(a, b, c=1, d=2): |
| 193 |
pass |
| 194 |
|
| 195 |
p = functools.partial(fun, 10, c=11) |
| 196 |
|
| 197 |
sig = inspect.signature(p) |
| 198 |
assert stringify_signature(sig) == '(b, *, c=11, d=2)' |
| 199 |
|
| 200 |
|
| 201 |
def test_signature_methods() -> None: |
| 202 |
class Foo: |
| 203 |
def meth1(self, arg1, **kwargs): |
| 204 |
pass |
| 205 |
|
| 206 |
@classmethod |
| 207 |
def meth2(cls, arg1, *args, **kwargs): |
| 208 |
pass |
| 209 |
|
| 210 |
@staticmethod |
| 211 |
def meth3(arg1, *args, **kwargs): |
| 212 |
pass |
| 213 |
|
| 214 |
@functools.wraps(Foo().meth1) |
| 215 |
def wrapped_bound_method(*args, **kwargs): |
| 216 |
pass |
| 217 |
|
| 218 |
# unbound method |
| 219 |
sig = inspect.signature(Foo.meth1) |
| 220 |
assert stringify_signature(sig) == '(self, arg1, **kwargs)' |
| 221 |
|
| 222 |
sig = inspect.signature(Foo.meth1, bound_method=True) |
| 223 |
assert stringify_signature(sig) == '(arg1, **kwargs)' |
| 224 |
|
| 225 |
# bound method |
| 226 |
sig = inspect.signature(Foo().meth1) |
| 227 |
assert stringify_signature(sig) == '(arg1, **kwargs)' |
| 228 |
|
| 229 |
# class method |
| 230 |
sig = inspect.signature(Foo.meth2) |
| 231 |
assert stringify_signature(sig) == '(arg1, *args, **kwargs)' |
| 232 |
|
| 233 |
sig = inspect.signature(Foo().meth2) |
| 234 |
assert stringify_signature(sig) == '(arg1, *args, **kwargs)' |
| 235 |
|
| 236 |
# static method |
| 237 |
sig = inspect.signature(Foo.meth3) |
| 238 |
assert stringify_signature(sig) == '(arg1, *args, **kwargs)' |
| 239 |
|
| 240 |
sig = inspect.signature(Foo().meth3) |
| 241 |
assert stringify_signature(sig) == '(arg1, *args, **kwargs)' |
| 242 |
|
| 243 |
# wrapped bound method |
| 244 |
sig = inspect.signature(wrapped_bound_method) |
| 245 |
assert stringify_signature(sig) == '(arg1, **kwargs)' |
| 246 |
|
| 247 |
|
| 248 |
def test_signature_partialmethod() -> None: |
| 249 |
from functools import partialmethod |
| 250 |
|
| 251 |
class Foo: |
| 252 |
def meth1(self, arg1, arg2, arg3=None, arg4=None): |
| 253 |
pass |
| 254 |
|
| 255 |
def meth2(self, arg1, arg2): |
| 256 |
pass |
| 257 |
|
| 258 |
foo = partialmethod(meth1, 1, 2) |
| 259 |
bar = partialmethod(meth1, 1, arg3=3) |
| 260 |
baz = partialmethod(meth2, 1, 2) |
| 261 |
|
| 262 |
subject = Foo() |
| 263 |
sig = inspect.signature(subject.foo) |
| 264 |
assert stringify_signature(sig) == '(arg3=None, arg4=None)' |
| 265 |
|
| 266 |
sig = inspect.signature(subject.bar) |
| 267 |
assert stringify_signature(sig) == '(arg2, *, arg3=3, arg4=None)' |
| 268 |
|
| 269 |
sig = inspect.signature(subject.baz) |
| 270 |
assert stringify_signature(sig) == '()' |
| 271 |
|
| 272 |
|
| 273 |
def test_signature_annotations() -> None: |
| 274 |
import tests.test_util.typing_test_data as mod |
| 275 |
|
| 276 |
# Class annotations |
| 277 |
sig = inspect.signature(mod.f0) |
| 278 |
assert stringify_signature(sig) == '(x: int, y: numbers.Integral) -> None' |
| 279 |
|
| 280 |
# Generic types with concrete parameters |
| 281 |
sig = inspect.signature(mod.f1) |
| 282 |
assert stringify_signature(sig) == '(x: list[int]) -> typing.List[int]' |
| 283 |
|
| 284 |
# TypeVars and generic types with TypeVars |
| 285 |
sig = inspect.signature(mod.f2) |
| 286 |
assert stringify_signature(sig) == ( |
| 287 |
'(x: typing.List[tests.test_util.typing_test_data.T],' |
| 288 |
' y: typing.List[tests.test_util.typing_test_data.T_co],' |
| 289 |
' z: tests.test_util.typing_test_data.T' |
| 290 |
') -> typing.List[tests.test_util.typing_test_data.T_contra]' |
| 291 |
) |
| 292 |
|
| 293 |
# Union types |
| 294 |
sig = inspect.signature(mod.f3) |
| 295 |
assert stringify_signature(sig) == '(x: str | numbers.Integral) -> None' |
| 296 |
|
| 297 |
# Quoted annotations |
| 298 |
sig = inspect.signature(mod.f4) |
| 299 |
assert stringify_signature(sig) == '(x: str, y: str) -> None' |
| 300 |
|
| 301 |
# Keyword-only arguments |
| 302 |
sig = inspect.signature(mod.f5) |
| 303 |
assert stringify_signature(sig) == '(x: int, *, y: str, z: str) -> None' |
| 304 |
|
| 305 |
# Keyword-only arguments with varargs |
| 306 |
sig = inspect.signature(mod.f6) |
| 307 |
assert stringify_signature(sig) == '(x: int, *args, y: str, z: str) -> None' |
| 308 |
|
| 309 |
# Space around '=' for defaults |
| 310 |
sig = inspect.signature(mod.f7) |
| 311 |
sig_str = stringify_signature(sig) |
| 312 |
assert sig_str == '(x: int = None, y: dict = {}) -> None' |
| 313 |
|
| 314 |
# Callable types |
| 315 |
sig = inspect.signature(mod.f8) |
| 316 |
assert stringify_signature(sig) == '(x: typing.Callable[[int, str], int]) -> None' |
| 317 |
|
| 318 |
sig = inspect.signature(mod.f9) |
| 319 |
assert stringify_signature(sig) == '(x: typing.Callable) -> None' |
| 320 |
|
| 321 |
# Tuple types |
| 322 |
sig = inspect.signature(mod.f10) |
| 323 |
sig_str = stringify_signature(sig) |
| 324 |
assert sig_str == '(x: typing.Tuple[int, str], y: typing.Tuple[int, ...]) -> None' |
| 325 |
|
| 326 |
# Instance annotations |
| 327 |
sig = inspect.signature(mod.f11) |
| 328 |
assert stringify_signature(sig) == '(x: CustomAnnotation, y: 123) -> None' |
| 329 |
|
| 330 |
# tuple with more than two items |
| 331 |
sig = inspect.signature(mod.f12) |
| 332 |
assert stringify_signature(sig) == '() -> typing.Tuple[int, str, int]' |
| 333 |
|
| 334 |
# optional |
| 335 |
sig = inspect.signature(mod.f13) |
| 336 |
assert stringify_signature(sig) == '() -> str | None' |
| 337 |
|
| 338 |
# optional union |
| 339 |
sig = inspect.signature(mod.f20) |
| 340 |
assert stringify_signature(sig) in { |
| 341 |
'() -> int | str | None', |
| 342 |
'() -> str | int | None', |
| 343 |
} |
| 344 |
|
| 345 |
# Any |
| 346 |
sig = inspect.signature(mod.f14) |
| 347 |
assert stringify_signature(sig) == '() -> typing.Any' |
| 348 |
|
| 349 |
# ForwardRef |
| 350 |
sig = inspect.signature(mod.f15) |
| 351 |
assert stringify_signature(sig) == '(x: Unknown, y: int) -> typing.Any' |
| 352 |
|
| 353 |
# keyword only arguments (1) |
| 354 |
sig = inspect.signature(mod.f16) |
| 355 |
assert stringify_signature(sig) == '(arg1, arg2, *, arg3=None, arg4=None)' |
| 356 |
|
| 357 |
# keyword only arguments (2) |
| 358 |
sig = inspect.signature(mod.f17) |
| 359 |
assert stringify_signature(sig) == '(*, arg3, arg4)' |
| 360 |
|
| 361 |
sig = inspect.signature(mod.f18) |
| 362 |
assert stringify_signature(sig) == ( |
| 363 |
'(self, arg1: int | typing.Tuple = 10) -> typing.List[typing.Dict]' |
| 364 |
) |
| 365 |
|
| 366 |
# annotations for variadic and keyword parameters |
| 367 |
sig = inspect.signature(mod.f19) |
| 368 |
assert stringify_signature(sig) == '(*args: int, **kwargs: str)' |
| 369 |
|
| 370 |
# default value is inspect.Signature.empty |
| 371 |
sig = inspect.signature(mod.f21) |
| 372 |
assert stringify_signature(sig) == "(arg1='whatever', arg2)" |
| 373 |
|
| 374 |
# type hints by string |
| 375 |
sig = inspect.signature(mod.Node.children) |
| 376 |
sig_str = stringify_signature(sig) |
| 377 |
assert sig_str == '(self) -> typing.List[tests.test_util.typing_test_data.Node]' |
| 378 |
|
| 379 |
sig = inspect.signature(mod.Node.__init__) |
| 380 |
sig_str = stringify_signature(sig) |
| 381 |
assert sig_str == ( |
| 382 |
'(self, parent: tests.test_util.typing_test_data.Node | None) -> None' |
| 383 |
) |
| 384 |
|
| 385 |
# show_annotation is False |
| 386 |
sig = inspect.signature(mod.f7) |
| 387 |
assert stringify_signature(sig, show_annotation=False) == '(x=None, y={})' |
| 388 |
|
| 389 |
# show_return_annotation is False |
| 390 |
sig = inspect.signature(mod.f7) |
| 391 |
sig_str = stringify_signature(sig, show_return_annotation=False) |
| 392 |
assert sig_str == '(x: int = None, y: dict = {})' |
| 393 |
|
| 394 |
# unqualified_typehints is True |
| 395 |
sig = inspect.signature(mod.f7) |
| 396 |
sig_str = stringify_signature(sig, unqualified_typehints=True) |
| 397 |
assert sig_str == '(x: int = None, y: dict = {}) -> None' |
| 398 |
|
| 399 |
# case: separator at head |
| 400 |
sig = inspect.signature(mod.f22) |
| 401 |
assert stringify_signature(sig) == '(*, a, b)' |
| 402 |
|
| 403 |
# case: separator in the middle |
| 404 |
sig = inspect.signature(mod.f23) |
| 405 |
assert stringify_signature(sig) == '(a, b, /, c, d)' |
| 406 |
|
| 407 |
sig = inspect.signature(mod.f24) |
| 408 |
assert stringify_signature(sig) == '(a, /, *, b)' |
| 409 |
|
| 410 |
# case: separator at tail |
| 411 |
sig = inspect.signature(mod.f25) |
| 412 |
assert stringify_signature(sig) == '(a, b, /)' |
| 413 |
|
| 414 |
# collapse Literal types |
| 415 |
sig = inspect.signature(mod.f26) |
| 416 |
sig_str = stringify_signature(sig) |
| 417 |
assert sig_str == ( |
| 418 |
"(x: typing.Literal[1, 2, 3] = 1, y: typing.Literal['a', 'b'] = 'a') -> None" |
| 419 |
) |
| 420 |
|
| 421 |
|
| 422 |
def test_signature_from_str_basic() -> None: |
| 423 |
signature = '(a, b, *args, c=0, d="blah", **kwargs)' |
| 424 |
sig = inspect.signature_from_str(signature) |
| 425 |
assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs'] |
| 426 |
assert sig.parameters['a'].name == 'a' |
| 427 |
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD |
| 428 |
assert sig.parameters['a'].default == Parameter.empty |
| 429 |
assert sig.parameters['a'].annotation == Parameter.empty |
| 430 |
assert sig.parameters['b'].name == 'b' |
| 431 |
assert sig.parameters['b'].kind == Parameter.POSITIONAL_OR_KEYWORD |
| 432 |
assert sig.parameters['b'].default == Parameter.empty |
| 433 |
assert sig.parameters['b'].annotation == Parameter.empty |
| 434 |
assert sig.parameters['args'].name == 'args' |
| 435 |
assert sig.parameters['args'].kind == Parameter.VAR_POSITIONAL |
| 436 |
assert sig.parameters['args'].default == Parameter.empty |
| 437 |
assert sig.parameters['args'].annotation == Parameter.empty |
| 438 |
assert sig.parameters['c'].name == 'c' |
| 439 |
assert sig.parameters['c'].kind == Parameter.KEYWORD_ONLY |
| 440 |
assert sig.parameters['c'].default == '0' |
| 441 |
assert sig.parameters['c'].annotation == Parameter.empty |
| 442 |
assert sig.parameters['d'].name == 'd' |
| 443 |
assert sig.parameters['d'].kind == Parameter.KEYWORD_ONLY |
| 444 |
assert sig.parameters['d'].default == "'blah'" |
| 445 |
assert sig.parameters['d'].annotation == Parameter.empty |
| 446 |
assert sig.parameters['kwargs'].name == 'kwargs' |
| 447 |
assert sig.parameters['kwargs'].kind == Parameter.VAR_KEYWORD |
| 448 |
assert sig.parameters['kwargs'].default == Parameter.empty |
| 449 |
assert sig.parameters['kwargs'].annotation == Parameter.empty |
| 450 |
assert sig.return_annotation == Parameter.empty |
| 451 |
|
| 452 |
|
| 453 |
def test_signature_from_str_default_values() -> None: |
| 454 |
signature = ( |
| 455 |
'(a=0, b=0.0, c="str", d=b"bytes", e=..., f=True, ' |
| 456 |
'g=[1, 2, 3], h={"a": 1}, i={1, 2, 3}, ' |
| 457 |
'j=lambda x, y: None, k=None, l=object(), m=foo.bar.CONSTANT)' |
| 458 |
) |
| 459 |
sig = inspect.signature_from_str(signature) |
| 460 |
assert sig.parameters['a'].default == '0' |
| 461 |
assert sig.parameters['b'].default == '0.0' |
| 462 |
assert sig.parameters['c'].default == "'str'" |
| 463 |
assert sig.parameters['d'].default == "b'bytes'" |
| 464 |
assert sig.parameters['e'].default == '...' |
| 465 |
assert sig.parameters['f'].default == 'True' |
| 466 |
assert sig.parameters['g'].default == '[1, 2, 3]' |
| 467 |
assert sig.parameters['h'].default == "{'a': 1}" |
| 468 |
assert sig.parameters['i'].default == '{1, 2, 3}' |
| 469 |
assert sig.parameters['j'].default == 'lambda x, y: ...' |
| 470 |
assert sig.parameters['k'].default == 'None' |
| 471 |
assert sig.parameters['l'].default == 'object()' |
| 472 |
assert sig.parameters['m'].default == 'foo.bar.CONSTANT' |
| 473 |
|
| 474 |
|
| 475 |
def test_signature_from_str_annotations() -> None: |
| 476 |
signature = '(a: int, *args: bytes, b: str = "blah", **kwargs: float) -> None' |
| 477 |
sig = inspect.signature_from_str(signature) |
| 478 |
assert list(sig.parameters.keys()) == ['a', 'args', 'b', 'kwargs'] |
| 479 |
assert sig.parameters['a'].annotation == 'int' |
| 480 |
assert sig.parameters['args'].annotation == 'bytes' |
| 481 |
assert sig.parameters['b'].annotation == 'str' |
| 482 |
assert sig.parameters['kwargs'].annotation == 'float' |
| 483 |
assert sig.return_annotation == 'None' |
| 484 |
|
| 485 |
|
| 486 |
def test_signature_from_str_complex_annotations() -> None: |
| 487 |
sig = inspect.signature_from_str('() -> Tuple[str, int, ...]') |
| 488 |
assert sig.return_annotation == 'Tuple[str, int, ...]' |
| 489 |
|
| 490 |
sig = inspect.signature_from_str('() -> Callable[[int, int], int]') |
| 491 |
assert sig.return_annotation == 'Callable[[int, int], int]' |
| 492 |
|
| 493 |
|
| 494 |
def test_signature_from_str_kwonly_args() -> None: |
| 495 |
sig = inspect.signature_from_str('(a, *, b)') |
| 496 |
assert list(sig.parameters.keys()) == ['a', 'b'] |
| 497 |
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD |
| 498 |
assert sig.parameters['a'].default == Parameter.empty |
| 499 |
assert sig.parameters['b'].kind == Parameter.KEYWORD_ONLY |
| 500 |
assert sig.parameters['b'].default == Parameter.empty |
| 501 |
|
| 502 |
|
| 503 |
def test_signature_from_str_positionaly_only_args() -> None: |
| 504 |
sig = inspect.signature_from_str('(a, b=0, /, c=1)') |
| 505 |
assert list(sig.parameters.keys()) == ['a', 'b', 'c'] |
| 506 |
assert sig.parameters['a'].kind == Parameter.POSITIONAL_ONLY |
| 507 |
assert sig.parameters['a'].default == Parameter.empty |
| 508 |
assert sig.parameters['b'].kind == Parameter.POSITIONAL_ONLY |
| 509 |
assert sig.parameters['b'].default == '0' |
| 510 |
assert sig.parameters['c'].kind == Parameter.POSITIONAL_OR_KEYWORD |
| 511 |
assert sig.parameters['c'].default == '1' |
| 512 |
|
| 513 |
|
| 514 |
def test_signature_from_str_invalid() -> None: |
| 515 |
with pytest.raises(SyntaxError): |
| 516 |
inspect.signature_from_str('') |
| 517 |
|
| 518 |
|
| 519 |
def test_signature_from_ast(): |
| 520 |
signature = 'def func(a, b, *args, c=0, d="blah", **kwargs): pass' |
| 521 |
tree = ast.parse(signature) |
| 522 |
sig = inspect.signature_from_ast(tree.body[0]) |
| 523 |
assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs'] |
| 524 |
assert sig.parameters['a'].name == 'a' |
| 525 |
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD |
| 526 |
assert sig.parameters['a'].default == Parameter.empty |
| 527 |
assert sig.parameters['a'].annotation == Parameter.empty |
| 528 |
assert sig.parameters['b'].name == 'b' |
| 529 |
assert sig.parameters['b'].kind == Parameter.POSITIONAL_OR_KEYWORD |
| 530 |
assert sig.parameters['b'].default == Parameter.empty |
| 531 |
assert sig.parameters['b'].annotation == Parameter.empty |
| 532 |
assert sig.parameters['args'].name == 'args' |
| 533 |
assert sig.parameters['args'].kind == Parameter.VAR_POSITIONAL |
| 534 |
assert sig.parameters['args'].default == Parameter.empty |
| 535 |
assert sig.parameters['args'].annotation == Parameter.empty |
| 536 |
assert sig.parameters['c'].name == 'c' |
| 537 |
assert sig.parameters['c'].kind == Parameter.KEYWORD_ONLY |
| 538 |
assert sig.parameters['c'].default == '0' |
| 539 |
assert sig.parameters['c'].annotation == Parameter.empty |
| 540 |
assert sig.parameters['d'].name == 'd' |
| 541 |
assert sig.parameters['d'].kind == Parameter.KEYWORD_ONLY |
| 542 |
assert sig.parameters['d'].default == "'blah'" |
| 543 |
assert sig.parameters['d'].annotation == Parameter.empty |
| 544 |
assert sig.parameters['kwargs'].name == 'kwargs' |
| 545 |
assert sig.parameters['kwargs'].kind == Parameter.VAR_KEYWORD |
| 546 |
assert sig.parameters['kwargs'].default == Parameter.empty |
| 547 |
assert sig.parameters['kwargs'].annotation == Parameter.empty |
| 548 |
assert sig.return_annotation == Parameter.empty |
| 549 |
|
| 550 |
|
| 551 |
def test_safe_getattr_with_default() -> None: |
| 552 |
class Foo: |
| 553 |
def __getattr__(self, item): |
| 554 |
raise Exception |
| 555 |
|
| 556 |
obj = Foo() |
| 557 |
|
| 558 |
result = inspect.safe_getattr(obj, 'bar', 'baz') |
| 559 |
|
| 560 |
assert result == 'baz' |
| 561 |
|
| 562 |
|
| 563 |
def test_safe_getattr_with_exception() -> None: |
| 564 |
class Foo: |
| 565 |
def __getattr__(self, item): |
| 566 |
raise Exception |
| 567 |
|
| 568 |
obj = Foo() |
| 569 |
|
| 570 |
with pytest.raises(AttributeError, match='bar'): |
| 571 |
inspect.safe_getattr(obj, 'bar') |
| 572 |
|
| 573 |
|
| 574 |
def test_safe_getattr_with_property_exception() -> None: |
| 575 |
class Foo: |
| 576 |
@property |
| 577 |
def bar(self): |
| 578 |
raise Exception |
| 579 |
|
| 580 |
obj = Foo() |
| 581 |
|
| 582 |
with pytest.raises(AttributeError, match='bar'): |
| 583 |
inspect.safe_getattr(obj, 'bar') |
| 584 |
|
| 585 |
|
| 586 |
def test_safe_getattr_with___dict___override() -> None: |
| 587 |
class Foo: |
| 588 |
@property |
| 589 |
def __dict__(self): |
| 590 |
raise Exception |
| 591 |
|
| 592 |
obj = Foo() |
| 593 |
|
| 594 |
with pytest.raises(AttributeError, match='bar'): |
| 595 |
inspect.safe_getattr(obj, 'bar') |
| 596 |
|
| 597 |
|
| 598 |
def test_dictionary_sorting() -> None: |
| 599 |
dictionary = {'c': 3, 'a': 1, 'd': 2, 'b': 4} |
| 600 |
description = inspect.object_description(dictionary) |
| 601 |
assert description == "{'a': 1, 'b': 4, 'c': 3, 'd': 2}" |
| 602 |
|
| 603 |
|
| 604 |
def test_set_sorting() -> None: |
| 605 |
set_ = set('gfedcba') |
| 606 |
description = inspect.object_description(set_) |
| 607 |
assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}" |
| 608 |
|
| 609 |
|
| 610 |
def test_set_sorting_enum() -> None: |
| 611 |
class MyEnum(enum.Enum): |
| 612 |
a = 1 |
| 613 |
b = 2 |
| 614 |
c = 3 |
| 615 |
|
| 616 |
set_ = set(MyEnum) |
| 617 |
description = inspect.object_description(set_) |
| 618 |
assert description == '{MyEnum.a, MyEnum.b, MyEnum.c}' |
| 619 |
|
| 620 |
|
| 621 |
def test_set_sorting_fallback() -> None: |
| 622 |
set_ = {None, 1} |
| 623 |
description = inspect.object_description(set_) |
| 624 |
assert description == '{1, None}' |
| 625 |
|
| 626 |
|
| 627 |
def test_deterministic_nested_collection_descriptions() -> None: |
| 628 |
# sortable |
| 629 |
assert inspect.object_description([{1, 2, 3, 10}]) == '[{1, 2, 3, 10}]' |
| 630 |
assert inspect.object_description(({1, 2, 3, 10},)) == '({1, 2, 3, 10},)' |
| 631 |
# non-sortable (elements of varying datatype) |
| 632 |
assert inspect.object_description([{None, 1}]) == '[{1, None}]' |
| 633 |
assert inspect.object_description(({None, 1},)) == '({1, None},)' |
| 634 |
assert inspect.object_description([{None, 1, 'A'}]) == "[{'A', 1, None}]" |
| 635 |
assert inspect.object_description(({None, 1, 'A'},)) == "({'A', 1, None},)" |
| 636 |
|
| 637 |
|
| 638 |
def test_frozenset_sorting() -> None: |
| 639 |
frozenset_ = frozenset('gfedcba') |
| 640 |
description = inspect.object_description(frozenset_) |
| 641 |
assert description == "frozenset({'a', 'b', 'c', 'd', 'e', 'f', 'g'})" |
| 642 |
|
| 643 |
|
| 644 |
def test_frozenset_sorting_fallback() -> None: |
| 645 |
frozenset_ = frozenset((None, 1)) |
| 646 |
description = inspect.object_description(frozenset_) |
| 647 |
assert description == 'frozenset({1, None})' |
| 648 |
|
| 649 |
|
| 650 |
def test_nested_tuple_sorting(): |
| 651 |
tuple_ = ({'c', 'b', 'a'},) # nb. trailing comma |
| 652 |
description = inspect.object_description(tuple_) |
| 653 |
assert description == "({'a', 'b', 'c'},)" |
| 654 |
|
| 655 |
tuple_ = ({'c', 'b', 'a'}, {'f', 'e', 'd'}) |
| 656 |
description = inspect.object_description(tuple_) |
| 657 |
assert description == "({'a', 'b', 'c'}, {'d', 'e', 'f'})" |
| 658 |
|
| 659 |
|
| 660 |
def test_recursive_collection_description(): |
| 661 |
dict_a_, dict_b_ = {'a': 1}, {'b': 2} |
| 662 |
dict_a_['link'], dict_b_['link'] = dict_b_, dict_a_ |
| 663 |
description_a, description_b = ( |
| 664 |
inspect.object_description(dict_a_), |
| 665 |
inspect.object_description(dict_b_), |
| 666 |
) |
| 667 |
assert description_a == "{'a': 1, 'link': {'b': 2, 'link': dict(...)}}" |
| 668 |
assert description_b == "{'b': 2, 'link': {'a': 1, 'link': dict(...)}}" |
| 669 |
|
| 670 |
list_c_, list_d_ = [1, 2, 3, 4], [5, 6, 7, 8] |
| 671 |
list_c_.append(list_d_) |
| 672 |
list_d_.append(list_c_) |
| 673 |
description_c, description_d = ( |
| 674 |
inspect.object_description(list_c_), |
| 675 |
inspect.object_description(list_d_), |
| 676 |
) |
| 677 |
|
| 678 |
assert description_c == '[1, 2, 3, 4, [5, 6, 7, 8, list(...)]]' |
| 679 |
assert description_d == '[5, 6, 7, 8, [1, 2, 3, 4, list(...)]]' |
| 680 |
|
| 681 |
|
| 682 |
def test_dict_customtype() -> None: |
| 683 |
class CustomType: |
| 684 |
def __init__(self, value): |
| 685 |
self._value = value |
| 686 |
|
| 687 |
def __repr__(self): |
| 688 |
return '<CustomType(%r)>' % self._value |
| 689 |
|
| 690 |
dictionary = {CustomType(2): 2, CustomType(1): 1} |
| 691 |
description = inspect.object_description(dictionary) |
| 692 |
# Type is unsortable, just check that it does not crash |
| 693 |
assert '<CustomType(2)>: 2' in description |
| 694 |
|
| 695 |
|
| 696 |
def test_object_description_enum() -> None: |
| 697 |
class MyEnum(enum.Enum): |
| 698 |
FOO = 1 |
| 699 |
BAR = 2 |
| 700 |
|
| 701 |
assert inspect.object_description(MyEnum.FOO) == 'MyEnum.FOO' |
| 702 |
|
| 703 |
|
| 704 |
def test_object_description_enum_custom_repr() -> None: |
| 705 |
class MyEnum(enum.Enum): |
| 706 |
FOO = 1 |
| 707 |
BAR = 2 |
| 708 |
|
| 709 |
def __repr__(self): |
| 710 |
return self.name |
| 711 |
|
| 712 |
assert inspect.object_description(MyEnum.FOO) == 'FOO' |
| 713 |
|
| 714 |
|
| 715 |
def test_getslots() -> None: |
| 716 |
class Foo: |
| 717 |
pass |
| 718 |
|
| 719 |
class Bar: |
| 720 |
__slots__ = ['attr'] |
| 721 |
|
| 722 |
class Baz: |
| 723 |
__slots__ = {'attr': 'docstring'} |
| 724 |
|
| 725 |
class Qux: |
| 726 |
__slots__ = 'attr' # NoQA: PLC0205 |
| 727 |
|
| 728 |
assert inspect.getslots(Foo) is None |
| 729 |
assert inspect.getslots(Bar) == {'attr': None} |
| 730 |
assert inspect.getslots(Baz) == {'attr': 'docstring'} |
| 731 |
assert inspect.getslots(Qux) == {'attr': None} |
| 732 |
|
| 733 |
with pytest.raises(TypeError): |
| 734 |
inspect.getslots(Bar()) |
| 735 |
|
| 736 |
|
| 737 |
@pytest.mark.parametrize( |
| 738 |
('expect', 'klass', 'name'), |
| 739 |
[ |
| 740 |
# class methods |
| 741 |
(True, Base, 'classmeth'), |
| 742 |
(True, Inherited, 'classmeth'), |
| 743 |
(True, MyInt, 'classmeth'), |
| 744 |
(True, MyIntOverride, 'from_bytes'), |
| 745 |
# non class methods |
| 746 |
(False, Base, 'meth'), |
| 747 |
(False, Inherited, 'meth'), |
| 748 |
(False, MyInt, 'conjugate'), |
| 749 |
(False, MyIntOverride, 'conjugate'), |
| 750 |
], |
| 751 |
) |
| 752 |
def test_isclassmethod(expect, klass, name): |
| 753 |
subject = getattr(klass, name) |
| 754 |
assert inspect.isclassmethod(subject) is expect |
| 755 |
assert inspect.isclassmethod(None, klass, name) is expect |
| 756 |
|
| 757 |
|
| 758 |
@pytest.mark.parametrize( |
| 759 |
('expect', 'klass', 'dict_key'), |
| 760 |
[ |
| 761 |
# int.from_bytes is not a class method descriptor |
| 762 |
# but int.__dict__['from_bytes'] is one. |
| 763 |
(True, int, 'from_bytes'), |
| 764 |
(True, MyInt, 'from_bytes'), # inherited |
| 765 |
# non class method descriptors |
| 766 |
(False, Base, 'classmeth'), |
| 767 |
(False, Inherited, 'classmeth'), |
| 768 |
(False, int, '__init__'), |
| 769 |
(False, int, 'conjugate'), |
| 770 |
(False, MyInt, 'classmeth'), |
| 771 |
(False, MyIntOverride, 'from_bytes'), # overridden in pure Python |
| 772 |
], |
| 773 |
) |
| 774 |
def test_is_classmethod_descriptor(expect, klass, dict_key): |
| 775 |
in_dict = dict_key in klass.__dict__ |
| 776 |
subject = klass.__dict__.get(dict_key) |
| 777 |
assert inspect.is_classmethod_descriptor(subject) is (in_dict and expect) |
| 778 |
assert inspect.is_classmethod_descriptor(None, klass, dict_key) is expect |
| 779 |
|
| 780 |
method = getattr(klass, dict_key) |
| 781 |
assert not inspect.is_classmethod_descriptor(method) |
| 782 |
|
| 783 |
|
| 784 |
@pytest.mark.parametrize( |
| 785 |
('expect', 'klass', 'dict_key'), |
| 786 |
[ |
| 787 |
# class method descriptors |
| 788 |
(True, int, 'from_bytes'), |
| 789 |
(True, bytes, 'fromhex'), |
| 790 |
(True, MyInt, 'from_bytes'), # in C only |
| 791 |
# non class method descriptors |
| 792 |
(False, Base, 'classmeth'), |
| 793 |
(False, Inherited, 'classmeth'), |
| 794 |
(False, int, '__init__'), |
| 795 |
(False, int, 'conjugate'), |
| 796 |
(False, MyInt, 'classmeth'), |
| 797 |
(False, MyIntOverride, 'from_bytes'), # overridden in pure Python |
| 798 |
], |
| 799 |
) |
| 800 |
def test_is_builtin_classmethod_like(expect, klass, dict_key): |
| 801 |
method = getattr(klass, dict_key) |
| 802 |
assert inspect.is_builtin_classmethod_like(method) is expect |
| 803 |
assert inspect.is_builtin_classmethod_like(None, klass, dict_key) is expect |
| 804 |
|
| 805 |
|
| 806 |
@pytest.mark.parametrize( |
| 807 |
('expect', 'klass', 'name'), |
| 808 |
[ |
| 809 |
# regular class methods |
| 810 |
(True, Base, 'classmeth'), |
| 811 |
(True, Inherited, 'classmeth'), |
| 812 |
(True, MyInt, 'classmeth'), |
| 813 |
# inherited C class method |
| 814 |
(True, MyIntOverride, 'from_bytes'), |
| 815 |
# class method descriptors |
| 816 |
(True, int, 'from_bytes'), |
| 817 |
(True, bytes, 'fromhex'), |
| 818 |
(True, MyInt, 'from_bytes'), # in C only |
| 819 |
# not classmethod-like |
| 820 |
(False, int, '__init__'), |
| 821 |
(False, int, 'conjugate'), |
| 822 |
(False, MyIntOverride, 'conjugate'), # overridden in pure Python |
| 823 |
], |
| 824 |
) |
| 825 |
def test_is_classmethod_like(expect, klass, name): |
| 826 |
subject = getattr(klass, name) |
| 827 |
assert inspect.is_classmethod_like(subject) is expect |
| 828 |
|
| 829 |
|
| 830 |
def test_isstaticmethod() -> None: |
| 831 |
assert inspect.isstaticmethod(Base.staticmeth, Base, 'staticmeth') |
| 832 |
assert not inspect.isstaticmethod(Base.meth, Base, 'meth') |
| 833 |
assert inspect.isstaticmethod(Inherited.staticmeth, Inherited, 'staticmeth') |
| 834 |
assert not inspect.isstaticmethod(Inherited.meth, Inherited, 'meth') |
| 835 |
|
| 836 |
|
| 837 |
def test_iscoroutinefunction() -> None: |
| 838 |
# function |
| 839 |
assert not inspect.iscoroutinefunction(func) |
| 840 |
# coroutine |
| 841 |
assert inspect.iscoroutinefunction(coroutinefunc) |
| 842 |
# partial-ed coroutine |
| 843 |
assert inspect.iscoroutinefunction(partial_coroutinefunc) |
| 844 |
# method |
| 845 |
assert not inspect.iscoroutinefunction(Base.meth) |
| 846 |
# coroutine-method |
| 847 |
assert inspect.iscoroutinefunction(Base.coroutinemeth) |
| 848 |
# coroutine classmethod |
| 849 |
assert inspect.iscoroutinefunction(Base.__dict__['coroutineclassmeth']) |
| 850 |
|
| 851 |
# partial-ed coroutine-method |
| 852 |
partial_coroutinemeth = Base.__dict__['partial_coroutinemeth'] |
| 853 |
assert inspect.iscoroutinefunction(partial_coroutinemeth) |
| 854 |
|
| 855 |
|
| 856 |
def test_iscoroutinefunction_wrapped() -> None: |
| 857 |
# function wrapping a callable obj |
| 858 |
assert inspect.isfunction(_decorator(coroutinefunc)) |
| 859 |
|
| 860 |
|
| 861 |
def test_isfunction() -> None: |
| 862 |
# fmt: off |
| 863 |
assert inspect.isfunction(func) # function |
| 864 |
assert inspect.isfunction(partial_func) # partial-ed function |
| 865 |
assert inspect.isfunction(Base.meth) # method of class |
| 866 |
assert inspect.isfunction(Base.partialmeth) # partial-ed method of class |
| 867 |
assert not inspect.isfunction(Base().meth) # method of instance |
| 868 |
assert not inspect.isfunction(builtin_func) # builtin function |
| 869 |
assert not inspect.isfunction(partial_builtin_func) # partial-ed builtin function |
| 870 |
# fmt: on |
| 871 |
|
| 872 |
|
| 873 |
def test_isfunction_wrapped() -> None: |
| 874 |
# function wrapping a callable obj |
| 875 |
assert inspect.isfunction(_decorator(_Callable())) |
| 876 |
|
| 877 |
|
| 878 |
def test_isbuiltin() -> None: |
| 879 |
# fmt: off |
| 880 |
assert inspect.isbuiltin(builtin_func) # builtin function |
| 881 |
assert inspect.isbuiltin(partial_builtin_func) # partial-ed builtin function |
| 882 |
assert not inspect.isbuiltin(func) # function |
| 883 |
assert not inspect.isbuiltin(partial_func) # partial-ed function |
| 884 |
assert not inspect.isbuiltin(Base.meth) # method of class |
| 885 |
assert not inspect.isbuiltin(Base().meth) # method of instance |
| 886 |
# fmt: on |
| 887 |
|
| 888 |
|
| 889 |
def test_isdescriptor() -> None: |
| 890 |
# fmt: off |
| 891 |
assert inspect.isdescriptor(Base.prop) # property of class |
| 892 |
assert not inspect.isdescriptor(Base().prop) # property of instance |
| 893 |
assert inspect.isdescriptor(Base.meth) # method of class |
| 894 |
assert inspect.isdescriptor(Base().meth) # method of instance |
| 895 |
assert inspect.isdescriptor(func) # function |
| 896 |
# fmt: on |
| 897 |
|
| 898 |
|
| 899 |
def test_isattributedescriptor() -> None: |
| 900 |
# fmt: off |
| 901 |
assert inspect.isattributedescriptor(Base.prop) # property |
| 902 |
assert not inspect.isattributedescriptor(Base.meth) # method |
| 903 |
assert not inspect.isattributedescriptor(Base.staticmeth) # staticmethod |
| 904 |
assert not inspect.isattributedescriptor(Base.classmeth) # classmetho |
| 905 |
assert not inspect.isattributedescriptor(Descriptor) # custom descriptor class |
| 906 |
assert not inspect.isattributedescriptor(str.join) # MethodDescriptorType |
| 907 |
assert not inspect.isattributedescriptor(object.__init__) # WrapperDescriptorType |
| 908 |
assert not inspect.isattributedescriptor(dict.__dict__['fromkeys']) # ClassMethodDescriptorType |
| 909 |
assert inspect.isattributedescriptor(types.FrameType.f_locals) # GetSetDescriptorType |
| 910 |
assert inspect.isattributedescriptor(datetime.timedelta.days) # MemberDescriptorType |
| 911 |
# fmt: on |
| 912 |
|
| 913 |
try: |
| 914 |
# _testcapi module cannot be importable in some distro |
| 915 |
# See: https://github.com/sphinx-doc/sphinx/issues/9868 |
| 916 |
import _testcapi # type: ignore[import-not-found] |
| 917 |
|
| 918 |
# instancemethod (C-API) |
| 919 |
testinstancemethod = _testcapi.instancemethod(str.__repr__) |
| 920 |
assert not inspect.isattributedescriptor(testinstancemethod) |
| 921 |
except ImportError: |
| 922 |
pass |
| 923 |
|
| 924 |
|
| 925 |
def test_isproperty() -> None: |
| 926 |
# fmt: off |
| 927 |
assert inspect.isproperty(Base.prop) # property of class |
| 928 |
assert not inspect.isproperty(Base().prop) # property of instance |
| 929 |
assert not inspect.isproperty(Base.meth) # method of class |
| 930 |
assert not inspect.isproperty(Base().meth) # method of instance |
| 931 |
assert not inspect.isproperty(func) # function |
| 932 |
# fmt: on |
| 933 |
|
| 934 |
|
| 935 |
def test_isgenericalias() -> None: |
| 936 |
#: A list of int |
| 937 |
T = List[int] # NoQA: UP006 |
| 938 |
S = list[Union[str, None]] # NoQA: UP007 |
| 939 |
|
| 940 |
C = Callable[[int], None] # a generic alias not having a doccomment |
| 941 |
|
| 942 |
assert inspect.isgenericalias(C) |
| 943 |
assert inspect.isgenericalias(Callable) |
| 944 |
assert inspect.isgenericalias(T) |
| 945 |
assert inspect.isgenericalias(List) # NoQA: UP006 |
| 946 |
assert inspect.isgenericalias(S) |
| 947 |
assert not inspect.isgenericalias(list) |
| 948 |
assert not inspect.isgenericalias([]) |
| 949 |
assert not inspect.isgenericalias(object()) |
| 950 |
assert not inspect.isgenericalias(Base) |
| 951 |
|
| 952 |
|
| 953 |
def test_unpartial() -> None: |
| 954 |
def func1(a, b, c): |
| 955 |
pass |
| 956 |
|
| 957 |
func2 = functools.partial(func1, 1) |
| 958 |
func2.__doc__ = 'func2' |
| 959 |
func3 = functools.partial(func2, 2) # nested partial object |
| 960 |
|
| 961 |
assert inspect.unpartial(func2) is func1 |
| 962 |
assert inspect.unpartial(func3) is func1 |
| 963 |
|
| 964 |
|
| 965 |
def test_getdoc_inherited_classmethod(): |
| 966 |
class Foo: |
| 967 |
@classmethod |
| 968 |
def meth(cls): |
| 969 |
"""Docstring |
| 970 |
indented text |
| 971 |
""" |
| 972 |
|
| 973 |
class Bar(Foo): |
| 974 |
@classmethod |
| 975 |
def meth(cls): |
| 976 |
# inherited classmethod |
| 977 |
pass |
| 978 |
|
| 979 |
assert inspect.getdoc(Bar.meth, getattr, False, Bar, 'meth') is None |
| 980 |
assert inspect.getdoc(Bar.meth, getattr, True, Bar, 'meth') == Foo.meth.__doc__ |
| 981 |
|
| 982 |
|
| 983 |
def test_getdoc_inherited_decorated_method(): |
| 984 |
class Foo: |
| 985 |
def meth(self): |
| 986 |
"""Docstring |
| 987 |
indented text |
| 988 |
""" |
| 989 |
|
| 990 |
class Bar(Foo): |
| 991 |
@functools.lru_cache # NoQA: B019 |
| 992 |
def meth(self): |
| 993 |
# inherited and decorated method |
| 994 |
pass |
| 995 |
|
| 996 |
assert inspect.getdoc(Bar.meth, getattr, False, Bar, 'meth') is None |
| 997 |
assert inspect.getdoc(Bar.meth, getattr, True, Bar, 'meth') == Foo.meth.__doc__ |
| 998 |
|
| 999 |
|
| 1000 |
def test_is_builtin_class_method() -> None: |
| 1001 |
class MyInt(int): |
| 1002 |
def my_method(self) -> None: |
| 1003 |
pass |
| 1004 |
|
| 1005 |
assert inspect.is_builtin_class_method(MyInt, 'to_bytes') |
| 1006 |
assert inspect.is_builtin_class_method(MyInt, '__init__') |
| 1007 |
assert not inspect.is_builtin_class_method(MyInt, 'my_method') |
| 1008 |
assert not inspect.is_builtin_class_method(MyInt, 'does_not_exist') |
| 1009 |
assert not inspect.is_builtin_class_method(4, 'still does not crash') |
| 1010 |
|
| 1011 |
class ObjectWithMroAttr: |
| 1012 |
def __init__(self, mro_attr): |
| 1013 |
self.__mro__ = mro_attr |
| 1014 |
|
| 1015 |
assert not inspect.is_builtin_class_method( |
| 1016 |
ObjectWithMroAttr([1, 2, 3]), 'still does not crash' |
| 1017 |
) |