Debian Codegraph @

Lib/test/test_symtable.py

raw
1 """
2 Test the API of the symtable module.
3 """
4
5 import textwrap
6 import symtable
7 import unittest
8
9 from test import support
10 from test.support import os_helper
11
12
13 TEST_CODE = """
14 import sys
15
16 glob = 42
17 some_var = 12
18 some_non_assigned_global_var: int
19 some_assigned_global_var = 11
20
21 class Mine:
22 instance_var = 24
23 def a_method(p1, p2):
24 pass
25
26 def spam(a, b, *var, **kw):
27 global bar
28 global some_assigned_global_var
29 some_assigned_global_var = 12
30 bar = 47
31 some_var = 10
32 x = 23
33 glob
34 def internal():
35 return x
36 def other_internal():
37 nonlocal some_var
38 some_var = 3
39 return some_var
40 return internal
41
42 def foo():
43 pass
44
45 def namespace_test(): pass
46 def namespace_test(): pass
47
48 type Alias = int
49 type GenericAlias[T] = list[T]
50
51 def generic_spam[T](a):
52 pass
53
54 class GenericMine[T: int, U: (int, str) = int]:
55 pass
56 """
57
58 TEST_COMPLEX_CLASS_CODE = """
59 # The following symbols are defined in ComplexClass
60 # without being introduced by a 'global' statement.
61 glob_unassigned_meth: Any
62 glob_unassigned_meth_pep_695: Any
63
64 glob_unassigned_async_meth: Any
65 glob_unassigned_async_meth_pep_695: Any
66
67 def glob_assigned_meth(): pass
68 def glob_assigned_meth_pep_695[T](): pass
69
70 async def glob_assigned_async_meth(): pass
71 async def glob_assigned_async_meth_pep_695[T](): pass
72
73 # The following symbols are defined in ComplexClass after
74 # being introduced by a 'global' statement (and therefore
75 # are not considered as local symbols of ComplexClass).
76 glob_unassigned_meth_ignore: Any
77 glob_unassigned_meth_pep_695_ignore: Any
78
79 glob_unassigned_async_meth_ignore: Any
80 glob_unassigned_async_meth_pep_695_ignore: Any
81
82 def glob_assigned_meth_ignore(): pass
83 def glob_assigned_meth_pep_695_ignore[T](): pass
84
85 async def glob_assigned_async_meth_ignore(): pass
86 async def glob_assigned_async_meth_pep_695_ignore[T](): pass
87
88 class ComplexClass:
89 a_var = 1234
90 a_genexpr = (x for x in [])
91 a_lambda = lambda x: x
92
93 type a_type_alias = int
94 type a_type_alias_pep_695[T] = list[T]
95
96 class a_class: pass
97 class a_class_pep_695[T]: pass
98
99 def a_method(self): pass
100 def a_method_pep_695[T](self): pass
101
102 async def an_async_method(self): pass
103 async def an_async_method_pep_695[T](self): pass
104
105 @classmethod
106 def a_classmethod(cls): pass
107 @classmethod
108 def a_classmethod_pep_695[T](self): pass
109
110 @classmethod
111 async def an_async_classmethod(cls): pass
112 @classmethod
113 async def an_async_classmethod_pep_695[T](self): pass
114
115 @staticmethod
116 def a_staticmethod(): pass
117 @staticmethod
118 def a_staticmethod_pep_695[T](self): pass
119
120 @staticmethod
121 async def an_async_staticmethod(): pass
122 @staticmethod
123 async def an_async_staticmethod_pep_695[T](self): pass
124
125 # These ones will be considered as methods because of the 'def' although
126 # they are *not* valid methods at runtime since they are not decorated
127 # with @staticmethod.
128 def a_fakemethod(): pass
129 def a_fakemethod_pep_695[T](): pass
130
131 async def an_async_fakemethod(): pass
132 async def an_async_fakemethod_pep_695[T](): pass
133
134 # Check that those are still considered as methods
135 # since they are not using the 'global' keyword.
136 def glob_unassigned_meth(): pass
137 def glob_unassigned_meth_pep_695[T](): pass
138
139 async def glob_unassigned_async_meth(): pass
140 async def glob_unassigned_async_meth_pep_695[T](): pass
141
142 def glob_assigned_meth(): pass
143 def glob_assigned_meth_pep_695[T](): pass
144
145 async def glob_assigned_async_meth(): pass
146 async def glob_assigned_async_meth_pep_695[T](): pass
147
148 # The following are not picked as local symbols because they are not
149 # visible by the class at runtime (this is equivalent to having the
150 # definitions outside of the class).
151 global glob_unassigned_meth_ignore
152 def glob_unassigned_meth_ignore(): pass
153 global glob_unassigned_meth_pep_695_ignore
154 def glob_unassigned_meth_pep_695_ignore[T](): pass
155
156 global glob_unassigned_async_meth_ignore
157 async def glob_unassigned_async_meth_ignore(): pass
158 global glob_unassigned_async_meth_pep_695_ignore
159 async def glob_unassigned_async_meth_pep_695_ignore[T](): pass
160
161 global glob_assigned_meth_ignore
162 def glob_assigned_meth_ignore(): pass
163 global glob_assigned_meth_pep_695_ignore
164 def glob_assigned_meth_pep_695_ignore[T](): pass
165
166 global glob_assigned_async_meth_ignore
167 async def glob_assigned_async_meth_ignore(): pass
168 global glob_assigned_async_meth_pep_695_ignore
169 async def glob_assigned_async_meth_pep_695_ignore[T](): pass
170 """
171
172
173 def find_block(block, name):
174 for ch in block.get_children():
175 if ch.get_name() == name:
176 return ch
177
178
179 class SymtableTest(unittest.TestCase):
180
181 top = symtable.symtable(TEST_CODE, "?", "exec")
182 # These correspond to scopes in TEST_CODE
183 Mine = find_block(top, "Mine")
184
185 a_method = find_block(Mine, "a_method")
186 spam = find_block(top, "spam")
187 internal = find_block(spam, "internal")
188 other_internal = find_block(spam, "other_internal")
189 foo = find_block(top, "foo")
190 Alias = find_block(top, "Alias")
191 GenericAlias = find_block(top, "GenericAlias")
192 GenericAlias_inner = find_block(GenericAlias, "GenericAlias")
193 generic_spam = find_block(top, "generic_spam")
194 generic_spam_inner = find_block(generic_spam, "generic_spam")
195 GenericMine = find_block(top, "GenericMine")
196 GenericMine_inner = find_block(GenericMine, "GenericMine")
197 T = find_block(GenericMine, "T")
198 U = find_block(GenericMine, "U")
199
200 def test_type(self):
201 self.assertEqual(self.top.get_type(), "module")
202 self.assertEqual(self.Mine.get_type(), "class")
203 self.assertEqual(self.a_method.get_type(), "function")
204 self.assertEqual(self.spam.get_type(), "function")
205 self.assertEqual(self.internal.get_type(), "function")
206 self.assertEqual(self.foo.get_type(), "function")
207 self.assertEqual(self.Alias.get_type(), "type alias")
208 self.assertEqual(self.GenericAlias.get_type(), "type parameters")
209 self.assertEqual(self.GenericAlias_inner.get_type(), "type alias")
210 self.assertEqual(self.generic_spam.get_type(), "type parameters")
211 self.assertEqual(self.generic_spam_inner.get_type(), "function")
212 self.assertEqual(self.GenericMine.get_type(), "type parameters")
213 self.assertEqual(self.GenericMine_inner.get_type(), "class")
214 self.assertEqual(self.T.get_type(), "type variable")
215 self.assertEqual(self.U.get_type(), "type variable")
216
217 def test_id(self):
218 self.assertGreater(self.top.get_id(), 0)
219 self.assertGreater(self.Mine.get_id(), 0)
220 self.assertGreater(self.a_method.get_id(), 0)
221 self.assertGreater(self.spam.get_id(), 0)
222 self.assertGreater(self.internal.get_id(), 0)
223 self.assertGreater(self.foo.get_id(), 0)
224 self.assertGreater(self.Alias.get_id(), 0)
225 self.assertGreater(self.GenericAlias.get_id(), 0)
226 self.assertGreater(self.generic_spam.get_id(), 0)
227 self.assertGreater(self.GenericMine.get_id(), 0)
228
229 def test_optimized(self):
230 self.assertFalse(self.top.is_optimized())
231
232 self.assertTrue(self.spam.is_optimized())
233
234 def test_nested(self):
235 self.assertFalse(self.top.is_nested())
236 self.assertFalse(self.Mine.is_nested())
237 self.assertFalse(self.spam.is_nested())
238 self.assertTrue(self.internal.is_nested())
239
240 def test_children(self):
241 self.assertTrue(self.top.has_children())
242 self.assertTrue(self.Mine.has_children())
243 self.assertFalse(self.foo.has_children())
244
245 def test_lineno(self):
246 self.assertEqual(self.top.get_lineno(), 0)
247 self.assertEqual(self.spam.get_lineno(), 14)
248
249 def test_function_info(self):
250 func = self.spam
251 self.assertEqual(sorted(func.get_parameters()), ["a", "b", "kw", "var"])
252 expected = ['a', 'b', 'internal', 'kw', 'other_internal', 'some_var', 'var', 'x']
253 self.assertEqual(sorted(func.get_locals()), expected)
254 self.assertEqual(sorted(func.get_globals()), ["bar", "glob", "some_assigned_global_var"])
255 self.assertEqual(self.internal.get_frees(), ("x",))
256
257 def test_globals(self):
258 self.assertTrue(self.spam.lookup("glob").is_global())
259 self.assertFalse(self.spam.lookup("glob").is_declared_global())
260 self.assertTrue(self.spam.lookup("bar").is_global())
261 self.assertTrue(self.spam.lookup("bar").is_declared_global())
262 self.assertFalse(self.internal.lookup("x").is_global())
263 self.assertFalse(self.Mine.lookup("instance_var").is_global())
264 self.assertTrue(self.spam.lookup("bar").is_global())
265 # Module-scope globals are both global and local
266 self.assertTrue(self.top.lookup("some_non_assigned_global_var").is_global())
267 self.assertTrue(self.top.lookup("some_assigned_global_var").is_global())
268
269 def test_nonlocal(self):
270 self.assertFalse(self.spam.lookup("some_var").is_nonlocal())
271 self.assertTrue(self.other_internal.lookup("some_var").is_nonlocal())
272 expected = ("some_var",)
273 self.assertEqual(self.other_internal.get_nonlocals(), expected)
274
275 def test_local(self):
276 self.assertTrue(self.spam.lookup("x").is_local())
277 self.assertFalse(self.spam.lookup("bar").is_local())
278 # Module-scope globals are both global and local
279 self.assertTrue(self.top.lookup("some_non_assigned_global_var").is_local())
280 self.assertTrue(self.top.lookup("some_assigned_global_var").is_local())
281
282 def test_free(self):
283 self.assertTrue(self.internal.lookup("x").is_free())
284
285 def test_referenced(self):
286 self.assertTrue(self.internal.lookup("x").is_referenced())
287 self.assertTrue(self.spam.lookup("internal").is_referenced())
288 self.assertFalse(self.spam.lookup("x").is_referenced())
289
290 def test_parameters(self):
291 for sym in ("a", "var", "kw"):
292 self.assertTrue(self.spam.lookup(sym).is_parameter())
293 self.assertFalse(self.spam.lookup("x").is_parameter())
294
295 def test_symbol_lookup(self):
296 self.assertEqual(len(self.top.get_identifiers()),
297 len(self.top.get_symbols()))
298
299 self.assertRaises(KeyError, self.top.lookup, "not_here")
300
301 def test_namespaces(self):
302 self.assertTrue(self.top.lookup("Mine").is_namespace())
303 self.assertTrue(self.Mine.lookup("a_method").is_namespace())
304 self.assertTrue(self.top.lookup("spam").is_namespace())
305 self.assertTrue(self.spam.lookup("internal").is_namespace())
306 self.assertTrue(self.top.lookup("namespace_test").is_namespace())
307 self.assertFalse(self.spam.lookup("x").is_namespace())
308
309 self.assertTrue(self.top.lookup("spam").get_namespace() is self.spam)
310 ns_test = self.top.lookup("namespace_test")
311 self.assertEqual(len(ns_test.get_namespaces()), 2)
312 self.assertRaises(ValueError, ns_test.get_namespace)
313
314 ns_test_2 = self.top.lookup("glob")
315 self.assertEqual(len(ns_test_2.get_namespaces()), 0)
316 self.assertRaises(ValueError, ns_test_2.get_namespace)
317
318 def test_assigned(self):
319 self.assertTrue(self.spam.lookup("x").is_assigned())
320 self.assertTrue(self.spam.lookup("bar").is_assigned())
321 self.assertTrue(self.top.lookup("spam").is_assigned())
322 self.assertTrue(self.Mine.lookup("a_method").is_assigned())
323 self.assertFalse(self.internal.lookup("x").is_assigned())
324
325 def test_annotated(self):
326 st1 = symtable.symtable('def f():\n x: int\n', 'test', 'exec')
327 st2 = st1.get_children()[0]
328 self.assertTrue(st2.lookup('x').is_local())
329 self.assertTrue(st2.lookup('x').is_annotated())
330 self.assertFalse(st2.lookup('x').is_global())
331 st3 = symtable.symtable('def f():\n x = 1\n', 'test', 'exec')
332 st4 = st3.get_children()[0]
333 self.assertTrue(st4.lookup('x').is_local())
334 self.assertFalse(st4.lookup('x').is_annotated())
335
336 # Test that annotations in the global scope are valid after the
337 # variable is declared as nonlocal.
338 st5 = symtable.symtable('global x\nx: int', 'test', 'exec')
339 self.assertTrue(st5.lookup("x").is_global())
340
341 # Test that annotations for nonlocals are valid after the
342 # variable is declared as nonlocal.
343 st6 = symtable.symtable('def g():\n'
344 ' x = 2\n'
345 ' def f():\n'
346 ' nonlocal x\n'
347 ' x: int',
348 'test', 'exec')
349
350 def test_imported(self):
351 self.assertTrue(self.top.lookup("sys").is_imported())
352
353 def test_name(self):
354 self.assertEqual(self.top.get_name(), "top")
355 self.assertEqual(self.spam.get_name(), "spam")
356 self.assertEqual(self.spam.lookup("x").get_name(), "x")
357 self.assertEqual(self.Mine.get_name(), "Mine")
358
359 def test_class_get_methods(self):
360 self.assertEqual(self.Mine.get_methods(), ('a_method',))
361
362 top = symtable.symtable(TEST_COMPLEX_CLASS_CODE, "?", "exec")
363 this = find_block(top, "ComplexClass")
364
365 self.assertEqual(this.get_methods(), (
366 'a_method', 'a_method_pep_695',
367 'an_async_method', 'an_async_method_pep_695',
368 'a_classmethod', 'a_classmethod_pep_695',
369 'an_async_classmethod', 'an_async_classmethod_pep_695',
370 'a_staticmethod', 'a_staticmethod_pep_695',
371 'an_async_staticmethod', 'an_async_staticmethod_pep_695',
372 'a_fakemethod', 'a_fakemethod_pep_695',
373 'an_async_fakemethod', 'an_async_fakemethod_pep_695',
374 'glob_unassigned_meth', 'glob_unassigned_meth_pep_695',
375 'glob_unassigned_async_meth', 'glob_unassigned_async_meth_pep_695',
376 'glob_assigned_meth', 'glob_assigned_meth_pep_695',
377 'glob_assigned_async_meth', 'glob_assigned_async_meth_pep_695',
378 ))
379
380 # Test generator expressions that are of type TYPE_FUNCTION
381 # but will not be reported by get_methods() since they are
382 # not functions per se.
383 #
384 # Other kind of comprehensions such as list, set or dict
385 # expressions do not have the TYPE_FUNCTION type.
386
387 def check_body(body, expected_methods):
388 indented = textwrap.indent(body, ' ' * 4)
389 top = symtable.symtable(f"class A:\n{indented}", "?", "exec")
390 this = find_block(top, "A")
391 self.assertEqual(this.get_methods(), expected_methods)
392
393 # statements with 'genexpr' inside it
394 GENEXPRS = (
395 'x = (x for x in [])',
396 'x = (x async for x in [])',
397 'type x[genexpr = (x for x in [])] = (x for x in [])',
398 'type x[genexpr = (x async for x in [])] = (x async for x in [])',
399 'genexpr = (x for x in [])',
400 'genexpr = (x async for x in [])',
401 'type genexpr[genexpr = (x for x in [])] = (x for x in [])',
402 'type genexpr[genexpr = (x async for x in [])] = (x async for x in [])',
403 )
404
405 for gen in GENEXPRS:
406 # test generator expression
407 with self.subTest(gen=gen):
408 check_body(gen, ())
409
410 # test generator expression + variable named 'genexpr'
411 with self.subTest(gen=gen, isvar=True):
412 check_body('\n'.join((gen, 'genexpr = 1')), ())
413 check_body('\n'.join(('genexpr = 1', gen)), ())
414
415 for paramlist in ('()', '(x)', '(x, y)', '(z: T)'):
416 for func in (
417 f'def genexpr{paramlist}:pass',
418 f'async def genexpr{paramlist}:pass',
419 f'def genexpr[T]{paramlist}:pass',
420 f'async def genexpr[T]{paramlist}:pass',
421 ):
422 with self.subTest(func=func):
423 # test function named 'genexpr'
424 check_body(func, ('genexpr',))
425
426 for gen in GENEXPRS:
427 with self.subTest(gen=gen, func=func):
428 # test generator expression + function named 'genexpr'
429 check_body('\n'.join((gen, func)), ('genexpr',))
430 check_body('\n'.join((func, gen)), ('genexpr',))
431
432 def test_filename_correct(self):
433 ### Bug tickler: SyntaxError file name correct whether error raised
434 ### while parsing or building symbol table.
435 def checkfilename(brokencode, offset):
436 try:
437 symtable.symtable(brokencode, "spam", "exec")
438 except SyntaxError as e:
439 self.assertEqual(e.filename, "spam")
440 self.assertEqual(e.lineno, 1)
441 self.assertEqual(e.offset, offset)
442 else:
443 self.fail("no SyntaxError for %r" % (brokencode,))
444 checkfilename("def f(x): foo)(", 14) # parse-time
445 checkfilename("def f(x): global x", 11) # symtable-build-time
446 symtable.symtable("pass", b"spam", "exec")
447 with self.assertRaises(TypeError):
448 symtable.symtable("pass", bytearray(b"spam"), "exec")
449 with self.assertRaises(TypeError):
450 symtable.symtable("pass", memoryview(b"spam"), "exec")
451 with self.assertRaises(TypeError):
452 symtable.symtable("pass", list(b"spam"), "exec")
453
454 def test_eval(self):
455 symbols = symtable.symtable("42", "?", "eval")
456
457 def test_single(self):
458 symbols = symtable.symtable("42", "?", "single")
459
460 def test_exec(self):
461 symbols = symtable.symtable("def f(x): return x", "?", "exec")
462
463 def test_bytes(self):
464 top = symtable.symtable(TEST_CODE.encode('utf8'), "?", "exec")
465 self.assertIsNotNone(find_block(top, "Mine"))
466
467 code = b'# -*- coding: iso8859-15 -*-\nclass \xb4: pass\n'
468
469 top = symtable.symtable(code, "?", "exec")
470 self.assertIsNotNone(find_block(top, "\u017d"))
471
472 def test_symtable_repr(self):
473 self.assertEqual(str(self.top), "<SymbolTable for module ?>")
474 self.assertEqual(str(self.spam), "<Function SymbolTable for spam in ?>")
475
476 def test_symbol_repr(self):
477 self.assertEqual(repr(self.spam.lookup("glob")),
478 "<symbol 'glob': GLOBAL_IMPLICIT, USE>")
479 self.assertEqual(repr(self.spam.lookup("bar")),
480 "<symbol 'bar': GLOBAL_EXPLICIT, DEF_GLOBAL|DEF_LOCAL>")
481 self.assertEqual(repr(self.spam.lookup("a")),
482 "<symbol 'a': LOCAL, DEF_PARAM>")
483 self.assertEqual(repr(self.spam.lookup("internal")),
484 "<symbol 'internal': LOCAL, USE|DEF_LOCAL>")
485 self.assertEqual(repr(self.spam.lookup("other_internal")),
486 "<symbol 'other_internal': LOCAL, DEF_LOCAL>")
487 self.assertEqual(repr(self.internal.lookup("x")),
488 "<symbol 'x': FREE, USE>")
489 self.assertEqual(repr(self.other_internal.lookup("some_var")),
490 "<symbol 'some_var': FREE, USE|DEF_NONLOCAL|DEF_LOCAL>")
491
492 def test_symtable_entry_repr(self):
493 expected = f"<symtable entry top({self.top.get_id()}), line {self.top.get_lineno()}>"
494 self.assertEqual(repr(self.top._table), expected)
495
496 def test__symtable_refleak(self):
497 # Regression test for reference leak in PyUnicode_FSDecoder.
498 # See https://github.com/python/cpython/issues/139748.
499 mortal_str = 'this is a mortal string'
500 # check error path when 'compile_type' AC conversion failed
501 self.assertRaises(TypeError, symtable.symtable, '', mortal_str, 1)
502
503
504 class CommandLineTest(unittest.TestCase):
505 maxDiff = None
506
507 def test_file(self):
508 filename = os_helper.TESTFN
509 self.addCleanup(os_helper.unlink, filename)
510 with open(filename, 'w') as f:
511 f.write(TEST_CODE)
512 with support.captured_stdout() as stdout:
513 symtable.main([filename])
514 out = stdout.getvalue()
515 self.assertIn('\n\n', out)
516 self.assertNotIn('\n\n\n', out)
517 lines = out.splitlines()
518 self.assertIn(f"symbol table for module from file {filename!r}:", lines)
519 self.assertIn(" local symbol 'glob': def_local", lines)
520 self.assertIn(" global_implicit symbol 'glob': use", lines)
521 self.assertIn(" local symbol 'spam': def_local", lines)
522 self.assertIn(" symbol table for function 'spam':", lines)
523
524 def test_stdin(self):
525 with support.captured_stdin() as stdin:
526 stdin.write(TEST_CODE)
527 stdin.seek(0)
528 with support.captured_stdout() as stdout:
529 symtable.main([])
530 out = stdout.getvalue()
531 stdin.seek(0)
532 with support.captured_stdout() as stdout:
533 symtable.main(['-'])
534 self.assertEqual(stdout.getvalue(), out)
535 lines = out.splitlines()
536 self.assertIn("symbol table for module from file '<stdin>':", lines)
537
538
539 if __name__ == '__main__':
540 unittest.main()