Refactor geolocation module and tests

This commit is contained in:
Jaisen Mathai 2016-10-25 22:10:48 -07:00
parent df6d80934b
commit 69467e6433
3 changed files with 127 additions and 48 deletions

View File

@ -31,7 +31,7 @@ def coordinates_by_name(name):
}
# If the name is not cached then we go ahead with an API lookup
geolocation_info = lookup(name)
geolocation_info = lookup(location=name)
if(geolocation_info is not None):
if(
@ -129,7 +129,7 @@ def place_name(lat, lon):
return cached_place_name
lookup_place_name = None
geolocation_info = reverse_lookup(lat, lon)
geolocation_info = lookup(lat=lat, lon=lon)
if(geolocation_info is not None):
if('address' in geolocation_info):
address = geolocation_info['address']
@ -147,8 +147,12 @@ def place_name(lat, lon):
return lookup_place_name
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
def lookup(**kwargs):
if(
'location' not in kwargs and
'lat' not in kwargs and
'lon' not in kwargs
):
return None
key = get_key()
@ -157,13 +161,19 @@ def reverse_lookup(lat, lon):
return None
try:
params = {'format': 'json', 'key': key, 'lat': lat, 'lon': lon}
headers = {"Accept-Language": constants.accepted_language}
r = requests.get(
'http://open.mapquestapi.com/nominatim/v1/reverse.php?%s' %
urllib.parse.urlencode(params), headers=headers
)
return r.json()
params = {'format': 'json', 'key': key}
params.update(kwargs)
path = '/geocoding/v1/address'
if('lat' in kwargs and 'lon' in kwargs):
path = '/nominatim/v1/reverse.php'
url = 'http://open.mapquestapi.com%s?%s' % (
path,
urllib.parse.urlencode(params)
)
if(constants.debug is True):
print(url)
r = requests.get(url)
return parse_result(r.json())
except requests.exceptions.RequestException as e:
if(constants.debug is True):
print(e)
@ -175,30 +185,19 @@ def reverse_lookup(lat, lon):
return None
def lookup(name):
if(name is None or len(name) == 0):
def parse_result(result):
if('error' in result):
return None
key = get_key()
if(
'results' in result and
len(result['results']) > 0 and
'locations' in result['results'][0]
and len(result['results'][0]['locations']) > 0 and
'latLng' in result['results'][0]['locations'][0]
):
latLng = result['results'][0]['locations'][0]['latLng']
if(latLng['lat'] == 39.78373 and latLng['lng'] == -100.445882):
return None
if(key is None):
return None
try:
params = {'format': 'json', 'key': key, 'location': name}
if(constants.debug is True):
print('http://open.mapquestapi.com/geocoding/v1/address?%s' % urllib.parse.urlencode(params)) # noqa
r = requests.get(
'http://open.mapquestapi.com/geocoding/v1/address?%s' %
urllib.parse.urlencode(params)
)
return r.json()
except requests.exceptions.RequestException as e:
if(constants.debug is True):
print(e)
return None
except ValueError as e:
if(constants.debug is True):
print(r.text)
print(e)
return None
return result

View File

@ -144,7 +144,7 @@ def test_update_location_on_audio():
shutil.rmtree(folder_destination)
assert status == True, status
assert metadata['latitude'] != metadata_processed['latitude']
assert metadata['latitude'] != metadata_processed['latitude'], metadata_processed['latitude']
assert helper.isclose(metadata_processed['latitude'], 37.36883), metadata_processed['latitude']
assert helper.isclose(metadata_processed['longitude'], -122.03635), metadata_processed['longitude']

View File

@ -3,6 +3,7 @@ from __future__ import division
from builtins import range
from past.utils import old_div
# Project imports
import mock
import os
import random
import re
@ -77,24 +78,103 @@ def test_dms_string_longitude():
assert check_value in dms_string, '%s not in %s' % (check_value, dms_string)
assert str(dms[0]) in dms_string, '%s not in %s' % (dms[0], dms_string)
def test_reverse_lookup_with_valid_key():
res = geolocation.lookup(lat=37.368, lon=-122.03)
assert res['address']['city'] == 'Sunnyvale', res
def test_reverse_lookup_with_invalid_lat_lon():
res = geolocation.lookup(lat=999, lon=999)
assert res is None, res
@mock.patch('elodie.geolocation.__KEY__', 'invalid_key')
def test_reverse_lookup_with_invalid_key():
geolocation.__KEY__ = 'invalid_key'
res = geolocation.reverse_lookup(123.45, 123.45)
res = geolocation.lookup(lat=37.368, lon=-122.03)
assert res is None, res
@patch('elodie.geolocation.constants')
def test_reverse_lookup_with_no_key(mock_constants):
mock_constants.application_directory = 'invalid path'
res = geolocation.reverse_lookup(123.45, 123.45)
def test_lookup_with_valid_key():
res = geolocation.lookup(location='Sunnyvale, CA')
latLng = res['results'][0]['locations'][0]['latLng']
assert latLng['lat'] == 37.36883, latLng
assert latLng['lng'] == -122.03635, latLng
def test_lookup_with_invalid_location():
res = geolocation.lookup(location='foobar dne')
assert res is None, res
@mock.patch('elodie.geolocation.__KEY__', 'invalid_key')
def test_lookup_with_invalid_key():
geolocation.__KEY__ = 'invalid_key'
res = geolocation.lookup('foo')
res = geolocation.lookup(location='Sunnyvale, CA')
assert res is None, res
@patch('elodie.geolocation.constants')
def test_lookup_with_no_key(mock_constants):
mock_constants.application_directory = 'invalid path'
res = geolocation.lookup('foo')
@mock.patch('elodie.geolocation.__KEY__', '')
def test_lookup_with_no_key():
res = geolocation.lookup(location='Sunnyvale, CA')
assert res is None, res
def test_parse_result_with_error():
res = geolocation.parse_result({'error': 'foo'})
assert res is None, res
def test_parse_result_with_city():
# http://open.mapquestapi.com/nominatim/v1/reverse.php?lat=37.368&lon=-122.03&key=key_goes_here&format=json
results = {
"place_id": "60197412",
"osm_type": "way",
"osm_id": "30907961",
"lat": "37.36746105",
"lon": "-122.030237558742",
"display_name": "111, East El Camino Real, Sunnyvale, Santa Clara County, California, 94087, United States of America",
"address": {
"house_number": "111",
"road": "East El Camino Real",
"city": "Sunnyvale",
"county": "Santa Clara County",
"state": "California",
"postcode": "94087",
"country": "United States of America",
"country_code": "us"
}
}
res = geolocation.parse_result(results)
assert res == results, res
def test_parse_result_with_lat_lon():
# http://open.mapquestapi.com/geocoding/v1/address?location=abcdefghijklmnopqrstuvwxyz&key=key_goes_here&format=json
results = {
"results": [
{
"locations": [
{
"latLng": {
"lat": 123.00,
"lng": -142.99
}
}
]
}
]
}
res = geolocation.parse_result(results)
assert res == results, res
def test_parse_result_with_unknown_lat_lon():
# http://open.mapquestapi.com/geocoding/v1/address?location=abcdefghijklmnopqrstuvwxyz&key=key_goes_here&format=json
results = {
"results": [
{
"locations": [
{
"latLng": {
"lat": 39.78373,
"lng": -100.445882
}
}
]
}
]
}
res = geolocation.parse_result(results)
assert res is None, res