From 4c632a78bc4dec916ac358d22c128fdfbb6f9165 Mon Sep 17 00:00:00 2001 From: James Prior Date: Tue, 18 Mar 2025 13:10:57 +0000 Subject: [PATCH] Improve error messages related to unbalanced brackets --- jsonpath_rfc9535/lex.py | 10 +++++----- pyproject.toml | 1 + tests/test_errors.py | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/jsonpath_rfc9535/lex.py b/jsonpath_rfc9535/lex.py index 65d8f2d..5aa2417 100644 --- a/jsonpath_rfc9535/lex.py +++ b/jsonpath_rfc9535/lex.py @@ -509,9 +509,12 @@ def tokenize(query: str) -> List[Token]: lexer, tokens = lex(query) lexer.run() - # Check for remaining opening brackets that have not been closes. + if tokens and tokens[-1].type_ == TokenType.ERROR: + raise JSONPathSyntaxError(tokens[-1].message, token=tokens[-1]) + + # Check for remaining opening brackets that have not been closed. if lexer.bracket_stack: - ch, index = lexer.bracket_stack[0] + ch, index = lexer.bracket_stack[-1] msg = f"unbalanced {'brackets' if ch == '[' else 'parentheses'}" raise JSONPathSyntaxError( msg, @@ -524,7 +527,4 @@ def tokenize(query: str) -> List[Token]: ), ) - if tokens and tokens[-1].type_ == TokenType.ERROR: - raise JSONPathSyntaxError(tokens[-1].message, token=tokens[-1]) - return tokens diff --git a/pyproject.toml b/pyproject.toml index 37ed166..e616d40 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -121,6 +121,7 @@ exclude = [ "dist", "node_modules", "venv", + "tests/nts", ] # Same as Black. diff --git a/tests/test_errors.py b/tests/test_errors.py index 3cfb8df..7406e45 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -18,14 +18,14 @@ def env() -> JSONPathEnvironment: def test_unclosed_selection_list(env: JSONPathEnvironment) -> None: with pytest.raises( - JSONPathSyntaxError, match=r"unbalanced brackets, line 1, column 1" + JSONPathSyntaxError, match=r"unbalanced brackets, line 1, column 5" ): env.compile("$[1,2") def test_unclosed_selection_list_inside_filter(env: JSONPathEnvironment) -> None: with pytest.raises( - JSONPathSyntaxError, match=r"unbalanced brackets, line 1, column 1" + JSONPathSyntaxError, match=r"unclosed bracketed selection, line 1, column 10" ): env.compile("$[?@.a < 1")