Skip to content

Commit

Permalink
formatting for linters
Browse files Browse the repository at this point in the history
  • Loading branch information
lmarion-source committed Jun 2, 2020
1 parent f1eafde commit d6eab49
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 75 deletions.
26 changes: 12 additions & 14 deletions base_geoengine/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ def convert_to_column(self, value, record):
shape_to_write = self.entry_to_shape(value, same_type=True)
if shape_to_write.is_empty:
return None
else:
return shape_to_write.wkt
return shape_to_write.wkt

def convert_to_cache(self, value, record, validate=True):
val = value
Expand Down Expand Up @@ -117,7 +116,6 @@ def create_geo_column(self, cr, col_name, table, model):
raise
finally:
cr.commit()

return True

def entry_to_shape(self, value, same_type=False):
Expand Down Expand Up @@ -261,28 +259,28 @@ def from_latlon(cls, cr, latitude, longitude):
def to_latlon(cls, cr, geopoint):
""" Convert a UTM coordinate point to (latitude, longitude):
"""
# Line to execute to retrieve longitude, latitude from UTM in postgres command line:
# Line to execute to retrieve longitude, latitude from UTM
# in postgres command line:
# SELECT ST_X(geom), ST_Y(geom) FROM (SELECT ST_TRANSFORM(ST_SetSRID(
# ST_MakePoint(601179.61612, 6399375,681364), 3847), 4326) as geom) g;
# ST_MakePoint(601179.61612, 6399375,681364), 3847), 4326) as geom) g;
if isinstance(geopoint, BaseGeometry):
geo_point_instance = geopoint
else:
geo_point_instance = asShape(geojson.loads(geopoint))
cr.execute("""
SELECT
ST_TRANSFORM(
ST_SetSRID(
ST_MakePoint(
%(coord_x)s, %(coord_y)s
),
%(srid)s
), 4326)""",
{'coord_x': geo_point_instance.x, 'coord_y':geo_point_instance.y, 'srid': cls._slots['srid']})
SELECT
ST_TRANSFORM(
ST_SetSRID(ST_MakePoint(%(coord_x)s, %(coord_y)s),
%(srid)s), 4326)""",
{'coord_x': geo_point_instance.x,
'coord_y': geo_point_instance.y,
'srid': cls._slots['srid']})

res = cr.fetchone()
point_latlon = cls.load_geo(res[0])
return point_latlon.x, point_latlon.y


class GeoPolygon(GeoField):
"""Field for POSTGIS geometry Polygon type"""
type = 'geo_polygon'
Expand Down
21 changes: 9 additions & 12 deletions base_geoengine/tests/test_geoengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
from odoo import fields
from odoo.exceptions import MissingError

from odoo.addons.base_geoengine.geo_model import GeoModel
from odoo.addons.base_geoengine import fields as geo_fields
from odoo.addons.base_geoengine.fields import GeoPoint
from .base_geoengine.geo_model import GeoModel
from .base_geoengine import fields as geo_fields
from .base_geoengine.fields import GeoPoint
from .data import MULTIPOLYGON_1, GEO_VIEW, FORM_VIEW
from .data import EXPECTED_GEO_COLUMN_MULTIPOLYGON

Expand All @@ -28,7 +28,8 @@
class TestGeoengine(common.TransactionCase):

def setUp(self):
common.TransactionCase.setUp(self)
super(TestGeoengine, self).setUp()

class DummyModel(GeoModel):
_name = 'test.dummy'

Expand Down Expand Up @@ -273,10 +274,9 @@ def test_create_line_from_points(self):
self.env.cr, geo_point_1, geo_point_2)
self.assertEqual(geo_line, expected_line)


def test_from_lat_lon(self):
latitude = 49.72842315886126
longitude = 5.400488376617026
longitude = 5.400488376617026

# This is computed with postgis in postgres:

Expand All @@ -286,15 +286,12 @@ def test_from_lat_lon(self):

self.assertAlmostEqual(geo_point.x, expected_coordinates[0], 4)
self.assertAlmostEqual(geo_point.y, expected_coordinates[1], 4)

def test_to_lat_lon(self):
x = 613393.2849222135
y = 5587677.847237722

geo_point = Point(601179.61612, 6399375,681364)
expected_lat_lon = [49.72842315886126, 5.400488376617026]
geo_point = Point(601179.61612, 6399375.681364)

longitude, latitude = GeoPoint.to_latlon(self.env.cr, geo_point)

self.assertAlmostEqual(latitude, 49.72842315886126, 4)
self.assertAlmostEqual(longitude, 5.400488376617026, 4)
self.assertAlmostEqual(longitude, 5.400488376617026, 4)
27 changes: 16 additions & 11 deletions base_geolocalize_openstreetmap/models/res_partner.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging
import requests

from odoo import api, exceptions, models, _
from odoo import exceptions, models, _

_logger = logging.getLogger(__name__)

Expand All @@ -16,8 +16,8 @@ class ResPartner(models.AbstractModel):
_inherit = 'res.partner'

@classmethod
def _geocode_address(
cls, street=None, zip_code=None, city=None, state=None, country=None):
def _geocode_address(cls, street=None,
zip_code=None, city=None, state=None, country=None):
"""Get the latitude and longitude by requesting Openstreetmap"
"""
pay_load = {
Expand All @@ -30,22 +30,27 @@ def _geocode_address(
'country': country or '',
}

request_result = requests.get(cls._url, params=pay_load)
request_result = requests.get(cls._url, params=pay_load)
try:
request_result.raise_for_status()
except Exception as e:
_logger.exception('Geocoding error')
raise exceptions.Warning(
_('Geocoding error. \n %s') % e.message)
values = request_result.json()
values = values and values[0] or {}
values = values[0] if values else {}
return values

@classmethod
def _geo_localize(cls, apikey, street='', zip='', city='', state='', country=''):
result = cls._geocode_address(street=street, zip_code=zip, city=city, state=state, country=country)

def _geo_localize(cls,
apikey, street='', zip='',
city='', state='', country=''):
result = cls._geocode_address(street=street,
zip_code=zip, city=city,
state=state, country=country)

if not result:
result = cls._geocode_address(city=city, state=state, country=country)

return result.get('lat'), result.get('lon')
result = cls._geocode_address(city=city,
state=state, country=country)

return result.get('lat'), result.get('lon')
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
# Copyright 2015-2017 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import responses
import requests
import odoo.tests.common as common


class TestGeolocalizeOpenstreetmap(common.TransactionCase):

def setUp(self):
common.TransactionCase.setUp(self)
super(TestGeolocalizeOpenstreetmap, self).setUp()
self.expected_latitude = 50.4311411
self.expected_longitude = 4.6132813

Expand All @@ -22,10 +22,10 @@ def setUp(self):
'state': 'Namur'
}


self.partner_id_known = self.env['res.partner'].create(vals)

# Second, test a fake street to force the code to go to the second iteration
# Second, test a fake street to force the code to go to
# the second iteration
vals2 = {
'name': 'Partner Project',
'street': 'Rue test',
Expand All @@ -34,7 +34,8 @@ def setUp(self):
}
self.partner_id_known_second = self.env['res.partner'].create(vals2)

# Third, test a fake street to force the code to go to the second iteration
# Third, test a fake street to force the code to go
# to the second iteration
vals3 = {
'name': 'Partner Project',
'street': 'Rue test',
Expand All @@ -43,50 +44,56 @@ def setUp(self):
}
self.partner_id_not_known = self.env['res.partner'].create(vals3)


@responses.activate
def test_osm_found_lat_long_with_mock(self):
responses.add(
responses.Response(
method='GET',
url ='https://nominatim.openstreetmap.org/search?city=Tamines&format=json&country=Belgium&state=&street=Rue+bois+des+noix&limit=1&postalCode=5060',
url='https://nominatim.openstreetmap.org/search?' +
'city=Tamines&format=json&country=Belgium&' +
'state=&street=Rue+bois+des+noix&limit=1&postalCode=5060',
match_querystring=True,
json=[{'lat': self.expected_latitude, 'lon': self.expected_longitude}],
json=[{'lat': self.expected_latitude,
'lon': self.expected_longitude}],
status=200
))

self.partner_id_known.geo_localize()

self.assertEqual(len(responses.calls), 1, 'call does not exist')
self.assertAlmostEqual(
self.partner_id_known.partner_latitude, self.expected_latitude, 3,
self.partner_id_known.partner_latitude, self.expected_latitude, 3,
'Latitude Should be equals')
self.assertAlmostEqual(
self.partner_id_known.partner_longitude, self.expected_longitude, 3,
self.partner_id_known.partner_longitude,
self.expected_longitude, 3,
'Longitude Should be equals')


@responses.activate
def test_osm_found_lat_long_second_time_with_mock(self):
responses.add(
responses.Response(
method='GET',
url ='https://nominatim.openstreetmap.org/search?city=Tamines&format=json&country=Belgium&state=&street=Rue+test&limit=1&postalCode=',
url='https://nominatim.openstreetmap.org/search?city=Tamines' +
'&format=json&country=Belgium&state=&street=Rue+test&' +
'limit=1&postalCode=',
match_querystring=True,
json=[{}],
status=200
))
responses.add(
responses.Response(
method='GET',
url ='https://nominatim.openstreetmap.org/search?city=Tamines&format=json&country=Belgium&state=&street=&limit=1&postalCode=',
url='https://nominatim.openstreetmap.org/search?city=Tamines' +
'&format=json&country=Belgium&state=&street=&' +
'limit=1&postalCode=',
match_querystring=True,
json=[{'lat': 50.825833, 'lon': 4.3475227}],
status=200
))

self.partner_id_known_second.geo_localize()

self.assertAlmostEqual(
self.partner_id_known_second.partner_latitude, 50.825833, 3,
'Latitude Should be equals')
Expand All @@ -100,23 +107,26 @@ def test_osm_loc_not_found_with_mock(self):
responses.add(
responses.Response(
method='GET',
url='https://nominatim.openstreetmap.org/search?city=Tmnss&format=json&country=Belgium&state=&street=Rue+test&limit=1&postalCode=',
url='https://nominatim.openstreetmap.org/search?city=Tmnss&' +
'format=json&country=Belgium&state=&street=Rue+test&' +
'limit=1&postalCode=',
match_querystring=True,
json=[{}]
))

responses.add(
responses.Response(
method='GET',
url='https://nominatim.openstreetmap.org/search?city=Tmnss&format=json&country=Belgium&state=&street=&limit=1&postalCode=',
url='https://nominatim.openstreetmap.org/search?city=Tmnss&' +
'format=json&country=Belgium&state=&street=&' +
'limit=1&postalCode=',
match_querystring=True,
json=[{}]
))

self.partner_id_not_known.geo_localize()


self.assertFalse(
self.partner_id_not_known.partner_longitude)
self.assertFalse(
self.partner_id_not_known.partner_latitude)
self.partner_id_not_known.partner_latitude)
22 changes: 4 additions & 18 deletions geoengine_base_geolocalize/models/res_partner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,15 @@
# Copyright 2015 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

import logging
from odoo import api, fields
from odoo import exceptions
from odoo.tools.translate import _
from odoo import api
from odoo.addons.base_geoengine import geo_model
from odoo.addons.base_geoengine import fields as geo_fields

try:
import requests
except ImportError:
logger = logging.getLogger(__name__)
logger.warning('requests is not available in the sys path')

_logger = logging.getLogger(__name__)


class ResPartner(geo_model.GeoModel):
"""Add geo_point to partner using a function field"""
_inherit = "res.partner"



@api.multi
@api.depends('partner_latitude', 'partner_longitude')
def _compute_geo_point(self):
Expand All @@ -48,8 +35,7 @@ def _compute_geo_point(self):
def _inverse_geo_point(self):
for rec in self:
if not rec.geo_point:
# FIXME: For now, if no coordinates are provided, latitude and longitude are set to false
rec.partner_longitude, rec.partner_latitude = False, False
rec.partner_longitude, rec.partner_latitude = False, False
else:
rec.partner_longitude, rec.partner_latitude = geo_fields.GeoPoint.to_latlon(rec.env.cr, rec.geo_point)

rec.partner_longitude, rec.partner_latitude = \
geo_fields.GeoPoint.to_latlon(rec.env.cr, rec.geo_point)
2 changes: 1 addition & 1 deletion geoengine_geoname_geocoder/res_partner.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def geocode_from_geonames(self, srid='900913',
url = base_url + urlencode(filters)
answer = urlopen(url)
add.geo_point = self._get_point_from_reply(answer)
except Exception, exc:
except Exception as exc:
logger.exception('error while updating geocodes')
if strict:
raise except_orm(_('Geoencoding fails'), str(exc))
Expand Down

0 comments on commit d6eab49

Please sign in to comment.