desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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=htown.point)
'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(upath(__file__)), '..', 'data')) co_shp = os.path.join(shp_path, 'counties', 'counties.shp') co_mapping = {'name': 'Name', 'state': 'State', 'mpoly': 'MULTIPOLYGON'} names = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo'] num_polys = [1, 2, 1, 19, 1] st_names = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado'] lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique='name') lm.save(silent=True, strict=True) for (c, name, num_poly, state) in zip(County.objects.order_by('name'), names, num_polys, st_names): self.assertEqual(4326, c.mpoly.srid) self.assertEqual(num_poly, len(c.mpoly)) self.assertEqual(name, c.name) self.assertEqual(state, c.state)
'Testing that Area calculations work on geography columns.'
def test06_geography_area(self):
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.assertEqual(sd['auth_srid'], srs.auth_srid) if postgis: self.assertTrue(srs.wkt.startswith(sd['srtext'])) self.assertTrue((srs.proj4text in sd['proj4']))
'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']))): self.assertEqual(True, sr.name.startswith(sd['name'])) if (postgis or spatialite): srs = sr.srs self.assertTrue((srs.proj4 in sd['proj4'])) if (not spatialite): self.assertTrue(srs.wkt.startswith(sd['srtext']))
'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], prec[i])
'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', 'lastBuildDate', 'item', 'georss:box', 'atom:link']) for feed in [feed1, feed2]: self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(items), City.objects.count()) for item in items: self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'georss:point'])
'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, feed2]: self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss') entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), City.objects.count()) for entry in entries: self.assertChildNodes(entry, ['title', 'link', 'id', 'summary', 'georss:point'])
'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('xmlns:geo'), 'http://www.w3.org/2003/01/geo/wgs84_pos#') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(items), City.objects.count()) for item in items: self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon']) self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/')
'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('xmlns'), '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('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9') self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0') urls = urlset.getElementsByTagName('url') self.assertEqual(2, len(urls)) for url in urls: self.assertChildNodes(url, ['loc', 'geo:geo']) geo_elem = url.getElementsByTagName('geo:geo')[0] geo_format = geo_elem.getElementsByTagName('geo:format')[0] self.assertEqual(kml_type, geo_format.childNodes[0].data) kml_url = url.getElementsByTagName('loc')[0].childNodes[0].data.split('http://example.com')[1] if (kml_type == 'kml'): kml_doc = minidom.parseString(self.client.get(kml_url).content) elif (kml_type == 'kmz'): buf = BytesIO(self.client.get(kml_url).content) zf = zipfile.ZipFile(buf) self.assertEqual(1, len(zf.filelist)) self.assertEqual('doc.kml', zf.filelist[0].filename) kml_doc = minidom.parseString(zf.read('doc.kml')) if ('city' in kml_url): model = City elif ('country' in kml_url): model = Country self.assertEqual(model.objects.count(), len(kml_doc.getElementsByTagName('Placemark')))
'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('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9') self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0') urls = urlset.getElementsByTagName('url') self.assertEqual(len(feed_dict), len(urls)) for url in urls: self.assertChildNodes(url, ['loc', 'geo:geo']) geo_elem = url.getElementsByTagName('geo:geo')[0] geo_format = geo_elem.getElementsByTagName('geo:format')[0] self.assertEqual('georss', geo_format.childNodes[0].data)
'Testing geographic model initialization from fixtures.'
def test_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 test_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(5, 23) nullcity.point = new self.assertEqual(4326, nullcity.point.srid) nullcity.save() self.assertEqual(new, City.objects.get(name='NullCity').point) nullcity.point.x = 23 nullcity.point.y = 5 self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) if gdal.HAS_GDAL: self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry)) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference)) self.assertEqual('WGS 84', ns.poly.srs.name) new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete()
'Testing automatic transform for lookups and inserts.'
@no_mysql def test_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 nad_pnt = fromstr(nad_wkt, srid=nad_srid) if oracle: tx = Country.objects.get(mpoly__contains=nad_pnt) else: tx = Country.objects.get(mpoly__intersects=nad_pnt) self.assertEqual('Texas', tx.name) sa = City.objects.create(name='San Antonio', point=nad_pnt) sa = City.objects.get(name='San Antonio') self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) if (not spatialite): m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual((-1), m1.geom.srid)
'Testing creating a model instance and the geometry being None'
def test_createnull(self):
c = City() self.assertEqual(c.point, None)
'Testing the general GeometryField.'
@no_spatialite def test_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, 0), (2, 2)), Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save() f_1 = Feature.objects.get(name='Point') self.assertEqual(True, isinstance(f_1.geom, Point)) self.assertEqual((1.0, 1.0), f_1.geom.tuple) f_2 = Feature.objects.get(name='LineString') self.assertEqual(True, isinstance(f_2.geom, LineString)) self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) f_3 = Feature.objects.get(name='Polygon') self.assertEqual(True, isinstance(f_3.geom, Polygon)) f_4 = Feature.objects.get(name='GeometryCollection') self.assertEqual(True, isinstance(f_4.geom, GeometryCollection)) self.assertEqual(f_3.geom, f_4.geom[2])
'Test GeoQuerySet methods on inherited Geometry fields.'
@no_mysql def test_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 raw SQL query.'
def test_raw_sql_query(self):
cities1 = City.objects.all() as_text = ('ST_AsText' if postgis else 'asText') cities2 = City.objects.raw(('select id, name, %s(point) from geoapp_city' % as_text)) self.assertEqual(len(cities1), len(list(cities2))) self.assertTrue(isinstance(cities2[0].point, Point))
'Testing the `disjoint` lookup type.'
@no_mysql def test_disjoint_lookup(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 test_contains_contained_lookups(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 = City.objects.get(name='Houston') wellington = City.objects.get(name='Wellington') pueblo = City.objects.get(name='Pueblo') okcity = City.objects.get(name='Oklahoma City') lawrence = City.objects.get(name='Lawrence') tx = Country.objects.get(mpoly__contains=houston.point) nz = Country.objects.get(mpoly__contains=wellington.point.hex) self.assertEqual('Texas', tx.name) self.assertEqual('New Zealand', nz.name) if (not spatialite): ks = State.objects.get(poly__contains=lawrence.point) self.assertEqual('Kansas', ks.name) self.assertEqual(0, len(Country.objects.filter(mpoly__contains=pueblo.point))) self.assertEqual(((mysql and 1) or 0), len(Country.objects.filter(mpoly__contains=okcity.point.wkt))) if (not oracle): qs = Country.objects.filter(mpoly__bbcontains=okcity.point) self.assertEqual(1, len(qs)) self.assertEqual('Texas', qs[0].name)
'Testing the \'left\' and \'right\' lookup types.'
@no_mysql @no_oracle @no_spatialite def test_left_right_lookups(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.assertEqual(True, (c.name in cities)) cities = ['Chicago', 'Wellington'] qs = City.objects.filter(point__right=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertEqual(True, (c.name in cities)) vic = City.objects.get(point__left=co_border) self.assertEqual('Victoria', vic.name) cities = ['Pueblo', 'Victoria'] qs = City.objects.filter(point__left=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertEqual(True, (c.name in cities))
'Testing the \'same_as\' and \'equals\' lookup types.'
def test_equals_lookups(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 NULL geometry support, and the `isnull` lookup type.'
@no_mysql def test_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 validqs] self.assertEqual(True, ('Colorado' in state_names)) self.assertEqual(True, ('Kansas' in state_names)) nmi = State.objects.create(name='Northern Mariana Islands', poly=None) self.assertEqual(nmi.poly, None) nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))' nmi.save() State.objects.filter(name='Northern Mariana Islands').update(poly=None) self.assertEqual(None, State.objects.get(name='Northern Mariana Islands').poly)
'Testing the \'relate\' lookup type.'
@no_mysql def test_relate_lookup(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), ValueError)]: qs = Country.objects.filter(mpoly__relate=bad_args) self.assertRaises(e, qs.count) if (postgis or spatialite): contains_mask = 'T*T***FF*' within_mask = 'T*F**F***' intersects_mask = 'T********' elif oracle: contains_mask = 'contains' within_mask = 'inside' intersects_mask = 'overlapbdyintersect' self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name) ks = State.objects.get(name='Kansas') self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name) if (not oracle): self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name) self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name)
'Testing the `centroid` GeoQuerySet method.'
@no_mysql def test_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 `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods.'
@no_mysql def test_diff_intersection_union(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.mpoly.difference(geom), c.difference) if (not spatialite): self.assertEqual(c.mpoly.intersection(geom), c.intersection) self.assertEqual(c.mpoly.sym_difference(geom), c.sym_difference) self.assertEqual(c.mpoly.union(geom), c.union)
'Testing the `extent` GeoQuerySet method.'
@no_mysql @no_spatialite def test_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 GeoQuerySet.force_rhr().'
@no_mysql @no_oracle @no_spatialite def test_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.coords)
'Testing GeoQuerySet.geohash().'
@no_mysql @no_oracle @no_spatialite def test_geohash(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 GeoJSON output from the database using GeoQuerySet.geojson().'
def test_geojson(self):
if (not connection.ops.geojson): self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly') return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' victoria_json = '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],"coordinates":[-123.305196,48.462611]}' chicago_json = '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}' if (postgis and (connection.ops.spatial_version < (1, 4, 0))): pueblo_json = '{"type":"Point","coordinates":[-104.60925200,38.25500100]}' houston_json = '{"type":"Point","crs":{"type":"EPSG","properties":{"EPSG":4326}},"coordinates":[-95.36315100,29.76337400]}' victoria_json = '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],"coordinates":[-123.30519600,48.46261100]}' elif spatialite: victoria_json = '{"type":"Point","bbox":[-123.305196,48.462611,-123.305196,48.462611],"coordinates":[-123.305196,48.462611]}' self.assertRaises(TypeError, City.objects.geojson, precision='foo') self.assertEqual(pueblo_json, City.objects.geojson().get(name='Pueblo').geojson) self.assertEqual(houston_json, City.objects.geojson(crs=True, model_att='json').get(name='Houston').json) self.assertEqual(victoria_json, City.objects.geojson(bbox=True).get(name='Victoria').geojson) self.assertEqual(chicago_json, City.objects.geojson(bbox=True, crs=True, precision=5).get(name='Chicago').geojson)
'Testing GML output from the database using GeoQuerySet.gml().'
def test_gml(self):
if (mysql or (spatialite and (not connection.ops.gml))): 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 = City.objects.gml(precision=9).get(name='Pueblo') if oracle: gml_regex = re.compile('^<gml:Point srsName="SDO:4326" xmlns:gml="http://www.opengis.net/gml"><gml:coordinates decimal="\\." cs="," ts=" ">-104.60925\\d+,38.25500\\d+ </gml:coordinates></gml:Point>') elif (spatialite and (connection.ops.spatial_version < (3, 0, 0))): gml_regex = re.compile('^<gml:Point SrsName="EPSG::4326"><gml:coordinates decimal="\\." cs="," ts=" ">-104.609251\\d+,38.255001</gml:coordinates></gml:Point>') else: gml_regex = re.compile('^<gml:Point srsName="EPSG:4326"><gml:coordinates>-104\\.60925\\d+,38\\.255001</gml:coordinates></gml:Point>') for ptown in [ptown1, ptown2]: self.assertTrue(gml_regex.match(ptown.gml)) if (postgis and (connection.ops.spatial_version >= (1, 5, 0))): self.assertIn('<gml:pos srsDimension="2">', City.objects.gml(version=3).get(name='Pueblo').gml)
'Testing KML output from the database using GeoQuerySet.kml().'
def test_kml(self):
if (not (postgis or (spatialite and connection.ops.kml))): 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</coordinates></Point>' else: ref_kml = '<Point><coordinates>-104.609252,38.255001,0</coordinates></Point>' ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo') ptown2 = City.objects.kml(precision=9).get(name='Pueblo') for ptown in [ptown1, ptown2]: self.assertEqual(ref_kml, ptown.kml)
'Testing the `make_line` GeoQuerySet method.'
@no_mysql @no_oracle @no_spatialite def test_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.850385,-123.305196 48.462611)', srid=4326) self.assertEqual(ref_line, City.objects.make_line())
'Testing the `num_geom` GeoQuerySet method.'
@no_mysql def test_num_geom(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 and (connection.ops.spatial_version < (2, 0, 0))): self.assertIsNone(c.num_geom) else: self.assertEqual(1, c.num_geom)
'Testing the `num_points` GeoQuerySet method.'
@no_mysql @no_spatialite def test_num_points(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 `point_on_surface` GeoQuerySet method.'
@no_mysql def test_point_on_surface(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': Country.objects.get(name='Texas').mpoly.point_on_surface} for c in Country.objects.point_on_surface(): if spatialite: tol = 1e-05 else: tol = 1e-09 self.assertEqual(True, ref[c.name].equals_exact(c.point_on_surface, tol))
'Testing GeoQuerySet.reverse_geom().'
@no_mysql @no_spatialite def test_reverse_geom(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.objects.reverse_geom)
'Testing the `scale` GeoQuerySet method.'
@no_mysql @no_oracle def test_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] * xfac), c2[0], tol) self.assertAlmostEqual((c1[1] * yfac), c2[1], tol)
'Testing GeoQuerySet.snap_to_grid().'
@no_mysql @no_oracle @no_spatialite def test_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(six.text_type, range(4)))): self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args) wkt = 'MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))' sm = Country.objects.create(name='San Marino', mpoly=fromstr(wkt)) tol = 1e-09 ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))') self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol)) ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))') self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol)) ref = fromstr('MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))') self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid, tol))
'Testing SVG output using GeoQuerySet.svg().'
def test_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').svg) self.assertEqual(svg2, City.objects.svg(relative=5).get(name='Pueblo').svg)
'Testing the transform() GeoQuerySet method.'
@no_mysql def test_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.assertAlmostEqual(htown.x, h.point.x, prec) self.assertAlmostEqual(htown.y, h.point.y, prec) p1 = City.objects.transform(ptown.srid, field_name='point').get(name='Pueblo') p2 = City.objects.transform(srid=ptown.srid).get(name='Pueblo') for p in [p1, p2]: self.assertEqual(2774, p.point.srid) self.assertAlmostEqual(ptown.x, p.point.x, prec) self.assertAlmostEqual(ptown.y, p.point.y, prec)
'Testing the `translate` GeoQuerySet method.'
@no_mysql @no_oracle def test_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] + xfac), c2[0], 5) self.assertAlmostEqual((c1[1] + yfac), c2[1], 5)
'Testing the `unionagg` (aggregate union) GeoQuerySet method.'
@no_mysql def test_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') u1 = qs.unionagg(field_name='point') u2 = qs.order_by('name').unionagg() tol = 1e-05 if oracle: union = union2 else: union = union1 self.assertEqual(True, union.equals_exact(u1, tol)) self.assertEqual(True, union.equals_exact(u2, tol)) qs = City.objects.filter(name='NotACity') self.assertEqual(None, qs.unionagg(field_name='point'))
'Testing GeoQuerySet.update(). See #10411.'
def test_update(self):
pnt = City.objects.get(name=u'Pueblo').point bak = pnt.clone() pnt.y += 0.005 pnt.x += 0.005 City.objects.filter(name=u'Pueblo').update(point=pnt) self.assertEqual(pnt, City.objects.get(name=u'Pueblo').point) City.objects.filter(name=u'Pueblo').update(point=bak) self.assertEqual(bak, City.objects.get(name=u'Pueblo').point)
'Testing `render_to_kmz` with non-ASCII data. See #11624.'
def test_kmz(self):
name = u'\xc5land Islands' places = [{u'name': name, u'description': name, u'kml': u'<Point><coordinates>5.0,23.0</coordinates></Point>'}] kmz = render_to_kmz(u'gis/kml/placemarks.kml', {u'places': places})
'Testing `extent` on a table with a single point. See #11827.'
@no_spatialite @no_mysql def test_extent(self):
pnt = City.objects.get(name=u'Pueblo').point ref_ext = (pnt.x, pnt.y, pnt.x, pnt.y) extent = City.objects.filter(name=u'Pueblo').extent() for (ref_val, val) in zip(ref_ext, extent): self.assertAlmostEqual(ref_val, val, 4)
'Testing dates are converted properly, even on SpatiaLite. See #16408.'
def test_unicode_date(self):
founded = datetime(1857, 5, 23) mansfield = PennsylvaniaCity.objects.create(name=u'Mansfield', county=u'Tioga', point=u'POINT(-77.071445 41.823881)', founded=founded) self.assertEqual(founded, PennsylvaniaCity.objects.dates(u'founded', u'day')[0]) self.assertEqual(founded, PennsylvaniaCity.objects.aggregate(Min(u'founded'))[u'founded__min'])
'Testing that PostGISAdapter.__eq__ does check empty strings. See #13670.'
def test_empty_count(self):
pueblo = City.objects.get(name=u'Pueblo') state = State.objects.filter(poly__contains=pueblo.point) cities_within_state = City.objects.filter(id__in=state) self.assertEqual(cities_within_state.count(), 1)
'Regression for #16409. Make sure defer() and only() work with annotate()'
def test_defer_or_only_with_annotate(self):
self.assertIsInstance(list(City.objects.annotate(Count(u'point')).defer(u'name')), list) self.assertIsInstance(list(City.objects.annotate(Count(u'point')).only(u'name')), list)
'Testing Boolean value conversion with the spatial backend, see #15169.'
def test_boolean_conversion(self):
t1 = Truth.objects.create(val=True) t2 = Truth.objects.create(val=False) val1 = Truth.objects.get(pk=1).val val2 = Truth.objects.get(pk=2).val self.assertIsInstance(val1, bool) self.assertIsInstance(val2, bool) self.assertEqual(val1, True) self.assertEqual(val2, False)
'Testing LayerMapping initialization.'
def test_init(self):
bad1 = copy(city_mapping) bad1[u'foobar'] = u'FooField' bad2 = copy(city_mapping) bad2[u'name'] = u'Nombre' bad3 = copy(city_mapping) bad3[u'point'] = u'CURVE' for bad_map in (bad1, bad2, bad3): with self.assertRaises(LayerMapError): lm = LayerMapping(City, city_shp, bad_map) with self.assertRaises(LookupError): lm = LayerMapping(City, city_shp, city_mapping, encoding=u'foobar')
'Test LayerMapping import of a simple point shapefile.'
def test_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[u'Name'].value) self.assertEqual(feat[u'Population'].value, city.population) self.assertEqual(Decimal(str(feat[u'Density'])), city.density) self.assertEqual(feat[u'Created'].value, city.dt) (pnt1, pnt2) = (feat.geom, city.point) self.assertAlmostEqual(pnt1.x, pnt2.x, 5) self.assertAlmostEqual(pnt1.y, pnt2.y, 5)
'Testing the `strict` keyword, and import of a LineString shapefile.'
def test_layermap_strict(self):
with self.assertRaises(InvalidDecimal): lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True, strict=True) Interstate.objects.all().delete() lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True) self.assertEqual(2, Interstate.objects.count()) ds = DataSource(inter_shp) valid_feats = ds[0][:2] for feat in valid_feats: istate = Interstate.objects.get(name=feat[u'Name'].value) if (feat.fid == 0): self.assertEqual(Decimal(str(feat[u'Length'])), istate.length) elif (feat.fid == 1): self.assertAlmostEqual(feat.get(u'Length'), float(istate.length), 2) for (p1, p2) in zip(feat.geom, istate.path): self.assertAlmostEqual(p1[0], p2[0], 6) self.assertAlmostEqual(p1[1], p2[1], 6)
'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 test_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=u'NAD83') for arg in (u'name', (u'name', u'mpoly')): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) except: self.fail(u'No exception should be raised for proper use of keywords.') for (e, arg) in ((TypeError, 5.0), (ValueError, u'foobar'), (ValueError, (u'name', u'mpolygon'))): self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg) if (not mysql): self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping) bad_fk_map1 = copy(co_mapping) bad_fk_map1[u'state'] = u'name' bad_fk_map2 = copy(co_mapping) bad_fk_map2[u'state'] = {u'nombre': u'State'} self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False) self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False) lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=u'name') self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True) State.objects.bulk_create([State(name=u'Colorado'), State(name=u'Hawaii'), State(name=u'Texas')]) lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=u'name') lm.save(silent=True, strict=True) lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) self.county_helper()
'Tests the `fid_range` keyword and the `step` keyword of .save().'
def test_test_fid_range_step(self):
def clear_counties(): County.objects.all().delete() State.objects.bulk_create([State(name=u'Colorado'), State(name=u'Hawaii'), State(name=u'Texas')]) lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=u'name') bad_ranges = (5.0, u'foo', co_shp) for bad in bad_ranges: self.assertRaises(TypeError, lm.save, fid_range=bad) fr = (3, 5) self.assertRaises(LayerMapError, lm.save, fid_range=fr, step=10) lm.save(fid_range=fr) qs = County.objects.all() self.assertEqual(1, qs.count()) self.assertEqual(u'Galveston', qs[0].name) clear_counties() lm.save(fid_range=slice(5, None), silent=True, strict=True) lm.save(fid_range=slice(None, 1), silent=True, strict=True) qs = County.objects.order_by(u'name') self.assertEqual(2, qs.count()) (hi, co) = tuple(qs) (hi_idx, co_idx) = tuple(map(NAMES.index, (u'Honolulu', u'Pueblo'))) self.assertEqual(u'Pueblo', co.name) self.assertEqual(NUMS[co_idx], len(co.mpoly)) self.assertEqual(u'Honolulu', hi.name) self.assertEqual(NUMS[hi_idx], len(hi.mpoly)) for st in (4, 7, 1000): clear_counties() lm.save(step=st, strict=True) self.county_helper(county_feat=False)
'Tests LayerMapping on inherited models. See #12093.'
def test_model_inheritance(self):
icity_mapping = {u'name': u'Name', u'population': u'Population', u'density': u'Density', u'point': u'POINT', u'dt': u'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.assertEqual(3, ICity2.objects.count())
'Tests LayerMapping on invalid geometries. See #15378.'
def test_invalid_layer(self):
invalid_mapping = {u'point': u'POINT'} lm = LayerMapping(Invalid, invalid_shp, invalid_mapping, source_srs=4326) lm.save(silent=True)
'Tests that String content fits also in a TextField'
def test_textfield(self):
mapping = copy(city_mapping) mapping[u'name_txt'] = u'Name' lm = LayerMapping(City, city_shp, mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 3) self.assertEqual(City.objects.all().order_by(u'name_txt')[0].name_txt, u'Houston')
'Test a layer containing utf-8-encoded name'
def test_encoded_name(self):
city_shp = os.path.join(shp_path, u'ch-city', u'ch-city.shp') lm = LayerMapping(City, city_shp, city_mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 1) self.assertEqual(City.objects.all()[0].name, u'Z\xfcrich')
'Check that changes are accurately noticed by OpenLayersWidget.'
def test_olwidget_has_changed(self):
geoadmin = admin.site._registry[City] form = geoadmin.get_changelist_form(None)() has_changed = form.fields['point'].widget._has_changed initial = Point(13.419745857296595, 52.51941085011498, srid=4326) data_same = 'SRID=3857;POINT(1493879.2754093995 6894592.019687599)' data_almost_same = 'SRID=3857;POINT(1493879.2754093990 6894592.019687590)' data_changed = 'SRID=3857;POINT(1493884.0527237 6894593.8111804)' self.assertTrue(has_changed(None, data_changed)) self.assertTrue(has_changed(initial, '')) self.assertFalse(has_changed(None, '')) self.assertFalse(has_changed(initial, data_same)) self.assertFalse(has_changed(initial, data_almost_same)) self.assertTrue(has_changed(initial, data_changed))
'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): self.assertEqual(d.yd, 100) (mm1, mm2) = (D(millimeter=1000), D(MiLLiMeTeR=1000)) for d in (mm1, mm2): self.assertEqual(d.m, 1.0) self.assertEqual(d.mm, 1000.0)
'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.assertFalse(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)) with self.assertRaises(TypeError): d5 = (d1 + 1) self.fail('Distance + number should raise TypeError') with self.assertRaises(TypeError): d5 = (d1 - 1) self.fail('Distance - number should raise TypeError') with self.assertRaises(TypeError): d1 += 1 self.fail('Distance += number should raise TypeError') with self.assertRaises(TypeError): d1 -= 1 self.fail('Distance -= number should raise TypeError')
'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) d5 = (d1 / D(m=2)) self.assertEqual(d5, 50) a5 = (d1 * D(m=10)) self.assertTrue(isinstance(a5, Area)) self.assertEqual(a5.sq_m, (100 * 10)) with self.assertRaises(TypeError): d1 *= D(m=1) self.fail('Distance *= Distance should raise TypeError') with self.assertRaises(TypeError): d1 /= D(m=1) self.fail('Distance /= Distance should raise TypeError')
'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.assertTrue((d2 > d1)) self.assertTrue((d1 == d1)) self.assertTrue((d1 < d2)) self.assertFalse(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.assertFalse(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)) with self.assertRaises(TypeError): a5 = (a1 + 1) self.fail('Area + number should raise TypeError') with self.assertRaises(TypeError): a5 = (a1 - 1) self.fail('Area - number should raise TypeError') with self.assertRaises(TypeError): a1 += 1 self.fail('Area += number should raise TypeError') with self.assertRaises(TypeError): a1 -= 1 self.fail('Area -= number should raise TypeError')
'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) with self.assertRaises(TypeError): a5 = (a1 * A(sq_m=1)) self.fail('Area * Area should raise TypeError') with self.assertRaises(TypeError): a1 *= A(sq_m=1) self.fail('Area *= Area should raise TypeError') with self.assertRaises(TypeError): a5 = (a1 / A(sq_m=1)) self.fail('Area / Area should raise TypeError') with self.assertRaises(TypeError): a1 /= A(sq_m=1) self.fail('Area /= Area should raise TypeError')
'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.assertTrue((a2 > a1)) self.assertTrue((a1 == a1)) self.assertTrue((a1 < a2)) self.assertFalse(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 zip(cities, qs): (nm, st, lon, lat) = ref self.assertEqual(nm, c.name) self.assertEqual(st, c.state) self.assertEqual(Point(lon, lat), c.location.point)
'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 868477.766629735)'), ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)')) for (name, srid, wkt) in transformed: qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point')) check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
'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='location__point') e3 = aggs['location__point__extent'] tol = 4 for (ref, e) in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: for (ref_val, e_val) in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol)
'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, p2, srid=4326) ref_u2 = MultiPoint(p3, p2, srid=4326) else: ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.unionagg(field_name='location__point') u2 = City.objects.exclude(name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth')).unionagg(field_name='location__point') u3 = aggs['location__point__union'] self.assertEqual(ref_u1, u1) self.assertEqual(ref_u2, u2) self.assertEqual(ref_u1, u3)
'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.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2) c1 = b1.centroid c2 = c1.transform(2276, clone=True) p2 = Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1) qs = Parcel.objects.filter(center1__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) if (not mysql): qs = Parcel.objects.filter(center2__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) qs = Parcel.objects.filter(center1=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) if (not mysql): qs = Parcel.objects.filter(border2__contains=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name)
'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.assertTrue(isinstance(d['point'], Geometry)) self.assertTrue(isinstance(t[1], Geometry)) self.assertEqual(m.point, d['point']) self.assertEqual(m.point, t[1])
'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 combined] self.assertEqual(2, len(names)) self.assertTrue(('Aurora' in names)) self.assertTrue(('Kecksburg' in names))
'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]['num_books'])
'Testing `Count` aggregate with `.values()`. See #15305.'
def test13c_count(self):
qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities') self.assertEqual(1, len(qs)) self.assertEqual(2, qs[0]['num_cities']) self.assertTrue(isinstance(qs[0]['point'], GEOSGeometry))
'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__collect'] for coll in (c1, c2): self.assertEqual(4, len(coll)) self.assertEqual(ref_geom, coll)
'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)