Skip to content

Commit e50bcb2

Browse files
committed
tests/test_namecollector.py
1 parent 1cb6e79 commit e50bcb2

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

tests/test_namecollector.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import ast
2+
3+
from tracefunc.core import NameCollector
4+
5+
6+
def _collect_names(src, node):
7+
collector = NameCollector(node)
8+
collector.visit(node)
9+
return collector.names
10+
11+
12+
def test_names_in_statement_do_not_descend_into_comprehension():
13+
mod = ast.parse(
14+
"def f(n):\n"
15+
" xs = [i * i for i in range(n)]\n"
16+
" return xs\n"
17+
)
18+
fn = mod.body[0]
19+
assign = fn.body[0]
20+
assert _collect_names(mod, assign) == {"xs"}
21+
22+
23+
def test_names_in_comprehension_include_iteration_vars():
24+
mod = ast.parse("def f(n):\n xs = [i * i for i in range(n)]\n")
25+
fn = mod.body[0]
26+
comp = fn.body[0].value
27+
assert _collect_names(mod, comp) == {"i", "n", "range"}
28+
29+
30+
def test_names_for_import_and_except_handler_are_root_only():
31+
mod = ast.parse("""\
32+
def f():
33+
import os.path as p
34+
try:
35+
1 / 0
36+
except Exception as err:
37+
return err
38+
""")
39+
fn = mod.body[0]
40+
imp = fn.body[0]
41+
try_stmt = fn.body[1]
42+
handler = try_stmt.handlers[0]
43+
assert _collect_names(mod, imp) == {"p"}
44+
assert _collect_names(mod, handler) == {"Exception", "err"}

0 commit comments

Comments
 (0)