desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the string representation. If GDAL is installed, it will be \'pretty\' OGC WKT.'
def __unicode__(self):
try: return unicode(self.srs) except: return unicode(self.wkt)
'Checks if the given aggregate name is supported (that is, if it\'s in `self.valid_aggregates`).'
def check_aggregate_support(self, aggregate):
agg_name = aggregate.__class__.__name__ return (agg_name in self.valid_aggregates)
'Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)".'
def convert_extent(self, box):
(ll, ur) = box[4:(-1)].split(',') (xmin, ymin) = map(float, ll.split()) (xmax, ymax) = map(float, ur.split()) return (xmin, ymin, xmax, ymax)
'Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)".'
def convert_extent3d(self, box3d):
(ll, ur) = box3d[6:(-1)].split(',') (xmin, ymin, zmin) = map(float, ll.split()) (xmax, ymax, zmax) = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax)
'Converts the geometry returned from PostGIS aggretates.'
def convert_geom(self, hex, geo_field):
if hex: return Geometry(hex) else: return None
'Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead.'
def geo_db_type(self, f):
if f.geography: if (not self.geography): raise NotImplementedError('PostGIS 1.5 required for geography column support.') if (f.srid != 4326): raise NotImplementedError('PostGIS 1.5 supports geography columns only with an SRID of ...
'Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what\'s available on projected geometry columns. In addition, it has to take int...
def get_distance(self, f, dist_val, lookup_type):
if (len(dist_val) == 1): (value, option) = (dist_val[0], None) else: (value, option) = dist_val geodetic = f.geodetic(self.connection) geography = (f.geography and self.geography) if isinstance(value, Distance): if geography: dist_param = value.m elif geod...
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call.'
def get_geom_placeholder(self, f, value):
if ((value is None) or (value.srid == f.srid)): placeholder = '%s' else: placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) if hasattr(value, 'expression'): placeholder = ((placeholder % '%s.%s') % tuple(map(self.quote_name, value.cols[value.expression]))) return placeho...
'Helper routine for calling PostGIS functions and returning their result.'
def _get_postgis_func(self, func):
cursor = self.connection._cursor() try: cursor.execute(('SELECT %s()' % func)) row = cursor.fetchone() except: raise finally: self.connection.close() return row[0]
'Returns the version of the GEOS library used with PostGIS.'
def postgis_geos_version(self):
return self._get_postgis_func('postgis_geos_version')
'Returns the version number of the PostGIS library used with PostgreSQL.'
def postgis_lib_version(self):
return self._get_postgis_func('postgis_lib_version')
'Returns the version of the PROJ.4 library used with PostGIS.'
def postgis_proj_version(self):
return self._get_postgis_func('postgis_proj_version')
'Returns PostGIS version number and compile-time options.'
def postgis_version(self):
return self._get_postgis_func('postgis_version')
'Returns PostGIS version number and compile-time options.'
def postgis_full_version(self):
return self._get_postgis_func('postgis_full_version')
'Returns the PostGIS version as a tuple (version string, major, minor, subminor).'
def postgis_version_tuple(self):
version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception(('Could not parse PostGIS version string: %s' % version))...
'Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers.'
def proj_version_tuple(self):
proj_regex = re.compile('(\\d+)\\.(\\d+)\\.(\\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostG...
'Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type.'
def num_params(self, lookup_type, num_param):
def exactly_two(np): return (np == 2) def two_to_three(np): return ((np >= 2) and (np <= 3)) if ((lookup_type in self.distance_functions) and (lookup_type != 'dwithin')): return two_to_three(num_param) else: return exactly_two(num_param)
'Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) if (lookup_type in self.geometry_operators): if (field.geography and (not (lookup_type in self.geography_operators))): raise ValueError(('PostGIS geography does not support the "%s" lookup.' % ...
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__ if (not self.check_aggregate_support(agg)): raise NotImplementedError(('%s spatial aggregate is not implmented for this backend.' % agg_name)) agg_name = agg_name.lower() if (agg_name == 'union'): agg_name += 'agg' sql_templat...
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'f_table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'f_geometry_column'
'Initializes on the geometry.'
def __init__(self, geom):
self.ewkb = str(geom.ewkb) self.srid = geom.srid
'Returns a properly quoted string for use in PostgreSQL/PostGIS.'
def getquoted(self):
return ('ST_GeomFromEWKB(E%s)' % Binary(self.ewkb))
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table ...
'Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported).'
def get_postgis_types(self):
cursor = self.connection.cursor() oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s' try: cursor.execute(oid_sql, ('geometry',)) GEOM_TYPE = cursor.fetchone()[0] postgis_types = {GEOM_TYPE: 'GeometryField'} if self.connection.ops.geography: ...
'The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it\'s a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type,'
def get_geometry_type(self, table_name, geo_col):
cursor = self.connection.cursor() try: try: cursor.execute('SELECT "coord_dimension", "srid", "type" FROM "geometry_columns" WHERE "f_table_name"=%s AND "f_geometry_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if (not row): ...
'Checks if the given aggregate name is supported (that is, if it\'s in `self.valid_aggregates`).'
def check_aggregate_support(self, aggregate):
agg_name = aggregate.__class__.__name__ return (agg_name in self.valid_aggregates)
'Converts geometry WKT returned from a SpatiaLite aggregate.'
def convert_geom(self, wkt, geo_field):
if wkt: return Geometry(wkt, geo_field.srid) else: return None
'Returns None because geometry columnas are added via the `AddGeometryColumn` stored procedure on SpatiaLite.'
def geo_db_type(self, f):
return None
'Returns the distance parameters for the given geometry field, lookup value, and lookup type. SpatiaLite only supports regular cartesian-based queries (no spheroid/sphere calculations for point geometries like PostGIS).'
def get_distance(self, f, value, lookup_type):
if (not value): return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError('SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system. Distance ob...
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the Transform() and GeomFromText() function call(s).'
def get_geom_placeholder(self, f, value):
def transform_value(value, srid): return (not ((value is None) or (value.srid == srid))) if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) else: placeholder = '%s' return ((place...
'Helper routine for calling SpatiaLite functions and returning their result.'
def _get_spatialite_func(self, func):
cursor = self.connection._cursor() try: cursor.execute(('SELECT %s' % func)) row = cursor.fetchone() except: raise finally: cursor.close() return row[0]
'Returns the version of GEOS used by SpatiaLite as a string.'
def geos_version(self):
return self._get_spatialite_func('geos_version()')
'Returns the version of the PROJ.4 library used by SpatiaLite.'
def proj4_version(self):
return self._get_spatialite_func('proj4_version()')
'Returns the SpatiaLite library version as a string.'
def spatialite_version(self):
return self._get_spatialite_func('spatialite_version()')
'Returns the SpatiaLite version as a tuple (version string, major, minor, subminor).'
def spatialite_version_tuple(self):
try: version = self.spatialite_version() except DatabaseError: version = None try: tmp = self._get_spatialite_func("X(GeomFromText('POINT(1 1)'))") if (tmp == 1.0): version = '2.3.0' except DatabaseError: pass if (ver...
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__ if (not self.check_aggregate_support(agg)): raise NotImplementedError(('%s spatial aggregate is not implmented for this backend.' % agg_name)) agg_name = agg_name.lower() if (agg_name == 'union'): agg_name += 'agg' sql_templat...
'Returns the SpatiaLite-specific SQL for the given lookup value [a tuple of (alias, column, db_type)], lookup type, lookup value, the model field, and the quoting function.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) if (lookup_type in self.geometry_functions): tmp = self.geometry_functions[lookup_type] if isinstance(tmp, tuple): (op, arg_type) = tmp if (not isinstance(value, (tuple, list))): ...
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'f_table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'f_geometry_column'
'Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. This method is overloaded to load up the SpatiaLite initialization SQL prior to calling the `syncdb` command.'
def create_test_db(self, verbosity=1, autoclobber=False):
if (verbosity >= 1): print ("Creating test database '%s'..." % self.connection.alias) test_database_name = self._create_test_db(verbosity, autoclobber) self.connection.close() self.connection.settings_dict['NAME'] = test_database_name can_rollback = self._rollback_works() self.c...
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table ...
'This routine loads up the SpatiaLite SQL file.'
def load_spatialite_sql(self):
spatialite_sql = self.spatialite_init_file() if (not os.path.isfile(spatialite_sql)): raise ImproperlyConfigured(('Could not find the required SpatiaLite initialization SQL file (necessary for testing): %s' % spatialite_sql)) sql_fh = open(spatialite_sql, 'r') ...
'The placeholder here has to include MySQL\'s WKT constructor. Because MySQL does not support spatial transformations, there is no need to modify the placeholder based on the contents of the given value.'
def get_geom_placeholder(self, value, srid):
if hasattr(value, 'expression'): placeholder = ('%s.%s' % tuple(map(self.quote_name, value.cols[value.expression]))) else: placeholder = ('%s(%%s)' % self.from_text) return placeholder
'Test initialization of distance models.'
def test01_init(self):
self.assertEqual(9, SouthTexasCity.objects.count()) self.assertEqual(9, SouthTexasCityFt.objects.count()) self.assertEqual(11, AustraliaCity.objects.count()) self.assertEqual(4, SouthTexasZipcode.objects.count()) self.assertEqual(4, CensusZipcode.objects.count()) self.assertEqual(1, Interstate.o...
'Testing the `dwithin` lookup type.'
@no_spatialite def test02_dwithin(self):
tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)] au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)] tx_cities = ['Downtown Houston', 'Southside Place'] au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong'] for dist in tx_dists: if isinstance(dist, tuple): (d...
'Testing the `distance` GeoQuerySet method on projected coordinate systems.'
def test03a_distance_method(self):
lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326) m_distances = [147075.069813, 139630.198056, 140888.552826, 138809.684197, 158309.246259, 212183.594374, 70870.188967, 165337.758878, 139196.085105] ft_distances = [482528.79154625, 458103.408123001, 462231.860397575, 455411.438904354, 519386.2...
'Testing the `distance` GeoQuerySet method on geodetic coordnate systems.'
@no_spatialite def test03b_distance_method(self):
if oracle: tol = 2 else: tol = 5 ls = LineString(((150.902, (-34.4245)), (150.87, (-34.5789)))) if (oracle or connection.ops.geography): distances = [1120954.92533513, 140575.720018241, 640396.662906304, 60580.9693849269, 972807.955955075, 568451.8357838, 40435.4335201384, 0, 682...
'Testing the `distance` GeoQuerySet method used with `transform` on a geographic field.'
@no_oracle def test03c_distance_method(self):
if (not connection.ops.geography): self.assertRaises(ValueError, CensusZipcode.objects.distance, self.stx_pnt) z = SouthTexasZipcode.objects.get(name='77005') dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242] buf1 = z.poly.centroid.buffer(100) buf2 = buf1.transform(4269, clone...
'Testing the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.'
def test04_distance_lookups(self):
qs1 = SouthTexasCity.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(point__distance_lte=(self.stx_pnt, D(km=20))) if (spatialite or oracle): dist_qs = (qs1,) else: qs2 = SouthTexasCityFt.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(point__distance_lt...
'Testing distance lookups on geodetic coordinate systems.'
def test05_geodetic_distance_lookups(self):
line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326) dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100))) if (oracle or connection.ops.geography): self.assertEqual(9, dist_qs.count()) self.assertEqual(['Batemans Bay', 'Canberra', 'Hil...
'Testing the `area` GeoQuerySet method.'
def test06_area(self):
area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461] tol = 2 for (i, z) in enumerate(SouthTexasZipcode.objects.area()): self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
'Testing the `length` GeoQuerySet method.'
def test07_length(self):
len_m1 = 473504.769553813 len_m2 = 4617.668 if spatialite: self.assertRaises(ValueError, Interstate.objects.length) else: qs = Interstate.objects.length() if oracle: tol = 2 else: tol = 5 self.assertAlmostEqual(len_m1, qs[0].length.m, tol) ...
'Testing the `perimeter` GeoQuerySet method.'
@no_spatialite def test08_perimeter(self):
perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697] if oracle: tol = 2 else: tol = 7 for (i, z) in enumerate(SouthTexasZipcode.objects.perimeter()): self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol) for (i, c) in enumerate(SouthTexasCity.ob...
'Testing the measurement GeoQuerySet methods on fields with NULL values.'
def test09_measurement_null_fields(self):
SouthTexasZipcode.objects.create(name='78212') htown = SouthTexasCity.objects.get(name='Downtown Houston') z = SouthTexasZipcode.objects.distance(htown.point).area().get(name='78212') self.assertEqual(None, z.distance) self.assertEqual(None, z.area)
'Test the creation of 3D models.'
def test01_3d(self):
for (name, pnt_data) in city_data: (x, y, z) = pnt_data pnt = Point(x, y, z, srid=4326) City3D.objects.create(name=name, point=pnt) city = City3D.objects.get(name=name) self.failUnless(city.point.hasz) self.assertEqual(z, city.point.z) for (name, line, exp_z) in i...
'Testing LayerMapping on 3D models.'
def test01a_3d_layermapping(self):
from models import Point2D, Point3D point_mapping = {'point': 'POINT'} mpoint_mapping = {'mpoint': 'MULTIPOINT'} lm = LayerMapping(Point2D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point2D.objects.count()) self.assertRaises(LayerMapError, LayerMapping, Point3D,...
'Test GeoQuerySet.kml() with Z values.'
def test02a_kml(self):
h = City3D.objects.kml(precision=6).get(name='Houston') ref_kml_regex = re.compile('^<Point><coordinates>-95.363\\d+,29.763\\d+,18</coordinates></Point>$') self.failUnless(ref_kml_regex.match(h.kml))
'Test GeoQuerySet.geojson() with Z values.'
def test02b_geojson(self):
h = City3D.objects.geojson(precision=6).get(name='Houston') ref_json_regex = re.compile('^{"type":"Point","coordinates":\\[-95.363151,29.763374,18(\\.0+)?\\]}$') self.failUnless(ref_json_regex.match(h.geojson))
'Testing the Union aggregate of 3D models.'
def test03a_union(self):
ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)' ref_union = GEOSGeometry(ref_...
'Testing the Extent3D aggregate for 3D models.'
def test03b_extent(self):
ref_extent3d = ((-123.305196), (-41.315268), 14, 174.783117, 48.462611, 1433) extent1 = City3D.objects.aggregate(Extent3D('point'))['point__extent3d'] extent2 = City3D.objects.extent3d() def check_extent3d(extent3d, tol=6): for (ref_val, ext_val) in zip(ref_extent3d, extent3d): self....
'Testing GeoQuerySet.perimeter() on 3D fields.'
def test04_perimeter(self):
ref_perim_3d = 76859.2620451 ref_perim_2d = 76859.2577803 tol = 6 self.assertAlmostEqual(ref_perim_2d, Polygon2D.objects.perimeter().get(name='2D BBox').perimeter.m, tol) self.assertAlmostEqual(ref_perim_3d, Polygon3D.objects.perimeter().get(name='3D BBox').perimeter.m, tol)
'Testing GeoQuerySet.length() on 3D fields.'
def test05_length(self):
tol = 3 ref_length_2d = 4368.1721949481 ref_length_3d = 4368.62547052088 self.assertAlmostEqual(ref_length_2d, Interstate2D.objects.length().get(name='I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, Interstate3D.objects.length().get(name='I-45').length.m, tol) ref_length_2d = 4367.71...
'Testing GeoQuerySet.scale() on Z values.'
def test06_scale(self):
zscales = ((-3), 4, 23) for zscale in zscales: for city in City3D.objects.scale(1.0, 1.0, zscale): self.assertEqual((city_dict[city.name][2] * zscale), city.scale.z)
'Testing GeoQuerySet.translate() on Z values.'
def test07_translate(self):
ztranslations = (5.23, 23, (-17)) for ztrans in ztranslations: for city in City3D.objects.translate(0, 0, ztrans): self.assertEqual((city_dict[city.name][2] + ztrans), city.translate.z)
'Testing GeoIP initialization.'
def test01_init(self):
g1 = GeoIP() path = settings.GEOIP_PATH g2 = GeoIP(path, 0) g3 = GeoIP.open(path, 0) for g in (g1, g2, g3): self.assertEqual(True, bool(g._country)) self.assertEqual(True, bool(g._city)) city = os.path.join(path, 'GeoLiteCity.dat') cntry = os.path.join(path, 'GeoIP.dat') ...
'Testing GeoIP query parameter checking.'
def test02_bad_query(self):
cntry_g = GeoIP(city='<foo>') self.assertRaises(GeoIPException, cntry_g.city, 'google.com') self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com') self.assertRaises(TypeError, cntry_g.country_code, 17) self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
'Testing GeoIP country querying methods.'
def test03_country(self):
g = GeoIP(city='<foo>') fqdn = 'www.google.com' addr = '12.215.42.19' for query in (fqdn, addr): for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_na...
'Testing GeoIP city querying methods.'
def test04_city(self):
g = GeoIP(country='<foo>') addr = '130.80.29.3' fqdn = 'chron.com' for query in (fqdn, addr): for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_...
'Ensure geography features loaded properly.'
def test01_fixture_load(self):
self.assertEqual(8, City.objects.count())
'Testing GeoQuerySet distance lookup support on non-point geography fields.'
def test02_distance_lookup(self):
z = Zipcode.objects.get(code='77002') cities1 = list(City.objects.filter(point__distance_lte=(z.poly, D(mi=500))).order_by('name').values_list('name', flat=True)) cities2 = list(City.objects.filter(point__dwithin=(z.poly, D(mi=500))).order_by('name').values_list('name', flat=True)) for cities in [cities...
'Testing GeoQuerySet.distance() support on non-point geography fields.'
def test03_distance_method(self):
htown = City.objects.get(name='Houston') qs = Zipcode.objects.distance(htown.point)
'Ensuring exceptions are raised for operators & functions invalid on geography fields.'
def test04_invalid_operators_functions(self):
z = Zipcode.objects.get(code='77002') self.assertRaises(ValueError, City.objects.filter(point__within=z.poly).count) self.assertRaises(ValueError, City.objects.filter(point__contained=z.poly).count) htown = City.objects.get(name='Houston') self.assertRaises(ValueError, City.objects.get, point__exact...
'Testing LayerMapping support on models with geography fields.'
def test05_geography_layermapping(self):
if (not gdal.HAS_GDAL): return from django.contrib.gis.utils import LayerMapping shp_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data')) co_shp = os.path.join(shp_path, 'counties', 'counties.shp') co_mapping = {'name': 'Name', 'state': 'State', 'mpoly': 'MULTIPOLYG...
'Testing that Area calculations work on geography columns.'
def test06_geography_area(self):
from django.contrib.gis.measure import A ref_area = 5439084.70637573 tol = 5 z = Zipcode.objects.area().get(code='77002') self.assertAlmostEqual(z.area.sq_m, ref_area, tol)
'Testing retrieval of SpatialRefSys model objects.'
@no_mysql def test01_retrieve(self):
for sd in test_srs: srs = SpatialRefSys.objects.get(srid=sd['srid']) self.assertEqual(sd['srid'], srs.srid) (auth_name, oracle_flag) = sd['auth_name'] if (postgis or (oracle and oracle_flag)): self.assertEqual(True, srs.auth_name.startswith(auth_name)) self.assert...
'Testing getting OSR objects from SpatialRefSys model objects.'
@no_mysql def test02_osr(self):
for sd in test_srs: sr = SpatialRefSys.objects.get(srid=sd['srid']) self.assertEqual(True, sr.spheroid.startswith(sd['spheroid'])) self.assertEqual(sd['geographic'], sr.geographic) self.assertEqual(sd['projected'], sr.projected) if (not (spatialite and (not sd['spatialite']))...
'Testing the ellipsoid property.'
@no_mysql def test03_ellipsoid(self):
for sd in test_srs: ellps1 = sd['ellipsoid'] prec = sd['eprec'] srs = SpatialRefSys.objects.get(srid=sd['srid']) ellps2 = srs.ellipsoid for i in range(3): param1 = ellps1[i] param2 = ellps2[i] self.assertAlmostEqual(ellps1[i], ellps2[i], pr...
'Taken from regressiontests/syndication/tests.py.'
def assertChildNodes(self, elem, expected):
actual = set([n.nodeName for n in elem.childNodes]) expected = set(expected) self.assertEqual(actual, expected)
'Tests geographic feeds using GeoRSS over RSSv2.'
def test_geofeed_rss(self):
doc1 = minidom.parseString(self.client.get('/feeds/rss1/').content) doc2 = minidom.parseString(self.client.get('/feeds/rss2/').content) (feed1, feed2) = (doc1.firstChild, doc2.firstChild) self.assertChildNodes(feed2.getElementsByTagName('channel')[0], ['title', 'link', 'description', 'language', 'lastBu...
'Testing geographic feeds using GeoRSS over Atom.'
def test_geofeed_atom(self):
doc1 = minidom.parseString(self.client.get('/feeds/atom1/').content) doc2 = minidom.parseString(self.client.get('/feeds/atom2/').content) (feed1, feed2) = (doc1.firstChild, doc2.firstChild) self.assertChildNodes(feed2, ['title', 'link', 'id', 'updated', 'entry', 'georss:box']) for feed in [feed1, fe...
'Testing geographic feeds using W3C Geo.'
def test_geofeed_w3c(self):
doc = minidom.parseString(self.client.get('/feeds/w3cgeo1/').content) feed = doc.firstChild self.assertEqual(feed.getAttribute(u'xmlns:geo'), u'http://www.w3.org/2003/01/geo/wgs84_pos#') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len...
'Taken from regressiontests/syndication/tests.py.'
def assertChildNodes(self, elem, expected):
actual = set([n.nodeName for n in elem.childNodes]) expected = set(expected) self.assertEqual(actual, expected)
'Tests geographic sitemap index.'
def test_geositemap_index(self):
doc = minidom.parseString(self.client.get('/sitemap.xml').content) index = doc.firstChild self.assertEqual(index.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9') self.assertEqual(3, len(index.getElementsByTagName('sitemap')))
'Tests KML/KMZ geographic sitemaps.'
def test_geositemap_kml(self):
for kml_type in ('kml', 'kmz'): doc = minidom.parseString(self.client.get(('/sitemaps/%s.xml' % kml_type)).content) urlset = doc.firstChild self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9') self.assertEqual(urlset.getAttribute(u'xmlns:geo...
'Tests GeoRSS geographic sitemaps.'
def test_geositemap_georss(self):
from feeds import feed_dict doc = minidom.parseString(self.client.get('/sitemaps/georss.xml').content) urlset = doc.firstChild self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9') self.assertEqual(urlset.getAttribute(u'xmlns:geo'), u'http://www.google.com/g...
'Testing geographic model initialization from fixtures.'
def test01_fixtures(self):
self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) self.assertEqual(2, State.objects.count())
'Testing Lazy-Geometry support (using the GeometryProxy).'
def test02_proxy(self):
pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') new = Point...
'Testing KML output from the database using GeoQuerySet.kml().'
def test03a_kml(self):
if (not postgis): self.assertRaises(NotImplementedError, State.objects.all().kml, field_name='poly') return qs = City.objects.all() self.assertRaises(TypeError, qs.kml, 'name') if (connection.ops.spatial_version >= (1, 3, 3)): ref_kml = '<Point><coordinates>-104.609252,38.255001<...
'Testing GML output from the database using GeoQuerySet.gml().'
def test03b_gml(self):
if (mysql or spatialite): self.assertRaises(NotImplementedError, Country.objects.all().gml, field_name='mpoly') return qs = City.objects.all() self.assertRaises(TypeError, qs.gml, field_name='name') ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo') ptown2 ...
'Testing GeoJSON output from the database using GeoQuerySet.geojson().'
def test03c_geojson(self):
if (not connection.ops.geojson): self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly') return if (connection.ops.spatial_version >= (1, 4, 0)): pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = '{"type":"Poin...
'Testing SVG output using GeoQuerySet.svg().'
def test03d_svg(self):
if (mysql or oracle): self.assertRaises(NotImplementedError, City.objects.svg) return self.assertRaises(TypeError, City.objects.svg, precision='foo') svg1 = 'cx="-104.609252" cy="-38.255001"' svg2 = svg1.replace('c', '') self.assertEqual(svg1, City.objects.svg().get(name='Pueblo')...
'Testing the transform() GeoManager method.'
@no_mysql def test04_transform(self):
htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084) ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774) prec = 3 if (not oracle): h = City.objects.transform(htown.srid).get(name='Houston') self.assertEqual(3084, h.point.srid) self.asser...
'Testing the `extent` GeoQuerySet method.'
@no_mysql @no_spatialite def test05_extent(self):
expected = ((-96.8016128540039), 29.7633724212646, (-95.3631439208984), 32.78205871582) qs = City.objects.filter(name__in=('Houston', 'Dallas')) extent = qs.extent() for (val, exp) in zip(extent, expected): self.assertAlmostEqual(exp, val, 4)
'Testing the `make_line` GeoQuerySet method.'
@no_mysql @no_oracle @no_spatialite def test06_make_line(self):
self.assertRaises(TypeError, State.objects.make_line) self.assertRaises(TypeError, Country.objects.make_line) ref_line = GEOSGeometry('LINESTRING(-95.363151 29.763374,-96.801611 32.782057,-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,-95.23506 38.971823,-87.650175 41....
'Testing the `disjoint` lookup type.'
@no_mysql def test09_disjoint(self):
ptown = City.objects.get(name='Pueblo') qs1 = City.objects.filter(point__disjoint=ptown.point) self.assertEqual(7, qs1.count()) qs2 = State.objects.filter(poly__disjoint=ptown.point) self.assertEqual(1, qs2.count()) self.assertEqual('Kansas', qs2[0].name)
'Testing the \'contained\', \'contains\', and \'bbcontains\' lookup types.'
def test10_contains_contained(self):
texas = Country.objects.get(name='Texas') if (not oracle): qs = City.objects.filter(point__contained=texas.mpoly) self.assertEqual(3, qs.count()) cities = ['Houston', 'Dallas', 'Oklahoma City'] for c in qs: self.assertEqual(True, (c.name in cities)) houston = C...
'Testing automatic transform for lookups and inserts.'
@no_mysql def test11_lookup_insert_transform(self):
sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) if oracle: nad_wkt = 'POINT (300662.034646583 5416427.45974934)' nad_srid = 41157 else: nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' nad_srid = 3084 ...
'Testing NULL geometry support, and the `isnull` lookup type.'
@no_mysql def test12_null_geometries(self):
State.objects.create(name='Puerto Rico') nullqs = State.objects.filter(poly__isnull=True) validqs = State.objects.filter(poly__isnull=False) self.assertEqual(1, len(nullqs)) self.assertEqual('Puerto Rico', nullqs[0].name) self.assertEqual(2, len(validqs)) state_names = [s.name for s in...
'Testing the \'left\' and \'right\' lookup types.'
@no_mysql @no_oracle @no_spatialite def test13_left_right(self):
co_border = State.objects.get(name='Colorado').poly ks_border = State.objects.get(name='Kansas').poly cities = ['Houston', 'Dallas', 'Oklahoma City', 'Lawrence', 'Chicago', 'Wellington'] qs = City.objects.filter(point__right=co_border) self.assertEqual(6, len(qs)) for c in qs: self.as...