forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_inspect.py
4543 lines (3776 loc) · 176 KB
/
test_inspect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import builtins
import collections
import datetime
import functools
import importlib
import inspect
import io
import linecache
import os
import dis
from os.path import normcase
import _pickle
import pickle
import shutil
import sys
import types
import textwrap
import unicodedata
import unittest
import unittest.mock
import warnings
try:
from concurrent.futures import ThreadPoolExecutor
except ImportError:
ThreadPoolExecutor = None
from test.support import cpython_only
from test.support import MISSING_C_DOCSTRINGS, ALWAYS_EQ
from test.support.import_helper import DirsOnSysPath
from test.support.os_helper import TESTFN
from test.support.script_helper import assert_python_ok, assert_python_failure
from test import inspect_fodder as mod
from test import inspect_fodder2 as mod2
from test import support
from test import inspect_stock_annotations
from test import inspect_stringized_annotations
from test import inspect_stringized_annotations_2
from test.test_import import _ready_to_import
# Functions tested in this suite:
# ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
# isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers,
# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource,
# getclasstree, getargvalues, formatargvalues,
# currentframe, stack, trace, isdatadescriptor,
# ismethodwrapper
# NOTE: There are some additional tests relating to interaction with
# zipimport in the test_zipimport_support test module.
modfile = mod.__file__
if modfile.endswith(('c', 'o')):
modfile = modfile[:-1]
# Normalize file names: on Windows, the case of file names of compiled
# modules depends on the path used to start the python executable.
modfile = normcase(modfile)
def revise(filename, *args):
return (normcase(filename),) + args
git = mod.StupidGit()
def signatures_with_lexicographic_keyword_only_parameters():
"""
Yields a whole bunch of functions with only keyword-only parameters,
where those parameters are always in lexicographically sorted order.
"""
parameters = ['a', 'bar', 'c', 'delta', 'ephraim', 'magical', 'yoyo', 'z']
for i in range(1, 2**len(parameters)):
p = []
bit = 1
for j in range(len(parameters)):
if i & (bit << j):
p.append(parameters[j])
fn_text = "def foo(*, " + ", ".join(p) + "): pass"
symbols = {}
exec(fn_text, symbols, symbols)
yield symbols['foo']
def unsorted_keyword_only_parameters_fn(*, throw, out, the, baby, with_,
the_, bathwater):
pass
unsorted_keyword_only_parameters = 'throw out the baby with_ the_ bathwater'.split()
class IsTestBase(unittest.TestCase):
predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode,
inspect.isframe, inspect.isfunction, inspect.ismethod,
inspect.ismodule, inspect.istraceback,
inspect.isgenerator, inspect.isgeneratorfunction,
inspect.iscoroutine, inspect.iscoroutinefunction,
inspect.isasyncgen, inspect.isasyncgenfunction,
inspect.ismethodwrapper])
def istest(self, predicate, exp):
obj = eval(exp)
self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
for other in self.predicates - set([predicate]):
if (predicate == inspect.isgeneratorfunction or \
predicate == inspect.isasyncgenfunction or \
predicate == inspect.iscoroutinefunction) and \
other == inspect.isfunction:
continue
self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))
def test__all__(self):
support.check__all__(self, inspect, not_exported=("modulesbyfile",))
def generator_function_example(self):
for i in range(2):
yield i
async def async_generator_function_example(self):
async for i in range(2):
yield i
async def coroutine_function_example(self):
return 'spam'
@types.coroutine
def gen_coroutine_function_example(self):
yield
return 'spam'
class TestPredicates(IsTestBase):
def test_excluding_predicates(self):
global tb
self.istest(inspect.isbuiltin, 'sys.exit')
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.__code__')
try:
1/0
except Exception as e:
tb = e.__traceback__
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.istraceback, 'tb')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
finally:
# Clear traceback and all the frames and local variables hanging to it.
tb = None
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismethod, 'mod.custom_method')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
self.istest(inspect.isgenerator, '(x for x in range(2))')
self.istest(inspect.isgeneratorfunction, 'generator_function_example')
self.istest(inspect.isasyncgen,
'async_generator_function_example(1)')
self.istest(inspect.isasyncgenfunction,
'async_generator_function_example')
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.istest(inspect.iscoroutine, 'coroutine_function_example(1)')
self.istest(inspect.iscoroutinefunction, 'coroutine_function_example')
if hasattr(types, 'MemberDescriptorType'):
self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
self.istest(inspect.ismethodwrapper, "object().__str__")
self.istest(inspect.ismethodwrapper, "object().__eq__")
self.istest(inspect.ismethodwrapper, "object().__repr__")
self.assertFalse(inspect.ismethodwrapper(type))
self.assertFalse(inspect.ismethodwrapper(int))
self.assertFalse(inspect.ismethodwrapper(type("AnyClass", (), {})))
def test_iscoroutine(self):
async_gen_coro = async_generator_function_example(1)
gen_coro = gen_coroutine_function_example(1)
coro = coroutine_function_example(1)
self.assertFalse(
inspect.iscoroutinefunction(gen_coroutine_function_example))
self.assertFalse(
inspect.iscoroutinefunction(
functools.partial(functools.partial(
gen_coroutine_function_example))))
self.assertFalse(inspect.iscoroutine(gen_coro))
self.assertTrue(
inspect.isgeneratorfunction(gen_coroutine_function_example))
self.assertTrue(
inspect.isgeneratorfunction(
functools.partial(functools.partial(
gen_coroutine_function_example))))
self.assertTrue(inspect.isgenerator(gen_coro))
async def _fn3():
pass
@inspect.markcoroutinefunction
def fn3():
return _fn3()
self.assertTrue(inspect.iscoroutinefunction(fn3))
self.assertTrue(
inspect.iscoroutinefunction(
inspect.markcoroutinefunction(lambda: _fn3())
)
)
class Cl:
async def __call__(self):
pass
self.assertFalse(inspect.iscoroutinefunction(Cl))
# instances with async def __call__ are NOT recognised.
self.assertFalse(inspect.iscoroutinefunction(Cl()))
# unless explicitly marked.
self.assertTrue(inspect.iscoroutinefunction(
inspect.markcoroutinefunction(Cl())
))
class Cl2:
@inspect.markcoroutinefunction
def __call__(self):
pass
self.assertFalse(inspect.iscoroutinefunction(Cl2))
# instances with marked __call__ are NOT recognised.
self.assertFalse(inspect.iscoroutinefunction(Cl2()))
# unless explicitly marked.
self.assertTrue(inspect.iscoroutinefunction(
inspect.markcoroutinefunction(Cl2())
))
class Cl3:
@inspect.markcoroutinefunction
@classmethod
def do_something_classy(cls):
pass
@inspect.markcoroutinefunction
@staticmethod
def do_something_static():
pass
self.assertTrue(inspect.iscoroutinefunction(Cl3.do_something_classy))
self.assertTrue(inspect.iscoroutinefunction(Cl3.do_something_static))
self.assertFalse(
inspect.iscoroutinefunction(unittest.mock.Mock()))
self.assertTrue(
inspect.iscoroutinefunction(unittest.mock.AsyncMock()))
self.assertTrue(
inspect.iscoroutinefunction(coroutine_function_example))
self.assertTrue(
inspect.iscoroutinefunction(
functools.partial(functools.partial(
coroutine_function_example))))
self.assertTrue(inspect.iscoroutine(coro))
self.assertFalse(
inspect.isgeneratorfunction(unittest.mock.Mock()))
self.assertFalse(
inspect.isgeneratorfunction(unittest.mock.AsyncMock()))
self.assertFalse(
inspect.isgeneratorfunction(coroutine_function_example))
self.assertFalse(
inspect.isgeneratorfunction(
functools.partial(functools.partial(
coroutine_function_example))))
self.assertFalse(inspect.isgenerator(coro))
self.assertFalse(
inspect.isasyncgenfunction(unittest.mock.Mock()))
self.assertFalse(
inspect.isasyncgenfunction(unittest.mock.AsyncMock()))
self.assertFalse(
inspect.isasyncgenfunction(coroutine_function_example))
self.assertTrue(
inspect.isasyncgenfunction(async_generator_function_example))
self.assertTrue(
inspect.isasyncgenfunction(
functools.partial(functools.partial(
async_generator_function_example))))
self.assertTrue(inspect.isasyncgen(async_gen_coro))
coro.close(); gen_coro.close(); # silence warnings
def test_isawaitable(self):
def gen(): yield
self.assertFalse(inspect.isawaitable(gen()))
coro = coroutine_function_example(1)
gen_coro = gen_coroutine_function_example(1)
self.assertTrue(inspect.isawaitable(coro))
self.assertTrue(inspect.isawaitable(gen_coro))
class Future:
def __await__():
pass
self.assertTrue(inspect.isawaitable(Future()))
self.assertFalse(inspect.isawaitable(Future))
class NotFuture: pass
not_fut = NotFuture()
not_fut.__await__ = lambda: None
self.assertFalse(inspect.isawaitable(not_fut))
coro.close(); gen_coro.close() # silence warnings
def test_isroutine(self):
# method
self.assertTrue(inspect.isroutine(git.argue))
self.assertTrue(inspect.isroutine(mod.custom_method))
self.assertTrue(inspect.isroutine([].count))
# function
self.assertTrue(inspect.isroutine(mod.spam))
self.assertTrue(inspect.isroutine(mod.StupidGit.abuse))
# slot-wrapper
self.assertTrue(inspect.isroutine(object.__init__))
self.assertTrue(inspect.isroutine(object.__str__))
self.assertTrue(inspect.isroutine(object.__lt__))
self.assertTrue(inspect.isroutine(int.__lt__))
# method-wrapper
self.assertTrue(inspect.isroutine(object().__init__))
self.assertTrue(inspect.isroutine(object().__str__))
self.assertTrue(inspect.isroutine(object().__lt__))
self.assertTrue(inspect.isroutine((42).__lt__))
# method-descriptor
self.assertTrue(inspect.isroutine(str.join))
self.assertTrue(inspect.isroutine(list.append))
self.assertTrue(inspect.isroutine(''.join))
self.assertTrue(inspect.isroutine([].append))
# object
self.assertFalse(inspect.isroutine(object))
self.assertFalse(inspect.isroutine(object()))
self.assertFalse(inspect.isroutine(str()))
# module
self.assertFalse(inspect.isroutine(mod))
# type
self.assertFalse(inspect.isroutine(type))
self.assertFalse(inspect.isroutine(int))
self.assertFalse(inspect.isroutine(type('some_class', (), {})))
def test_isclass(self):
self.istest(inspect.isclass, 'mod.StupidGit')
self.assertTrue(inspect.isclass(list))
class CustomGetattr(object):
def __getattr__(self, attr):
return None
self.assertFalse(inspect.isclass(CustomGetattr()))
def test_get_slot_members(self):
class C(object):
__slots__ = ("a", "b")
x = C()
x.a = 42
members = dict(inspect.getmembers(x))
self.assertIn('a', members)
self.assertNotIn('b', members)
def test_isabstract(self):
from abc import ABCMeta, abstractmethod
class AbstractClassExample(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
class ClassExample(AbstractClassExample):
def foo(self):
pass
a = ClassExample()
# Test general behaviour.
self.assertTrue(inspect.isabstract(AbstractClassExample))
self.assertFalse(inspect.isabstract(ClassExample))
self.assertFalse(inspect.isabstract(a))
self.assertFalse(inspect.isabstract(int))
self.assertFalse(inspect.isabstract(5))
def test_isabstract_during_init_subclass(self):
from abc import ABCMeta, abstractmethod
isabstract_checks = []
class AbstractChecker(metaclass=ABCMeta):
def __init_subclass__(cls):
isabstract_checks.append(inspect.isabstract(cls))
class AbstractClassExample(AbstractChecker):
@abstractmethod
def foo(self):
pass
class ClassExample(AbstractClassExample):
def foo(self):
pass
self.assertEqual(isabstract_checks, [True, False])
isabstract_checks.clear()
class AbstractChild(AbstractClassExample):
pass
class AbstractGrandchild(AbstractChild):
pass
class ConcreteGrandchild(ClassExample):
pass
self.assertEqual(isabstract_checks, [True, True, False])
class TestInterpreterStack(IsTestBase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
git.abuse(7, 8, 9)
def test_abuse_done(self):
self.istest(inspect.istraceback, 'git.ex[2]')
self.istest(inspect.isframe, 'mod.fr')
def test_stack(self):
self.assertTrue(len(mod.st) >= 5)
frame1, frame2, frame3, frame4, *_ = mod.st
frameinfo = revise(*frame1[1:])
self.assertEqual(frameinfo,
(modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0))
self.assertEqual(frame1.positions, dis.Positions(16, 16, 9, 24))
frameinfo = revise(*frame2[1:])
self.assertEqual(frameinfo,
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0))
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22))
frameinfo = revise(*frame3[1:])
self.assertEqual(frameinfo,
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0))
self.assertEqual(frame3.positions, dis.Positions(43, 43, 12, 25))
frameinfo = revise(*frame4[1:])
self.assertEqual(frameinfo,
(modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0))
self.assertEqual(frame4.positions, dis.Positions(39, 39, 8, 27))
# Test named tuple fields
record = mod.st[0]
self.assertIs(record.frame, mod.fr)
self.assertEqual(record.lineno, 16)
self.assertEqual(record.filename, mod.__file__)
self.assertEqual(record.function, 'eggs')
self.assertIn('inspect.stack()', record.code_context[0])
self.assertEqual(record.index, 0)
def test_trace(self):
self.assertEqual(len(git.tr), 3)
frame1, frame2, frame3, = git.tr
self.assertEqual(revise(*frame1[1:]),
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0))
self.assertEqual(frame1.positions, dis.Positions(43, 43, 12, 25))
self.assertEqual(revise(*frame2[1:]),
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0))
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22))
self.assertEqual(revise(*frame3[1:]),
(modfile, 18, 'eggs', [' q = y / 0\n'], 0))
self.assertEqual(frame3.positions, dis.Positions(18, 18, 8, 13))
def test_frame(self):
args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
self.assertEqual(args, ['x', 'y'])
self.assertEqual(varargs, None)
self.assertEqual(varkw, None)
self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
'(x=11, y=14)')
def test_previous_frame(self):
args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f'])
self.assertEqual(varargs, 'g')
self.assertEqual(varkw, 'h')
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
'(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})')
class GetSourceBase(unittest.TestCase):
# Subclasses must override.
fodderModule = None
def setUp(self):
with open(inspect.getsourcefile(self.fodderModule), encoding="utf-8") as fp:
self.source = fp.read()
def sourcerange(self, top, bottom):
lines = self.source.split("\n")
return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "")
def assertSourceEqual(self, obj, top, bottom):
self.assertEqual(inspect.getsource(obj),
self.sourcerange(top, bottom))
class SlotUser:
'Docstrings for __slots__'
__slots__ = {'power': 'measured in kilowatts',
'distance': 'measured in kilometers'}
class TestRetrievingSourceCode(GetSourceBase):
fodderModule = mod
def test_getclasses(self):
classes = inspect.getmembers(mod, inspect.isclass)
self.assertEqual(classes,
[('FesteringGob', mod.FesteringGob),
('MalodorousPervert', mod.MalodorousPervert),
('ParrotDroppings', mod.ParrotDroppings),
('StupidGit', mod.StupidGit),
('Tit', mod.MalodorousPervert),
('WhichComments', mod.WhichComments),
])
tree = inspect.getclasstree([cls[1] for cls in classes])
self.assertEqual(tree,
[(object, ()),
[(mod.ParrotDroppings, (object,)),
[(mod.FesteringGob, (mod.MalodorousPervert,
mod.ParrotDroppings))
],
(mod.StupidGit, (object,)),
[(mod.MalodorousPervert, (mod.StupidGit,)),
[(mod.FesteringGob, (mod.MalodorousPervert,
mod.ParrotDroppings))
]
],
(mod.WhichComments, (object,),)
]
])
tree = inspect.getclasstree([cls[1] for cls in classes], True)
self.assertEqual(tree,
[(object, ()),
[(mod.ParrotDroppings, (object,)),
(mod.StupidGit, (object,)),
[(mod.MalodorousPervert, (mod.StupidGit,)),
[(mod.FesteringGob, (mod.MalodorousPervert,
mod.ParrotDroppings))
]
],
(mod.WhichComments, (object,),)
]
])
def test_getfunctions(self):
functions = inspect.getmembers(mod, inspect.isfunction)
self.assertEqual(functions, [('eggs', mod.eggs),
('lobbest', mod.lobbest),
('spam', mod.spam)])
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_getdoc(self):
self.assertEqual(inspect.getdoc(mod), 'A module docstring.')
self.assertEqual(inspect.getdoc(mod.StupidGit),
'A longer,\n\nindented\n\ndocstring.')
self.assertEqual(inspect.getdoc(git.abuse),
'Another\n\ndocstring\n\ncontaining\n\ntabs')
self.assertEqual(inspect.getdoc(SlotUser.power),
'measured in kilowatts')
self.assertEqual(inspect.getdoc(SlotUser.distance),
'measured in kilometers')
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_getdoc_inherited(self):
self.assertEqual(inspect.getdoc(mod.FesteringGob),
'A longer,\n\nindented\n\ndocstring.')
self.assertEqual(inspect.getdoc(mod.FesteringGob.abuse),
'Another\n\ndocstring\n\ncontaining\n\ntabs')
self.assertEqual(inspect.getdoc(mod.FesteringGob().abuse),
'Another\n\ndocstring\n\ncontaining\n\ntabs')
self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction),
'The automatic gainsaying.')
@unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings")
def test_finddoc(self):
finddoc = inspect._finddoc
self.assertEqual(finddoc(int), int.__doc__)
self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__)
self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__)
self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__)
self.assertEqual(finddoc(int.real), int.real.__doc__)
def test_cleandoc(self):
self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'),
'An\nindented\ndocstring.')
def test_getcomments(self):
self.assertEqual(inspect.getcomments(mod), '# line 1\n')
self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n')
self.assertEqual(inspect.getcomments(mod2.cls160), '# line 159\n')
# If the object source file is not available, return None.
co = compile('x=1', '_non_existing_filename.py', 'exec')
self.assertIsNone(inspect.getcomments(co))
# If the object has been defined in C, return None.
self.assertIsNone(inspect.getcomments(list))
def test_getmodule(self):
# Check actual module
self.assertEqual(inspect.getmodule(mod), mod)
# Check class (uses __module__ attribute)
self.assertEqual(inspect.getmodule(mod.StupidGit), mod)
# Check a method (no __module__ attribute, falls back to filename)
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
# Do it again (check the caching isn't broken)
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
# Check a builtin
self.assertEqual(inspect.getmodule(str), sys.modules["builtins"])
# Check filename override
self.assertEqual(inspect.getmodule(None, modfile), mod)
def test_getmodule_file_not_found(self):
# See bpo-45406
def _getabsfile(obj, _filename):
raise FileNotFoundError('bad file')
with unittest.mock.patch('inspect.getabsfile', _getabsfile):
f = inspect.currentframe()
self.assertIsNone(inspect.getmodule(f))
inspect.getouterframes(f) # smoke test
def test_getframeinfo_get_first_line(self):
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50)
self.assertEqual(frame_info.code_context[0], "# line 1\n")
self.assertEqual(frame_info.code_context[1], "'A module docstring.'\n")
def test_getsource(self):
self.assertSourceEqual(git.abuse, 29, 39)
self.assertSourceEqual(mod.StupidGit, 21, 51)
self.assertSourceEqual(mod.lobbest, 75, 76)
def test_getsourcefile(self):
self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile)
self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile)
fn = "_non_existing_filename_used_for_sourcefile_test.py"
co = compile("x=1", fn, "exec")
self.assertEqual(inspect.getsourcefile(co), None)
linecache.cache[co.co_filename] = (1, None, "None", co.co_filename)
try:
self.assertEqual(normcase(inspect.getsourcefile(co)), fn)
finally:
del linecache.cache[co.co_filename]
def test_getfile(self):
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
def test_getfile_builtin_module(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(sys)
self.assertTrue(str(e.exception).startswith('<module'))
def test_getfile_builtin_class(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(int)
self.assertTrue(str(e.exception).startswith('<class'))
def test_getfile_builtin_function_or_method(self):
with self.assertRaises(TypeError) as e_abs:
inspect.getfile(abs)
self.assertIn('expected, got', str(e_abs.exception))
with self.assertRaises(TypeError) as e_append:
inspect.getfile(list.append)
self.assertIn('expected, got', str(e_append.exception))
def test_getfile_class_without_module(self):
class CM(type):
@property
def __module__(cls):
raise AttributeError
class C(metaclass=CM):
pass
with self.assertRaises(TypeError):
inspect.getfile(C)
def test_getfile_broken_repr(self):
class ErrorRepr:
def __repr__(self):
raise Exception('xyz')
er = ErrorRepr()
with self.assertRaises(TypeError):
inspect.getfile(er)
def test_getmodule_recursion(self):
from types import ModuleType
name = '__inspect_dummy'
m = sys.modules[name] = ModuleType(name)
m.__file__ = "<string>" # hopefully not a real filename...
m.__loader__ = "dummy" # pretend the filename is understood by a loader
exec("def x(): pass", m.__dict__)
self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>')
del sys.modules[name]
inspect.getmodule(compile('a=10','','single'))
def test_proceed_with_fake_filename(self):
'''doctest monkeypatches linecache to enable inspection'''
fn, source = '<test>', 'def x(): pass\n'
getlines = linecache.getlines
def monkey(filename, module_globals=None):
if filename == fn:
return source.splitlines(keepends=True)
else:
return getlines(filename, module_globals)
linecache.getlines = monkey
try:
ns = {}
exec(compile(source, fn, 'single'), ns)
inspect.getsource(ns["x"])
finally:
linecache.getlines = getlines
def test_getsource_on_code_object(self):
self.assertSourceEqual(mod.eggs.__code__, 12, 18)
class TestGetsourceInteractive(unittest.TestCase):
def test_getclasses_interactive(self):
# bpo-44648: simulate a REPL session;
# there is no `__file__` in the __main__ module
code = "import sys, inspect; \
assert not hasattr(sys.modules['__main__'], '__file__'); \
A = type('A', (), {}); \
inspect.getsource(A)"
_, _, stderr = assert_python_failure("-c", code, __isolated=True)
self.assertIn(b'OSError: source code not available', stderr)
class TestGettingSourceOfToplevelFrames(GetSourceBase):
fodderModule = mod
def test_range_toplevel_frame(self):
self.maxDiff = None
self.assertSourceEqual(mod.currentframe, 1, None)
def test_range_traceback_toplevel_frame(self):
self.assertSourceEqual(mod.tb, 1, None)
class TestDecorators(GetSourceBase):
fodderModule = mod2
def test_wrapped_decorator(self):
self.assertSourceEqual(mod2.wrapped, 14, 17)
def test_replacing_decorator(self):
self.assertSourceEqual(mod2.gone, 9, 10)
def test_getsource_unwrap(self):
self.assertSourceEqual(mod2.real, 130, 132)
def test_decorator_with_lambda(self):
self.assertSourceEqual(mod2.func114, 113, 115)
class TestOneliners(GetSourceBase):
fodderModule = mod2
def test_oneline_lambda(self):
# Test inspect.getsource with a one-line lambda function.
self.assertSourceEqual(mod2.oll, 25, 25)
def test_threeline_lambda(self):
# Test inspect.getsource with a three-line lambda function,
# where the second and third lines are _not_ indented.
self.assertSourceEqual(mod2.tll, 28, 30)
def test_twoline_indented_lambda(self):
# Test inspect.getsource with a two-line lambda function,
# where the second line _is_ indented.
self.assertSourceEqual(mod2.tlli, 33, 34)
def test_onelinefunc(self):
# Test inspect.getsource with a regular one-line function.
self.assertSourceEqual(mod2.onelinefunc, 37, 37)
def test_manyargs(self):
# Test inspect.getsource with a regular function where
# the arguments are on two lines and _not_ indented and
# the body on the second line with the last arguments.
self.assertSourceEqual(mod2.manyargs, 40, 41)
def test_twolinefunc(self):
# Test inspect.getsource with a regular function where
# the body is on two lines, following the argument list and
# continued on the next line by a \\.
self.assertSourceEqual(mod2.twolinefunc, 44, 45)
def test_lambda_in_list(self):
# Test inspect.getsource with a one-line lambda function
# defined in a list, indented.
self.assertSourceEqual(mod2.a[1], 49, 49)
def test_anonymous(self):
# Test inspect.getsource with a lambda function defined
# as argument to another function.
self.assertSourceEqual(mod2.anonymous, 55, 55)
class TestBlockComments(GetSourceBase):
fodderModule = mod
def test_toplevel_class(self):
self.assertSourceEqual(mod.WhichComments, 96, 114)
def test_class_method(self):
self.assertSourceEqual(mod.WhichComments.f, 99, 104)
def test_class_async_method(self):
self.assertSourceEqual(mod.WhichComments.asyncf, 109, 112)
class TestBuggyCases(GetSourceBase):
fodderModule = mod2
def test_with_comment(self):
self.assertSourceEqual(mod2.with_comment, 58, 59)
def test_multiline_sig(self):
self.assertSourceEqual(mod2.multiline_sig[0], 63, 64)
def test_nested_class(self):
self.assertSourceEqual(mod2.func69().func71, 71, 72)
def test_one_liner_followed_by_non_name(self):
self.assertSourceEqual(mod2.func77, 77, 77)
def test_one_liner_dedent_non_name(self):
self.assertSourceEqual(mod2.cls82.func83, 83, 83)
def test_with_comment_instead_of_docstring(self):
self.assertSourceEqual(mod2.func88, 88, 90)
def test_method_in_dynamic_class(self):
self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
# This should not skip for CPython, but might on a repackaged python where
# unicodedata is not an external module, or on pypy.
@unittest.skipIf(not hasattr(unicodedata, '__file__') or
unicodedata.__file__.endswith('.py'),
"unicodedata is not an external binary module")
def test_findsource_binary(self):
self.assertRaises(OSError, inspect.getsource, unicodedata)
self.assertRaises(OSError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(OSError, inspect.findsource, co)
self.assertRaises(OSError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
try:
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
finally:
del linecache.cache[co.co_filename]
def test_findsource_without_filename(self):
for fname in ['', '<string>']:
co = compile('x=1', fname, "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
def test_findsource_with_out_of_bounds_lineno(self):
mod_len = len(inspect.getsource(mod))
src = '\n' * 2* mod_len + "def f(): pass"
co = compile(src, mod.__file__, "exec")
g, l = {}, {}
eval(co, g, l)
func = l['f']
self.assertEqual(func.__code__.co_firstlineno, 1+2*mod_len)
with self.assertRaisesRegex(IOError, "lineno is out of bounds"):
inspect.findsource(func)
def test_getsource_on_method(self):
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119)
def test_nested_func(self):
self.assertSourceEqual(mod2.cls135.func136, 136, 139)
def test_class_definition_in_multiline_string_definition(self):
self.assertSourceEqual(mod2.cls149, 149, 152)
def test_class_definition_in_multiline_comment(self):
self.assertSourceEqual(mod2.cls160, 160, 163)
def test_nested_class_definition_indented_string(self):
self.assertSourceEqual(mod2.cls173.cls175, 175, 176)
def test_nested_class_definition(self):
self.assertSourceEqual(mod2.cls183, 183, 188)
self.assertSourceEqual(mod2.cls183.cls185, 185, 188)
def test_class_decorator(self):
self.assertSourceEqual(mod2.cls196, 194, 201)
self.assertSourceEqual(mod2.cls196.cls200, 198, 201)
def test_class_inside_conditional(self):
self.assertSourceEqual(mod2.cls238, 238, 240)
self.assertSourceEqual(mod2.cls238.cls239, 239, 240)
def test_multiple_children_classes(self):
self.assertSourceEqual(mod2.cls203, 203, 209)
self.assertSourceEqual(mod2.cls203.cls204, 204, 206)
self.assertSourceEqual(mod2.cls203.cls204.cls205, 205, 206)
self.assertSourceEqual(mod2.cls203.cls207, 207, 209)
self.assertSourceEqual(mod2.cls203.cls207.cls205, 208, 209)
def test_nested_class_definition_inside_function(self):
self.assertSourceEqual(mod2.func212(), 213, 214)
self.assertSourceEqual(mod2.cls213, 218, 222)
self.assertSourceEqual(mod2.cls213().func219(), 220, 221)
@unittest.skipIf(
support.is_emscripten or support.is_wasi,
"socket.accept is broken"
)
def test_nested_class_definition_inside_async_function(self):
import asyncio
self.addCleanup(asyncio.set_event_loop_policy, None)
self.assertSourceEqual(asyncio.run(mod2.func225()), 226, 227)
self.assertSourceEqual(mod2.cls226, 231, 235)
self.assertSourceEqual(asyncio.run(mod2.cls226().func232()), 233, 234)
class TestNoEOL(GetSourceBase):
def setUp(self):
self.tempdir = TESTFN + '_dir'
os.mkdir(self.tempdir)
with open(os.path.join(self.tempdir, 'inspect_fodder3%spy' % os.extsep),
'w', encoding='utf-8') as f:
f.write("class X:\n pass # No EOL")
with DirsOnSysPath(self.tempdir):
import inspect_fodder3 as mod3
self.fodderModule = mod3
super().setUp()
def tearDown(self):
shutil.rmtree(self.tempdir)
def test_class(self):
self.assertSourceEqual(self.fodderModule.X, 1, 2)
class TestComplexDecorator(GetSourceBase):
fodderModule = mod2
def test_parens_in_decorator(self):
self.assertSourceEqual(self.fodderModule.complex_decorated, 273, 275)
class _BrokenDataDescriptor(object):
"""
A broken data descriptor. See bug #1785.
"""
def __get__(*args):
raise AttributeError("broken data descriptor")
def __set__(*args):
raise RuntimeError
def __getattr__(*args):
raise AttributeError("broken data descriptor")
class _BrokenMethodDescriptor(object):
"""
A broken method descriptor. See bug #1785.
"""
def __get__(*args):
raise AttributeError("broken method descriptor")
def __getattr__(*args):
raise AttributeError("broken method descriptor")
# Helper for testing classify_class_attrs.
def attrs_wo_objs(cls):
return [t[:3] for t in inspect.classify_class_attrs(cls)]
class TestClassesAndFunctions(unittest.TestCase):
def test_newstyle_mro(self):
# The same w/ new-class MRO.
class A(object): pass
class B(A): pass
class C(A): pass
class D(B, C): pass
expected = (D, B, C, A, object)
got = inspect.getmro(D)
self.assertEqual(expected, got)
def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None,
varkw_e=None, defaults_e=None,
posonlyargs_e=[], kwonlyargs_e=[],
kwonlydefaults_e=None,
ann_e={}):
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
inspect.getfullargspec(routine)
self.assertEqual(args, args_e)
self.assertEqual(varargs, varargs_e)
self.assertEqual(varkw, varkw_e)
self.assertEqual(defaults, defaults_e)