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...
'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': 'MUL...
'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.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('xmlns:geo'), 'http://www.w3.org/2003/01/geo/wgs84_pos#') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(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 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'),...
'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/...
'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...
'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 ...
'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...
'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 = C...
'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.as...
'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...
'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), Val...
'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.mpo...
'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.c...
'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"}},"co...
'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)...
'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 = '<...
'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....
'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': Co...
'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...
'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] * xf...
'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 ...
'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')...
'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.asser...
'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] ...
'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') ...
'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, Cit...
'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.ag...
'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_...
'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) se...
'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.coun...
'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_sh...
'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: ...
'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()...
'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 = 'SR...
'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.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('Distan...
'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 ...
'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) ...
'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): ...
'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...
'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.assertTrue(isinstance(d['point'], Geometry)) self.assertTrue(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 `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__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)