Fixed #18 : Parsing and evaluating Python
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import ast
|
||||
|
||||
import pytest
|
||||
|
||||
from common.ast_utils import NamesWithAttributesVisitor, UnreferencedNamesVisitor, UnreferencedVariablesVisitor
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source, expected", [
|
||||
("a,b", {"a", "b"}),
|
||||
("isinstance(a, int)", {"isinstance", "a", "int"}),
|
||||
("date.today()", {"date"}),
|
||||
("test()", {"test"}),
|
||||
("sheerka.test()", {"sheerka"}),
|
||||
("for i in range(10): pass", set()),
|
||||
("func(x=a, y=b)", {"func", "a", "b"}),
|
||||
|
||||
])
|
||||
def test_i_can_get_unreferenced_names_from_simple_expressions(context, source, expected):
|
||||
ast_ = ast.parse(source)
|
||||
visitor = UnreferencedNamesVisitor(context)
|
||||
visitor.visit(ast_)
|
||||
|
||||
assert visitor.names == expected
|
||||
|
||||
|
||||
def test_name_with_attribute():
|
||||
# Looks for all attributes for a given name
|
||||
ast_ = ast.parse("foo.bar.baz", "<src>", mode="exec")
|
||||
assert NamesWithAttributesVisitor().get_sequences(ast_, "foo") == [["foo", "bar", "baz"]]
|
||||
|
||||
# It parses all expressions / statements
|
||||
ast_ = ast.parse("foo.bar.baz; one.two.three; foo.bar", "<src>", mode="exec")
|
||||
assert NamesWithAttributesVisitor().get_sequences(ast_, "foo") == [["foo", "bar", "baz"], ["foo", "bar"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source, expected", [
|
||||
("a,b", {"a", "b"}),
|
||||
("isinstance(a, int)", {"a", "int"}),
|
||||
("date.today()", set()),
|
||||
("test()", set()),
|
||||
("sheerka.test()", set()),
|
||||
("for i in range(10): pass", set()),
|
||||
("func(x=a, y=b)", {"a", "b", "x", "y"}),
|
||||
])
|
||||
def test_i_can_get_unreferenced_variables_from_simple_expressions(context, source, expected):
|
||||
ast_ = ast.parse(source)
|
||||
visitor = UnreferencedVariablesVisitor(context)
|
||||
visitor.visit(ast_)
|
||||
|
||||
assert visitor.names == expected
|
||||
Reference in New Issue
Block a user