Instagram / LibCST

A concrete syntax tree parser and serializer library for Python that preserves many aspects of Python's abstract syntax tree
https://libcst.readthedocs.io/
Other
1.57k stars 192 forks source link

Add validation for If node #1177

Closed kiri11 closed 4 months ago

kiri11 commented 4 months ago

Don't allow no space no parentheses after if.

Summary

There should be a validation for If node similar to others such as While or Assert to not allow generating incorrect code. There is even a TODO left for that reason.

Let me know if there should be other validations for If.

Test Plan

Before:

With the current version of LibCST it is possible to generate the code like this with an If node followed by Name('x') without space:

ifx:
    pass

which isn't correct Syntax.

The new test fails:

======================================================================
FAIL: test_invalid_0 (libcst._nodes.tests.test_if.IfTest.test_invalid_0)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "libcst\testing\utils.py", line 88, in new_test
    return member(self, *data)
           ^^^^^^^^^^^^^^^^^^^
  File "libcst\_nodes\tests\test_if.py", line 149, in test_invalid
    self.assert_invalid(get_node, expected_re)
  File "libcst\_nodes\tests\base.py", line 95, in assert_invalid
    with self.assertRaisesRegex(cst.CSTValidationError, expected_re):
AssertionError: CSTValidationError not raised

After:

Attempting to generate incorrect code raises an exception preventing it:

libcst._nodes.base.CSTValidationError: Must have at least one space after 'if' keyword.

The new test passes:

----------------------------------------------------------------------
Ran 2076 tests in 62.315s

OK (skipped=18, expected failures=2)
codecov[bot] commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 91.26%. Comparing base (e20e757) to head (3dc3480).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #1177 +/- ## ======================================= Coverage 91.26% 91.26% ======================================= Files 261 261 Lines 26877 26883 +6 ======================================= + Hits 24529 24535 +6 Misses 2348 2348 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

zsol commented 4 months ago

✨ Thanks! ✨