Nick Coghlan | f9e227e | 2014-08-17 14:01:19 +1000 | [diff] [blame] | 1 | import builtins |
Guido van Rossum | 813b0e5 | 2007-05-21 18:11:34 +0000 | [diff] [blame] | 2 | import collections |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 3 | import datetime |
Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 4 | import functools |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 5 | import importlib |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 6 | import inspect |
| 7 | import io |
| 8 | import linecache |
| 9 | import os |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 10 | from os.path import normcase |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 11 | import _pickle |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 12 | import pickle |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 13 | import re |
| 14 | import shutil |
| 15 | import sys |
| 16 | import types |
Yury Selivanov | ef1e750 | 2014-12-08 16:05:34 -0500 | [diff] [blame] | 17 | import textwrap |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 18 | import unicodedata |
| 19 | import unittest |
Yury Selivanov | a773de0 | 2014-02-21 18:30:53 -0500 | [diff] [blame] | 20 | import unittest.mock |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 21 | import warnings |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 22 | |
Brett Cannon | 634a8fc | 2013-10-02 10:25:42 -0400 | [diff] [blame] | 23 | try: |
| 24 | from concurrent.futures import ThreadPoolExecutor |
| 25 | except ImportError: |
| 26 | ThreadPoolExecutor = None |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 27 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 28 | from test.support import run_unittest, TESTFN, DirsOnSysPath, cpython_only |
Nick Coghlan | f9e227e | 2014-08-17 14:01:19 +1000 | [diff] [blame] | 29 | from test.support import MISSING_C_DOCSTRINGS, cpython_only |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 30 | from test.support.script_helper import assert_python_ok, assert_python_failure |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 31 | from test import inspect_fodder as mod |
| 32 | from test import inspect_fodder2 as mod2 |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 33 | |
Yury Selivanov | ef1e750 | 2014-12-08 16:05:34 -0500 | [diff] [blame] | 34 | from test.test_import import _ready_to_import |
| 35 | |
R. David Murray | 74b8924 | 2009-05-13 17:33:03 +0000 | [diff] [blame] | 36 | |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 37 | # Functions tested in this suite: |
| 38 | # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 39 | # isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers, |
| 40 | # getdoc, getfile, getmodule, getsourcefile, getcomments, getsource, |
| 41 | # getclasstree, getargspec, getargvalues, formatargspec, formatargvalues, |
| 42 | # currentframe, stack, trace, isdatadescriptor |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 43 | |
Nick Coghlan | f088e5e | 2008-12-14 11:50:48 +0000 | [diff] [blame] | 44 | # NOTE: There are some additional tests relating to interaction with |
| 45 | # zipimport in the test_zipimport_support test module. |
| 46 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 47 | modfile = mod.__file__ |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 48 | if modfile.endswith(('c', 'o')): |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 49 | modfile = modfile[:-1] |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 50 | |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 51 | # Normalize file names: on Windows, the case of file names of compiled |
| 52 | # modules depends on the path used to start the python executable. |
| 53 | modfile = normcase(modfile) |
| 54 | |
| 55 | def revise(filename, *args): |
| 56 | return (normcase(filename),) + args |
| 57 | |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 58 | import builtins |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 59 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 60 | git = mod.StupidGit() |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 61 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 62 | class IsTestBase(unittest.TestCase): |
| 63 | predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, |
| 64 | inspect.isframe, inspect.isfunction, inspect.ismethod, |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 65 | inspect.ismodule, inspect.istraceback, |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 66 | inspect.isgenerator, inspect.isgeneratorfunction, |
| 67 | inspect.iscoroutine, inspect.iscoroutinefunction]) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 68 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 69 | def istest(self, predicate, exp): |
| 70 | obj = eval(exp) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 71 | self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 72 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 73 | for other in self.predicates - set([predicate]): |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 74 | if (predicate == inspect.isgeneratorfunction or \ |
| 75 | predicate == inspect.iscoroutinefunction) and \ |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 76 | other == inspect.isfunction: |
| 77 | continue |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 78 | self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 79 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 80 | def generator_function_example(self): |
| 81 | for i in range(2): |
| 82 | yield i |
| 83 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 84 | async def coroutine_function_example(self): |
| 85 | return 'spam' |
| 86 | |
| 87 | @types.coroutine |
| 88 | def gen_coroutine_function_example(self): |
| 89 | yield |
| 90 | return 'spam' |
| 91 | |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 92 | class EqualsToAll: |
| 93 | def __eq__(self, other): |
| 94 | return True |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 95 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 96 | class TestPredicates(IsTestBase): |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 97 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 98 | def test_excluding_predicates(self): |
Antoine Pitrou | d5a1a21 | 2012-06-17 23:18:07 +0200 | [diff] [blame] | 99 | global tb |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 100 | self.istest(inspect.isbuiltin, 'sys.exit') |
| 101 | self.istest(inspect.isbuiltin, '[].append') |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 102 | self.istest(inspect.iscode, 'mod.spam.__code__') |
Antoine Pitrou | d5a1a21 | 2012-06-17 23:18:07 +0200 | [diff] [blame] | 103 | try: |
| 104 | 1/0 |
| 105 | except: |
| 106 | tb = sys.exc_info()[2] |
| 107 | self.istest(inspect.isframe, 'tb.tb_frame') |
| 108 | self.istest(inspect.istraceback, 'tb') |
| 109 | if hasattr(types, 'GetSetDescriptorType'): |
| 110 | self.istest(inspect.isgetsetdescriptor, |
| 111 | 'type(tb.tb_frame).f_locals') |
| 112 | else: |
| 113 | self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) |
| 114 | finally: |
| 115 | # Clear traceback and all the frames and local variables hanging to it. |
| 116 | tb = None |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 117 | self.istest(inspect.isfunction, 'mod.spam') |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 118 | self.istest(inspect.isfunction, 'mod.StupidGit.abuse') |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 119 | self.istest(inspect.ismethod, 'git.argue') |
| 120 | self.istest(inspect.ismodule, 'mod') |
Guido van Rossum | 813b0e5 | 2007-05-21 18:11:34 +0000 | [diff] [blame] | 121 | self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory') |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 122 | self.istest(inspect.isgenerator, '(x for x in range(2))') |
| 123 | self.istest(inspect.isgeneratorfunction, 'generator_function_example') |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 124 | |
| 125 | with warnings.catch_warnings(): |
| 126 | warnings.simplefilter("ignore") |
| 127 | self.istest(inspect.iscoroutine, 'coroutine_function_example(1)') |
| 128 | self.istest(inspect.iscoroutinefunction, 'coroutine_function_example') |
| 129 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 130 | if hasattr(types, 'MemberDescriptorType'): |
| 131 | self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') |
| 132 | else: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 133 | self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 134 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 135 | def test_iscoroutine(self): |
| 136 | gen_coro = gen_coroutine_function_example(1) |
| 137 | coro = coroutine_function_example(1) |
| 138 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 139 | self.assertFalse( |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 140 | inspect.iscoroutinefunction(gen_coroutine_function_example)) |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 141 | self.assertFalse(inspect.iscoroutine(gen_coro)) |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 142 | |
| 143 | self.assertTrue( |
| 144 | inspect.isgeneratorfunction(gen_coroutine_function_example)) |
| 145 | self.assertTrue(inspect.isgenerator(gen_coro)) |
| 146 | |
| 147 | self.assertTrue( |
| 148 | inspect.iscoroutinefunction(coroutine_function_example)) |
| 149 | self.assertTrue(inspect.iscoroutine(coro)) |
| 150 | |
| 151 | self.assertFalse( |
| 152 | inspect.isgeneratorfunction(coroutine_function_example)) |
| 153 | self.assertFalse(inspect.isgenerator(coro)) |
| 154 | |
| 155 | coro.close(); gen_coro.close() # silence warnings |
| 156 | |
Yury Selivanov | fdbeb2b | 2015-07-03 13:11:35 -0400 | [diff] [blame] | 157 | def test_isawaitable(self): |
| 158 | def gen(): yield |
| 159 | self.assertFalse(inspect.isawaitable(gen())) |
| 160 | |
| 161 | coro = coroutine_function_example(1) |
| 162 | gen_coro = gen_coroutine_function_example(1) |
| 163 | |
| 164 | self.assertTrue(inspect.isawaitable(coro)) |
| 165 | self.assertTrue(inspect.isawaitable(gen_coro)) |
| 166 | |
| 167 | class Future: |
| 168 | def __await__(): |
| 169 | pass |
| 170 | self.assertTrue(inspect.isawaitable(Future())) |
| 171 | self.assertFalse(inspect.isawaitable(Future)) |
| 172 | |
| 173 | class NotFuture: pass |
| 174 | not_fut = NotFuture() |
| 175 | not_fut.__await__ = lambda: None |
| 176 | self.assertFalse(inspect.isawaitable(not_fut)) |
| 177 | |
| 178 | coro.close(); gen_coro.close() # silence warnings |
| 179 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 180 | def test_isroutine(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 181 | self.assertTrue(inspect.isroutine(mod.spam)) |
| 182 | self.assertTrue(inspect.isroutine([].count)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 183 | |
Benjamin Peterson | c465600 | 2009-01-17 22:41:18 +0000 | [diff] [blame] | 184 | def test_isclass(self): |
| 185 | self.istest(inspect.isclass, 'mod.StupidGit') |
| 186 | self.assertTrue(inspect.isclass(list)) |
| 187 | |
| 188 | class CustomGetattr(object): |
| 189 | def __getattr__(self, attr): |
| 190 | return None |
| 191 | self.assertFalse(inspect.isclass(CustomGetattr())) |
| 192 | |
Benjamin Peterson | 058e31e | 2009-01-16 03:54:08 +0000 | [diff] [blame] | 193 | def test_get_slot_members(self): |
| 194 | class C(object): |
| 195 | __slots__ = ("a", "b") |
Benjamin Peterson | 058e31e | 2009-01-16 03:54:08 +0000 | [diff] [blame] | 196 | x = C() |
| 197 | x.a = 42 |
| 198 | members = dict(inspect.getmembers(x)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 199 | self.assertIn('a', members) |
| 200 | self.assertNotIn('b', members) |
Benjamin Peterson | 058e31e | 2009-01-16 03:54:08 +0000 | [diff] [blame] | 201 | |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 202 | def test_isabstract(self): |
| 203 | from abc import ABCMeta, abstractmethod |
| 204 | |
| 205 | class AbstractClassExample(metaclass=ABCMeta): |
| 206 | |
| 207 | @abstractmethod |
| 208 | def foo(self): |
| 209 | pass |
| 210 | |
| 211 | class ClassExample(AbstractClassExample): |
| 212 | def foo(self): |
| 213 | pass |
| 214 | |
| 215 | a = ClassExample() |
| 216 | |
| 217 | # Test general behaviour. |
| 218 | self.assertTrue(inspect.isabstract(AbstractClassExample)) |
| 219 | self.assertFalse(inspect.isabstract(ClassExample)) |
| 220 | self.assertFalse(inspect.isabstract(a)) |
| 221 | self.assertFalse(inspect.isabstract(int)) |
| 222 | self.assertFalse(inspect.isabstract(5)) |
| 223 | |
Benjamin Peterson | 058e31e | 2009-01-16 03:54:08 +0000 | [diff] [blame] | 224 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 225 | class TestInterpreterStack(IsTestBase): |
| 226 | def __init__(self, *args, **kwargs): |
| 227 | unittest.TestCase.__init__(self, *args, **kwargs) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 228 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 229 | git.abuse(7, 8, 9) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 230 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 231 | def test_abuse_done(self): |
| 232 | self.istest(inspect.istraceback, 'git.ex[2]') |
| 233 | self.istest(inspect.isframe, 'mod.fr') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 234 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 235 | def test_stack(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 236 | self.assertTrue(len(mod.st) >= 5) |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 237 | self.assertEqual(revise(*mod.st[0][1:]), |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 238 | (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 239 | self.assertEqual(revise(*mod.st[1][1:]), |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 240 | (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 241 | self.assertEqual(revise(*mod.st[2][1:]), |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 242 | (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 243 | self.assertEqual(revise(*mod.st[3][1:]), |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 244 | (modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0)) |
Antoine Pitrou | cdcafb7 | 2014-08-24 10:50:28 -0400 | [diff] [blame] | 245 | # Test named tuple fields |
| 246 | record = mod.st[0] |
| 247 | self.assertIs(record.frame, mod.fr) |
| 248 | self.assertEqual(record.lineno, 16) |
| 249 | self.assertEqual(record.filename, mod.__file__) |
| 250 | self.assertEqual(record.function, 'eggs') |
| 251 | self.assertIn('inspect.stack()', record.code_context[0]) |
| 252 | self.assertEqual(record.index, 0) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 253 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 254 | def test_trace(self): |
| 255 | self.assertEqual(len(git.tr), 3) |
Florent Xicluna | c857592 | 2010-03-24 17:37:49 +0000 | [diff] [blame] | 256 | self.assertEqual(revise(*git.tr[0][1:]), |
| 257 | (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) |
| 258 | self.assertEqual(revise(*git.tr[1][1:]), |
| 259 | (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) |
| 260 | self.assertEqual(revise(*git.tr[2][1:]), |
| 261 | (modfile, 18, 'eggs', [' q = y / 0\n'], 0)) |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 262 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 263 | def test_frame(self): |
| 264 | args, varargs, varkw, locals = inspect.getargvalues(mod.fr) |
| 265 | self.assertEqual(args, ['x', 'y']) |
| 266 | self.assertEqual(varargs, None) |
| 267 | self.assertEqual(varkw, None) |
| 268 | self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14}) |
| 269 | self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
| 270 | '(x=11, y=14)') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 271 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 272 | def test_previous_frame(self): |
| 273 | args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 274 | self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f']) |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 275 | self.assertEqual(varargs, 'g') |
| 276 | self.assertEqual(varkw, 'h') |
| 277 | self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 278 | '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})') |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 279 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 280 | class GetSourceBase(unittest.TestCase): |
| 281 | # Subclasses must override. |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 282 | fodderModule = None |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 283 | |
Yury Selivanov | 6738b11 | 2015-05-16 10:10:21 -0400 | [diff] [blame] | 284 | def setUp(self): |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 285 | with open(inspect.getsourcefile(self.fodderModule)) as fp: |
Philip Jenvey | a27c5bd | 2009-05-28 06:09:08 +0000 | [diff] [blame] | 286 | self.source = fp.read() |
Ka-Ping Yee | 6397c7c | 2001-02-27 14:43:21 +0000 | [diff] [blame] | 287 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 288 | def sourcerange(self, top, bottom): |
| 289 | lines = self.source.split("\n") |
| 290 | return "\n".join(lines[top-1:bottom]) + "\n" |
Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 291 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 292 | def assertSourceEqual(self, obj, top, bottom): |
| 293 | self.assertEqual(inspect.getsource(obj), |
| 294 | self.sourcerange(top, bottom)) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 295 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 296 | class TestRetrievingSourceCode(GetSourceBase): |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 297 | fodderModule = mod |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 298 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 299 | def test_getclasses(self): |
| 300 | classes = inspect.getmembers(mod, inspect.isclass) |
| 301 | self.assertEqual(classes, |
| 302 | [('FesteringGob', mod.FesteringGob), |
| 303 | ('MalodorousPervert', mod.MalodorousPervert), |
| 304 | ('ParrotDroppings', mod.ParrotDroppings), |
Serhiy Storchaka | 362c1b5 | 2013-09-05 17:14:32 +0300 | [diff] [blame] | 305 | ('StupidGit', mod.StupidGit), |
| 306 | ('Tit', mod.MalodorousPervert), |
| 307 | ]) |
| 308 | tree = inspect.getclasstree([cls[1] for cls in classes]) |
| 309 | self.assertEqual(tree, |
| 310 | [(object, ()), |
| 311 | [(mod.ParrotDroppings, (object,)), |
| 312 | [(mod.FesteringGob, (mod.MalodorousPervert, |
| 313 | mod.ParrotDroppings)) |
| 314 | ], |
| 315 | (mod.StupidGit, (object,)), |
| 316 | [(mod.MalodorousPervert, (mod.StupidGit,)), |
| 317 | [(mod.FesteringGob, (mod.MalodorousPervert, |
| 318 | mod.ParrotDroppings)) |
| 319 | ] |
| 320 | ] |
| 321 | ] |
| 322 | ]) |
| 323 | tree = inspect.getclasstree([cls[1] for cls in classes], True) |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 324 | self.assertEqual(tree, |
Thomas Wouters | 725af87 | 2006-04-15 09:13:19 +0000 | [diff] [blame] | 325 | [(object, ()), |
| 326 | [(mod.ParrotDroppings, (object,)), |
| 327 | (mod.StupidGit, (object,)), |
| 328 | [(mod.MalodorousPervert, (mod.StupidGit,)), |
| 329 | [(mod.FesteringGob, (mod.MalodorousPervert, |
| 330 | mod.ParrotDroppings)) |
| 331 | ] |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 332 | ] |
| 333 | ] |
| 334 | ]) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 335 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 336 | def test_getfunctions(self): |
| 337 | functions = inspect.getmembers(mod, inspect.isfunction) |
| 338 | self.assertEqual(functions, [('eggs', mod.eggs), |
Yury Selivanov | e4e811d | 2015-07-21 19:01:52 +0300 | [diff] [blame] | 339 | ('lobbest', mod.lobbest), |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 340 | ('spam', mod.spam)]) |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 341 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 342 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 343 | "Docstrings are omitted with -O2 and above") |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 344 | def test_getdoc(self): |
| 345 | self.assertEqual(inspect.getdoc(mod), 'A module docstring.') |
| 346 | self.assertEqual(inspect.getdoc(mod.StupidGit), |
| 347 | 'A longer,\n\nindented\n\ndocstring.') |
| 348 | self.assertEqual(inspect.getdoc(git.abuse), |
| 349 | 'Another\n\ndocstring\n\ncontaining\n\ntabs') |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 350 | |
Serhiy Storchaka | 5cf2b72 | 2015-04-03 22:38:53 +0300 | [diff] [blame] | 351 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 352 | "Docstrings are omitted with -O2 and above") |
| 353 | def test_getdoc_inherited(self): |
| 354 | self.assertEqual(inspect.getdoc(mod.FesteringGob), |
| 355 | 'A longer,\n\nindented\n\ndocstring.') |
| 356 | self.assertEqual(inspect.getdoc(mod.FesteringGob.abuse), |
| 357 | 'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 358 | self.assertEqual(inspect.getdoc(mod.FesteringGob().abuse), |
| 359 | 'Another\n\ndocstring\n\ncontaining\n\ntabs') |
| 360 | self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction), |
| 361 | 'The automatic gainsaying.') |
| 362 | |
| 363 | @unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings") |
| 364 | def test_finddoc(self): |
| 365 | finddoc = inspect._finddoc |
| 366 | self.assertEqual(finddoc(int), int.__doc__) |
| 367 | self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__) |
| 368 | self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__) |
| 369 | self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__) |
| 370 | self.assertEqual(finddoc(int.real), int.real.__doc__) |
| 371 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 372 | def test_cleandoc(self): |
| 373 | self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'), |
| 374 | 'An\nindented\ndocstring.') |
| 375 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 376 | def test_getcomments(self): |
| 377 | self.assertEqual(inspect.getcomments(mod), '# line 1\n') |
| 378 | self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 379 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 380 | def test_getmodule(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 381 | # Check actual module |
| 382 | self.assertEqual(inspect.getmodule(mod), mod) |
| 383 | # Check class (uses __module__ attribute) |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 384 | self.assertEqual(inspect.getmodule(mod.StupidGit), mod) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 385 | # Check a method (no __module__ attribute, falls back to filename) |
| 386 | self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
| 387 | # Do it again (check the caching isn't broken) |
| 388 | self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) |
| 389 | # Check a builtin |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 390 | self.assertEqual(inspect.getmodule(str), sys.modules["builtins"]) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 391 | # Check filename override |
| 392 | self.assertEqual(inspect.getmodule(None, modfile), mod) |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 393 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 394 | def test_getsource(self): |
| 395 | self.assertSourceEqual(git.abuse, 29, 39) |
Serhiy Storchaka | ac4bdcc | 2015-10-29 08:15:50 +0200 | [diff] [blame] | 396 | self.assertSourceEqual(mod.StupidGit, 21, 51) |
| 397 | self.assertSourceEqual(mod.lobbest, 75, 76) |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 398 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 399 | def test_getsourcefile(self): |
Christian Heimes | a3538eb | 2007-11-06 11:44:48 +0000 | [diff] [blame] | 400 | self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile) |
| 401 | self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile) |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 402 | fn = "_non_existing_filename_used_for_sourcefile_test.py" |
| 403 | co = compile("None", fn, "exec") |
R. David Murray | 4155f97 | 2010-06-17 13:23:18 +0000 | [diff] [blame] | 404 | self.assertEqual(inspect.getsourcefile(co), None) |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 405 | linecache.cache[co.co_filename] = (1, None, "None", co.co_filename) |
Antoine Pitrou | 5d62a61 | 2012-07-08 13:48:46 +0200 | [diff] [blame] | 406 | try: |
| 407 | self.assertEqual(normcase(inspect.getsourcefile(co)), fn) |
| 408 | finally: |
| 409 | del linecache.cache[co.co_filename] |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 410 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 411 | def test_getfile(self): |
| 412 | self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 413 | |
Yury Selivanov | 2eed8b7 | 2014-01-27 13:24:56 -0500 | [diff] [blame] | 414 | def test_getfile_class_without_module(self): |
| 415 | class CM(type): |
| 416 | @property |
| 417 | def __module__(cls): |
| 418 | raise AttributeError |
| 419 | class C(metaclass=CM): |
| 420 | pass |
| 421 | with self.assertRaises(TypeError): |
| 422 | inspect.getfile(C) |
| 423 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 424 | def test_getmodule_recursion(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 425 | from types import ModuleType |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 426 | name = '__inspect_dummy' |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 427 | m = sys.modules[name] = ModuleType(name) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 428 | m.__file__ = "<string>" # hopefully not a real filename... |
| 429 | m.__loader__ = "dummy" # pretend the filename is understood by a loader |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 430 | exec("def x(): pass", m.__dict__) |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 431 | self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 432 | del sys.modules[name] |
| 433 | inspect.getmodule(compile('a=10','','single')) |
| 434 | |
Benjamin Peterson | 9620cc0 | 2011-06-11 15:53:11 -0500 | [diff] [blame] | 435 | def test_proceed_with_fake_filename(self): |
| 436 | '''doctest monkeypatches linecache to enable inspection''' |
| 437 | fn, source = '<test>', 'def x(): pass\n' |
| 438 | getlines = linecache.getlines |
| 439 | def monkey(filename, module_globals=None): |
| 440 | if filename == fn: |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 441 | return source.splitlines(keepends=True) |
Benjamin Peterson | 9620cc0 | 2011-06-11 15:53:11 -0500 | [diff] [blame] | 442 | else: |
| 443 | return getlines(filename, module_globals) |
| 444 | linecache.getlines = monkey |
| 445 | try: |
| 446 | ns = {} |
| 447 | exec(compile(source, fn, 'single'), ns) |
| 448 | inspect.getsource(ns["x"]) |
| 449 | finally: |
| 450 | linecache.getlines = getlines |
| 451 | |
Antoine Pitrou | a8723a0 | 2015-04-15 00:41:29 +0200 | [diff] [blame] | 452 | def test_getsource_on_code_object(self): |
| 453 | self.assertSourceEqual(mod.eggs.__code__, 12, 18) |
| 454 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 455 | class TestDecorators(GetSourceBase): |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 456 | fodderModule = mod2 |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 457 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 458 | def test_wrapped_decorator(self): |
Christian Heimes | 09aaa88 | 2008-02-23 15:01:06 +0000 | [diff] [blame] | 459 | self.assertSourceEqual(mod2.wrapped, 14, 17) |
Johannes Gijsbers | c473c99 | 2004-08-18 12:40:31 +0000 | [diff] [blame] | 460 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 461 | def test_replacing_decorator(self): |
| 462 | self.assertSourceEqual(mod2.gone, 9, 10) |
Tim Peters | e0b2d7a | 2001-09-22 06:10:55 +0000 | [diff] [blame] | 463 | |
Yury Selivanov | 081bbf6 | 2014-09-26 17:34:54 -0400 | [diff] [blame] | 464 | def test_getsource_unwrap(self): |
Antoine Pitrou | a8723a0 | 2015-04-15 00:41:29 +0200 | [diff] [blame] | 465 | self.assertSourceEqual(mod2.real, 130, 132) |
| 466 | |
| 467 | def test_decorator_with_lambda(self): |
| 468 | self.assertSourceEqual(mod2.func114, 113, 115) |
Yury Selivanov | 081bbf6 | 2014-09-26 17:34:54 -0400 | [diff] [blame] | 469 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 470 | class TestOneliners(GetSourceBase): |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 471 | fodderModule = mod2 |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 472 | def test_oneline_lambda(self): |
| 473 | # Test inspect.getsource with a one-line lambda function. |
| 474 | self.assertSourceEqual(mod2.oll, 25, 25) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 475 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 476 | def test_threeline_lambda(self): |
| 477 | # Test inspect.getsource with a three-line lambda function, |
| 478 | # where the second and third lines are _not_ indented. |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 479 | self.assertSourceEqual(mod2.tll, 28, 30) |
| 480 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 481 | def test_twoline_indented_lambda(self): |
| 482 | # Test inspect.getsource with a two-line lambda function, |
| 483 | # where the second line _is_ indented. |
| 484 | self.assertSourceEqual(mod2.tlli, 33, 34) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 485 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 486 | def test_onelinefunc(self): |
| 487 | # Test inspect.getsource with a regular one-line function. |
| 488 | self.assertSourceEqual(mod2.onelinefunc, 37, 37) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 489 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 490 | def test_manyargs(self): |
| 491 | # Test inspect.getsource with a regular function where |
| 492 | # the arguments are on two lines and _not_ indented and |
| 493 | # the body on the second line with the last arguments. |
| 494 | self.assertSourceEqual(mod2.manyargs, 40, 41) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 495 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 496 | def test_twolinefunc(self): |
| 497 | # Test inspect.getsource with a regular function where |
| 498 | # the body is on two lines, following the argument list and |
| 499 | # continued on the next line by a \\. |
| 500 | self.assertSourceEqual(mod2.twolinefunc, 44, 45) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 501 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 502 | def test_lambda_in_list(self): |
| 503 | # Test inspect.getsource with a one-line lambda function |
| 504 | # defined in a list, indented. |
| 505 | self.assertSourceEqual(mod2.a[1], 49, 49) |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 506 | |
Johannes Gijsbers | 1542f34 | 2004-12-12 16:46:28 +0000 | [diff] [blame] | 507 | def test_anonymous(self): |
| 508 | # Test inspect.getsource with a lambda function defined |
| 509 | # as argument to another function. |
| 510 | self.assertSourceEqual(mod2.anonymous, 55, 55) |
| 511 | |
Johannes Gijsbers | a5855d5 | 2005-03-12 16:37:11 +0000 | [diff] [blame] | 512 | class TestBuggyCases(GetSourceBase): |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 513 | fodderModule = mod2 |
Johannes Gijsbers | a5855d5 | 2005-03-12 16:37:11 +0000 | [diff] [blame] | 514 | |
| 515 | def test_with_comment(self): |
| 516 | self.assertSourceEqual(mod2.with_comment, 58, 59) |
| 517 | |
| 518 | def test_multiline_sig(self): |
| 519 | self.assertSourceEqual(mod2.multiline_sig[0], 63, 64) |
| 520 | |
Armin Rigo | dd5c023 | 2005-09-25 11:45:45 +0000 | [diff] [blame] | 521 | def test_nested_class(self): |
| 522 | self.assertSourceEqual(mod2.func69().func71, 71, 72) |
| 523 | |
| 524 | def test_one_liner_followed_by_non_name(self): |
| 525 | self.assertSourceEqual(mod2.func77, 77, 77) |
| 526 | |
| 527 | def test_one_liner_dedent_non_name(self): |
| 528 | self.assertSourceEqual(mod2.cls82.func83, 83, 83) |
| 529 | |
| 530 | def test_with_comment_instead_of_docstring(self): |
| 531 | self.assertSourceEqual(mod2.func88, 88, 90) |
| 532 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 533 | def test_method_in_dynamic_class(self): |
| 534 | self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97) |
| 535 | |
R David Murray | 32562d7 | 2014-10-03 11:15:38 -0400 | [diff] [blame] | 536 | # This should not skip for CPython, but might on a repackaged python where |
| 537 | # unicodedata is not an external module, or on pypy. |
| 538 | @unittest.skipIf(not hasattr(unicodedata, '__file__') or |
| 539 | unicodedata.__file__.endswith('.py'), |
| 540 | "unicodedata is not an external binary module") |
R. David Murray | 74b8924 | 2009-05-13 17:33:03 +0000 | [diff] [blame] | 541 | def test_findsource_binary(self): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 542 | self.assertRaises(OSError, inspect.getsource, unicodedata) |
| 543 | self.assertRaises(OSError, inspect.findsource, unicodedata) |
R. David Murray | 74b8924 | 2009-05-13 17:33:03 +0000 | [diff] [blame] | 544 | |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 545 | def test_findsource_code_in_linecache(self): |
| 546 | lines = ["x=1"] |
| 547 | co = compile(lines[0], "_dynamically_created_file", "exec") |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 548 | self.assertRaises(OSError, inspect.findsource, co) |
| 549 | self.assertRaises(OSError, inspect.getsource, co) |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 550 | linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) |
Antoine Pitrou | 5d62a61 | 2012-07-08 13:48:46 +0200 | [diff] [blame] | 551 | try: |
| 552 | self.assertEqual(inspect.findsource(co), (lines,0)) |
| 553 | self.assertEqual(inspect.getsource(co), lines[0]) |
| 554 | finally: |
| 555 | del linecache.cache[co.co_filename] |
R. David Murray | a1b3740 | 2010-06-17 02:04:29 +0000 | [diff] [blame] | 556 | |
Ezio Melotti | 1b14592 | 2013-03-30 05:17:24 +0200 | [diff] [blame] | 557 | def test_findsource_without_filename(self): |
| 558 | for fname in ['', '<string>']: |
| 559 | co = compile('x=1', fname, "exec") |
| 560 | self.assertRaises(IOError, inspect.findsource, co) |
| 561 | self.assertRaises(IOError, inspect.getsource, co) |
| 562 | |
Antoine Pitrou | a8723a0 | 2015-04-15 00:41:29 +0200 | [diff] [blame] | 563 | def test_getsource_on_method(self): |
| 564 | self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119) |
| 565 | |
Yury Selivanov | 4f4913b | 2015-07-23 17:10:00 +0300 | [diff] [blame] | 566 | def test_nested_func(self): |
| 567 | self.assertSourceEqual(mod2.cls135.func136, 136, 139) |
| 568 | |
| 569 | |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 570 | class TestNoEOL(GetSourceBase): |
Yury Selivanov | 6738b11 | 2015-05-16 10:10:21 -0400 | [diff] [blame] | 571 | def setUp(self): |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 572 | self.tempdir = TESTFN + '_dir' |
| 573 | os.mkdir(self.tempdir) |
| 574 | with open(os.path.join(self.tempdir, |
| 575 | 'inspect_fodder3%spy' % os.extsep), 'w') as f: |
| 576 | f.write("class X:\n pass # No EOL") |
| 577 | with DirsOnSysPath(self.tempdir): |
| 578 | import inspect_fodder3 as mod3 |
| 579 | self.fodderModule = mod3 |
Yury Selivanov | 6738b11 | 2015-05-16 10:10:21 -0400 | [diff] [blame] | 580 | super().setUp() |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 581 | |
| 582 | def tearDown(self): |
| 583 | shutil.rmtree(self.tempdir) |
| 584 | |
| 585 | def test_class(self): |
| 586 | self.assertSourceEqual(self.fodderModule.X, 1, 2) |
| 587 | |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 588 | |
| 589 | class _BrokenDataDescriptor(object): |
| 590 | """ |
| 591 | A broken data descriptor. See bug #1785. |
| 592 | """ |
| 593 | def __get__(*args): |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 594 | raise AttributeError("broken data descriptor") |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 595 | |
| 596 | def __set__(*args): |
| 597 | raise RuntimeError |
| 598 | |
| 599 | def __getattr__(*args): |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 600 | raise AttributeError("broken data descriptor") |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 601 | |
| 602 | |
| 603 | class _BrokenMethodDescriptor(object): |
| 604 | """ |
| 605 | A broken method descriptor. See bug #1785. |
| 606 | """ |
| 607 | def __get__(*args): |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 608 | raise AttributeError("broken method descriptor") |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 609 | |
| 610 | def __getattr__(*args): |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 611 | raise AttributeError("broken method descriptor") |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 612 | |
| 613 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 614 | # Helper for testing classify_class_attrs. |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 615 | def attrs_wo_objs(cls): |
| 616 | return [t[:3] for t in inspect.classify_class_attrs(cls)] |
| 617 | |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 618 | |
Tim Peters | 5a9fb3c | 2005-01-07 16:01:32 +0000 | [diff] [blame] | 619 | class TestClassesAndFunctions(unittest.TestCase): |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 620 | def test_newstyle_mro(self): |
| 621 | # The same w/ new-class MRO. |
| 622 | class A(object): pass |
| 623 | class B(A): pass |
| 624 | class C(A): pass |
| 625 | class D(B, C): pass |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 626 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 627 | expected = (D, B, C, A, object) |
| 628 | got = inspect.getmro(D) |
| 629 | self.assertEqual(expected, got) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 630 | |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 631 | def assertArgSpecEquals(self, routine, args_e, varargs_e=None, |
| 632 | varkw_e=None, defaults_e=None, formatted=None): |
Yury Selivanov | 3cfec2e | 2015-05-22 11:38:38 -0400 | [diff] [blame] | 633 | with self.assertWarns(DeprecationWarning): |
| 634 | args, varargs, varkw, defaults = inspect.getargspec(routine) |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 635 | self.assertEqual(args, args_e) |
| 636 | self.assertEqual(varargs, varargs_e) |
| 637 | self.assertEqual(varkw, varkw_e) |
| 638 | self.assertEqual(defaults, defaults_e) |
| 639 | if formatted is not None: |
| 640 | self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults), |
| 641 | formatted) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 642 | |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 643 | def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None, |
| 644 | varkw_e=None, defaults_e=None, |
| 645 | kwonlyargs_e=[], kwonlydefaults_e=None, |
| 646 | ann_e={}, formatted=None): |
| 647 | args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ |
| 648 | inspect.getfullargspec(routine) |
| 649 | self.assertEqual(args, args_e) |
| 650 | self.assertEqual(varargs, varargs_e) |
| 651 | self.assertEqual(varkw, varkw_e) |
| 652 | self.assertEqual(defaults, defaults_e) |
| 653 | self.assertEqual(kwonlyargs, kwonlyargs_e) |
| 654 | self.assertEqual(kwonlydefaults, kwonlydefaults_e) |
| 655 | self.assertEqual(ann, ann_e) |
| 656 | if formatted is not None: |
| 657 | self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults, |
| 658 | kwonlyargs, kwonlydefaults, ann), |
| 659 | formatted) |
| 660 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 661 | def test_getargspec(self): |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 662 | self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted='(x, y)') |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 663 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 664 | self.assertArgSpecEquals(mod.spam, |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 665 | ['a', 'b', 'c', 'd', 'e', 'f'], |
| 666 | 'g', 'h', (3, 4, 5), |
| 667 | '(a, b, c, d=3, e=4, f=5, *g, **h)') |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 668 | |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 669 | self.assertRaises(ValueError, self.assertArgSpecEquals, |
| 670 | mod2.keyworded, []) |
| 671 | |
| 672 | self.assertRaises(ValueError, self.assertArgSpecEquals, |
| 673 | mod2.annotated, []) |
Benjamin Peterson | 9953a8d | 2009-01-17 04:15:01 +0000 | [diff] [blame] | 674 | self.assertRaises(ValueError, self.assertArgSpecEquals, |
| 675 | mod2.keyword_only_arg, []) |
| 676 | |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 677 | |
| 678 | def test_getfullargspec(self): |
| 679 | self.assertFullArgSpecEquals(mod2.keyworded, [], varargs_e='arg1', |
| 680 | kwonlyargs_e=['arg2'], |
| 681 | kwonlydefaults_e={'arg2':1}, |
| 682 | formatted='(*arg1, arg2=1)') |
| 683 | |
| 684 | self.assertFullArgSpecEquals(mod2.annotated, ['arg1'], |
Christian Heimes | c9543e4 | 2007-11-28 08:28:28 +0000 | [diff] [blame] | 685 | ann_e={'arg1' : list}, |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 686 | formatted='(arg1: list)') |
Benjamin Peterson | 9953a8d | 2009-01-17 04:15:01 +0000 | [diff] [blame] | 687 | self.assertFullArgSpecEquals(mod2.keyword_only_arg, [], |
| 688 | kwonlyargs_e=['arg'], |
| 689 | formatted='(*, arg)') |
| 690 | |
Yury Selivanov | 57d240e | 2014-02-19 16:27:23 -0500 | [diff] [blame] | 691 | def test_argspec_api_ignores_wrapped(self): |
| 692 | # Issue 20684: low level introspection API must ignore __wrapped__ |
| 693 | @functools.wraps(mod.spam) |
| 694 | def ham(x, y): |
| 695 | pass |
| 696 | # Basic check |
| 697 | self.assertArgSpecEquals(ham, ['x', 'y'], formatted='(x, y)') |
| 698 | self.assertFullArgSpecEquals(ham, ['x', 'y'], formatted='(x, y)') |
| 699 | self.assertFullArgSpecEquals(functools.partial(ham), |
| 700 | ['x', 'y'], formatted='(x, y)') |
| 701 | # Other variants |
| 702 | def check_method(f): |
| 703 | self.assertArgSpecEquals(f, ['self', 'x', 'y'], |
| 704 | formatted='(self, x, y)') |
| 705 | class C: |
| 706 | @functools.wraps(mod.spam) |
| 707 | def ham(self, x, y): |
| 708 | pass |
| 709 | pham = functools.partialmethod(ham) |
| 710 | @functools.wraps(mod.spam) |
| 711 | def __call__(self, x, y): |
| 712 | pass |
| 713 | check_method(C()) |
| 714 | check_method(C.ham) |
| 715 | check_method(C().ham) |
| 716 | check_method(C.pham) |
| 717 | check_method(C().pham) |
| 718 | |
| 719 | class C_new: |
| 720 | @functools.wraps(mod.spam) |
| 721 | def __new__(self, x, y): |
| 722 | pass |
| 723 | check_method(C_new) |
| 724 | |
| 725 | class C_init: |
| 726 | @functools.wraps(mod.spam) |
| 727 | def __init__(self, x, y): |
| 728 | pass |
| 729 | check_method(C_init) |
| 730 | |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 731 | def test_getfullargspec_signature_attr(self): |
| 732 | def test(): |
| 733 | pass |
| 734 | spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) |
| 735 | test.__signature__ = inspect.Signature(parameters=(spam_param,)) |
| 736 | |
| 737 | self.assertFullArgSpecEquals(test, args_e=['spam'], formatted='(spam)') |
| 738 | |
Yury Selivanov | 4cb9391 | 2014-01-29 11:54:12 -0500 | [diff] [blame] | 739 | def test_getfullargspec_signature_annos(self): |
| 740 | def test(a:'spam') -> 'ham': pass |
| 741 | spec = inspect.getfullargspec(test) |
| 742 | self.assertEqual(test.__annotations__, spec.annotations) |
| 743 | |
| 744 | def test(): pass |
| 745 | spec = inspect.getfullargspec(test) |
| 746 | self.assertEqual(test.__annotations__, spec.annotations) |
| 747 | |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 748 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 749 | "Signature information for builtins requires docstrings") |
| 750 | def test_getfullargspec_builtin_methods(self): |
| 751 | self.assertFullArgSpecEquals(_pickle.Pickler.dump, |
| 752 | args_e=['self', 'obj'], formatted='(self, obj)') |
| 753 | |
| 754 | self.assertFullArgSpecEquals(_pickle.Pickler(io.BytesIO()).dump, |
| 755 | args_e=['self', 'obj'], formatted='(self, obj)') |
| 756 | |
Yury Selivanov | 8c185ee | 2014-02-21 01:32:42 -0500 | [diff] [blame] | 757 | self.assertFullArgSpecEquals( |
| 758 | os.stat, |
| 759 | args_e=['path'], |
| 760 | kwonlyargs_e=['dir_fd', 'follow_symlinks'], |
| 761 | kwonlydefaults_e={'dir_fd': None, 'follow_symlinks': True}, |
| 762 | formatted='(path, *, dir_fd=None, follow_symlinks=True)') |
| 763 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 764 | @cpython_only |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 765 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 766 | "Signature information for builtins requires docstrings") |
| 767 | def test_getfullagrspec_builtin_func(self): |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 768 | import _testcapi |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 769 | builtin = _testcapi.docstring_with_signature_with_defaults |
| 770 | spec = inspect.getfullargspec(builtin) |
| 771 | self.assertEqual(spec.defaults[0], 'avocado') |
| 772 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 773 | @cpython_only |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 774 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 775 | "Signature information for builtins requires docstrings") |
| 776 | def test_getfullagrspec_builtin_func_no_signature(self): |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 777 | import _testcapi |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 778 | builtin = _testcapi.docstring_no_signature |
| 779 | with self.assertRaises(TypeError): |
| 780 | inspect.getfullargspec(builtin) |
Christian Heimes | 3795b53 | 2007-11-08 13:48:53 +0000 | [diff] [blame] | 781 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 782 | def test_getargspec_method(self): |
| 783 | class A(object): |
| 784 | def m(self): |
| 785 | pass |
| 786 | self.assertArgSpecEquals(A.m, ['self']) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 787 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 788 | def test_classify_newstyle(self): |
| 789 | class A(object): |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 790 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 791 | def s(): pass |
| 792 | s = staticmethod(s) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 793 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 794 | def c(cls): pass |
| 795 | c = classmethod(c) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 796 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 797 | def getp(self): pass |
| 798 | p = property(getp) |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 799 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 800 | def m(self): pass |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 801 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 802 | def m1(self): pass |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 803 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 804 | datablob = '1' |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 805 | |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 806 | dd = _BrokenDataDescriptor() |
| 807 | md = _BrokenMethodDescriptor() |
| 808 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 809 | attrs = attrs_wo_objs(A) |
Yury Selivanov | 0860a0b | 2014-01-31 14:28:44 -0500 | [diff] [blame] | 810 | |
| 811 | self.assertIn(('__new__', 'method', object), attrs, 'missing __new__') |
| 812 | self.assertIn(('__init__', 'method', object), attrs, 'missing __init__') |
| 813 | |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 814 | self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 815 | self.assertIn(('c', 'class method', A), attrs, 'missing class method') |
| 816 | self.assertIn(('p', 'property', A), attrs, 'missing property') |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 817 | self.assertIn(('m', 'method', A), attrs, |
| 818 | 'missing plain method: %r' % attrs) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 819 | self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 820 | self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 821 | self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 822 | self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 823 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 824 | class B(A): |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 825 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 826 | def m(self): pass |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 827 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 828 | attrs = attrs_wo_objs(B) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 829 | self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 830 | self.assertIn(('c', 'class method', A), attrs, 'missing class method') |
| 831 | self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 832 | self.assertIn(('m', 'method', B), attrs, 'missing plain method') |
| 833 | self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 834 | self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 835 | self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 836 | self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 837 | |
| 838 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 839 | class C(A): |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 840 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 841 | def m(self): pass |
| 842 | def c(self): pass |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 843 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 844 | attrs = attrs_wo_objs(C) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 845 | self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 846 | self.assertIn(('c', 'method', C), attrs, 'missing plain method') |
| 847 | self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 848 | self.assertIn(('m', 'method', C), attrs, 'missing plain method') |
| 849 | self.assertIn(('m1', 'method', A), attrs, 'missing plain method') |
| 850 | self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 851 | self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 852 | self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 853 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 854 | class D(B, C): |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 855 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 856 | def m1(self): pass |
Tim Peters | 13b49d3 | 2001-09-23 02:00:29 +0000 | [diff] [blame] | 857 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 858 | attrs = attrs_wo_objs(D) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 859 | self.assertIn(('s', 'static method', A), attrs, 'missing static method') |
| 860 | self.assertIn(('c', 'method', C), attrs, 'missing plain method') |
| 861 | self.assertIn(('p', 'property', A), attrs, 'missing property') |
| 862 | self.assertIn(('m', 'method', B), attrs, 'missing plain method') |
| 863 | self.assertIn(('m1', 'method', D), attrs, 'missing plain method') |
| 864 | self.assertIn(('datablob', 'data', A), attrs, 'missing data') |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 865 | self.assertIn(('md', 'method', A), attrs, 'missing method descriptor') |
| 866 | self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor') |
| 867 | |
| 868 | def test_classify_builtin_types(self): |
| 869 | # Simple sanity check that all built-in types can have their |
| 870 | # attributes classified. |
| 871 | for name in dir(__builtins__): |
| 872 | builtin = getattr(__builtins__, name) |
| 873 | if isinstance(builtin, type): |
| 874 | inspect.classify_class_attrs(builtin) |
| 875 | |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 876 | def test_classify_DynamicClassAttribute(self): |
| 877 | class Meta(type): |
| 878 | def __getattr__(self, name): |
| 879 | if name == 'ham': |
| 880 | return 'spam' |
| 881 | return super().__getattr__(name) |
| 882 | class VA(metaclass=Meta): |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 883 | @types.DynamicClassAttribute |
| 884 | def ham(self): |
| 885 | return 'eggs' |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 886 | should_find_dca = inspect.Attribute('ham', 'data', VA, VA.__dict__['ham']) |
| 887 | self.assertIn(should_find_dca, inspect.classify_class_attrs(VA)) |
Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 888 | should_find_ga = inspect.Attribute('ham', 'data', Meta, 'spam') |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 889 | self.assertIn(should_find_ga, inspect.classify_class_attrs(VA)) |
| 890 | |
Yury Selivanov | bf341fb | 2015-05-21 15:41:57 -0400 | [diff] [blame] | 891 | def test_classify_overrides_bool(self): |
| 892 | class NoBool(object): |
| 893 | def __eq__(self, other): |
| 894 | return NoBool() |
| 895 | |
| 896 | def __bool__(self): |
| 897 | raise NotImplementedError( |
| 898 | "This object does not specify a boolean value") |
| 899 | |
| 900 | class HasNB(object): |
| 901 | dd = NoBool() |
| 902 | |
| 903 | should_find_attr = inspect.Attribute('dd', 'data', HasNB, HasNB.dd) |
| 904 | self.assertIn(should_find_attr, inspect.classify_class_attrs(HasNB)) |
| 905 | |
Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 906 | def test_classify_metaclass_class_attribute(self): |
| 907 | class Meta(type): |
| 908 | fish = 'slap' |
| 909 | def __dir__(self): |
Serhiy Storchaka | a60c2fe | 2015-03-12 21:56:08 +0200 | [diff] [blame] | 910 | return ['__class__', '__module__', '__name__', 'fish'] |
Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 911 | class Class(metaclass=Meta): |
| 912 | pass |
| 913 | should_find = inspect.Attribute('fish', 'data', Meta, 'slap') |
| 914 | self.assertIn(should_find, inspect.classify_class_attrs(Class)) |
| 915 | |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 916 | def test_classify_VirtualAttribute(self): |
| 917 | class Meta(type): |
| 918 | def __dir__(cls): |
| 919 | return ['__class__', '__module__', '__name__', 'BOOM'] |
| 920 | def __getattr__(self, name): |
| 921 | if name =='BOOM': |
| 922 | return 42 |
| 923 | return super().__getattr(name) |
| 924 | class Class(metaclass=Meta): |
| 925 | pass |
Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 926 | should_find = inspect.Attribute('BOOM', 'data', Meta, 42) |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 927 | self.assertIn(should_find, inspect.classify_class_attrs(Class)) |
| 928 | |
| 929 | def test_classify_VirtualAttribute_multi_classes(self): |
| 930 | class Meta1(type): |
| 931 | def __dir__(cls): |
| 932 | return ['__class__', '__module__', '__name__', 'one'] |
| 933 | def __getattr__(self, name): |
| 934 | if name =='one': |
| 935 | return 1 |
| 936 | return super().__getattr__(name) |
| 937 | class Meta2(type): |
| 938 | def __dir__(cls): |
| 939 | return ['__class__', '__module__', '__name__', 'two'] |
| 940 | def __getattr__(self, name): |
| 941 | if name =='two': |
| 942 | return 2 |
| 943 | return super().__getattr__(name) |
| 944 | class Meta3(Meta1, Meta2): |
| 945 | def __dir__(cls): |
| 946 | return list(sorted(set(['__class__', '__module__', '__name__', 'three'] + |
| 947 | Meta1.__dir__(cls) + Meta2.__dir__(cls)))) |
| 948 | def __getattr__(self, name): |
| 949 | if name =='three': |
| 950 | return 3 |
| 951 | return super().__getattr__(name) |
| 952 | class Class1(metaclass=Meta1): |
| 953 | pass |
| 954 | class Class2(Class1, metaclass=Meta3): |
| 955 | pass |
| 956 | |
Ethan Furman | b0c84cd | 2013-10-20 22:37:39 -0700 | [diff] [blame] | 957 | should_find1 = inspect.Attribute('one', 'data', Meta1, 1) |
| 958 | should_find2 = inspect.Attribute('two', 'data', Meta2, 2) |
| 959 | should_find3 = inspect.Attribute('three', 'data', Meta3, 3) |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 960 | cca = inspect.classify_class_attrs(Class2) |
| 961 | for sf in (should_find1, should_find2, should_find3): |
| 962 | self.assertIn(sf, cca) |
| 963 | |
| 964 | def test_classify_class_attrs_with_buggy_dir(self): |
| 965 | class M(type): |
| 966 | def __dir__(cls): |
| 967 | return ['__class__', '__name__', 'missing'] |
| 968 | class C(metaclass=M): |
| 969 | pass |
| 970 | attrs = [a[0] for a in inspect.classify_class_attrs(C)] |
| 971 | self.assertNotIn('missing', attrs) |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 972 | |
Antoine Pitrou | 86a8a9a | 2011-12-21 09:57:40 +0100 | [diff] [blame] | 973 | def test_getmembers_descriptors(self): |
| 974 | class A(object): |
| 975 | dd = _BrokenDataDescriptor() |
| 976 | md = _BrokenMethodDescriptor() |
| 977 | |
| 978 | def pred_wrapper(pred): |
| 979 | # A quick'n'dirty way to discard standard attributes of new-style |
| 980 | # classes. |
| 981 | class Empty(object): |
| 982 | pass |
| 983 | def wrapped(x): |
| 984 | if '__name__' in dir(x) and hasattr(Empty, x.__name__): |
| 985 | return False |
| 986 | return pred(x) |
| 987 | return wrapped |
| 988 | |
| 989 | ismethoddescriptor = pred_wrapper(inspect.ismethoddescriptor) |
| 990 | isdatadescriptor = pred_wrapper(inspect.isdatadescriptor) |
| 991 | |
| 992 | self.assertEqual(inspect.getmembers(A, ismethoddescriptor), |
| 993 | [('md', A.__dict__['md'])]) |
| 994 | self.assertEqual(inspect.getmembers(A, isdatadescriptor), |
| 995 | [('dd', A.__dict__['dd'])]) |
| 996 | |
| 997 | class B(A): |
| 998 | pass |
| 999 | |
| 1000 | self.assertEqual(inspect.getmembers(B, ismethoddescriptor), |
| 1001 | [('md', A.__dict__['md'])]) |
| 1002 | self.assertEqual(inspect.getmembers(B, isdatadescriptor), |
| 1003 | [('dd', A.__dict__['dd'])]) |
| 1004 | |
Antoine Pitrou | 0c60381 | 2012-01-18 17:40:18 +0100 | [diff] [blame] | 1005 | def test_getmembers_method(self): |
| 1006 | class B: |
| 1007 | def f(self): |
| 1008 | pass |
| 1009 | |
| 1010 | self.assertIn(('f', B.f), inspect.getmembers(B)) |
| 1011 | self.assertNotIn(('f', B.f), inspect.getmembers(B, inspect.ismethod)) |
| 1012 | b = B() |
| 1013 | self.assertIn(('f', b.f), inspect.getmembers(b)) |
| 1014 | self.assertIn(('f', b.f), inspect.getmembers(b, inspect.ismethod)) |
| 1015 | |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 1016 | def test_getmembers_VirtualAttribute(self): |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 1017 | class M(type): |
| 1018 | def __getattr__(cls, name): |
| 1019 | if name == 'eggs': |
| 1020 | return 'scrambled' |
| 1021 | return super().__getattr__(name) |
| 1022 | class A(metaclass=M): |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 1023 | @types.DynamicClassAttribute |
| 1024 | def eggs(self): |
| 1025 | return 'spam' |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 1026 | self.assertIn(('eggs', 'scrambled'), inspect.getmembers(A)) |
| 1027 | self.assertIn(('eggs', 'spam'), inspect.getmembers(A())) |
| 1028 | |
| 1029 | def test_getmembers_with_buggy_dir(self): |
| 1030 | class M(type): |
| 1031 | def __dir__(cls): |
| 1032 | return ['__class__', '__name__', 'missing'] |
| 1033 | class C(metaclass=M): |
| 1034 | pass |
| 1035 | attrs = [a[0] for a in inspect.getmembers(C)] |
| 1036 | self.assertNotIn('missing', attrs) |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 1037 | |
Jeremy Hylton | c4bf5ed | 2003-06-27 18:43:12 +0000 | [diff] [blame] | 1038 | |
Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 1039 | _global_ref = object() |
| 1040 | class TestGetClosureVars(unittest.TestCase): |
| 1041 | |
| 1042 | def test_name_resolution(self): |
| 1043 | # Basic test of the 4 different resolution mechanisms |
| 1044 | def f(nonlocal_ref): |
| 1045 | def g(local_ref): |
| 1046 | print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 1047 | return g |
| 1048 | _arg = object() |
| 1049 | nonlocal_vars = {"nonlocal_ref": _arg} |
| 1050 | global_vars = {"_global_ref": _global_ref} |
| 1051 | builtin_vars = {"print": print} |
| 1052 | unbound_names = {"unbound_ref"} |
| 1053 | expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 1054 | builtin_vars, unbound_names) |
| 1055 | self.assertEqual(inspect.getclosurevars(f(_arg)), expected) |
| 1056 | |
| 1057 | def test_generator_closure(self): |
| 1058 | def f(nonlocal_ref): |
| 1059 | def g(local_ref): |
| 1060 | print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 1061 | yield |
| 1062 | return g |
| 1063 | _arg = object() |
| 1064 | nonlocal_vars = {"nonlocal_ref": _arg} |
| 1065 | global_vars = {"_global_ref": _global_ref} |
| 1066 | builtin_vars = {"print": print} |
| 1067 | unbound_names = {"unbound_ref"} |
| 1068 | expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 1069 | builtin_vars, unbound_names) |
| 1070 | self.assertEqual(inspect.getclosurevars(f(_arg)), expected) |
| 1071 | |
| 1072 | def test_method_closure(self): |
| 1073 | class C: |
| 1074 | def f(self, nonlocal_ref): |
| 1075 | def g(local_ref): |
| 1076 | print(local_ref, nonlocal_ref, _global_ref, unbound_ref) |
| 1077 | return g |
| 1078 | _arg = object() |
| 1079 | nonlocal_vars = {"nonlocal_ref": _arg} |
| 1080 | global_vars = {"_global_ref": _global_ref} |
| 1081 | builtin_vars = {"print": print} |
| 1082 | unbound_names = {"unbound_ref"} |
| 1083 | expected = inspect.ClosureVars(nonlocal_vars, global_vars, |
| 1084 | builtin_vars, unbound_names) |
| 1085 | self.assertEqual(inspect.getclosurevars(C().f(_arg)), expected) |
| 1086 | |
| 1087 | def test_nonlocal_vars(self): |
| 1088 | # More complex tests of nonlocal resolution |
| 1089 | def _nonlocal_vars(f): |
| 1090 | return inspect.getclosurevars(f).nonlocals |
| 1091 | |
| 1092 | def make_adder(x): |
| 1093 | def add(y): |
| 1094 | return x + y |
| 1095 | return add |
| 1096 | |
| 1097 | def curry(func, arg1): |
| 1098 | return lambda arg2: func(arg1, arg2) |
| 1099 | |
| 1100 | def less_than(a, b): |
| 1101 | return a < b |
| 1102 | |
| 1103 | # The infamous Y combinator. |
| 1104 | def Y(le): |
| 1105 | def g(f): |
| 1106 | return le(lambda x: f(f)(x)) |
| 1107 | Y.g_ref = g |
| 1108 | return g(g) |
| 1109 | |
| 1110 | def check_y_combinator(func): |
| 1111 | self.assertEqual(_nonlocal_vars(func), {'f': Y.g_ref}) |
| 1112 | |
| 1113 | inc = make_adder(1) |
| 1114 | add_two = make_adder(2) |
| 1115 | greater_than_five = curry(less_than, 5) |
| 1116 | |
| 1117 | self.assertEqual(_nonlocal_vars(inc), {'x': 1}) |
| 1118 | self.assertEqual(_nonlocal_vars(add_two), {'x': 2}) |
| 1119 | self.assertEqual(_nonlocal_vars(greater_than_five), |
| 1120 | {'arg1': 5, 'func': less_than}) |
| 1121 | self.assertEqual(_nonlocal_vars((lambda x: lambda y: x + y)(3)), |
| 1122 | {'x': 3}) |
| 1123 | Y(check_y_combinator) |
| 1124 | |
| 1125 | def test_getclosurevars_empty(self): |
| 1126 | def foo(): pass |
| 1127 | _empty = inspect.ClosureVars({}, {}, {}, set()) |
| 1128 | self.assertEqual(inspect.getclosurevars(lambda: True), _empty) |
| 1129 | self.assertEqual(inspect.getclosurevars(foo), _empty) |
| 1130 | |
| 1131 | def test_getclosurevars_error(self): |
| 1132 | class T: pass |
| 1133 | self.assertRaises(TypeError, inspect.getclosurevars, 1) |
| 1134 | self.assertRaises(TypeError, inspect.getclosurevars, list) |
| 1135 | self.assertRaises(TypeError, inspect.getclosurevars, {}) |
| 1136 | |
Nick Coghlan | 6c6e254 | 2012-06-23 20:07:39 +1000 | [diff] [blame] | 1137 | def _private_globals(self): |
| 1138 | code = """def f(): print(path)""" |
| 1139 | ns = {} |
| 1140 | exec(code, ns) |
| 1141 | return ns["f"], ns |
| 1142 | |
| 1143 | def test_builtins_fallback(self): |
| 1144 | f, ns = self._private_globals() |
| 1145 | ns.pop("__builtins__", None) |
| 1146 | expected = inspect.ClosureVars({}, {}, {"print":print}, {"path"}) |
| 1147 | self.assertEqual(inspect.getclosurevars(f), expected) |
| 1148 | |
| 1149 | def test_builtins_as_dict(self): |
| 1150 | f, ns = self._private_globals() |
| 1151 | ns["__builtins__"] = {"path":1} |
| 1152 | expected = inspect.ClosureVars({}, {}, {"path":1}, {"print"}) |
| 1153 | self.assertEqual(inspect.getclosurevars(f), expected) |
| 1154 | |
| 1155 | def test_builtins_as_module(self): |
| 1156 | f, ns = self._private_globals() |
| 1157 | ns["__builtins__"] = os |
| 1158 | expected = inspect.ClosureVars({}, {}, {"path":os.path}, {"print"}) |
| 1159 | self.assertEqual(inspect.getclosurevars(f), expected) |
| 1160 | |
Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 1161 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1162 | class TestGetcallargsFunctions(unittest.TestCase): |
| 1163 | |
| 1164 | def assertEqualCallArgs(self, func, call_params_string, locs=None): |
| 1165 | locs = dict(locs or {}, func=func) |
| 1166 | r1 = eval('func(%s)' % call_params_string, None, locs) |
| 1167 | r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None, |
| 1168 | locs) |
| 1169 | self.assertEqual(r1, r2) |
| 1170 | |
| 1171 | def assertEqualException(self, func, call_param_string, locs=None): |
| 1172 | locs = dict(locs or {}, func=func) |
| 1173 | try: |
| 1174 | eval('func(%s)' % call_param_string, None, locs) |
| 1175 | except Exception as e: |
| 1176 | ex1 = e |
| 1177 | else: |
| 1178 | self.fail('Exception not raised') |
| 1179 | try: |
| 1180 | eval('inspect.getcallargs(func, %s)' % call_param_string, None, |
| 1181 | locs) |
| 1182 | except Exception as e: |
| 1183 | ex2 = e |
| 1184 | else: |
| 1185 | self.fail('Exception not raised') |
| 1186 | self.assertIs(type(ex1), type(ex2)) |
| 1187 | self.assertEqual(str(ex1), str(ex2)) |
| 1188 | del ex1, ex2 |
| 1189 | |
| 1190 | def makeCallable(self, signature): |
| 1191 | """Create a function that returns its locals()""" |
| 1192 | code = "lambda %s: locals()" |
| 1193 | return eval(code % signature) |
| 1194 | |
| 1195 | def test_plain(self): |
| 1196 | f = self.makeCallable('a, b=1') |
| 1197 | self.assertEqualCallArgs(f, '2') |
| 1198 | self.assertEqualCallArgs(f, '2, 3') |
| 1199 | self.assertEqualCallArgs(f, 'a=2') |
| 1200 | self.assertEqualCallArgs(f, 'b=3, a=2') |
| 1201 | self.assertEqualCallArgs(f, '2, b=3') |
| 1202 | # expand *iterable / **mapping |
| 1203 | self.assertEqualCallArgs(f, '*(2,)') |
| 1204 | self.assertEqualCallArgs(f, '*[2]') |
| 1205 | self.assertEqualCallArgs(f, '*(2, 3)') |
| 1206 | self.assertEqualCallArgs(f, '*[2, 3]') |
| 1207 | self.assertEqualCallArgs(f, '**{"a":2}') |
| 1208 | self.assertEqualCallArgs(f, 'b=3, **{"a":2}') |
| 1209 | self.assertEqualCallArgs(f, '2, **{"b":3}') |
| 1210 | self.assertEqualCallArgs(f, '**{"b":3, "a":2}') |
| 1211 | # expand UserList / UserDict |
| 1212 | self.assertEqualCallArgs(f, '*collections.UserList([2])') |
| 1213 | self.assertEqualCallArgs(f, '*collections.UserList([2, 3])') |
| 1214 | self.assertEqualCallArgs(f, '**collections.UserDict(a=2)') |
| 1215 | self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)') |
| 1216 | self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') |
| 1217 | |
| 1218 | def test_varargs(self): |
| 1219 | f = self.makeCallable('a, b=1, *c') |
| 1220 | self.assertEqualCallArgs(f, '2') |
| 1221 | self.assertEqualCallArgs(f, '2, 3') |
| 1222 | self.assertEqualCallArgs(f, '2, 3, 4') |
| 1223 | self.assertEqualCallArgs(f, '*(2,3,4)') |
| 1224 | self.assertEqualCallArgs(f, '2, *[3,4]') |
| 1225 | self.assertEqualCallArgs(f, '2, 3, *collections.UserList([4])') |
| 1226 | |
| 1227 | def test_varkw(self): |
| 1228 | f = self.makeCallable('a, b=1, **c') |
| 1229 | self.assertEqualCallArgs(f, 'a=2') |
| 1230 | self.assertEqualCallArgs(f, '2, b=3, c=4') |
| 1231 | self.assertEqualCallArgs(f, 'b=3, a=2, c=4') |
| 1232 | self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}') |
| 1233 | self.assertEqualCallArgs(f, '2, c=4, **{"b":3}') |
| 1234 | self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}') |
| 1235 | self.assertEqualCallArgs(f, '**collections.UserDict(a=2, b=3, c=4)') |
| 1236 | self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)') |
| 1237 | self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3, c=4)') |
| 1238 | |
Benjamin Peterson | 6a2638b | 2011-03-28 17:32:31 -0500 | [diff] [blame] | 1239 | def test_varkw_only(self): |
| 1240 | # issue11256: |
| 1241 | f = self.makeCallable('**c') |
| 1242 | self.assertEqualCallArgs(f, '') |
| 1243 | self.assertEqualCallArgs(f, 'a=1') |
| 1244 | self.assertEqualCallArgs(f, 'a=1, b=2') |
| 1245 | self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}') |
| 1246 | self.assertEqualCallArgs(f, '**collections.UserDict(a=1, b=2)') |
| 1247 | self.assertEqualCallArgs(f, 'c=3, **collections.UserDict(a=1, b=2)') |
| 1248 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1249 | def test_keyword_only(self): |
| 1250 | f = self.makeCallable('a=3, *, c, d=2') |
| 1251 | self.assertEqualCallArgs(f, 'c=3') |
| 1252 | self.assertEqualCallArgs(f, 'c=3, a=3') |
| 1253 | self.assertEqualCallArgs(f, 'a=2, c=4') |
| 1254 | self.assertEqualCallArgs(f, '4, c=4') |
| 1255 | self.assertEqualException(f, '') |
| 1256 | self.assertEqualException(f, '3') |
| 1257 | self.assertEqualException(f, 'a=3') |
| 1258 | self.assertEqualException(f, 'd=4') |
| 1259 | |
Benjamin Peterson | 6a2638b | 2011-03-28 17:32:31 -0500 | [diff] [blame] | 1260 | f = self.makeCallable('*, c, d=2') |
| 1261 | self.assertEqualCallArgs(f, 'c=3') |
| 1262 | self.assertEqualCallArgs(f, 'c=3, d=4') |
| 1263 | self.assertEqualCallArgs(f, 'd=4, c=3') |
| 1264 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1265 | def test_multiple_features(self): |
| 1266 | f = self.makeCallable('a, b=2, *f, **g') |
| 1267 | self.assertEqualCallArgs(f, '2, 3, 7') |
| 1268 | self.assertEqualCallArgs(f, '2, 3, x=8') |
| 1269 | self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') |
| 1270 | self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9') |
| 1271 | self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9') |
| 1272 | self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' |
| 1273 | '[2, 3, (4,[5,6])]), **{"y":9, "z":10}') |
| 1274 | self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' |
| 1275 | '(4,[5,6])]), **collections.UserDict(' |
| 1276 | 'y=9, z=10)') |
| 1277 | |
Benjamin Peterson | 6a2638b | 2011-03-28 17:32:31 -0500 | [diff] [blame] | 1278 | f = self.makeCallable('a, b=2, *f, x, y=99, **g') |
| 1279 | self.assertEqualCallArgs(f, '2, 3, x=8') |
| 1280 | self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') |
| 1281 | self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10') |
| 1282 | self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10') |
| 1283 | self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' |
| 1284 | '[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}') |
| 1285 | self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' |
| 1286 | '(4,[5,6])]), q=0, **collections.UserDict(' |
| 1287 | 'y=9, z=10)') |
| 1288 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1289 | def test_errors(self): |
| 1290 | f0 = self.makeCallable('') |
| 1291 | f1 = self.makeCallable('a, b') |
| 1292 | f2 = self.makeCallable('a, b=1') |
| 1293 | # f0 takes no arguments |
| 1294 | self.assertEqualException(f0, '1') |
| 1295 | self.assertEqualException(f0, 'x=1') |
| 1296 | self.assertEqualException(f0, '1,x=1') |
| 1297 | # f1 takes exactly 2 arguments |
| 1298 | self.assertEqualException(f1, '') |
| 1299 | self.assertEqualException(f1, '1') |
| 1300 | self.assertEqualException(f1, 'a=2') |
| 1301 | self.assertEqualException(f1, 'b=3') |
| 1302 | # f2 takes at least 1 argument |
| 1303 | self.assertEqualException(f2, '') |
| 1304 | self.assertEqualException(f2, 'b=3') |
| 1305 | for f in f1, f2: |
| 1306 | # f1/f2 takes exactly/at most 2 arguments |
| 1307 | self.assertEqualException(f, '2, 3, 4') |
| 1308 | self.assertEqualException(f, '1, 2, 3, a=1') |
| 1309 | self.assertEqualException(f, '2, 3, 4, c=5') |
Georg Brandl | 178e5ea | 2012-02-21 00:32:36 +0100 | [diff] [blame] | 1310 | # XXX: success of this one depends on dict order |
| 1311 | ## self.assertEqualException(f, '2, 3, 4, a=1, c=5') |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1312 | # f got an unexpected keyword argument |
| 1313 | self.assertEqualException(f, 'c=2') |
| 1314 | self.assertEqualException(f, '2, c=3') |
| 1315 | self.assertEqualException(f, '2, 3, c=4') |
| 1316 | self.assertEqualException(f, '2, c=4, b=3') |
| 1317 | self.assertEqualException(f, '**{u"\u03c0\u03b9": 4}') |
| 1318 | # f got multiple values for keyword argument |
| 1319 | self.assertEqualException(f, '1, a=2') |
| 1320 | self.assertEqualException(f, '1, **{"a":2}') |
| 1321 | self.assertEqualException(f, '1, 2, b=3') |
| 1322 | # XXX: Python inconsistency |
| 1323 | # - for functions and bound methods: unexpected keyword 'c' |
| 1324 | # - for unbound methods: multiple values for keyword 'a' |
| 1325 | #self.assertEqualException(f, '1, c=3, a=2') |
Benjamin Peterson | 6a2638b | 2011-03-28 17:32:31 -0500 | [diff] [blame] | 1326 | # issue11256: |
| 1327 | f3 = self.makeCallable('**c') |
| 1328 | self.assertEqualException(f3, '1, 2') |
| 1329 | self.assertEqualException(f3, '1, 2, a=1, b=2') |
| 1330 | f4 = self.makeCallable('*, a, b=0') |
| 1331 | self.assertEqualException(f3, '1, 2') |
| 1332 | self.assertEqualException(f3, '1, 2, a=1, b=2') |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1333 | |
Yury Selivanov | 875df20 | 2014-03-27 18:23:03 -0400 | [diff] [blame] | 1334 | # issue #20816: getcallargs() fails to iterate over non-existent |
| 1335 | # kwonlydefaults and raises a wrong TypeError |
| 1336 | def f5(*, a): pass |
| 1337 | with self.assertRaisesRegex(TypeError, |
| 1338 | 'missing 1 required keyword-only'): |
| 1339 | inspect.getcallargs(f5) |
| 1340 | |
| 1341 | |
Yury Selivanov | dccfa13 | 2014-03-27 18:42:52 -0400 | [diff] [blame] | 1342 | # issue20817: |
| 1343 | def f6(a, b, c): |
| 1344 | pass |
| 1345 | with self.assertRaisesRegex(TypeError, "'a', 'b' and 'c'"): |
| 1346 | inspect.getcallargs(f6) |
| 1347 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 1348 | class TestGetcallargsMethods(TestGetcallargsFunctions): |
| 1349 | |
| 1350 | def setUp(self): |
| 1351 | class Foo(object): |
| 1352 | pass |
| 1353 | self.cls = Foo |
| 1354 | self.inst = Foo() |
| 1355 | |
| 1356 | def makeCallable(self, signature): |
| 1357 | assert 'self' not in signature |
| 1358 | mk = super(TestGetcallargsMethods, self).makeCallable |
| 1359 | self.cls.method = mk('self, ' + signature) |
| 1360 | return self.inst.method |
| 1361 | |
| 1362 | class TestGetcallargsUnboundMethods(TestGetcallargsMethods): |
| 1363 | |
| 1364 | def makeCallable(self, signature): |
| 1365 | super(TestGetcallargsUnboundMethods, self).makeCallable(signature) |
| 1366 | return self.cls.method |
| 1367 | |
| 1368 | def assertEqualCallArgs(self, func, call_params_string, locs=None): |
| 1369 | return super(TestGetcallargsUnboundMethods, self).assertEqualCallArgs( |
| 1370 | *self._getAssertEqualParams(func, call_params_string, locs)) |
| 1371 | |
| 1372 | def assertEqualException(self, func, call_params_string, locs=None): |
| 1373 | return super(TestGetcallargsUnboundMethods, self).assertEqualException( |
| 1374 | *self._getAssertEqualParams(func, call_params_string, locs)) |
| 1375 | |
| 1376 | def _getAssertEqualParams(self, func, call_params_string, locs=None): |
| 1377 | assert 'inst' not in call_params_string |
| 1378 | locs = dict(locs or {}, inst=self.inst) |
| 1379 | return (func, 'inst,' + call_params_string, locs) |
| 1380 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1381 | |
| 1382 | class TestGetattrStatic(unittest.TestCase): |
| 1383 | |
| 1384 | def test_basic(self): |
| 1385 | class Thing(object): |
| 1386 | x = object() |
| 1387 | |
| 1388 | thing = Thing() |
| 1389 | self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1390 | self.assertEqual(inspect.getattr_static(thing, 'x', None), Thing.x) |
| 1391 | with self.assertRaises(AttributeError): |
| 1392 | inspect.getattr_static(thing, 'y') |
| 1393 | |
| 1394 | self.assertEqual(inspect.getattr_static(thing, 'y', 3), 3) |
| 1395 | |
| 1396 | def test_inherited(self): |
| 1397 | class Thing(object): |
| 1398 | x = object() |
| 1399 | class OtherThing(Thing): |
| 1400 | pass |
| 1401 | |
| 1402 | something = OtherThing() |
| 1403 | self.assertEqual(inspect.getattr_static(something, 'x'), Thing.x) |
| 1404 | |
| 1405 | def test_instance_attr(self): |
| 1406 | class Thing(object): |
| 1407 | x = 2 |
| 1408 | def __init__(self, x): |
| 1409 | self.x = x |
| 1410 | thing = Thing(3) |
| 1411 | self.assertEqual(inspect.getattr_static(thing, 'x'), 3) |
| 1412 | del thing.x |
| 1413 | self.assertEqual(inspect.getattr_static(thing, 'x'), 2) |
| 1414 | |
| 1415 | def test_property(self): |
| 1416 | class Thing(object): |
| 1417 | @property |
| 1418 | def x(self): |
| 1419 | raise AttributeError("I'm pretending not to exist") |
| 1420 | thing = Thing() |
| 1421 | self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1422 | |
Ezio Melotti | 75cbd73 | 2011-04-28 00:59:29 +0300 | [diff] [blame] | 1423 | def test_descriptor_raises_AttributeError(self): |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1424 | class descriptor(object): |
| 1425 | def __get__(*_): |
| 1426 | raise AttributeError("I'm pretending not to exist") |
| 1427 | desc = descriptor() |
| 1428 | class Thing(object): |
| 1429 | x = desc |
| 1430 | thing = Thing() |
| 1431 | self.assertEqual(inspect.getattr_static(thing, 'x'), desc) |
| 1432 | |
| 1433 | def test_classAttribute(self): |
| 1434 | class Thing(object): |
| 1435 | x = object() |
| 1436 | |
| 1437 | self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.x) |
| 1438 | |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 1439 | def test_classVirtualAttribute(self): |
| 1440 | class Thing(object): |
| 1441 | @types.DynamicClassAttribute |
| 1442 | def x(self): |
| 1443 | return self._x |
| 1444 | _x = object() |
| 1445 | |
| 1446 | self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.__dict__['x']) |
| 1447 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1448 | def test_inherited_classattribute(self): |
| 1449 | class Thing(object): |
| 1450 | x = object() |
| 1451 | class OtherThing(Thing): |
| 1452 | pass |
| 1453 | |
| 1454 | self.assertEqual(inspect.getattr_static(OtherThing, 'x'), Thing.x) |
| 1455 | |
| 1456 | def test_slots(self): |
| 1457 | class Thing(object): |
| 1458 | y = 'bar' |
| 1459 | __slots__ = ['x'] |
| 1460 | def __init__(self): |
| 1461 | self.x = 'foo' |
| 1462 | thing = Thing() |
| 1463 | self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1464 | self.assertEqual(inspect.getattr_static(thing, 'y'), 'bar') |
| 1465 | |
| 1466 | del thing.x |
| 1467 | self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x) |
| 1468 | |
| 1469 | def test_metaclass(self): |
| 1470 | class meta(type): |
| 1471 | attr = 'foo' |
| 1472 | class Thing(object, metaclass=meta): |
| 1473 | pass |
| 1474 | self.assertEqual(inspect.getattr_static(Thing, 'attr'), 'foo') |
| 1475 | |
| 1476 | class sub(meta): |
| 1477 | pass |
| 1478 | class OtherThing(object, metaclass=sub): |
| 1479 | x = 3 |
| 1480 | self.assertEqual(inspect.getattr_static(OtherThing, 'attr'), 'foo') |
| 1481 | |
| 1482 | class OtherOtherThing(OtherThing): |
| 1483 | pass |
| 1484 | # this test is odd, but it was added as it exposed a bug |
| 1485 | self.assertEqual(inspect.getattr_static(OtherOtherThing, 'x'), 3) |
| 1486 | |
| 1487 | def test_no_dict_no_slots(self): |
| 1488 | self.assertEqual(inspect.getattr_static(1, 'foo', None), None) |
| 1489 | self.assertNotEqual(inspect.getattr_static('foo', 'lower'), None) |
| 1490 | |
| 1491 | def test_no_dict_no_slots_instance_member(self): |
| 1492 | # returns descriptor |
| 1493 | with open(__file__) as handle: |
| 1494 | self.assertEqual(inspect.getattr_static(handle, 'name'), type(handle).name) |
| 1495 | |
| 1496 | def test_inherited_slots(self): |
| 1497 | # returns descriptor |
| 1498 | class Thing(object): |
| 1499 | __slots__ = ['x'] |
| 1500 | def __init__(self): |
| 1501 | self.x = 'foo' |
| 1502 | |
| 1503 | class OtherThing(Thing): |
| 1504 | pass |
| 1505 | # it would be nice if this worked... |
| 1506 | # we get the descriptor instead of the instance attribute |
| 1507 | self.assertEqual(inspect.getattr_static(OtherThing(), 'x'), Thing.x) |
| 1508 | |
| 1509 | def test_descriptor(self): |
| 1510 | class descriptor(object): |
| 1511 | def __get__(self, instance, owner): |
| 1512 | return 3 |
| 1513 | class Foo(object): |
| 1514 | d = descriptor() |
| 1515 | |
| 1516 | foo = Foo() |
| 1517 | |
| 1518 | # for a non data descriptor we return the instance attribute |
| 1519 | foo.__dict__['d'] = 1 |
| 1520 | self.assertEqual(inspect.getattr_static(foo, 'd'), 1) |
| 1521 | |
| 1522 | # if the descriptor is a data-desciptor we should return the |
| 1523 | # descriptor |
| 1524 | descriptor.__set__ = lambda s, i, v: None |
| 1525 | self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d']) |
| 1526 | |
| 1527 | |
| 1528 | def test_metaclass_with_descriptor(self): |
| 1529 | class descriptor(object): |
| 1530 | def __get__(self, instance, owner): |
| 1531 | return 3 |
| 1532 | class meta(type): |
| 1533 | d = descriptor() |
| 1534 | class Thing(object, metaclass=meta): |
| 1535 | pass |
| 1536 | self.assertEqual(inspect.getattr_static(Thing, 'd'), meta.__dict__['d']) |
| 1537 | |
| 1538 | |
Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame] | 1539 | def test_class_as_property(self): |
| 1540 | class Base(object): |
| 1541 | foo = 3 |
| 1542 | |
| 1543 | class Something(Base): |
Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1544 | executed = False |
Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame] | 1545 | @property |
| 1546 | def __class__(self): |
Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1547 | self.executed = True |
Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame] | 1548 | return object |
| 1549 | |
Michael Foord | 35184ed | 2010-11-20 16:58:30 +0000 | [diff] [blame] | 1550 | instance = Something() |
| 1551 | self.assertEqual(inspect.getattr_static(instance, 'foo'), 3) |
| 1552 | self.assertFalse(instance.executed) |
Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame] | 1553 | self.assertEqual(inspect.getattr_static(Something, 'foo'), 3) |
| 1554 | |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1555 | def test_mro_as_property(self): |
| 1556 | class Meta(type): |
| 1557 | @property |
| 1558 | def __mro__(self): |
| 1559 | return (object,) |
| 1560 | |
| 1561 | class Base(object): |
| 1562 | foo = 3 |
| 1563 | |
| 1564 | class Something(Base, metaclass=Meta): |
| 1565 | pass |
| 1566 | |
| 1567 | self.assertEqual(inspect.getattr_static(Something(), 'foo'), 3) |
| 1568 | self.assertEqual(inspect.getattr_static(Something, 'foo'), 3) |
| 1569 | |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1570 | def test_dict_as_property(self): |
| 1571 | test = self |
| 1572 | test.called = False |
| 1573 | |
| 1574 | class Foo(dict): |
| 1575 | a = 3 |
| 1576 | @property |
| 1577 | def __dict__(self): |
| 1578 | test.called = True |
| 1579 | return {} |
| 1580 | |
| 1581 | foo = Foo() |
| 1582 | foo.a = 4 |
| 1583 | self.assertEqual(inspect.getattr_static(foo, 'a'), 3) |
| 1584 | self.assertFalse(test.called) |
| 1585 | |
| 1586 | def test_custom_object_dict(self): |
| 1587 | test = self |
| 1588 | test.called = False |
| 1589 | |
| 1590 | class Custom(dict): |
| 1591 | def get(self, key, default=None): |
| 1592 | test.called = True |
| 1593 | super().get(key, default) |
| 1594 | |
| 1595 | class Foo(object): |
| 1596 | a = 3 |
| 1597 | foo = Foo() |
| 1598 | foo.__dict__ = Custom() |
| 1599 | self.assertEqual(inspect.getattr_static(foo, 'a'), 3) |
| 1600 | self.assertFalse(test.called) |
| 1601 | |
| 1602 | def test_metaclass_dict_as_property(self): |
| 1603 | class Meta(type): |
| 1604 | @property |
| 1605 | def __dict__(self): |
| 1606 | self.executed = True |
| 1607 | |
| 1608 | class Thing(metaclass=Meta): |
| 1609 | executed = False |
| 1610 | |
| 1611 | def __init__(self): |
| 1612 | self.spam = 42 |
| 1613 | |
| 1614 | instance = Thing() |
| 1615 | self.assertEqual(inspect.getattr_static(instance, "spam"), 42) |
| 1616 | self.assertFalse(Thing.executed) |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1617 | |
Michael Foord | a51623b | 2011-12-18 22:01:40 +0000 | [diff] [blame] | 1618 | def test_module(self): |
| 1619 | sentinel = object() |
| 1620 | self.assertIsNot(inspect.getattr_static(sys, "version", sentinel), |
| 1621 | sentinel) |
| 1622 | |
Michael Foord | 3ba95f8 | 2011-12-22 01:13:37 +0000 | [diff] [blame] | 1623 | def test_metaclass_with_metaclass_with_dict_as_property(self): |
| 1624 | class MetaMeta(type): |
| 1625 | @property |
| 1626 | def __dict__(self): |
| 1627 | self.executed = True |
| 1628 | return dict(spam=42) |
| 1629 | |
| 1630 | class Meta(type, metaclass=MetaMeta): |
| 1631 | executed = False |
| 1632 | |
| 1633 | class Thing(metaclass=Meta): |
| 1634 | pass |
| 1635 | |
| 1636 | with self.assertRaises(AttributeError): |
| 1637 | inspect.getattr_static(Thing, "spam") |
| 1638 | self.assertFalse(Thing.executed) |
| 1639 | |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1640 | class TestGetGeneratorState(unittest.TestCase): |
| 1641 | |
| 1642 | def setUp(self): |
| 1643 | def number_generator(): |
| 1644 | for number in range(5): |
| 1645 | yield number |
| 1646 | self.generator = number_generator() |
| 1647 | |
| 1648 | def _generatorstate(self): |
| 1649 | return inspect.getgeneratorstate(self.generator) |
| 1650 | |
| 1651 | def test_created(self): |
| 1652 | self.assertEqual(self._generatorstate(), inspect.GEN_CREATED) |
| 1653 | |
| 1654 | def test_suspended(self): |
| 1655 | next(self.generator) |
| 1656 | self.assertEqual(self._generatorstate(), inspect.GEN_SUSPENDED) |
| 1657 | |
| 1658 | def test_closed_after_exhaustion(self): |
| 1659 | for i in self.generator: |
| 1660 | pass |
| 1661 | self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 1662 | |
| 1663 | def test_closed_after_immediate_exception(self): |
| 1664 | with self.assertRaises(RuntimeError): |
| 1665 | self.generator.throw(RuntimeError) |
| 1666 | self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED) |
| 1667 | |
| 1668 | def test_running(self): |
| 1669 | # As mentioned on issue #10220, checking for the RUNNING state only |
| 1670 | # makes sense inside the generator itself. |
| 1671 | # The following generator checks for this by using the closure's |
| 1672 | # reference to self and the generator state checking helper method |
| 1673 | def running_check_generator(): |
| 1674 | for number in range(5): |
| 1675 | self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING) |
| 1676 | yield number |
| 1677 | self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING) |
| 1678 | self.generator = running_check_generator() |
| 1679 | # Running up to the first yield |
| 1680 | next(self.generator) |
| 1681 | # Running after the first yield |
| 1682 | next(self.generator) |
| 1683 | |
Nick Coghlan | 7921b9f | 2010-11-30 06:36:04 +0000 | [diff] [blame] | 1684 | def test_easy_debugging(self): |
| 1685 | # repr() and str() of a generator state should contain the state name |
| 1686 | names = 'GEN_CREATED GEN_RUNNING GEN_SUSPENDED GEN_CLOSED'.split() |
| 1687 | for name in names: |
| 1688 | state = getattr(inspect, name) |
| 1689 | self.assertIn(name, repr(state)) |
| 1690 | self.assertIn(name, str(state)) |
| 1691 | |
Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1692 | def test_getgeneratorlocals(self): |
| 1693 | def each(lst, a=None): |
| 1694 | b=(1, 2, 3) |
| 1695 | for v in lst: |
| 1696 | if v == 3: |
| 1697 | c = 12 |
| 1698 | yield v |
| 1699 | |
| 1700 | numbers = each([1, 2, 3]) |
| 1701 | self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 1702 | {'a': None, 'lst': [1, 2, 3]}) |
| 1703 | next(numbers) |
| 1704 | self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 1705 | {'a': None, 'lst': [1, 2, 3], 'v': 1, |
| 1706 | 'b': (1, 2, 3)}) |
| 1707 | next(numbers) |
| 1708 | self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 1709 | {'a': None, 'lst': [1, 2, 3], 'v': 2, |
| 1710 | 'b': (1, 2, 3)}) |
| 1711 | next(numbers) |
| 1712 | self.assertEqual(inspect.getgeneratorlocals(numbers), |
| 1713 | {'a': None, 'lst': [1, 2, 3], 'v': 3, |
| 1714 | 'b': (1, 2, 3), 'c': 12}) |
| 1715 | try: |
| 1716 | next(numbers) |
| 1717 | except StopIteration: |
| 1718 | pass |
| 1719 | self.assertEqual(inspect.getgeneratorlocals(numbers), {}) |
| 1720 | |
| 1721 | def test_getgeneratorlocals_empty(self): |
| 1722 | def yield_one(): |
| 1723 | yield 1 |
| 1724 | one = yield_one() |
| 1725 | self.assertEqual(inspect.getgeneratorlocals(one), {}) |
| 1726 | try: |
| 1727 | next(one) |
| 1728 | except StopIteration: |
| 1729 | pass |
| 1730 | self.assertEqual(inspect.getgeneratorlocals(one), {}) |
| 1731 | |
| 1732 | def test_getgeneratorlocals_error(self): |
| 1733 | self.assertRaises(TypeError, inspect.getgeneratorlocals, 1) |
| 1734 | self.assertRaises(TypeError, inspect.getgeneratorlocals, lambda x: True) |
| 1735 | self.assertRaises(TypeError, inspect.getgeneratorlocals, set) |
| 1736 | self.assertRaises(TypeError, inspect.getgeneratorlocals, (2,3)) |
| 1737 | |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1738 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1739 | class TestGetCoroutineState(unittest.TestCase): |
| 1740 | |
| 1741 | def setUp(self): |
| 1742 | @types.coroutine |
| 1743 | def number_coroutine(): |
| 1744 | for number in range(5): |
| 1745 | yield number |
| 1746 | async def coroutine(): |
| 1747 | await number_coroutine() |
| 1748 | self.coroutine = coroutine() |
| 1749 | |
| 1750 | def tearDown(self): |
| 1751 | self.coroutine.close() |
| 1752 | |
| 1753 | def _coroutinestate(self): |
| 1754 | return inspect.getcoroutinestate(self.coroutine) |
| 1755 | |
| 1756 | def test_created(self): |
| 1757 | self.assertEqual(self._coroutinestate(), inspect.CORO_CREATED) |
| 1758 | |
| 1759 | def test_suspended(self): |
| 1760 | self.coroutine.send(None) |
| 1761 | self.assertEqual(self._coroutinestate(), inspect.CORO_SUSPENDED) |
| 1762 | |
| 1763 | def test_closed_after_exhaustion(self): |
| 1764 | while True: |
| 1765 | try: |
| 1766 | self.coroutine.send(None) |
| 1767 | except StopIteration: |
| 1768 | break |
| 1769 | |
| 1770 | self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 1771 | |
| 1772 | def test_closed_after_immediate_exception(self): |
| 1773 | with self.assertRaises(RuntimeError): |
| 1774 | self.coroutine.throw(RuntimeError) |
| 1775 | self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED) |
| 1776 | |
| 1777 | def test_easy_debugging(self): |
| 1778 | # repr() and str() of a coroutine state should contain the state name |
| 1779 | names = 'CORO_CREATED CORO_RUNNING CORO_SUSPENDED CORO_CLOSED'.split() |
| 1780 | for name in names: |
| 1781 | state = getattr(inspect, name) |
| 1782 | self.assertIn(name, repr(state)) |
| 1783 | self.assertIn(name, str(state)) |
| 1784 | |
| 1785 | def test_getcoroutinelocals(self): |
| 1786 | @types.coroutine |
| 1787 | def gencoro(): |
| 1788 | yield |
| 1789 | |
| 1790 | gencoro = gencoro() |
| 1791 | async def func(a=None): |
| 1792 | b = 'spam' |
| 1793 | await gencoro |
| 1794 | |
| 1795 | coro = func() |
| 1796 | self.assertEqual(inspect.getcoroutinelocals(coro), |
| 1797 | {'a': None, 'gencoro': gencoro}) |
| 1798 | coro.send(None) |
| 1799 | self.assertEqual(inspect.getcoroutinelocals(coro), |
| 1800 | {'a': None, 'gencoro': gencoro, 'b': 'spam'}) |
| 1801 | |
| 1802 | |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 1803 | class MySignature(inspect.Signature): |
| 1804 | # Top-level to make it picklable; |
| 1805 | # used in test_signature_object_pickle |
| 1806 | pass |
| 1807 | |
| 1808 | class MyParameter(inspect.Parameter): |
| 1809 | # Top-level to make it picklable; |
| 1810 | # used in test_signature_object_pickle |
| 1811 | pass |
| 1812 | |
Nick Coghlan | f9e227e | 2014-08-17 14:01:19 +1000 | [diff] [blame] | 1813 | |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 1814 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1815 | class TestSignatureObject(unittest.TestCase): |
| 1816 | @staticmethod |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 1817 | def signature(func, **kw): |
| 1818 | sig = inspect.signature(func, **kw) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1819 | return (tuple((param.name, |
| 1820 | (... if param.default is param.empty else param.default), |
| 1821 | (... if param.annotation is param.empty |
| 1822 | else param.annotation), |
| 1823 | str(param.kind).lower()) |
| 1824 | for param in sig.parameters.values()), |
| 1825 | (... if sig.return_annotation is sig.empty |
| 1826 | else sig.return_annotation)) |
| 1827 | |
| 1828 | def test_signature_object(self): |
| 1829 | S = inspect.Signature |
| 1830 | P = inspect.Parameter |
| 1831 | |
| 1832 | self.assertEqual(str(S()), '()') |
| 1833 | |
Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 1834 | def test(po, pk, pod=42, pkd=100, *args, ko, **kwargs): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1835 | pass |
| 1836 | sig = inspect.signature(test) |
| 1837 | po = sig.parameters['po'].replace(kind=P.POSITIONAL_ONLY) |
Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 1838 | pod = sig.parameters['pod'].replace(kind=P.POSITIONAL_ONLY) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1839 | pk = sig.parameters['pk'] |
Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 1840 | pkd = sig.parameters['pkd'] |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1841 | args = sig.parameters['args'] |
| 1842 | ko = sig.parameters['ko'] |
| 1843 | kwargs = sig.parameters['kwargs'] |
| 1844 | |
| 1845 | S((po, pk, args, ko, kwargs)) |
| 1846 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 1847 | with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1848 | S((pk, po, args, ko, kwargs)) |
| 1849 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 1850 | with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1851 | S((po, args, pk, ko, kwargs)) |
| 1852 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 1853 | with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1854 | S((args, po, pk, ko, kwargs)) |
| 1855 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 1856 | with self.assertRaisesRegex(ValueError, 'wrong parameter order'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1857 | S((po, pk, args, kwargs, ko)) |
| 1858 | |
| 1859 | kwargs2 = kwargs.replace(name='args') |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 1860 | with self.assertRaisesRegex(ValueError, 'duplicate parameter name'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1861 | S((po, pk, args, kwargs2, ko)) |
| 1862 | |
Yury Selivanov | 07a9e45 | 2014-01-29 10:58:16 -0500 | [diff] [blame] | 1863 | with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 1864 | S((pod, po)) |
| 1865 | |
| 1866 | with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 1867 | S((po, pkd, pk)) |
| 1868 | |
| 1869 | with self.assertRaisesRegex(ValueError, 'follows default argument'): |
| 1870 | S((pkd, pk)) |
| 1871 | |
Yury Selivanov | 374375d | 2014-03-27 12:41:53 -0400 | [diff] [blame] | 1872 | self.assertTrue(repr(sig).startswith('<Signature')) |
Yury Selivanov | 0cd2bf4 | 2015-05-15 12:55:20 -0400 | [diff] [blame] | 1873 | self.assertTrue('(po, pk' in repr(sig)) |
Yury Selivanov | 374375d | 2014-03-27 12:41:53 -0400 | [diff] [blame] | 1874 | |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 1875 | def test_signature_object_pickle(self): |
| 1876 | def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 1877 | foo_partial = functools.partial(foo, a=1) |
| 1878 | |
| 1879 | sig = inspect.signature(foo_partial) |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 1880 | |
| 1881 | for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1882 | with self.subTest(pickle_ver=ver, subclass=False): |
| 1883 | sig_pickled = pickle.loads(pickle.dumps(sig, ver)) |
| 1884 | self.assertEqual(sig, sig_pickled) |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 1885 | |
| 1886 | # Test that basic sub-classing works |
| 1887 | sig = inspect.signature(foo) |
| 1888 | myparam = MyParameter(name='z', kind=inspect.Parameter.POSITIONAL_ONLY) |
| 1889 | myparams = collections.OrderedDict(sig.parameters, a=myparam) |
| 1890 | mysig = MySignature().replace(parameters=myparams.values(), |
| 1891 | return_annotation=sig.return_annotation) |
| 1892 | self.assertTrue(isinstance(mysig, MySignature)) |
| 1893 | self.assertTrue(isinstance(mysig.parameters['z'], MyParameter)) |
| 1894 | |
| 1895 | for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1896 | with self.subTest(pickle_ver=ver, subclass=True): |
| 1897 | sig_pickled = pickle.loads(pickle.dumps(mysig, ver)) |
| 1898 | self.assertEqual(mysig, sig_pickled) |
| 1899 | self.assertTrue(isinstance(sig_pickled, MySignature)) |
| 1900 | self.assertTrue(isinstance(sig_pickled.parameters['z'], |
| 1901 | MyParameter)) |
| 1902 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1903 | def test_signature_immutability(self): |
| 1904 | def test(a): |
| 1905 | pass |
| 1906 | sig = inspect.signature(test) |
| 1907 | |
| 1908 | with self.assertRaises(AttributeError): |
| 1909 | sig.foo = 'bar' |
| 1910 | |
| 1911 | with self.assertRaises(TypeError): |
| 1912 | sig.parameters['a'] = None |
| 1913 | |
| 1914 | def test_signature_on_noarg(self): |
| 1915 | def test(): |
| 1916 | pass |
| 1917 | self.assertEqual(self.signature(test), ((), ...)) |
| 1918 | |
| 1919 | def test_signature_on_wargs(self): |
| 1920 | def test(a, b:'foo') -> 123: |
| 1921 | pass |
| 1922 | self.assertEqual(self.signature(test), |
| 1923 | ((('a', ..., ..., "positional_or_keyword"), |
| 1924 | ('b', ..., 'foo', "positional_or_keyword")), |
| 1925 | 123)) |
| 1926 | |
| 1927 | def test_signature_on_wkwonly(self): |
| 1928 | def test(*, a:float, b:str) -> int: |
| 1929 | pass |
| 1930 | self.assertEqual(self.signature(test), |
| 1931 | ((('a', ..., float, "keyword_only"), |
| 1932 | ('b', ..., str, "keyword_only")), |
| 1933 | int)) |
| 1934 | |
| 1935 | def test_signature_on_complex_args(self): |
| 1936 | def test(a, b:'foo'=10, *args:'bar', spam:'baz', ham=123, **kwargs:int): |
| 1937 | pass |
| 1938 | self.assertEqual(self.signature(test), |
| 1939 | ((('a', ..., ..., "positional_or_keyword"), |
| 1940 | ('b', 10, 'foo', "positional_or_keyword"), |
| 1941 | ('args', ..., 'bar', "var_positional"), |
| 1942 | ('spam', ..., 'baz', "keyword_only"), |
| 1943 | ('ham', 123, ..., "keyword_only"), |
| 1944 | ('kwargs', ..., int, "var_keyword")), |
| 1945 | ...)) |
| 1946 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 1947 | @cpython_only |
Larry Hastings | fcafe43 | 2013-11-23 17:35:48 -0800 | [diff] [blame] | 1948 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 1949 | "Signature information for builtins requires docstrings") |
| 1950 | def test_signature_on_builtins(self): |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 1951 | import _testcapi |
Larry Hastings | 16c5191 | 2014-01-07 11:53:01 -0800 | [diff] [blame] | 1952 | |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 1953 | def test_unbound_method(o): |
| 1954 | """Use this to test unbound methods (things that should have a self)""" |
| 1955 | signature = inspect.signature(o) |
| 1956 | self.assertTrue(isinstance(signature, inspect.Signature)) |
| 1957 | self.assertEqual(list(signature.parameters.values())[0].name, 'self') |
| 1958 | return signature |
| 1959 | |
| 1960 | def test_callable(o): |
| 1961 | """Use this to test bound methods or normal callables (things that don't expect self)""" |
| 1962 | signature = inspect.signature(o) |
| 1963 | self.assertTrue(isinstance(signature, inspect.Signature)) |
| 1964 | if signature.parameters: |
| 1965 | self.assertNotEqual(list(signature.parameters.values())[0].name, 'self') |
| 1966 | return signature |
| 1967 | |
| 1968 | signature = test_callable(_testcapi.docstring_with_signature_with_defaults) |
Larry Hastings | 16c5191 | 2014-01-07 11:53:01 -0800 | [diff] [blame] | 1969 | def p(name): return signature.parameters[name].default |
| 1970 | self.assertEqual(p('s'), 'avocado') |
Larry Hastings | 2a72791 | 2014-01-16 11:32:01 -0800 | [diff] [blame] | 1971 | self.assertEqual(p('b'), b'bytes') |
Larry Hastings | 16c5191 | 2014-01-07 11:53:01 -0800 | [diff] [blame] | 1972 | self.assertEqual(p('d'), 3.14) |
| 1973 | self.assertEqual(p('i'), 35) |
Larry Hastings | 16c5191 | 2014-01-07 11:53:01 -0800 | [diff] [blame] | 1974 | self.assertEqual(p('n'), None) |
| 1975 | self.assertEqual(p('t'), True) |
| 1976 | self.assertEqual(p('f'), False) |
Larry Hastings | 2a72791 | 2014-01-16 11:32:01 -0800 | [diff] [blame] | 1977 | self.assertEqual(p('local'), 3) |
| 1978 | self.assertEqual(p('sys'), sys.maxsize) |
| 1979 | self.assertEqual(p('exp'), sys.maxsize - 1) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 1980 | |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 1981 | test_callable(object) |
| 1982 | |
| 1983 | # normal method |
| 1984 | # (PyMethodDescr_Type, "method_descriptor") |
| 1985 | test_unbound_method(_pickle.Pickler.dump) |
| 1986 | d = _pickle.Pickler(io.StringIO()) |
| 1987 | test_callable(d.dump) |
| 1988 | |
| 1989 | # static method |
| 1990 | test_callable(str.maketrans) |
| 1991 | test_callable('abc'.maketrans) |
| 1992 | |
| 1993 | # class method |
| 1994 | test_callable(dict.fromkeys) |
| 1995 | test_callable({}.fromkeys) |
| 1996 | |
| 1997 | # wrapper around slot (PyWrapperDescr_Type, "wrapper_descriptor") |
| 1998 | test_unbound_method(type.__call__) |
| 1999 | test_unbound_method(int.__add__) |
| 2000 | test_callable((3).__add__) |
| 2001 | |
| 2002 | # _PyMethodWrapper_Type |
| 2003 | # support for 'method-wrapper' |
| 2004 | test_callable(min.__call__) |
| 2005 | |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2006 | # This doesn't work now. |
| 2007 | # (We don't have a valid signature for "type" in 3.4) |
| 2008 | with self.assertRaisesRegex(ValueError, "no signature found"): |
| 2009 | class ThisWorksNow: |
| 2010 | __call__ = type |
| 2011 | test_callable(ThisWorksNow()) |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 2012 | |
Yury Selivanov | 056e265 | 2014-03-02 12:25:27 -0500 | [diff] [blame] | 2013 | # Regression test for issue #20786 |
| 2014 | test_unbound_method(dict.__delitem__) |
| 2015 | test_unbound_method(property.__delete__) |
| 2016 | |
Zachary Ware | 8ef887c | 2015-04-13 18:22:35 -0500 | [diff] [blame] | 2017 | # Regression test for issue #20586 |
| 2018 | test_callable(_testcapi.docstring_with_signature_but_no_doc) |
| 2019 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 2020 | @cpython_only |
Yury Selivanov | 76c6c59 | 2014-01-29 10:52:57 -0500 | [diff] [blame] | 2021 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 2022 | "Signature information for builtins requires docstrings") |
| 2023 | def test_signature_on_decorated_builtins(self): |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 2024 | import _testcapi |
Yury Selivanov | 76c6c59 | 2014-01-29 10:52:57 -0500 | [diff] [blame] | 2025 | func = _testcapi.docstring_with_signature_with_defaults |
| 2026 | |
| 2027 | def decorator(func): |
| 2028 | @functools.wraps(func) |
| 2029 | def wrapper(*args, **kwargs) -> int: |
| 2030 | return func(*args, **kwargs) |
| 2031 | return wrapper |
| 2032 | |
| 2033 | decorated_func = decorator(func) |
| 2034 | |
| 2035 | self.assertEqual(inspect.signature(func), |
| 2036 | inspect.signature(decorated_func)) |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 2037 | |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 2038 | def wrapper_like(*args, **kwargs) -> int: pass |
| 2039 | self.assertEqual(inspect.signature(decorated_func, |
| 2040 | follow_wrapped=False), |
| 2041 | inspect.signature(wrapper_like)) |
| 2042 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 2043 | @cpython_only |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 2044 | def test_signature_on_builtins_no_signature(self): |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 2045 | import _testcapi |
Yury Selivanov | bf304fc | 2015-05-30 17:08:36 -0400 | [diff] [blame] | 2046 | with self.assertRaisesRegex(ValueError, |
| 2047 | 'no signature found for builtin'): |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 2048 | inspect.signature(_testcapi.docstring_no_signature) |
| 2049 | |
Yury Selivanov | bf304fc | 2015-05-30 17:08:36 -0400 | [diff] [blame] | 2050 | with self.assertRaisesRegex(ValueError, |
| 2051 | 'no signature found for builtin'): |
| 2052 | inspect.signature(str) |
| 2053 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2054 | def test_signature_on_non_function(self): |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2055 | with self.assertRaisesRegex(TypeError, 'is not a callable object'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2056 | inspect.signature(42) |
| 2057 | |
Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 2058 | def test_signature_from_functionlike_object(self): |
| 2059 | def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): |
| 2060 | pass |
| 2061 | |
| 2062 | class funclike: |
| 2063 | # Has to be callable, and have correct |
| 2064 | # __code__, __annotations__, __defaults__, __name__, |
| 2065 | # and __kwdefaults__ attributes |
| 2066 | |
| 2067 | def __init__(self, func): |
| 2068 | self.__name__ = func.__name__ |
| 2069 | self.__code__ = func.__code__ |
| 2070 | self.__annotations__ = func.__annotations__ |
| 2071 | self.__defaults__ = func.__defaults__ |
| 2072 | self.__kwdefaults__ = func.__kwdefaults__ |
| 2073 | self.func = func |
| 2074 | |
| 2075 | def __call__(self, *args, **kwargs): |
| 2076 | return self.func(*args, **kwargs) |
| 2077 | |
Yury Selivanov | 57c74fc | 2015-05-20 23:07:02 -0400 | [diff] [blame] | 2078 | sig_func = inspect.Signature.from_callable(func) |
Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 2079 | |
Yury Selivanov | 57c74fc | 2015-05-20 23:07:02 -0400 | [diff] [blame] | 2080 | sig_funclike = inspect.Signature.from_callable(funclike(func)) |
Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 2081 | self.assertEqual(sig_funclike, sig_func) |
| 2082 | |
| 2083 | sig_funclike = inspect.signature(funclike(func)) |
| 2084 | self.assertEqual(sig_funclike, sig_func) |
| 2085 | |
| 2086 | # If object is not a duck type of function, then |
| 2087 | # signature will try to get a signature for its '__call__' |
| 2088 | # method |
| 2089 | fl = funclike(func) |
| 2090 | del fl.__defaults__ |
| 2091 | self.assertEqual(self.signature(fl), |
| 2092 | ((('args', ..., ..., "var_positional"), |
| 2093 | ('kwargs', ..., ..., "var_keyword")), |
| 2094 | ...)) |
| 2095 | |
Yury Selivanov | a773de0 | 2014-02-21 18:30:53 -0500 | [diff] [blame] | 2096 | # Test with cython-like builtins: |
| 2097 | _orig_isdesc = inspect.ismethoddescriptor |
| 2098 | def _isdesc(obj): |
| 2099 | if hasattr(obj, '_builtinmock'): |
| 2100 | return True |
| 2101 | return _orig_isdesc(obj) |
| 2102 | |
| 2103 | with unittest.mock.patch('inspect.ismethoddescriptor', _isdesc): |
| 2104 | builtin_func = funclike(func) |
| 2105 | # Make sure that our mock setup is working |
| 2106 | self.assertFalse(inspect.ismethoddescriptor(builtin_func)) |
| 2107 | builtin_func._builtinmock = True |
| 2108 | self.assertTrue(inspect.ismethoddescriptor(builtin_func)) |
| 2109 | self.assertEqual(inspect.signature(builtin_func), sig_func) |
| 2110 | |
Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 2111 | def test_signature_functionlike_class(self): |
| 2112 | # We only want to duck type function-like objects, |
| 2113 | # not classes. |
| 2114 | |
| 2115 | def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): |
| 2116 | pass |
| 2117 | |
| 2118 | class funclike: |
| 2119 | def __init__(self, marker): |
| 2120 | pass |
| 2121 | |
| 2122 | __name__ = func.__name__ |
| 2123 | __code__ = func.__code__ |
| 2124 | __annotations__ = func.__annotations__ |
| 2125 | __defaults__ = func.__defaults__ |
| 2126 | __kwdefaults__ = func.__kwdefaults__ |
| 2127 | |
Yury Selivanov | 63da7c7 | 2014-01-31 14:48:37 -0500 | [diff] [blame] | 2128 | self.assertEqual(str(inspect.signature(funclike)), '(marker)') |
| 2129 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2130 | def test_signature_on_method(self): |
| 2131 | class Test: |
Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 2132 | def __init__(*args): |
| 2133 | pass |
| 2134 | def m1(self, arg1, arg2=1) -> int: |
| 2135 | pass |
| 2136 | def m2(*args): |
| 2137 | pass |
| 2138 | def __call__(*, a): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2139 | pass |
| 2140 | |
Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 2141 | self.assertEqual(self.signature(Test().m1), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2142 | ((('arg1', ..., ..., "positional_or_keyword"), |
| 2143 | ('arg2', 1, ..., "positional_or_keyword")), |
| 2144 | int)) |
| 2145 | |
Yury Selivanov | 62560fb | 2014-01-28 12:26:24 -0500 | [diff] [blame] | 2146 | self.assertEqual(self.signature(Test().m2), |
| 2147 | ((('args', ..., ..., "var_positional"),), |
| 2148 | ...)) |
| 2149 | |
| 2150 | self.assertEqual(self.signature(Test), |
| 2151 | ((('args', ..., ..., "var_positional"),), |
| 2152 | ...)) |
| 2153 | |
| 2154 | with self.assertRaisesRegex(ValueError, 'invalid method signature'): |
| 2155 | self.signature(Test()) |
| 2156 | |
Yury Selivanov | 46c759d | 2015-05-27 21:56:53 -0400 | [diff] [blame] | 2157 | def test_signature_wrapped_bound_method(self): |
| 2158 | # Issue 24298 |
| 2159 | class Test: |
| 2160 | def m1(self, arg1, arg2=1) -> int: |
| 2161 | pass |
| 2162 | @functools.wraps(Test().m1) |
| 2163 | def m1d(*args, **kwargs): |
| 2164 | pass |
| 2165 | self.assertEqual(self.signature(m1d), |
| 2166 | ((('arg1', ..., ..., "positional_or_keyword"), |
| 2167 | ('arg2', 1, ..., "positional_or_keyword")), |
| 2168 | int)) |
| 2169 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2170 | def test_signature_on_classmethod(self): |
| 2171 | class Test: |
| 2172 | @classmethod |
| 2173 | def foo(cls, arg1, *, arg2=1): |
| 2174 | pass |
| 2175 | |
| 2176 | meth = Test().foo |
| 2177 | self.assertEqual(self.signature(meth), |
| 2178 | ((('arg1', ..., ..., "positional_or_keyword"), |
| 2179 | ('arg2', 1, ..., "keyword_only")), |
| 2180 | ...)) |
| 2181 | |
| 2182 | meth = Test.foo |
| 2183 | self.assertEqual(self.signature(meth), |
| 2184 | ((('arg1', ..., ..., "positional_or_keyword"), |
| 2185 | ('arg2', 1, ..., "keyword_only")), |
| 2186 | ...)) |
| 2187 | |
| 2188 | def test_signature_on_staticmethod(self): |
| 2189 | class Test: |
| 2190 | @staticmethod |
| 2191 | def foo(cls, *, arg): |
| 2192 | pass |
| 2193 | |
| 2194 | meth = Test().foo |
| 2195 | self.assertEqual(self.signature(meth), |
| 2196 | ((('cls', ..., ..., "positional_or_keyword"), |
| 2197 | ('arg', ..., ..., "keyword_only")), |
| 2198 | ...)) |
| 2199 | |
| 2200 | meth = Test.foo |
| 2201 | self.assertEqual(self.signature(meth), |
| 2202 | ((('cls', ..., ..., "positional_or_keyword"), |
| 2203 | ('arg', ..., ..., "keyword_only")), |
| 2204 | ...)) |
| 2205 | |
| 2206 | def test_signature_on_partial(self): |
| 2207 | from functools import partial |
| 2208 | |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2209 | Parameter = inspect.Parameter |
| 2210 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2211 | def test(): |
| 2212 | pass |
| 2213 | |
| 2214 | self.assertEqual(self.signature(partial(test)), ((), ...)) |
| 2215 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2216 | with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2217 | inspect.signature(partial(test, 1)) |
| 2218 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2219 | with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2220 | inspect.signature(partial(test, a=1)) |
| 2221 | |
| 2222 | def test(a, b, *, c, d): |
| 2223 | pass |
| 2224 | |
| 2225 | self.assertEqual(self.signature(partial(test)), |
| 2226 | ((('a', ..., ..., "positional_or_keyword"), |
| 2227 | ('b', ..., ..., "positional_or_keyword"), |
| 2228 | ('c', ..., ..., "keyword_only"), |
| 2229 | ('d', ..., ..., "keyword_only")), |
| 2230 | ...)) |
| 2231 | |
| 2232 | self.assertEqual(self.signature(partial(test, 1)), |
| 2233 | ((('b', ..., ..., "positional_or_keyword"), |
| 2234 | ('c', ..., ..., "keyword_only"), |
| 2235 | ('d', ..., ..., "keyword_only")), |
| 2236 | ...)) |
| 2237 | |
| 2238 | self.assertEqual(self.signature(partial(test, 1, c=2)), |
| 2239 | ((('b', ..., ..., "positional_or_keyword"), |
| 2240 | ('c', 2, ..., "keyword_only"), |
| 2241 | ('d', ..., ..., "keyword_only")), |
| 2242 | ...)) |
| 2243 | |
| 2244 | self.assertEqual(self.signature(partial(test, b=1, c=2)), |
| 2245 | ((('a', ..., ..., "positional_or_keyword"), |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2246 | ('b', 1, ..., "keyword_only"), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2247 | ('c', 2, ..., "keyword_only"), |
| 2248 | ('d', ..., ..., "keyword_only")), |
| 2249 | ...)) |
| 2250 | |
| 2251 | self.assertEqual(self.signature(partial(test, 0, b=1, c=2)), |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2252 | ((('b', 1, ..., "keyword_only"), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2253 | ('c', 2, ..., "keyword_only"), |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2254 | ('d', ..., ..., "keyword_only")), |
| 2255 | ...)) |
| 2256 | |
| 2257 | self.assertEqual(self.signature(partial(test, a=1)), |
| 2258 | ((('a', 1, ..., "keyword_only"), |
| 2259 | ('b', ..., ..., "keyword_only"), |
| 2260 | ('c', ..., ..., "keyword_only"), |
| 2261 | ('d', ..., ..., "keyword_only")), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2262 | ...)) |
| 2263 | |
| 2264 | def test(a, *args, b, **kwargs): |
| 2265 | pass |
| 2266 | |
| 2267 | self.assertEqual(self.signature(partial(test, 1)), |
| 2268 | ((('args', ..., ..., "var_positional"), |
| 2269 | ('b', ..., ..., "keyword_only"), |
| 2270 | ('kwargs', ..., ..., "var_keyword")), |
| 2271 | ...)) |
| 2272 | |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2273 | self.assertEqual(self.signature(partial(test, a=1)), |
| 2274 | ((('a', 1, ..., "keyword_only"), |
| 2275 | ('b', ..., ..., "keyword_only"), |
| 2276 | ('kwargs', ..., ..., "var_keyword")), |
| 2277 | ...)) |
| 2278 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2279 | self.assertEqual(self.signature(partial(test, 1, 2, 3)), |
| 2280 | ((('args', ..., ..., "var_positional"), |
| 2281 | ('b', ..., ..., "keyword_only"), |
| 2282 | ('kwargs', ..., ..., "var_keyword")), |
| 2283 | ...)) |
| 2284 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2285 | self.assertEqual(self.signature(partial(test, 1, 2, 3, test=True)), |
| 2286 | ((('args', ..., ..., "var_positional"), |
| 2287 | ('b', ..., ..., "keyword_only"), |
| 2288 | ('kwargs', ..., ..., "var_keyword")), |
| 2289 | ...)) |
| 2290 | |
| 2291 | self.assertEqual(self.signature(partial(test, 1, 2, 3, test=1, b=0)), |
| 2292 | ((('args', ..., ..., "var_positional"), |
| 2293 | ('b', 0, ..., "keyword_only"), |
| 2294 | ('kwargs', ..., ..., "var_keyword")), |
| 2295 | ...)) |
| 2296 | |
| 2297 | self.assertEqual(self.signature(partial(test, b=0)), |
| 2298 | ((('a', ..., ..., "positional_or_keyword"), |
| 2299 | ('args', ..., ..., "var_positional"), |
| 2300 | ('b', 0, ..., "keyword_only"), |
| 2301 | ('kwargs', ..., ..., "var_keyword")), |
| 2302 | ...)) |
| 2303 | |
| 2304 | self.assertEqual(self.signature(partial(test, b=0, test=1)), |
| 2305 | ((('a', ..., ..., "positional_or_keyword"), |
| 2306 | ('args', ..., ..., "var_positional"), |
| 2307 | ('b', 0, ..., "keyword_only"), |
| 2308 | ('kwargs', ..., ..., "var_keyword")), |
| 2309 | ...)) |
| 2310 | |
| 2311 | def test(a, b, c:int) -> 42: |
| 2312 | pass |
| 2313 | |
| 2314 | sig = test.__signature__ = inspect.signature(test) |
| 2315 | |
| 2316 | self.assertEqual(self.signature(partial(partial(test, 1))), |
| 2317 | ((('b', ..., ..., "positional_or_keyword"), |
| 2318 | ('c', ..., int, "positional_or_keyword")), |
| 2319 | 42)) |
| 2320 | |
| 2321 | self.assertEqual(self.signature(partial(partial(test, 1), 2)), |
| 2322 | ((('c', ..., int, "positional_or_keyword"),), |
| 2323 | 42)) |
| 2324 | |
| 2325 | psig = inspect.signature(partial(partial(test, 1), 2)) |
| 2326 | |
| 2327 | def foo(a): |
| 2328 | return a |
| 2329 | _foo = partial(partial(foo, a=10), a=20) |
| 2330 | self.assertEqual(self.signature(_foo), |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2331 | ((('a', 20, ..., "keyword_only"),), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2332 | ...)) |
| 2333 | # check that we don't have any side-effects in signature(), |
| 2334 | # and the partial object is still functioning |
| 2335 | self.assertEqual(_foo(), 20) |
| 2336 | |
| 2337 | def foo(a, b, c): |
| 2338 | return a, b, c |
| 2339 | _foo = partial(partial(foo, 1, b=20), b=30) |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2340 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2341 | self.assertEqual(self.signature(_foo), |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2342 | ((('b', 30, ..., "keyword_only"), |
| 2343 | ('c', ..., ..., "keyword_only")), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2344 | ...)) |
| 2345 | self.assertEqual(_foo(c=10), (1, 30, 10)) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2346 | |
| 2347 | def foo(a, b, c, *, d): |
| 2348 | return a, b, c, d |
| 2349 | _foo = partial(partial(foo, d=20, c=20), b=10, d=30) |
| 2350 | self.assertEqual(self.signature(_foo), |
| 2351 | ((('a', ..., ..., "positional_or_keyword"), |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2352 | ('b', 10, ..., "keyword_only"), |
| 2353 | ('c', 20, ..., "keyword_only"), |
| 2354 | ('d', 30, ..., "keyword_only"), |
| 2355 | ), |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2356 | ...)) |
| 2357 | ba = inspect.signature(_foo).bind(a=200, b=11) |
| 2358 | self.assertEqual(_foo(*ba.args, **ba.kwargs), (200, 11, 20, 30)) |
| 2359 | |
| 2360 | def foo(a=1, b=2, c=3): |
| 2361 | return a, b, c |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2362 | _foo = partial(foo, c=13) # (a=1, b=2, *, c=13) |
| 2363 | |
| 2364 | ba = inspect.signature(_foo).bind(a=11) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2365 | self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 2, 13)) |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2366 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2367 | ba = inspect.signature(_foo).bind(11, 12) |
| 2368 | self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2369 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2370 | ba = inspect.signature(_foo).bind(11, b=12) |
| 2371 | self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2372 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2373 | ba = inspect.signature(_foo).bind(b=12) |
Yury Selivanov | 3f73ca2 | 2014-04-08 11:30:45 -0400 | [diff] [blame] | 2374 | self.assertEqual(_foo(*ba.args, **ba.kwargs), (1, 12, 13)) |
| 2375 | |
| 2376 | _foo = partial(_foo, b=10, c=20) |
| 2377 | ba = inspect.signature(_foo).bind(12) |
| 2378 | self.assertEqual(_foo(*ba.args, **ba.kwargs), (12, 10, 20)) |
| 2379 | |
| 2380 | |
| 2381 | def foo(a, b, c, d, **kwargs): |
| 2382 | pass |
| 2383 | sig = inspect.signature(foo) |
| 2384 | params = sig.parameters.copy() |
| 2385 | params['a'] = params['a'].replace(kind=Parameter.POSITIONAL_ONLY) |
| 2386 | params['b'] = params['b'].replace(kind=Parameter.POSITIONAL_ONLY) |
| 2387 | foo.__signature__ = inspect.Signature(params.values()) |
| 2388 | sig = inspect.signature(foo) |
| 2389 | self.assertEqual(str(sig), '(a, b, /, c, d, **kwargs)') |
| 2390 | |
| 2391 | self.assertEqual(self.signature(partial(foo, 1)), |
| 2392 | ((('b', ..., ..., 'positional_only'), |
| 2393 | ('c', ..., ..., 'positional_or_keyword'), |
| 2394 | ('d', ..., ..., 'positional_or_keyword'), |
| 2395 | ('kwargs', ..., ..., 'var_keyword')), |
| 2396 | ...)) |
| 2397 | |
| 2398 | self.assertEqual(self.signature(partial(foo, 1, 2)), |
| 2399 | ((('c', ..., ..., 'positional_or_keyword'), |
| 2400 | ('d', ..., ..., 'positional_or_keyword'), |
| 2401 | ('kwargs', ..., ..., 'var_keyword')), |
| 2402 | ...)) |
| 2403 | |
| 2404 | self.assertEqual(self.signature(partial(foo, 1, 2, 3)), |
| 2405 | ((('d', ..., ..., 'positional_or_keyword'), |
| 2406 | ('kwargs', ..., ..., 'var_keyword')), |
| 2407 | ...)) |
| 2408 | |
| 2409 | self.assertEqual(self.signature(partial(foo, 1, 2, c=3)), |
| 2410 | ((('c', 3, ..., 'keyword_only'), |
| 2411 | ('d', ..., ..., 'keyword_only'), |
| 2412 | ('kwargs', ..., ..., 'var_keyword')), |
| 2413 | ...)) |
| 2414 | |
| 2415 | self.assertEqual(self.signature(partial(foo, 1, c=3)), |
| 2416 | ((('b', ..., ..., 'positional_only'), |
| 2417 | ('c', 3, ..., 'keyword_only'), |
| 2418 | ('d', ..., ..., 'keyword_only'), |
| 2419 | ('kwargs', ..., ..., 'var_keyword')), |
| 2420 | ...)) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2421 | |
Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 2422 | def test_signature_on_partialmethod(self): |
| 2423 | from functools import partialmethod |
| 2424 | |
| 2425 | class Spam: |
| 2426 | def test(): |
| 2427 | pass |
| 2428 | ham = partialmethod(test) |
| 2429 | |
| 2430 | with self.assertRaisesRegex(ValueError, "has incorrect arguments"): |
| 2431 | inspect.signature(Spam.ham) |
| 2432 | |
| 2433 | class Spam: |
| 2434 | def test(it, a, *, c) -> 'spam': |
| 2435 | pass |
| 2436 | ham = partialmethod(test, c=1) |
| 2437 | |
| 2438 | self.assertEqual(self.signature(Spam.ham), |
| 2439 | ((('it', ..., ..., 'positional_or_keyword'), |
| 2440 | ('a', ..., ..., 'positional_or_keyword'), |
| 2441 | ('c', 1, ..., 'keyword_only')), |
| 2442 | 'spam')) |
| 2443 | |
| 2444 | self.assertEqual(self.signature(Spam().ham), |
| 2445 | ((('a', ..., ..., 'positional_or_keyword'), |
| 2446 | ('c', 1, ..., 'keyword_only')), |
| 2447 | 'spam')) |
| 2448 | |
Yury Selivanov | 0486f81 | 2014-01-29 12:18:59 -0500 | [diff] [blame] | 2449 | def test_signature_on_fake_partialmethod(self): |
| 2450 | def foo(a): pass |
| 2451 | foo._partialmethod = 'spam' |
| 2452 | self.assertEqual(str(inspect.signature(foo)), '(a)') |
| 2453 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2454 | def test_signature_on_decorated(self): |
| 2455 | import functools |
| 2456 | |
| 2457 | def decorator(func): |
| 2458 | @functools.wraps(func) |
| 2459 | def wrapper(*args, **kwargs) -> int: |
| 2460 | return func(*args, **kwargs) |
| 2461 | return wrapper |
| 2462 | |
| 2463 | class Foo: |
| 2464 | @decorator |
| 2465 | def bar(self, a, b): |
| 2466 | pass |
| 2467 | |
| 2468 | self.assertEqual(self.signature(Foo.bar), |
| 2469 | ((('self', ..., ..., "positional_or_keyword"), |
| 2470 | ('a', ..., ..., "positional_or_keyword"), |
| 2471 | ('b', ..., ..., "positional_or_keyword")), |
| 2472 | ...)) |
| 2473 | |
| 2474 | self.assertEqual(self.signature(Foo().bar), |
| 2475 | ((('a', ..., ..., "positional_or_keyword"), |
| 2476 | ('b', ..., ..., "positional_or_keyword")), |
| 2477 | ...)) |
| 2478 | |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 2479 | self.assertEqual(self.signature(Foo.bar, follow_wrapped=False), |
| 2480 | ((('args', ..., ..., "var_positional"), |
| 2481 | ('kwargs', ..., ..., "var_keyword")), |
| 2482 | ...)) # functools.wraps will copy __annotations__ |
| 2483 | # from "func" to "wrapper", hence no |
| 2484 | # return_annotation |
| 2485 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2486 | # Test that we handle method wrappers correctly |
| 2487 | def decorator(func): |
| 2488 | @functools.wraps(func) |
| 2489 | def wrapper(*args, **kwargs) -> int: |
| 2490 | return func(42, *args, **kwargs) |
| 2491 | sig = inspect.signature(func) |
| 2492 | new_params = tuple(sig.parameters.values())[1:] |
| 2493 | wrapper.__signature__ = sig.replace(parameters=new_params) |
| 2494 | return wrapper |
| 2495 | |
| 2496 | class Foo: |
| 2497 | @decorator |
| 2498 | def __call__(self, a, b): |
| 2499 | pass |
| 2500 | |
| 2501 | self.assertEqual(self.signature(Foo.__call__), |
| 2502 | ((('a', ..., ..., "positional_or_keyword"), |
| 2503 | ('b', ..., ..., "positional_or_keyword")), |
| 2504 | ...)) |
| 2505 | |
| 2506 | self.assertEqual(self.signature(Foo().__call__), |
| 2507 | ((('b', ..., ..., "positional_or_keyword"),), |
| 2508 | ...)) |
| 2509 | |
Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 2510 | # Test we handle __signature__ partway down the wrapper stack |
| 2511 | def wrapped_foo_call(): |
| 2512 | pass |
| 2513 | wrapped_foo_call.__wrapped__ = Foo.__call__ |
| 2514 | |
| 2515 | self.assertEqual(self.signature(wrapped_foo_call), |
| 2516 | ((('a', ..., ..., "positional_or_keyword"), |
| 2517 | ('b', ..., ..., "positional_or_keyword")), |
| 2518 | ...)) |
| 2519 | |
| 2520 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2521 | def test_signature_on_class(self): |
| 2522 | class C: |
| 2523 | def __init__(self, a): |
| 2524 | pass |
| 2525 | |
| 2526 | self.assertEqual(self.signature(C), |
| 2527 | ((('a', ..., ..., "positional_or_keyword"),), |
| 2528 | ...)) |
| 2529 | |
| 2530 | class CM(type): |
| 2531 | def __call__(cls, a): |
| 2532 | pass |
| 2533 | class C(metaclass=CM): |
| 2534 | def __init__(self, b): |
| 2535 | pass |
| 2536 | |
| 2537 | self.assertEqual(self.signature(C), |
| 2538 | ((('a', ..., ..., "positional_or_keyword"),), |
| 2539 | ...)) |
| 2540 | |
| 2541 | class CM(type): |
| 2542 | def __new__(mcls, name, bases, dct, *, foo=1): |
| 2543 | return super().__new__(mcls, name, bases, dct) |
| 2544 | class C(metaclass=CM): |
| 2545 | def __init__(self, b): |
| 2546 | pass |
| 2547 | |
| 2548 | self.assertEqual(self.signature(C), |
| 2549 | ((('b', ..., ..., "positional_or_keyword"),), |
| 2550 | ...)) |
| 2551 | |
| 2552 | self.assertEqual(self.signature(CM), |
| 2553 | ((('name', ..., ..., "positional_or_keyword"), |
| 2554 | ('bases', ..., ..., "positional_or_keyword"), |
| 2555 | ('dct', ..., ..., "positional_or_keyword"), |
| 2556 | ('foo', 1, ..., "keyword_only")), |
| 2557 | ...)) |
| 2558 | |
| 2559 | class CMM(type): |
| 2560 | def __new__(mcls, name, bases, dct, *, foo=1): |
| 2561 | return super().__new__(mcls, name, bases, dct) |
| 2562 | def __call__(cls, nm, bs, dt): |
| 2563 | return type(nm, bs, dt) |
| 2564 | class CM(type, metaclass=CMM): |
| 2565 | def __new__(mcls, name, bases, dct, *, bar=2): |
| 2566 | return super().__new__(mcls, name, bases, dct) |
| 2567 | class C(metaclass=CM): |
| 2568 | def __init__(self, b): |
| 2569 | pass |
| 2570 | |
| 2571 | self.assertEqual(self.signature(CMM), |
| 2572 | ((('name', ..., ..., "positional_or_keyword"), |
| 2573 | ('bases', ..., ..., "positional_or_keyword"), |
| 2574 | ('dct', ..., ..., "positional_or_keyword"), |
| 2575 | ('foo', 1, ..., "keyword_only")), |
| 2576 | ...)) |
| 2577 | |
| 2578 | self.assertEqual(self.signature(CM), |
| 2579 | ((('nm', ..., ..., "positional_or_keyword"), |
| 2580 | ('bs', ..., ..., "positional_or_keyword"), |
| 2581 | ('dt', ..., ..., "positional_or_keyword")), |
| 2582 | ...)) |
| 2583 | |
| 2584 | self.assertEqual(self.signature(C), |
| 2585 | ((('b', ..., ..., "positional_or_keyword"),), |
| 2586 | ...)) |
| 2587 | |
| 2588 | class CM(type): |
| 2589 | def __init__(cls, name, bases, dct, *, bar=2): |
| 2590 | return super().__init__(name, bases, dct) |
| 2591 | class C(metaclass=CM): |
| 2592 | def __init__(self, b): |
| 2593 | pass |
| 2594 | |
| 2595 | self.assertEqual(self.signature(CM), |
| 2596 | ((('name', ..., ..., "positional_or_keyword"), |
| 2597 | ('bases', ..., ..., "positional_or_keyword"), |
| 2598 | ('dct', ..., ..., "positional_or_keyword"), |
| 2599 | ('bar', 2, ..., "keyword_only")), |
| 2600 | ...)) |
| 2601 | |
Yury Selivanov | 145dff8 | 2014-02-01 13:49:29 -0500 | [diff] [blame] | 2602 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 2603 | "Signature information for builtins requires docstrings") |
| 2604 | def test_signature_on_class_without_init(self): |
Yury Selivanov | e7dcc5e | 2014-01-27 19:29:45 -0500 | [diff] [blame] | 2605 | # Test classes without user-defined __init__ or __new__ |
| 2606 | class C: pass |
| 2607 | self.assertEqual(str(inspect.signature(C)), '()') |
| 2608 | class D(C): pass |
| 2609 | self.assertEqual(str(inspect.signature(D)), '()') |
| 2610 | |
| 2611 | # Test meta-classes without user-defined __init__ or __new__ |
| 2612 | class C(type): pass |
Yury Selivanov | e7dcc5e | 2014-01-27 19:29:45 -0500 | [diff] [blame] | 2613 | class D(C): pass |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 2614 | with self.assertRaisesRegex(ValueError, "callable.*is not supported"): |
| 2615 | self.assertEqual(inspect.signature(C), None) |
| 2616 | with self.assertRaisesRegex(ValueError, "callable.*is not supported"): |
| 2617 | self.assertEqual(inspect.signature(D), None) |
Yury Selivanov | e7dcc5e | 2014-01-27 19:29:45 -0500 | [diff] [blame] | 2618 | |
Yury Selivanov | 7d2bfed | 2014-02-03 02:46:07 -0500 | [diff] [blame] | 2619 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 2620 | "Signature information for builtins requires docstrings") |
| 2621 | def test_signature_on_builtin_class(self): |
| 2622 | self.assertEqual(str(inspect.signature(_pickle.Pickler)), |
| 2623 | '(file, protocol=None, fix_imports=True)') |
| 2624 | |
| 2625 | class P(_pickle.Pickler): pass |
| 2626 | class EmptyTrait: pass |
| 2627 | class P2(EmptyTrait, P): pass |
| 2628 | self.assertEqual(str(inspect.signature(P)), |
| 2629 | '(file, protocol=None, fix_imports=True)') |
| 2630 | self.assertEqual(str(inspect.signature(P2)), |
| 2631 | '(file, protocol=None, fix_imports=True)') |
| 2632 | |
| 2633 | class P3(P2): |
| 2634 | def __init__(self, spam): |
| 2635 | pass |
| 2636 | self.assertEqual(str(inspect.signature(P3)), '(spam)') |
| 2637 | |
| 2638 | class MetaP(type): |
| 2639 | def __call__(cls, foo, bar): |
| 2640 | pass |
| 2641 | class P4(P2, metaclass=MetaP): |
| 2642 | pass |
| 2643 | self.assertEqual(str(inspect.signature(P4)), '(foo, bar)') |
| 2644 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2645 | def test_signature_on_callable_objects(self): |
| 2646 | class Foo: |
| 2647 | def __call__(self, a): |
| 2648 | pass |
| 2649 | |
| 2650 | self.assertEqual(self.signature(Foo()), |
| 2651 | ((('a', ..., ..., "positional_or_keyword"),), |
| 2652 | ...)) |
| 2653 | |
| 2654 | class Spam: |
| 2655 | pass |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2656 | with self.assertRaisesRegex(TypeError, "is not a callable object"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2657 | inspect.signature(Spam()) |
| 2658 | |
| 2659 | class Bar(Spam, Foo): |
| 2660 | pass |
| 2661 | |
| 2662 | self.assertEqual(self.signature(Bar()), |
| 2663 | ((('a', ..., ..., "positional_or_keyword"),), |
| 2664 | ...)) |
| 2665 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2666 | class Wrapped: |
| 2667 | pass |
| 2668 | Wrapped.__wrapped__ = lambda a: None |
| 2669 | self.assertEqual(self.signature(Wrapped), |
| 2670 | ((('a', ..., ..., "positional_or_keyword"),), |
| 2671 | ...)) |
Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 2672 | # wrapper loop: |
| 2673 | Wrapped.__wrapped__ = Wrapped |
| 2674 | with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 2675 | self.signature(Wrapped) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2676 | |
| 2677 | def test_signature_on_lambdas(self): |
| 2678 | self.assertEqual(self.signature((lambda a=10: a)), |
| 2679 | ((('a', 10, ..., "positional_or_keyword"),), |
| 2680 | ...)) |
| 2681 | |
| 2682 | def test_signature_equality(self): |
| 2683 | def foo(a, *, b:int) -> float: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2684 | self.assertFalse(inspect.signature(foo) == 42) |
| 2685 | self.assertTrue(inspect.signature(foo) != 42) |
| 2686 | self.assertTrue(inspect.signature(foo) == EqualsToAll()) |
| 2687 | self.assertFalse(inspect.signature(foo) != EqualsToAll()) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2688 | |
| 2689 | def bar(a, *, b:int) -> float: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2690 | self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 2691 | self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2692 | self.assertEqual( |
| 2693 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2694 | |
| 2695 | def bar(a, *, b:int) -> int: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2696 | self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 2697 | self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2698 | self.assertNotEqual( |
| 2699 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2700 | |
| 2701 | def bar(a, *, b:int): pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2702 | self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 2703 | self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2704 | self.assertNotEqual( |
| 2705 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2706 | |
| 2707 | def bar(a, *, b:int=42) -> float: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2708 | self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 2709 | self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2710 | self.assertNotEqual( |
| 2711 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2712 | |
| 2713 | def bar(a, *, c) -> float: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2714 | self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 2715 | self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2716 | self.assertNotEqual( |
| 2717 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2718 | |
| 2719 | def bar(a, b:int) -> float: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2720 | self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 2721 | self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2722 | self.assertNotEqual( |
| 2723 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2724 | def spam(b:int, a) -> float: pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2725 | self.assertFalse(inspect.signature(spam) == inspect.signature(bar)) |
| 2726 | self.assertTrue(inspect.signature(spam) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2727 | self.assertNotEqual( |
| 2728 | hash(inspect.signature(spam)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2729 | |
| 2730 | def foo(*, a, b, c): pass |
| 2731 | def bar(*, c, b, a): pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2732 | self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 2733 | self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2734 | self.assertEqual( |
| 2735 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2736 | |
| 2737 | def foo(*, a=1, b, c): pass |
| 2738 | def bar(*, c, b, a=1): pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2739 | self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 2740 | self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2741 | self.assertEqual( |
| 2742 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2743 | |
| 2744 | def foo(pos, *, a=1, b, c): pass |
| 2745 | def bar(pos, *, c, b, a=1): pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2746 | self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 2747 | self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2748 | self.assertEqual( |
| 2749 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2750 | |
| 2751 | def foo(pos, *, a, b, c): pass |
| 2752 | def bar(pos, *, c, b, a=1): pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2753 | self.assertFalse(inspect.signature(foo) == inspect.signature(bar)) |
| 2754 | self.assertTrue(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2755 | self.assertNotEqual( |
| 2756 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2757 | |
| 2758 | def foo(pos, *args, a=42, b, c, **kwargs:int): pass |
| 2759 | def bar(pos, *args, c, b, a=42, **kwargs:int): pass |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2760 | self.assertTrue(inspect.signature(foo) == inspect.signature(bar)) |
| 2761 | self.assertFalse(inspect.signature(foo) != inspect.signature(bar)) |
Yury Selivanov | 08d4a4f | 2014-09-12 15:48:02 -0400 | [diff] [blame] | 2762 | self.assertEqual( |
| 2763 | hash(inspect.signature(foo)), hash(inspect.signature(bar))) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2764 | |
Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2765 | def test_signature_hashable(self): |
| 2766 | S = inspect.Signature |
| 2767 | P = inspect.Parameter |
| 2768 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2769 | def foo(a): pass |
Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2770 | foo_sig = inspect.signature(foo) |
| 2771 | |
| 2772 | manual_sig = S(parameters=[P('a', P.POSITIONAL_OR_KEYWORD)]) |
| 2773 | |
| 2774 | self.assertEqual(hash(foo_sig), hash(manual_sig)) |
| 2775 | self.assertNotEqual(hash(foo_sig), |
| 2776 | hash(manual_sig.replace(return_annotation='spam'))) |
| 2777 | |
| 2778 | def bar(a) -> 1: pass |
| 2779 | self.assertNotEqual(hash(foo_sig), hash(inspect.signature(bar))) |
| 2780 | |
| 2781 | def foo(a={}): pass |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2782 | with self.assertRaisesRegex(TypeError, 'unhashable type'): |
Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2783 | hash(inspect.signature(foo)) |
| 2784 | |
| 2785 | def foo(a) -> {}: pass |
| 2786 | with self.assertRaisesRegex(TypeError, 'unhashable type'): |
| 2787 | hash(inspect.signature(foo)) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2788 | |
| 2789 | def test_signature_str(self): |
| 2790 | def foo(a:int=1, *, b, c=None, **kwargs) -> 42: |
| 2791 | pass |
| 2792 | self.assertEqual(str(inspect.signature(foo)), |
| 2793 | '(a:int=1, *, b, c=None, **kwargs) -> 42') |
| 2794 | |
| 2795 | def foo(a:int=1, *args, b, c=None, **kwargs) -> 42: |
| 2796 | pass |
| 2797 | self.assertEqual(str(inspect.signature(foo)), |
| 2798 | '(a:int=1, *args, b, c=None, **kwargs) -> 42') |
| 2799 | |
| 2800 | def foo(): |
| 2801 | pass |
| 2802 | self.assertEqual(str(inspect.signature(foo)), '()') |
| 2803 | |
| 2804 | def test_signature_str_positional_only(self): |
| 2805 | P = inspect.Parameter |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2806 | S = inspect.Signature |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2807 | |
| 2808 | def test(a_po, *, b, **kwargs): |
| 2809 | return a_po, kwargs |
| 2810 | |
| 2811 | sig = inspect.signature(test) |
| 2812 | new_params = list(sig.parameters.values()) |
| 2813 | new_params[0] = new_params[0].replace(kind=P.POSITIONAL_ONLY) |
| 2814 | test.__signature__ = sig.replace(parameters=new_params) |
| 2815 | |
| 2816 | self.assertEqual(str(inspect.signature(test)), |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2817 | '(a_po, /, *, b, **kwargs)') |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2818 | |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2819 | self.assertEqual(str(S(parameters=[P('foo', P.POSITIONAL_ONLY)])), |
| 2820 | '(foo, /)') |
| 2821 | |
| 2822 | self.assertEqual(str(S(parameters=[ |
| 2823 | P('foo', P.POSITIONAL_ONLY), |
| 2824 | P('bar', P.VAR_KEYWORD)])), |
| 2825 | '(foo, /, **bar)') |
| 2826 | |
| 2827 | self.assertEqual(str(S(parameters=[ |
| 2828 | P('foo', P.POSITIONAL_ONLY), |
| 2829 | P('bar', P.VAR_POSITIONAL)])), |
| 2830 | '(foo, /, *bar)') |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2831 | |
| 2832 | def test_signature_replace_anno(self): |
| 2833 | def test() -> 42: |
| 2834 | pass |
| 2835 | |
| 2836 | sig = inspect.signature(test) |
| 2837 | sig = sig.replace(return_annotation=None) |
| 2838 | self.assertIs(sig.return_annotation, None) |
| 2839 | sig = sig.replace(return_annotation=sig.empty) |
| 2840 | self.assertIs(sig.return_annotation, sig.empty) |
| 2841 | sig = sig.replace(return_annotation=42) |
| 2842 | self.assertEqual(sig.return_annotation, 42) |
| 2843 | self.assertEqual(sig, inspect.signature(test)) |
| 2844 | |
Yury Selivanov | 34ce99f | 2014-02-18 12:49:41 -0500 | [diff] [blame] | 2845 | def test_signature_on_mangled_parameters(self): |
| 2846 | class Spam: |
| 2847 | def foo(self, __p1:1=2, *, __p2:2=3): |
| 2848 | pass |
| 2849 | class Ham(Spam): |
| 2850 | pass |
| 2851 | |
| 2852 | self.assertEqual(self.signature(Spam.foo), |
| 2853 | ((('self', ..., ..., "positional_or_keyword"), |
| 2854 | ('_Spam__p1', 2, 1, "positional_or_keyword"), |
| 2855 | ('_Spam__p2', 3, 2, "keyword_only")), |
| 2856 | ...)) |
| 2857 | |
| 2858 | self.assertEqual(self.signature(Spam.foo), |
| 2859 | self.signature(Ham.foo)) |
| 2860 | |
Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 2861 | def test_signature_from_callable_python_obj(self): |
| 2862 | class MySignature(inspect.Signature): pass |
| 2863 | def foo(a, *, b:1): pass |
| 2864 | foo_sig = MySignature.from_callable(foo) |
| 2865 | self.assertTrue(isinstance(foo_sig, MySignature)) |
| 2866 | |
| 2867 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 2868 | "Signature information for builtins requires docstrings") |
| 2869 | def test_signature_from_callable_builtin_obj(self): |
| 2870 | class MySignature(inspect.Signature): pass |
| 2871 | sig = MySignature.from_callable(_pickle.Pickler) |
| 2872 | self.assertTrue(isinstance(sig, MySignature)) |
| 2873 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2874 | |
| 2875 | class TestParameterObject(unittest.TestCase): |
| 2876 | def test_signature_parameter_kinds(self): |
| 2877 | P = inspect.Parameter |
| 2878 | self.assertTrue(P.POSITIONAL_ONLY < P.POSITIONAL_OR_KEYWORD < \ |
| 2879 | P.VAR_POSITIONAL < P.KEYWORD_ONLY < P.VAR_KEYWORD) |
| 2880 | |
| 2881 | self.assertEqual(str(P.POSITIONAL_ONLY), 'POSITIONAL_ONLY') |
| 2882 | self.assertTrue('POSITIONAL_ONLY' in repr(P.POSITIONAL_ONLY)) |
| 2883 | |
| 2884 | def test_signature_parameter_object(self): |
| 2885 | p = inspect.Parameter('foo', default=10, |
| 2886 | kind=inspect.Parameter.POSITIONAL_ONLY) |
| 2887 | self.assertEqual(p.name, 'foo') |
| 2888 | self.assertEqual(p.default, 10) |
| 2889 | self.assertIs(p.annotation, p.empty) |
| 2890 | self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) |
| 2891 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2892 | with self.assertRaisesRegex(ValueError, 'invalid value'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2893 | inspect.Parameter('foo', default=10, kind='123') |
| 2894 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2895 | with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2896 | inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD) |
| 2897 | |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2898 | with self.assertRaisesRegex(TypeError, 'name must be a str'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2899 | inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD) |
| 2900 | |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2901 | with self.assertRaisesRegex(ValueError, |
| 2902 | 'is not a valid parameter name'): |
| 2903 | inspect.Parameter('$', kind=inspect.Parameter.VAR_KEYWORD) |
| 2904 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2905 | with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2906 | inspect.Parameter('a', default=42, |
| 2907 | kind=inspect.Parameter.VAR_KEYWORD) |
| 2908 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2909 | with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2910 | inspect.Parameter('a', default=42, |
| 2911 | kind=inspect.Parameter.VAR_POSITIONAL) |
| 2912 | |
| 2913 | p = inspect.Parameter('a', default=42, |
| 2914 | kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2915 | with self.assertRaisesRegex(ValueError, 'cannot have default values'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2916 | p.replace(kind=inspect.Parameter.VAR_POSITIONAL) |
| 2917 | |
| 2918 | self.assertTrue(repr(p).startswith('<Parameter')) |
Yury Selivanov | 374375d | 2014-03-27 12:41:53 -0400 | [diff] [blame] | 2919 | self.assertTrue('"a=42"' in repr(p)) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2920 | |
Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 2921 | def test_signature_parameter_hashable(self): |
| 2922 | P = inspect.Parameter |
| 2923 | foo = P('foo', kind=P.POSITIONAL_ONLY) |
| 2924 | self.assertEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY))) |
| 2925 | self.assertNotEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY, |
| 2926 | default=42))) |
| 2927 | self.assertNotEqual(hash(foo), |
| 2928 | hash(foo.replace(kind=P.VAR_POSITIONAL))) |
| 2929 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2930 | def test_signature_parameter_equality(self): |
| 2931 | P = inspect.Parameter |
| 2932 | p = P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) |
| 2933 | |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2934 | self.assertTrue(p == p) |
| 2935 | self.assertFalse(p != p) |
| 2936 | self.assertFalse(p == 42) |
| 2937 | self.assertTrue(p != 42) |
| 2938 | self.assertTrue(p == EqualsToAll()) |
| 2939 | self.assertFalse(p != EqualsToAll()) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2940 | |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 2941 | self.assertTrue(p == P('foo', default=42, |
| 2942 | kind=inspect.Parameter.KEYWORD_ONLY)) |
| 2943 | self.assertFalse(p != P('foo', default=42, |
| 2944 | kind=inspect.Parameter.KEYWORD_ONLY)) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2945 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2946 | def test_signature_parameter_replace(self): |
| 2947 | p = inspect.Parameter('foo', default=42, |
| 2948 | kind=inspect.Parameter.KEYWORD_ONLY) |
| 2949 | |
| 2950 | self.assertIsNot(p, p.replace()) |
| 2951 | self.assertEqual(p, p.replace()) |
| 2952 | |
| 2953 | p2 = p.replace(annotation=1) |
| 2954 | self.assertEqual(p2.annotation, 1) |
| 2955 | p2 = p2.replace(annotation=p2.empty) |
| 2956 | self.assertEqual(p, p2) |
| 2957 | |
| 2958 | p2 = p2.replace(name='bar') |
| 2959 | self.assertEqual(p2.name, 'bar') |
| 2960 | self.assertNotEqual(p2, p) |
| 2961 | |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2962 | with self.assertRaisesRegex(ValueError, |
| 2963 | 'name is a required attribute'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2964 | p2 = p2.replace(name=p2.empty) |
| 2965 | |
| 2966 | p2 = p2.replace(name='foo', default=None) |
| 2967 | self.assertIs(p2.default, None) |
| 2968 | self.assertNotEqual(p2, p) |
| 2969 | |
| 2970 | p2 = p2.replace(name='foo', default=p2.empty) |
| 2971 | self.assertIs(p2.default, p2.empty) |
| 2972 | |
| 2973 | |
| 2974 | p2 = p2.replace(default=42, kind=p2.POSITIONAL_OR_KEYWORD) |
| 2975 | self.assertEqual(p2.kind, p2.POSITIONAL_OR_KEYWORD) |
| 2976 | self.assertNotEqual(p2, p) |
| 2977 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 2978 | with self.assertRaisesRegex(ValueError, 'invalid value for'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2979 | p2 = p2.replace(kind=p2.empty) |
| 2980 | |
| 2981 | p2 = p2.replace(kind=p2.KEYWORD_ONLY) |
| 2982 | self.assertEqual(p2, p) |
| 2983 | |
| 2984 | def test_signature_parameter_positional_only(self): |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2985 | with self.assertRaisesRegex(TypeError, 'name must be a str'): |
| 2986 | inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2987 | |
| 2988 | def test_signature_parameter_immutability(self): |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 2989 | p = inspect.Parameter('spam', kind=inspect.Parameter.KEYWORD_ONLY) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 2990 | |
| 2991 | with self.assertRaises(AttributeError): |
| 2992 | p.foo = 'bar' |
| 2993 | |
| 2994 | with self.assertRaises(AttributeError): |
| 2995 | p.kind = 123 |
| 2996 | |
| 2997 | |
| 2998 | class TestSignatureBind(unittest.TestCase): |
| 2999 | @staticmethod |
| 3000 | def call(func, *args, **kwargs): |
| 3001 | sig = inspect.signature(func) |
| 3002 | ba = sig.bind(*args, **kwargs) |
| 3003 | return func(*ba.args, **ba.kwargs) |
| 3004 | |
| 3005 | def test_signature_bind_empty(self): |
| 3006 | def test(): |
| 3007 | return 42 |
| 3008 | |
| 3009 | self.assertEqual(self.call(test), 42) |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3010 | with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3011 | self.call(test, 1) |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3012 | with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3013 | self.call(test, 1, spam=10) |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3014 | with self.assertRaisesRegex( |
| 3015 | TypeError, "got an unexpected keyword argument 'spam'"): |
| 3016 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3017 | self.call(test, spam=1) |
| 3018 | |
| 3019 | def test_signature_bind_var(self): |
| 3020 | def test(*args, **kwargs): |
| 3021 | return args, kwargs |
| 3022 | |
| 3023 | self.assertEqual(self.call(test), ((), {})) |
| 3024 | self.assertEqual(self.call(test, 1), ((1,), {})) |
| 3025 | self.assertEqual(self.call(test, 1, 2), ((1, 2), {})) |
| 3026 | self.assertEqual(self.call(test, foo='bar'), ((), {'foo': 'bar'})) |
| 3027 | self.assertEqual(self.call(test, 1, foo='bar'), ((1,), {'foo': 'bar'})) |
| 3028 | self.assertEqual(self.call(test, args=10), ((), {'args': 10})) |
| 3029 | self.assertEqual(self.call(test, 1, 2, foo='bar'), |
| 3030 | ((1, 2), {'foo': 'bar'})) |
| 3031 | |
| 3032 | def test_signature_bind_just_args(self): |
| 3033 | def test(a, b, c): |
| 3034 | return a, b, c |
| 3035 | |
| 3036 | self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 3037 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3038 | with self.assertRaisesRegex(TypeError, 'too many positional arguments'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3039 | self.call(test, 1, 2, 3, 4) |
| 3040 | |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3041 | with self.assertRaisesRegex(TypeError, |
| 3042 | "missing a required argument: 'b'"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3043 | self.call(test, 1) |
| 3044 | |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3045 | with self.assertRaisesRegex(TypeError, |
| 3046 | "missing a required argument: 'a'"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3047 | self.call(test) |
| 3048 | |
| 3049 | def test(a, b, c=10): |
| 3050 | return a, b, c |
| 3051 | self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 3052 | self.assertEqual(self.call(test, 1, 2), (1, 2, 10)) |
| 3053 | |
| 3054 | def test(a=1, b=2, c=3): |
| 3055 | return a, b, c |
| 3056 | self.assertEqual(self.call(test, a=10, c=13), (10, 2, 13)) |
| 3057 | self.assertEqual(self.call(test, a=10), (10, 2, 3)) |
| 3058 | self.assertEqual(self.call(test, b=10), (1, 10, 3)) |
| 3059 | |
| 3060 | def test_signature_bind_varargs_order(self): |
| 3061 | def test(*args): |
| 3062 | return args |
| 3063 | |
| 3064 | self.assertEqual(self.call(test), ()) |
| 3065 | self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) |
| 3066 | |
| 3067 | def test_signature_bind_args_and_varargs(self): |
| 3068 | def test(a, b, c=3, *args): |
| 3069 | return a, b, c, args |
| 3070 | |
| 3071 | self.assertEqual(self.call(test, 1, 2, 3, 4, 5), (1, 2, 3, (4, 5))) |
| 3072 | self.assertEqual(self.call(test, 1, 2), (1, 2, 3, ())) |
| 3073 | self.assertEqual(self.call(test, b=1, a=2), (2, 1, 3, ())) |
| 3074 | self.assertEqual(self.call(test, 1, b=2), (1, 2, 3, ())) |
| 3075 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3076 | with self.assertRaisesRegex(TypeError, |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3077 | "multiple values for argument 'c'"): |
| 3078 | self.call(test, 1, 2, 3, c=4) |
| 3079 | |
| 3080 | def test_signature_bind_just_kwargs(self): |
| 3081 | def test(**kwargs): |
| 3082 | return kwargs |
| 3083 | |
| 3084 | self.assertEqual(self.call(test), {}) |
| 3085 | self.assertEqual(self.call(test, foo='bar', spam='ham'), |
| 3086 | {'foo': 'bar', 'spam': 'ham'}) |
| 3087 | |
| 3088 | def test_signature_bind_args_and_kwargs(self): |
| 3089 | def test(a, b, c=3, **kwargs): |
| 3090 | return a, b, c, kwargs |
| 3091 | |
| 3092 | self.assertEqual(self.call(test, 1, 2), (1, 2, 3, {})) |
| 3093 | self.assertEqual(self.call(test, 1, 2, foo='bar', spam='ham'), |
| 3094 | (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 3095 | self.assertEqual(self.call(test, b=2, a=1, foo='bar', spam='ham'), |
| 3096 | (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 3097 | self.assertEqual(self.call(test, a=1, b=2, foo='bar', spam='ham'), |
| 3098 | (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 3099 | self.assertEqual(self.call(test, 1, b=2, foo='bar', spam='ham'), |
| 3100 | (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) |
| 3101 | self.assertEqual(self.call(test, 1, b=2, c=4, foo='bar', spam='ham'), |
| 3102 | (1, 2, 4, {'foo': 'bar', 'spam': 'ham'})) |
| 3103 | self.assertEqual(self.call(test, 1, 2, 4, foo='bar'), |
| 3104 | (1, 2, 4, {'foo': 'bar'})) |
| 3105 | self.assertEqual(self.call(test, c=5, a=4, b=3), |
| 3106 | (4, 3, 5, {})) |
| 3107 | |
| 3108 | def test_signature_bind_kwonly(self): |
| 3109 | def test(*, foo): |
| 3110 | return foo |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3111 | with self.assertRaisesRegex(TypeError, |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3112 | 'too many positional arguments'): |
| 3113 | self.call(test, 1) |
| 3114 | self.assertEqual(self.call(test, foo=1), 1) |
| 3115 | |
| 3116 | def test(a, *, foo=1, bar): |
| 3117 | return foo |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3118 | with self.assertRaisesRegex(TypeError, |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3119 | "missing a required argument: 'bar'"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3120 | self.call(test, 1) |
| 3121 | |
| 3122 | def test(foo, *, bar): |
| 3123 | return foo, bar |
| 3124 | self.assertEqual(self.call(test, 1, bar=2), (1, 2)) |
| 3125 | self.assertEqual(self.call(test, bar=2, foo=1), (1, 2)) |
| 3126 | |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3127 | with self.assertRaisesRegex( |
| 3128 | TypeError, "got an unexpected keyword argument 'spam'"): |
| 3129 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3130 | self.call(test, bar=2, foo=1, spam=10) |
| 3131 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3132 | with self.assertRaisesRegex(TypeError, |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3133 | 'too many positional arguments'): |
| 3134 | self.call(test, 1, 2) |
| 3135 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3136 | with self.assertRaisesRegex(TypeError, |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3137 | 'too many positional arguments'): |
| 3138 | self.call(test, 1, 2, bar=2) |
| 3139 | |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3140 | with self.assertRaisesRegex( |
| 3141 | TypeError, "got an unexpected keyword argument 'spam'"): |
| 3142 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3143 | self.call(test, 1, bar=2, spam='ham') |
| 3144 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3145 | with self.assertRaisesRegex(TypeError, |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3146 | "missing a required argument: 'bar'"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3147 | self.call(test, 1) |
| 3148 | |
| 3149 | def test(foo, *, bar, **bin): |
| 3150 | return foo, bar, bin |
| 3151 | self.assertEqual(self.call(test, 1, bar=2), (1, 2, {})) |
| 3152 | self.assertEqual(self.call(test, foo=1, bar=2), (1, 2, {})) |
| 3153 | self.assertEqual(self.call(test, 1, bar=2, spam='ham'), |
| 3154 | (1, 2, {'spam': 'ham'})) |
| 3155 | self.assertEqual(self.call(test, spam='ham', foo=1, bar=2), |
| 3156 | (1, 2, {'spam': 'ham'})) |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3157 | with self.assertRaisesRegex(TypeError, |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3158 | "missing a required argument: 'foo'"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3159 | self.call(test, spam='ham', bar=2) |
| 3160 | self.assertEqual(self.call(test, 1, bar=2, bin=1, spam=10), |
| 3161 | (1, 2, {'bin': 1, 'spam': 10})) |
| 3162 | |
| 3163 | def test_signature_bind_arguments(self): |
| 3164 | def test(a, *args, b, z=100, **kwargs): |
| 3165 | pass |
| 3166 | sig = inspect.signature(test) |
| 3167 | ba = sig.bind(10, 20, b=30, c=40, args=50, kwargs=60) |
| 3168 | # we won't have 'z' argument in the bound arguments object, as we didn't |
| 3169 | # pass it to the 'bind' |
| 3170 | self.assertEqual(tuple(ba.arguments.items()), |
| 3171 | (('a', 10), ('args', (20,)), ('b', 30), |
| 3172 | ('kwargs', {'c': 40, 'args': 50, 'kwargs': 60}))) |
| 3173 | self.assertEqual(ba.kwargs, |
| 3174 | {'b': 30, 'c': 40, 'args': 50, 'kwargs': 60}) |
| 3175 | self.assertEqual(ba.args, (10, 20)) |
| 3176 | |
| 3177 | def test_signature_bind_positional_only(self): |
| 3178 | P = inspect.Parameter |
| 3179 | |
| 3180 | def test(a_po, b_po, c_po=3, foo=42, *, bar=50, **kwargs): |
| 3181 | return a_po, b_po, c_po, foo, bar, kwargs |
| 3182 | |
| 3183 | sig = inspect.signature(test) |
| 3184 | new_params = collections.OrderedDict(tuple(sig.parameters.items())) |
| 3185 | for name in ('a_po', 'b_po', 'c_po'): |
| 3186 | new_params[name] = new_params[name].replace(kind=P.POSITIONAL_ONLY) |
| 3187 | new_sig = sig.replace(parameters=new_params.values()) |
| 3188 | test.__signature__ = new_sig |
| 3189 | |
| 3190 | self.assertEqual(self.call(test, 1, 2, 4, 5, bar=6), |
| 3191 | (1, 2, 4, 5, 6, {})) |
| 3192 | |
Yury Selivanov | 38b0d5a | 2014-01-28 17:27:39 -0500 | [diff] [blame] | 3193 | self.assertEqual(self.call(test, 1, 2), |
| 3194 | (1, 2, 3, 42, 50, {})) |
| 3195 | |
| 3196 | self.assertEqual(self.call(test, 1, 2, foo=4, bar=5), |
| 3197 | (1, 2, 3, 4, 5, {})) |
| 3198 | |
| 3199 | with self.assertRaisesRegex(TypeError, "but was passed as a keyword"): |
| 3200 | self.call(test, 1, 2, foo=4, bar=5, c_po=10) |
| 3201 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3202 | with self.assertRaisesRegex(TypeError, "parameter is positional only"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3203 | self.call(test, 1, 2, c_po=4) |
| 3204 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3205 | with self.assertRaisesRegex(TypeError, "parameter is positional only"): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3206 | self.call(test, a_po=1, b_po=2) |
| 3207 | |
Antoine Pitrou | bd41d1b | 2013-01-29 21:20:57 +0100 | [diff] [blame] | 3208 | def test_signature_bind_with_self_arg(self): |
| 3209 | # Issue #17071: one of the parameters is named "self |
| 3210 | def test(a, self, b): |
| 3211 | pass |
| 3212 | sig = inspect.signature(test) |
| 3213 | ba = sig.bind(1, 2, 3) |
| 3214 | self.assertEqual(ba.args, (1, 2, 3)) |
| 3215 | ba = sig.bind(1, self=2, b=3) |
| 3216 | self.assertEqual(ba.args, (1, 2, 3)) |
| 3217 | |
Yury Selivanov | 38b0d5a | 2014-01-28 17:27:39 -0500 | [diff] [blame] | 3218 | def test_signature_bind_vararg_name(self): |
| 3219 | def test(a, *args): |
| 3220 | return a, args |
| 3221 | sig = inspect.signature(test) |
| 3222 | |
Yury Selivanov | 8687275 | 2015-05-19 00:27:49 -0400 | [diff] [blame] | 3223 | with self.assertRaisesRegex( |
| 3224 | TypeError, "got an unexpected keyword argument 'args'"): |
| 3225 | |
Yury Selivanov | 38b0d5a | 2014-01-28 17:27:39 -0500 | [diff] [blame] | 3226 | sig.bind(a=0, args=1) |
| 3227 | |
| 3228 | def test(*args, **kwargs): |
| 3229 | return args, kwargs |
| 3230 | self.assertEqual(self.call(test, args=1), ((), {'args': 1})) |
| 3231 | |
| 3232 | sig = inspect.signature(test) |
| 3233 | ba = sig.bind(args=1) |
| 3234 | self.assertEqual(ba.arguments, {'kwargs': {'args': 1}}) |
| 3235 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3236 | |
| 3237 | class TestBoundArguments(unittest.TestCase): |
| 3238 | def test_signature_bound_arguments_unhashable(self): |
| 3239 | def foo(a): pass |
| 3240 | ba = inspect.signature(foo).bind(1) |
| 3241 | |
Antoine Pitrou | 46cb1ef | 2012-06-23 18:11:59 +0200 | [diff] [blame] | 3242 | with self.assertRaisesRegex(TypeError, 'unhashable type'): |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3243 | hash(ba) |
| 3244 | |
| 3245 | def test_signature_bound_arguments_equality(self): |
| 3246 | def foo(a): pass |
| 3247 | ba = inspect.signature(foo).bind(1) |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 3248 | self.assertTrue(ba == ba) |
| 3249 | self.assertFalse(ba != ba) |
| 3250 | self.assertTrue(ba == EqualsToAll()) |
| 3251 | self.assertFalse(ba != EqualsToAll()) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3252 | |
| 3253 | ba2 = inspect.signature(foo).bind(1) |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 3254 | self.assertTrue(ba == ba2) |
| 3255 | self.assertFalse(ba != ba2) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3256 | |
| 3257 | ba3 = inspect.signature(foo).bind(2) |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 3258 | self.assertFalse(ba == ba3) |
| 3259 | self.assertTrue(ba != ba3) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3260 | ba3.arguments['a'] = 1 |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 3261 | self.assertTrue(ba == ba3) |
| 3262 | self.assertFalse(ba != ba3) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3263 | |
| 3264 | def bar(b): pass |
| 3265 | ba4 = inspect.signature(bar).bind(1) |
Serhiy Storchaka | 3018cc4 | 2015-07-18 23:19:05 +0300 | [diff] [blame] | 3266 | self.assertFalse(ba == ba4) |
| 3267 | self.assertTrue(ba != ba4) |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3268 | |
Yury Selivanov | 4cfd4ea | 2015-05-14 18:30:27 -0400 | [diff] [blame] | 3269 | def foo(*, a, b): pass |
| 3270 | sig = inspect.signature(foo) |
| 3271 | ba1 = sig.bind(a=1, b=2) |
| 3272 | ba2 = sig.bind(b=2, a=1) |
Serhiy Storchaka | 2489bd5 | 2015-07-18 23:20:50 +0300 | [diff] [blame] | 3273 | self.assertTrue(ba1 == ba2) |
| 3274 | self.assertFalse(ba1 != ba2) |
Yury Selivanov | 4cfd4ea | 2015-05-14 18:30:27 -0400 | [diff] [blame] | 3275 | |
Yury Selivanov | a5d63dd | 2014-03-27 11:31:43 -0400 | [diff] [blame] | 3276 | def test_signature_bound_arguments_pickle(self): |
| 3277 | def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 3278 | sig = inspect.signature(foo) |
| 3279 | ba = sig.bind(20, 30, z={}) |
| 3280 | |
| 3281 | for ver in range(pickle.HIGHEST_PROTOCOL + 1): |
| 3282 | with self.subTest(pickle_ver=ver): |
| 3283 | ba_pickled = pickle.loads(pickle.dumps(ba, ver)) |
| 3284 | self.assertEqual(ba, ba_pickled) |
| 3285 | |
Yury Selivanov | 3f6538f | 2015-05-14 18:47:17 -0400 | [diff] [blame] | 3286 | def test_signature_bound_arguments_repr(self): |
| 3287 | def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass |
| 3288 | sig = inspect.signature(foo) |
| 3289 | ba = sig.bind(20, 30, z={}) |
Yury Selivanov | f229bc5 | 2015-05-15 12:53:56 -0400 | [diff] [blame] | 3290 | self.assertRegex(repr(ba), r'<BoundArguments \(a=20,.*\}\}\)>') |
Yury Selivanov | 3f6538f | 2015-05-14 18:47:17 -0400 | [diff] [blame] | 3291 | |
Yury Selivanov | b907a51 | 2015-05-16 13:45:09 -0400 | [diff] [blame] | 3292 | def test_signature_bound_arguments_apply_defaults(self): |
| 3293 | def foo(a, b=1, *args, c:1={}, **kw): pass |
| 3294 | sig = inspect.signature(foo) |
| 3295 | |
| 3296 | ba = sig.bind(20) |
| 3297 | ba.apply_defaults() |
| 3298 | self.assertEqual( |
| 3299 | list(ba.arguments.items()), |
| 3300 | [('a', 20), ('b', 1), ('args', ()), ('c', {}), ('kw', {})]) |
| 3301 | |
| 3302 | # Make sure that we preserve the order: |
| 3303 | # i.e. 'c' should be *before* 'kw'. |
| 3304 | ba = sig.bind(10, 20, 30, d=1) |
| 3305 | ba.apply_defaults() |
| 3306 | self.assertEqual( |
| 3307 | list(ba.arguments.items()), |
| 3308 | [('a', 10), ('b', 20), ('args', (30,)), ('c', {}), ('kw', {'d':1})]) |
| 3309 | |
| 3310 | # Make sure that BoundArguments produced by bind_partial() |
| 3311 | # are supported. |
| 3312 | def foo(a, b): pass |
| 3313 | sig = inspect.signature(foo) |
| 3314 | ba = sig.bind_partial(20) |
| 3315 | ba.apply_defaults() |
| 3316 | self.assertEqual( |
| 3317 | list(ba.arguments.items()), |
| 3318 | [('a', 20)]) |
| 3319 | |
| 3320 | # Test no args |
| 3321 | def foo(): pass |
| 3322 | sig = inspect.signature(foo) |
| 3323 | ba = sig.bind() |
| 3324 | ba.apply_defaults() |
| 3325 | self.assertEqual(list(ba.arguments.items()), []) |
| 3326 | |
Yury Selivanov | f9e1f2b | 2016-03-02 11:07:47 -0500 | [diff] [blame] | 3327 | # Make sure a no-args binding still acquires proper defaults. |
| 3328 | def foo(a='spam'): pass |
| 3329 | sig = inspect.signature(foo) |
| 3330 | ba = sig.bind() |
| 3331 | ba.apply_defaults() |
| 3332 | self.assertEqual(list(ba.arguments.items()), [('a', 'spam')]) |
| 3333 | |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3334 | |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 3335 | class TestSignaturePrivateHelpers(unittest.TestCase): |
| 3336 | def test_signature_get_bound_param(self): |
| 3337 | getter = inspect._signature_get_bound_param |
| 3338 | |
| 3339 | self.assertEqual(getter('($self)'), 'self') |
| 3340 | self.assertEqual(getter('($self, obj)'), 'self') |
| 3341 | self.assertEqual(getter('($cls, /, obj)'), 'cls') |
| 3342 | |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 3343 | def _strip_non_python_syntax(self, input, |
| 3344 | clean_signature, self_parameter, last_positional_only): |
| 3345 | computed_clean_signature, \ |
| 3346 | computed_self_parameter, \ |
| 3347 | computed_last_positional_only = \ |
| 3348 | inspect._signature_strip_non_python_syntax(input) |
| 3349 | self.assertEqual(computed_clean_signature, clean_signature) |
| 3350 | self.assertEqual(computed_self_parameter, self_parameter) |
| 3351 | self.assertEqual(computed_last_positional_only, last_positional_only) |
| 3352 | |
| 3353 | def test_signature_strip_non_python_syntax(self): |
| 3354 | self._strip_non_python_syntax( |
| 3355 | "($module, /, path, mode, *, dir_fd=None, " + |
| 3356 | "effective_ids=False,\n follow_symlinks=True)", |
| 3357 | "(module, path, mode, *, dir_fd=None, " + |
| 3358 | "effective_ids=False, follow_symlinks=True)", |
| 3359 | 0, |
| 3360 | 0) |
| 3361 | |
| 3362 | self._strip_non_python_syntax( |
| 3363 | "($module, word, salt, /)", |
| 3364 | "(module, word, salt)", |
| 3365 | 0, |
| 3366 | 2) |
| 3367 | |
| 3368 | self._strip_non_python_syntax( |
| 3369 | "(x, y=None, z=None, /)", |
| 3370 | "(x, y=None, z=None)", |
| 3371 | None, |
| 3372 | 2) |
| 3373 | |
| 3374 | self._strip_non_python_syntax( |
| 3375 | "(x, y=None, z=None)", |
| 3376 | "(x, y=None, z=None)", |
| 3377 | None, |
| 3378 | None) |
| 3379 | |
| 3380 | self._strip_non_python_syntax( |
| 3381 | "(x,\n y=None,\n z = None )", |
| 3382 | "(x, y=None, z=None)", |
| 3383 | None, |
| 3384 | None) |
| 3385 | |
| 3386 | self._strip_non_python_syntax( |
| 3387 | "", |
| 3388 | "", |
| 3389 | None, |
| 3390 | None) |
| 3391 | |
| 3392 | self._strip_non_python_syntax( |
| 3393 | None, |
| 3394 | None, |
| 3395 | None, |
| 3396 | None) |
| 3397 | |
Nick Coghlan | 9c680b0 | 2015-04-13 12:54:54 -0400 | [diff] [blame] | 3398 | class TestSignatureDefinitions(unittest.TestCase): |
| 3399 | # This test case provides a home for checking that particular APIs |
| 3400 | # have signatures available for introspection |
| 3401 | |
| 3402 | @cpython_only |
| 3403 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 3404 | "Signature information for builtins requires docstrings") |
| 3405 | def test_builtins_have_signatures(self): |
| 3406 | # This checks all builtin callables in CPython have signatures |
| 3407 | # A few have signatures Signature can't yet handle, so we skip those |
| 3408 | # since they will have to wait until PEP 457 adds the required |
| 3409 | # introspection support to the inspect module |
| 3410 | # Some others also haven't been converted yet for various other |
| 3411 | # reasons, so we also skip those for the time being, but design |
| 3412 | # the test to fail in order to indicate when it needs to be |
| 3413 | # updated. |
| 3414 | no_signature = set() |
| 3415 | # These need PEP 457 groups |
| 3416 | needs_groups = {"range", "slice", "dir", "getattr", |
| 3417 | "next", "iter", "vars"} |
| 3418 | no_signature |= needs_groups |
| 3419 | # These need PEP 457 groups or a signature change to accept None |
| 3420 | needs_semantic_update = {"round"} |
| 3421 | no_signature |= needs_semantic_update |
| 3422 | # These need *args support in Argument Clinic |
| 3423 | needs_varargs = {"min", "max", "print", "__build_class__"} |
| 3424 | no_signature |= needs_varargs |
| 3425 | # These simply weren't covered in the initial AC conversion |
| 3426 | # for builtin callables |
| 3427 | not_converted_yet = {"open", "__import__"} |
| 3428 | no_signature |= not_converted_yet |
| 3429 | # These builtin types are expected to provide introspection info |
| 3430 | types_with_signatures = set() |
| 3431 | # Check the signatures we expect to be there |
| 3432 | ns = vars(builtins) |
| 3433 | for name, obj in sorted(ns.items()): |
| 3434 | if not callable(obj): |
| 3435 | continue |
| 3436 | # The builtin types haven't been converted to AC yet |
| 3437 | if isinstance(obj, type) and (name not in types_with_signatures): |
| 3438 | # Note that this also skips all the exception types |
| 3439 | no_signature.add(name) |
| 3440 | if (name in no_signature): |
| 3441 | # Not yet converted |
| 3442 | continue |
| 3443 | with self.subTest(builtin=name): |
| 3444 | self.assertIsNotNone(inspect.signature(obj)) |
| 3445 | # Check callables that haven't been converted don't claim a signature |
| 3446 | # This ensures this test will start failing as more signatures are |
| 3447 | # added, so the affected items can be moved into the scope of the |
| 3448 | # regression test above |
| 3449 | for name in no_signature: |
| 3450 | with self.subTest(builtin=name): |
| 3451 | self.assertIsNone(obj.__text_signature__) |
| 3452 | |
Yury Selivanov | d82eddc | 2014-01-29 11:24:39 -0500 | [diff] [blame] | 3453 | |
Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 3454 | class TestUnwrap(unittest.TestCase): |
| 3455 | |
| 3456 | def test_unwrap_one(self): |
| 3457 | def func(a, b): |
| 3458 | return a + b |
| 3459 | wrapper = functools.lru_cache(maxsize=20)(func) |
| 3460 | self.assertIs(inspect.unwrap(wrapper), func) |
| 3461 | |
| 3462 | def test_unwrap_several(self): |
| 3463 | def func(a, b): |
| 3464 | return a + b |
| 3465 | wrapper = func |
| 3466 | for __ in range(10): |
| 3467 | @functools.wraps(wrapper) |
| 3468 | def wrapper(): |
| 3469 | pass |
| 3470 | self.assertIsNot(wrapper.__wrapped__, func) |
| 3471 | self.assertIs(inspect.unwrap(wrapper), func) |
| 3472 | |
| 3473 | def test_stop(self): |
| 3474 | def func1(a, b): |
| 3475 | return a + b |
| 3476 | @functools.wraps(func1) |
| 3477 | def func2(): |
| 3478 | pass |
| 3479 | @functools.wraps(func2) |
| 3480 | def wrapper(): |
| 3481 | pass |
| 3482 | func2.stop_here = 1 |
| 3483 | unwrapped = inspect.unwrap(wrapper, |
| 3484 | stop=(lambda f: hasattr(f, "stop_here"))) |
| 3485 | self.assertIs(unwrapped, func2) |
| 3486 | |
| 3487 | def test_cycle(self): |
| 3488 | def func1(): pass |
| 3489 | func1.__wrapped__ = func1 |
| 3490 | with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 3491 | inspect.unwrap(func1) |
| 3492 | |
| 3493 | def func2(): pass |
| 3494 | func2.__wrapped__ = func1 |
| 3495 | func1.__wrapped__ = func2 |
| 3496 | with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 3497 | inspect.unwrap(func1) |
| 3498 | with self.assertRaisesRegex(ValueError, 'wrapper loop'): |
| 3499 | inspect.unwrap(func2) |
| 3500 | |
| 3501 | def test_unhashable(self): |
| 3502 | def func(): pass |
| 3503 | func.__wrapped__ = None |
| 3504 | class C: |
| 3505 | __hash__ = None |
| 3506 | __wrapped__ = func |
| 3507 | self.assertIsNone(inspect.unwrap(C())) |
| 3508 | |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 3509 | class TestMain(unittest.TestCase): |
| 3510 | def test_only_source(self): |
| 3511 | module = importlib.import_module('unittest') |
| 3512 | rc, out, err = assert_python_ok('-m', 'inspect', |
| 3513 | 'unittest') |
| 3514 | lines = out.decode().splitlines() |
| 3515 | # ignore the final newline |
| 3516 | self.assertEqual(lines[:-1], inspect.getsource(module).splitlines()) |
| 3517 | self.assertEqual(err, b'') |
| 3518 | |
Yury Selivanov | 42407ab | 2014-06-23 10:23:50 -0700 | [diff] [blame] | 3519 | def test_custom_getattr(self): |
| 3520 | def foo(): |
| 3521 | pass |
| 3522 | foo.__signature__ = 42 |
| 3523 | with self.assertRaises(TypeError): |
| 3524 | inspect.signature(foo) |
| 3525 | |
Brett Cannon | 634a8fc | 2013-10-02 10:25:42 -0400 | [diff] [blame] | 3526 | @unittest.skipIf(ThreadPoolExecutor is None, |
Brett Cannon | 0de3f01 | 2013-10-02 10:58:58 -0400 | [diff] [blame] | 3527 | 'threads required to test __qualname__ for source files') |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 3528 | def test_qualname_source(self): |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 3529 | rc, out, err = assert_python_ok('-m', 'inspect', |
| 3530 | 'concurrent.futures:ThreadPoolExecutor') |
| 3531 | lines = out.decode().splitlines() |
| 3532 | # ignore the final newline |
| 3533 | self.assertEqual(lines[:-1], |
Brett Cannon | 634a8fc | 2013-10-02 10:25:42 -0400 | [diff] [blame] | 3534 | inspect.getsource(ThreadPoolExecutor).splitlines()) |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 3535 | self.assertEqual(err, b'') |
| 3536 | |
| 3537 | def test_builtins(self): |
| 3538 | module = importlib.import_module('unittest') |
| 3539 | _, out, err = assert_python_failure('-m', 'inspect', |
| 3540 | 'sys') |
| 3541 | lines = err.decode().splitlines() |
| 3542 | self.assertEqual(lines, ["Can't get info for builtin modules."]) |
| 3543 | |
| 3544 | def test_details(self): |
| 3545 | module = importlib.import_module('unittest') |
| 3546 | rc, out, err = assert_python_ok('-m', 'inspect', |
| 3547 | 'unittest', '--details') |
| 3548 | output = out.decode() |
| 3549 | # Just a quick sanity check on the output |
| 3550 | self.assertIn(module.__name__, output) |
| 3551 | self.assertIn(module.__file__, output) |
Serhiy Storchaka | b12cb6a | 2013-12-08 18:16:18 +0200 | [diff] [blame] | 3552 | if not sys.flags.optimize: |
| 3553 | self.assertIn(module.__cached__, output) |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 3554 | self.assertEqual(err, b'') |
| 3555 | |
| 3556 | |
Yury Selivanov | ef1e750 | 2014-12-08 16:05:34 -0500 | [diff] [blame] | 3557 | class TestReload(unittest.TestCase): |
| 3558 | |
| 3559 | src_before = textwrap.dedent("""\ |
| 3560 | def foo(): |
| 3561 | print("Bla") |
| 3562 | """) |
| 3563 | |
| 3564 | src_after = textwrap.dedent("""\ |
| 3565 | def foo(): |
| 3566 | print("Oh no!") |
| 3567 | """) |
| 3568 | |
| 3569 | def assertInspectEqual(self, path, source): |
| 3570 | inspected_src = inspect.getsource(source) |
| 3571 | with open(path) as src: |
| 3572 | self.assertEqual( |
| 3573 | src.read().splitlines(True), |
| 3574 | inspected_src.splitlines(True) |
| 3575 | ) |
| 3576 | |
| 3577 | def test_getsource_reload(self): |
| 3578 | # see issue 1218234 |
| 3579 | with _ready_to_import('reload_bug', self.src_before) as (name, path): |
| 3580 | module = importlib.import_module(name) |
| 3581 | self.assertInspectEqual(path, module) |
| 3582 | with open(path, 'w') as src: |
| 3583 | src.write(self.src_after) |
| 3584 | self.assertInspectEqual(path, module) |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 3585 | |
Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 3586 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 3587 | def test_main(): |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 3588 | run_unittest( |
| 3589 | TestDecorators, TestRetrievingSourceCode, TestOneliners, TestBuggyCases, |
| 3590 | TestInterpreterStack, TestClassesAndFunctions, TestPredicates, |
| 3591 | TestGetcallargsFunctions, TestGetcallargsMethods, |
Alexander Belopolsky | f546e70 | 2010-12-02 00:10:11 +0000 | [diff] [blame] | 3592 | TestGetcallargsUnboundMethods, TestGetattrStatic, TestGetGeneratorState, |
Larry Hastings | 7c7cbfc | 2012-06-22 15:19:35 -0700 | [diff] [blame] | 3593 | TestNoEOL, TestSignatureObject, TestSignatureBind, TestParameterObject, |
Nick Coghlan | 9c680b0 | 2015-04-13 12:54:54 -0400 | [diff] [blame] | 3594 | TestBoundArguments, TestSignaturePrivateHelpers, |
| 3595 | TestSignatureDefinitions, |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 3596 | TestGetClosureVars, TestUnwrap, TestMain, TestReload, |
| 3597 | TestGetCoroutineState |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 3598 | ) |
Martin v. Löwis | 893ffa4 | 2003-10-31 15:35:53 +0000 | [diff] [blame] | 3599 | |
Johannes Gijsbers | cb9015d | 2004-12-12 16:20:22 +0000 | [diff] [blame] | 3600 | if __name__ == "__main__": |
| 3601 | test_main() |