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