PageRenderTime 544ms CodeModel.GetById 101ms app.highlight 224ms RepoModel.GetById 118ms app.codeStats 0ms

/django/contrib/gis/tests/geoapp/tests.py

https://code.google.com/p/mango-py/
Python | 735 lines | 537 code | 86 blank | 112 comment | 98 complexity | f9c41eebb91519d68a8fda7b88e6a73a MD5 | raw file
  1import re
  2from django.db import connection
  3from django.contrib.gis import gdal
  4from django.contrib.gis.geos import fromstr, GEOSGeometry, \
  5    Point, LineString, LinearRing, Polygon, GeometryCollection
  6from django.contrib.gis.measure import Distance
  7from django.contrib.gis.tests.utils import \
  8    no_mysql, no_oracle, no_spatialite, \
  9    mysql, oracle, postgis, spatialite
 10from django.test import TestCase
 11
 12from models import Country, City, PennsylvaniaCity, State, Track
 13
 14if not spatialite:
 15    from models import Feature, MinusOneSRID
 16
 17class GeoModelTest(TestCase):
 18
 19    def test01_fixtures(self):
 20        "Testing geographic model initialization from fixtures."
 21        # Ensuring that data was loaded from initial data fixtures.
 22        self.assertEqual(2, Country.objects.count())
 23        self.assertEqual(8, City.objects.count())
 24        self.assertEqual(2, State.objects.count())
 25
 26    def test02_proxy(self):
 27        "Testing Lazy-Geometry support (using the GeometryProxy)."
 28        ## Testing on a Point
 29        pnt = Point(0, 0)
 30        nullcity = City(name='NullCity', point=pnt)
 31        nullcity.save()
 32
 33        # Making sure TypeError is thrown when trying to set with an
 34        #  incompatible type.
 35        for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
 36            try:
 37                nullcity.point = bad
 38            except TypeError:
 39                pass
 40            else:
 41                self.fail('Should throw a TypeError')
 42
 43        # Now setting with a compatible GEOS Geometry, saving, and ensuring
 44        #  the save took, notice no SRID is explicitly set.
 45        new = Point(5, 23)
 46        nullcity.point = new
 47
 48        # Ensuring that the SRID is automatically set to that of the
 49        #  field after assignment, but before saving.
 50        self.assertEqual(4326, nullcity.point.srid)
 51        nullcity.save()
 52
 53        # Ensuring the point was saved correctly after saving
 54        self.assertEqual(new, City.objects.get(name='NullCity').point)
 55
 56        # Setting the X and Y of the Point
 57        nullcity.point.x = 23
 58        nullcity.point.y = 5
 59        # Checking assignments pre & post-save.
 60        self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
 61        nullcity.save()
 62        self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
 63        nullcity.delete()
 64
 65        ## Testing on a Polygon
 66        shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
 67        inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))
 68
 69        # Creating a State object using a built Polygon
 70        ply = Polygon(shell, inner)
 71        nullstate = State(name='NullState', poly=ply)
 72        self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
 73        nullstate.save()
 74
 75        ns = State.objects.get(name='NullState')
 76        self.assertEqual(ply, ns.poly)
 77
 78        # Testing the `ogr` and `srs` lazy-geometry properties.
 79        if gdal.HAS_GDAL:
 80            self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry))
 81            self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
 82            self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference))
 83            self.assertEqual('WGS 84', ns.poly.srs.name)
 84
 85        # Changing the interior ring on the poly attribute.
 86        new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
 87        ns.poly[1] = new_inner
 88        ply[1] = new_inner
 89        self.assertEqual(4326, ns.poly.srid)
 90        ns.save()
 91        self.assertEqual(ply, State.objects.get(name='NullState').poly)
 92        ns.delete()
 93
 94    def test03a_kml(self):
 95        "Testing KML output from the database using GeoQuerySet.kml()."
 96        # Only PostGIS supports KML serialization
 97        if not postgis:
 98            self.assertRaises(NotImplementedError, State.objects.all().kml, field_name='poly')
 99            return
