]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/http_responses.py
a3493b975790441881f8b76115d7567edd9535dd
[nominatim.git] / test / bdd / steps / http_responses.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Classes wrapping HTTP responses from the Nominatim API.
9 """
10 import re
11 import json
12 import xml.etree.ElementTree as ET
13
14 from check_functions import Almost, OsmType, Field, check_for_attributes
15
16
17 class GenericResponse:
18     """ Common base class for all API responses.
19     """
20     def __init__(self, page, fmt, errorcode=200):
21         fmt = fmt.strip()
22         if fmt == 'jsonv2':
23             fmt = 'json'
24
25         self.page = page
26         self.format = fmt
27         self.errorcode = errorcode
28         self.result = []
29         self.header = dict()
30
31         if errorcode == 200 and fmt != 'debug':
32             getattr(self, '_parse_' + fmt)()
33
34     def _parse_json(self):
35         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
36         if m is None:
37             code = self.page
38         else:
39             code = m.group(2)
40             self.header['json_func'] = m.group(1)
41         self.result = json.JSONDecoder().decode(code)
42         if isinstance(self.result, dict):
43             if 'error' in self.result:
44                 self.result = []
45             else:
46                 self.result = [self.result]
47
48
49     def _parse_geojson(self):
50         self._parse_json()
51         if self.result:
52             geojson = self.result[0]
53             # check for valid geojson
54             check_for_attributes(geojson, 'type,features')
55             assert geojson['type'] == 'FeatureCollection'
56             assert isinstance(geojson['features'], list)
57
58             self.result = []
59             for result in geojson['features']:
60                 check_for_attributes(result, 'type,properties,geometry')
61                 assert result['type'] == 'Feature'
62                 new = result['properties']
63                 check_for_attributes(new, 'geojson', 'absent')
64                 new['geojson'] = result['geometry']
65                 if 'bbox' in result:
66                     check_for_attributes(new, 'boundingbox', 'absent')
67                     # bbox is  minlon, minlat, maxlon, maxlat
68                     # boundingbox is minlat, maxlat, minlon, maxlon
69                     new['boundingbox'] = [result['bbox'][1],
70                                           result['bbox'][3],
71                                           result['bbox'][0],
72                                           result['bbox'][2]]
73                 for k, v in geojson.items():
74                     if k not in ('type', 'features'):
75                         check_for_attributes(new, '__' + k, 'absent')
76                         new['__' + k] = v
77                 self.result.append(new)
78
79
80     def _parse_geocodejson(self):
81         self._parse_geojson()
82         if self.result:
83             for r in self.result:
84                 assert set(r.keys()) == {'geocoding', 'geojson', '__geocoding'}, \
85                        f"Unexpected keys in result: {r.keys()}"
86                 check_for_attributes(r['geocoding'], 'geojson', 'absent')
87                 r |= r.pop('geocoding')
88
89
90     def assert_subfield(self, idx, path, value):
91         assert path
92
93         field = self.result[idx]
94         for p in path:
95             assert isinstance(field, dict)
96             assert p in field
97             field = field[p]
98
99         if isinstance(value, float):
100             assert Almost(value) == float(field)
101         elif value.startswith("^"):
102             assert re.fullmatch(value, field)
103         elif isinstance(field, dict):
104             assert field, eval('{' + value + '}')
105         else:
106             assert str(field) == str(value)
107
108
109     def assert_address_field(self, idx, field, value):
110         """ Check that result rows`idx` has a field `field` with value `value`
111             in its address. If idx is None, then all results are checked.
112         """
113         if idx is None:
114             todo = range(len(self.result))
115         else:
116             todo = [int(idx)]
117
118         for idx in todo:
119             self.check_row(idx, 'address' in self.result[idx], "No field 'address'")
120
121             address = self.result[idx]['address']
122             self.check_row_field(idx, field, value, base=address)
123
124
125     def match_row(self, row, context=None):
126         """ Match the result fields against the given behave table row.
127         """
128         if 'ID' in row.headings:
129             todo = [int(row['ID'])]
130         else:
131             todo = range(len(self.result))
132
133         for i in todo:
134             for name, value in zip(row.headings, row.cells):
135                 if name == 'ID':
136                     pass
137                 elif name == 'osm':
138                     self.check_row_field(i, 'osm_type', OsmType(value[0]))
139                     self.check_row_field(i, 'osm_id', Field(value[1:]))
140                 elif name == 'centroid':
141                     if ' ' in value:
142                         lon, lat = value.split(' ')
143                     elif context is not None:
144                         lon, lat = context.osm.grid_node(int(value))
145                     else:
146                         raise RuntimeError("Context needed when using grid coordinates")
147                     self.check_row_field(i, 'lat', Field(float(lat)))
148                     self.check_row_field(i, 'lon', Field(float(lon)))
149                 elif '+' in name:
150                     self.assert_subfield(i, name.split('+'), value)
151                 else:
152                     self.check_row_field(i, name, Field(value))
153
154
155     def property_list(self, prop):
156         return [x[prop] for x in self.result]
157
158
159     def check_row(self, idx, check, msg):
160         """ Assert for the condition 'check' and print 'msg' on fail together
161             with the contents of the failing result.
162         """
163         class _RowError:
164             def __init__(self, row):
165                 self.row = row
166
167             def __str__(self):
168                 return f"{msg}. Full row {idx}:\n" \
169                        + json.dumps(self.row, indent=4, ensure_ascii=False)
170
171         assert check, _RowError(self.result[idx])
172
173
174     def check_row_field(self, idx, field, expected, base=None):
175         """ Check field 'field' of result 'idx' for the expected value
176             and print a meaningful error if the condition fails.
177             When 'base' is set to a dictionary, then the field is checked
178             in that base. The error message will still report the contents
179             of the full result.
180         """
181         if base is None:
182             base = self.result[idx]
183
184         self.check_row(idx, field in base, f"No field '{field}'")
185         value = base[field]
186
187         self.check_row(idx, expected == value,
188                        f"\nBad value for field '{field}'. Expected: {expected}, got: {value}")
189
190
191
192 class SearchResponse(GenericResponse):
193     """ Specialised class for search and lookup responses.
194         Transforms the xml response in a format similar to json.
195     """
196
197     def _parse_xml(self):
198         xml_tree = ET.fromstring(self.page)
199
200         self.header = dict(xml_tree.attrib)
201
202         for child in xml_tree:
203             assert child.tag == "place"
204             self.result.append(dict(child.attrib))
205
206             address = {}
207             for sub in child:
208                 if sub.tag == 'extratags':
209                     self.result[-1]['extratags'] = {}
210                     for tag in sub:
211                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
212                 elif sub.tag == 'namedetails':
213                     self.result[-1]['namedetails'] = {}
214                     for tag in sub:
215                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
216                 elif sub.tag == 'geokml':
217                     self.result[-1][sub.tag] = True
218                 else:
219                     address[sub.tag] = sub.text
220
221             if address:
222                 self.result[-1]['address'] = address
223
224
225 class ReverseResponse(GenericResponse):
226     """ Specialised class for reverse responses.
227         Transforms the xml response in a format similar to json.
228     """
229
230     def _parse_xml(self):
231         xml_tree = ET.fromstring(self.page)
232
233         self.header = dict(xml_tree.attrib)
234         self.result = []
235
236         for child in xml_tree:
237             if child.tag == 'result':
238                 assert not self.result, "More than one result in reverse result"
239                 self.result.append(dict(child.attrib))
240             elif child.tag == 'addressparts':
241                 address = {}
242                 for sub in child:
243                     address[sub.tag] = sub.text
244                 self.result[0]['address'] = address
245             elif child.tag == 'extratags':
246                 self.result[0]['extratags'] = {}
247                 for tag in child:
248                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
249             elif child.tag == 'namedetails':
250                 self.result[0]['namedetails'] = {}
251                 for tag in child:
252                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
253             elif child.tag == 'geokml':
254                 self.result[0][child.tag] = True
255             else:
256                 assert child.tag == 'error', \
257                        "Unknown XML tag {} on page: {}".format(child.tag, self.page)
258
259
260 class StatusResponse(GenericResponse):
261     """ Specialised class for status responses.
262         Can also parse text responses.
263     """
264
265     def _parse_text(self):
266         pass