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 OSM_TYPE = {'N' : 'node', 'W' : 'way', 'R' : 'relation',
 
  12             'n' : 'node', 'w' : 'way', 'r' : 'relation',
 
  13             'node' : 'n', 'way' : 'w', 'relation' : 'r'}
 
  15 def _geojson_result_to_json_result(geojson_result):
 
  16     result = geojson_result['properties']
 
  17     result['geojson'] = geojson_result['geometry']
 
  18     if 'bbox' in geojson_result:
 
  19         # bbox is  minlon, minlat, maxlon, maxlat
 
  20         # boundingbox is minlat, maxlat, minlon, maxlon
 
  21         result['boundingbox'] = [geojson_result['bbox'][1],
 
  22                                  geojson_result['bbox'][3],
 
  23                                  geojson_result['bbox'][0],
 
  24                                  geojson_result['bbox'][2]]
 
  27 class BadRowValueAssert:
 
  28     """ Lazily formatted message for failures to find a field content.
 
  31     def __init__(self, response, idx, field, value):
 
  35         self.row = response.result[idx]
 
  38         return "\nBad value for row {} field '{}'. Expected: {}, got: {}.\nFull row: {}"""\
 
  39                    .format(self.idx, self.field, self.value,
 
  40                            self.row[self.field], json.dumps(self.row, indent=4))
 
  43 class GenericResponse:
 
  44     """ Common base class for all API responses.
 
  46     def __init__(self, page, fmt, errorcode=200):
 
  53         self.errorcode = errorcode
 
  57         if errorcode == 200 and fmt != 'debug':
 
  58             getattr(self, '_parse_' + fmt)()
 
  60     def _parse_json(self):
 
  61         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
  66             self.header['json_func'] = m.group(1)
 
  67         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
 
  68         if isinstance(self.result, OrderedDict):
 
  69             self.result = [self.result]
 
  71     def _parse_geojson(self):
 
  73         if 'error' in self.result[0]:
 
  76             self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
 
  78     def _parse_geocodejson(self):
 
  80         if self.result is not None:
 
  81             self.result = [r['geocoding'] for r in self.result]
 
  83     def assert_field(self, idx, field, value):
 
  84         """ Check that result row `idx` has a field `field` with value `value`.
 
  85             Float numbers are matched approximately. When the expected value
 
  86             starts with a carat, regular expression matching is used.
 
  88         assert field in self.result[idx], \
 
  89                "Result row {} has no field '{}'.\nFull row: {}"\
 
  90                    .format(idx, field, json.dumps(self.result[idx], indent=4))
 
  92         if isinstance(value, float):
 
  93             assert Almost(value) == float(self.result[idx][field]), \
 
  94                    BadRowValueAssert(self, idx, field, value)
 
  95         elif value.startswith("^"):
 
  96             assert re.fullmatch(value, self.result[idx][field]), \
 
  97                    BadRowValueAssert(self, idx, field, value)
 
  99             assert str(self.result[idx][field]) == str(value), \
 
 100                    BadRowValueAssert(self, idx, field, value)
 
 102     def assert_address_field(self, idx, field, value):
 
 103         """ Check that result rows`idx` has a field `field` with value `value`
 
 104             in its address. If idx is None, then all results are checked.
 
 107             todo = range(len(self.result))
 
 112             assert 'address' in self.result[idx], \
 
 113                    "Result row {} has no field 'address'.\nFull row: {}"\
 
 114                        .format(idx, json.dumps(self.result[idx], indent=4))
 
 116             address = self.result[idx]['address']
 
 117             assert field in address, \
 
 118                    "Result row {} has no field '{}' in address.\nFull address: {}"\
 
 119                        .format(idx, field, json.dumps(address, indent=4))
 
 121             assert address[field] == value, \
 
 122                    "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
 
 123                        .format(idx, field, value, address[field], json.dumps(address, indent=4))
 
 125     def match_row(self, row):
 
 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                     assert 'osm_type' in self.result[i], \
 
 139                            "Result row {} has no field 'osm_type'.\nFull row: {}"\
 
 140                                .format(i, json.dumps(self.result[i], indent=4))
 
 141                     assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
 
 142                            BadRowValueAssert(self, i, 'osm_type', value)
 
 143                     self.assert_field(i, 'osm_id', value[1:])
 
 144                 elif name == 'osm_type':
 
 145                     assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
 
 146                            BadRowValueAssert(self, i, 'osm_type', value)
 
 147                 elif name == 'centroid':
 
 148                     lon, lat = value.split(' ')
 
 149                     self.assert_field(i, 'lat', float(lat))
 
 150                     self.assert_field(i, 'lon', float(lon))
 
 152                     self.assert_field(i, name, value)
 
 154     def property_list(self, prop):
 
 155         return [x[prop] for x in self.result]
 
 158 class SearchResponse(GenericResponse):
 
 159     """ Specialised class for search and lookup responses.
 
 160         Transforms the xml response in a format similar to json.
 
 163     def _parse_xml(self):
 
 164         xml_tree = ET.fromstring(self.page)
 
 166         self.header = dict(xml_tree.attrib)
 
 168         for child in xml_tree:
 
 169             assert child.tag == "place"
 
 170             self.result.append(dict(child.attrib))
 
 174                 if sub.tag == 'extratags':
 
 175                     self.result[-1]['extratags'] = {}
 
 177                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 178                 elif sub.tag == 'namedetails':
 
 179                     self.result[-1]['namedetails'] = {}
 
 181                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
 
 182                 elif sub.tag == 'geokml':
 
 183                     self.result[-1][sub.tag] = True
 
 185                     address[sub.tag] = sub.text
 
 188                 self.result[-1]['address'] = address
 
 191 class ReverseResponse(GenericResponse):
 
 192     """ Specialised class for reverse responses.
 
 193         Transforms the xml response in a format similar to json.
 
 196     def _parse_xml(self):
 
 197         xml_tree = ET.fromstring(self.page)
 
 199         self.header = dict(xml_tree.attrib)
 
 202         for child in xml_tree:
 
 203             if child.tag == 'result':
 
 204                 assert not self.result, "More than one result in reverse result"
 
 205                 self.result.append(dict(child.attrib))
 
 206             elif child.tag == 'addressparts':
 
 209                     address[sub.tag] = sub.text
 
 210                 self.result[0]['address'] = address
 
 211             elif child.tag == 'extratags':
 
 212                 self.result[0]['extratags'] = {}
 
 214                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 215             elif child.tag == 'namedetails':
 
 216                 self.result[0]['namedetails'] = {}
 
 218                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
 
 219             elif child.tag == 'geokml':
 
 220                 self.result[0][child.tag] = True
 
 222                 assert child.tag == 'error', \
 
 223                        "Unknown XML tag {} on page: {}".format(child.tag, self.page)
 
 226 class StatusResponse(GenericResponse):
 
 227     """ Specialised class for status responses.
 
 228         Can also parse text responses.
 
 231     def _parse_text(self):