Skip to content

Commit a3262da

Browse files
committed
Parser test cases and bug fixes.
1 parent 4b8f37f commit a3262da

6 files changed

Lines changed: 128 additions & 27 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ dependencies = [
4545
]
4646

4747
[tool.hatch.envs.default.scripts]
48-
cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=python_json_path --cov=tests {args}"
48+
cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=python_jsonpath --cov=tests {args}"
4949
no-cov = "cov --no-cov {args}"
5050
test = "pytest {args}"
5151

‎python_jsonpath/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
# SPDX-FileCopyrightText: 2023-present James Prior <[email protected]>
22
#
33
# SPDX-License-Identifier: MIT
4+
from .path import CompoundJSONPath
45
from .path import JSONPath
56
from .env import JSONPathEnvironment
67
from .lex import Lexer
78
from .parse import Parser
89

910
__all__ = (
11+
"CompoundJSONPath",
1012
"JSONPath",
1113
"JSONPathEnvironment",
1214
"Lexer",

‎python_jsonpath/parse.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -282,12 +282,14 @@ def parse_selector_list(self, stream: TokenStream) -> ListSelector:
282282
elif stream.current.kind == TOKEN_SLICE_START:
283283
list_items.append(self.parse_slice(stream))
284284
elif stream.current.kind == TOKEN_EOF:
285-
raise JSONPathSyntaxError("unexpected end of list")
286-
stream.next_token()
285+
raise JSONPathSyntaxError("unexpected end of selector list")
286+
287287
if stream.peek.kind != TOKEN_LIST_END:
288288
stream.expect_peek(TOKEN_COMMA)
289289
stream.next_token()
290290

291+
stream.next_token()
292+
291293
return ListSelector(env=self.env, token=tok, items=list_items)
292294

293295
def parse_filter(self, stream: TokenStream) -> Filter:

‎python_jsonpath/path.py‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,29 @@
1212
from typing import Tuple
1313
from typing import TypeVar
1414
from typing import Union
15-
from typing import TYPE_CHECKING
1615

1716
from .match import JSONPathMatch
18-
19-
if TYPE_CHECKING:
20-
from .selectors import JSONPathSelector
17+
from .selectors import JSONPathSelector
2118

2219

2320
class JSONPath:
2421
"""A compiled JSONPath ready to be applied to a JSON string or Python object."""
2522

2623
__slots__ = ("_selectors",)
2724

25+
# TODO: pass env?
26+
27+
# TODO: Store these on env
28+
root_token = "$"
29+
union_token = "|"
30+
intersection_token = "&"
31+
2832
def __init__(self, *, selectors: Iterable[JSONPathSelector]) -> None:
2933
self._selectors = list(selectors)
3034

35+
def __str__(self) -> str:
36+
return self.root_token + "".join(str(selector) for selector in self._selectors)
37+
3138
def findall(
3239
self, data: Union[str, Sequence[Any], Mapping[str, Any]]
3340
) -> List[object]:
@@ -47,7 +54,7 @@ def finditer(
4754
data = json.loads(data)
4855

4956
matches: Iterable[JSONPathMatch] = [
50-
JSONPathMatch(path="$", obj=data, root=data)
57+
JSONPathMatch(path=self.root_token, obj=data, root=data)
5158
]
5259

5360
for selector in self._selectors:
@@ -73,7 +80,7 @@ async def finditer_async(
7380
data = json.loads(data)
7481

7582
async def root_iter() -> AsyncIterable[JSONPathMatch]:
76-
yield JSONPathMatch(path="$", obj=data, root=data)
83+
yield JSONPathMatch(path=self.root_token, obj=data, root=data)
7784

7885
matches: AsyncIterable[JSONPathMatch] = root_iter()
7986

@@ -88,22 +95,32 @@ class CompoundJSONPath:
8895

8996
__slots__ = ("path", "paths")
9097

98+
root_token = "$"
99+
union_token = "|"
100+
intersection_token = "&"
101+
91102
def __init__(self, path: Union[JSONPath, CompoundJSONPath]) -> None:
92103
self.path = path
93104
self.paths: List[Tuple[(str, JSONPath)]] = []
94105

106+
def __str__(self) -> str:
107+
buf: List[str] = [str(self.path)]
108+
for op, path in self.paths:
109+
buf.append(f" {op} ")
110+
buf.append(str(path))
111+
return "".join(buf)
112+
95113
def findall(
96114
self, data: Union[str, Sequence[Any], Mapping[str, Any]]
97115
) -> List[object]:
98116
"""Return a list of objects matching this path in the given data."""
99117
objs = self.path.findall(data)
100118

101119
for op, path in self.paths:
102-
assert op in ("|", "&")
103120
_objs = path.findall(data)
104-
if op == "|":
121+
if op == self.union_token:
105122
objs.extend(_objs)
106-
elif op == "&":
123+
elif op == self.intersection_token:
107124
objs = [obj for obj in objs if obj in _objs]
108125

109126
return objs
@@ -116,11 +133,10 @@ def finditer(
116133
matches = self.path.finditer(data)
117134

118135
for op, path in self.paths:
119-
assert op in ("|", "&")
120136
_matches = path.finditer(data)
121-
if op == "|":
137+
if op == self.union_token:
122138
matches = itertools.chain(matches, _matches)
123-
elif op == "&":
139+
elif op == self.intersection_token:
124140
_objs = [match.obj for match in _matches]
125141
_matches = (match for match in matches if match.obj in _objs)
126142

@@ -133,11 +149,10 @@ async def findall_async(
133149
objs = await self.path.findall_async(data)
134150

135151
for op, path in self.paths:
136-
assert op in ("|", "&")
137152
_objs = await path.findall_async(data)
138-
if op == "|":
153+
if op == self.union_token:
139154
objs.extend(_objs)
140-
elif op == "&":
155+
elif op == self.intersection_token:
141156
objs = [obj for obj in objs if obj in _objs]
142157

143158
return objs
@@ -150,24 +165,23 @@ async def finditer_async(
150165
matches = await self.path.finditer_async(data)
151166

152167
for op, path in self.paths:
153-
assert op in ("|", "&")
154168
_matches = await path.finditer_async(data)
155-
if op == "|":
169+
if op == self.union_token:
156170
matches = _achain(matches, _matches)
157-
elif op == "&":
171+
elif op == self.intersection_token:
158172
_objs = [match.obj async for match in _matches]
159173
_matches = (match async for match in matches if match.obj in _objs)
160174

161175
return matches
162176

163177
def union(self, path: JSONPath) -> CompoundJSONPath:
164178
"""In-place union of this path and another path."""
165-
self.paths.append(("|", path))
179+
self.paths.append((self.union_token, path))
166180
return self
167181

168182
def intersection(self, path: JSONPath) -> CompoundJSONPath:
169183
"""In-place intersection of this path and another path."""
170-
self.paths.append(("&", path))
184+
self.paths.append((self.intersection_token, path))
171185
return self
172186

173187

‎python_jsonpath/selectors.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,7 @@ def __init__(
6060
self.path = str(self)
6161

6262
def __str__(self) -> str:
63-
"""Return a string representation of an object property key."""
64-
if self.env.re_key.match(self.name):
63+
if self.env.re_key.fullmatch(self.name):
6564
return f".{self.name}"
6665
return f'["{self.name}"]'
6766

@@ -183,7 +182,7 @@ def __init__(
183182
def __str__(self) -> str:
184183
stop = self.slice.stop if self.slice.stop is not None else ""
185184
start = self.slice.start if self.slice.start is not None else ""
186-
step = self.slice.step if self.slice.step is not None else ""
185+
step = self.slice.step if self.slice.step is not None else "1"
187186
return f"[{start}:{stop}:{step}]"
188187

189188
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
@@ -343,7 +342,8 @@ def __str__(self) -> str:
343342
if isinstance(item, SliceSelector):
344343
stop = item.slice.stop if item.slice.stop is not None else ""
345344
start = item.slice.start if item.slice.start is not None else ""
346-
buf.append(f"{start}:{stop}")
345+
step = item.slice.step if item.slice.step is not None else "1"
346+
buf.append(f"{start}:{stop}:{step}")
347347
elif isinstance(item, PropertySelector):
348348
buf.append(item.name)
349349
else:

‎tests/test_parse.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# pylint: disable=missing-class-docstring, missing-function-docstring
2+
import dataclasses
3+
import operator
4+
5+
import pytest
6+
7+
from python_jsonpath import JSONPathEnvironment
8+
9+
10+
@dataclasses.dataclass
11+
class Case:
12+
description: str
13+
path: str
14+
want: str
15+
16+
17+
TEST_CASES = [
18+
Case(description="empty", path="", want="$"),
19+
Case(description="just root", path="$", want="$"),
20+
Case(description="root dot", path="$.", want="$"),
21+
Case(description="implicit root dot property", path=".thing", want="$.thing"),
22+
Case(description="root dot property", path="$.thing", want="$.thing"),
23+
Case(description="root bracket property", path="$[thing]", want="$.thing"),
24+
Case(description="root double quoted property", path='$["thing"]', want="$.thing"),
25+
Case(description="root single quoted property", path="$['thing']", want="$.thing"),
26+
Case(
27+
description="root quoted property with non-ident chars",
28+
path="$['anything{!%']",
29+
want='$["anything{!%"]',
30+
),
31+
Case(description="root dot bracket property", path="$.[thing]", want="$.thing"),
32+
Case(description="root dot index", path="$.1", want="$[1]"),
33+
Case(description="root bracket index", path="$[1]", want="$[1]"),
34+
Case(description="root slice", path="$[1:-1]", want="$[1:-1:1]"),
35+
Case(description="root dot slice", path="$.[1:-1]", want="$[1:-1:1]"),
36+
Case(description="root slice with step", path="$[1:-1:2]", want="$[1:-1:2]"),
37+
Case(description="root slice with empty start", path="$[:-1]", want="$[:-1:1]"),
38+
Case(description="root slice with empty stop", path="$[1:]", want="$[1::1]"),
39+
Case(description="root dot wild", path="$.*", want="$.*"),
40+
Case(description="root bracket wild", path="$[*]", want="$.*"),
41+
Case(description="root dot bracket wild", path="$.[*]", want="$.*"),
42+
Case(description="root descend", path="$..", want="$.."),
43+
Case(description="root dot descend", path="$...", want="$.."),
44+
Case(description="root selector list", path="$[1,2]", want="$[1, 2]"),
45+
Case(description="root dot selector list", path="$.[1,2]", want="$[1, 2]"),
46+
Case(
47+
description="root selector list with slice",
48+
path="$[1,5:-1:1]",
49+
want="$[1, 5:-1:1]",
50+
),
51+
Case(
52+
description="root selector list with properties",
53+
path="$[some,thing]",
54+
want="$[some, thing]",
55+
),
56+
Case(
57+
description="root selector list with quoted properties",
58+
path="$[\"some\",'thing']",
59+
want="$[some, thing]",
60+
),
61+
Case(
62+
description="implicit root selector list with mixed selectors",
63+
path='$["some",thing, 1, 2:-2:2]',
64+
want="$[some, thing, 1, 2:-2:2]",
65+
),
66+
# Case(
67+
# description="filter self dot property",
68+
# path="[?(@.thing)]",
69+
# want="[?(@.thing)]",
70+
# ),
71+
]
72+
73+
74+
@pytest.fixture
75+
def env() -> JSONPathEnvironment:
76+
return JSONPathEnvironment()
77+
78+
79+
# pylint: disable=redefined-outer-name
80+
@pytest.mark.parametrize("case", TEST_CASES, ids=operator.attrgetter("description"))
81+
def test_default_parser(env: JSONPathEnvironment, case: Case) -> None:
82+
path = env.compile(case.path)
83+
assert str(path) == case.want

0 commit comments

Comments
 (0)