Skip to content

Commit

Permalink
Add some literal tests
Browse files Browse the repository at this point in the history
Also start mapping `BinaryOp`.
  • Loading branch information
knutwannheden committed Aug 20, 2024
1 parent 2d93cc3 commit 83e3bfc
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
29 changes: 29 additions & 0 deletions rewrite/rewrite-python/src/rewrite/python/__parser_visitor__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,35 @@ def visit_Assert(self, node):
self.__pad_left(self.__source_before(','), self.__convert(node.msg)) if node.msg else None,
)

def visit_BoolOp(self, node):
# Get the operator as a string (can be 'or', 'and', etc.)
if isinstance(node.op, ast.Or):
op = j.Binary.Type.Or
op_str = 'or'
elif isinstance(node.op, ast.And):
op = j.Binary.Type.And
op_str = 'and'
else:
raise ValueError(f"Unsupported Boolean operation: {node.op}")

binaries = []
prefix = self.__whitespace()
left = self.__convert(node.values[0])
for i, right_expr in enumerate(node.values[1:], 1):
left = j.Binary(
random_id(),
prefix,
Markers.EMPTY,
left,
self.__pad_left(self.__source_before(op_str), op),
self.__convert(right_expr),
self.__map_type(node)
)
binaries.append(left)
prefix = self.__whitespace() if i < len(node.values) - 1 else Space.EMPTY

return binaries[-1]

def visit_Constant(self, node):
# noinspection PyTypeChecker
type_: JavaType.Primitive = self.__map_type(node)
Expand Down
41 changes: 41 additions & 0 deletions rewrite/rewrite-python/tests/rewrite/python/tree/literal_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import ast
import textwrap

from rewrite.python.__parser_visitor__ import ParserVisitor


def test_none(rewrite_remote):
# language=python
source = textwrap.dedent("""\
assert None
""")

tree = ast.parse(source)
visitor = ParserVisitor(source)
cu = visitor.visit(tree)
assert cu.print_all() == source


def test_boolean(rewrite_remote):
# language=python
source = textwrap.dedent("""\
assert True or False
""")

tree = ast.parse(source)
visitor = ParserVisitor(source)
cu = visitor.visit(tree)
assert cu.print_all() == source


# noinspection PyUnreachableCode
def test_number(rewrite_remote):
# language=python
source = textwrap.dedent("""\
assert 0 or 0.0
""")

tree = ast.parse(source)
visitor = ParserVisitor(source)
cu = visitor.visit(tree)
assert cu.print_all() == source

0 comments on commit 83e3bfc

Please sign in to comment.