mirror of
https://github.com/httprunner/httprunner.git
synced 2026-05-12 11:29:48 +08:00
Merge pull request #679 from chenhuahuan/master
feat: support jsonpath to parse json response
This commit is contained in:
@@ -2,10 +2,12 @@
|
||||
|
||||
import json
|
||||
import re
|
||||
import jsonpath
|
||||
|
||||
from httprunner import exceptions, logger, utils
|
||||
from httprunner.compat import OrderedDict, basestring, is_py2
|
||||
|
||||
|
||||
text_extractor_regexp_compile = re.compile(r".*\(.*\).*")
|
||||
|
||||
|
||||
@@ -36,6 +38,35 @@ class ResponseObject(object):
|
||||
logger.log_error(err_msg)
|
||||
raise exceptions.ParamsError(err_msg)
|
||||
|
||||
def _extract_field_with_jsonpath(self, field):
|
||||
"""
|
||||
JSONPath Docs: https://goessner.net/articles/JsonPath/
|
||||
For example, response body like below:
|
||||
{
|
||||
"code": 200,
|
||||
"data": {
|
||||
"items": [{
|
||||
"id": 1,
|
||||
"name": "Bob"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "James"
|
||||
}
|
||||
]
|
||||
},
|
||||
"message": "操作成功"
|
||||
}
|
||||
|
||||
:param field: Jsonpath expression, e.g. 1)$.code 2) $..items.*.id
|
||||
:return: A list that extracted from json repsonse example. 1) [200] 2) [1, 2]
|
||||
"""
|
||||
result = jsonpath.jsonpath(self.parsed_body(), field)
|
||||
if result:
|
||||
return result
|
||||
else:
|
||||
raise exceptions.ExtractFailure("\tjsonpath {} get nothing\n".format(field))
|
||||
|
||||
def _extract_field_with_regex(self, field):
|
||||
""" extract field from response content with regex.
|
||||
requests.Response body could be json or html text.
|
||||
@@ -209,7 +240,9 @@ class ResponseObject(object):
|
||||
|
||||
msg = "extract: {}".format(field)
|
||||
|
||||
if text_extractor_regexp_compile.match(field):
|
||||
if field.startswith("$"):
|
||||
value = self._extract_field_with_jsonpath(field)
|
||||
elif text_extractor_regexp_compile.match(field):
|
||||
value = self._extract_field_with_regex(field)
|
||||
else:
|
||||
value = self._extract_field_with_delimiter(field)
|
||||
|
||||
@@ -30,6 +30,7 @@ colorama = "^0.4.1"
|
||||
colorlog = "^4.0"
|
||||
filetype = "^1.0"
|
||||
future = { version = "^0.17.1", python = "~2.7" }
|
||||
jsonpath = "^0.82"
|
||||
|
||||
[tool.poetry.dev-dependencies]
|
||||
flask = "<1.0.0"
|
||||
|
||||
Reference in New Issue
Block a user