Skip to content

Commit 36c1bad

Browse files
oskarrrrrrrmichaelmior
authored andcommitted
Fix exception type on certain syntax errors
Raise JsonPathParserError when there is a syntax error at the end of path string. Before, for example, 'foo[*' would raise an AttributeError instead. The bug was in `p_error` method, it was assumed that it always got a token but it gets a None whenever the error is at the end of path. See: https://ply.readthedocs.io/en/latest/ply.html?highlight=p_error#syntax-error-handling ("if the syntax error is due to reaching the end-of-file, p_error() is called with an argument of None")
1 parent 4c1effd commit 36c1bad

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

jsonpath_ng/parser.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ def parse_token_stream(self, token_iterator, start_symbol='jsonpath'):
8080
]
8181

8282
def p_error(self, t):
83+
if t is None:
84+
raise JsonPathParserError('Parse error near the end of string!')
8385
raise JsonPathParserError('Parse error at %s:%s near token %s (%s)'
8486
% (t.lineno, t.col, t.value, t.type))
8587

tests/test_exceptions.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,31 @@ def test_rw_exception_class():
1010
rw_parse('foo.bar.`grandparent`.baz')
1111

1212

13-
def test_rw_exception_subclass():
13+
@pytest.mark.parametrize(
14+
"path",
15+
(
16+
'foo[*.bar.baz',
17+
'foo.bar.`grandparent`.baz',
18+
# error at the end of string
19+
'foo[*',
20+
# `len` extension not available in the base parser
21+
'foo.bar.`len`',
22+
)
23+
)
24+
def test_rw_exception_subclass(path):
1425
with pytest.raises(JsonPathParserError):
15-
rw_parse('foo.bar.`grandparent`.baz')
26+
rw_parse(path)
1627

1728

18-
def test_ext_exception_subclass():
29+
@pytest.mark.parametrize(
30+
"path",
31+
(
32+
'foo[*.bar.baz',
33+
'foo.bar.`grandparent`.baz',
34+
# error at the end of string
35+
'foo[*',
36+
)
37+
)
38+
def test_ext_exception_subclass(path):
1939
with pytest.raises(JsonPathParserError):
20-
ext_parse('foo.bar.`grandparent`.baz')
40+
ext_parse(path)

0 commit comments

Comments
 (0)