blob: e607af2de9c284c1ba0939ea35fcc662a4da4883 [file] [log] [blame]
Johannes Gijsberscb9015d2004-12-12 16:20:22 +00001import sys
Barry Warsaw00decd72006-07-27 23:43:15 +00002import types
Johannes Gijsberscb9015d2004-12-12 16:20:22 +00003import unittest
4import inspect
Barry Warsaw00decd72006-07-27 23:43:15 +00005import datetime
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00006
Georg Brandla4f46e12010-02-07 17:03:15 +00007from test.test_support import run_unittest
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00008
Senthil Kumarance8e33a2010-01-08 19:04:16 +00009from test import inspect_fodder as mod
10from test import inspect_fodder2 as mod2
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000011
R. David Murray996ba022009-05-13 17:14:11 +000012# C module for test_findsource_binary
R. David Murray87855542009-05-14 16:12:57 +000013import unicodedata
R. David Murray996ba022009-05-13 17:14:11 +000014
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000015# Functions tested in this suite:
16# ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
Facundo Batista759bfc62008-02-18 03:43:43 +000017# isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers,
18# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource,
19# getclasstree, getargspec, getargvalues, formatargspec, formatargvalues,
20# currentframe, stack, trace, isdatadescriptor
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000021
Nick Coghlana2053472008-12-14 10:54:50 +000022# NOTE: There are some additional tests relating to interaction with
23# zipimport in the test_zipimport_support test module.
24
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000025modfile = mod.__file__
Georg Brandlb2afe852006-06-09 20:43:48 +000026if modfile.endswith(('c', 'o')):
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000027 modfile = modfile[:-1]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000028
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000029import __builtin__
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000030
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000031try:
Senthil Kumarance8e33a2010-01-08 19:04:16 +000032 1/0
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000033except:
34 tb = sys.exc_traceback
35
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000036git = mod.StupidGit()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000037
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000038class IsTestBase(unittest.TestCase):
39 predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode,
40 inspect.isframe, inspect.isfunction, inspect.ismethod,
Facundo Batista759bfc62008-02-18 03:43:43 +000041 inspect.ismodule, inspect.istraceback,
42 inspect.isgenerator, inspect.isgeneratorfunction])
Tim Peters5a9fb3c2005-01-07 16:01:32 +000043
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000044 def istest(self, predicate, exp):
45 obj = eval(exp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000046 self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
Tim Peters5a9fb3c2005-01-07 16:01:32 +000047
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000048 for other in self.predicates - set([predicate]):
Facundo Batista759bfc62008-02-18 03:43:43 +000049 if predicate == inspect.isgeneratorfunction and\
50 other == inspect.isfunction:
51 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +000052 self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000053
Facundo Batista759bfc62008-02-18 03:43:43 +000054def generator_function_example(self):
55 for i in xrange(2):
56 yield i
57
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000058class TestPredicates(IsTestBase):
Christian Heimes728bee82008-03-03 20:30:29 +000059 def test_sixteen(self):
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000060 count = len(filter(lambda x:x.startswith('is'), dir(inspect)))
Facundo Batista759bfc62008-02-18 03:43:43 +000061 # This test is here for remember you to update Doc/library/inspect.rst
Georg Brandl26bc1772008-03-03 20:39:00 +000062 # which claims there are 16 such functions
Christian Heimes728bee82008-03-03 20:30:29 +000063 expected = 16
Neal Norwitzdf80af72006-07-28 04:22:34 +000064 err_msg = "There are %d (not %d) is* functions" % (count, expected)
65 self.assertEqual(count, expected, err_msg)
Tim Peters5a9fb3c2005-01-07 16:01:32 +000066
Facundo Batista759bfc62008-02-18 03:43:43 +000067
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000068 def test_excluding_predicates(self):
69 self.istest(inspect.isbuiltin, 'sys.exit')
70 self.istest(inspect.isbuiltin, '[].append')
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000071 self.istest(inspect.iscode, 'mod.spam.func_code')
72 self.istest(inspect.isframe, 'tb.tb_frame')
73 self.istest(inspect.isfunction, 'mod.spam')
74 self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
75 self.istest(inspect.ismethod, 'git.argue')
76 self.istest(inspect.ismodule, 'mod')
77 self.istest(inspect.istraceback, 'tb')
78 self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
79 self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
Facundo Batista759bfc62008-02-18 03:43:43 +000080 self.istest(inspect.isgenerator, '(x for x in xrange(2))')
81 self.istest(inspect.isgeneratorfunction, 'generator_function_example')
Barry Warsaw00decd72006-07-27 23:43:15 +000082 if hasattr(types, 'GetSetDescriptorType'):
83 self.istest(inspect.isgetsetdescriptor,
84 'type(tb.tb_frame).f_locals')
85 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000086 self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
Barry Warsaw00decd72006-07-27 23:43:15 +000087 if hasattr(types, 'MemberDescriptorType'):
88 self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
89 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000090 self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000091
Johannes Gijsberscb9015d2004-12-12 16:20:22 +000092 def test_isroutine(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000093 self.assertTrue(inspect.isroutine(mod.spam))
94 self.assertTrue(inspect.isroutine([].count))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000095
Benjamin Peterson5e5fbb62009-01-17 22:27:54 +000096 def test_isclass(self):
97 self.istest(inspect.isclass, 'mod.StupidGit')
98 self.assertTrue(inspect.isclass(list))
99
100 class newstyle(object): pass
101 self.assertTrue(inspect.isclass(newstyle))
102
103 class CustomGetattr(object):
104 def __getattr__(self, attr):
105 return None
106 self.assertFalse(inspect.isclass(CustomGetattr()))
107
Amaury Forgeot d'Arcb54447f2009-01-13 23:39:22 +0000108 def test_get_slot_members(self):
109 class C(object):
110 __slots__ = ("a", "b")
111
112 x = C()
113 x.a = 42
114 members = dict(inspect.getmembers(x))
Ezio Melottiaa980582010-01-23 23:04:36 +0000115 self.assertIn('a', members)
116 self.assertNotIn('b', members)
Amaury Forgeot d'Arcb54447f2009-01-13 23:39:22 +0000117
Benjamin Petersonc63457b2009-10-15 03:06:55 +0000118 def test_isabstract(self):
119 from abc import ABCMeta, abstractmethod
120
121 class AbstractClassExample(object):
122 __metaclass__ = ABCMeta
123
124 @abstractmethod
125 def foo(self):
126 pass
127
128 class ClassExample(AbstractClassExample):
129 def foo(self):
130 pass
131
132 a = ClassExample()
133
134 # Test general behaviour.
135 self.assertTrue(inspect.isabstract(AbstractClassExample))
136 self.assertFalse(inspect.isabstract(ClassExample))
137 self.assertFalse(inspect.isabstract(a))
138 self.assertFalse(inspect.isabstract(int))
139 self.assertFalse(inspect.isabstract(5))
140
Amaury Forgeot d'Arcb54447f2009-01-13 23:39:22 +0000141
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000142class TestInterpreterStack(IsTestBase):
143 def __init__(self, *args, **kwargs):
144 unittest.TestCase.__init__(self, *args, **kwargs)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000145
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000146 git.abuse(7, 8, 9)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000147
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000148 def test_abuse_done(self):
149 self.istest(inspect.istraceback, 'git.ex[2]')
150 self.istest(inspect.isframe, 'mod.fr')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000151
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000152 def test_stack(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000153 self.assertTrue(len(mod.st) >= 5)
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000154 self.assertEqual(mod.st[0][1:],
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000155 (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0))
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000156 self.assertEqual(mod.st[1][1:],
157 (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0))
158 self.assertEqual(mod.st[2][1:],
159 (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0))
160 self.assertEqual(mod.st[3][1:],
161 (modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000162
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000163 def test_trace(self):
164 self.assertEqual(len(git.tr), 3)
165 self.assertEqual(git.tr[0][1:], (modfile, 43, 'argue',
166 [' spam(a, b, c)\n'], 0))
167 self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam',
168 [' eggs(b + d, c + f)\n'], 0))
169 self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs',
Mark Dickinsonc68e9f02010-02-03 16:50:14 +0000170 [' q = y // 0\n'], 0))
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000171
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000172 def test_frame(self):
173 args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
174 self.assertEqual(args, ['x', 'y'])
175 self.assertEqual(varargs, None)
176 self.assertEqual(varkw, None)
177 self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
178 self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
179 '(x=11, y=14)')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000180
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000181 def test_previous_frame(self):
182 args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
183 self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
184 self.assertEqual(varargs, 'g')
185 self.assertEqual(varkw, 'h')
186 self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
187 '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000188
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000189class GetSourceBase(unittest.TestCase):
190 # Subclasses must override.
191 fodderFile = None
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000192
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000193 def __init__(self, *args, **kwargs):
194 unittest.TestCase.__init__(self, *args, **kwargs)
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000195
Philip Jenvey6a111022009-05-28 05:58:44 +0000196 with open(inspect.getsourcefile(self.fodderFile)) as fp:
197 self.source = fp.read()
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000198
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000199 def sourcerange(self, top, bottom):
200 lines = self.source.split("\n")
201 return "\n".join(lines[top-1:bottom]) + "\n"
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000202
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000203 def assertSourceEqual(self, obj, top, bottom):
204 self.assertEqual(inspect.getsource(obj),
205 self.sourcerange(top, bottom))
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000206
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000207class TestRetrievingSourceCode(GetSourceBase):
208 fodderFile = mod
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000209
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000210 def test_getclasses(self):
211 classes = inspect.getmembers(mod, inspect.isclass)
212 self.assertEqual(classes,
213 [('FesteringGob', mod.FesteringGob),
214 ('MalodorousPervert', mod.MalodorousPervert),
215 ('ParrotDroppings', mod.ParrotDroppings),
216 ('StupidGit', mod.StupidGit)])
217 tree = inspect.getclasstree([cls[1] for cls in classes], 1)
218 self.assertEqual(tree,
219 [(mod.ParrotDroppings, ()),
220 (mod.StupidGit, ()),
221 [(mod.MalodorousPervert, (mod.StupidGit,)),
222 [(mod.FesteringGob, (mod.MalodorousPervert,
223 mod.ParrotDroppings))
224 ]
225 ]
226 ])
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000227
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000228 def test_getfunctions(self):
229 functions = inspect.getmembers(mod, inspect.isfunction)
230 self.assertEqual(functions, [('eggs', mod.eggs),
231 ('spam', mod.spam)])
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000232
R. David Murrayf28fd242010-02-23 00:24:49 +0000233 @unittest.skipIf(sys.flags.optimize >= 2,
234 "Docstrings are omitted with -O2 and above")
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000235 def test_getdoc(self):
236 self.assertEqual(inspect.getdoc(mod), 'A module docstring.')
237 self.assertEqual(inspect.getdoc(mod.StupidGit),
238 'A longer,\n\nindented\n\ndocstring.')
239 self.assertEqual(inspect.getdoc(git.abuse),
240 'Another\n\ndocstring\n\ncontaining\n\ntabs')
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000241
Georg Brandl7be19aa2008-06-07 15:59:10 +0000242 def test_cleandoc(self):
243 self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'),
244 'An\nindented\ndocstring.')
245
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000246 def test_getcomments(self):
247 self.assertEqual(inspect.getcomments(mod), '# line 1\n')
248 self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n')
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000249
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000250 def test_getmodule(self):
Nick Coghlanc495c662006-09-07 10:50:34 +0000251 # Check actual module
252 self.assertEqual(inspect.getmodule(mod), mod)
253 # Check class (uses __module__ attribute)
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000254 self.assertEqual(inspect.getmodule(mod.StupidGit), mod)
Nick Coghlanc495c662006-09-07 10:50:34 +0000255 # Check a method (no __module__ attribute, falls back to filename)
256 self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
257 # Do it again (check the caching isn't broken)
258 self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
259 # Check a builtin
260 self.assertEqual(inspect.getmodule(str), sys.modules["__builtin__"])
261 # Check filename override
262 self.assertEqual(inspect.getmodule(None, modfile), mod)
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000263
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000264 def test_getsource(self):
265 self.assertSourceEqual(git.abuse, 29, 39)
266 self.assertSourceEqual(mod.StupidGit, 21, 46)
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000267
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000268 def test_getsourcefile(self):
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000269 self.assertEqual(inspect.getsourcefile(mod.spam), modfile)
270 self.assertEqual(inspect.getsourcefile(git.abuse), modfile)
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000271
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000272 def test_getfile(self):
273 self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000274
Phillip J. Eby5d86bdb2006-07-10 19:03:29 +0000275 def test_getmodule_recursion(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000276 from types import ModuleType
Phillip J. Eby5d86bdb2006-07-10 19:03:29 +0000277 name = '__inspect_dummy'
Christian Heimesc756d002007-11-27 21:34:01 +0000278 m = sys.modules[name] = ModuleType(name)
Tim Peters722b8832006-07-10 21:11:49 +0000279 m.__file__ = "<string>" # hopefully not a real filename...
Phillip J. Eby5d86bdb2006-07-10 19:03:29 +0000280 m.__loader__ = "dummy" # pretend the filename is understood by a loader
281 exec "def x(): pass" in m.__dict__
282 self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
283 del sys.modules[name]
Phillip J. Eby1a2959c2006-07-20 15:54:16 +0000284 inspect.getmodule(compile('a=10','','single'))
Phillip J. Eby5d86bdb2006-07-10 19:03:29 +0000285
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000286class TestDecorators(GetSourceBase):
287 fodderFile = mod2
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000288
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000289 def test_wrapped_decorator(self):
290 self.assertSourceEqual(mod2.wrapped, 14, 17)
Johannes Gijsbersc473c992004-08-18 12:40:31 +0000291
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000292 def test_replacing_decorator(self):
293 self.assertSourceEqual(mod2.gone, 9, 10)
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000294
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000295class TestOneliners(GetSourceBase):
296 fodderFile = mod2
297 def test_oneline_lambda(self):
298 # Test inspect.getsource with a one-line lambda function.
299 self.assertSourceEqual(mod2.oll, 25, 25)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000300
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000301 def test_threeline_lambda(self):
302 # Test inspect.getsource with a three-line lambda function,
303 # where the second and third lines are _not_ indented.
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000304 self.assertSourceEqual(mod2.tll, 28, 30)
305
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000306 def test_twoline_indented_lambda(self):
307 # Test inspect.getsource with a two-line lambda function,
308 # where the second line _is_ indented.
309 self.assertSourceEqual(mod2.tlli, 33, 34)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000310
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000311 def test_onelinefunc(self):
312 # Test inspect.getsource with a regular one-line function.
313 self.assertSourceEqual(mod2.onelinefunc, 37, 37)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000314
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000315 def test_manyargs(self):
316 # Test inspect.getsource with a regular function where
317 # the arguments are on two lines and _not_ indented and
318 # the body on the second line with the last arguments.
319 self.assertSourceEqual(mod2.manyargs, 40, 41)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000320
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000321 def test_twolinefunc(self):
322 # Test inspect.getsource with a regular function where
323 # the body is on two lines, following the argument list and
324 # continued on the next line by a \\.
325 self.assertSourceEqual(mod2.twolinefunc, 44, 45)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000326
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000327 def test_lambda_in_list(self):
328 # Test inspect.getsource with a one-line lambda function
329 # defined in a list, indented.
330 self.assertSourceEqual(mod2.a[1], 49, 49)
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000331
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000332 def test_anonymous(self):
333 # Test inspect.getsource with a lambda function defined
334 # as argument to another function.
335 self.assertSourceEqual(mod2.anonymous, 55, 55)
336
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000337class TestBuggyCases(GetSourceBase):
338 fodderFile = mod2
339
340 def test_with_comment(self):
341 self.assertSourceEqual(mod2.with_comment, 58, 59)
342
343 def test_multiline_sig(self):
344 self.assertSourceEqual(mod2.multiline_sig[0], 63, 64)
345
Armin Rigodd5c0232005-09-25 11:45:45 +0000346 def test_nested_class(self):
347 self.assertSourceEqual(mod2.func69().func71, 71, 72)
348
349 def test_one_liner_followed_by_non_name(self):
350 self.assertSourceEqual(mod2.func77, 77, 77)
351
352 def test_one_liner_dedent_non_name(self):
353 self.assertSourceEqual(mod2.cls82.func83, 83, 83)
354
355 def test_with_comment_instead_of_docstring(self):
356 self.assertSourceEqual(mod2.func88, 88, 90)
357
Georg Brandl2463f8f2006-08-14 21:34:08 +0000358 def test_method_in_dynamic_class(self):
359 self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
360
R. David Murray87855542009-05-14 16:12:57 +0000361 @unittest.skipIf(
362 not hasattr(unicodedata, '__file__') or
363 unicodedata.__file__[-4:] in (".pyc", ".pyo"),
364 "unicodedata is not an external binary module")
R. David Murray996ba022009-05-13 17:14:11 +0000365 def test_findsource_binary(self):
R. David Murray87855542009-05-14 16:12:57 +0000366 self.assertRaises(IOError, inspect.getsource, unicodedata)
367 self.assertRaises(IOError, inspect.findsource, unicodedata)
R. David Murray996ba022009-05-13 17:14:11 +0000368
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000369# Helper for testing classify_class_attrs.
Tim Peters13b49d32001-09-23 02:00:29 +0000370def attrs_wo_objs(cls):
371 return [t[:3] for t in inspect.classify_class_attrs(cls)]
372
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000373class TestClassesAndFunctions(unittest.TestCase):
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000374 def test_classic_mro(self):
375 # Test classic-class method resolution order.
376 class A: pass
377 class B(A): pass
378 class C(A): pass
379 class D(B, C): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000380
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000381 expected = (D, B, A, C)
382 got = inspect.getmro(D)
383 self.assertEqual(expected, got)
Tim Peters13b49d32001-09-23 02:00:29 +0000384
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000385 def test_newstyle_mro(self):
386 # The same w/ new-class MRO.
387 class A(object): pass
388 class B(A): pass
389 class C(A): pass
390 class D(B, C): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000391
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000392 expected = (D, B, C, A, object)
393 got = inspect.getmro(D)
394 self.assertEqual(expected, got)
Tim Peters13b49d32001-09-23 02:00:29 +0000395
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000396 def assertArgSpecEquals(self, routine, args_e, varargs_e = None,
397 varkw_e = None, defaults_e = None,
398 formatted = None):
399 args, varargs, varkw, defaults = inspect.getargspec(routine)
400 self.assertEqual(args, args_e)
401 self.assertEqual(varargs, varargs_e)
402 self.assertEqual(varkw, varkw_e)
403 self.assertEqual(defaults, defaults_e)
404 if formatted is not None:
405 self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults),
406 formatted)
Tim Peters13b49d32001-09-23 02:00:29 +0000407
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000408 def test_getargspec(self):
409 self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)')
Tim Peters13b49d32001-09-23 02:00:29 +0000410
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000411 self.assertArgSpecEquals(mod.spam,
412 ['a', 'b', 'c', 'd', ['e', ['f']]],
413 'g', 'h', (3, (4, (5,))),
414 '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
Tim Peters13b49d32001-09-23 02:00:29 +0000415
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000416 def test_getargspec_method(self):
417 class A(object):
418 def m(self):
419 pass
420 self.assertArgSpecEquals(A.m, ['self'])
Tim Peters13b49d32001-09-23 02:00:29 +0000421
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000422 def test_getargspec_sublistofone(self):
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000423 def sublistOfOne((foo,)): return 1
424 self.assertArgSpecEquals(sublistOfOne, [['foo']])
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000425
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000426 def fakeSublistOfOne((foo)): return 1
427 self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
Neal Norwitz33b730e2006-03-27 08:58:23 +0000428
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000429 def test_classify_oldstyle(self):
430 class A:
431 def s(): pass
432 s = staticmethod(s)
433
434 def c(cls): pass
435 c = classmethod(c)
436
437 def getp(self): pass
438 p = property(getp)
439
440 def m(self): pass
441
442 def m1(self): pass
443
444 datablob = '1'
445
446 attrs = attrs_wo_objs(A)
Ezio Melottiaa980582010-01-23 23:04:36 +0000447 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
448 self.assertIn(('c', 'class method', A), attrs, 'missing class method')
449 self.assertIn(('p', 'property', A), attrs, 'missing property')
450 self.assertIn(('m', 'method', A), attrs, 'missing plain method')
451 self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
452 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000453
454 class B(A):
455 def m(self): pass
456
457 attrs = attrs_wo_objs(B)
Ezio Melottiaa980582010-01-23 23:04:36 +0000458 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
459 self.assertIn(('c', 'class method', A), attrs, 'missing class method')
460 self.assertIn(('p', 'property', A), attrs, 'missing property')
461 self.assertIn(('m', 'method', B), attrs, 'missing plain method')
462 self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
463 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Tim Peters13b49d32001-09-23 02:00:29 +0000464
465
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000466 class C(A):
467 def m(self): pass
468 def c(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000469
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000470 attrs = attrs_wo_objs(C)
Ezio Melottiaa980582010-01-23 23:04:36 +0000471 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
472 self.assertIn(('c', 'method', C), attrs, 'missing plain method')
473 self.assertIn(('p', 'property', A), attrs, 'missing property')
474 self.assertIn(('m', 'method', C), attrs, 'missing plain method')
475 self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
476 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Tim Peters13b49d32001-09-23 02:00:29 +0000477
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000478 class D(B, C):
479 def m1(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000480
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000481 attrs = attrs_wo_objs(D)
Ezio Melottiaa980582010-01-23 23:04:36 +0000482 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
483 self.assertIn(('c', 'class method', A), attrs, 'missing class method')
484 self.assertIn(('p', 'property', A), attrs, 'missing property')
485 self.assertIn(('m', 'method', B), attrs, 'missing plain method')
486 self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
487 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Tim Peters13b49d32001-09-23 02:00:29 +0000488
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000489 # Repeat all that, but w/ new-style classes.
490 def test_classify_newstyle(self):
491 class A(object):
Tim Peters13b49d32001-09-23 02:00:29 +0000492
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000493 def s(): pass
494 s = staticmethod(s)
Tim Peters13b49d32001-09-23 02:00:29 +0000495
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000496 def c(cls): pass
497 c = classmethod(c)
Tim Peters13b49d32001-09-23 02:00:29 +0000498
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000499 def getp(self): pass
500 p = property(getp)
Tim Peters13b49d32001-09-23 02:00:29 +0000501
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000502 def m(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000503
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000504 def m1(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000505
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000506 datablob = '1'
Tim Peters13b49d32001-09-23 02:00:29 +0000507
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000508 attrs = attrs_wo_objs(A)
Ezio Melottiaa980582010-01-23 23:04:36 +0000509 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
510 self.assertIn(('c', 'class method', A), attrs, 'missing class method')
511 self.assertIn(('p', 'property', A), attrs, 'missing property')
512 self.assertIn(('m', 'method', A), attrs, 'missing plain method')
513 self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
514 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Tim Peters13b49d32001-09-23 02:00:29 +0000515
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000516 class B(A):
Tim Peters13b49d32001-09-23 02:00:29 +0000517
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000518 def m(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000519
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000520 attrs = attrs_wo_objs(B)
Ezio Melottiaa980582010-01-23 23:04:36 +0000521 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
522 self.assertIn(('c', 'class method', A), attrs, 'missing class method')
523 self.assertIn(('p', 'property', A), attrs, 'missing property')
524 self.assertIn(('m', 'method', B), attrs, 'missing plain method')
525 self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
526 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Tim Peters13b49d32001-09-23 02:00:29 +0000527
528
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000529 class C(A):
Tim Peters13b49d32001-09-23 02:00:29 +0000530
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000531 def m(self): pass
532 def c(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000533
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000534 attrs = attrs_wo_objs(C)
Ezio Melottiaa980582010-01-23 23:04:36 +0000535 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
536 self.assertIn(('c', 'method', C), attrs, 'missing plain method')
537 self.assertIn(('p', 'property', A), attrs, 'missing property')
538 self.assertIn(('m', 'method', C), attrs, 'missing plain method')
539 self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
540 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Tim Peters13b49d32001-09-23 02:00:29 +0000541
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000542 class D(B, C):
Tim Peters13b49d32001-09-23 02:00:29 +0000543
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000544 def m1(self): pass
Tim Peters13b49d32001-09-23 02:00:29 +0000545
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000546 attrs = attrs_wo_objs(D)
Ezio Melottiaa980582010-01-23 23:04:36 +0000547 self.assertIn(('s', 'static method', A), attrs, 'missing static method')
548 self.assertIn(('c', 'method', C), attrs, 'missing plain method')
549 self.assertIn(('p', 'property', A), attrs, 'missing property')
550 self.assertIn(('m', 'method', B), attrs, 'missing plain method')
551 self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
552 self.assertIn(('datablob', 'data', A), attrs, 'missing data')
Jeremy Hyltonc4bf5ed2003-06-27 18:43:12 +0000553
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000554def test_main():
Johannes Gijsbers1542f342004-12-12 16:46:28 +0000555 run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners,
Johannes Gijsbersa5855d52005-03-12 16:37:11 +0000556 TestBuggyCases,
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000557 TestInterpreterStack, TestClassesAndFunctions, TestPredicates)
Martin v. Löwis893ffa42003-10-31 15:35:53 +0000558
Johannes Gijsberscb9015d2004-12-12 16:20:22 +0000559if __name__ == "__main__":
560 test_main()