100
101        # Should throw a TypeError when trying to obtain KML from a
102        #  non-geometry field.
103        qs = City.objects.all()
104        self.assertRaises(TypeError, qs.kml, 'name')
105
106        # The reference KML depends on the version of PostGIS used
107        # (the output stopped including altitude in 1.3.3).
108        if connection.ops.spatial_version >= (1, 3, 3):
109            ref_kml =  '<Point><coordinates>-104.609252,38.255001</coordinates></Point>'
110        else:
111            ref_kml = '<Point><coordinates>-104.609252,38.255001,0</coordinates></Point>'
112
113        # Ensuring the KML is as expected.
114        ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo')
115        ptown2 = City.objects.kml(precision=9).get(name='Pueblo')
116        for ptown in [ptown1, ptown2]:
117            self.assertEqual(ref_kml, ptown.kml)
118
119    def test03b_gml(self):
120        "Testing GML output from the database using GeoQuerySet.gml()."
121        if mysql or spatialite:
122            self.assertRaises(NotImplementedError, Country.objects.all().gml, field_name='mpoly')
123            return
124
125        # Should throw a TypeError when tyring to obtain GML from a
126        # non-geometry field.
127        qs = City.objects.all()
128        self.assertRaises(TypeError, qs.gml, field_name='name')
129        ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo')
130        ptown2 = City.objects.gml(precision=9).get(name='Pueblo')
131
132        if oracle:
133            # No precision parameter for Oracle :-/
134            gml_regex = re.compile(r'^<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>')
135            for ptown in [ptown1, ptown2]:
136                self.assertTrue(gml_regex.match(ptown.gml))
137        else:
138            gml_regex = re.compile(r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>')
139            for ptown in [ptown1, ptown2]:
140                self.assertTrue(gml_regex.match(ptown.gml))
141
142    def test03c_geojson(self):
143        "Testing GeoJSON output from the database using GeoQuerySet.geojson()."
144        # Only PostGIS 1.3.4+ supports GeoJSON.
145        if not connection.ops.geojson:
146            self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly')
147            return
148
149        if connection.ops.spatial_version >= (1, 4, 0):
150            pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
151            houston_json = '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
152            victoria_json = '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],"coordinates":[-123.305196,48.462611]}'
153            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]}'
154        else:
155            pueblo_json = '{"type":"Point","coordinates":[-104.60925200,38.25500100]}'
156            houston_json = '{"type":"Point","crs":{"type":"EPSG","properties":{"EPSG":4326}},"coordinates":[-95.36315100,29.76337400]}'
157            victoria_json = '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],"coordinates":[-123.30519600,48.46261100]}'
158            chicago_json = '{"type":"Point","crs":{"type":"EPSG","properties":{"EPSG":4326}},"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}'
159
160        # Precision argument should only be an integer
161        self.assertRaises(TypeError, City.objects.geojson, precision='foo')
162
163        # Reference queries and values.
164        # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo';
165        self.assertEqual(pueblo_json, City.objects.geojson().get(name='Pueblo').geojson)
166
167        # 1.3.x: SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Houston';
168        # 1.4.x: SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Houston';
169        # This time we want to include the CRS by using the `crs` keyword.
170        self.assertEqual(houston_json, City.objects.geojson(crs=True, model_att='json').get(name='Houston').json)
171
172        # 1.3.x: SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Victoria';
173        # 1.4.x: SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Houston';
174        # This time we include the bounding box by using the `bbox` keyword.
175        self.assertEqual(victoria_json, City.objects.geojson(bbox=True).get(name='Victoria').geojson)
176
177        # 1.(3|4).x: SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Chicago';
178        # Finally, we set every available keyword.
179        self.assertEqual(chicago_json, City.objects.geojson(bbox=True, crs=True, precision=5).get(name='Chicago').geojson)
180
181    def test03d_svg(self):
182        "Testing SVG output using GeoQuerySet.svg()."
183        if mysql or oracle:
184            self.assertRaises(NotImplementedError, City.objects.svg)
185            return
186
187        self.assertRaises(TypeError, City.objects.svg, precision='foo')
188        # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo';
189        svg1 = 'cx="-104.609252" cy="-38.255001"'
190        # Even though relative, only one point so it's practically the same except for
191        # the 'c' letter prefix on the x,y values.
192        svg2 = svg1.replace('c', '')
193        self.assertEqual(svg1, City.objects.svg().get(name='Pueblo').svg)
194        self.assertEqual(svg2, City.objects.svg(relative=5).get(name='Pueblo').svg)
195
196    @no_mysql
197    def test04_transform(self):
198        "Testing the transform() GeoManager method."
199        # Pre-transformed points for Houston and Pueblo.
200        htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084)
201        ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774)
202        prec = 3 # Precision is low due to version variations in PROJ and GDAL.
203
204        # Asserting the result of the transform operation with the values in
205        #  the pre-transformed points.  Oracle does not have the 3084 SRID.
206        if not oracle:
207            h = City.objects.transform(htown.srid).get(name='Houston')
208            self.assertEqual(3084, h.point.srid)
209            self.assertAlmostEqual(htown.x, h.point.x, prec)
210            self.assertAlmostEqual(htown.y, h.point.y, prec)
211
212        p1 = City.objects.transform(ptown.srid, field_name='point').get(name='Pueblo')
213        p2 = City.objects.transform(srid=ptown.srid).get(name='Pueblo')
214        for p in [p1, p2]:
215            self.assertEqual(2774, p.point.srid)
216            self.assertAlmostEqual(ptown.x, p.point.x, prec)
217            self.assertAlmostEqual(ptown.y, p.point.y, prec)
218
219    @no_mysql
220    @no_spatialite # SpatiaLite does not have an Extent function
221    def test05_extent(self):
222        "Testing the `extent` GeoQuerySet method."
223        # Reference query:
224        # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');`
225        #   =>  BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
226        expected = (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820)
227
228        qs = City.objects.filter(name__in=('Houston', 'Dallas'))
229        extent = qs.extent()
230
231        for val, exp in zip(extent, expected):
232            self.assertAlmostEqual(exp, val, 4)
233
234    # Only PostGIS has support for the MakeLine aggregate.
235    @no_mysql
236    @no_oracle
237    @no_spatialite
238    def test06_make_line(self):
239        "Testing the `make_line` GeoQuerySet method."
240        # Ensuring that a `TypeError` is raised on models without PointFields.
241        self.assertRaises(TypeError, State.objects.make_line)
242        self.assertRaises(TypeError, Country.objects.make_line)
243        # Reference query:
244        # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
245        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)
246        self.assertEqual(ref_line, City.objects.make_line())
247
248    @no_mysql
249    def test09_disjoint(self):
250        "Testing the `disjoint` lookup type."
251        ptown = City.objects.get(name='Pueblo')
252        qs1 = City.objects.filter(point__disjoint=ptown.point)
253        self.assertEqual(7, qs1.count())
254
255        qs2 = State.objects.filter(poly__disjoint=ptown.point)
256        self.assertEqual(1, qs2.count())
257        self.assertEqual('Kansas', qs2[0].name)
258
259    def test10_contains_contained(self):
260        "Testing the 'contained', 'contains', and 'bbcontains' lookup types."
261        # Getting Texas, yes we were a country -- once ;)
262        texas = Country.objects.get(name='Texas')
263
264        # Seeing what cities are in Texas, should get Houston and Dallas,
265        #  and Oklahoma City because 'contained' only checks on the
266        #  _bounding box_ of the Geometries.
267        if not oracle:
268            qs = City.objects.filter(point__contained=texas.mpoly)
269            self.assertEqual(3, qs.count())
270            cities = ['Houston', 'Dallas', 'Oklahoma City']
271            for c in qs: self.assertEqual(True, c.name in cities)
272
273        # Pulling out some cities.
274        houston = City.objects.get(name='Houston')
275        wellington = City.objects.get(name='Wellington')
276        pueblo = City.objects.get(name='Pueblo')
277        okcity = City.objects.get(name='Oklahoma City')
278        lawrence = City.objects.get(name='Lawrence')
279
280        # Now testing contains on the countries using the points for
281        #  Houston and Wellington.
282        tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry
283        nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX
284        self.assertEqual('Texas', tx.name)
285        self.assertEqual('New Zealand', nz.name)
286
287        # Spatialite 2.3 thinks that Lawrence is in Puerto Rico (a NULL geometry).
288        if not spatialite:
289            ks = State.objects.get(poly__contains=lawrence.point)
290            self.assertEqual('Kansas', ks.name)
291
292        # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas)
293        # are not contained in Texas or New Zealand.
294        self.assertEqual(0, len(Country.objects.filter(mpoly__contains=pueblo.point))) # Query w/GEOSGeometry object
295        self.assertEqual((mysql and 1) or 0,
296                         len(Country.objects.filter(mpoly__contains=okcity.point.wkt))) # Qeury w/WKT
297
298        # OK City is contained w/in bounding box of Texas.
299        if not oracle:
300            qs = Country.objects.filter(mpoly__bbcontains=okcity.point)
301            self.assertEqual(1, len(qs))
302            self.assertEqual('Texas', qs[0].name)
303
304    @no_mysql
305    def test11_lookup_insert_transform(self):
306        "Testing automatic transform for lookups and inserts."
307        # San Antonio in 'WGS84' (SRID 4326)
308        sa_4326 = 'POINT (-98.493183 29.424170)'
309        wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84
310
311        # Oracle doesn't have SRID 3084, using 41157.
312        if oracle:
313            # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157)
314            # Used the following Oracle SQL to get this value:
315            #  SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL;
316            nad_wkt  = 'POINT (300662.034646583 5416427.45974934)'
317            nad_srid = 41157
318        else:
319            # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084)
320            nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform
321            nad_srid = 3084
322
323        # Constructing & querying with a point from a different SRID. Oracle
324        # `SDO_OVERLAPBDYINTERSECT` operates differently from
325        # `ST_Intersects`, so contains is used instead.
326        nad_pnt = fromstr(nad_wkt, srid=nad_srid)
327        if oracle:
328            tx = Country.objects.get(mpoly__contains=nad_pnt)
329        else:
330            tx = Country.objects.get(mpoly__intersects=nad_pnt)
331        self.assertEqual('Texas', tx.name)
332
333        # Creating San Antonio.  Remember the Alamo.
334        sa = City.objects.create(name='San Antonio', point=nad_pnt)
335
336        # Now verifying that San Antonio was transformed correctly
337        sa = City.objects.get(name='San Antonio')
338        self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
339        self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
340
341        # If the GeometryField SRID is -1, then we shouldn't perform any
342        # transformation if the SRID of the input geometry is different.
343        # SpatiaLite does not support missing SRID values.
344        if not spatialite:
345            m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
346            m1.save()
347            self.assertEqual(-1, m1.geom.srid)
348
349    @no_mysql
350    def test12_null_geometries(self):
351        "Testing NULL geometry support, and the `isnull` lookup type."
352        # Creating a state with a NULL boundary.
353        State.objects.create(name='Puerto Rico')
354
355        # Querying for both NULL and Non-NULL values.
356        nullqs = State.objects.filter(poly__isnull=True)
357        validqs = State.objects.filter(poly__isnull=False)
358
359        # Puerto Rico should be NULL (it's a commonwealth unincorporated territory)
360        self.assertEqual(1, len(nullqs))
361        self.assertEqual('Puerto Rico', nullqs[0].name)
362
363        # The valid states should be Colorado & Kansas
364        self.assertEqual(2, len(validqs))
365        state_names = [s.name for s in validqs]
366        self.assertEqual(True, 'Colorado' in state_names)
367        self.assertEqual(True, 'Kansas' in state_names)
368
369        # Saving another commonwealth w/a NULL geometry.
370        nmi = State.objects.create(name='Northern Mariana Islands', poly=None)
371        self.assertEqual(nmi.poly, None)
372
373        # Assigning a geomery and saving -- then UPDATE back to NULL.
374        nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))'
375        nmi.save()
376        State.objects.filter(name='Northern Mariana Islands').update(poly=None)
377        self.assertEqual(None, State.objects.get(name='Northern Mariana Islands').poly)
378
379    # Only PostGIS has `left` and `right` lookup types.
380    @no_mysql
381    @no_oracle
382    @no_spatialite
383    def test13_left_right(self):
384        "Testing the 'left' and 'right' lookup types."
385        # Left: A << B => true if xmax(A) < xmin(B)
386        # Right: A >> B => true if xmin(A) > xmax(B)
387        # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source.
388
389        # Getting the borders for Colorado & Kansas
390        co_border = State.objects.get(name='Colorado').poly
391        ks_border = State.objects.get(name='Kansas').poly
392
393        # Note: Wellington has an 'X' value of 174, so it will not be considered
394        # to the left of CO.
395
396        # These cities should be strictly to the right of the CO border.
397        cities = ['Houston', 'Dallas', 'Oklahoma City',
398                  'Lawrence', 'Chicago', 'Wellington']
399        qs = City.objects.filter(point__right=co_border)
400        self.assertEqual(6, len(qs))
401        for c in qs: self.assertEqual(True, c.name in cities)
402
403        # These cities should be strictly to the right of the KS border.
404        cities = ['Chicago', 'Wellington']
405        qs = City.objects.filter(point__right=ks_border)
406        self.assertEqual(2, len(qs))
407        for c in qs: self.assertEqual(True, c.name in cities)
408
409        # Note: Wellington has an 'X' value of 174, so it will not be considered
410        #  to the left of CO.
411        vic = City.objects.get(point__left=co_border)
412        self.assertEqual('Victoria', vic.name)
413
414        cities = ['Pueblo', 'Victoria']
415        qs = City.objects.filter(point__left=ks_border)
416        self.assertEqual(2, len(qs))
417        for c in qs: self.assertEqual(True, c.name in cities)
418
419    def test14_equals(self):
420        "Testing the 'same_as' and 'equals' lookup types."
421        pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326)
422        c1 = City.objects.get(point=pnt)
423        c2 = City.objects.get(point__same_as=pnt)
424        c3 = City.objects.get(point__equals=pnt)
425        for c in [c1, c2, c3]: self.assertEqual('Houston', c.name)
426
427    @no_mysql
428    def test15_relate(self):
429        "Testing the 'relate' lookup type."
430        # To make things more interesting, we will have our Texas reference point in
431        # different SRIDs.
432        pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847)
433        pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326)
434
435        # Not passing in a geometry as first param shoud
436        # raise a type error when initializing the GeoQuerySet
437        self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo'))
438
439        # Making sure the right exception is raised for the given
440        # bad arguments.
441        for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]:
442            qs = Country.objects.filter(mpoly__relate=bad_args)
443            self.assertRaises(e, qs.count)
444
445        # Relate works differently for the different backends.
446        if postgis or spatialite:
447            contains_mask = 'T*T***FF*'
448            within_mask = 'T*F**F***'
449            intersects_mask = 'T********'
450        elif oracle:
451            contains_mask = 'contains'
452            within_mask = 'inside'
453            # TODO: This is not quite the same as the PostGIS mask above
454            intersects_mask = 'overlapbdyintersect'
455
456        # Testing contains relation mask.
457        self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name)
458        self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name)
459
460        # Testing within relation mask.
461        ks = State.objects.get(name='Kansas')
462        self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name)
463
464        # Testing intersection relation mask.
465        if not oracle:
466            self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name)
467            self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name)
468            self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name)
469
470    def test16_createnull(self):
471        "Testing creating a model instance and the geometry being None"
472        c = City()
473        self.assertEqual(c.point, None)
474
475    @no_mysql
476    def test17_unionagg(self):
477        "Testing the `unionagg` (aggregate union) GeoManager method."
478        tx = Country.objects.get(name='Texas').mpoly
479        # Houston, Dallas -- Oracle has different order.
480        union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)')
481        union2 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)')
482        qs = City.objects.filter(point__within=tx)
483        self.assertRaises(TypeError, qs.unionagg, 'name')
484        # Using `field_name` keyword argument in one query and specifying an
485        # order in the other (which should not be used because this is
486        # an aggregate method on a spatial column)
487        u1 = qs.unionagg(field_name='point')
488        u2 = qs.order_by('name').unionagg()
489        tol = 0.00001
490        if oracle:
491            union = union2
492        else:
493            union = union1
494        self.assertEqual(True, union.equals_exact(u1, tol))
495        self.assertEqual(True, union.equals_exact(u2, tol))
496        qs = City.objects.filter(name='NotACity')
497        self.assertEqual(None, qs.unionagg(field_name='point'))
498
499    @no_spatialite # SpatiaLite does not support abstract geometry columns
500    def test18_geometryfield(self):
501        "Testing the general GeometryField."
502        Feature(name='Point', geom=Point(1, 1)).save()
503        Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save()
504        Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save()
505        Feature(name='GeometryCollection',
506                geom=GeometryCollection(Point(2, 2), LineString((0, 0), (2, 2)),
507                                        Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save()
508
509        f_1 = Feature.objects.get(name='Point')
510        self.assertEqual(True, isinstance(f_1.geom, Point))
511        self.assertEqual((1.0, 1.0), f_1.geom.tuple)
512        f_2 = Feature.objects.get(name='LineString')
513        self.assertEqual(True, isinstance(f_2.geom, LineString))
514        self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple)
515
516        f_3 = Feature.objects.get(name='Polygon')
517        self.assertEqual(True, isinstance(f_3.geom, Polygon))
518        f_4 = Feature.objects.get(name='GeometryCollection')
519        self.assertEqual(True, isinstance(f_4.geom, GeometryCollection))
520        self.assertEqual(f_3.geom, f_4.geom[2])
521
522    @no_mysql
523    def test19_centroid(self):
524        "Testing the `centroid` GeoQuerySet method."
525        qs = State.objects.exclude(poly__isnull=True).centroid()
526        if oracle:
527            tol = 0.1
528        elif spatialite:
529            tol = 0.000001
530        else:
531            tol = 0.000000001
532        for s in qs:
533            self.assertEqual(True, s.poly.centroid.equals_exact(s.centroid, tol))
534
535    @no_mysql
536    def test20_pointonsurface(self):
537        "Testing the `point_on_surface` GeoQuerySet method."
538        # Reference values.
539        if oracle:
540            # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05)) FROM GEOAPP_COUNTRY;
541            ref = {'New Zealand' : fromstr('POINT (174.616364 -36.100861)', srid=4326),
542                   'Texas' : fromstr('POINT (-103.002434 36.500397)', srid=4326),
543                   }
544
545        elif postgis or spatialite:
546            # Using GEOSGeometry to compute the reference point on surface values
547            # -- since PostGIS also uses GEOS these should be the same.
548            ref = {'New Zealand' : Country.objects.get(name='New Zealand').mpoly.point_on_surface,
549                   'Texas' : Country.objects.get(name='Texas').mpoly.point_on_surface
550                   }
551
552        for c in Country.objects.point_on_surface():
553            if spatialite:
554                # XXX This seems to be a WKT-translation-related precision issue?
555                tol = 0.00001
556            else:
557                tol = 0.000000001
558            self.assertEqual(True, ref[c.name].equals_exact(c.point_on_surface, tol))
559
560    @no_mysql
561    @no_oracle
562    def test21_scale(self):
563        "Testing the `scale` GeoQuerySet method."
564        xfac, yfac = 2, 3
565        tol = 5 # XXX The low precision tolerance is for SpatiaLite
566        qs = Country.objects.scale(xfac, yfac, model_att='scaled')
567        for c in qs:
568            for p1, p2 in zip(c.mpoly, c.scaled):
569                for r1, r2 in zip(p1, p2):
570                    for c1, c2 in zip(r1.coords, r2.coords):
571                        self.assertAlmostEqual(c1[0] * xfac, c2[0], tol)
572                        self.assertAlmostEqual(c1[1] * yfac, c2[1], tol)
573
574    @no_mysql
575    @no_oracle
576    def test22_translate(self):
577        "Testing the `translate` GeoQuerySet method."
578        xfac, yfac = 5, -23
579        qs = Country.objects.translate(xfac, yfac, model_att='translated')
580        for c in qs:
581            for p1, p2 in zip(c.mpoly, c.translated):
582                for r1, r2 in zip(p1, p2):
583                    for c1, c2 in zip(r1.coords, r2.coords):
584                        # XXX The low precision is for SpatiaLite
585                        self.assertAlmostEqual(c1[0] + xfac, c2[0], 5)
586                        self.assertAlmostEqual(c1[1] + yfac, c2[1], 5)
587
588    @no_mysql
589    def test23_numgeom(self):
590        "Testing the `num_geom` GeoQuerySet method."
591        # Both 'countries' only have two geometries.
592        for c in Country.objects.num_geom(): self.assertEqual(2, c.num_geom)
593        for c in City.objects.filter(point__isnull=False).num_geom():
594            # Oracle will return 1 for the number of geometries on non-collections,
595            # whereas PostGIS will return None.
596            if postgis:
597                self.assertEqual(None, c.num_geom)
598            else:
599                self.assertEqual(1, c.num_geom)
600
601    @no_mysql
602    @no_spatialite # SpatiaLite can only count vertices in LineStrings
603    def test24_numpoints(self):
604        "Testing the `num_points` GeoQuerySet method."
605        for c in Country.objects.num_points():
606            self.assertEqual(c.mpoly.num_points, c.num_points)
607
608        if not oracle:
609            # Oracle cannot count vertices in Point geometries.
610            for c in City.objects.num_points(): self.assertEqual(1, c.num_points)
611
612    @no_mysql
613    def test25_geoset(self):
614        "Testing the `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods."
615        geom = Point(5, 23)
616        tol = 1
617        qs = Country.objects.all().difference(geom).sym_difference(geom).union(geom)
618
619        # XXX For some reason SpatiaLite does something screwey with the Texas geometry here.  Also,
620        # XXX it doesn't like the null intersection.
621        if spatialite:
622            qs = qs.exclude(name='Texas')
623        else:
624            qs = qs.intersection(geom)
625
626        for c in qs:
627            if oracle:
628                # Should be able to execute the queries; however, they won't be the same
629                # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or
630                # SpatiaLite).
631                pass
632            else:
633                self.assertEqual(c.mpoly.difference(geom), c.difference)
634                if not spatialite:
635                    self.assertEqual(c.mpoly.intersection(geom), c.intersection)
636                self.assertEqual(c.mpoly.sym_difference(geom), c.sym_difference)
637                self.assertEqual(c.mpoly.union(geom), c.union)
638
639    @no_mysql
640    def test26_inherited_geofields(self):
641        "Test GeoQuerySet methods on inherited Geometry fields."
642        # Creating a Pennsylvanian city.
643        mansfield = PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)')
644
645        # All transformation SQL will need to be performed on the
646        # _parent_ table.
647        qs = PennsylvaniaCity.objects.transform(32128)
648
649        self.assertEqual(1, qs.count())
650        for pc in qs: self.assertEqual(32128, pc.point.srid)
651
652    @no_mysql
653    @no_oracle
654    @no_spatialite
655    def test27_snap_to_grid(self):
656        "Testing GeoQuerySet.snap_to_grid()."
657        # Let's try and break snap_to_grid() with bad combinations of arguments.
658        for bad_args in ((), range(3), range(5)):
659            self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args)
660        for bad_args in (('1.0',), (1.0, None), tuple(map(unicode, range(4)))):
661            self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args)
662
663        # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
664        # from the world borders dataset he provides.
665        wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,'
666               '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,'
667               '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,'
668               '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,'
669               '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,'
670               '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,'
671               '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,'
672               '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))')
673        sm = Country.objects.create(name='San Marino', mpoly=fromstr(wkt))
674
675        # Because floating-point arithmitic isn't exact, we set a tolerance
676        # to pass into GEOS `equals_exact`.
677        tol = 0.000000001
678
679        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" WHERE "geoapp_country"."name" = 'San Marino';
680        ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))')
681        self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol))
682
683        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" WHERE "geoapp_country"."name" = 'San Marino';
684        ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))')
685        self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol))
686
687        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" WHERE "geoapp_country"."name" = 'San Marino';
688        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)))')
689        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))
690
691    @no_mysql
692    @no_spatialite
693    def test28_reverse(self):
694        "Testing GeoQuerySet.reverse_geom()."
695        coords = [ (-95.363151, 29.763374), (-95.448601, 29.713803) ]
696        Track.objects.create(name='Foo', line=LineString(coords))
697        t = Track.objects.reverse_geom().get(name='Foo')
698        coords.reverse()
699        self.assertEqual(tuple(coords), t.reverse_geom.coords)
700        if oracle:
701            self.assertRaises(TypeError, State.objects.reverse_geom)
702
703    @no_mysql
704    @no_oracle
705    @no_spatialite
706    def test29_force_rhr(self):
707        "Testing GeoQuerySet.force_rhr()."
708        rings = ( ( (0, 0), (5, 0), (0, 5), (0, 0) ),
709                  ( (1, 1), (1, 3), (3, 1), (1, 1) ),
710                  )
711        rhr_rings = ( ( (0, 0), (0, 5), (5, 0), (0, 0) ),
712                      ( (1, 1), (3, 1), (1, 3), (1, 1) ),
713                      )
714        State.objects.create(name='Foo', poly=Polygon(*rings))
715        s = State.objects.force_rhr().get(name='Foo')
716        self.assertEqual(rhr_rings, s.force_rhr.coords)
717
718    @no_mysql
719    @no_oracle
720    @no_spatialite
721    def test30_geohash(self):
722        "Testing GeoQuerySet.geohash()."
723        if not connection.ops.geohash: return
724        # Reference query:
725        # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston';
726        # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston';
727        ref_hash = '9vk1mfq8jx0c8e0386z6'
728        h1 = City.objects.geohash().get(name='Houston')
729        h2 = City.objects.geohash(precision=5).get(name='Houston')
730        self.assertEqual(ref_hash, h1.geohash)
731        self.assertEqual(ref_hash[:5], h2.geohash)
732
733from test_feeds import GeoFeedTest
734from test_regress import GeoRegressionTests
735from test_sitemaps import GeoSitemapTest