PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/pwaller/pypy
Python | 754 lines | 683 code | 52 blank | 19 comment | 13 complexity | ea10926c5c6b9382a3a7f8b67e17c577 MD5 | raw file
  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. class TestDecorators(GetSourceBase):
  247. fodderFile = mod2
  248. def test_wrapped_decorator(self):
  249. self.assertSourceEqual(mod2.wrapped, 14, 17)
  250. def test_replacing_decorator(self):
  251. self.assertSourceEqual(mod2.gone, 9, 10)
  252. class TestOneliners(GetSourceBase):
  253. fodderFile = mod2
  254. def test_oneline_lambda(self):
  255. # Test inspect.getsource with a one-line lambda function.
  256. self.assertSourceEqual(mod2.oll, 25, 25)
  257. def test_threeline_lambda(self):
  258. # Test inspect.getsource with a three-line lambda function,
  259. # where the second and third lines are _not_ indented.
  260. self.assertSourceEqual(mod2.tll, 28, 30)
  261. def test_twoline_indented_lambda(self):
  262. # Test inspect.getsource with a two-line lambda function,
  263. # where the second line _is_ indented.
  264. self.assertSourceEqual(mod2.tlli, 33, 34)
  265. def test_onelinefunc(self):
  266. # Test inspect.getsource with a regular one-line function.
  267. self.assertSourceEqual(mod2.onelinefunc, 37, 37)
  268. def test_manyargs(self):
  269. # Test inspect.getsource with a regular function where
  270. # the arguments are on two lines and _not_ indented and
  271. # the body on the second line with the last arguments.
  272. self.assertSourceEqual(mod2.manyargs, 40, 41)
  273. def test_twolinefunc(self):
  274. # Test inspect.getsource with a regular function where
  275. # the body is on two lines, following the argument list and
  276. # continued on the next line by a \\.
  277. self.assertSourceEqual(mod2.twolinefunc, 44, 45)
  278. def test_lambda_in_list(self):
  279. # Test inspect.getsource with a one-line lambda function
  280. # defined in a list, indented.
  281. self.assertSourceEqual(mod2.a[1], 49, 49)
  282. def test_anonymous(self):
  283. # Test inspect.getsource with a lambda function defined
  284. # as argument to another function.
  285. self.assertSourceEqual(mod2.anonymous, 55, 55)
  286. class TestBuggyCases(GetSourceBase):
  287. fodderFile = mod2
  288. def test_with_comment(self):
  289. self.assertSourceEqual(mod2.with_comment, 58, 59)
  290. def test_multiline_sig(self):
  291. self.assertSourceEqual(mod2.multiline_sig[0], 63, 64)
  292. def test_nested_class(self):
  293. self.assertSourceEqual(mod2.func69().func71, 71, 72)
  294. def test_one_liner_followed_by_non_name(self):
  295. self.assertSourceEqual(mod2.func77, 77, 77)
  296. def test_one_liner_dedent_non_name(self):
  297. self.assertSourceEqual(mod2.cls82.func83, 83, 83)
  298. def test_with_comment_instead_of_docstring(self):
  299. self.assertSourceEqual(mod2.func88, 88, 90)
  300. def test_method_in_dynamic_class(self):
  301. self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
  302. @unittest.skipIf(
  303. not hasattr(unicodedata, '__file__') or
  304. unicodedata.__file__[-4:] in (".pyc", ".pyo"),
  305. "unicodedata is not an external binary module")
  306. def test_findsource_binary(self):
  307. self.assertRaises(IOError, inspect.getsource, unicodedata)
  308. self.assertRaises(IOError, inspect.findsource, unicodedata)
  309. def test_findsource_code_in_linecache(self):
  310. lines = ["x=1"]
  311. co = compile(lines[0], "_dynamically_created_file", "exec")
  312. self.assertRaises(IOError, inspect.findsource, co)
  313. self.assertRaises(IOError, inspect.getsource, co)
  314. linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
  315. self.assertEqual(inspect.findsource(co), (lines,0))
  316. self.assertEqual(inspect.getsource(co), lines[0])
  317. # Helper for testing classify_class_attrs.
  318. def attrs_wo_objs(cls):
  319. return [t[:3] for t in inspect.classify_class_attrs(cls)]
  320. class TestClassesAndFunctions(unittest.TestCase):
  321. def test_classic_mro(self):
  322. # Test classic-class method resolution order.
  323. class A: pass
  324. class B(A): pass
  325. class C(A): pass
  326. class D(B, C): pass
  327. expected = (D, B, A, C)
  328. got = inspect.getmro(D)
  329. self.assertEqual(expected, got)
  330. def test_newstyle_mro(self):
  331. # The same w/ new-class MRO.
  332. class A(object): pass
  333. class B(A): pass
  334. class C(A): pass
  335. class D(B, C): pass
  336. expected = (D, B, C, A, object)
  337. got = inspect.getmro(D)
  338. self.assertEqual(expected, got)
  339. def assertArgSpecEquals(self, routine, args_e, varargs_e = None,
  340. varkw_e = None, defaults_e = None,
  341. formatted = None):
  342. args, varargs, varkw, defaults = inspect.getargspec(routine)
  343. self.assertEqual(args, args_e)
  344. self.assertEqual(varargs, varargs_e)
  345. self.assertEqual(varkw, varkw_e)
  346. self.assertEqual(defaults, defaults_e)
  347. if formatted is not None:
  348. self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults),
  349. formatted)
  350. def test_getargspec(self):
  351. self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)')
  352. self.assertArgSpecEquals(mod.spam,
  353. ['a', 'b', 'c', 'd', ['e', ['f']]],
  354. 'g', 'h', (3, (4, (5,))),
  355. '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
  356. def test_getargspec_method(self):
  357. class A(object):
  358. def m(self):
  359. pass
  360. self.assertArgSpecEquals(A.m, ['self'])
  361. def test_getargspec_sublistofone(self):
  362. with check_py3k_warnings(
  363. ("tuple parameter unpacking has been removed", SyntaxWarning),
  364. ("parenthesized argument names are invalid", SyntaxWarning)):
  365. exec 'def sublistOfOne((foo,)): return 1'
  366. self.assertArgSpecEquals(sublistOfOne, [['foo']])
  367. exec 'def fakeSublistOfOne((foo)): return 1'
  368. self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
  369. def _classify_test(self, newstyle):
  370. """Helper for testing that classify_class_attrs finds a bunch of
  371. different kinds of attributes on a given class.
  372. """
  373. if newstyle:
  374. base = object
  375. else:
  376. class base:
  377. pass
  378. class A(base):
  379. def s(): pass
  380. s = staticmethod(s)
  381. def c(cls): pass
  382. c = classmethod(c)
  383. def getp(self): pass
  384. p = property(getp)
  385. def m(self): pass
  386. def m1(self): pass
  387. datablob = '1'
  388. attrs = attrs_wo_objs(A)
  389. self.assertIn(('s', 'static method', A), attrs, 'missing static method')
  390. self.assertIn(('c', 'class method', A), attrs, 'missing class method')
  391. self.assertIn(('p', 'property', A), attrs, 'missing property')
  392. self.assertIn(('m', 'method', A), attrs, 'missing plain method')
  393. self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
  394. self.assertIn(('datablob', 'data', A), attrs, 'missing data')
  395. class B(A):
  396. def m(self): pass
  397. attrs = attrs_wo_objs(B)
  398. self.assertIn(('s', 'static method', A), attrs, 'missing static method')
  399. self.assertIn(('c', 'class method', A), attrs, 'missing class method')
  400. self.assertIn(('p', 'property', A), attrs, 'missing property')
  401. self.assertIn(('m', 'method', B), attrs, 'missing plain method')
  402. self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
  403. self.assertIn(('datablob', 'data', A), attrs, 'missing data')
  404. class C(A):
  405. def m(self): pass
  406. def c(self): pass
  407. attrs = attrs_wo_objs(C)
  408. self.assertIn(('s', 'static method', A), attrs, 'missing static method')
  409. self.assertIn(('c', 'method', C), attrs, 'missing plain method')
  410. self.assertIn(('p', 'property', A), attrs, 'missing property')
  411. self.assertIn(('m', 'method', C), attrs, 'missing plain method')
  412. self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
  413. self.assertIn(('datablob', 'data', A), attrs, 'missing data')
  414. class D(B, C):
  415. def m1(self): pass
  416. attrs = attrs_wo_objs(D)
  417. self.assertIn(('s', 'static method', A), attrs, 'missing static method')
  418. if newstyle:
  419. self.assertIn(('c', 'method', C), attrs, 'missing plain method')
  420. else:
  421. self.assertIn(('c', 'class method', A), attrs, 'missing class method')
  422. self.assertIn(('p', 'property', A), attrs, 'missing property')
  423. self.assertIn(('m', 'method', B), attrs, 'missing plain method')
  424. self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
  425. self.assertIn(('datablob', 'data', A), attrs, 'missing data')
  426. def test_classify_oldstyle(self):
  427. """classify_class_attrs finds static methods, class methods,
  428. properties, normal methods, and data attributes on an old-style
  429. class.
  430. """
  431. self._classify_test(False)
  432. def test_classify_newstyle(self):
  433. """Just like test_classify_oldstyle, but for a new-style class.
  434. """
  435. self._classify_test(True)
  436. class TestGetcallargsFunctions(unittest.TestCase):
  437. # tuple parameters are named '.1', '.2', etc.
  438. is_tuplename = re.compile(r'^\.\d+$').match
  439. def assertEqualCallArgs(self, func, call_params_string, locs=None):
  440. locs = dict(locs or {}, func=func)
  441. r1 = eval('func(%s)' % call_params_string, None, locs)
  442. r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None,
  443. locs)
  444. self.assertEqual(r1, r2)
  445. def assertEqualException(self, func, call_param_string, locs=None):
  446. locs = dict(locs or {}, func=func)
  447. try:
  448. eval('func(%s)' % call_param_string, None, locs)
  449. except Exception, ex1:
  450. pass
  451. else:
  452. self.fail('Exception not raised')
  453. try:
  454. eval('inspect.getcallargs(func, %s)' % call_param_string, None,
  455. locs)
  456. except Exception, ex2:
  457. pass
  458. else:
  459. self.fail('Exception not raised')
  460. self.assertIs(type(ex1), type(ex2))
  461. if check_impl_detail():
  462. self.assertEqual(str(ex1), str(ex2))
  463. def makeCallable(self, signature):
  464. """Create a function that returns its locals(), excluding the
  465. autogenerated '.1', '.2', etc. tuple param names (if any)."""
  466. with check_py3k_warnings(
  467. ("tuple parameter unpacking has been removed", SyntaxWarning),
  468. quiet=True):
  469. code = ("lambda %s: dict(i for i in locals().items() "
  470. "if not is_tuplename(i[0]))")
  471. return eval(code % signature, {'is_tuplename' : self.is_tuplename})
  472. def test_plain(self):
  473. f = self.makeCallable('a, b=1')
  474. self.assertEqualCallArgs(f, '2')
  475. self.assertEqualCallArgs(f, '2, 3')
  476. self.assertEqualCallArgs(f, 'a=2')
  477. self.assertEqualCallArgs(f, 'b=3, a=2')
  478. self.assertEqualCallArgs(f, '2, b=3')
  479. # expand *iterable / **mapping
  480. self.assertEqualCallArgs(f, '*(2,)')
  481. self.assertEqualCallArgs(f, '*[2]')
  482. self.assertEqualCallArgs(f, '*(2, 3)')
  483. self.assertEqualCallArgs(f, '*[2, 3]')
  484. self.assertEqualCallArgs(f, '**{"a":2}')
  485. self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
  486. self.assertEqualCallArgs(f, '2, **{"b":3}')
  487. self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
  488. # expand UserList / UserDict
  489. self.assertEqualCallArgs(f, '*UserList([2])')
  490. self.assertEqualCallArgs(f, '*UserList([2, 3])')
  491. self.assertEqualCallArgs(f, '**UserDict(a=2)')
  492. self.assertEqualCallArgs(f, '2, **UserDict(b=3)')
  493. self.assertEqualCallArgs(f, 'b=2, **UserDict(a=3)')
  494. # unicode keyword args
  495. self.assertEqualCallArgs(f, '**{u"a":2}')
  496. self.assertEqualCallArgs(f, 'b=3, **{u"a":2}')
  497. self.assertEqualCallArgs(f, '2, **{u"b":3}')
  498. self.assertEqualCallArgs(f, '**{u"b":3, u"a":2}')
  499. def test_varargs(self):
  500. f = self.makeCallable('a, b=1, *c')
  501. self.assertEqualCallArgs(f, '2')
  502. self.assertEqualCallArgs(f, '2, 3')
  503. self.assertEqualCallArgs(f, '2, 3, 4')
  504. self.assertEqualCallArgs(f, '*(2,3,4)')
  505. self.assertEqualCallArgs(f, '2, *[3,4]')
  506. self.assertEqualCallArgs(f, '2, 3, *UserList([4])')
  507. def test_varkw(self):
  508. f = self.makeCallable('a, b=1, **c')
  509. self.assertEqualCallArgs(f, 'a=2')
  510. self.assertEqualCallArgs(f, '2, b=3, c=4')
  511. self.assertEqualCallArgs(f, 'b=3, a=2, c=4')
  512. self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}')
  513. self.assertEqualCallArgs(f, '2, c=4, **{"b":3}')
  514. self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}')
  515. self.assertEqualCallArgs(f, '**UserDict(a=2, b=3, c=4)')
  516. self.assertEqualCallArgs(f, '2, c=4, **UserDict(b=3)')
  517. self.assertEqualCallArgs(f, 'b=2, **UserDict(a=3, c=4)')
  518. # unicode keyword args
  519. self.assertEqualCallArgs(f, 'c=4, **{u"a":2, u"b":3}')
  520. self.assertEqualCallArgs(f, '2, c=4, **{u"b":3}')
  521. self.assertEqualCallArgs(f, 'b=2, **{u"a":3, u"c":4}')
  522. def test_varkw_only(self):
  523. # issue11256:
  524. f = self.makeCallable('**c')
  525. self.assertEqualCallArgs(f, '')
  526. self.assertEqualCallArgs(f, 'a=1')
  527. self.assertEqualCallArgs(f, 'a=1, b=2')
  528. self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}')
  529. self.assertEqualCallArgs(f, '**UserDict(a=1, b=2)')
  530. self.assertEqualCallArgs(f, 'c=3, **UserDict(a=1, b=2)')
  531. def test_tupleargs(self):
  532. f = self.makeCallable('(b,c), (d,(e,f))=(0,[1,2])')
  533. self.assertEqualCallArgs(f, '(2,3)')
  534. self.assertEqualCallArgs(f, '[2,3]')
  535. self.assertEqualCallArgs(f, 'UserList([2,3])')
  536. self.assertEqualCallArgs(f, '(2,3), (4,(5,6))')
  537. self.assertEqualCallArgs(f, '(2,3), (4,[5,6])')
  538. self.assertEqualCallArgs(f, '(2,3), [4,UserList([5,6])]')
  539. def test_multiple_features(self):
  540. f = self.makeCallable('a, b=2, (c,(d,e))=(3,[4,5]), *f, **g')
  541. self.assertEqualCallArgs(f, '2, 3, (4,[5,6]), 7')
  542. self.assertEqualCallArgs(f, '2, 3, *[(4,[5,6]), 7], x=8')
  543. self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
  544. self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
  545. self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
  546. self.assertEqualCallArgs(f, 'x=8, *UserList([2, 3, (4,[5,6])]), '
  547. '**{"y":9, "z":10}')
  548. self.assertEqualCallArgs(f, '2, x=8, *UserList([3, (4,[5,6])]), '
  549. '**UserDict(y=9, z=10)')
  550. def test_errors(self):
  551. f0 = self.makeCallable('')
  552. f1 = self.makeCallable('a, b')
  553. f2 = self.makeCallable('a, b=1')
  554. # f0 takes no arguments
  555. self.assertEqualException(f0, '1')
  556. self.assertEqualException(f0, 'x=1')
  557. self.assertEqualException(f0, '1,x=1')
  558. # f1 takes exactly 2 arguments
  559. self.assertEqualException(f1, '')
  560. self.assertEqualException(f1, '1')
  561. self.assertEqualException(f1, 'a=2')
  562. self.assertEqualException(f1, 'b=3')
  563. # f2 takes at least 1 argument
  564. self.assertEqualException(f2, '')
  565. self.assertEqualException(f2, 'b=3')
  566. for f in f1, f2:
  567. # f1/f2 takes exactly/at most 2 arguments
  568. self.assertEqualException(f, '2, 3, 4')
  569. self.assertEqualException(f, '1, 2, 3, a=1')
  570. self.assertEqualException(f, '2, 3, 4, c=5')
  571. self.assertEqualException(f, '2, 3, 4, a=1, c=5')
  572. # f got an unexpected keyword argument
  573. self.assertEqualException(f, 'c=2')
  574. self.assertEqualException(f, '2, c=3')
  575. self.assertEqualException(f, '2, 3, c=4')
  576. self.assertEqualException(f, '2, c=4, b=3')
  577. self.assertEqualException(f, '**{u"\u03c0\u03b9": 4}')
  578. # f got multiple values for keyword argument
  579. self.assertEqualException(f, '1, a=2')
  580. self.assertEqualException(f, '1, **{"a":2}')
  581. self.assertEqualException(f, '1, 2, b=3')
  582. # XXX: Python inconsistency
  583. # - for functions and bound methods: unexpected keyword 'c'
  584. # - for unbound methods: multiple values for keyword 'a'
  585. #self.assertEqualException(f, '1, c=3, a=2')
  586. f = self.makeCallable('(a,b)=(0,1)')
  587. self.assertEqualException(f, '1')
  588. self.assertEqualException(f, '[1]')
  589. self.assertEqualException(f, '(1,2,3)')
  590. # issue11256:
  591. f3 = self.makeCallable('**c')
  592. self.assertEqualException(f3, '1, 2')
  593. self.assertEqualException(f3, '1, 2, a=1, b=2')
  594. class TestGetcallargsMethods(TestGetcallargsFunctions):
  595. def setUp(self):
  596. class Foo(object):
  597. pass
  598. self.cls = Foo
  599. self.inst = Foo()
  600. def makeCallable(self, signature):
  601. assert 'self' not in signature
  602. mk = super(TestGetcallargsMethods, self).makeCallable
  603. self.cls.method = mk('self, ' + signature)
  604. return self.inst.method
  605. class TestGetcallargsUnboundMethods(TestGetcallargsMethods):
  606. def makeCallable(self, signature):
  607. super(TestGetcallargsUnboundMethods, self).makeCallable(signature)
  608. return self.cls.method
  609. def assertEqualCallArgs(self, func, call_params_string, locs=None):
  610. return super(TestGetcallargsUnboundMethods, self).assertEqualCallArgs(
  611. *self._getAssertEqualParams(func, call_params_string, locs))
  612. def assertEqualException(self, func, call_params_string, locs=None):
  613. return super(TestGetcallargsUnboundMethods, self).assertEqualException(
  614. *self._getAssertEqualParams(func, call_params_string, locs))
  615. def _getAssertEqualParams(self, func, call_params_string, locs=None):
  616. assert 'inst' not in call_params_string
  617. locs = dict(locs or {}, inst=self.inst)
  618. return (func, 'inst,' + call_params_string, locs)
  619. def test_main():
  620. run_unittest(
  621. TestDecorators, TestRetrievingSourceCode, TestOneliners, TestBuggyCases,
  622. TestInterpreterStack, TestClassesAndFunctions, TestPredicates,
  623. TestGetcallargsFunctions, TestGetcallargsMethods,
  624. TestGetcallargsUnboundMethods)
  625. if __name__ == "__main__":
  626. test_main()