Skip to content

Commit

Permalink
Fix filter query existence tests in logical expressions.
Browse files Browse the repository at this point in the history
  • Loading branch information
jg-rp committed Mar 11, 2024
1 parent 2832305 commit 02e332c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
13 changes: 7 additions & 6 deletions jsonpath/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def set_children(self, children: List[FilterExpression]) -> None:
class InfixExpression(FilterExpression):
"""A pair of expressions and a comparison or logical operator."""

__slots__ = ("left", "operator", "right")
__slots__ = ("left", "operator", "right", "logical")

def __init__(
self,
Expand All @@ -329,10 +329,11 @@ def __init__(
self.left = left
self.operator = operator
self.right = right
self.logical = operator in ("&&", "||")
super().__init__()

def __str__(self) -> str:
if self.operator in ("&&", "||"):
if self.logical:
return f"({self.left} {self.operator} {self.right})"
return f"{self.left} {self.operator} {self.right}"

Expand All @@ -346,22 +347,22 @@ def __eq__(self, other: object) -> bool:

def evaluate(self, context: FilterContext) -> bool:
left = self.left.evaluate(context)
if isinstance(left, NodeList) and len(left) == 1:
if not self.logical and isinstance(left, NodeList) and len(left) == 1:
left = left[0].obj

right = self.right.evaluate(context)
if isinstance(right, NodeList) and len(right) == 1:
if not self.logical and isinstance(right, NodeList) and len(right) == 1:
right = right[0].obj

return context.env.compare(left, self.operator, right)

async def evaluate_async(self, context: FilterContext) -> bool:
left = await self.left.evaluate_async(context)
if isinstance(left, NodeList) and len(left) == 1:
if not self.logical and isinstance(left, NodeList) and len(left) == 1:
left = left[0].obj

right = await self.right.evaluate_async(context)
if isinstance(right, NodeList) and len(right) == 1:
if not self.logical and isinstance(right, NodeList) and len(right) == 1:
right = right[0].obj

return context.env.compare(left, self.operator, right)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ class Case:
data={"some": {"thing": "else", "foo": {"bar": "baz"}}},
want=["some", "thing", "foo", "bar"],
),
Case(
description="logical expr existence tests",
path="$[[email protected] && @.b]",
data=[{"a": True, "b": False}],
want=[{"a": True, "b": False}],
),
Case(
description="logical expr existence tests, alternate and",
path="$[[email protected] and @.b]",
data=[{"a": True, "b": False}],
want=[{"a": True, "b": False}],
),
]


Expand Down

0 comments on commit 02e332c

Please sign in to comment.