test_inspect.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. import re
  2. import sys
  3. import types
  4. import unittest
  5. import inspect
  6. import linecache
  7. import datetime
  8. from UserList import UserList
  9. from UserDict import UserDict
  10. from test.test_support import run_unittest, check_py3k_warnings, have_unicode
  11. with check_py3k_warnings(
  12. ("tuple parameter unpacking has been removed", SyntaxWarning),
  13. quiet=True):
  14. from test import inspect_fodder as mod
  15. from test import inspect_fodder2 as mod2
  16. # C module for test_findsource_binary
  17. try:
  18. import unicodedata
  19. except ImportError:
  20. unicodedata = None
  21. # Functions tested in this suite:
  22. # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
  23. # isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers,
  24. # getdoc, getfile, getmodule, getsourcefile, getcomments, getsource,
  25. # getclasstree, getargspec, getargvalues, formatargspec, formatargvalues,
  26. # currentframe, stack, trace, isdatadescriptor
  27. # NOTE: There are some additional tests relating to interaction with
  28. # zipimport in the test_zipimport_support test module.
  29. modfile = mod.__file__
  30. if modfile.endswith(('c', 'o')):
  31. modfile = modfile[:-1]
  32. import __builtin__
  33. try:
  34. 1 // 0
  35. except:
  36. tb = sys.exc_traceback
  37. git = mod.StupidGit()
  38. class IsTestBase(unittest.TestCase):
  39. predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode,
  40. inspect.isframe, inspect.isfunction, inspect.ismethod,
  41. inspect.ismodule, inspect.istraceback,
  42. inspect.isgenerator, inspect.isgeneratorfunction])
  43. def istest(self, predicate, exp):
  44. obj = eval(exp)
  45. self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
  46. for other in self.predicates - set([predicate]):
  47. if predicate == inspect.isgeneratorfunction and\
  48. other == inspect.isfunction:
  49. continue
  50. self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))
  51. def generator_function_example(self):
  52. for i in xrange(2):
  53. yield i
  54. class TestPredicates(IsTestBase):
  55. def test_sixteen(self):
  56. count = len(filter(lambda x:x.startswith('is'), dir(inspect)))
  57. # This test is here for remember you to update Doc/library/inspect.rst
  58. # which claims there are 16 such functions
  59. expected = 16
  60. err_msg = "There are %d (not %d) is* functions" % (count, expected)
  61. self.assertEqual(count, expected, err_msg)
  62. def test_excluding_predicates(self):
  63. self.istest(inspect.isbuiltin, 'sys.exit')
  64. self.istest(inspect.isbuiltin, '[].append')
  65. self.istest(inspect.iscode, 'mod.spam.func_code')
  66. self.istest(inspect.isframe, 'tb.tb_frame')
  67. self.istest(inspect.isfunction, 'mod.spam')
  68. self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
  69. self.istest(inspect.ismethod, 'git.argue')
  70. self.istest(inspect.ismodule, 'mod')
  71. self.istest(inspect.istraceback, 'tb')
  72. self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
  73. self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
  74. self.istest(inspect.isgenerator, '(x for x in xrange(2))')
  75. self.istest(inspect.isgeneratorfunction, 'generator_function_example')
  76. if hasattr(types, 'GetSetDescriptorType'):
  77. self.istest(inspect.isgetsetdescriptor,
  78. 'type(tb.tb_frame).f_locals')
  79. else:
  80. self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
  81. if hasattr(types, 'MemberDescriptorType'):
  82. self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
  83. else:
  84. self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
  85. def test_isroutine(self):
  86. self.assertTrue(inspect.isroutine(mod.spam))
  87. self.assertTrue(inspect.isroutine([].count))
  88. def test_isclass(self):
  89. self.istest(inspect.isclass, 'mod.StupidGit')
  90. self.assertTrue(inspect.isclass(list))
  91. class newstyle(object): pass
  92. self.assertTrue(inspect.isclass(newstyle))
  93. class CustomGetattr(object):
  94. def __getattr__(self, attr):
  95. return None
  96. self.assertFalse(inspect.isclass(CustomGetattr()))
  97. def test_get_slot_members(self):
  98. class C(object):
  99. __slots__ = ("a", "b")
  100. x = C()
  101. x.a = 42
  102. members = dict(inspect.getmembers(x))
  103. self.assertIn('a', members)
  104. self.assertNotIn('b', members)
  105. def test_isabstract(self):
  106. from abc import ABCMeta, abstractmethod
  107. class AbstractClassExample(object):
  108. __metaclass__ = ABCMeta
  109. @abstractmethod
  110. def foo(self):
  111. pass
  112. class ClassExample(AbstractClassExample):
  113. def foo(self):
  114. pass
  115. a = ClassExample()
  116. # Test general behaviour.
  117. self.assertTrue(inspect.isabstract(AbstractClassExample))
  118. self.assertFalse(inspect.isabstract(ClassExample))
  119. self.assertFalse(inspect.isabstract(a))
  120. self.assertFalse(inspect.isabstract(int))
  121. self.assertFalse(inspect.isabstract(5))
  122. class TestInterpreterStack(IsTestBase):
  123. def __init__(self, *args, **kwargs):
  124. unittest.TestCase.__init__(self, *args, **kwargs)
  125. git.abuse(7, 8, 9)
  126. def test_abuse_done(self):
  127. self.istest(inspect.istraceback, 'git.ex[2]')
  128. self.istest(inspect.isframe, 'mod.fr')
  129. def test_stack(self):
  130. self.assertTrue(len(mod.st) >= 5)
  131. self.assertEqual(mod.st[0][1:],
  132. (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0))
  133. self.assertEqual(mod.st[1][1:],
  134. (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0))
  135. self.assertEqual(mod.st[2][1:],
  136. (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0))
  137. self.assertEqual(mod.st[3][1:],
  138. (modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0))
  139. def test_trace(self):
  140. self.assertEqual(len(git.tr), 3)
  141. self.assertEqual(git.tr[0][1:], (modfile, 43, 'argue',
  142. [' spam(a, b, c)\n'], 0))
  143. self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam',
  144. [' eggs(b + d, c + f)\n'], 0))
  145. self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs',
  146. [' q = y // 0\n'], 0))
  147. def test_frame(self):
  148. args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
  149. self.assertEqual(args, ['x', 'y'])
  150. self.assertEqual(varargs, None)
  151. self.assertEqual(varkw, None)
  152. self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
  153. self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
  154. '(x=11, y=14)')
  155. def test_previous_frame(self):
  156. args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
  157. self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
  158. self.assertEqual(varargs, 'g')
  159. self.assertEqual(varkw, 'h')
  160. self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
  161. '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
  162. class GetSourceBase(unittest.TestCase):
  163. # Subclasses must override.
  164. fodderFile = None
  165. def __init__(self, *args, **kwargs):
  166. unittest.TestCase.__init__(self, *args, **kwargs)
  167. with open(inspect.getsourcefile(self.fodderFile)) as fp:
  168. self.source = fp.read()
  169. def sourcerange(self, top, bottom):
  170. lines = self.source.split("\n")
  171. return "\n".join(lines[top-1:bottom]) + "\n"
  172. def assertSourceEqual(self, obj, top, bottom):
  173. self.assertEqual(inspect.getsource(obj),
  174. self.sourcerange(top, bottom))
  175. class TestRetrievingSourceCode(GetSourceBase):
  176. fodderFile = mod
  177. def test_getclasses(self):
  178. classes = inspect.getmembers(mod, inspect.isclass)
  179. self.assertEqual(classes,
  180. [('FesteringGob', mod.FesteringGob),
  181. ('MalodorousPervert', mod.MalodorousPervert),
  182. ('ParrotDroppings', mod.ParrotDroppings),
  183. ('StupidGit', mod.StupidGit),
  184. ('Tit', mod.MalodorousPervert),
  185. ])
  186. tree = inspect.getclasstree([cls[1] for cls in classes])
  187. self.assertEqual(tree,
  188. [(mod.ParrotDroppings, ()),
  189. [(mod.FesteringGob, (mod.MalodorousPervert,
  190. mod.ParrotDroppings))
  191. ],
  192. (mod.StupidGit, ()),
  193. [(mod.MalodorousPervert, (mod.StupidGit,)),
  194. [(mod.FesteringGob, (mod.MalodorousPervert,
  195. mod.ParrotDroppings))
  196. ]
  197. ]
  198. ])
  199. tree = inspect.getclasstree([cls[1] for cls in classes], True)
  200. self.assertEqual(tree,
  201. [(mod.ParrotDroppings, ()),
  202. (mod.StupidGit, ()),
  203. [(mod.MalodorousPervert, (mod.StupidGit,)),
  204. [(mod.FesteringGob, (mod.MalodorousPervert,
  205. mod.ParrotDroppings))
  206. ]
  207. ]
  208. ])
  209. def test_getfunctions(self):
  210. functions = inspect.getmembers(mod, inspect.isfunction)
  211. self.assertEqual(functions, [('eggs', mod.eggs),
  212. ('spam', mod.spam)])
  213. @unittest.skipIf(sys.flags.optimize >= 2,
  214. "Docstrings are omitted with -O2 and above")
  215. def test_getdoc(self):
  216. self.assertEqual(inspect.getdoc(mod), 'A module docstring.')
  217. self.assertEqual(inspect.getdoc(mod.StupidGit),
  218. 'A longer,\n\nindented\n\ndocstring.')
  219. self.assertEqual(inspect.getdoc(git.abuse),
  220. 'Another\n\ndocstring\n\ncontaining\n\ntabs')
  221. def test_cleandoc(self):
  222. self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'),
  223. 'An\nindented\ndocstring.')
  224. def test_getcomments(self):
  225. self.assertEqual(inspect.getcomments(mod), '# line 1\n')
  226. self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n')
  227. def test_getmodule(self):
  228. # Check actual module
  229. self.assertEqual(inspect.getmodule(mod), mod)
  230. # Check class (uses __module__ attribute)
  231. self.assertEqual(inspect.getmodule(mod.StupidGit), mod)
  232. # Check a method (no __module__ attribute, falls back to filename)
  233. self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
  234. # Do it again (check the caching isn't broken)
  235. self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
  236. # Check a builtin
  237. self.assertEqual(inspect.getmodule(str), sys.modules["__builtin__"])
  238. # Check filename override
  239. self.assertEqual(inspect.getmodule(None, modfile), mod)
  240. def test_getsource(self):
  241. self.assertSourceEqual(git.abuse, 29, 39)
  242. self.assertSourceEqual(mod.StupidGit, 21, 46)
  243. def test_getsourcefile(self):
  244. self.assertEqual(inspect.getsourcefile(mod.spam), modfile)
  245. self.assertEqual(inspect.getsourcefile(git.abuse), modfile)
  246. fn = "_non_existing_filename_used_for_sourcefile_test.py"
  247. co = compile("None", fn, "exec")
  248. self.assertEqual(inspect.getsourcefile(co), None)
  249. linecache.cache[co.co_filename] = (1, None, "None", co.co_filename)
  250. self.assertEqual(inspect.getsourcefile(co), fn)
  251. def test_getfile(self):
  252. self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
  253. def test_getmodule_recursion(self):
  254. from types import ModuleType
  255. name = '__inspect_dummy'
  256. m = sys.modules[name] = ModuleType(name)
  257. m.__file__ = "<string>" # hopefully not a real filename...
  258. m.__loader__ = "dummy" # pretend the filename is understood by a loader
  259. exec "def x(): pass" in m.__dict__
  260. self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
  261. del sys.modules[name]
  262. inspect.getmodule(compile('a=10','','single'))
  263. def test_proceed_with_fake_filename(self):
  264. '''doctest monkeypatches linecache to enable inspection'''
  265. fn, source = '<test>', 'def x(): pass\n'
  266. getlines = linecache.getlines
  267. def monkey(filename, module_globals=None):
  268. if filename == fn:
  269. return source.splitlines(True)
  270. else:
  271. return getlines(filename, module_globals)
  272. linecache.getlines = monkey
  273. try:
  274. ns = {}
  275. exec compile(source, fn, 'single') in ns
  276. inspect.getsource(ns["x"])
  277. finally:
  278. linecache.getlines = getlines
  279. class TestDecorators(GetSourceBase):
  280. fodderFile = mod2
  281. def test_wrapped_decorator(self):
  282. self.assertSourceEqual(mod2.wrapped, 14, 17)
  283. def test_replacing_decorator(self):
  284. self.assertSourceEqual(mod2.gone, 9, 10)
  285. class TestOneliners(GetSourceBase):
  286. fodderFile = mod2
  287. def test_oneline_lambda(self):
  288. # Test inspect.getsource with a one-line lambda function.
  289. self.assertSourceEqual(mod2.oll, 25, 25)
  290. def test_threeline_lambda(self):
  291. # Test inspect.getsource with a three-line lambda function,
  292. # where the second and third lines are _not_ indented.
  293. self.assertSourceEqual(mod2.tll, 28, 30)
  294. def test_twoline_indented_lambda(self):
  295. # Test inspect.getsource with a two-line lambda function,
  296. # where the second line _is_ indented.
  297. self.assertSourceEqual(mod2.tlli, 33, 34)
  298. def test_onelinefunc(self):
  299. # Test inspect.getsource with a regular one-line function.
  300. self.assertSourceEqual(mod2.onelinefunc, 37, 37)
  301. def test_manyargs(self):
  302. # Test inspect.getsource with a regular function where
  303. # the arguments are on two lines and _not_ indented and
  304. # the body on the second line with the last arguments.
  305. self.assertSourceEqual(mod2.manyargs, 40, 41)
  306. def test_twolinefunc(self):
  307. # Test inspect.getsource with a regular function where
  308. # the body is on two lines, following the argument list and
  309. # continued on the next line by a \\.
  310. self.assertSourceEqual(mod2.twolinefunc, 44, 45)
  311. def test_lambda_in_list(self):
  312. # Test inspect.getsource with a one-line lambda function
  313. # defined in a list, indented.
  314. self.assertSourceEqual(mod2.a[1], 49, 49)
  315. def test_anonymous(self):
  316. # Test inspect.getsource with a lambda function defined
  317. # as argument to another function.
  318. self.assertSourceEqual(mod2.anonymous, 55, 55)
  319. class TestBuggyCases(GetSourceBase):
  320. fodderFile = mod2
  321. def test_with_comment(self):
  322. self.assertSourceEqual(mod2.with_comment, 58, 59)
  323. def test_multiline_sig(self):
  324. self.assertSourceEqual(mod2.multiline_sig[0], 63, 64)
  325. def test_nested_class(self):
  326. self.assertSourceEqual(mod2.func69().func71, 71, 72)
  327. def test_one_liner_followed_by_non_name(self):
  328. self.assertSourceEqual(mod2.func77, 77, 77)
  329. def test_one_liner_dedent_non_name(self):
  330. self.assertSourceEqual(mod2.cls82.func83, 83, 83)
  331. def test_with_comment_instead_of_docstring(self):
  332. self.assertSourceEqual(mod2.func88, 88, 90)
  333. def test_method_in_dynamic_class(self):
  334. self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
  335. @unittest.skipIf(
  336. not hasattr(unicodedata, '__file__') or
  337. unicodedata.__file__[-4:] in (".pyc", ".pyo"),
  338. "unicodedata is not an external binary module")
  339. def test_findsource_binary(self):
  340. self.assertRaises(IOError, inspect.getsource, unicodedata)
  341. self.assertRaises(IOError, inspect.findsource, unicodedata)
  342. def test_findsource_code_in_linecache(self):
  343. lines = ["x=1"]
  344. co = compile(lines[0], "_dynamically_created_file", "exec")
  345. self.assertRaises(IOError, inspect.findsource, co)
  346. self.assertRaises(IOError, inspect.getsource, co)
  347. linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
  348. self.assertEqual(inspect.findsource(co), (lines,0))
  349. self.assertEqual(inspect.getsource(co), lines[0])
  350. def test_findsource_without_filename(self):
  351. for fname in ['', '<string>']:
  352. co = compile('x=1', fname, "exec")
  353. self.assertRaises(IOError, inspect.findsource, co)
  354. self.assertRaises(IOError, inspect.getsource, co)
  355. class _BrokenDataDescriptor(object):
  356. """
  357. A broken data descriptor. See bug #1785.
  358. """
  359. def __get__(*args):
  360. raise AssertionError("should not __get__ data descriptors")
  361. def __set__(*args):
  362. raise RuntimeError
  363. def __getattr__(*args):
  364. raise AssertionError("should not __getattr__ data descriptors")
  365. class _BrokenMethodDescriptor(object):
  366. """
  367. A broken method descriptor. See bug #1785.
  368. """
  369. def __get__(*args):
  370. raise AssertionError("should not __get__ method descriptors")
  371. def __getattr__(*args):
  372. raise AssertionError("should not __getattr__ method descriptors")
  373. # Helper for testing classify_class_attrs.
  374. def attrs_wo_objs(cls):
  375. return [t[:3] for t in inspect.classify_class_attrs(cls)]
  376. class TestClassesAndFunctions(unittest.TestCase):
  377. def test_classic_mro(self):
  378. # Test classic-class method resolution order.
  379. class A: pass
  380. class B(A): pass
  381. class C(A): pass
  382. class D(B, C): pass
  383. expected = (D, B, A, C)
  384. got = inspect.getmro(D)
  385. self.assertEqual(expected, got)
  386. def test_newstyle_mro(self):
  387. # The same w/ new-class MRO.
  388. class A(object): pass
  389. class B(A): pass
  390. class C(A): pass
  391. class D(B, C): pass
  392. expected = (D, B, C, A, object)
  393. got = inspect.getmro(D)
  394. self.assertEqual(expected, got)
  395. def assertArgSpecEquals(self, routine, args_e, varargs_e = None,
  396. varkw_e = None, defaults_e = None,
  397. formatted = None):
  398. args, varargs, varkw, defaults = inspect.getargspec(routine)
  399. self.assertEqual(args, args_e)
  400. self.assertEqual(varargs, varargs_e)
  401. self.assertEqual(varkw, varkw_e)
  402. self.assertEqual(defaults, defaults_e)
  403. if formatted is not None:
  404. self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults),
  405. formatted)
  406. def test_getargspec(self):
  407. self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)')
  408. self.assertArgSpecEquals(mod.spam,
  409. ['a', 'b', 'c', 'd', ['e', ['f']]],
  410. 'g', 'h', (3, (4, (5,))),
  411. '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
  412. def test_getargspec_method(self):
  413. class A(object):
  414. def m(self):
  415. pass
  416. self.assertArgSpecEquals(A.m, ['self'])
  417. def test_getargspec_sublistofone(self):
  418. with check_py3k_warnings(
  419. ("tuple parameter unpacking has been removed", SyntaxWarning),
  420. ("parenthesized argument names are invalid", SyntaxWarning)):
  421. exec 'def sublistOfOne((foo,)): return 1'
  422. self.assertArgSpecEquals(sublistOfOne, [['foo']])
  423. exec 'def fakeSublistOfOne((foo)): return 1'
  424. self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
  425. def _classify_test(self, newstyle):
  426. """Helper for testing that classify_class_attrs finds a bunch of
  427. different kinds of attributes on a given class.
  428. """
  429. if newstyle:
  430. base = object
  431. else:
  432. class base:
  433. pass
  434. class A(base):
  435. def s(): pass
  436. s = staticmethod(s)
  437. def c(cls): pass
  438. c = classmethod(c)
  439. def getp(self): pass
  440. p = property(getp)
  441. def m(self): pass
  442. def m1(self): pass
  443. datablob = '1'
  444. dd = _BrokenDataDescriptor()
  445. md = _BrokenMethodDescriptor()
  446. attrs = attrs_wo_objs(A)
  447. 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')
  453. self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
  454. self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
  455. class B(A):
  456. def m(self): pass
  457. attrs = attrs_wo_objs(B)
  458. 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')
  464. self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
  465. self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
  466. class C(A):
  467. def m(self): pass
  468. def c(self): pass
  469. attrs = attrs_wo_objs(C)
  470. self.assertIn(('s', 'static method', A), attrs, 'missing static method')
  471. self.assertIn(('c', 'method', C), attrs, 'missing plain method')
  472. self.assertIn(('p', 'property', A), attrs, 'missing property')
  473. self.assertIn(('m', 'method', C), attrs, 'missing plain method')
  474. self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
  475. self.assertIn(('datablob', 'data', A), attrs, 'missing data')
  476. self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
  477. self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
  478. class D(B, C):
  479. def m1(self): pass
  480. attrs = attrs_wo_objs(D)
  481. self.assertIn(('s', 'static method', A), attrs, 'missing static method')
  482. if newstyle:
  483. self.assertIn(('c', 'method', C), attrs, 'missing plain method')
  484. else:
  485. self.assertIn(('c', 'class method', A), attrs, 'missing class method')
  486. self.assertIn(('p', 'property', A), attrs, 'missing property')
  487. self.assertIn(('m', 'method', B), attrs, 'missing plain method')
  488. self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
  489. self.assertIn(('datablob', 'data', A), attrs, 'missing data')
  490. self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
  491. self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
  492. def test_classify_oldstyle(self):
  493. """classify_class_attrs finds static methods, class methods,
  494. properties, normal methods, and data attributes on an old-style
  495. class.
  496. """
  497. self._classify_test(False)
  498. def test_classify_newstyle(self):
  499. """Just like test_classify_oldstyle, but for a new-style class.
  500. """
  501. self._classify_test(True)
  502. def test_classify_builtin_types(self):
  503. # Simple sanity check that all built-in types can have their
  504. # attributes classified.
  505. for name in dir(__builtin__):
  506. builtin = getattr(__builtin__, name)
  507. if isinstance(builtin, type):
  508. inspect.classify_class_attrs(builtin)
  509. def test_getmembers_method(self):
  510. # Old-style classes
  511. class B:
  512. def f(self):
  513. pass
  514. self.assertIn(('f', B.f), inspect.getmembers(B))
  515. # contrary to spec, ismethod() is also True for unbound methods
  516. # (see #1785)
  517. self.assertIn(('f', B.f), inspect.getmembers(B, inspect.ismethod))
  518. b = B()
  519. self.assertIn(('f', b.f), inspect.getmembers(b))
  520. self.assertIn(('f', b.f), inspect.getmembers(b, inspect.ismethod))
  521. # New-style classes
  522. class B(object):
  523. def f(self):
  524. pass
  525. self.assertIn(('f', B.f), inspect.getmembers(B))
  526. self.assertIn(('f', B.f), inspect.getmembers(B, inspect.ismethod))
  527. b = B()
  528. self.assertIn(('f', b.f), inspect.getmembers(b))
  529. self.assertIn(('f', b.f), inspect.getmembers(b, inspect.ismethod))
  530. class TestGetcallargsFunctions(unittest.TestCase):
  531. # tuple parameters are named '.1', '.2', etc.
  532. is_tuplename = re.compile(r'^\.\d+$').match
  533. def assertEqualCallArgs(self, func, call_params_string, locs=None):
  534. locs = dict(locs or {}, func=func)
  535. r1 = eval('func(%s)' % call_params_string, None, locs)
  536. r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None,
  537. locs)
  538. self.assertEqual(r1, r2)
  539. def assertEqualException(self, func, call_param_string, locs=None):
  540. locs = dict(locs or {}, func=func)
  541. try:
  542. eval('func(%s)' % call_param_string, None, locs)
  543. except Exception, ex1:
  544. pass
  545. else:
  546. self.fail('Exception not raised')
  547. try:
  548. eval('inspect.getcallargs(func, %s)' % call_param_string, None,
  549. locs)
  550. except Exception, ex2:
  551. pass
  552. else:
  553. self.fail('Exception not raised')
  554. self.assertIs(type(ex1), type(ex2))
  555. self.assertEqual(str(ex1), str(ex2))
  556. def makeCallable(self, signature):
  557. """Create a function that returns its locals(), excluding the
  558. autogenerated '.1', '.2', etc. tuple param names (if any)."""
  559. with check_py3k_warnings(
  560. ("tuple parameter unpacking has been removed", SyntaxWarning),
  561. quiet=True):
  562. code = ("lambda %s: dict(i for i in locals().items() "
  563. "if not is_tuplename(i[0]))")
  564. return eval(code % signature, {'is_tuplename' : self.is_tuplename})
  565. def test_plain(self):
  566. f = self.makeCallable('a, b=1')
  567. self.assertEqualCallArgs(f, '2')
  568. self.assertEqualCallArgs(f, '2, 3')
  569. self.assertEqualCallArgs(f, 'a=2')
  570. self.assertEqualCallArgs(f, 'b=3, a=2')
  571. self.assertEqualCallArgs(f, '2, b=3')
  572. # expand *iterable / **mapping
  573. self.assertEqualCallArgs(f, '*(2,)')
  574. self.assertEqualCallArgs(f, '*[2]')
  575. self.assertEqualCallArgs(f, '*(2, 3)')
  576. self.assertEqualCallArgs(f, '*[2, 3]')
  577. self.assertEqualCallArgs(f, '**{"a":2}')
  578. self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
  579. self.assertEqualCallArgs(f, '2, **{"b":3}')
  580. self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
  581. # expand UserList / UserDict
  582. self.assertEqualCallArgs(f, '*UserList([2])')
  583. self.assertEqualCallArgs(f, '*UserList([2, 3])')
  584. self.assertEqualCallArgs(f, '**UserDict(a=2)')
  585. self.assertEqualCallArgs(f, '2, **UserDict(b=3)')
  586. self.assertEqualCallArgs(f, 'b=2, **UserDict(a=3)')
  587. # unicode keyword args
  588. self.assertEqualCallArgs(f, '**{u"a":2}')
  589. self.assertEqualCallArgs(f, 'b=3, **{u"a":2}')
  590. self.assertEqualCallArgs(f, '2, **{u"b":3}')
  591. self.assertEqualCallArgs(f, '**{u"b":3, u"a":2}')
  592. def test_varargs(self):
  593. f = self.makeCallable('a, b=1, *c')
  594. self.assertEqualCallArgs(f, '2')
  595. self.assertEqualCallArgs(f, '2, 3')
  596. self.assertEqualCallArgs(f, '2, 3, 4')
  597. self.assertEqualCallArgs(f, '*(2,3,4)')
  598. self.assertEqualCallArgs(f, '2, *[3,4]')
  599. self.assertEqualCallArgs(f, '2, 3, *UserList([4])')
  600. def test_varkw(self):
  601. f = self.makeCallable('a, b=1, **c')
  602. self.assertEqualCallArgs(f, 'a=2')
  603. self.assertEqualCallArgs(f, '2, b=3, c=4')
  604. self.assertEqualCallArgs(f, 'b=3, a=2, c=4')
  605. self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}')
  606. self.assertEqualCallArgs(f, '2, c=4, **{"b":3}')
  607. self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}')
  608. self.assertEqualCallArgs(f, '**UserDict(a=2, b=3, c=4)')
  609. self.assertEqualCallArgs(f, '2, c=4, **UserDict(b=3)')
  610. self.assertEqualCallArgs(f, 'b=2, **UserDict(a=3, c=4)')
  611. # unicode keyword args
  612. self.assertEqualCallArgs(f, 'c=4, **{u"a":2, u"b":3}')
  613. self.assertEqualCallArgs(f, '2, c=4, **{u"b":3}')
  614. self.assertEqualCallArgs(f, 'b=2, **{u"a":3, u"c":4}')
  615. def test_varkw_only(self):
  616. # issue11256:
  617. f = self.makeCallable('**c')
  618. self.assertEqualCallArgs(f, '')
  619. self.assertEqualCallArgs(f, 'a=1')
  620. self.assertEqualCallArgs(f, 'a=1, b=2')
  621. self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}')
  622. self.assertEqualCallArgs(f, '**UserDict(a=1, b=2)')
  623. self.assertEqualCallArgs(f, 'c=3, **UserDict(a=1, b=2)')
  624. def test_tupleargs(self):
  625. f = self.makeCallable('(b,c), (d,(e,f))=(0,[1,2])')
  626. self.assertEqualCallArgs(f, '(2,3)')
  627. self.assertEqualCallArgs(f, '[2,3]')
  628. self.assertEqualCallArgs(f, 'UserList([2,3])')
  629. self.assertEqualCallArgs(f, '(2,3), (4,(5,6))')
  630. self.assertEqualCallArgs(f, '(2,3), (4,[5,6])')
  631. self.assertEqualCallArgs(f, '(2,3), [4,UserList([5,6])]')
  632. def test_multiple_features(self):
  633. f = self.makeCallable('a, b=2, (c,(d,e))=(3,[4,5]), *f, **g')
  634. self.assertEqualCallArgs(f, '2, 3, (4,[5,6]), 7')
  635. self.assertEqualCallArgs(f, '2, 3, *[(4,[5,6]), 7], x=8')
  636. self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
  637. self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
  638. self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
  639. self.assertEqualCallArgs(f, 'x=8, *UserList([2, 3, (4,[5,6])]), '
  640. '**{"y":9, "z":10}')
  641. self.assertEqualCallArgs(f, '2, x=8, *UserList([3, (4,[5,6])]), '
  642. '**UserDict(y=9, z=10)')
  643. def test_errors(self):
  644. f0 = self.makeCallable('')
  645. f1 = self.makeCallable('a, b')
  646. f2 = self.makeCallable('a, b=1')
  647. # f0 takes no arguments
  648. self.assertEqualException(f0, '1')
  649. self.assertEqualException(f0, 'x=1')
  650. self.assertEqualException(f0, '1,x=1')
  651. # f1 takes exactly 2 arguments
  652. self.assertEqualException(f1, '')
  653. self.assertEqualException(f1, '1')
  654. self.assertEqualException(f1, 'a=2')
  655. self.assertEqualException(f1, 'b=3')
  656. # f2 takes at least 1 argument
  657. self.assertEqualException(f2, '')
  658. self.assertEqualException(f2, 'b=3')
  659. for f in f1, f2:
  660. # f1/f2 takes exactly/at most 2 arguments
  661. self.assertEqualException(f, '2, 3, 4')
  662. self.assertEqualException(f, '1, 2, 3, a=1')
  663. self.assertEqualException(f, '2, 3, 4, c=5')
  664. self.assertEqualException(f, '2, 3, 4, a=1, c=5')
  665. # f got an unexpected keyword argument
  666. self.assertEqualException(f, 'c=2')
  667. self.assertEqualException(f, '2, c=3')
  668. self.assertEqualException(f, '2, 3, c=4')
  669. self.assertEqualException(f, '2, c=4, b=3')
  670. if have_unicode:
  671. self.assertEqualException(f, '**{u"\u03c0\u03b9": 4}')
  672. # f got multiple values for keyword argument
  673. self.assertEqualException(f, '1, a=2')
  674. self.assertEqualException(f, '1, **{"a":2}')
  675. self.assertEqualException(f, '1, 2, b=3')
  676. # XXX: Python inconsistency
  677. # - for functions and bound methods: unexpected keyword 'c'
  678. # - for unbound methods: multiple values for keyword 'a'
  679. #self.assertEqualException(f, '1, c=3, a=2')
  680. f = self.makeCallable('(a,b)=(0,1)')
  681. self.assertEqualException(f, '1')
  682. self.assertEqualException(f, '[1]')
  683. self.assertEqualException(f, '(1,2,3)')
  684. # issue11256:
  685. f3 = self.makeCallable('**c')
  686. self.assertEqualException(f3, '1, 2')
  687. self.assertEqualException(f3, '1, 2, a=1, b=2')
  688. class TestGetcallargsMethods(TestGetcallargsFunctions):
  689. def setUp(self):
  690. class Foo(object):
  691. pass
  692. self.cls = Foo
  693. self.inst = Foo()
  694. def makeCallable(self, signature):
  695. assert 'self' not in signature
  696. mk = super(TestGetcallargsMethods, self).makeCallable
  697. self.cls.method = mk('self, ' + signature)
  698. return self.inst.method
  699. class TestGetcallargsUnboundMethods(TestGetcallargsMethods):
  700. def makeCallable(self, signature):
  701. super(TestGetcallargsUnboundMethods, self).makeCallable(signature)
  702. return self.cls.method
  703. def assertEqualCallArgs(self, func, call_params_string, locs=None):
  704. return super(TestGetcallargsUnboundMethods, self).assertEqualCallArgs(
  705. *self._getAssertEqualParams(func, call_params_string, locs))
  706. def assertEqualException(self, func, call_params_string, locs=None):
  707. return super(TestGetcallargsUnboundMethods, self).assertEqualException(
  708. *self._getAssertEqualParams(func, call_params_string, locs))
  709. def _getAssertEqualParams(self, func, call_params_string, locs=None):
  710. assert 'inst' not in call_params_string
  711. locs = dict(locs or {}, inst=self.inst)
  712. return (func, 'inst,' + call_params_string, locs)
  713. def test_main():
  714. run_unittest(
  715. TestDecorators, TestRetrievingSourceCode, TestOneliners, TestBuggyCases,
  716. TestInterpreterStack, TestClassesAndFunctions, TestPredicates,
  717. TestGetcallargsFunctions, TestGetcallargsMethods,
  718. TestGetcallargsUnboundMethods)
  719. if __name__ == "__main__":
  720. test_main()