fix: extract with jsonpath

This commit is contained in:
debugtalk
2020-02-21 20:44:43 +08:00
parent c7684101ff
commit 25b2fcd0f5

View File

@@ -36,9 +36,20 @@ class ResponseObject(object):
logger.log_error(err_msg) logger.log_error(err_msg)
raise exceptions.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
def _extract_field_with_jsonpath(self, field): def _extract_field_with_jsonpath(self, field: str) -> list:
""" """ extract field from response content with jsonpath expression.
JSONPath Docs: https://goessner.net/articles/JsonPath/ JSONPath Docs: https://goessner.net/articles/JsonPath/
Args:
field: jsonpath expression, e.g. $.code, $..items.*.id
Returns:
A list that extracted from json response example. 1) [200] 2) [1, 2]
Raises:
exceptions.ExtractFailure: If no content matched with jsonpath expression.
Examples:
For example, response body like below: For example, response body like below:
{ {
"code": 200, "code": 200,
@@ -56,14 +67,24 @@ class ResponseObject(object):
"message": "success" "message": "success"
} }
:param field: Jsonpath expression, e.g. 1)$.code 2) $..items.*.id >>> _extract_field_with_regex("$.code")
:return: A list that extracted from json repsonse example. 1) [200] 2) [1, 2] [200]
>>> _extract_field_with_regex("$..items.*.id")
[1, 2]
""" """
result = jsonpath.jsonpath(self.parsed_body(), field) try:
if result: json_body = self.json
assert json_body
result = jsonpath.jsonpath(json_body, field)
assert result
return result return result
else: except (AssertionError, exceptions.JSONDecodeError):
raise exceptions.ExtractFailure("\tjsonpath {} get nothing\n".format(field)) err_msg = u"Failed to extract data with jsonpath! => {}\n".format(field)
err_msg += u"response body: {}\n".format(self.text)
logger.log_error(err_msg)
raise exceptions.ExtractFailure(err_msg)
def _extract_field_with_regex(self, field): def _extract_field_with_regex(self, field):
""" extract field from response content with regex. """ extract field from response content with regex.