PageRenderTime 112ms CodeModel.GetById 32ms RepoModel.GetById 2ms app.codeStats 0ms

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

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