| 1 |
import io |
| 2 |
import sys |
| 3 |
from types import ModuleType |
| 4 |
from typing import Sequence, Type |
| 5 |
|
| 6 |
import pytest |
| 7 |
|
| 8 |
from rich import inspect |
| 9 |
from rich._inspect import ( |
| 10 |
get_object_types_mro, |
| 11 |
get_object_types_mro_as_strings, |
| 12 |
is_object_one_of_types, |
| 13 |
) |
| 14 |
from rich.console import Console |
| 15 |
|
| 16 |
skip_py38 = pytest.mark.skipif( |
| 17 |
sys.version_info.minor == 8 and sys.version_info.major == 3, |
| 18 |
reason="rendered differently on py3.8", |
| 19 |
) |
| 20 |
|
| 21 |
skip_py39 = pytest.mark.skipif( |
| 22 |
sys.version_info.minor == 9 and sys.version_info.major == 3, |
| 23 |
reason="rendered differently on py3.9", |
| 24 |
) |
| 25 |
|
| 26 |
skip_py310 = pytest.mark.skipif( |
| 27 |
sys.version_info.minor == 10 and sys.version_info.major == 3, |
| 28 |
reason="rendered differently on py3.10", |
| 29 |
) |
| 30 |
|
| 31 |
skip_py311 = pytest.mark.skipif( |
| 32 |
sys.version_info.minor == 11 and sys.version_info.major == 3, |
| 33 |
reason="rendered differently on py3.11", |
| 34 |
) |
| 35 |
|
| 36 |
skip_py312 = pytest.mark.skipif( |
| 37 |
sys.version_info.minor == 12 and sys.version_info.major == 3, |
| 38 |
reason="rendered differently on py3.12", |
| 39 |
) |
| 40 |
|
| 41 |
skip_py313 = pytest.mark.skipif( |
| 42 |
sys.version_info.minor == 13 and sys.version_info.major == 3, |
| 43 |
reason="rendered differently on py3.13", |
| 44 |
) |
| 45 |
|
| 46 |
skip_py314 = pytest.mark.skipif( |
| 47 |
sys.version_info.minor == 14 and sys.version_info.major == 3, |
| 48 |
reason="rendered differently on py3.14", |
| 49 |
) |
| 50 |
|
| 51 |
|
| 52 |
skip_pypy3 = pytest.mark.skipif( |
| 53 |
hasattr(sys, "pypy_version_info"), |
| 54 |
reason="rendered differently on pypy3", |
| 55 |
) |
| 56 |
|
| 57 |
|
| 58 |
def render(obj, methods=False, value=False, width=50) -> str: |
| 59 |
console = Console(file=io.StringIO(), width=width, legacy_windows=False) |
| 60 |
inspect(obj, console=console, methods=methods, value=value) |
| 61 |
return console.file.getvalue() |
| 62 |
|
| 63 |
|
| 64 |
class InspectError(Exception): |
| 65 |
def __str__(self) -> str: |
| 66 |
return "INSPECT ERROR" |
| 67 |
|
| 68 |
|
| 69 |
class Foo: |
| 70 |
"""Foo test |
| 71 |
|
| 72 |
Second line |
| 73 |
""" |
| 74 |
|
| 75 |
def __init__(self, foo: int) -> None: |
| 76 |
"""constructor docs.""" |
| 77 |
self.foo = foo |
| 78 |
|
| 79 |
@property |
| 80 |
def broken(self): |
| 81 |
raise InspectError() |
| 82 |
|
| 83 |
def method(self, a, b) -> str: |
| 84 |
"""Multi line |
| 85 |
|
| 86 |
docs. |
| 87 |
""" |
| 88 |
return "test" |
| 89 |
|
| 90 |
def __dir__(self): |
| 91 |
return ["__init__", "broken", "method"] |
| 92 |
|
| 93 |
|
| 94 |
class FooSubclass(Foo): |
| 95 |
pass |
| 96 |
|
| 97 |
|
| 98 |
def test_render(): |
| 99 |
console = Console(width=100, file=io.StringIO(), legacy_windows=False) |
| 100 |
|
| 101 |
foo = Foo("hello") |
| 102 |
inspect(foo, console=console, all=True, value=False) |
| 103 |
result = console.file.getvalue() |
| 104 |
print(repr(result)) |
| 105 |
expected = "╭────────────── <class 'tests.test_inspect.Foo'> ──────────────╮\n│ Foo test │\n│ │\n│ broken = InspectError() │\n│ __init__ = def __init__(foo: int) -> None: constructor docs. │\n│ method = def method(a, b) -> str: Multi line │\n╰──────────────────────────────────────────────────────────────╯\n" |
| 106 |
assert result == expected |
| 107 |
|
| 108 |
|
| 109 |
@skip_pypy3 |
| 110 |
def test_inspect_text(): |
| 111 |
num_attributes = 34 if sys.version_info >= (3, 11) else 33 |
| 112 |
expected = ( |
| 113 |
"╭──────────────── <class 'str'> ─────────────────╮\n" |
| 114 |
"│ str(object='') -> str │\n" |
| 115 |
"│ str(bytes_or_buffer[, encoding[, errors]]) -> │\n" |
| 116 |
"│ str │\n" |
| 117 |
"│ │\n" |
| 118 |
f"│ {num_attributes} attribute(s) not shown. Run │\n" |
| 119 |
"│ inspect(inspect) for options. │\n" |
| 120 |
"╰────────────────────────────────────────────────╯\n" |
| 121 |
) |
| 122 |
print(repr(expected)) |
| 123 |
assert render("Hello") == expected |
| 124 |
|
| 125 |
|
| 126 |
@skip_pypy3 |
| 127 |
def test_inspect_empty_dict(): |
| 128 |
expected = ( |
| 129 |
"╭──────────────── <class 'dict'> ────────────────╮\n" |
| 130 |
"│ dict() -> new empty dictionary │\n" |
| 131 |
"│ dict(mapping) -> new dictionary initialized │\n" |
| 132 |
"│ from a mapping object's │\n" |
| 133 |
"│ (key, value) pairs │\n" |
| 134 |
"│ dict(iterable) -> new dictionary initialized │\n" |
| 135 |
"│ as if via: │\n" |
| 136 |
"│ d = {} │\n" |
| 137 |
"│ for k, v in iterable: │\n" |
| 138 |
"│ d[k] = v │\n" |
| 139 |
"│ dict(**kwargs) -> new dictionary initialized │\n" |
| 140 |
"│ with the name=value pairs │\n" |
| 141 |
"│ in the keyword argument list. For │\n" |
| 142 |
"│ example: dict(one=1, two=2) │\n" |
| 143 |
"│ │\n" |
| 144 |
) |
| 145 |
assert render({}).startswith(expected) |
| 146 |
|
| 147 |
|
| 148 |
@skip_py314 |
| 149 |
@skip_py313 |
| 150 |
@skip_py312 |
| 151 |
@skip_py311 |
| 152 |
@skip_pypy3 |
| 153 |
def test_inspect_builtin_function_except_python311(): |
| 154 |
# Pre-3.11 Python versions - print builtin has no signature available |
| 155 |
expected = ( |
| 156 |
"╭────────── <built-in function print> ───────────╮\n" |
| 157 |
"│ def print(...) │\n" |
| 158 |
"│ │\n" |
| 159 |
"│ print(value, ..., sep=' ', end='\\n', │\n" |
| 160 |
"│ file=sys.stdout, flush=False) │\n" |
| 161 |
"│ │\n" |
| 162 |
"│ 29 attribute(s) not shown. Run │\n" |
| 163 |
"│ inspect(inspect) for options. │\n" |
| 164 |
"╰────────────────────────────────────────────────╯\n" |
| 165 |
) |
| 166 |
assert render(print) == expected |
| 167 |
|
| 168 |
|
| 169 |
@pytest.mark.skipif( |
| 170 |
sys.version_info < (3, 11), reason="print builtin signature only available on 3.11+" |
| 171 |
) |
| 172 |
@skip_pypy3 |
| 173 |
def test_inspect_builtin_function_only_python311(): |
| 174 |
# On 3.11, the print builtin *does* have a signature, unlike in prior versions |
| 175 |
expected = ( |
| 176 |
"╭────────── <built-in function print> ───────────╮\n" |
| 177 |
"│ def print(*args, sep=' ', end='\\n', file=None, │\n" |
| 178 |
"│ flush=False): │\n" |
| 179 |
"│ │\n" |
| 180 |
"│ Prints the values to a stream, or to │\n" |
| 181 |
"│ sys.stdout by default. │\n" |
| 182 |
"│ │\n" |
| 183 |
"│ 30 attribute(s) not shown. Run │\n" |
| 184 |
"│ inspect(inspect) for options. │\n" |
| 185 |
"╰────────────────────────────────────────────────╯\n" |
| 186 |
) |
| 187 |
assert render(print) == expected |
| 188 |
|
| 189 |
|
| 190 |
@skip_pypy3 |
| 191 |
def test_inspect_coroutine(): |
| 192 |
async def coroutine(): |
| 193 |
pass |
| 194 |
|
| 195 |
expected = ( |
| 196 |
"╭─ <function test_inspect_coroutine.<locals>.cor─╮\n" |
| 197 |
"│ async def │\n" |
| 198 |
"│ test_inspect_coroutine.<locals>.coroutine(): │\n" |
| 199 |
) |
| 200 |
assert render(coroutine).startswith(expected) |
| 201 |
|
| 202 |
|
| 203 |
def test_inspect_integer(): |
| 204 |
expected = ( |
| 205 |
"╭────── <class 'int'> ───────╮\n" |
| 206 |
"│ int([x]) -> integer │\n" |
| 207 |
"│ int(x, base=10) -> integer │\n" |
| 208 |
"│ │\n" |
| 209 |
"│ denominator = 1 │\n" |
| 210 |
"│ imag = 0 │\n" |
| 211 |
"│ numerator = 1 │\n" |
| 212 |
"│ real = 1 │\n" |
| 213 |
"╰────────────────────────────╯\n" |
| 214 |
) |
| 215 |
assert expected == render(1) |
| 216 |
|
| 217 |
|
| 218 |
def test_inspect_integer_with_value(): |
| 219 |
expected = "╭────── <class 'int'> ───────╮\n│ int([x]) -> integer │\n│ int(x, base=10) -> integer │\n│ │\n│ ╭────────────────────────╮ │\n│ │ 1 │ │\n│ ╰────────────────────────╯ │\n│ │\n│ denominator = 1 │\n│ imag = 0 │\n│ numerator = 1 │\n│ real = 1 │\n╰────────────────────────────╯\n" |
| 220 |
value = render(1, value=True) |
| 221 |
print(repr(value)) |
| 222 |
assert value == expected |
| 223 |
|
| 224 |
|
| 225 |
@skip_py310 |
| 226 |
@skip_py311 |
| 227 |
@skip_py312 |
| 228 |
@skip_py313 |
| 229 |
@skip_py314 |
| 230 |
def test_inspect_integer_with_methods_python38_and_python39(): |
| 231 |
expected = ( |
| 232 |
"╭──────────────── <class 'int'> ─────────────────╮\n" |
| 233 |
"│ int([x]) -> integer │\n" |
| 234 |
"│ int(x, base=10) -> integer │\n" |
| 235 |
"│ │\n" |
| 236 |
"│ denominator = 1 │\n" |
| 237 |
"│ imag = 0 │\n" |
| 238 |
"│ numerator = 1 │\n" |
| 239 |
"│ real = 1 │\n" |
| 240 |
"│ as_integer_ratio = def as_integer_ratio(): │\n" |
| 241 |
"│ Return integer ratio. │\n" |
| 242 |
"│ bit_length = def bit_length(): Number of │\n" |
| 243 |
"│ bits necessary to represent │\n" |
| 244 |
"│ self in binary. │\n" |
| 245 |
"│ conjugate = def conjugate(...) Returns │\n" |
| 246 |
"│ self, the complex conjugate │\n" |
| 247 |
"│ of any int. │\n" |
| 248 |
"│ from_bytes = def from_bytes(bytes, │\n" |
| 249 |
"│ byteorder, *, │\n" |
| 250 |
"│ signed=False): Return the │\n" |
| 251 |
"│ integer represented by the │\n" |
| 252 |
"│ given array of bytes. │\n" |
| 253 |
"│ to_bytes = def to_bytes(length, │\n" |
| 254 |
"│ byteorder, *, │\n" |
| 255 |
"│ signed=False): Return an │\n" |
| 256 |
"│ array of bytes representing │\n" |
| 257 |
"│ an integer. │\n" |
| 258 |
"╰────────────────────────────────────────────────╯\n" |
| 259 |
) |
| 260 |
assert render(1, methods=True) == expected |
| 261 |
|
| 262 |
|
| 263 |
@skip_py38 |
| 264 |
@skip_py39 |
| 265 |
@skip_py311 |
| 266 |
@skip_py312 |
| 267 |
@skip_py313 |
| 268 |
@skip_py314 |
| 269 |
def test_inspect_integer_with_methods_python310only(): |
| 270 |
expected = ( |
| 271 |
"╭──────────────── <class 'int'> ─────────────────╮\n" |
| 272 |
"│ int([x]) -> integer │\n" |
| 273 |
"│ int(x, base=10) -> integer │\n" |
| 274 |
"│ │\n" |
| 275 |
"│ denominator = 1 │\n" |
| 276 |
"│ imag = 0 │\n" |
| 277 |
"│ numerator = 1 │\n" |
| 278 |
"│ real = 1 │\n" |
| 279 |
"│ as_integer_ratio = def as_integer_ratio(): │\n" |
| 280 |
"│ Return integer ratio. │\n" |
| 281 |
"│ bit_count = def bit_count(): Number of │\n" |
| 282 |
"│ ones in the binary │\n" |
| 283 |
"│ representation of the │\n" |
| 284 |
"│ absolute value of self. │\n" |
| 285 |
"│ bit_length = def bit_length(): Number of │\n" |
| 286 |
"│ bits necessary to represent │\n" |
| 287 |
"│ self in binary. │\n" |
| 288 |
"│ conjugate = def conjugate(...) Returns │\n" |
| 289 |
"│ self, the complex conjugate │\n" |
| 290 |
"│ of any int. │\n" |
| 291 |
"│ from_bytes = def from_bytes(bytes, │\n" |
| 292 |
"│ byteorder, *, │\n" |
| 293 |
"│ signed=False): Return the │\n" |
| 294 |
"│ integer represented by the │\n" |
| 295 |
"│ given array of bytes. │\n" |
| 296 |
"│ to_bytes = def to_bytes(length, │\n" |
| 297 |
"│ byteorder, *, │\n" |
| 298 |
"│ signed=False): Return an │\n" |
| 299 |
"│ array of bytes representing │\n" |
| 300 |
"│ an integer. │\n" |
| 301 |
"╰────────────────────────────────────────────────╯\n" |
| 302 |
) |
| 303 |
assert render(1, methods=True) == expected |
| 304 |
|
| 305 |
|
| 306 |
@skip_py38 |
| 307 |
@skip_py39 |
| 308 |
@skip_py310 |
| 309 |
@skip_py312 |
| 310 |
@skip_py313 |
| 311 |
@skip_py314 |
| 312 |
def test_inspect_integer_with_methods_python311(): |
| 313 |
# to_bytes and from_bytes methods on int had minor signature change - |
| 314 |
# they now, as of 3.11, have default values for all of their parameters |
| 315 |
expected = ( |
| 316 |
"╭──────────────── <class 'int'> ─────────────────╮\n" |
| 317 |
"│ int([x]) -> integer │\n" |
| 318 |
"│ int(x, base=10) -> integer │\n" |
| 319 |
"│ │\n" |
| 320 |
"│ denominator = 1 │\n" |
| 321 |
"│ imag = 0 │\n" |
| 322 |
"│ numerator = 1 │\n" |
| 323 |
"│ real = 1 │\n" |
| 324 |
"│ as_integer_ratio = def as_integer_ratio(): │\n" |
| 325 |
"│ Return integer ratio. │\n" |
| 326 |
"│ bit_count = def bit_count(): Number of │\n" |
| 327 |
"│ ones in the binary │\n" |
| 328 |
"│ representation of the │\n" |
| 329 |
"│ absolute value of self. │\n" |
| 330 |
"│ bit_length = def bit_length(): Number of │\n" |
| 331 |
"│ bits necessary to represent │\n" |
| 332 |
"│ self in binary. │\n" |
| 333 |
"│ conjugate = def conjugate(...) Returns │\n" |
| 334 |
"│ self, the complex conjugate │\n" |
| 335 |
"│ of any int. │\n" |
| 336 |
"│ from_bytes = def from_bytes(bytes, │\n" |
| 337 |
"│ byteorder='big', *, │\n" |
| 338 |
"│ signed=False): Return the │\n" |
| 339 |
"│ integer represented by the │\n" |
| 340 |
"│ given array of bytes. │\n" |
| 341 |
"│ to_bytes = def to_bytes(length=1, │\n" |
| 342 |
"│ byteorder='big', *, │\n" |
| 343 |
"│ signed=False): Return an │\n" |
| 344 |
"│ array of bytes representing │\n" |
| 345 |
"│ an integer. │\n" |
| 346 |
"╰────────────────────────────────────────────────╯\n" |
| 347 |
) |
| 348 |
assert render(1, methods=True) == expected |
| 349 |
|
| 350 |
|
| 351 |
@skip_pypy3 |
| 352 |
def test_broken_call_attr(): |
| 353 |
class NotCallable: |
| 354 |
__call__ = 5 # Passes callable() but isn't really callable |
| 355 |
|
| 356 |
def __repr__(self): |
| 357 |
return "NotCallable()" |
| 358 |
|
| 359 |
class Foo: |
| 360 |
foo = NotCallable() |
| 361 |
|
| 362 |
foo = Foo() |
| 363 |
assert callable(foo.foo) |
| 364 |
expected = "╭─ <class 'tests.test_inspect.test_broken_call_attr.<locals>.Foo'> ─╮\n│ foo = NotCallable() │\n╰───────────────────────────────────────────────────────────────────╯\n" |
| 365 |
result = render(foo, methods=True, width=100) |
| 366 |
print(repr(result)) |
| 367 |
assert expected == result |
| 368 |
|
| 369 |
|
| 370 |
def test_inspect_swig_edge_case(): |
| 371 |
"""Issue #1838 - Edge case with Faiss library - object with empty dir()""" |
| 372 |
|
| 373 |
class Thing: |
| 374 |
@property |
| 375 |
def __class__(self): |
| 376 |
raise AttributeError |
| 377 |
|
| 378 |
thing = Thing() |
| 379 |
try: |
| 380 |
inspect(thing) |
| 381 |
except Exception as e: |
| 382 |
assert False, f"Object with no __class__ shouldn't raise {e}" |
| 383 |
|
| 384 |
|
| 385 |
def test_inspect_module_with_class(): |
| 386 |
def function(): |
| 387 |
pass |
| 388 |
|
| 389 |
class Thing: |
| 390 |
"""Docstring""" |
| 391 |
|
| 392 |
pass |
| 393 |
|
| 394 |
module = ModuleType("my_module") |
| 395 |
module.SomeClass = Thing |
| 396 |
module.function = function |
| 397 |
|
| 398 |
expected = ( |
| 399 |
"╭────────── <module 'my_module'> ──────────╮\n" |
| 400 |
"│ function = def function(): │\n" |
| 401 |
"│ SomeClass = class SomeClass(): Docstring │\n" |
| 402 |
"╰──────────────────────────────────────────╯\n" |
| 403 |
) |
| 404 |
assert render(module, methods=True) == expected |
| 405 |
|
| 406 |
|
| 407 |
def test_qualname_in_slots(): |
| 408 |
from functools import lru_cache |
| 409 |
|
| 410 |
@lru_cache |
| 411 |
class Klass: |
| 412 |
__slots__ = ("__qualname__",) |
| 413 |
|
| 414 |
try: |
| 415 |
inspect(Klass) |
| 416 |
except Exception as e: |
| 417 |
assert False, f"Class with __qualname__ in __slots__ shouldn't raise {e}" |
| 418 |
|
| 419 |
|
| 420 |
@pytest.mark.parametrize( |
| 421 |
"special_character,expected_replacement", |
| 422 |
( |
| 423 |
("\a", "\\a"), |
| 424 |
("\b", "\\b"), |
| 425 |
("\f", "\\f"), |
| 426 |
("\r", "\\r"), |
| 427 |
("\v", "\\v"), |
| 428 |
), |
| 429 |
) |
| 430 |
def test_can_handle_special_characters_in_docstrings( |
| 431 |
special_character: str, expected_replacement: str |
| 432 |
) -> None: |
| 433 |
class Something: |
| 434 |
class Thing: |
| 435 |
pass |
| 436 |
|
| 437 |
Something.Thing.__doc__ = f""" |
| 438 |
Multiline docstring |
| 439 |
with {special_character} should be handled |
| 440 |
""" |
| 441 |
|
| 442 |
expected = """\ |
| 443 |
╭─ <class 'tests.test_inspect.test_can_handle_sp─╮ |
| 444 |
│ class │ |
| 445 |
│ test_can_handle_special_characters_in_docstrin │ |
| 446 |
│ gs.<locals>.Something(): │ |
| 447 |
│ │ |
| 448 |
│ Thing = class Thing(): │ |
| 449 |
│ Multiline docstring │ |
| 450 |
│ with %s should be handled │ |
| 451 |
╰────────────────────────────────────────────────╯ |
| 452 |
""" % ( |
| 453 |
expected_replacement |
| 454 |
) |
| 455 |
assert render(Something, methods=True) == expected |
| 456 |
|
| 457 |
|
| 458 |
@pytest.mark.parametrize( |
| 459 |
"obj,expected_result", |
| 460 |
( |
| 461 |
[object, (object,)], |
| 462 |
[object(), (object,)], |
| 463 |
["hi", (str, object)], |
| 464 |
[str, (str, object)], |
| 465 |
[Foo(1), (Foo, object)], |
| 466 |
[Foo, (Foo, object)], |
| 467 |
[FooSubclass(1), (FooSubclass, Foo, object)], |
| 468 |
[FooSubclass, (FooSubclass, Foo, object)], |
| 469 |
), |
| 470 |
) |
| 471 |
def test_object_types_mro(obj: object, expected_result: Sequence[Type]): |
| 472 |
assert get_object_types_mro(obj) == expected_result |
| 473 |
|
| 474 |
|
| 475 |
@pytest.mark.parametrize( |
| 476 |
"obj,expected_result", |
| 477 |
( |
| 478 |
# fmt: off |
| 479 |
["hi", ["builtins.str", "builtins.object"]], |
| 480 |
[str, ["builtins.str", "builtins.object"]], |
| 481 |
[Foo(1), [f"{__name__}.Foo", "builtins.object"]], |
| 482 |
[Foo, [f"{__name__}.Foo", "builtins.object"]], |
| 483 |
[FooSubclass(1), |
| 484 |
[f"{__name__}.FooSubclass", f"{__name__}.Foo", "builtins.object"]], |
| 485 |
[FooSubclass, |
| 486 |
[f"{__name__}.FooSubclass", f"{__name__}.Foo", "builtins.object"]], |
| 487 |
# fmt: on |
| 488 |
), |
| 489 |
) |
| 490 |
def test_object_types_mro_as_strings(obj: object, expected_result: Sequence[str]): |
| 491 |
assert get_object_types_mro_as_strings(obj) == expected_result |
| 492 |
|
| 493 |
|
| 494 |
@pytest.mark.parametrize( |
| 495 |
"obj,types,expected_result", |
| 496 |
( |
| 497 |
# fmt: off |
| 498 |
["hi", ["builtins.str"], True], |
| 499 |
[str, ["builtins.str"], True], |
| 500 |
["hi", ["builtins.str", "foo"], True], |
| 501 |
[str, ["builtins.str", "foo"], True], |
| 502 |
[Foo(1), [f"{__name__}.Foo"], True], |
| 503 |
[Foo, [f"{__name__}.Foo"], True], |
| 504 |
[Foo(1), ["builtins.str", f"{__name__}.Foo"], True], |
| 505 |
[Foo, ["builtins.int", f"{__name__}.Foo"], True], |
| 506 |
[Foo(1), [f"{__name__}.FooSubclass"], False], |
| 507 |
[Foo, [f"{__name__}.FooSubclass"], False], |
| 508 |
[Foo(1), [f"{__name__}.FooSubclass", f"{__name__}.Foo"], True], |
| 509 |
[Foo, [f"{__name__}.Foo", f"{__name__}.FooSubclass"], True], |
| 510 |
# fmt: on |
| 511 |
), |
| 512 |
) |
| 513 |
def test_object_is_one_of_types( |
| 514 |
obj: object, types: Sequence[str], expected_result: bool |
| 515 |
): |
| 516 |
assert is_object_one_of_types(obj, types) is expected_result |