Skip to content

Commit

Permalink
handle multiple json path query results as ambiguous
Browse files Browse the repository at this point in the history
  • Loading branch information
KPrasch committed Jul 24, 2024
1 parent a88f526 commit bd8a5f9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
19 changes: 14 additions & 5 deletions nucypher/policy/conditions/offchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,20 +123,29 @@ def deserialize_response(self, response: requests.Response) -> Any:
return data

def query_response(self, data: Any) -> Any:

if not self.query:
return data # primitive value

try:
expression = parse(self.query)
matches = expression.find(data)
if not matches:
self.logger.info("No matches found for the JSONPath query.")
raise ConditionEvaluationFailed(
"No matches found for the JSONPath query."
)
result = matches[0].value
message = f"No matches found for the JSONPath query: {self.query}"
self.logger.info(message)
raise ConditionEvaluationFailed(message)
except (JsonPathLexerError, JsonPathParserError) as jsonpath_err:
self.logger.error(f"JSONPath error occurred: {jsonpath_err}")
raise ConditionEvaluationFailed(f"JSONPath error: {jsonpath_err}")

if len(matches) > 1:
message = (
f"Ambiguous JSONPath query - Multiple matches found for: {self.query}"
)
self.logger.info(message)
raise ConditionEvaluationFailed(message)
result = matches[0].value

return result

def verify(self, **context) -> Tuple[bool, Any]:
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/conditions/test_json_api_condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,21 @@ def test_json_api_condition_from_lingo_expression():
lingo_json = json.dumps(lingo_dict)
condition = JsonApiCondition.from_json(lingo_json)
assert isinstance(condition, JsonApiCondition)


def test_ambiguous_json_path_multiple_results(mocker):
mock_response = mocker.Mock(status_code=200)
mock_response.json.return_value = {"store": {"book": [{"price": 1}, {"price": 2}]}}

mocker.patch("requests.get", return_value=mock_response)

condition = JsonApiCondition(
endpoint="https://api.example.com/data",
query="$.store.book[*].price",
return_value_test=ReturnValueTest("==", 1),
)

with pytest.raises(ConditionEvaluationFailed) as excinfo:
condition.verify()

assert "Ambiguous JSONPath query" in str(excinfo.value)

0 comments on commit bd8a5f9

Please sign in to comment.