1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 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.
10 from collections import OrderedDict
13 import xml.etree.ElementTree as ET
15 from check_functions import Almost
17 OSM_TYPE = {'N' : 'node', 'W' : 'way', 'R' : 'relation',
18 'n' : 'node', 'w' : 'way', 'r' : 'relation',
19 'node' : 'n', 'way' : 'w', 'relation' : 'r'}
21 def _geojson_result_to_json_result(geojson_result):
22 result = geojson_result['properties']
23 result['geojson'] = geojson_result['geometry']
24 if 'bbox' in geojson_result:
25 # bbox is minlon, minlat, maxlon, maxlat
26 # boundingbox is minlat, maxlat, minlon, maxlon
27 result['boundingbox'] = [geojson_result['bbox'][1],
28 geojson_result['bbox'][3],
29 geojson_result['bbox'][0],
30 geojson_result['bbox'][2]]
33 class BadRowValueAssert:
34 """ Lazily formatted message for failures to find a field content.
37 def __init__(self, response, idx, field, value):
41 self.row = response.result[idx]
44 return "\nBad value for row {} field '{}'. Expected: {}, got: {}.\nFull row: {}"""\
45 .format(self.idx, self.field, self.value,
46 self.row[self.field], json.dumps(self.row, indent=4))
49 class GenericResponse:
50 """ Common base class for all API responses.
52 def __init__(self, page, fmt, errorcode=200):
59 self.errorcode = errorcode
63 if errorcode == 200 and fmt != 'debug':
64 getattr(self, '_parse_' + fmt)()
66 def _parse_json(self):
67 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
72 self.header['json_func'] = m.group(1)
73 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
74 if isinstance(self.result, OrderedDict):
75 if 'error' in self.result:
78 self.result = [self.result]
80 def _parse_geojson(self):
83 self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
85 def _parse_geocodejson(self):
87 if self.result is not None:
88 self.result = [r['geocoding'] for r in self.result]
90 def assert_field(self, idx, field, value):
91 """ Check that result row `idx` has a field `field` with value `value`.
92 Float numbers are matched approximately. When the expected value
93 starts with a carat, regular expression matching is used.
95 assert field in self.result[idx], \
96 "Result row {} has no field '{}'.\nFull row: {}"\
97 .format(idx, field, json.dumps(self.result[idx], indent=4))
99 if isinstance(value, float):
100 assert Almost(value) == float(self.result[idx][field]), \
101 BadRowValueAssert(self, idx, field, value)
102 elif value.startswith("^"):
103 assert re.fullmatch(value, self.result[idx][field]), \
104 BadRowValueAssert(self, idx, field, value)
106 assert str(self.result[idx][field]) == str(value), \
107 BadRowValueAssert(self, idx, field, 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 assert 'address' in self.result[idx], \
120 "Result row {} has no field 'address'.\nFull row: {}"\
121 .format(idx, json.dumps(self.result[idx], indent=4))
123 address = self.result[idx]['address']
124 assert field in address, \
125 "Result row {} has no field '{}' in address.\nFull address: {}"\
126 .format(idx, field, json.dumps(address, indent=4))
128 assert address[field] == value, \
129 "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
130 .format(idx, field, value, address[field], json.dumps(address, indent=4))
132 def match_row(self, row, context=None):
133 """ Match the result fields against the given behave table row.
135 if 'ID' in row.headings:
136 todo = [int(row['ID'])]
138 todo = range(len(self.result))
141 for name, value in zip(row.headings, row.cells):
145 assert 'osm_type' in self.result[i], \
146 "Result row {} has no field 'osm_type'.\nFull row: {}"\
147 .format(i, json.dumps(self.result[i], indent=4))
148 assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
149 BadRowValueAssert(self, i, 'osm_type', value)
150 self.assert_field(i, 'osm_id', value[1:])
151 elif name == 'osm_type':
152 assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
153 BadRowValueAssert(self, i, 'osm_type', value)
154 elif name == 'centroid':
156 lon, lat = value.split(' ')
157 elif context is not None:
158 lon, lat = context.osm.grid_node(int(value))
160 raise RuntimeError("Context needed when using grid coordinates")
161 self.assert_field(i, 'lat', float(lat))
162 self.assert_field(i, 'lon', float(lon))
164 self.assert_field(i, name, value)
166 def property_list(self, prop):
167 return [x[prop] for x in self.result]
170 class SearchResponse(GenericResponse):
171 """ Specialised class for search and lookup responses.
172 Transforms the xml response in a format similar to json.
175 def _parse_xml(self):
176 xml_tree = ET.fromstring(self.page)
178 self.header = dict(xml_tree.attrib)
180 for child in xml_tree:
181 assert child.tag == "place"
182 self.result.append(dict(child.attrib))
186 if sub.tag == 'extratags':
187 self.result[-1]['extratags'] = {}
189 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
190 elif sub.tag == 'namedetails':
191 self.result[-1]['namedetails'] = {}
193 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
194 elif sub.tag == 'geokml':
195 self.result[-1][sub.tag] = True
197 address[sub.tag] = sub.text
200 self.result[-1]['address'] = address
203 class ReverseResponse(GenericResponse):
204 """ Specialised class for reverse responses.
205 Transforms the xml response in a format similar to json.
208 def _parse_xml(self):
209 xml_tree = ET.fromstring(self.page)
211 self.header = dict(xml_tree.attrib)
214 for child in xml_tree:
215 if child.tag == 'result':
216 assert not self.result, "More than one result in reverse result"
217 self.result.append(dict(child.attrib))
218 elif child.tag == 'addressparts':
221 address[sub.tag] = sub.text
222 self.result[0]['address'] = address
223 elif child.tag == 'extratags':
224 self.result[0]['extratags'] = {}
226 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
227 elif child.tag == 'namedetails':
228 self.result[0]['namedetails'] = {}
230 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
231 elif child.tag == 'geokml':
232 self.result[0][child.tag] = True
234 assert child.tag == 'error', \
235 "Unknown XML tag {} on page: {}".format(child.tag, self.page)
238 class StatusResponse(GenericResponse):
239 """ Specialised class for status responses.
240 Can also parse text responses.
243 def _parse_text(self):