Skip to content

Commit

Permalink
Merge pull request #185 from geoalchemy/to-shape
Browse files Browse the repository at this point in the history
Fix to_shape with SpatiaLite
  • Loading branch information
elemoine committed Jul 17, 2018
2 parents 29d0a3c + ccdd274 commit 1b3e27f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
6 changes: 4 additions & 2 deletions geoalchemy2/shape.py
Expand Up @@ -11,7 +11,7 @@
import shapely.wkt

from .elements import WKBElement, WKTElement
from .compat import buffer, bytes
from .compat import buffer, bytes, str


def to_shape(element):
Expand All @@ -26,7 +26,9 @@ def to_shape(element):
"""
assert isinstance(element, (WKBElement, WKTElement))
if isinstance(element, WKBElement):
return shapely.wkb.loads(bytes(element.data))
data, hex = (element.data, True) if isinstance(element.data, str) else \
(bytes(element.data), False)
return shapely.wkb.loads(data, hex=hex)
elif isinstance(element, WKTElement):
return shapely.wkt.loads(element.data)

Expand Down
34 changes: 33 additions & 1 deletion tests/test_functional_spatialite.py
Expand Up @@ -11,7 +11,8 @@

from geoalchemy2 import Geometry
from geoalchemy2.elements import WKTElement, WKBElement
from geoalchemy2.shape import from_shape
from geoalchemy2.shape import from_shape, to_shape
from geoalchemy2.compat import str as str_

from shapely.geometry import LineString

Expand Down Expand Up @@ -143,6 +144,37 @@ def test_WKBElement(self):
assert srid == 4326


class TestShapely():

def setup(self):
metadata.drop_all(checkfirst=True)
metadata.create_all()

def teardown(self):
session.rollback()
metadata.drop_all()

def test_to_shape(self):
l = Lake(WKTElement('LINESTRING(0 0,1 1)', srid=4326))
session.add(l)
session.flush()
session.expire(l)
l = session.query(Lake).one()
assert isinstance(l.geom, WKBElement)
assert isinstance(l.geom.data, str_)
assert l.geom.srid == 4326
s = to_shape(l.geom)
assert isinstance(s, LineString)
assert s.wkt == 'LINESTRING (0 0, 1 1)'
l = Lake(l.geom)
session.add(l)
session.flush()
session.expire(l)
assert isinstance(l.geom, WKBElement)
assert isinstance(l.geom.data, str_)
assert l.geom.srid == 4326


class TestCallFunction():

def setup(self):
Expand Down
11 changes: 10 additions & 1 deletion tests/test_shape.py
@@ -1,4 +1,4 @@
from geoalchemy2.compat import buffer, bytes
from geoalchemy2.compat import buffer, bytes, str
from geoalchemy2.elements import WKBElement, WKTElement
from geoalchemy2.shape import from_shape, to_shape

Expand All @@ -16,6 +16,15 @@ def test_to_shape_WKBElement():
assert s.y == 2


def test_to_shape_WKBElement_str():
# POINT(1 2)
e = WKBElement(str('0101000000000000000000f03f0000000000000040'))
s = to_shape(e)
assert isinstance(s, Point)
assert s.x == 1
assert s.y == 2


def test_to_shape_ExtendedWKBElement():
# SRID=3857;POINT(1 2 3)
e = WKBElement(b'\x01\x01\x00\x00\xa0\x11\x0f\x00\x00\x00'
Expand Down

0 comments on commit 1b3e27f

Please sign in to comment.