diff --git a/httprunner/response.py b/httprunner/response.py index 6520794a..5ab5ac33 100644 --- a/httprunner/response.py +++ b/httprunner/response.py @@ -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) diff --git a/pyproject.toml b/pyproject.toml index c7e8f540..db5bae3a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"