2 Classes wrapping HTTP responses from the Nominatim API.
4 from collections import OrderedDict
7 import xml.etree.ElementTree as ET
9 from check_functions import Almost
11 def _geojson_result_to_json_result(geojson_result):
12 result = geojson_result['properties']
13 result['geojson'] = geojson_result['geometry']
14 if 'bbox' in geojson_result:
15 # bbox is minlon, minlat, maxlon, maxlat
16 # boundingbox is minlat, maxlat, minlon, maxlon
17 result['boundingbox'] = [geojson_result['bbox'][1],
18 geojson_result['bbox'][3],
19 geojson_result['bbox'][0],
20 geojson_result['bbox'][2]]
23 class BadRowValueAssert:
24 """ Lazily formatted message for failures to find a field content.
27 def __init__(self, response, idx, field, value):
31 self.row = response.result[idx]
34 return "\nBad value for row {} field '{}'. Expected: {}, got: {}.\nFull row: {}"""\
35 .format(self.idx, self.field, self.value,
36 self.row[self.field], json.dumps(self.row, indent=4))
39 class GenericResponse:
40 """ Common base class for all API responses.
42 def __init__(self, page, fmt, errorcode=200):
49 self.errorcode = errorcode
53 if errorcode == 200 and fmt != 'debug':
54 getattr(self, '_parse_' + fmt)()
56 def _parse_json(self):
57 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
62 self.header['json_func'] = m.group(1)
63 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
64 if isinstance(self.result, OrderedDict):
65 self.result = [self.result]
67 def _parse_geojson(self):
69 if 'error' in self.result[0]:
72 self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
74 def _parse_geocodejson(self):
76 if self.result is not None:
77 self.result = [r['geocoding'] for r in self.result]
79 def assert_field(self, idx, field, value):
80 """ Check that result row `idx` has a field `field` with value `value`.
81 Float numbers are matched approximately. When the expected value
82 starts with a carat, regular expression matching is used.
84 assert field in self.result[idx], \
85 "Result row {} has no field '{}'.\nFull row: {}"\
86 .format(idx, field, json.dumps(self.result[idx], indent=4))
88 if isinstance(value, float):
89 assert Almost(value) == float(self.result[idx][field]), \
90 BadRowValueAssert(self, idx, field, value)
91 elif value.startswith("^"):
92 assert re.fullmatch(value, self.result[idx][field]), \
93 BadRowValueAssert(self, idx, field, value)
95 assert str(self.result[idx][field]) == str(value), \
96 BadRowValueAssert(self, idx, field, value)
98 def assert_address_field(self, idx, field, value):
99 """ Check that result rows`idx` has a field `field` with value `value`
100 in its address. If idx is None, then all results are checked.
103 todo = range(len(self.result))
108 assert 'address' in self.result[idx], \
109 "Result row {} has no field 'address'.\nFull row: {}"\
110 .format(idx, json.dumps(self.result[idx], indent=4))
112 address = self.result[idx]['address']
113 assert field in address, \
114 "Result row {} has no field '{}' in address.\nFull address: {}"\
115 .format(idx, field, json.dumps(address, indent=4))
117 assert address[field] == value, \
118 "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
119 .format(idx, field, value, address[field], json.dumps(address, indent=4))
121 def match_row(self, row):
122 """ Match the result fields against the given behave table row.
124 if 'ID' in row.headings:
125 todo = [int(row['ID'])]
127 todo = range(len(self.result))
130 for name, value in zip(row.headings, row.cells):
134 self.assert_field(i, 'osm_type', value[0])
135 self.assert_field(i, 'osm_id', value[1:])
136 elif name == 'centroid':
137 lon, lat = value.split(' ')
138 self.assert_field(i, 'lat', float(lat))
139 self.assert_field(i, 'lon', float(lon))
141 self.assert_field(i, name, value)
143 def property_list(self, prop):
144 return [x[prop] for x in self.result]
147 class SearchResponse(GenericResponse):
148 """ Specialised class for search and lookup responses.
149 Transforms the xml response in a format similar to json.
152 def _parse_xml(self):
153 xml_tree = ET.fromstring(self.page)
155 self.header = dict(xml_tree.attrib)
157 for child in xml_tree:
158 assert child.tag == "place"
159 self.result.append(dict(child.attrib))
163 if sub.tag == 'extratags':
164 self.result[-1]['extratags'] = {}
166 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
167 elif sub.tag == 'namedetails':
168 self.result[-1]['namedetails'] = {}
170 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
171 elif sub.tag == 'geokml':
172 self.result[-1][sub.tag] = True
174 address[sub.tag] = sub.text
177 self.result[-1]['address'] = address
180 class ReverseResponse(GenericResponse):
181 """ Specialised class for reverse responses.
182 Transforms the xml response in a format similar to json.
185 def _parse_xml(self):
186 xml_tree = ET.fromstring(self.page)
188 self.header = dict(xml_tree.attrib)
191 for child in xml_tree:
192 if child.tag == 'result':
193 assert not self.result, "More than one result in reverse result"
194 self.result.append(dict(child.attrib))
195 elif child.tag == 'addressparts':
198 address[sub.tag] = sub.text
199 self.result[0]['address'] = address
200 elif child.tag == 'extratags':
201 self.result[0]['extratags'] = {}
203 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
204 elif child.tag == 'namedetails':
205 self.result[0]['namedetails'] = {}
207 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
208 elif child.tag == 'geokml':
209 self.result[0][child.tag] = True
211 assert child.tag == 'error', \
212 "Unknown XML tag {} on page: {}".format(child.tag, self.page)
215 class StatusResponse(GenericResponse):
216 """ Specialised class for status responses.
217 Can also parse text responses.
220 def _parse_text(self):