Debian Codegraph @

tests/test_oinspect.py

raw
1 from contextlib import contextmanager
2 from inspect import signature, Signature, Parameter
3 import inspect
4 import os
5 import pytest
6 import re
7 import sys
8
9 from IPython.core import oinspect
10
11 from decorator import decorator
12
13 from IPython.testing.tools import AssertPrints, AssertNotPrints
14 from IPython.utils.path import compress_user
15
16
17 # -----------------------------------------------------------------------------
18 # Globals and constants
19 # -----------------------------------------------------------------------------
20
21 inspector = None
22
23
24 def setup_module():
25 global inspector
26 inspector = oinspect.Inspector(theme_name="nocolor")
27
28
29 class SourceModuleMainTest:
30 __module__ = "__main__"
31
32
33 # -----------------------------------------------------------------------------
34 # Local utilities
35 # -----------------------------------------------------------------------------
36
37 # WARNING: since this test checks the line number where a function is
38 # defined, if any code is inserted above, the following line will need to be
39 # updated. Do NOT insert any whitespace between the next line and the function
40 # definition below.
41 THIS_LINE_NUMBER = 41 # Put here the actual number of this line
42
43
44 def test_find_source_lines():
45 assert oinspect.find_source_lines(test_find_source_lines) == THIS_LINE_NUMBER + 3
46 assert oinspect.find_source_lines(type) is None
47 assert oinspect.find_source_lines(SourceModuleMainTest) is None
48 assert oinspect.find_source_lines(SourceModuleMainTest()) is None
49
50
51 def test_getsource():
52 assert oinspect.getsource(type) is None
53 assert oinspect.getsource(SourceModuleMainTest) is None
54 assert oinspect.getsource(SourceModuleMainTest()) is None
55
56
57 def test_inspect_getfile_raises_exception():
58 """Check oinspect.find_file/getsource/find_source_lines expectations"""
59 with pytest.raises(TypeError):
60 inspect.getfile(type)
61 with pytest.raises(OSError):
62 inspect.getfile(SourceModuleMainTest)
63
64
65 # A couple of utilities to ensure these tests work the same from a source or a
66 # binary install
67 def pyfile(fname):
68 return os.path.normcase(re.sub(".py[co]$", ".py", fname))
69
70
71 def match_pyfiles(f1, f2):
72 assert pyfile(f1) == pyfile(f2)
73
74
75 def test_find_file():
76 match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__))
77 assert oinspect.find_file(type) is None
78 assert oinspect.find_file(SourceModuleMainTest) is None
79 assert oinspect.find_file(SourceModuleMainTest()) is None
80
81
82 def test_find_file_decorated1():
83 @decorator
84 def noop1(f):
85 def wrapper(*a, **kw):
86 return f(*a, **kw)
87
88 return wrapper
89
90 @noop1
91 def f(x):
92 "My docstring"
93
94 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
95 assert f.__doc__ == "My docstring"
96
97
98 def test_find_file_decorated2():
99 @decorator
100 def noop2(f, *a, **kw):
101 return f(*a, **kw)
102
103 @noop2
104 @noop2
105 @noop2
106 def f(x):
107 "My docstring 2"
108
109 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
110 assert f.__doc__ == "My docstring 2"
111
112
113 def test_find_file_magic():
114 run = ip.find_line_magic("run")
115 assert oinspect.find_file(run) is not None
116
117
118 # A few generic objects we can then inspect in the tests below
119
120
121 class Call(object):
122 """This is the class docstring."""
123
124 def __init__(self, x, y=1):
125 """This is the constructor docstring."""
126
127 def __call__(self, *a, **kw):
128 """This is the call docstring."""
129
130 def method(self, x, z=2):
131 """Some method's docstring"""
132
133
134 class HasSignature(object):
135 """This is the class docstring."""
136
137 __signature__ = Signature([Parameter("test", Parameter.POSITIONAL_OR_KEYWORD)])
138
139 def __init__(self, *args):
140 """This is the init docstring"""
141
142
143 class SimpleClass(object):
144 def method(self, x, z=2):
145 """Some method's docstring"""
146
147
148 class Awkward(object):
149 def __getattr__(self, name):
150 raise Exception(name)
151
152
153 class NoBoolCall:
154 """
155 callable with `__bool__` raising should still be inspect-able.
156 """
157
158 def __call__(self):
159 """does nothing"""
160 pass
161
162 def __bool__(self):
163 """just raise NotImplemented"""
164 raise NotImplementedError("Must be implemented")
165
166
167 class SerialLiar(object):
168 """Attribute accesses always get another copy of the same class.
169
170 unittest.mock.call does something similar, but it's not ideal for testing
171 as the failure mode is to eat all your RAM. This gives up after 10k levels.
172 """
173
174 def __init__(self, max_fibbing_twig, lies_told=0):
175 if lies_told > 10000:
176 raise RuntimeError("Nose too long, honesty is the best policy")
177 self.max_fibbing_twig = max_fibbing_twig
178 self.lies_told = lies_told
179 max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told)
180
181 def __getattr__(self, item):
182 return SerialLiar(self.max_fibbing_twig, self.lies_told + 1)
183
184
185 # -----------------------------------------------------------------------------
186 # Tests
187 # -----------------------------------------------------------------------------
188
189
190 def test_info():
191 "Check that Inspector.info fills out various fields as expected."
192 i = inspector.info(Call, oname="Call")
193 assert i["type_name"] == "type"
194 expected_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
195 assert i["base_class"] == expected_class
196 assert re.search(
197 "<class 'tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>",
198 i["string_form"],
199 )
200 fname = __file__
201 if fname.endswith(".pyc"):
202 fname = fname[:-1]
203 # case-insensitive comparison needed on some filesystems
204 # e.g. Windows:
205 assert i["file"].lower() == compress_user(fname).lower()
206 assert i["definition"] == None
207 assert i["docstring"] == Call.__doc__
208 assert i["source"] == None
209 assert i["isclass"] is True
210 assert i["init_definition"] == "Call(x, y=1)"
211 assert i["init_docstring"] == Call.__init__.__doc__
212
213 i = inspector.info(Call, detail_level=1)
214 assert i["source"] is not None
215 assert i["docstring"] == None
216
217 c = Call(1)
218 c.__doc__ = "Modified instance docstring"
219 i = inspector.info(c)
220 assert i["type_name"] == "Call"
221 assert i["docstring"] == "Modified instance docstring"
222 assert i["class_docstring"] == Call.__doc__
223 assert i["init_docstring"] == Call.__init__.__doc__
224 assert i["call_docstring"] == Call.__call__.__doc__
225
226
227 def test_class_signature():
228 info = inspector.info(HasSignature, "HasSignature")
229 assert info["init_definition"] == "HasSignature(test)"
230 assert info["init_docstring"] == HasSignature.__init__.__doc__
231
232
233 def test_info_awkward():
234 # Just test that this doesn't throw an error.
235 inspector.info(Awkward())
236
237
238 def test_bool_raise():
239 inspector.info(NoBoolCall())
240
241
242 def test_info_serialliar():
243 fib_tracker = [0]
244 inspector.info(SerialLiar(fib_tracker))
245
246 # Nested attribute access should be cut off at 100 levels deep to avoid
247 # infinite loops: https://github.com/ipython/ipython/issues/9122
248 assert fib_tracker[0] < 9000
249
250
251 def support_function_one(x, y=2, *a, **kw):
252 """A simple function."""
253
254
255 def test_calldef_none():
256 # We should ignore __call__ for all of these.
257 for obj in [support_function_one, SimpleClass().method, any, str.upper]:
258 i = inspector.info(obj)
259 assert i["call_def"] is None
260
261
262 def f_kwarg(pos, *, kwonly):
263 pass
264
265
266 def test_definition_kwonlyargs():
267 i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore
268 assert i["definition"] == "f_kwarg(pos, *, kwonly)"
269
270
271 def test_getdoc():
272 class A(object):
273 """standard docstring"""
274
275 pass
276
277 class B(object):
278 """standard docstring"""
279
280 def getdoc(self):
281 return "custom docstring"
282
283 class C(object):
284 """standard docstring"""
285
286 def getdoc(self):
287 return None
288
289 a = A()
290 b = B()
291 c = C()
292
293 assert oinspect.getdoc(a) == "standard docstring"
294 assert oinspect.getdoc(b) == "custom docstring"
295 assert oinspect.getdoc(c) == "standard docstring"
296
297
298 def test_empty_property_has_no_source():
299 i = inspector.info(property(), detail_level=1)
300 assert i["source"] is None
301
302
303 def test_property_sources():
304 # A simple adder whose source and signature stays
305 # the same across Python distributions
306 def simple_add(a, b):
307 "Adds two numbers"
308 return a + b
309
310 class A(object):
311 @property
312 def foo(self):
313 return "bar"
314
315 foo = foo.setter(lambda self, v: setattr(self, "bar", v))
316
317 dname = property(oinspect.getdoc)
318 adder = property(simple_add)
319
320 i = inspector.info(A.foo, detail_level=1)
321 assert "def foo(self):" in i["source"]
322 assert "lambda self, v:" in i["source"]
323
324 i = inspector.info(A.dname, detail_level=1)
325 assert "def getdoc(obj)" in i["source"]
326
327 i = inspector.info(A.adder, detail_level=1)
328 assert "def simple_add(a, b)" in i["source"]
329
330
331 def test_property_docstring_is_in_info_for_detail_level_0():
332 class A(object):
333 @property
334 def foobar(self):
335 """This is `foobar` property."""
336 pass
337
338 ip.user_ns["a_obj"] = A()
339 assert (
340 "This is `foobar` property."
341 == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"]
342 )
343
344 ip.user_ns["a_cls"] = A
345 assert (
346 "This is `foobar` property."
347 == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"]
348 )
349
350
351 def test_pdef():
352 # See gh-1914
353 def foo():
354 pass
355
356 inspector.pdef(foo, "foo")
357
358
359 @contextmanager
360 def cleanup_user_ns(**kwargs):
361 """
362 On exit delete all the keys that were not in user_ns before entering.
363
364 It does not restore old values !
365
366 Parameters
367 ----------
368
369 **kwargs
370 used to update ip.user_ns
371
372 """
373 try:
374 known = set(ip.user_ns.keys())
375 ip.user_ns.update(kwargs)
376 yield
377 finally:
378 added = set(ip.user_ns.keys()) - known
379 for k in added:
380 del ip.user_ns[k]
381
382
383 def test_pinfo_bool_raise():
384 """
385 Test that bool method is not called on parent.
386 """
387
388 class RaiseBool:
389 attr = None
390
391 def __bool__(self):
392 raise ValueError("pinfo should not access this method")
393
394 raise_bool = RaiseBool()
395
396 with cleanup_user_ns(raise_bool=raise_bool):
397 ip._inspect("pinfo", "raise_bool.attr", detail_level=0)
398
399
400 def test_pinfo_getindex():
401 def dummy():
402 """
403 MARKER
404 """
405
406 container = [dummy]
407 with cleanup_user_ns(container=container):
408 with AssertPrints("MARKER"):
409 ip._inspect("pinfo", "container[0]", detail_level=0)
410 assert "container" not in ip.user_ns.keys()
411
412
413 def test_qmark_getindex():
414 def dummy():
415 """
416 MARKER 2
417 """
418
419 container = [dummy]
420 with cleanup_user_ns(container=container):
421 with AssertPrints("MARKER 2"):
422 ip.run_cell("container[0]?")
423 assert "container" not in ip.user_ns.keys()
424
425
426 def test_qmark_getindex_negatif():
427 def dummy():
428 """
429 MARKER 3
430 """
431
432 container = [dummy]
433 with cleanup_user_ns(container=container):
434 with AssertPrints("MARKER 3"):
435 ip.run_cell("container[-1]?")
436 assert "container" not in ip.user_ns.keys()
437
438
439 def test_pinfo_nonascii():
440 # See gh-1177
441 from . import nonascii2
442
443 ip.user_ns["nonascii2"] = nonascii2
444 ip._inspect("pinfo", "nonascii2", detail_level=1)
445
446
447 def test_pinfo_type():
448 """
449 type can fail in various edge case, for example `type.__subclass__()`
450 """
451 ip._inspect("pinfo", "type")
452
453
454 def test_pinfo_docstring_no_source():
455 """Docstring should be included with detail_level=1 if there is no source"""
456 with AssertPrints("Docstring:"):
457 ip._inspect("pinfo", "str.format", detail_level=0)
458 with AssertPrints("Docstring:"):
459 ip._inspect("pinfo", "str.format", detail_level=1)
460
461
462 def test_pinfo_no_docstring_if_source():
463 """Docstring should not be included with detail_level=1 if source is found"""
464
465 def foo():
466 """foo has a docstring"""
467
468 ip.user_ns["foo"] = foo
469
470 with AssertPrints("Docstring:"):
471 ip._inspect("pinfo", "foo", detail_level=0)
472 with AssertPrints("Source:"):
473 ip._inspect("pinfo", "foo", detail_level=1)
474 with AssertNotPrints("Docstring:"):
475 ip._inspect("pinfo", "foo", detail_level=1)
476
477
478 def test_pinfo_docstring_if_detail_and_no_source():
479 """Docstring should be displayed if source info not available"""
480 obj_def = '''class Foo(object):
481 """ This is a docstring for Foo """
482 def bar(self):
483 """ This is a docstring for Foo.bar """
484 pass
485 '''
486
487 ip.run_cell(obj_def)
488 ip.run_cell("foo = Foo()")
489
490 with AssertNotPrints("Source:"):
491 with AssertPrints("Docstring:"):
492 ip._inspect("pinfo", "foo", detail_level=0)
493 with AssertPrints("Docstring:"):
494 ip._inspect("pinfo", "foo", detail_level=1)
495 with AssertPrints("Docstring:"):
496 ip._inspect("pinfo", "foo.bar", detail_level=0)
497
498 with AssertNotPrints("Docstring:"):
499 with AssertPrints("Source:"):
500 ip._inspect("pinfo", "foo.bar", detail_level=1)
501
502
503 @pytest.mark.xfail(
504 sys.version_info.releaselevel not in ("final", "candidate"),
505 reason="fails on 3.13.dev",
506 strict=(sys.version_info < (3, 15)),
507 )
508 def test_pinfo_docstring_dynamic(capsys):
509 obj_def = """class Bar:
510 __custom_documentations__ = {
511 "prop" : "cdoc for prop",
512 "non_exist" : "cdoc for non_exist",
513 }
514 @property
515 def prop(self):
516 '''
517 Docstring for prop
518 '''
519 return self._prop
520
521 @prop.setter
522 def prop(self, v):
523 self._prop = v
524 """
525 ip.run_cell(obj_def)
526
527 ip.run_cell("b = Bar()")
528
529 ip.run_line_magic("pinfo", "b.prop")
530 captured = capsys.readouterr()
531 assert re.search(r"Docstring:\s+cdoc for prop", captured.out)
532
533 ip.run_line_magic("pinfo", "b.non_exist")
534 captured = capsys.readouterr()
535 assert re.search(r"Docstring:\s+cdoc for non_exist", captured.out)
536
537 ip.run_cell("b.prop?")
538 captured = capsys.readouterr()
539 assert re.search(r"Docstring:\s+cdoc for prop", captured.out)
540
541 ip.run_cell("b.non_exist?")
542 captured = capsys.readouterr()
543 assert re.search(r"Docstring:\s+cdoc for non_exist", captured.out)
544
545 ip.run_cell("b.undefined?")
546 captured = capsys.readouterr()
547 assert re.search(r"Type:\s+NoneType", captured.out)
548
549
550 def test_pinfo_magic():
551 with AssertPrints("Docstring:"):
552 ip._inspect("pinfo", "lsmagic", detail_level=0)
553
554 with AssertPrints("Source:"):
555 ip._inspect("pinfo", "lsmagic", detail_level=1)
556
557
558 def test_init_colors():
559 # ensure colors are not present in signature info
560 info = inspector.info(HasSignature)
561 init_def = info["init_definition"]
562 assert "[0m" not in init_def
563
564
565 def test_builtin_init():
566 info = inspector.info(list)
567 init_def = info["init_definition"]
568 assert init_def is not None
569
570
571 def test_render_signature_short():
572 def short_fun(a=1):
573 pass
574
575 sig = oinspect._render_signature(
576 signature(short_fun),
577 short_fun.__name__,
578 )
579 assert sig == "short_fun(a=1)"
580
581
582 def test_render_signature_long():
583 from typing import Optional
584
585 def long_function(
586 a_really_long_parameter: int,
587 and_another_long_one: bool = False,
588 let_us_make_sure_this_is_looong: Optional[str] = None,
589 ) -> bool:
590 pass
591
592 sig = oinspect._render_signature(
593 signature(long_function),
594 long_function.__name__,
595 )
596 expected = """\
597 long_function(
598 a_really_long_parameter: int,
599 and_another_long_one: bool = False,
600 let_us_make_sure_this_is_looong: Optional[str] = None,
601 ) -> bool\
602 """
603 if sys.version_info >= (3, 14):
604 expected = expected.replace("Optional[str]", "str | None")
605
606 assert sig == expected