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 self.result = [self.result]
77 def _parse_geojson(self):
79 if 'error' in self.result[0]:
82 self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
84 def _parse_geocodejson(self):
86 if self.result is not None:
87 self.result = [r['geocoding'] for r in self.result]
89 def assert_field(self, idx, field, value):
90 """ Check that result row `idx` has a field `field` with value `value`.
91 Float numbers are matched approximately. When the expected value
92 starts with a carat, regular expression matching is used.
94 assert field in self.result[idx], \
95 "Result row {} has no field '{}'.\nFull row: {}"\
96 .format(idx, field, json.dumps(self.result[idx], indent=4))
98 if isinstance(value, float):
99 assert Almost(value) == float(self.result[idx][field]), \
100 BadRowValueAssert(self, idx, field, value)
101 elif value.startswith("^"):
102 assert re.fullmatch(value, self.result[idx][field]), \
103 BadRowValueAssert(self, idx, field, value)
105 assert str(self.result[idx][field]) == str(value), \
106 BadRowValueAssert(self, idx, field, value)
108 def assert_address_field(self, idx, field, value):
109 """ Check that result rows`idx` has a field `field` with value `value`
110 in its address. If idx is None, then all results are checked.
113 todo = range(len(self.result))
118 assert 'address' in self.result[idx], \
119 "Result row {} has no field 'address'.\nFull row: {}"\
120 .format(idx, json.dumps(self.result[idx], indent=4))
122 address = self.result[idx]['address']
123 assert field in address, \
124 "Result row {} has no field '{}' in address.\nFull address: {}"\
125 .format(idx, field, json.dumps(address, indent=4))
127 assert address[field] == value, \
128 "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
129 .format(idx, field, value, address[field], json.dumps(address, indent=4))
131 def match_row(self, row):
132 """ Match the result fields against the given behave table row.
134 if 'ID' in row.headings:
135 todo = [int(row['ID'])]
137 todo = range(len(self.result))
140 for name, value in zip(row.headings, row.cells):
144 assert 'osm_type' in self.result[i], \
145 "Result row {} has no field 'osm_type'.\nFull row: {}"\
146 .format(i, json.dumps(self.result[i], indent=4))
147 assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
148 BadRowValueAssert(self, i, 'osm_type', value)
149 self.assert_field(i, 'osm_id', value[1:])
150 elif name == 'osm_type':
151 assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
152 BadRowValueAssert(self, i, 'osm_type', value)
153 elif name == 'centroid':
154 lon, lat = value.split(' ')
155 self.assert_field(i, 'lat', float(lat))
156 self.assert_field(i, 'lon', float(lon))
158 self.assert_field(i, name, value)
160 def property_list(self, prop):
161 return [x[prop] for x in self.result]
164 class SearchResponse(GenericResponse):
165 """ Specialised class for search and lookup responses.
166 Transforms the xml response in a format similar to json.
169 def _parse_xml(self):
170 xml_tree = ET.fromstring(self.page)
172 self.header = dict(xml_tree.attrib)
174 for child in xml_tree:
175 assert child.tag == "place"
176 self.result.append(dict(child.attrib))
180 if sub.tag == 'extratags':
181 self.result[-1]['extratags'] = {}
183 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
184 elif sub.tag == 'namedetails':
185 self.result[-1]['namedetails'] = {}
187 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
188 elif sub.tag == 'geokml':
189 self.result[-1][sub.tag] = True
191 address[sub.tag] = sub.text
194 self.result[-1]['address'] = address
197 class ReverseResponse(GenericResponse):
198 """ Specialised class for reverse responses.
199 Transforms the xml response in a format similar to json.
202 def _parse_xml(self):
203 xml_tree = ET.fromstring(self.page)
205 self.header = dict(xml_tree.attrib)
208 for child in xml_tree:
209 if child.tag == 'result':
210 assert not self.result, "More than one result in reverse result"
211 self.result.append(dict(child.attrib))
212 elif child.tag == 'addressparts':
215 address[sub.tag] = sub.text
216 self.result[0]['address'] = address
217 elif child.tag == 'extratags':
218 self.result[0]['extratags'] = {}
220 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
221 elif child.tag == 'namedetails':
222 self.result[0]['namedetails'] = {}
224 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
225 elif child.tag == 'geokml':
226 self.result[0][child.tag] = True
228 assert child.tag == 'error', \
229 "Unknown XML tag {} on page: {}".format(child.tag, self.page)
232 class StatusResponse(GenericResponse):
233 """ Specialised class for status responses.
234 Can also parse text responses.
237 def _parse_text(self):