Skip to content

Commit

Permalink
Add validation for If node (#1177)
Browse files Browse the repository at this point in the history
* Add validation for If node

Don't allow no space no parentheses.
  • Loading branch information
kiri11 authored Jul 30, 2024
1 parent e20e757 commit b0d145d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
7 changes: 6 additions & 1 deletion libcst/_nodes/statement.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,12 @@ class If(BaseCompoundStatement):
#: The whitespace appearing after the test expression but before the colon.
whitespace_after_test: SimpleWhitespace = SimpleWhitespace.field("")

# TODO: _validate
def _validate(self) -> None:
if (
self.whitespace_before_test.empty
and not self.test._safe_to_use_with_word_operator(ExpressionPosition.RIGHT)
):
raise CSTValidationError("Must have at least one space after 'if' keyword.")

def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "If":
return If(
Expand Down
20 changes: 19 additions & 1 deletion libcst/_nodes/tests/test_if.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from typing import Any
from typing import Any, Callable

import libcst as cst
from libcst import parse_statement
Expand Down Expand Up @@ -129,3 +129,21 @@ class IfTest(CSTNodeTest):
)
def test_valid(self, **kwargs: Any) -> None:
self.validate_node(**kwargs)

@data_provider(
(
# Validate whitespace handling
(
lambda: cst.If(
cst.Name("conditional"),
cst.SimpleStatementSuite((cst.Pass(),)),
whitespace_before_test=cst.SimpleWhitespace(""),
),
"Must have at least one space after 'if' keyword.",
),
)
)
def test_invalid(
self, get_node: Callable[[], cst.CSTNode], expected_re: str
) -> None:
self.assert_invalid(get_node, expected_re)

0 comments on commit b0d145d

Please sign in to comment.