1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Classes wrapping HTTP responses from the Nominatim API.
12 import xml.etree.ElementTree as ET
14 from check_functions import Almost, OsmType, Field, check_for_attributes
17 class GenericResponse:
18 """ Common base class for all API responses.
20 def __init__(self, page, fmt, errorcode=200):
27 self.errorcode = errorcode
31 if errorcode == 200 and fmt != 'debug':
32 getattr(self, '_parse_' + fmt)()
34 def _parse_json(self):
35 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
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:
46 self.result = [self.result]
49 def _parse_geojson(self):
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)
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']
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],
73 for k, v in geojson.items():
74 if k not in ('type', 'features'):
75 check_for_attributes(new, '__' + k, 'absent')
77 self.result.append(new)
80 def _parse_geocodejson(self):
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')
90 def assert_subfield(self, idx, path, value):
93 field = self.result[idx]
95 assert isinstance(field, dict)
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 + '}')
106 assert str(field) == str(value)
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.
114 todo = range(len(self.result))
119 self.check_row(idx, 'address' in self.result[idx], "No field 'address'")
121 address = self.result[idx]['address']
122 self.check_row_field(idx, field, value, base=address)
125 def match_row(self, row, context=None):
126 """ Match the result fields against the given behave table row.
128 if 'ID' in row.headings:
129 todo = [int(row['ID'])]
131 todo = range(len(self.result))
134 for name, value in zip(row.headings, row.cells):
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 == 'osm_type':
141 self.check_row_field(i, 'osm_type', OsmType(value[0]))
142 elif name == 'centroid':
144 lon, lat = value.split(' ')
145 elif context is not None:
146 lon, lat = context.osm.grid_node(int(value))
148 raise RuntimeError("Context needed when using grid coordinates")
149 self.check_row_field(i, 'lat', Field(float(lat)), base=subdict)
150 self.check_row_field(i, 'lon', Field(float(lon)), base=subdict)
152 self.assert_subfield(i, name.split('+'), value)
154 self.check_row_field(i, name, Field(value))
157 def property_list(self, prop):
158 return [x[prop] for x in self.result]
161 def check_row(self, idx, check, msg):
162 """ Assert for the condition 'check' and print 'msg' on fail together
163 with the contents of the failing result.
166 def __init__(self, row):
170 return f"{msg}. Full row {idx}:\n" \
171 + json.dumps(self.row, indent=4, ensure_ascii=False)
173 assert check, _RowError(self.result[idx])
176 def check_row_field(self, idx, field, expected, base=None):
177 """ Check field 'field' of result 'idx' for the expected value
178 and print a meaningful error if the condition fails.
179 When 'base' is set to a dictionary, then the field is checked
180 in that base. The error message will still report the contents
184 base = self.result[idx]
186 self.check_row(idx, field in base, f"No field '{field}'")
189 self.check_row(idx, expected == value,
190 f"\nBad value for field '{field}'. Expected: {expected}, got: {value}")
194 class SearchResponse(GenericResponse):
195 """ Specialised class for search and lookup responses.
196 Transforms the xml response in a format similar to json.
199 def _parse_xml(self):
200 xml_tree = ET.fromstring(self.page)
202 self.header = dict(xml_tree.attrib)
204 for child in xml_tree:
205 assert child.tag == "place"
206 self.result.append(dict(child.attrib))
210 if sub.tag == 'extratags':
211 self.result[-1]['extratags'] = {}
213 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
214 elif sub.tag == 'namedetails':
215 self.result[-1]['namedetails'] = {}
217 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
218 elif sub.tag == 'geokml':
219 self.result[-1][sub.tag] = True
221 address[sub.tag] = sub.text
224 self.result[-1]['address'] = address
227 class ReverseResponse(GenericResponse):
228 """ Specialised class for reverse responses.
229 Transforms the xml response in a format similar to json.
232 def _parse_xml(self):
233 xml_tree = ET.fromstring(self.page)
235 self.header = dict(xml_tree.attrib)
238 for child in xml_tree:
239 if child.tag == 'result':
240 assert not self.result, "More than one result in reverse result"
241 self.result.append(dict(child.attrib))
242 elif child.tag == 'addressparts':
245 address[sub.tag] = sub.text
246 self.result[0]['address'] = address
247 elif child.tag == 'extratags':
248 self.result[0]['extratags'] = {}
250 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
251 elif child.tag == 'namedetails':
252 self.result[0]['namedetails'] = {}
254 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
255 elif child.tag == 'geokml':
256 self.result[0][child.tag] = True
258 assert child.tag == 'error', \
259 "Unknown XML tag {} on page: {}".format(child.tag, self.page)
262 class StatusResponse(GenericResponse):
263 """ Specialised class for status responses.
264 Can also parse text responses.
267 def _parse_text(self):