desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Testing the \'same_as\' and \'equals\' lookup types.'
| def test14_equals(self):
| pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326)
c1 = City.objects.get(point=pnt)
c2 = City.objects.get(point__same_as=pnt)
c3 = City.objects.get(point__equals=pnt)
for c in [c1, c2, c3]:
self.assertEqual('Houston', c.name)
|
'Testing the \'relate\' lookup type.'
| @no_mysql
def test15_relate(self):
| pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847)
pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326)
self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo'))
for (bad_args, e) in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), Val... |
'Testing creating a model instance and the geometry being None'
| def test16_createnull(self):
| c = City()
self.assertEqual(c.point, None)
|
'Testing the `unionagg` (aggregate union) GeoManager method.'
| @no_mysql
def test17_unionagg(self):
| tx = Country.objects.get(name='Texas').mpoly
union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)')
union2 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)')
qs = City.objects.filter(point__within=tx)
self.assertRaises(TypeError, qs.unionagg, 'name')
... |
'Testing the general GeometryField.'
| @no_spatialite
def test18_geometryfield(self):
| Feature(name='Point', geom=Point(1, 1)).save()
Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save()
Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save()
Feature(name='GeometryCollection', geom=GeometryCollection(Point(2, 2), LineString((0... |
'Testing the `centroid` GeoQuerySet method.'
| @no_mysql
def test19_centroid(self):
| qs = State.objects.exclude(poly__isnull=True).centroid()
if oracle:
tol = 0.1
elif spatialite:
tol = 1e-06
else:
tol = 1e-09
for s in qs:
self.assertEqual(True, s.poly.centroid.equals_exact(s.centroid, tol))
|
'Testing the `point_on_surface` GeoQuerySet method.'
| @no_mysql
def test20_pointonsurface(self):
| if oracle:
ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326), 'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326)}
elif (postgis or spatialite):
ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface, 'Texas': Co... |
'Testing the `scale` GeoQuerySet method.'
| @no_mysql
@no_oracle
def test21_scale(self):
| (xfac, yfac) = (2, 3)
tol = 5
qs = Country.objects.scale(xfac, yfac, model_att='scaled')
for c in qs:
for (p1, p2) in zip(c.mpoly, c.scaled):
for (r1, r2) in zip(p1, p2):
for (c1, c2) in zip(r1.coords, r2.coords):
self.assertAlmostEqual((c1[0] * xf... |
'Testing the `translate` GeoQuerySet method.'
| @no_mysql
@no_oracle
def test22_translate(self):
| (xfac, yfac) = (5, (-23))
qs = Country.objects.translate(xfac, yfac, model_att='translated')
for c in qs:
for (p1, p2) in zip(c.mpoly, c.translated):
for (r1, r2) in zip(p1, p2):
for (c1, c2) in zip(r1.coords, r2.coords):
self.assertAlmostEqual((c1[0] ... |
'Testing the `num_geom` GeoQuerySet method.'
| @no_mysql
def test23_numgeom(self):
| for c in Country.objects.num_geom():
self.assertEqual(2, c.num_geom)
for c in City.objects.filter(point__isnull=False).num_geom():
if postgis:
self.assertEqual(None, c.num_geom)
else:
self.assertEqual(1, c.num_geom)
|
'Testing the `num_points` GeoQuerySet method.'
| @no_mysql
@no_spatialite
def test24_numpoints(self):
| for c in Country.objects.num_points():
self.assertEqual(c.mpoly.num_points, c.num_points)
if (not oracle):
for c in City.objects.num_points():
self.assertEqual(1, c.num_points)
|
'Testing the `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods.'
| @no_mysql
def test25_geoset(self):
| geom = Point(5, 23)
tol = 1
qs = Country.objects.all().difference(geom).sym_difference(geom).union(geom)
if spatialite:
qs = qs.exclude(name='Texas')
else:
qs = qs.intersection(geom)
for c in qs:
if oracle:
pass
else:
self.assertEqual(c.mpo... |
'Test GeoQuerySet methods on inherited Geometry fields.'
| @no_mysql
def test26_inherited_geofields(self):
| mansfield = PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)')
qs = PennsylvaniaCity.objects.transform(32128)
self.assertEqual(1, qs.count())
for pc in qs:
self.assertEqual(32128, pc.point.srid)
|
'Testing GeoQuerySet.snap_to_grid().'
| @no_mysql
@no_oracle
@no_spatialite
def test27_snap_to_grid(self):
| for bad_args in ((), range(3), range(5)):
self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args)
for bad_args in (('1.0',), (1.0, None), tuple(map(unicode, range(4)))):
self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args)
wkt = 'MULTIPOLYGON(((12.41580 43.... |
'Testing GeoQuerySet.reverse_geom().'
| @no_mysql
@no_spatialite
def test28_reverse(self):
| coords = [((-95.363151), 29.763374), ((-95.448601), 29.713803)]
Track.objects.create(name='Foo', line=LineString(coords))
t = Track.objects.reverse_geom().get(name='Foo')
coords.reverse()
self.assertEqual(tuple(coords), t.reverse_geom.coords)
if oracle:
self.assertRaises(TypeError, State... |
'Testing GeoQuerySet.force_rhr().'
| @no_mysql
@no_oracle
@no_spatialite
def test29_force_rhr(self):
| rings = (((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)))
rhr_rings = (((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)))
State.objects.create(name='Foo', poly=Polygon(*rings))
s = State.objects.force_rhr().get(name='Foo')
self.assertEqual(rhr_rings, s.force_rhr.c... |
'Testing GeoQuerySet.geohash().'
| @no_mysql
@no_oracle
@no_spatialite
def test29_force_rhr(self):
| if (not connection.ops.geohash):
return
ref_hash = '9vk1mfq8jx0c8e0386z6'
h1 = City.objects.geohash().get(name='Houston')
h2 = City.objects.geohash(precision=5).get(name='Houston')
self.assertEqual(ref_hash, h1.geohash)
self.assertEqual(ref_hash[:5], h2.geohash)
|
'Testing GeoQuerySet.update(), see #10411.'
| def test01_update(self):
| pnt = City.objects.get(name='Pueblo').point
bak = pnt.clone()
pnt.y += 0.005
pnt.x += 0.005
City.objects.filter(name='Pueblo').update(point=pnt)
self.assertEqual(pnt, City.objects.get(name='Pueblo').point)
City.objects.filter(name='Pueblo').update(point=bak)
self.assertEqual(bak, City.ob... |
'Testing `render_to_kmz` with non-ASCII data, see #11624.'
| def test02_kmz(self):
| name = '\xc3\x85land Islands'.decode('iso-8859-1')
places = [{'name': name, 'description': name, 'kml': '<Point><coordinates>5.0,23.0</coordinates></Point>'}]
kmz = render_to_kmz('gis/kml/placemarks.kml', {'places': places})
|
'Testing `extent` on a table with a single point, see #11827.'
| @no_spatialite
@no_mysql
def test03_extent(self):
| pnt = City.objects.get(name='Pueblo').point
ref_ext = (pnt.x, pnt.y, pnt.x, pnt.y)
extent = City.objects.filter(name='Pueblo').extent()
for (ref_val, val) in zip(ref_ext, extent):
self.assertAlmostEqual(ref_val, val, 4)
|
'Testing LayerMapping initialization.'
| def test01_init(self):
| bad1 = copy(city_mapping)
bad1['foobar'] = 'FooField'
bad2 = copy(city_mapping)
bad2['name'] = 'Nombre'
bad3 = copy(city_mapping)
bad3['point'] = 'CURVE'
for bad_map in (bad1, bad2, bad3):
try:
lm = LayerMapping(City, city_shp, bad_map)
except LayerMapError:
... |
'Test LayerMapping import of a simple point shapefile.'
| def test02_simple_layermap(self):
| lm = LayerMapping(City, city_shp, city_mapping)
lm.save()
self.assertEqual(3, City.objects.count())
ds = DataSource(city_shp)
layer = ds[0]
for feat in layer:
city = City.objects.get(name=feat['Name'].value)
self.assertEqual(feat['Population'].value, city.population)
self... |
'Testing the `strict` keyword, and import of a LineString shapefile.'
| def test03_layermap_strict(self):
| try:
lm = LayerMapping(Interstate, inter_shp, inter_mapping)
lm.save(silent=True, strict=True)
except InvalidDecimal:
if mysql:
Interstate.objects.all().delete()
else:
self.fail('Should have failed on strict import with invalid decimal v... |
'Helper function for ensuring the integrity of the mapped County models.'
| def county_helper(self, county_feat=True):
| for (name, n, st) in zip(NAMES, NUMS, STATES):
c = County.objects.get(name=name)
self.assertEqual(n, len(c.mpoly))
self.assertEqual(st, c.state.name)
if county_feat:
qs = CountyFeat.objects.filter(name=name)
self.assertEqual(n, qs.count())
|
'Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings.'
| def test04_layermap_unique_multigeometry_fk(self):
| try:
lm = LayerMapping(County, co_shp, co_mapping, transform=False)
lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269)
lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83')
for arg in ('name', ('name', 'mpoly')):
lm = LayerMapping(County, co_shp, c... |
'Tests the `fid_range` keyword and the `step` keyword of .save().'
| def test05_test_fid_range_step(self):
| def clear_counties():
County.objects.all().delete()
lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
clear_counties()
bad_ranges = (5.0, 'foo', co_shp)
for bad in bad_ranges:
self.assertRaises(TypeError, lm.save, fid_range=bad)
fr = (3, 5)
self.as... |
'Tests LayerMapping on inherited models. See #12093.'
| def test06_model_inheritance(self):
| icity_mapping = {'name': 'Name', 'population': 'Population', 'density': 'Density', 'point': 'POINT', 'dt': 'Created'}
lm1 = LayerMapping(ICity1, city_shp, icity_mapping)
lm1.save()
lm2 = LayerMapping(ICity2, city_shp, icity_mapping)
lm2.save()
self.assertEqual(6, ICity1.objects.count())
self... |
'Testing initialisation from valid units'
| def testInit(self):
| d = Distance(m=100)
self.assertEqual(d.m, 100)
(d1, d2, d3) = (D(m=100), D(meter=100), D(metre=100))
for d in (d1, d2, d3):
self.assertEqual(d.m, 100)
d = D(nm=100)
self.assertEqual(d.m, 185200)
(y1, y2, y3) = (D(yd=100), D(yard=100), D(Yard=100))
for d in (y1, y2, y3):
s... |
'Testing initialisation from invalid units'
| def testInitInvalid(self):
| self.assertRaises(AttributeError, D, banana=100)
|
'Testing access in different units'
| def testAccess(self):
| d = D(m=100)
self.assertEqual(d.km, 0.1)
self.assertAlmostEqual(d.ft, 328.084, 3)
|
'Testing access in invalid units'
| def testAccessInvalid(self):
| d = D(m=100)
self.failIf(hasattr(d, 'banana'))
|
'Test addition & subtraction'
| def testAddition(self):
| d1 = D(m=100)
d2 = D(m=200)
d3 = (d1 + d2)
self.assertEqual(d3.m, 300)
d3 += d1
self.assertEqual(d3.m, 400)
d4 = (d1 - d2)
self.assertEqual(d4.m, (-100))
d4 -= d1
self.assertEqual(d4.m, (-200))
try:
d5 = (d1 + 1)
except TypeError as e:
pass
else:
... |
'Test multiplication & division'
| def testMultiplication(self):
| d1 = D(m=100)
d3 = (d1 * 2)
self.assertEqual(d3.m, 200)
d3 = (2 * d1)
self.assertEqual(d3.m, 200)
d3 *= 5
self.assertEqual(d3.m, 1000)
d4 = (d1 / 2)
self.assertEqual(d4.m, 50)
d4 /= 5
self.assertEqual(d4.m, 10)
a5 = (d1 * D(m=10))
self.assert_(isinstance(a5, Area))
... |
'Testing default units during maths'
| def testUnitConversions(self):
| d1 = D(m=100)
d2 = D(km=1)
d3 = (d1 + d2)
self.assertEqual(d3._default_unit, 'm')
d4 = (d2 + d1)
self.assertEqual(d4._default_unit, 'km')
d5 = (d1 * 2)
self.assertEqual(d5._default_unit, 'm')
d6 = (d1 / 2)
self.assertEqual(d6._default_unit, 'm')
|
'Testing comparisons'
| def testComparisons(self):
| d1 = D(m=100)
d2 = D(km=1)
d3 = D(km=0)
self.assert_((d2 > d1))
self.assert_((d1 == d1))
self.assert_((d1 < d2))
self.failIf(d3)
|
'Testing conversion to strings'
| def testUnitsStr(self):
| d1 = D(m=100)
d2 = D(km=3.5)
self.assertEqual(str(d1), '100.0 m')
self.assertEqual(str(d2), '3.5 km')
self.assertEqual(repr(d1), 'Distance(m=100.0)')
self.assertEqual(repr(d2), 'Distance(km=3.5)')
|
'Testing the `unit_attname` class method'
| def testUnitAttName(self):
| unit_tuple = [('Yard', 'yd'), ('Nautical Mile', 'nm'), ('German legal metre', 'german_m'), ('Indian yard', 'indian_yd'), ('Chain (Sears)', 'chain_sears'), ('Chain', 'chain')]
for (nm, att) in unit_tuple:
self.assertEqual(att, D.unit_attname(nm))
|
'Testing initialisation from valid units'
| def testInit(self):
| a = Area(sq_m=100)
self.assertEqual(a.sq_m, 100)
a = A(sq_m=100)
self.assertEqual(a.sq_m, 100)
a = A(sq_mi=100)
self.assertEqual(a.sq_m, 258998811.0336)
|
'Testing initialisation from invalid units'
| def testInitInvaliA(self):
| self.assertRaises(AttributeError, A, banana=100)
|
'Testing access in different units'
| def testAccess(self):
| a = A(sq_m=100)
self.assertEqual(a.sq_km, 0.0001)
self.assertAlmostEqual(a.sq_ft, 1076.391, 3)
|
'Testing access in invalid units'
| def testAccessInvaliA(self):
| a = A(sq_m=100)
self.failIf(hasattr(a, 'banana'))
|
'Test addition & subtraction'
| def testAddition(self):
| a1 = A(sq_m=100)
a2 = A(sq_m=200)
a3 = (a1 + a2)
self.assertEqual(a3.sq_m, 300)
a3 += a1
self.assertEqual(a3.sq_m, 400)
a4 = (a1 - a2)
self.assertEqual(a4.sq_m, (-100))
a4 -= a1
self.assertEqual(a4.sq_m, (-200))
try:
a5 = (a1 + 1)
except TypeError as e:
pa... |
'Test multiplication & division'
| def testMultiplication(self):
| a1 = A(sq_m=100)
a3 = (a1 * 2)
self.assertEqual(a3.sq_m, 200)
a3 = (2 * a1)
self.assertEqual(a3.sq_m, 200)
a3 *= 5
self.assertEqual(a3.sq_m, 1000)
a4 = (a1 / 2)
self.assertEqual(a4.sq_m, 50)
a4 /= 5
self.assertEqual(a4.sq_m, 10)
try:
a5 = (a1 * A(sq_m=1))
exce... |
'Testing default units during maths'
| def testUnitConversions(self):
| a1 = A(sq_m=100)
a2 = A(sq_km=1)
a3 = (a1 + a2)
self.assertEqual(a3._default_unit, 'sq_m')
a4 = (a2 + a1)
self.assertEqual(a4._default_unit, 'sq_km')
a5 = (a1 * 2)
self.assertEqual(a5._default_unit, 'sq_m')
a6 = (a1 / 2)
self.assertEqual(a6._default_unit, 'sq_m')
|
'Testing comparisons'
| def testComparisons(self):
| a1 = A(sq_m=100)
a2 = A(sq_km=1)
a3 = A(sq_km=0)
self.assert_((a2 > a1))
self.assert_((a1 == a1))
self.assert_((a1 < a2))
self.failIf(a3)
|
'Testing conversion to strings'
| def testUnitsStr(self):
| a1 = A(sq_m=100)
a2 = A(sq_km=3.5)
self.assertEqual(str(a1), '100.0 sq_m')
self.assertEqual(str(a2), '3.5 sq_km')
self.assertEqual(repr(a1), 'Area(sq_m=100.0)')
self.assertEqual(repr(a2), 'Area(sq_km=3.5)')
|
'Testing `select_related` on geographic models (see #7126).'
| def test02_select_related(self):
| qs1 = City.objects.all()
qs2 = City.objects.select_related()
qs3 = City.objects.select_related('location')
cities = (('Aurora', 'TX', (-97.516111), 33.058333), ('Roswell', 'NM', (-104.528056), 33.387222), ('Kecksburg', 'PA', (-79.460734), 40.18476))
for qs in (qs1, qs2, qs3):
for (ref, c) in... |
'Testing the `transform` GeoQuerySet method on related geographic models.'
| @no_mysql
def test03_transform_related(self):
| tol = 0
def check_pnt(ref, pnt):
self.assertAlmostEqual(ref.x, pnt.x, tol)
self.assertAlmostEqual(ref.y, pnt.y, tol)
self.assertEqual(ref.srid, pnt.srid)
transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'), ('Roswell', 2257, 'POINT(481902.189077221 86... |
'Testing the `extent` GeoQuerySet aggregates on related geographic models.'
| @no_mysql
@no_spatialite
def test04a_related_extent_aggregate(self):
| aggs = City.objects.aggregate(Extent('location__point'))
all_extent = ((-104.528056), 29.763374, (-79.460734), 40.18476)
txpa_extent = ((-97.516111), 29.763374, (-79.460734), 40.18476)
e1 = City.objects.extent(field_name='location__point')
e2 = City.objects.exclude(state='NM').extent(field_name='loc... |
'Testing the `unionagg` GeoQuerySet aggregates on related geographic models.'
| @no_mysql
def test04b_related_union_aggregate(self):
| aggs = City.objects.aggregate(Union('location__point'))
p1 = Point((-104.528056), 33.387222)
p2 = Point((-97.516111), 33.058333)
p3 = Point((-79.460734), 40.18476)
p4 = Point((-96.801611), 32.782057)
p5 = Point((-95.363151), 29.763374)
if oracle:
ref_u1 = MultiPoint(p4, p5, p3, p1, p... |
'Testing that calling select_related on a query over a model with an FK to a model subclass works'
| def test05_select_related_fk_to_subclass(self):
| l = list(DirectoryEntry.objects.all().select_related())
|
'Testing F() expressions on GeometryFields.'
| def test06_f_expressions(self):
| b1 = GEOSGeometry('POLYGON((-97.501205 33.052520,-97.501205 33.052576,-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326)
pcity = City.objects.get(name='Aurora')
c1 = pcity.location.point
c2 = c1.transform(2276, clone=True)
b2 = c2.buffer(100)
p1 = Parcel... |
'Testing values() and values_list() and GeoQuerySets.'
| def test07_values(self):
| gqs = Location.objects.all()
gvqs = Location.objects.values()
gvlqs = Location.objects.values_list()
for (m, d, t) in zip(gqs, gvqs, gvlqs):
self.failUnless(isinstance(d['point'], Geometry))
self.failUnless(isinstance(t[1], Geometry))
self.assertEqual(m.point, d['point'])
... |
'Testing defer() and only() on Geographic models.'
| def test08_defer_only(self):
| qs = Location.objects.all()
def_qs = Location.objects.defer('point')
for (loc, def_loc) in zip(qs, def_qs):
self.assertEqual(loc.point, def_loc.point)
|
'Ensuring correct primary key column is selected across relations. See #10757.'
| def test09_pk_relations(self):
| city_ids = (1, 2, 3, 4, 5)
loc_ids = (1, 2, 3, 5, 4)
ids_qs = City.objects.order_by('id').values('id', 'location__id')
for (val_dict, c_id, l_id) in zip(ids_qs, city_ids, loc_ids):
self.assertEqual(val_dict['id'], c_id)
self.assertEqual(val_dict['location__id'], l_id)
|
'Testing the combination of two GeoQuerySets. See #10807.'
| def test10_combine(self):
| buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1)
buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1)
qs1 = City.objects.filter(location__point__within=buf1)
qs2 = City.objects.filter(location__point__within=buf2)
combined = (qs1 | qs2)
names = [c.name for c in c... |
'Ensuring GeoQuery objects are unpickled correctly. See #10839.'
| def test11_geoquery_pickle(self):
| import pickle
from django.contrib.gis.db.models.sql import GeoQuery
qs = City.objects.all()
q_str = pickle.dumps(qs.query)
q = pickle.loads(q_str)
self.assertEqual(GeoQuery, q.__class__)
|
'Testing `Count` aggregate use with the `GeoManager` on geo-fields.'
| @no_oracle
def test12a_count(self):
| dallas = City.objects.get(name='Dallas')
loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id)
self.assertEqual(2, loc.num_cities)
|
'Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087.'
| def test12b_count(self):
| qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1)
self.assertEqual(1, len(qs))
self.assertEqual(3, qs[0].num_books)
self.assertEqual(1, len(vqs))
self.assertEqual(3, vqs[0]... |
'Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381.'
| @no_oracle
def test13_select_related_null_fk(self):
| no_author = Book.objects.create(title='Without Author')
b = Book.objects.select_related('author').get(title='Without Author')
self.assertEqual(None, b.author)
|
'Testing the `collect` GeoQuerySet method and `Collect` aggregate.'
| @no_mysql
@no_oracle
@no_spatialite
def test14_collect(self):
| ref_geom = GEOSGeometry('MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,-95.363151 29.763374,-96.801611 32.782057)')
c1 = City.objects.filter(state='TX').collect(field_name='location__point')
c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__colle... |
'Testing doing select_related on the related name manager of a unique FK. See #13934.'
| def test15_invalid_select_related(self):
| qs = Article.objects.select_related('author__article')
sql = str(qs.query)
|
'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 (-... |
'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('... |
'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['no_geom'])
try:
geom = GEOSGeometry(value)
except:
raise forms.ValidationError(self.error_messages['invalid_geom'])
if ((str(... |
'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_resolutio... |
'Injects OpenLayers JavaScript into the admin.'
| 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... |
'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(s... | 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 (le... |
'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
return GEOSGeometry(('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % (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!
... | 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
... |
'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()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.