Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""Tests for filter.py"""
import unittest
from geojson import Feature, Polygon, LineString
from label_maker.filter import create_filter, _compile, _compile_property_reference, \
_compile_comparison_op, _compile_logical_op, _compile_in_op, _compile_has_op, \
_compile_negation, _stringify
line_geometry = LineString([(0, 0), (1, 1)])
polygon_geometry = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])
class TestCompiledFilters(unittest.TestCase):
"""Tests for compiled filter functions"""
def test_comparison(self):
"""Test comparison filter function"""
ff = create_filter(['==', 'a', 5])
passing = Feature(geometry=line_geometry, properties=dict(a=5))
failing = Feature(geometry=line_geometry, properties=dict(a=4))
self.assertTrue(ff(passing))
self.assertFalse(ff(failing))
def test_any(self):
"""Test any filter function"""
ff = create_filter(['any', ['==', 'a', 5], ['==', 'b', 3]])
def test_invalid_linestring(self):
with self.assertRaises(ValueError) as cm:
geojson.LineString([(8.919, 44.4074)], validate=True)
self.assertIn('must be an array of two or more positions',
str(cm.exception))
with self.assertRaises(ValueError) as cm:
geojson.LineString([(8.919, 44.4074), [3]], validate=True)
self.assertIn('a position must have exactly 2 or 3 values',
str(cm.exception))
###############################################################################
import geojson
class MyPoint():
def __init__(self, x, y):
self.x = x
self.y = y
@property
def __geo_interface__(self):
return {'type': 'Point',
'coordinates': (self.x, self.y)}
point_instance = MyPoint(52.235, -19.234)
geojson.dumps(point_instance, sort_keys=True)
###############################################################################
import geojson
my_line = geojson.LineString([(-152.62, 51.21),
(5.21, 10.69)])
my_feature = geojson.Feature(geometry=my_line)
list(geojson.utils.coords(my_feature))
###############################################################################
import geojson
new_point = geojson.utils.map_coords(lambda x: x/2,
geojson.Point((-115.81, 37.24)))
geojson.dumps(new_point, sort_keys=True)
###############################################################################
import geojson
geojson.utils.generate_random("LineString")
def geometry(self):
try:
if self.type() == 'node':
if not self.lon() or not self.lat():
self._raiseException('Cannot build geometry: geometry information not included.')
return geojson.Point((self.lon(), self.lat()))
elif self.type() == 'way':
if not self.__getElement('geometry'):
self._raiseException('Cannot build geometry: geometry information not included.')
cs = self.__geometry_csToList(self.__getElement('geometry'))
if self.__geometry_equal(cs[0], cs[-1]):
return geojson.Polygon([cs])
else:
return geojson.LineString(cs)
elif self.type() == 'relation':
members = copy.deepcopy(self.__members())
membersOuter = self.__geometry_extract(members, 'outer')
if len(membersOuter) == 0:
self._raiseException('Cannot build geometry: no outer rings found.')
membersInner = self.__geometry_extract(members, 'inner')
ringsOuter = self.__geometry_buildRings(membersOuter)
ringsInner = self.__geometry_buildRings(membersInner)
ringsOuter = self.__geometry_orientRings(ringsOuter, positive=True)
ringsInner = self.__geometry_orientRings(ringsInner, positive=False)
polygons = self.__geometry_buildPolygons(ringsOuter, ringsInner)
if len(polygons) > 1:
return geojson.MultiPolygon(polygons)
else:
return geojson.Polygon(polygons[0])
else:
def _asGeoJSON(self, elements):
features = []
for elem in elements:
elem_type = elem["type"]
if elem_type == "node":
geometry = geojson.Point((elem["lon"], elem["lat"]))
elif elem_type == "way":
points = []
for coords in elem["geometry"]:
points.append((coords["lon"], coords["lat"]))
geometry = geojson.LineString(points)
else:
continue
feature = geojson.Feature(
id=elem["id"],
geometry=geometry,
properties=elem.get("tags"))
features.append(feature)
return geojson.FeatureCollection(features)
def _make_geo():
geometry = geojson.Point((-122.0,38.0))
ls = geojson.LineString([(-122,38),(-122,39)])
features = [
geojson.Feature(geometry=geometry, id=1, properties={'name':'john','addr':1212, 'gpa':3.5}),
geojson.Feature(geometry=geometry, id=2, properties={'fish':'salmon', 'addr':'sea', 'gpa':3, 'foo':None}),
geojson.Feature(geometry=ls, id=10, properties={'other':10}),
geojson.Feature(geometry=geometry, id=3, properties={'num':2**80}),
geojson.Feature(geometry=geometry, id=4, properties={'Num':2}),
geojson.Feature(geometry=geometry, id=5, properties={'NUM':'many'})
]
geo = geojson.FeatureCollection(features)
return geo
def create_line_string_from_shape_file(path):
coordinates = [tuple([float(i['shape_pt_lat']), float(i['shape_pt_lon'])])
for i in csv.DictReader(open(path, encoding="utf8"))]
return geojson.LineString(coordinates=coordinates)
if point['shape_pt_sequence'] == '0':
print 'creating trip'
currentTrip = point['shape_id']
if i > 0:
ls = LineString(jsonpoints)
feature = Feature(geometry=ls, properties={"shape_id": currentTrip})
# print feature
features.append(feature)
jsonpoints = []
else:
pnt = (float(point['shape_pt_lon']), float(point['shape_pt_lat']))
# print pnt
jsonpoints.append(pnt)
# write linestring for last shape
ls = LineString(jsonpoints)
feature = Feature(geometry=ls, properties={"shape_id": currentTrip})
print feature
features.append(feature)
jsonpoints = []
fc = FeatureCollection(features)
print fc
geojsonfile = os.path.join(geojsondir, 'shapes.geojson')
with open(geojsonfile, 'wb') as tripgeo:
geojson.dump(fc, tripgeo)