Debian Codegraph @

gabbi/handlers/jsonhandler.py

raw
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
12 # under the License.
13 """JSON-related content handling."""
14
15 import json
16
17 from gabbi.exception import GabbiDataLoadError
18 from gabbi.handlers import base
19 import jsonpath_ng.ext as json_parser
20
21
22 class JSONHandler(base.ContentHandler):
23 """A ContentHandler for JSON
24
25 * Structured test ``data`` is turned into JSON when request
26 content-type is JSON.
27 * Response bodies that are JSON strings are made into Python
28 data on the test ``response_data`` attribute when the response
29 content-type is JSON.
30 * A ``response_json_paths`` response handler is added.
31 * JSONPaths in $RESPONSE substitutions are supported.
32 """
33
34 test_key_suffix = 'json_paths'
35 test_key_value = {}
36
37 @staticmethod
38 def accepts(content_type):
39 content_type = content_type.lower()
40 parameters = ''
41 if ';' in content_type:
42 content_type, parameters = content_type.split(';', 1)
43 content_type = content_type.strip()
44 return (content_type.endswith('+json') or
45 content_type == 'application/json'
46 and 'stream=' not in parameters)
47
48 @classmethod
49 def replacer(cls, response_data, match):
50 return cls.extract_json_path_value(response_data, match)
51
52 @staticmethod
53 def dumps(data, pretty=False, test=None):
54 if pretty:
55 return json.dumps(data, indent=2, separators=(',', ': '))
56 else:
57 return json.dumps(data)
58
59 @staticmethod
60 def loads(data):
61 try:
62 return json.loads(data)
63 except ValueError as exc:
64 raise GabbiDataLoadError('unable to parse data') from exc
65
66 @staticmethod
67 def load_data_file(test, file_path):
68 info = test.load_data_file(file_path)
69 info = str(info, 'UTF-8')
70 return json.loads(info)
71
72 @staticmethod
73 def extract_json_path_value(data, path):
74 """Extract the value at JSON Path path from the data.
75
76 The input data is a Python datastructure, not a JSON string.
77 """
78 path_expr = json_parser.parse(path)
79 matches = [match.value for match in path_expr.find(data)]
80 if matches:
81 if len(matches) > 1:
82 return matches
83 else:
84 return matches[0]
85 else:
86 raise ValueError(
87 "JSONPath '%s' failed to match on data: '%s'" % (path, data))
88
89 def action(self, test, path, value=None):
90 """Test json_paths against json data."""
91 # Do template expansion in the left hand side.
92 lhs_path = test.replace_template(path)
93 rhs_path = rhs_match = None
94 try:
95 lhs_match = self.extract_json_path_value(
96 test.response_data, lhs_path)
97 except AttributeError:
98 raise AssertionError('unable to extract JSON from test results')
99 except ValueError:
100 raise AssertionError('left hand side json path %s cannot match '
101 '%s' % (path, test.response_data))
102
103 # read data from disk if the value starts with '<@'
104 if isinstance(value, str) and value.startswith('<@'):
105 # Do template expansion in the rhs if rhs_path is provided.
106 if ':' in value:
107 value, rhs_path = value.split(':$', 1)
108 rhs_path = test.replace_template('$' + rhs_path)
109 value = self.load_data_file(test, value.replace('<@', '', 1))
110 if rhs_path:
111 try:
112 rhs_match = self.extract_json_path_value(value, rhs_path)
113 except AttributeError:
114 raise AssertionError('unable to extract JSON from data on '
115 'disk')
116 except ValueError:
117 raise AssertionError('right hand side json path %s cannot '
118 'match %s' % (rhs_path, value))
119
120 # If expected is a string, check to see if it is a regex.
121 is_regex = isinstance(value, str) and self.is_regex(value)
122 expected = (rhs_match or
123 test.replace_template(value, escape_regex=is_regex))
124 match = lhs_match
125 if is_regex and not rhs_match:
126 expected = expected[1:-1]
127 # match may be a number so stringify
128 match = str(match)
129 test.assertRegex(
130 match, expected,
131 'Expect jsonpath %s to match /%s/, got %s' %
132 (path, expected, match))
133 else:
134 test.assertEqual(expected, match,
135 'Unable to match %s as %s, got %s' %
136 (path, expected, match))