|
1 import sys |
|
2 import types |
|
3 import unittest |
|
4 import inspect |
|
5 import datetime |
|
6 |
|
7 from test.test_support import TESTFN, run_unittest |
|
8 |
|
9 from test import inspect_fodder as mod |
|
10 from test import inspect_fodder2 as mod2 |
|
11 |
|
12 # Functions tested in this suite: |
|
13 # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, |
|
14 # isbuiltin, isroutine, getmembers, getdoc, getfile, getmodule, |
|
15 # getsourcefile, getcomments, getsource, getclasstree, getargspec, |
|
16 # getargvalues, formatargspec, formatargvalues, currentframe, stack, trace |
|
17 # isdatadescriptor |
|
18 |
|
19 modfile = mod.__file__ |
|
20 if modfile.endswith(('c', 'o')): |
|
21 modfile = modfile[:-1] |
|
22 |
|
23 import __builtin__ |
|
24 |
|
25 try: |
|
26 1/0 |
|
27 except: |
|
28 tb = sys.exc_traceback |
|
29 |
|
30 git = mod.StupidGit() |
|
31 |
|
32 class IsTestBase(unittest.TestCase): |
|
33 predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, |
|
34 inspect.isframe, inspect.isfunction, inspect.ismethod, |
|
35 inspect.ismodule, inspect.istraceback]) |
|
36 |
|
37 def istest(self, predicate, exp): |
|
38 obj = eval(exp) |
|
39 self.failUnless(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) |
|
40 |
|
41 for other in self.predicates - set([predicate]): |
|
42 self.failIf(other(obj), 'not %s(%s)' % (other.__name__, exp)) |
|
43 |
|
44 class TestPredicates(IsTestBase): |
|
45 def test_thirteen(self): |
|
46 count = len(filter(lambda x:x.startswith('is'), dir(inspect))) |
|
47 # Doc/lib/libinspect.tex claims there are 13 such functions |
|
48 expected = 13 |
|
49 err_msg = "There are %d (not %d) is* functions" % (count, expected) |
|
50 self.assertEqual(count, expected, err_msg) |
|
51 |
|
52 def test_excluding_predicates(self): |
|
53 self.istest(inspect.isbuiltin, 'sys.exit') |
|
54 self.istest(inspect.isbuiltin, '[].append') |
|
55 self.istest(inspect.isclass, 'mod.StupidGit') |
|
56 self.istest(inspect.iscode, 'mod.spam.func_code') |
|
57 self.istest(inspect.isframe, 'tb.tb_frame') |
|
58 self.istest(inspect.isfunction, 'mod.spam') |
|
59 self.istest(inspect.ismethod, 'mod.StupidGit.abuse') |
|
60 self.istest(inspect.ismethod, 'git.argue') |
|
61 self.istest(inspect.ismodule, 'mod') |
|
62 self.istest(inspect.istraceback, 'tb') |
|
63 self.istest(inspect.isdatadescriptor, '__builtin__.file.closed') |
|
64 self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace') |
|
65 if hasattr(types, 'GetSetDescriptorType'): |
|
66 self.istest(inspect.isgetsetdescriptor, |
|
67 'type(tb.tb_frame).f_locals') |
|
68 else: |
|
69 self.failIf(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) |
|
70 if hasattr(types, 'MemberDescriptorType'): |
|
71 self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') |
|
72 else: |
|
73 self.failIf(inspect.ismemberdescriptor(datetime.timedelta.days)) |
|
74 |
|
75 def test_isroutine(self): |
|
76 self.assert_(inspect.isroutine(mod.spam)) |
|
77 self.assert_(inspect.isroutine([].count)) |
|
78 |
|
79 class TestInterpreterStack(IsTestBase): |
|
80 def __init__(self, *args, **kwargs): |
|
81 unittest.TestCase.__init__(self, *args, **kwargs) |
|
82 |
|
83 git.abuse(7, 8, 9) |
|
84 |
|
85 def test_abuse_done(self): |
|
86 self.istest(inspect.istraceback, 'git.ex[2]') |
|
87 self.istest(inspect.isframe, 'mod.fr') |
|
88 |
|
89 def test_stack(self): |
|
90 self.assert_(len(mod.st) >= 5) |
|
91 self.assertEqual(mod.st[0][1:], |
|
92 (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) |
|
93 self.assertEqual(mod.st[1][1:], |
|
94 (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
|
95 self.assertEqual(mod.st[2][1:], |
|
96 (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
|
97 self.assertEqual(mod.st[3][1:], |
|
98 (modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0)) |
|
99 |
|
100 def test_trace(self): |
|
101 self.assertEqual(len(git.tr), 3) |
|
102 self.assertEqual(git.tr[0][1:], (modfile, 43, 'argue', |
|
103 [' spam(a, b, c)\n'], 0)) |
|
104 self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam', |
|
105 [' eggs(b + d, c + f)\n'], 0)) |
|
106 self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs', |
|
107 [' q = y / 0\n'], 0)) |
|
108 |
|
109 def test_frame(self): |
|
110 args, varargs, varkw, locals = inspect.getargvalues(mod.fr) |
|
111 self.assertEqual(args, ['x', 'y']) |
|
112 self.assertEqual(varargs, None) |
|
113 self.assertEqual(varkw, None) |
|
114 self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14}) |
|
115 self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
|
116 '(x=11, y=14)') |
|
117 |
|
118 def test_previous_frame(self): |
|
119 args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) |
|
120 self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]]) |
|
121 self.assertEqual(varargs, 'g') |
|
122 self.assertEqual(varkw, 'h') |
|
123 self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
|
124 '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})') |
|
125 |
|
126 class GetSourceBase(unittest.TestCase): |
|
127 # Subclasses must override. |
|
128 fodderFile = None |
|
129 |
|
130 def __init__(self, *args, **kwargs): |
|
131 unittest.TestCase.__init__(self, *args, **kwargs) |
|
132 |
|
133 self.source = file(inspect.getsourcefile(self.fodderFile)).read() |
|
134 |
|
135 def sourcerange(self, top, bottom): |
|
136 lines = self.source.split("\n") |
|
137 return "\n".join(lines[top-1:bottom]) + "\n" |
|
138 |
|
139 def assertSourceEqual(self, obj, top, bottom): |
|
140 self.assertEqual(inspect.getsource(obj), |
|
141 self.sourcerange(top, bottom)) |
|
142 |
|
143 class TestRetrievingSourceCode(GetSourceBase): |
|
144 fodderFile = mod |
|
145 |
|
146 def test_getclasses(self): |
|
147 classes = inspect.getmembers(mod, inspect.isclass) |
|
148 self.assertEqual(classes, |
|
149 [('FesteringGob', mod.FesteringGob), |
|
150 ('MalodorousPervert', mod.MalodorousPervert), |
|
151 ('ParrotDroppings', mod.ParrotDroppings), |
|
152 ('StupidGit', mod.StupidGit)]) |
|
153 tree = inspect.getclasstree([cls[1] for cls in classes], 1) |
|
154 self.assertEqual(tree, |
|
155 [(mod.ParrotDroppings, ()), |
|
156 (mod.StupidGit, ()), |
|
157 [(mod.MalodorousPervert, (mod.StupidGit,)), |
|
158 [(mod.FesteringGob, (mod.MalodorousPervert, |
|
159 mod.ParrotDroppings)) |
|
160 ] |
|
161 ] |
|
162 ]) |
|
163 |
|
164 def test_getfunctions(self): |
|
165 functions = inspect.getmembers(mod, inspect.isfunction) |
|
166 self.assertEqual(functions, [('eggs', mod.eggs), |
|
167 ('spam', mod.spam)]) |
|
168 |
|
169 def test_getdoc(self): |
|
170 self.assertEqual(inspect.getdoc(mod), 'A module docstring.') |
|
171 self.assertEqual(inspect.getdoc(mod.StupidGit), |
|
172 'A longer,\n\nindented\n\ndocstring.') |
|
173 self.assertEqual(inspect.getdoc(git.abuse), |
|
174 'Another\n\ndocstring\n\ncontaining\n\ntabs') |
|
175 |
|
176 def test_getcomments(self): |
|
177 self.assertEqual(inspect.getcomments(mod), '# line 1\n') |
|
178 self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') |
|
179 |
|
180 def test_getmodule(self): |
|
181 # Check actual module |
|
182 self.assertEqual(inspect.getmodule(mod), mod) |
|
183 # Check class (uses __module__ attribute) |
|
184 self.assertEqual(inspect.getmodule(mod.StupidGit), mod) |
|
185 # Check a method (no __module__ attribute, falls back to filename) |
|
186 self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
|
187 # Do it again (check the caching isn't broken) |
|
188 self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
|
189 # Check a builtin |
|
190 self.assertEqual(inspect.getmodule(str), sys.modules["__builtin__"]) |
|
191 # Check filename override |
|
192 self.assertEqual(inspect.getmodule(None, modfile), mod) |
|
193 |
|
194 def test_getsource(self): |
|
195 self.assertSourceEqual(git.abuse, 29, 39) |
|
196 self.assertSourceEqual(mod.StupidGit, 21, 46) |
|
197 |
|
198 def test_getsourcefile(self): |
|
199 self.assertEqual(inspect.getsourcefile(mod.spam), modfile) |
|
200 self.assertEqual(inspect.getsourcefile(git.abuse), modfile) |
|
201 |
|
202 def test_getfile(self): |
|
203 self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) |
|
204 |
|
205 def test_getmodule_recursion(self): |
|
206 from new import module |
|
207 name = '__inspect_dummy' |
|
208 m = sys.modules[name] = module(name) |
|
209 m.__file__ = "<string>" # hopefully not a real filename... |
|
210 m.__loader__ = "dummy" # pretend the filename is understood by a loader |
|
211 exec "def x(): pass" in m.__dict__ |
|
212 self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>') |
|
213 del sys.modules[name] |
|
214 inspect.getmodule(compile('a=10','','single')) |
|
215 |
|
216 class TestDecorators(GetSourceBase): |
|
217 fodderFile = mod2 |
|
218 |
|
219 def test_wrapped_decorator(self): |
|
220 self.assertSourceEqual(mod2.wrapped, 14, 17) |
|
221 |
|
222 def test_replacing_decorator(self): |
|
223 self.assertSourceEqual(mod2.gone, 9, 10) |
|
224 |
|
225 class TestOneliners(GetSourceBase): |
|
226 fodderFile = mod2 |
|
227 def test_oneline_lambda(self): |
|
228 # Test inspect.getsource with a one-line lambda function. |
|
229 self.assertSourceEqual(mod2.oll, 25, 25) |
|
230 |
|
231 def test_threeline_lambda(self): |
|
232 # Test inspect.getsource with a three-line lambda function, |
|
233 # where the second and third lines are _not_ indented. |
|
234 self.assertSourceEqual(mod2.tll, 28, 30) |
|
235 |
|
236 def test_twoline_indented_lambda(self): |
|
237 # Test inspect.getsource with a two-line lambda function, |
|
238 # where the second line _is_ indented. |
|
239 self.assertSourceEqual(mod2.tlli, 33, 34) |
|
240 |
|
241 def test_onelinefunc(self): |
|
242 # Test inspect.getsource with a regular one-line function. |
|
243 self.assertSourceEqual(mod2.onelinefunc, 37, 37) |
|
244 |
|
245 def test_manyargs(self): |
|
246 # Test inspect.getsource with a regular function where |
|
247 # the arguments are on two lines and _not_ indented and |
|
248 # the body on the second line with the last arguments. |
|
249 self.assertSourceEqual(mod2.manyargs, 40, 41) |
|
250 |
|
251 def test_twolinefunc(self): |
|
252 # Test inspect.getsource with a regular function where |
|
253 # the body is on two lines, following the argument list and |
|
254 # continued on the next line by a \\. |
|
255 self.assertSourceEqual(mod2.twolinefunc, 44, 45) |
|
256 |
|
257 def test_lambda_in_list(self): |
|
258 # Test inspect.getsource with a one-line lambda function |
|
259 # defined in a list, indented. |
|
260 self.assertSourceEqual(mod2.a[1], 49, 49) |
|
261 |
|
262 def test_anonymous(self): |
|
263 # Test inspect.getsource with a lambda function defined |
|
264 # as argument to another function. |
|
265 self.assertSourceEqual(mod2.anonymous, 55, 55) |
|
266 |
|
267 class TestBuggyCases(GetSourceBase): |
|
268 fodderFile = mod2 |
|
269 |
|
270 def test_with_comment(self): |
|
271 self.assertSourceEqual(mod2.with_comment, 58, 59) |
|
272 |
|
273 def test_multiline_sig(self): |
|
274 self.assertSourceEqual(mod2.multiline_sig[0], 63, 64) |
|
275 |
|
276 def test_nested_class(self): |
|
277 self.assertSourceEqual(mod2.func69().func71, 71, 72) |
|
278 |
|
279 def test_one_liner_followed_by_non_name(self): |
|
280 self.assertSourceEqual(mod2.func77, 77, 77) |
|
281 |
|
282 def test_one_liner_dedent_non_name(self): |
|
283 self.assertSourceEqual(mod2.cls82.func83, 83, 83) |
|
284 |
|
285 def test_with_comment_instead_of_docstring(self): |
|
286 self.assertSourceEqual(mod2.func88, 88, 90) |
|
287 |
|
288 def test_method_in_dynamic_class(self): |
|
289 self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97) |
|
290 |
|
291 # Helper for testing classify_class_attrs. |
|
292 def attrs_wo_objs(cls): |
|
293 return [t[:3] for t in inspect.classify_class_attrs(cls)] |
|
294 |
|
295 class TestClassesAndFunctions(unittest.TestCase): |
|
296 def test_classic_mro(self): |
|
297 # Test classic-class method resolution order. |
|
298 class A: pass |
|
299 class B(A): pass |
|
300 class C(A): pass |
|
301 class D(B, C): pass |
|
302 |
|
303 expected = (D, B, A, C) |
|
304 got = inspect.getmro(D) |
|
305 self.assertEqual(expected, got) |
|
306 |
|
307 def test_newstyle_mro(self): |
|
308 # The same w/ new-class MRO. |
|
309 class A(object): pass |
|
310 class B(A): pass |
|
311 class C(A): pass |
|
312 class D(B, C): pass |
|
313 |
|
314 expected = (D, B, C, A, object) |
|
315 got = inspect.getmro(D) |
|
316 self.assertEqual(expected, got) |
|
317 |
|
318 def assertArgSpecEquals(self, routine, args_e, varargs_e = None, |
|
319 varkw_e = None, defaults_e = None, |
|
320 formatted = None): |
|
321 args, varargs, varkw, defaults = inspect.getargspec(routine) |
|
322 self.assertEqual(args, args_e) |
|
323 self.assertEqual(varargs, varargs_e) |
|
324 self.assertEqual(varkw, varkw_e) |
|
325 self.assertEqual(defaults, defaults_e) |
|
326 if formatted is not None: |
|
327 self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults), |
|
328 formatted) |
|
329 |
|
330 def test_getargspec(self): |
|
331 self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)') |
|
332 |
|
333 self.assertArgSpecEquals(mod.spam, |
|
334 ['a', 'b', 'c', 'd', ['e', ['f']]], |
|
335 'g', 'h', (3, (4, (5,))), |
|
336 '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)') |
|
337 |
|
338 def test_getargspec_method(self): |
|
339 class A(object): |
|
340 def m(self): |
|
341 pass |
|
342 self.assertArgSpecEquals(A.m, ['self']) |
|
343 |
|
344 def test_getargspec_sublistofone(self): |
|
345 def sublistOfOne((foo,)): return 1 |
|
346 self.assertArgSpecEquals(sublistOfOne, [['foo']]) |
|
347 |
|
348 def fakeSublistOfOne((foo)): return 1 |
|
349 self.assertArgSpecEquals(fakeSublistOfOne, ['foo']) |
|
350 |
|
351 def test_classify_oldstyle(self): |
|
352 class A: |
|
353 def s(): pass |
|
354 s = staticmethod(s) |
|
355 |
|
356 def c(cls): pass |
|
357 c = classmethod(c) |
|
358 |
|
359 def getp(self): pass |
|
360 p = property(getp) |
|
361 |
|
362 def m(self): pass |
|
363 |
|
364 def m1(self): pass |
|
365 |
|
366 datablob = '1' |
|
367 |
|
368 attrs = attrs_wo_objs(A) |
|
369 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
370 self.assert_(('c', 'class method', A) in attrs, 'missing class method') |
|
371 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
372 self.assert_(('m', 'method', A) in attrs, 'missing plain method') |
|
373 self.assert_(('m1', 'method', A) in attrs, 'missing plain method') |
|
374 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
375 |
|
376 class B(A): |
|
377 def m(self): pass |
|
378 |
|
379 attrs = attrs_wo_objs(B) |
|
380 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
381 self.assert_(('c', 'class method', A) in attrs, 'missing class method') |
|
382 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
383 self.assert_(('m', 'method', B) in attrs, 'missing plain method') |
|
384 self.assert_(('m1', 'method', A) in attrs, 'missing plain method') |
|
385 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
386 |
|
387 |
|
388 class C(A): |
|
389 def m(self): pass |
|
390 def c(self): pass |
|
391 |
|
392 attrs = attrs_wo_objs(C) |
|
393 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
394 self.assert_(('c', 'method', C) in attrs, 'missing plain method') |
|
395 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
396 self.assert_(('m', 'method', C) in attrs, 'missing plain method') |
|
397 self.assert_(('m1', 'method', A) in attrs, 'missing plain method') |
|
398 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
399 |
|
400 class D(B, C): |
|
401 def m1(self): pass |
|
402 |
|
403 attrs = attrs_wo_objs(D) |
|
404 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
405 self.assert_(('c', 'class method', A) in attrs, 'missing class method') |
|
406 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
407 self.assert_(('m', 'method', B) in attrs, 'missing plain method') |
|
408 self.assert_(('m1', 'method', D) in attrs, 'missing plain method') |
|
409 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
410 |
|
411 # Repeat all that, but w/ new-style classes. |
|
412 def test_classify_newstyle(self): |
|
413 class A(object): |
|
414 |
|
415 def s(): pass |
|
416 s = staticmethod(s) |
|
417 |
|
418 def c(cls): pass |
|
419 c = classmethod(c) |
|
420 |
|
421 def getp(self): pass |
|
422 p = property(getp) |
|
423 |
|
424 def m(self): pass |
|
425 |
|
426 def m1(self): pass |
|
427 |
|
428 datablob = '1' |
|
429 |
|
430 attrs = attrs_wo_objs(A) |
|
431 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
432 self.assert_(('c', 'class method', A) in attrs, 'missing class method') |
|
433 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
434 self.assert_(('m', 'method', A) in attrs, 'missing plain method') |
|
435 self.assert_(('m1', 'method', A) in attrs, 'missing plain method') |
|
436 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
437 |
|
438 class B(A): |
|
439 |
|
440 def m(self): pass |
|
441 |
|
442 attrs = attrs_wo_objs(B) |
|
443 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
444 self.assert_(('c', 'class method', A) in attrs, 'missing class method') |
|
445 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
446 self.assert_(('m', 'method', B) in attrs, 'missing plain method') |
|
447 self.assert_(('m1', 'method', A) in attrs, 'missing plain method') |
|
448 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
449 |
|
450 |
|
451 class C(A): |
|
452 |
|
453 def m(self): pass |
|
454 def c(self): pass |
|
455 |
|
456 attrs = attrs_wo_objs(C) |
|
457 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
458 self.assert_(('c', 'method', C) in attrs, 'missing plain method') |
|
459 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
460 self.assert_(('m', 'method', C) in attrs, 'missing plain method') |
|
461 self.assert_(('m1', 'method', A) in attrs, 'missing plain method') |
|
462 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
463 |
|
464 class D(B, C): |
|
465 |
|
466 def m1(self): pass |
|
467 |
|
468 attrs = attrs_wo_objs(D) |
|
469 self.assert_(('s', 'static method', A) in attrs, 'missing static method') |
|
470 self.assert_(('c', 'method', C) in attrs, 'missing plain method') |
|
471 self.assert_(('p', 'property', A) in attrs, 'missing property') |
|
472 self.assert_(('m', 'method', B) in attrs, 'missing plain method') |
|
473 self.assert_(('m1', 'method', D) in attrs, 'missing plain method') |
|
474 self.assert_(('datablob', 'data', A) in attrs, 'missing data') |
|
475 |
|
476 def test_main(): |
|
477 run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners, |
|
478 TestBuggyCases, |
|
479 TestInterpreterStack, TestClassesAndFunctions, TestPredicates) |
|
480 |
|
481 if __name__ == "__main__": |
|
482 test_main() |