desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure annotated date querysets work if spatial backend is used. See #14648.'
def test16_annotated_date_queryset(self):
birth_years = [dt.year for dt in list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))] birth_years.sort() self.assertEqual([1950, 1974], birth_years)
'Testing GeometryField initialization with defaults.'
def test00_init(self):
fld = forms.GeometryField() for bad_default in ('blah', 3, 'FoO', None, 0): self.assertRaises(ValidationError, fld.clean, bad_default)
'Testing GeometryField with a SRID set.'
def test01_srid(self):
fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) fld = forms.GeometryField(srid=32140) tol = 1e-07 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)') self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
'Testing GeometryField\'s handling of null (None) geometries.'
def test02_null(self):
fld = forms.GeometryField() self.assertRaises(forms.ValidationError, fld.clean, None) fld = forms.GeometryField(required=False, null=False) self.assertRaises(forms.ValidationError, fld.clean, None) fld = forms.GeometryField(required=False) self.assertEqual(None, fld.clean(None))
'Testing GeometryField\'s handling of different geometry types.'
def test03_geom_type(self):
fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)')) self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)')) self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)')
'Testing to_python returns a correct GEOSGeometry object or a ValidationError'
def test04_to_python(self):
fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt)) for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'): self.assertRaises(forms.ValidationError, fld.to_python, wkt)
'Transforms the value to a Geometry object.'
def to_python(self, value):
try: return GEOSGeometry(value) except (GEOSException, ValueError, TypeError): raise forms.ValidationError(self.error_messages[u'invalid_geom'])
'Validates that the input value can be converted to a Geometry object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry.'
def clean(self, value):
if (not value): if (self.null and (not self.required)): return None else: raise forms.ValidationError(self.error_messages[u'no_geom']) geom = self.to_python(value) if ((str(geom.geom_type).upper() != self.geom_type) and (not (self.geom_type == u'GEOMETRY'))): raise forms.ValidationError(self.error_messages[u'invalid_geom_type']) if self.srid: if (not geom.srid): geom.srid = self.srid elif ((self.srid != (-1)) and (self.srid != geom.srid)): try: geom.transform(self.srid) except: raise forms.ValidationError(self.error_messages[u'transform_error']) return geom
'Builds the map options hash for the OpenLayers template.'
def map_options(self):
def ol_bounds(extent): return ('new OpenLayers.Bounds(%s)' % str(extent)) def ol_projection(srid): return ('new OpenLayers.Projection("EPSG:%s")' % srid) map_types = [('srid', 'projection', 'srid'), ('display_srid', 'displayProjection', 'srid'), ('units', 'units', str), ('max_resolution', 'maxResolution', float), ('max_extent', 'maxExtent', 'bounds'), ('num_zoom', 'numZoomLevels', int), ('max_zoom', 'maxZoomLevels', int), ('min_zoom', 'minZoomLevel', int)] map_options = {} for (param_name, js_name, option_type) in map_types: if self.params.get(param_name, False): if (option_type == 'srid'): value = ol_projection(self.params[param_name]) elif (option_type == 'bounds'): value = ol_bounds(self.params[param_name]) elif (option_type in (float, int)): value = self.params[param_name] elif (option_type in (str,)): value = ('"%s"' % self.params[param_name]) else: raise TypeError map_options[js_name] = value return map_options
'Compare geographic value of data with its initial value.'
def _has_changed(self, initial, data):
if isinstance(initial, six.string_types): try: initial = GEOSGeometry(initial) except (GEOSException, ValueError): initial = None if (initial and data): data = fromstr(data) data.transform(initial.srid) return (not initial.equals_exact(data, tolerance=1e-06)) else: return (bool(initial) != bool(data))
'Injects OpenLayers JavaScript into the admin.'
@property def media(self):
media = super(GeoModelAdmin, self).media media.add_js([self.openlayers_url]) media.add_js(self.extra_js) return media
'Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing GeometryFields.'
def formfield_for_dbfield(self, db_field, **kwargs):
if isinstance(db_field, models.GeometryField): request = kwargs.pop('request', None) kwargs['widget'] = self.get_map_widget(db_field) return db_field.formfield(**kwargs) else: return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
'Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.'
def get_map_widget(self, db_field):
is_collection = (db_field.geom_type in ('MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION')) if is_collection: if (db_field.geom_type == 'GEOMETRYCOLLECTION'): collection_type = 'Any' else: collection_type = OGRGeomType(db_field.geom_type.replace('MULTI', '')) else: collection_type = 'None' class OLMap(self.widget, ): template = self.map_template geom_type = db_field.geom_type wms_options = '' if self.wms_options: wms_options = [("%s: '%s'" % pair) for pair in self.wms_options.items()] wms_options = (', %s' % ', '.join(wms_options)) params = {'default_lon': self.default_lon, 'default_lat': self.default_lat, 'default_zoom': self.default_zoom, 'display_wkt': (self.debug or self.display_wkt), 'geom_type': OGRGeomType(db_field.geom_type), 'field_name': db_field.name, 'is_collection': is_collection, 'scrollable': self.scrollable, 'layerswitcher': self.layerswitcher, 'collection_type': collection_type, 'is_linestring': (db_field.geom_type in ('LINESTRING', 'MULTILINESTRING')), 'is_polygon': (db_field.geom_type in ('POLYGON', 'MULTIPOLYGON')), 'is_point': (db_field.geom_type in ('POINT', 'MULTIPOINT')), 'num_zoom': self.num_zoom, 'max_zoom': self.max_zoom, 'min_zoom': self.min_zoom, 'units': self.units, 'max_resolution': self.max_resolution, 'max_extent': self.max_extent, 'modifiable': self.modifiable, 'mouse_position': self.mouse_position, 'scale_text': self.scale_text, 'map_width': self.map_width, 'map_height': self.map_height, 'point_zoom': self.point_zoom, 'srid': self.map_srid, 'display_srid': self.display_srid, 'wms_url': self.wms_url, 'wms_layer': self.wms_layer, 'wms_name': self.wms_name, 'wms_options': wms_options, 'debug': self.debug} return OLMap
'Initializes on an exterior ring and a sequence of holes (both instances may be either LinearRing instances, or a tuple/list that may be constructed into a LinearRing). Examples of initialization, where shell, hole1, and hole2 are valid LinearRing geometries: >>> poly = Polygon(shell, hole1, hole2) >>> poly = Polygon(shell, (hole1, hole2)) Example where a tuple parameters are used: >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)), ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))'
def __init__(self, *args, **kwargs):
if (not args): raise TypeError('Must provide at least one LinearRing, or a tuple, to initialize a Polygon.') ext_ring = args[0] init_holes = args[1:] n_holes = len(init_holes) if ((n_holes == 1) and isinstance(init_holes[0], (tuple, list))): if (len(init_holes[0]) == 0): init_holes = () n_holes = 0 elif isinstance(init_holes[0][0], LinearRing): init_holes = init_holes[0] n_holes = len(init_holes) polygon = self._create_polygon((n_holes + 1), ((ext_ring,) + init_holes)) super(Polygon, self).__init__(polygon, **kwargs)
'Iterates over each ring in the polygon.'
def __iter__(self):
for i in xrange(len(self)): (yield self[i])
'Returns the number of rings in this Polygon.'
def __len__(self):
return (self.num_interior_rings + 1)
'Constructs a Polygon from a bounding box (4-tuple).'
@classmethod def from_bbox(cls, bbox):
(x0, y0, x1, y1) = bbox for z in bbox: if (not isinstance(z, (six.integer_types + (float,)))): return GEOSGeometry(('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))) return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))
'Helper routine for trying to construct a ring from the given parameter.'
def _construct_ring(self, param, msg='Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'):
if isinstance(param, LinearRing): return param try: ring = LinearRing(param) return ring except TypeError: raise TypeError(msg)
'Returns the ring at the specified index. The first index, 0, will always return the exterior ring. Indices > 0 will return the interior ring at the given index (e.g., poly[1] and poly[2] would return the first and second interior ring, respectively). CAREFUL: Internal/External are not the same as Interior/Exterior! _get_single_internal returns a pointer from the existing geometries for use internally by the object\'s methods. _get_single_external returns a clone of the same geometry for use by external code.'
def _get_single_internal(self, index):
if (index == 0): return capi.get_extring(self.ptr) else: return capi.get_intring(self.ptr, (index - 1))
'Returns the number of interior rings.'
@property def num_interior_rings(self):
return capi.get_nrings(self.ptr)
'Gets the exterior ring of the Polygon.'
def _get_ext_ring(self):
return self[0]
'Sets the exterior ring of the Polygon.'
def _set_ext_ring(self, ring):
self[0] = ring
'Gets the tuple for each ring in this Polygon.'
@property def tuple(self):
return tuple([self[i].tuple for i in xrange(len(self))])
'Returns the KML representation of this Polygon.'
@property def kml(self):
inner_kml = ''.join([('<innerBoundaryIs>%s</innerBoundaryIs>' % self[(i + 1)].kml) for i in xrange(self.num_interior_rings)]) return ('<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>' % (self[0].kml, inner_kml))
'Initializes from a GEOS pointer.'
def __init__(self, ptr, z=False):
if (not isinstance(ptr, CS_PTR)): raise TypeError('Coordinate sequence should initialize with a CS_PTR.') self._ptr = ptr self._z = z
'Iterates over each point in the coordinate sequence.'
def __iter__(self):
for i in xrange(self.size): (yield self[i])
'Returns the number of points in the coordinate sequence.'
def __len__(self):
return int(self.size)
'Returns the string representation of the coordinate sequence.'
def __str__(self):
return str(self.tuple)
'Returns the coordinate sequence value at the given index.'
def __getitem__(self, index):
coords = [self.getX(index), self.getY(index)] if ((self.dims == 3) and self._z): coords.append(self.getZ(index)) return tuple(coords)
'Sets the coordinate sequence value at the given index.'
def __setitem__(self, index, value):
if isinstance(value, (list, tuple)): pass elif (numpy and isinstance(value, numpy.ndarray)): pass else: raise TypeError('Must set coordinate with a sequence (list, tuple, or numpy array).') if ((self.dims == 3) and self._z): n_args = 3 set_3d = True else: n_args = 2 set_3d = False if (len(value) != n_args): raise TypeError('Dimension of value does not match.') self.setX(index, value[0]) self.setY(index, value[1]) if set_3d: self.setZ(index, value[2])
'Checks the given index.'
def _checkindex(self, index):
sz = self.size if ((sz < 1) or (index < 0) or (index >= sz)): raise GEOSIndexError(('invalid GEOS Geometry index: %s' % str(index)))
'Checks the given dimension.'
def _checkdim(self, dim):
if ((dim < 0) or (dim > 2)): raise GEOSException(('invalid ordinate dimension "%d"' % dim))
'Returns the value for the given dimension and index.'
def getOrdinate(self, dimension, index):
self._checkindex(index) self._checkdim(dimension) return capi.cs_getordinate(self.ptr, index, dimension, byref(c_double()))
'Sets the value for the given dimension and index.'
def setOrdinate(self, dimension, index, value):
self._checkindex(index) self._checkdim(dimension) capi.cs_setordinate(self.ptr, index, dimension, value)
'Get the X value at the index.'
def getX(self, index):
return self.getOrdinate(0, index)
'Set X with the value at the given index.'
def setX(self, index, value):
self.setOrdinate(0, index, value)
'Get the Y value at the given index.'
def getY(self, index):
return self.getOrdinate(1, index)
'Set Y with the value at the given index.'
def setY(self, index, value):
self.setOrdinate(1, index, value)
'Get Z with the value at the given index.'
def getZ(self, index):
return self.getOrdinate(2, index)
'Set Z with the value at the given index.'
def setZ(self, index, value):
self.setOrdinate(2, index, value)
'Returns the size of this coordinate sequence.'
@property def size(self):
return capi.cs_getsize(self.ptr, byref(c_uint()))
'Returns the dimensions of this coordinate sequence.'
@property def dims(self):
return capi.cs_getdims(self.ptr, byref(c_uint()))
'Returns whether this coordinate sequence is 3D. This property value is inherited from the parent Geometry.'
@property def hasz(self):
return self._z
'Clones this coordinate sequence.'
def clone(self):
return GEOSCoordSeq(capi.cs_clone(self.ptr), self.hasz)
'Returns the KML representation for the coordinates.'
@property def kml(self):
if self.hasz: substr = '%s,%s,%s ' else: substr = '%s,%s,0 ' return ('<coordinates>%s</coordinates>' % ''.join([(substr % self[i]) for i in xrange(len(self))]).strip())
'Returns a tuple version of this coordinate sequence.'
@property def tuple(self):
n = self.size if (n == 1): return self[0] else: return tuple([self[i] for i in xrange(n)])
'Initializes on the given sequence -- may take lists, tuples, NumPy arrays of X,Y pairs, or Point objects. If Point objects are used, ownership is _not_ transferred to the LineString object. Examples: ls = LineString((1, 1), (2, 2)) ls = LineString([(1, 1), (2, 2)]) ls = LineString(array([(1, 1), (2, 2)])) ls = LineString(Point(1, 1), Point(2, 2))'
def __init__(self, *args, **kwargs):
if (len(args) == 1): coords = args[0] else: coords = args if isinstance(coords, (tuple, list)): ncoords = len(coords) if coords: ndim = len(coords[0]) else: raise TypeError('Cannot initialize on empty sequence.') self._checkdim(ndim) for i in xrange(1, ncoords): if (not isinstance(coords[i], (tuple, list, Point))): raise TypeError('each coordinate should be a sequence (list or tuple)') if (len(coords[i]) != ndim): raise TypeError('Dimension mismatch.') numpy_coords = False elif (numpy and isinstance(coords, numpy.ndarray)): shape = coords.shape if (len(shape) != 2): raise TypeError('Too many dimensions.') self._checkdim(shape[1]) ncoords = shape[0] ndim = shape[1] numpy_coords = True else: raise TypeError('Invalid initialization input for LineStrings.') cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool((ndim == 3))) for i in xrange(ncoords): if numpy_coords: cs[i] = coords[i, :] elif isinstance(coords[i], Point): cs[i] = coords[i].tuple else: cs[i] = coords[i] srid = kwargs.get('srid', None) super(LineString, self).__init__(self._init_func(cs.ptr), srid=srid)
'Allows iteration over this LineString.'
def __iter__(self):
for i in xrange(len(self)): (yield self[i])
'Returns the number of points in this LineString.'
def __len__(self):
return len(self._cs)
'Returns a tuple version of the geometry from the coordinate sequence.'
@property def tuple(self):
return self._cs.tuple
'Internal routine that returns a sequence (list) corresponding with the given function. Will return a numpy array if possible.'
def _listarr(self, func):
lst = [func(i) for i in xrange(len(self))] if numpy: return numpy.array(lst) else: return lst
'Returns a numpy array for the LineString.'
@property def array(self):
return self._listarr(self._cs.__getitem__)
'Returns the line merge of this LineString.'
@property def merged(self):
return self._topology(capi.geos_linemerge(self.ptr))
'Returns a list or numpy array of the X variable.'
@property def x(self):
return self._listarr(self._cs.getX)
'Returns a list or numpy array of the Y variable.'
@property def y(self):
return self._listarr(self._cs.getY)
'Returns a list or numpy array of the Z variable.'
@property def z(self):
if (not self.hasz): return None else: return self._listarr(self._cs.getZ)
'Returns a GEOSGeometry for the given WKB buffer.'
def read(self, wkb):
return GEOSGeometry(super(WKBReader, self).read(wkb))
'Returns a GEOSGeometry for the given WKT string.'
def read(self, wkt):
return GEOSGeometry(super(WKTReader, self).read(wkt))
'Testing Geometry GEOSIndexError'
def test00_GEOSIndexException(self):
p = Point(1, 2) for i in range((-2), 2): p._checkindex(i) self.assertRaises(GEOSIndexError, p._checkindex, 2) self.assertRaises(GEOSIndexError, p._checkindex, (-3))
'Testing Point mutations'
def test01_PointMutations(self):
for p in (Point(1, 2, 3), fromstr('POINT (1 2 3)')): self.assertEqual(p._get_single_external(1), 2.0, 'Point _get_single_external') p._set_single(0, 100) self.assertEqual(p.coords, (100.0, 2.0, 3.0), 'Point _set_single') p._set_list(2, (50, 3141)) self.assertEqual(p.coords, (50.0, 3141.0), 'Point _set_list')
'Testing Point exceptions'
def test02_PointExceptions(self):
self.assertRaises(TypeError, Point, range(1)) self.assertRaises(TypeError, Point, range(4))
'Testing Point API'
def test03_PointApi(self):
q = Point(4, 5, 3) for p in (Point(1, 2, 3), fromstr('POINT (1 2 3)')): p[0:2] = [4, 5] for f in geos_function_tests: self.assertEqual(f(q), f(p), ('Point ' + f.__name__))
'Testing LineString mutations'
def test04_LineStringMutations(self):
for ls in (LineString((1, 0), (4, 1), (6, (-1))), fromstr('LINESTRING (1 0,4 1,6 -1)')): self.assertEqual(ls._get_single_external(1), (4.0, 1.0), 'LineString _get_single_external') ls._set_single(0, ((-50), 25)) self.assertEqual(ls.coords, (((-50.0), 25.0), (4.0, 1.0), (6.0, (-1.0))), 'LineString _set_single') ls._set_list(2, (((-50.0), 25.0), (6.0, (-1.0)))) self.assertEqual(ls.coords, (((-50.0), 25.0), (6.0, (-1.0))), 'LineString _set_list') lsa = LineString(ls.coords) for f in geos_function_tests: self.assertEqual(f(lsa), f(ls), ('LineString ' + f.__name__))
'Testing Polygon mutations'
def test05_Polygon(self):
for pg in (Polygon(((1, 0), (4, 1), (6, (-1)), (8, 10), (1, 0)), ((5, 4), (6, 4), (6, 3), (5, 4))), fromstr('POLYGON ((1 0,4 1,6 -1,8 10,1 0),(5 4,6 4,6 3,5 4))')): self.assertEqual(pg._get_single_external(0), LinearRing((1, 0), (4, 1), (6, (-1)), (8, 10), (1, 0)), 'Polygon _get_single_external(0)') self.assertEqual(pg._get_single_external(1), LinearRing((5, 4), (6, 4), (6, 3), (5, 4)), 'Polygon _get_single_external(1)') pg._set_list(2, (((1, 2), (10, 0), (12, 9), ((-1), 15), (1, 2)), ((4, 2), (5, 2), (5, 3), (4, 2)))) self.assertEqual(pg.coords, (((1.0, 2.0), (10.0, 0.0), (12.0, 9.0), ((-1.0), 15.0), (1.0, 2.0)), ((4.0, 2.0), (5.0, 2.0), (5.0, 3.0), (4.0, 2.0))), 'Polygon _set_list') lsa = Polygon(*pg.coords) for f in geos_function_tests: self.assertEqual(f(lsa), f(pg), ('Polygon ' + f.__name__))
'Testing Collection mutations'
def test06_Collection(self):
for mp in (MultiPoint(*map(Point, ((3, 4), ((-1), 2), (5, (-4)), (2, 8)))), fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)')): self.assertEqual(mp._get_single_external(2), Point(5, (-4)), 'Collection _get_single_external') mp._set_list(3, map(Point, ((5, 5), (3, (-2)), (8, 1)))) self.assertEqual(mp.coords, ((5.0, 5.0), (3.0, (-2.0)), (8.0, 1.0)), 'Collection _set_list') lsa = MultiPoint(*map(Point, ((5, 5), (3, (-2)), (8, 1)))) for f in geos_function_tests: self.assertEqual(f(lsa), f(mp), ('MultiPoint ' + f.__name__))
'Slice retrieval'
def test01_getslice(self):
(pl, ul) = self.lists_of_len() for i in self.limits_plus(1): self.assertEqual(pl[i:], ul[i:], ('slice [%d:]' % i)) self.assertEqual(pl[:i], ul[:i], ('slice [:%d]' % i)) for j in self.limits_plus(1): self.assertEqual(pl[i:j], ul[i:j], ('slice [%d:%d]' % (i, j))) for k in self.step_range(): self.assertEqual(pl[i:j:k], ul[i:j:k], ('slice [%d:%d:%d]' % (i, j, k))) for k in self.step_range(): self.assertEqual(pl[i::k], ul[i::k], ('slice [%d::%d]' % (i, k))) self.assertEqual(pl[:i:k], ul[:i:k], ('slice [:%d:%d]' % (i, k))) for k in self.step_range(): self.assertEqual(pl[::k], ul[::k], ('slice [::%d]' % k))
'Slice assignment'
def test02_setslice(self):
def setfcn(x, i, j, k, L): x[i:j:k] = range(L) (pl, ul) = self.lists_of_len() for slen in range((self.limit + 1)): ssl = nextRange(slen) ul[:] = ssl pl[:] = ssl self.assertEqual(pl, ul[:], 'set slice [:]') for i in self.limits_plus(1): ssl = nextRange(slen) ul[i:] = ssl pl[i:] = ssl self.assertEqual(pl, ul[:], ('set slice [%d:]' % i)) ssl = nextRange(slen) ul[:i] = ssl pl[:i] = ssl self.assertEqual(pl, ul[:], ('set slice [:%d]' % i)) for j in self.limits_plus(1): ssl = nextRange(slen) ul[i:j] = ssl pl[i:j] = ssl self.assertEqual(pl, ul[:], ('set slice [%d:%d]' % (i, j))) for k in self.step_range(): ssl = nextRange(len(ul[i:j:k])) ul[i:j:k] = ssl pl[i:j:k] = ssl self.assertEqual(pl, ul[:], ('set slice [%d:%d:%d]' % (i, j, k))) sliceLen = len(ul[i:j:k]) self.assertRaises(ValueError, setfcn, ul, i, j, k, (sliceLen + 1)) if (sliceLen > 2): self.assertRaises(ValueError, setfcn, ul, i, j, k, (sliceLen - 1)) for k in self.step_range(): ssl = nextRange(len(ul[i::k])) ul[i::k] = ssl pl[i::k] = ssl self.assertEqual(pl, ul[:], ('set slice [%d::%d]' % (i, k))) ssl = nextRange(len(ul[:i:k])) ul[:i:k] = ssl pl[:i:k] = ssl self.assertEqual(pl, ul[:], ('set slice [:%d:%d]' % (i, k))) for k in self.step_range(): ssl = nextRange(len(ul[::k])) ul[::k] = ssl pl[::k] = ssl self.assertEqual(pl, ul[:], ('set slice [::%d]' % k))
'Delete slice'
def test03_delslice(self):
for Len in range(self.limit): (pl, ul) = self.lists_of_len(Len) del pl[:] del ul[:] self.assertEqual(pl[:], ul[:], 'del slice [:]') for i in range(((- Len) - 1), (Len + 1)): (pl, ul) = self.lists_of_len(Len) del pl[i:] del ul[i:] self.assertEqual(pl[:], ul[:], ('del slice [%d:]' % i)) (pl, ul) = self.lists_of_len(Len) del pl[:i] del ul[:i] self.assertEqual(pl[:], ul[:], ('del slice [:%d]' % i)) for j in range(((- Len) - 1), (Len + 1)): (pl, ul) = self.lists_of_len(Len) del pl[i:j] del ul[i:j] self.assertEqual(pl[:], ul[:], ('del slice [%d:%d]' % (i, j))) for k in (list(range(((- Len) - 1), 0)) + list(range(1, Len))): (pl, ul) = self.lists_of_len(Len) del pl[i:j:k] del ul[i:j:k] self.assertEqual(pl[:], ul[:], ('del slice [%d:%d:%d]' % (i, j, k))) for k in (list(range(((- Len) - 1), 0)) + list(range(1, Len))): (pl, ul) = self.lists_of_len(Len) del pl[:i:k] del ul[:i:k] self.assertEqual(pl[:], ul[:], ('del slice [:%d:%d]' % (i, k))) (pl, ul) = self.lists_of_len(Len) del pl[i::k] del ul[i::k] self.assertEqual(pl[:], ul[:], ('del slice [%d::%d]' % (i, k))) for k in (list(range(((- Len) - 1), 0)) + list(range(1, Len))): (pl, ul) = self.lists_of_len(Len) del pl[::k] del ul[::k] self.assertEqual(pl[:], ul[:], ('del slice [::%d]' % k))
'Get/set/delete single item'
def test04_get_set_del_single(self):
(pl, ul) = self.lists_of_len() for i in self.limits_plus(0): self.assertEqual(pl[i], ul[i], ('get single item [%d]' % i)) for i in self.limits_plus(0): (pl, ul) = self.lists_of_len() pl[i] = 100 ul[i] = 100 self.assertEqual(pl[:], ul[:], ('set single item [%d]' % i)) for i in self.limits_plus(0): (pl, ul) = self.lists_of_len() del pl[i] del ul[i] self.assertEqual(pl[:], ul[:], ('del single item [%d]' % i))
'Out of range exceptions'
def test05_out_of_range_exceptions(self):
def setfcn(x, i): x[i] = 20 def getfcn(x, i): return x[i] def delfcn(x, i): del x[i] (pl, ul) = self.lists_of_len() for i in (((-1) - self.limit), self.limit): self.assertRaises(IndexError, setfcn, ul, i) self.assertRaises(IndexError, getfcn, ul, i) self.assertRaises(IndexError, delfcn, ul, i)
'List methods'
def test06_list_methods(self):
(pl, ul) = self.lists_of_len() pl.append(40) ul.append(40) self.assertEqual(pl[:], ul[:], 'append') pl.extend(range(50, 55)) ul.extend(range(50, 55)) self.assertEqual(pl[:], ul[:], 'extend') pl.reverse() ul.reverse() self.assertEqual(pl[:], ul[:], 'reverse') for i in self.limits_plus(1): (pl, ul) = self.lists_of_len() pl.insert(i, 50) ul.insert(i, 50) self.assertEqual(pl[:], ul[:], ('insert at %d' % i)) for i in self.limits_plus(0): (pl, ul) = self.lists_of_len() self.assertEqual(pl.pop(i), ul.pop(i), ('popped value at %d' % i)) self.assertEqual(pl[:], ul[:], ('after pop at %d' % i)) (pl, ul) = self.lists_of_len() self.assertEqual(pl.pop(), ul.pop(i), 'popped value') self.assertEqual(pl[:], ul[:], 'after pop') (pl, ul) = self.lists_of_len() def popfcn(x, i): x.pop(i) self.assertRaises(IndexError, popfcn, ul, self.limit) self.assertRaises(IndexError, popfcn, ul, ((-1) - self.limit)) (pl, ul) = self.lists_of_len() for val in range(self.limit): self.assertEqual(pl.index(val), ul.index(val), ('index of %d' % val)) for val in self.limits_plus(2): self.assertEqual(pl.count(val), ul.count(val), ('count %d' % val)) for val in range(self.limit): (pl, ul) = self.lists_of_len() pl.remove(val) ul.remove(val) self.assertEqual(pl[:], ul[:], ('after remove val %d' % val)) def indexfcn(x, v): return x.index(v) def removefcn(x, v): return x.remove(v) self.assertRaises(ValueError, indexfcn, ul, 40) self.assertRaises(ValueError, removefcn, ul, 40)
'Type-restricted list'
def test07_allowed_types(self):
(pl, ul) = self.lists_of_len() ul._allowed = six.integer_types ul[1] = 50 ul[:2] = [60, 70, 80] def setfcn(x, i, v): x[i] = v self.assertRaises(TypeError, setfcn, ul, 2, 'hello') self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), ('hello', 'goodbye'))
'Length limits'
def test08_min_length(self):
(pl, ul) = self.lists_of_len() ul._minlength = 1 def delfcn(x, i): del x[:i] def setfcn(x, i): x[:i] = [] for i in range(((self.limit - ul._minlength) + 1), (self.limit + 1)): self.assertRaises(ValueError, delfcn, ul, i) self.assertRaises(ValueError, setfcn, ul, i) del ul[:ul._minlength] ul._maxlength = 4 for i in range(0, (ul._maxlength - len(ul))): ul.append(i) self.assertRaises(ValueError, ul.append, 10)
'Error on assigning non-iterable to slice'
def test09_iterable_check(self):
(pl, ul) = self.lists_of_len((self.limit + 1)) def setfcn(x, i, v): x[i] = v self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), 2)
'Index check'
def test10_checkindex(self):
(pl, ul) = self.lists_of_len() for i in self.limits_plus(0): if (i < 0): self.assertEqual(ul._checkindex(i), (i + self.limit), '_checkindex(neg index)') else: self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)') for i in (((- self.limit) - 1), self.limit): self.assertRaises(IndexError, ul._checkindex, i) ul._IndexError = TypeError self.assertRaises(TypeError, ul._checkindex, ((- self.limit) - 1))
'Sorting'
def test_11_sorting(self):
(pl, ul) = self.lists_of_len() pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort() ul.sort() self.assertEqual(pl[:], ul[:], 'sort') mid = pl[(len(pl) // 2)] pl.sort(key=(lambda x: ((mid - x) ** 2))) ul.sort(key=(lambda x: ((mid - x) ** 2))) self.assertEqual(pl[:], ul[:], 'sort w/ key') pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort(reverse=True) ul.sort(reverse=True) self.assertEqual(pl[:], ul[:], 'sort w/ reverse') mid = pl[(len(pl) // 2)] pl.sort(key=(lambda x: ((mid - x) ** 2))) ul.sort(key=(lambda x: ((mid - x) ** 2))) self.assertEqual(pl[:], ul[:], 'sort w/ key')
'Arithmetic'
def test_12_arithmetic(self):
(pl, ul) = self.lists_of_len() al = list(range(10, 14)) self.assertEqual(list((pl + al)), list((ul + al)), 'add') self.assertEqual(type(ul), type((ul + al)), 'type of add result') self.assertEqual(list((al + pl)), list((al + ul)), 'radd') self.assertEqual(type(al), type((al + ul)), 'type of radd result') objid = id(ul) pl += al ul += al self.assertEqual(pl[:], ul[:], 'in-place add') self.assertEqual(objid, id(ul), 'in-place add id') for n in ((-1), 0, 1, 3): (pl, ul) = self.lists_of_len() self.assertEqual(list((pl * n)), list((ul * n)), ('mul by %d' % n)) self.assertEqual(type(ul), type((ul * n)), ('type of mul by %d result' % n)) self.assertEqual(list((n * pl)), list((n * ul)), ('rmul by %d' % n)) self.assertEqual(type(ul), type((n * ul)), ('type of rmul by %d result' % n)) objid = id(ul) pl *= n ul *= n self.assertEqual(pl[:], ul[:], ('in-place mul by %d' % n)) self.assertEqual(objid, id(ul), ('in-place mul by %d id' % n)) (pl, ul) = self.lists_of_len() self.assertEqual(pl, ul, 'cmp for equal') self.assertFalse((ul == (pl + [2])), 'cmp for not equal') self.assertTrue((pl >= ul), 'cmp for gte self') self.assertTrue((pl <= ul), 'cmp for lte self') self.assertTrue((ul >= pl), 'cmp for self gte') self.assertTrue((ul <= pl), 'cmp for self lte') self.assertTrue(((pl + [5]) > ul), 'cmp') self.assertTrue(((pl + [5]) >= ul), 'cmp') self.assertTrue((pl < (ul + [2])), 'cmp') self.assertTrue((pl <= (ul + [2])), 'cmp') self.assertTrue(((ul + [5]) > pl), 'cmp') self.assertTrue(((ul + [5]) >= pl), 'cmp') self.assertTrue((ul < (pl + [2])), 'cmp') self.assertTrue((ul <= (pl + [2])), 'cmp') ul_longer = (ul + [2]) ul_longer._IndexError = TypeError ul._IndexError = TypeError self.assertFalse((ul_longer == pl)) self.assertFalse((ul == ul_longer)) self.assertTrue((ul_longer > ul)) pl[1] = 20 self.assertTrue((pl > ul), 'cmp for gt self') self.assertTrue((ul < pl), 'cmp for self lt') pl[1] = (-20) self.assertTrue((pl < ul), 'cmp for lt self') self.assertTrue((pl < ul), 'cmp for lt self')
'Returns the proper null SRID depending on the GEOS version. See the comments in `test_srid` for more details.'
@property def null_srid(self):
info = geos_version_info() if ((info[u'version'] == u'3.0.0') and info[u'release_candidate']): return (-1) else: return None
'Tests out the GEOSBase class.'
def test_base(self):
class FakeGeom1(GEOSBase, ): pass c_float_p = ctypes.POINTER(ctypes.c_float) class FakeGeom2(GEOSBase, ): ptr_type = c_float_p fg1 = FakeGeom1() fg2 = FakeGeom2() fg1.ptr = ctypes.c_void_p() fg1.ptr = None fg2.ptr = c_float_p(ctypes.c_float(5.23)) fg2.ptr = None for fg in (fg1, fg2): self.assertRaises(GEOSException, fg._get_ptr) bad_ptrs = (5, ctypes.c_char_p('foobar')) for bad_ptr in bad_ptrs: self.assertRaises(TypeError, fg1._set_ptr, bad_ptr) self.assertRaises(TypeError, fg2._set_ptr, bad_ptr)
'Testing WKT output.'
def test_wkt(self):
for g in self.geometries.wkt_out: geom = fromstr(g.wkt) self.assertEqual(g.ewkt, geom.wkt)
'Testing HEX output.'
def test_hex(self):
for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode())
'Testing (HEX)EWKB output.'
def test_hexewkb(self):
ogc_hex = '01010000000000000000000000000000000000F03F' ogc_hex_3d = '01010000800000000000000000000000000000F03F0000000000000040' hexewkb_2d = '0101000020E61000000000000000000000000000000000F03F' hexewkb_3d = '01010000A0E61000000000000000000000000000000000F03F0000000000000040' pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) if GEOS_PREPARE: self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz) else: try: hexewkb = pnt_3d.hexewkb except GEOSException: pass else: self.fail(u'Should have raised GEOSException.') self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) if GEOS_PREPARE: self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) else: try: ewkb = pnt_3d.ewkb except GEOSException: pass else: self.fail(u'Should have raised GEOSException') self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
'Testing KML output.'
def test_kml(self):
for tg in self.geometries.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, u'kml', False) if kml: self.assertEqual(kml, geom.kml)
'Testing the Error handlers.'
def test_errors(self):
for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): _ = fromstr(err.wkt) self.assertRaises(GEOSException, GEOSGeometry, memoryview('0')) class NotAGeometry(object, ): pass self.assertRaises(TypeError, GEOSGeometry, NotAGeometry()) self.assertRaises(TypeError, GEOSGeometry, None)
'Testing WKB output.'
def test_wkb(self):
for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex)
'Testing creation from HEX.'
def test_create_hex(self):
for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt)
'Testing creation from WKB.'
def test_create_wkb(self):
for g in self.geometries.hex_wkt: wkb = memoryview(a2b_hex(g.hex.encode())) geom_h = GEOSGeometry(wkb) geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt)
'Testing EWKT.'
def test_ewkt(self):
srids = ((-1), 32140) for srid in srids: for p in self.geometries.polygons: ewkt = (u'SRID=%d;%s' % (srid, p.wkt)) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid)
'Testing GeoJSON input/output (via GDAL).'
@unittest.skipUnless(gdal.HAS_GDAL, u'gdal is required') def test_json(self):
for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if (not hasattr(g, u'not_equal')): self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))
'Testing the fromfile() factory.'
def test_fromfile(self):
ref_pnt = GEOSGeometry(u'POINT(5 23)') wkt_f = BytesIO() wkt_f.write(force_bytes(ref_pnt.wkt)) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt)
'Testing equivalence.'
def test_eq(self):
p = fromstr(u'POINT(5 23)') self.assertEqual(p, p.wkt) self.assertNotEqual(p, u'foo') ls = fromstr(u'LINESTRING(0 0, 1 1, 5 5)') self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, u'bar') for g in (p, ls): self.assertNotEqual(g, None) self.assertNotEqual(g, {u'foo': u'bar'}) self.assertNotEqual(g, False)
'Testing Point objects.'
def test_points(self):
prev = fromstr(u'POINT(0 0)') for p in self.geometries.points: pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, u'Point') self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(True, (pnt == fromstr(p.wkt))) self.assertEqual(False, (pnt == prev)) self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) if hasattr(p, u'z'): self.assertEqual(True, pnt.hasz) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertEqual(False, pnt.hasz) self.assertEqual(None, pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) self.assertEqual(p.centroid, pnt.centroid.tuple) pnt2 = Point(tup_args) pnt3 = Point(*tup_args) self.assertEqual(True, (pnt == pnt2)) self.assertEqual(True, (pnt == pnt3)) pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt
'Testing MultiPoint objects.'
def test_multipoints(self):
for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, u'MultiPoint') self.assertEqual(mpnt.geom_typeid, 4) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) self.assertRaises(GEOSIndexError, mpnt.__getitem__, len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple((m.tuple for m in mpnt))) for p in mpnt: self.assertEqual(p.geom_type, u'Point') self.assertEqual(p.geom_typeid, 0) self.assertEqual(p.empty, False) self.assertEqual(p.valid, True)
'Testing LineString objects.'
def test_linestring(self):
prev = fromstr(u'POINT(0 0)') for l in self.geometries.linestrings: ls = fromstr(l.wkt) self.assertEqual(ls.geom_type, u'LineString') self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.empty, False) self.assertEqual(ls.ring, False) if hasattr(l, u'centroid'): self.assertEqual(l.centroid, ls.centroid.tuple) if hasattr(l, u'tup'): self.assertEqual(l.tup, ls.tuple) self.assertEqual(True, (ls == fromstr(l.wkt))) self.assertEqual(False, (ls == prev)) self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls)) prev = ls self.assertEqual(ls, LineString(ls.tuple)) self.assertEqual(ls, LineString(*ls.tuple)) self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) self.assertEqual(ls.wkt, LineString(*tuple((Point(tup) for tup in ls.tuple))).wkt) if numpy: self.assertEqual(ls, LineString(numpy.array(ls.tuple)))
'Testing MultiLineString objects.'
def test_multilinestring(self):
prev = fromstr(u'POINT(0 0)') for l in self.geometries.multilinestrings: ml = fromstr(l.wkt) self.assertEqual(ml.geom_type, u'MultiLineString') self.assertEqual(ml.geom_typeid, 5) self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9) self.assertEqual(True, (ml == fromstr(l.wkt))) self.assertEqual(False, (ml == prev)) prev = ml for ls in ml: self.assertEqual(ls.geom_type, u'LineString') self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.empty, False) self.assertRaises(GEOSIndexError, ml.__getitem__, len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple((s.clone() for s in ml))).wkt) self.assertEqual(ml, MultiLineString(*tuple((LineString(s.tuple) for s in ml))))
'Testing LinearRing objects.'
def test_linearring(self):
for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, u'LinearRing') self.assertEqual(lr.geom_typeid, 2) self.assertEqual(rr.n_p, len(lr)) self.assertEqual(True, lr.valid) self.assertEqual(False, lr.empty) self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
'Testing `from_bbox` class method.'
def test_polygons_from_bbox(self):
bbox = ((-180), (-90), 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) x = 3.141592653589793 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[(-1)] self.assertEqual(format(x, u'.13f'), format(y, u'.13f'))
'Testing Polygon objects.'
def test_polygons(self):
prev = fromstr(u'POINT(0 0)') for p in self.geometries.polygons: poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, u'Polygon') self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.empty, False) self.assertEqual(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual((p.n_i + 1), len(poly)) self.assertEqual(p.n_p, poly.num_points) self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) self.assertEqual(True, (poly == fromstr(p.wkt))) self.assertEqual(False, (poly == prev)) self.assertEqual(True, (poly != prev)) ring = poly.exterior_ring self.assertEqual(ring.geom_type, u'LinearRing') self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly)) self.assertRaises(GEOSIndexError, poly.__setitem__, len(poly), False) self.assertRaises(GEOSIndexError, poly.__getitem__, (((-1) * len(poly)) - 1)) for r in poly: self.assertEqual(r.geom_type, u'LinearRing') self.assertEqual(r.geom_typeid, 2) self.assertRaises(TypeError, Polygon, 0, [1, 2, 3]) self.assertRaises(TypeError, Polygon, u'foo') rings = tuple((r for r in poly)) self.assertEqual(poly, Polygon(rings[0], rings[1:])) ring_tuples = tuple((r.tuple for r in poly)) self.assertEqual(poly, Polygon(*ring_tuples)) self.assertEqual(poly.wkt, Polygon(*tuple((r for r in poly))).wkt) self.assertEqual(poly.wkt, Polygon(*tuple((LinearRing(r.tuple) for r in poly))).wkt)
'Testing MultiPolygon objects.'
def test_multipolygons(self):
prev = fromstr(u'POINT (0 0)') for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, u'MultiPolygon') self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, u'Polygon') self.assertEqual(p.geom_typeid, 3) self.assertEqual(p.valid, True) self.assertEqual(mpoly.wkt, MultiPolygon(*tuple((poly.clone() for poly in mpoly))).wkt)
'Testing Geometry __del__() on rings and polygons.'
def test_memory_hijinks(self):
poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] del poly (s1, s2) = (str(ring1), str(ring2))