Skip to content

Commit 484cc0d

Browse files
authored
Merge pull request #37 from dreadnode/bugfix/http-spec-json-string-return
test(http): ensure JSONPath transform outputs valid JSON
2 parents 82ab95e + 8799d2c commit 484cc0d

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

rigging/generator/http.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def parse_response_body(self, data: str) -> str:
191191
matches = [match.value for match in jsonpath_expr.find(result)]
192192
if len(matches) == 0:
193193
raise Exception(f"No matches found for JSONPath: {transform.pattern} from {result}")
194-
result = json.dumps(matches) if len(matches) > 1 else str(matches[0])
194+
result = json.dumps(matches) if len(matches) > 1 else json.dumps(matches[0])
195195

196196
elif transform.type == "regex":
197197
matches = re.findall(_to_str(transform.pattern), result)

tests/test_http_spec.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import pytest
23
from pydantic import ValidationError
34

@@ -246,3 +247,39 @@ def test_parse_response_body_list() -> None:
246247
)
247248
result = spec.parse_response_body('{"foo": [{"baz": 1}, {"baz": 2}]}')
248249
assert result == "[1, 2]"
250+
251+
252+
def test_parse_single_value_response_body() -> None:
253+
spec = HTTPSpec(
254+
request={
255+
"url": "https://api.example.com/v1/chat",
256+
"method": "POST",
257+
"headers": {"Authorization": "Bearer {{api_key}}"},
258+
"transforms": [{"type": "json", "pattern": {"model": "$model", "messages": "$messages"}}],
259+
},
260+
response={
261+
"valid_status_codes": [200, 201],
262+
"transforms": [{"type": "jsonpath", "pattern": "$.foo"}],
263+
},
264+
)
265+
result = spec.parse_response_body('{"foo": 1, "bar": 2}')
266+
assert result == "1"
267+
268+
269+
270+
def test_jsonpath_transform_into_json() -> None:
271+
spec = HTTPSpec(
272+
request={
273+
"url": "https://api.example.com/v1/chat",
274+
"method": "POST",
275+
"headers": {"Authorization": "Bearer {{api_key}}"},
276+
"transforms": [{"type": "json", "pattern": {"model": "$model", "messages": "$messages"}}],
277+
},
278+
response={
279+
"valid_status_codes": [200, 201],
280+
"transforms": [{"type": "jsonpath", "pattern": "$"}],
281+
},
282+
)
283+
result = spec.parse_response_body('{"foo": [{"baz": 1}, {"baz": 2}]}')
284+
assert result
285+
assert json.loads(result)

0 commit comments

Comments
 (0)