PageRenderTime 62ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/test/test_inspect.py

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