Debian Codegraph @

tests/test_inspect.py

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