test_call.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. import unittest
  2. from test.support import cpython_only
  3. try:
  4. import _testcapi
  5. except ImportError:
  6. _testcapi = None
  7. import struct
  8. import collections
  9. import itertools
  10. import gc
  11. import contextlib
  12. class BadStr(str):
  13. def __eq__(self, other):
  14. return True
  15. def __hash__(self):
  16. # Guaranteed different hash
  17. return str.__hash__(self) ^ 3
  18. class FunctionCalls(unittest.TestCase):
  19. def test_kwargs_order(self):
  20. # bpo-34320: **kwargs should preserve order of passed OrderedDict
  21. od = collections.OrderedDict([('a', 1), ('b', 2)])
  22. od.move_to_end('a')
  23. expected = list(od.items())
  24. def fn(**kw):
  25. return kw
  26. res = fn(**od)
  27. self.assertIsInstance(res, dict)
  28. self.assertEqual(list(res.items()), expected)
  29. def test_frames_are_popped_after_failed_calls(self):
  30. # GH-93252: stuff blows up if we don't pop the new frame after
  31. # recovering from failed calls:
  32. def f():
  33. pass
  34. for _ in range(1000):
  35. try:
  36. f(None)
  37. except TypeError:
  38. pass
  39. # BOOM!
  40. @cpython_only
  41. class CFunctionCallsErrorMessages(unittest.TestCase):
  42. def test_varargs0(self):
  43. msg = r"__contains__\(\) takes exactly one argument \(0 given\)"
  44. self.assertRaisesRegex(TypeError, msg, {}.__contains__)
  45. def test_varargs2(self):
  46. msg = r"__contains__\(\) takes exactly one argument \(2 given\)"
  47. self.assertRaisesRegex(TypeError, msg, {}.__contains__, 0, 1)
  48. def test_varargs3(self):
  49. msg = r"^from_bytes\(\) takes at most 2 positional arguments \(3 given\)"
  50. self.assertRaisesRegex(TypeError, msg, int.from_bytes, b'a', 'little', False)
  51. def test_varargs1min(self):
  52. msg = r"get expected at least 1 argument, got 0"
  53. self.assertRaisesRegex(TypeError, msg, {}.get)
  54. msg = r"expected 1 argument, got 0"
  55. self.assertRaisesRegex(TypeError, msg, {}.__delattr__)
  56. def test_varargs2min(self):
  57. msg = r"getattr expected at least 2 arguments, got 0"
  58. self.assertRaisesRegex(TypeError, msg, getattr)
  59. def test_varargs1max(self):
  60. msg = r"input expected at most 1 argument, got 2"
  61. self.assertRaisesRegex(TypeError, msg, input, 1, 2)
  62. def test_varargs2max(self):
  63. msg = r"get expected at most 2 arguments, got 3"
  64. self.assertRaisesRegex(TypeError, msg, {}.get, 1, 2, 3)
  65. def test_varargs1_kw(self):
  66. msg = r"__contains__\(\) takes no keyword arguments"
  67. self.assertRaisesRegex(TypeError, msg, {}.__contains__, x=2)
  68. def test_varargs2_kw(self):
  69. msg = r"__contains__\(\) takes no keyword arguments"
  70. self.assertRaisesRegex(TypeError, msg, {}.__contains__, x=2, y=2)
  71. def test_varargs3_kw(self):
  72. msg = r"bool\(\) takes no keyword arguments"
  73. self.assertRaisesRegex(TypeError, msg, bool, x=2)
  74. def test_varargs4_kw(self):
  75. msg = r"^list[.]index\(\) takes no keyword arguments$"
  76. self.assertRaisesRegex(TypeError, msg, [].index, x=2)
  77. def test_varargs5_kw(self):
  78. msg = r"^hasattr\(\) takes no keyword arguments$"
  79. self.assertRaisesRegex(TypeError, msg, hasattr, x=2)
  80. def test_varargs6_kw(self):
  81. msg = r"^getattr\(\) takes no keyword arguments$"
  82. self.assertRaisesRegex(TypeError, msg, getattr, x=2)
  83. def test_varargs7_kw(self):
  84. msg = r"^next\(\) takes no keyword arguments$"
  85. self.assertRaisesRegex(TypeError, msg, next, x=2)
  86. def test_varargs8_kw(self):
  87. msg = r"^_struct[.]pack\(\) takes no keyword arguments$"
  88. self.assertRaisesRegex(TypeError, msg, struct.pack, x=2)
  89. def test_varargs9_kw(self):
  90. msg = r"^_struct[.]pack_into\(\) takes no keyword arguments$"
  91. self.assertRaisesRegex(TypeError, msg, struct.pack_into, x=2)
  92. def test_varargs10_kw(self):
  93. msg = r"^deque[.]index\(\) takes no keyword arguments$"
  94. self.assertRaisesRegex(TypeError, msg, collections.deque().index, x=2)
  95. def test_varargs11_kw(self):
  96. msg = r"^Struct[.]pack\(\) takes no keyword arguments$"
  97. self.assertRaisesRegex(TypeError, msg, struct.Struct.pack, struct.Struct(""), x=2)
  98. def test_varargs12_kw(self):
  99. msg = r"^staticmethod\(\) takes no keyword arguments$"
  100. self.assertRaisesRegex(TypeError, msg, staticmethod, func=id)
  101. def test_varargs13_kw(self):
  102. msg = r"^classmethod\(\) takes no keyword arguments$"
  103. self.assertRaisesRegex(TypeError, msg, classmethod, func=id)
  104. def test_varargs14_kw(self):
  105. msg = r"^product\(\) takes at most 1 keyword argument \(2 given\)$"
  106. self.assertRaisesRegex(TypeError, msg,
  107. itertools.product, 0, repeat=1, foo=2)
  108. def test_varargs15_kw(self):
  109. msg = r"^ImportError\(\) takes at most 2 keyword arguments \(3 given\)$"
  110. self.assertRaisesRegex(TypeError, msg,
  111. ImportError, 0, name=1, path=2, foo=3)
  112. def test_varargs16_kw(self):
  113. msg = r"^min\(\) takes at most 2 keyword arguments \(3 given\)$"
  114. self.assertRaisesRegex(TypeError, msg,
  115. min, 0, default=1, key=2, foo=3)
  116. def test_varargs17_kw(self):
  117. msg = r"'foo' is an invalid keyword argument for print\(\)$"
  118. self.assertRaisesRegex(TypeError, msg,
  119. print, 0, sep=1, end=2, file=3, flush=4, foo=5)
  120. def test_varargs18_kw(self):
  121. # _PyArg_UnpackKeywordsWithVararg()
  122. msg = r"invalid keyword argument for print\(\)$"
  123. with self.assertRaisesRegex(TypeError, msg):
  124. print(0, 1, **{BadStr('foo'): ','})
  125. def test_varargs19_kw(self):
  126. # _PyArg_UnpackKeywords()
  127. msg = r"invalid keyword argument for round\(\)$"
  128. with self.assertRaisesRegex(TypeError, msg):
  129. round(1.75, **{BadStr('foo'): 1})
  130. def test_oldargs0_1(self):
  131. msg = r"keys\(\) takes no arguments \(1 given\)"
  132. self.assertRaisesRegex(TypeError, msg, {}.keys, 0)
  133. def test_oldargs0_2(self):
  134. msg = r"keys\(\) takes no arguments \(2 given\)"
  135. self.assertRaisesRegex(TypeError, msg, {}.keys, 0, 1)
  136. def test_oldargs0_1_kw(self):
  137. msg = r"keys\(\) takes no keyword arguments"
  138. self.assertRaisesRegex(TypeError, msg, {}.keys, x=2)
  139. def test_oldargs0_2_kw(self):
  140. msg = r"keys\(\) takes no keyword arguments"
  141. self.assertRaisesRegex(TypeError, msg, {}.keys, x=2, y=2)
  142. def test_oldargs1_0(self):
  143. msg = r"count\(\) takes exactly one argument \(0 given\)"
  144. self.assertRaisesRegex(TypeError, msg, [].count)
  145. def test_oldargs1_2(self):
  146. msg = r"count\(\) takes exactly one argument \(2 given\)"
  147. self.assertRaisesRegex(TypeError, msg, [].count, 1, 2)
  148. def test_oldargs1_0_kw(self):
  149. msg = r"count\(\) takes no keyword arguments"
  150. self.assertRaisesRegex(TypeError, msg, [].count, x=2)
  151. def test_oldargs1_1_kw(self):
  152. msg = r"count\(\) takes no keyword arguments"
  153. self.assertRaisesRegex(TypeError, msg, [].count, {}, x=2)
  154. def test_oldargs1_2_kw(self):
  155. msg = r"count\(\) takes no keyword arguments"
  156. self.assertRaisesRegex(TypeError, msg, [].count, x=2, y=2)
  157. class TestCallingConventions(unittest.TestCase):
  158. """Test calling using various C calling conventions (METH_*) from Python
  159. Subclasses test several kinds of functions (module-level, methods,
  160. class methods static methods) using these attributes:
  161. obj: the object that contains tested functions (as attributes)
  162. expected_self: expected "self" argument to the C function
  163. The base class tests module-level functions.
  164. """
  165. def setUp(self):
  166. self.obj = self.expected_self = _testcapi
  167. def test_varargs(self):
  168. self.assertEqual(
  169. self.obj.meth_varargs(1, 2, 3),
  170. (self.expected_self, (1, 2, 3)),
  171. )
  172. def test_varargs_ext(self):
  173. self.assertEqual(
  174. self.obj.meth_varargs(*(1, 2, 3)),
  175. (self.expected_self, (1, 2, 3)),
  176. )
  177. def test_varargs_error_kw(self):
  178. msg = r"meth_varargs\(\) takes no keyword arguments"
  179. self.assertRaisesRegex(
  180. TypeError, msg, lambda: self.obj.meth_varargs(k=1),
  181. )
  182. def test_varargs_keywords(self):
  183. self.assertEqual(
  184. self.obj.meth_varargs_keywords(1, 2, a=3, b=4),
  185. (self.expected_self, (1, 2), {'a': 3, 'b': 4})
  186. )
  187. def test_varargs_keywords_ext(self):
  188. self.assertEqual(
  189. self.obj.meth_varargs_keywords(*[1, 2], **{'a': 3, 'b': 4}),
  190. (self.expected_self, (1, 2), {'a': 3, 'b': 4})
  191. )
  192. def test_o(self):
  193. self.assertEqual(self.obj.meth_o(1), (self.expected_self, 1))
  194. def test_o_ext(self):
  195. self.assertEqual(self.obj.meth_o(*[1]), (self.expected_self, 1))
  196. def test_o_error_no_arg(self):
  197. msg = r"meth_o\(\) takes exactly one argument \(0 given\)"
  198. self.assertRaisesRegex(TypeError, msg, self.obj.meth_o)
  199. def test_o_error_two_args(self):
  200. msg = r"meth_o\(\) takes exactly one argument \(2 given\)"
  201. self.assertRaisesRegex(
  202. TypeError, msg, lambda: self.obj.meth_o(1, 2),
  203. )
  204. def test_o_error_ext(self):
  205. msg = r"meth_o\(\) takes exactly one argument \(3 given\)"
  206. self.assertRaisesRegex(
  207. TypeError, msg, lambda: self.obj.meth_o(*(1, 2, 3)),
  208. )
  209. def test_o_error_kw(self):
  210. msg = r"meth_o\(\) takes no keyword arguments"
  211. self.assertRaisesRegex(
  212. TypeError, msg, lambda: self.obj.meth_o(k=1),
  213. )
  214. def test_o_error_arg_kw(self):
  215. msg = r"meth_o\(\) takes no keyword arguments"
  216. self.assertRaisesRegex(
  217. TypeError, msg, lambda: self.obj.meth_o(k=1),
  218. )
  219. def test_noargs(self):
  220. self.assertEqual(self.obj.meth_noargs(), self.expected_self)
  221. def test_noargs_ext(self):
  222. self.assertEqual(self.obj.meth_noargs(*[]), self.expected_self)
  223. def test_noargs_error_arg(self):
  224. msg = r"meth_noargs\(\) takes no arguments \(1 given\)"
  225. self.assertRaisesRegex(
  226. TypeError, msg, lambda: self.obj.meth_noargs(1),
  227. )
  228. def test_noargs_error_arg2(self):
  229. msg = r"meth_noargs\(\) takes no arguments \(2 given\)"
  230. self.assertRaisesRegex(
  231. TypeError, msg, lambda: self.obj.meth_noargs(1, 2),
  232. )
  233. def test_noargs_error_ext(self):
  234. msg = r"meth_noargs\(\) takes no arguments \(3 given\)"
  235. self.assertRaisesRegex(
  236. TypeError, msg, lambda: self.obj.meth_noargs(*(1, 2, 3)),
  237. )
  238. def test_noargs_error_kw(self):
  239. msg = r"meth_noargs\(\) takes no keyword arguments"
  240. self.assertRaisesRegex(
  241. TypeError, msg, lambda: self.obj.meth_noargs(k=1),
  242. )
  243. def test_fastcall(self):
  244. self.assertEqual(
  245. self.obj.meth_fastcall(1, 2, 3),
  246. (self.expected_self, (1, 2, 3)),
  247. )
  248. def test_fastcall_ext(self):
  249. self.assertEqual(
  250. self.obj.meth_fastcall(*(1, 2, 3)),
  251. (self.expected_self, (1, 2, 3)),
  252. )
  253. def test_fastcall_error_kw(self):
  254. msg = r"meth_fastcall\(\) takes no keyword arguments"
  255. self.assertRaisesRegex(
  256. TypeError, msg, lambda: self.obj.meth_fastcall(k=1),
  257. )
  258. def test_fastcall_keywords(self):
  259. self.assertEqual(
  260. self.obj.meth_fastcall_keywords(1, 2, a=3, b=4),
  261. (self.expected_self, (1, 2), {'a': 3, 'b': 4})
  262. )
  263. def test_fastcall_keywords_ext(self):
  264. self.assertEqual(
  265. self.obj.meth_fastcall_keywords(*(1, 2), **{'a': 3, 'b': 4}),
  266. (self.expected_self, (1, 2), {'a': 3, 'b': 4})
  267. )
  268. class TestCallingConventionsInstance(TestCallingConventions):
  269. """Test calling instance methods using various calling conventions"""
  270. def setUp(self):
  271. self.obj = self.expected_self = _testcapi.MethInstance()
  272. class TestCallingConventionsClass(TestCallingConventions):
  273. """Test calling class methods using various calling conventions"""
  274. def setUp(self):
  275. self.obj = self.expected_self = _testcapi.MethClass
  276. class TestCallingConventionsClassInstance(TestCallingConventions):
  277. """Test calling class methods on instance"""
  278. def setUp(self):
  279. self.obj = _testcapi.MethClass()
  280. self.expected_self = _testcapi.MethClass
  281. class TestCallingConventionsStatic(TestCallingConventions):
  282. """Test calling static methods using various calling conventions"""
  283. def setUp(self):
  284. self.obj = _testcapi.MethStatic()
  285. self.expected_self = None
  286. def pyfunc(arg1, arg2):
  287. return [arg1, arg2]
  288. def pyfunc_noarg():
  289. return "noarg"
  290. class PythonClass:
  291. def method(self, arg1, arg2):
  292. return [arg1, arg2]
  293. def method_noarg(self):
  294. return "noarg"
  295. @classmethod
  296. def class_method(cls):
  297. return "classmethod"
  298. @staticmethod
  299. def static_method():
  300. return "staticmethod"
  301. PYTHON_INSTANCE = PythonClass()
  302. NULL_OR_EMPTY = object()
  303. class FastCallTests(unittest.TestCase):
  304. """Test calling using various callables from C
  305. """
  306. # Test calls with positional arguments
  307. CALLS_POSARGS = [
  308. # (func, args: tuple, result)
  309. # Python function with 2 arguments
  310. (pyfunc, (1, 2), [1, 2]),
  311. # Python function without argument
  312. (pyfunc_noarg, (), "noarg"),
  313. # Python class methods
  314. (PythonClass.class_method, (), "classmethod"),
  315. (PythonClass.static_method, (), "staticmethod"),
  316. # Python instance methods
  317. (PYTHON_INSTANCE.method, (1, 2), [1, 2]),
  318. (PYTHON_INSTANCE.method_noarg, (), "noarg"),
  319. (PYTHON_INSTANCE.class_method, (), "classmethod"),
  320. (PYTHON_INSTANCE.static_method, (), "staticmethod"),
  321. # C callables are added later
  322. ]
  323. # Test calls with positional and keyword arguments
  324. CALLS_KWARGS = [
  325. # (func, args: tuple, kwargs: dict, result)
  326. # Python function with 2 arguments
  327. (pyfunc, (1,), {'arg2': 2}, [1, 2]),
  328. (pyfunc, (), {'arg1': 1, 'arg2': 2}, [1, 2]),
  329. # Python instance methods
  330. (PYTHON_INSTANCE.method, (1,), {'arg2': 2}, [1, 2]),
  331. (PYTHON_INSTANCE.method, (), {'arg1': 1, 'arg2': 2}, [1, 2]),
  332. # C callables are added later
  333. ]
  334. # Add all the calling conventions and variants of C callables
  335. _instance = _testcapi.MethInstance()
  336. for obj, expected_self in (
  337. (_testcapi, _testcapi), # module-level function
  338. (_instance, _instance), # bound method
  339. (_testcapi.MethClass, _testcapi.MethClass), # class method on class
  340. (_testcapi.MethClass(), _testcapi.MethClass), # class method on inst.
  341. (_testcapi.MethStatic, None), # static method
  342. ):
  343. CALLS_POSARGS.extend([
  344. (obj.meth_varargs, (1, 2), (expected_self, (1, 2))),
  345. (obj.meth_varargs_keywords,
  346. (1, 2), (expected_self, (1, 2), NULL_OR_EMPTY)),
  347. (obj.meth_fastcall, (1, 2), (expected_self, (1, 2))),
  348. (obj.meth_fastcall, (), (expected_self, ())),
  349. (obj.meth_fastcall_keywords,
  350. (1, 2), (expected_self, (1, 2), NULL_OR_EMPTY)),
  351. (obj.meth_fastcall_keywords,
  352. (), (expected_self, (), NULL_OR_EMPTY)),
  353. (obj.meth_noargs, (), expected_self),
  354. (obj.meth_o, (123, ), (expected_self, 123)),
  355. ])
  356. CALLS_KWARGS.extend([
  357. (obj.meth_varargs_keywords,
  358. (1, 2), {'x': 'y'}, (expected_self, (1, 2), {'x': 'y'})),
  359. (obj.meth_varargs_keywords,
  360. (), {'x': 'y'}, (expected_self, (), {'x': 'y'})),
  361. (obj.meth_varargs_keywords,
  362. (1, 2), {}, (expected_self, (1, 2), NULL_OR_EMPTY)),
  363. (obj.meth_fastcall_keywords,
  364. (1, 2), {'x': 'y'}, (expected_self, (1, 2), {'x': 'y'})),
  365. (obj.meth_fastcall_keywords,
  366. (), {'x': 'y'}, (expected_self, (), {'x': 'y'})),
  367. (obj.meth_fastcall_keywords,
  368. (1, 2), {}, (expected_self, (1, 2), NULL_OR_EMPTY)),
  369. ])
  370. def check_result(self, result, expected):
  371. if isinstance(expected, tuple) and expected[-1] is NULL_OR_EMPTY:
  372. if result[-1] in ({}, None):
  373. expected = (*expected[:-1], result[-1])
  374. self.assertEqual(result, expected)
  375. def test_fastcall(self):
  376. # Test _PyObject_FastCall()
  377. for func, args, expected in self.CALLS_POSARGS:
  378. with self.subTest(func=func, args=args):
  379. result = _testcapi.pyobject_fastcall(func, args)
  380. self.check_result(result, expected)
  381. if not args:
  382. # args=NULL, nargs=0
  383. result = _testcapi.pyobject_fastcall(func, None)
  384. self.check_result(result, expected)
  385. def test_vectorcall_dict(self):
  386. # Test PyObject_VectorcallDict()
  387. for func, args, expected in self.CALLS_POSARGS:
  388. with self.subTest(func=func, args=args):
  389. # kwargs=NULL
  390. result = _testcapi.pyobject_fastcalldict(func, args, None)
  391. self.check_result(result, expected)
  392. if not args:
  393. # args=NULL, nargs=0, kwargs=NULL
  394. result = _testcapi.pyobject_fastcalldict(func, None, None)
  395. self.check_result(result, expected)
  396. for func, args, kwargs, expected in self.CALLS_KWARGS:
  397. with self.subTest(func=func, args=args, kwargs=kwargs):
  398. result = _testcapi.pyobject_fastcalldict(func, args, kwargs)
  399. self.check_result(result, expected)
  400. def test_vectorcall(self):
  401. # Test PyObject_Vectorcall()
  402. for func, args, expected in self.CALLS_POSARGS:
  403. with self.subTest(func=func, args=args):
  404. # kwnames=NULL
  405. result = _testcapi.pyobject_vectorcall(func, args, None)
  406. self.check_result(result, expected)
  407. # kwnames=()
  408. result = _testcapi.pyobject_vectorcall(func, args, ())
  409. self.check_result(result, expected)
  410. if not args:
  411. # kwnames=NULL
  412. result = _testcapi.pyobject_vectorcall(func, None, None)
  413. self.check_result(result, expected)
  414. # kwnames=()
  415. result = _testcapi.pyobject_vectorcall(func, None, ())
  416. self.check_result(result, expected)
  417. for func, args, kwargs, expected in self.CALLS_KWARGS:
  418. with self.subTest(func=func, args=args, kwargs=kwargs):
  419. kwnames = tuple(kwargs.keys())
  420. args = args + tuple(kwargs.values())
  421. result = _testcapi.pyobject_vectorcall(func, args, kwnames)
  422. self.check_result(result, expected)
  423. def test_fastcall_clearing_dict(self):
  424. # Test bpo-36907: the point of the test is just checking that this
  425. # does not crash.
  426. class IntWithDict:
  427. __slots__ = ["kwargs"]
  428. def __init__(self, **kwargs):
  429. self.kwargs = kwargs
  430. def __index__(self):
  431. self.kwargs.clear()
  432. gc.collect()
  433. return 0
  434. x = IntWithDict(optimize=IntWithDict())
  435. # We test the argument handling of "compile" here, the compilation
  436. # itself is not relevant. When we pass flags=x below, x.__index__() is
  437. # called, which changes the keywords dict.
  438. compile("pass", "", "exec", x, **x.kwargs)
  439. Py_TPFLAGS_HAVE_VECTORCALL = 1 << 11
  440. Py_TPFLAGS_METHOD_DESCRIPTOR = 1 << 17
  441. def testfunction(self):
  442. """some doc"""
  443. return self
  444. def testfunction_kw(self, *, kw):
  445. """some doc"""
  446. return self
  447. class TestPEP590(unittest.TestCase):
  448. def test_method_descriptor_flag(self):
  449. import functools
  450. cached = functools.lru_cache(1)(testfunction)
  451. self.assertFalse(type(repr).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  452. self.assertTrue(type(list.append).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  453. self.assertTrue(type(list.__add__).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  454. self.assertTrue(type(testfunction).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  455. self.assertTrue(type(cached).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  456. self.assertTrue(_testcapi.MethodDescriptorBase.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  457. self.assertTrue(_testcapi.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  458. self.assertFalse(_testcapi.MethodDescriptorNopGet.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  459. # Mutable heap types should not inherit Py_TPFLAGS_METHOD_DESCRIPTOR
  460. class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
  461. pass
  462. self.assertFalse(MethodDescriptorHeap.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
  463. def test_vectorcall_flag(self):
  464. self.assertTrue(_testcapi.MethodDescriptorBase.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
  465. self.assertTrue(_testcapi.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
  466. self.assertFalse(_testcapi.MethodDescriptorNopGet.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
  467. self.assertTrue(_testcapi.MethodDescriptor2.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
  468. # Mutable heap types should not inherit Py_TPFLAGS_HAVE_VECTORCALL
  469. class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
  470. pass
  471. self.assertFalse(MethodDescriptorHeap.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
  472. def test_vectorcall_override(self):
  473. # Check that tp_call can correctly override vectorcall.
  474. # MethodDescriptorNopGet implements tp_call but it inherits from
  475. # MethodDescriptorBase, which implements vectorcall. Since
  476. # MethodDescriptorNopGet returns the args tuple when called, we check
  477. # additionally that no new tuple is created for this call.
  478. args = tuple(range(5))
  479. f = _testcapi.MethodDescriptorNopGet()
  480. self.assertIs(f(*args), args)
  481. def test_vectorcall(self):
  482. # Test a bunch of different ways to call objects:
  483. # 1. vectorcall using PyVectorcall_Call()
  484. # (only for objects that support vectorcall directly)
  485. # 2. normal call
  486. # 3. vectorcall using PyObject_Vectorcall()
  487. # 4. call as bound method
  488. # 5. call using functools.partial
  489. # A list of (function, args, kwargs, result) calls to test
  490. calls = [(len, (range(42),), {}, 42),
  491. (list.append, ([], 0), {}, None),
  492. ([].append, (0,), {}, None),
  493. (sum, ([36],), {"start":6}, 42),
  494. (testfunction, (42,), {}, 42),
  495. (testfunction_kw, (42,), {"kw":None}, 42),
  496. (_testcapi.MethodDescriptorBase(), (0,), {}, True),
  497. (_testcapi.MethodDescriptorDerived(), (0,), {}, True),
  498. (_testcapi.MethodDescriptor2(), (0,), {}, False)]
  499. from _testcapi import pyobject_vectorcall, pyvectorcall_call
  500. from types import MethodType
  501. from functools import partial
  502. def vectorcall(func, args, kwargs):
  503. args = *args, *kwargs.values()
  504. kwnames = tuple(kwargs)
  505. return pyobject_vectorcall(func, args, kwnames)
  506. for (func, args, kwargs, expected) in calls:
  507. with self.subTest(str(func)):
  508. if not kwargs:
  509. self.assertEqual(expected, pyvectorcall_call(func, args))
  510. self.assertEqual(expected, pyvectorcall_call(func, args, kwargs))
  511. # Add derived classes (which do not support vectorcall directly,
  512. # but do support all other ways of calling).
  513. class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
  514. pass
  515. class MethodDescriptorOverridden(_testcapi.MethodDescriptorBase):
  516. def __call__(self, n):
  517. return 'new'
  518. class SuperBase:
  519. def __call__(self, *args):
  520. return super().__call__(*args)
  521. class MethodDescriptorSuper(SuperBase, _testcapi.MethodDescriptorBase):
  522. def __call__(self, *args):
  523. return super().__call__(*args)
  524. calls += [
  525. (dict.update, ({},), {"key":True}, None),
  526. ({}.update, ({},), {"key":True}, None),
  527. (MethodDescriptorHeap(), (0,), {}, True),
  528. (MethodDescriptorOverridden(), (0,), {}, 'new'),
  529. (MethodDescriptorSuper(), (0,), {}, True),
  530. ]
  531. for (func, args, kwargs, expected) in calls:
  532. with self.subTest(str(func)):
  533. args1 = args[1:]
  534. meth = MethodType(func, args[0])
  535. wrapped = partial(func)
  536. if not kwargs:
  537. self.assertEqual(expected, func(*args))
  538. self.assertEqual(expected, pyobject_vectorcall(func, args, None))
  539. self.assertEqual(expected, meth(*args1))
  540. self.assertEqual(expected, wrapped(*args))
  541. self.assertEqual(expected, func(*args, **kwargs))
  542. self.assertEqual(expected, vectorcall(func, args, kwargs))
  543. self.assertEqual(expected, meth(*args1, **kwargs))
  544. self.assertEqual(expected, wrapped(*args, **kwargs))
  545. class A:
  546. def method_two_args(self, x, y):
  547. pass
  548. @staticmethod
  549. def static_no_args():
  550. pass
  551. @staticmethod
  552. def positional_only(arg, /):
  553. pass
  554. @cpython_only
  555. class TestErrorMessagesUseQualifiedName(unittest.TestCase):
  556. @contextlib.contextmanager
  557. def check_raises_type_error(self, message):
  558. with self.assertRaises(TypeError) as cm:
  559. yield
  560. self.assertEqual(str(cm.exception), message)
  561. def test_missing_arguments(self):
  562. msg = "A.method_two_args() missing 1 required positional argument: 'y'"
  563. with self.check_raises_type_error(msg):
  564. A().method_two_args("x")
  565. def test_too_many_positional(self):
  566. msg = "A.static_no_args() takes 0 positional arguments but 1 was given"
  567. with self.check_raises_type_error(msg):
  568. A.static_no_args("oops it's an arg")
  569. def test_positional_only_passed_as_keyword(self):
  570. msg = "A.positional_only() got some positional-only arguments passed as keyword arguments: 'arg'"
  571. with self.check_raises_type_error(msg):
  572. A.positional_only(arg="x")
  573. def test_unexpected_keyword(self):
  574. msg = "A.method_two_args() got an unexpected keyword argument 'bad'"
  575. with self.check_raises_type_error(msg):
  576. A().method_two_args(bad="x")
  577. def test_multiple_values(self):
  578. msg = "A.method_two_args() got multiple values for argument 'x'"
  579. with self.check_raises_type_error(msg):
  580. A().method_two_args("x", "y", x="oops")
  581. if __name__ == "__main__":
  582. unittest.main()