PageRenderTime 102ms CodeModel.GetById 17ms app.highlight 68ms RepoModel.GetById 2ms app.codeStats 0ms

/django/contrib/gis/tests/relatedapp/tests.py

https://code.google.com/p/mango-py/
Python | 284 lines | 178 code | 41 blank | 65 comment | 27 complexity | 55dc1a7fca0052bf6c58fd29cad5e085 MD5 | raw file
  1from django.test import TestCase
  2
  3from django.contrib.gis.geos import GEOSGeometry, Point, MultiPoint
  4from django.contrib.gis.db.models import Collect, Count, Extent, F, Union
  5from django.contrib.gis.geometry.backend import Geometry
  6from django.contrib.gis.tests.utils import mysql, oracle, no_mysql, no_oracle, no_spatialite
  7
  8from models import City, Location, DirectoryEntry, Parcel, Book, Author, Article
  9
 10class RelatedGeoModelTest(TestCase):
 11
 12    def test02_select_related(self):
 13        "Testing `select_related` on geographic models (see #7126)."
 14        qs1 = City.objects.all()
 15        qs2 = City.objects.select_related()
 16        qs3 = City.objects.select_related('location')
 17
 18        # Reference data for what's in the fixtures.
 19        cities = (
 20            ('Aurora', 'TX', -97.516111, 33.058333),
 21            ('Roswell', 'NM', -104.528056, 33.387222),
 22            ('Kecksburg', 'PA',  -79.460734, 40.18476),
 23        )
 24
 25        for qs in (qs1, qs2, qs3):
 26            for ref, c in zip(cities, qs):
 27                nm, st, lon, lat = ref
 28                self.assertEqual(nm, c.name)
 29                self.assertEqual(st, c.state)
 30                self.assertEqual(Point(lon, lat), c.location.point)
 31
 32    @no_mysql
 33    def test03_transform_related(self):
 34        "Testing the `transform` GeoQuerySet method on related geographic models."
 35        # All the transformations are to state plane coordinate systems using
 36        # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot).
 37        tol = 0
 38
 39        def check_pnt(ref, pnt):
 40            self.assertAlmostEqual(ref.x, pnt.x, tol)
 41            self.assertAlmostEqual(ref.y, pnt.y, tol)
 42            self.assertEqual(ref.srid, pnt.srid)
 43
 44        # Each city transformed to the SRID of their state plane coordinate system.
 45        transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'),
 46                       ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'),
 47                       ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'),
 48                       )
 49
 50        for name, srid, wkt in transformed:
 51            # Doing this implicitly sets `select_related` select the location.
 52            # TODO: Fix why this breaks on Oracle.
 53            qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point'))
 54            check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
 55
 56    @no_mysql
 57    @no_spatialite
 58    def test04a_related_extent_aggregate(self):
 59        "Testing the `extent` GeoQuerySet aggregates on related geographic models."
 60        # This combines the Extent and Union aggregates into one query
 61        aggs = City.objects.aggregate(Extent('location__point'))
 62
 63        # One for all locations, one that excludes New Mexico (Roswell).
 64        all_extent = (-104.528056, 29.763374, -79.460734, 40.18476)
 65        txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476)
 66        e1 = City.objects.extent(field_name='location__point')
 67        e2 = City.objects.exclude(state='NM').extent(field_name='location__point')
 68        e3 = aggs['location__point__extent']
 69
 70        # The tolerance value is to four decimal places because of differences
 71        # between the Oracle and PostGIS spatial backends on the extent calculation.
 72        tol = 4
 73        for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]:
 74            for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol)
 75
 76    @no_mysql
 77    def test04b_related_union_aggregate(self):
 78        "Testing the `unionagg` GeoQuerySet aggregates on related geographic models."
 79        # This combines the Extent and Union aggregates into one query
 80        aggs = City.objects.aggregate(Union('location__point'))
 81
 82        # These are the points that are components of the aggregate geographic
 83        # union that is returned.  Each point # corresponds to City PK.
 84        p1 = Point(-104.528056, 33.387222)
 85        p2 = Point(-97.516111, 33.058333)
 86        p3 = Point(-79.460734, 40.18476)
 87        p4 = Point(-96.801611, 32.782057)
 88        p5 = Point(-95.363151, 29.763374)
 89
 90        # Creating the reference union geometry depending on the spatial backend,
 91        # as Oracle will have a different internal ordering of the component
 92        # geometries than PostGIS.  The second union aggregate is for a union
 93        # query that includes limiting information in the WHERE clause (in other
 94        # words a `.filter()` precedes the call to `.unionagg()`).
 95        if oracle:
 96            ref_u1 = MultiPoint(p4, p5, p3, p1, p2, srid=4326)
 97            ref_u2 = MultiPoint(p3, p2, srid=4326)
 98        else:
 99            # Looks like PostGIS points by longitude value.
100            ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326)
101            ref_u2 = MultiPoint(p2, p3, srid=4326)
102
103        u1 = City.objects.unionagg(field_name='location__point')
104        u2 = City.objects.exclude(name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth')).unionagg(field_name='location__point')
105        u3 = aggs['location__point__union']
106
107        self.assertEqual(ref_u1, u1)
108        self.assertEqual(ref_u2, u2)
109        self.assertEqual(ref_u1, u3)
110
111    def test05_select_related_fk_to_subclass(self):
112        "Testing that calling select_related on a query over a model with an FK to a model subclass works"
113        # Regression test for #9752.
114        l = list(DirectoryEntry.objects.all().select_related())
115
116    def test06_f_expressions(self):
117        "Testing F() expressions on GeometryFields."
118        # Constructing a dummy parcel border and getting the City instance for
119        # assigning the FK.
120        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)
121        pcity = City.objects.get(name='Aurora')
122
123        # First parcel has incorrect center point that is equal to the City;
124        # it also has a second border that is different from the first as a
125        # 100ft buffer around the City.
126        c1 = pcity.location.point
127        c2 = c1.transform(2276, clone=True)
128        b2 = c2.buffer(100)
129        p1 = Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2)
130
131        # Now creating a second Parcel where the borders are the same, just
132        # in different coordinate systems.  The center points are also the
133        # the same (but in different coordinate systems), and this time they
134        # actually correspond to the centroid of the border.
135        c1 = b1.centroid
136        c2 = c1.transform(2276, clone=True)
137        p2 = Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1)
138
139        # Should return the second Parcel, which has the center within the
140        # border.
141        qs = Parcel.objects.filter(center1__within=F('border1'))
142        self.assertEqual(1, len(qs))
143        self.assertEqual('P2', qs[0].name)
144
145        if not mysql:
146            # This time center2 is in a different coordinate system and needs
147            # to be wrapped in transformation SQL.
148            qs = Parcel.objects.filter(center2__within=F('border1'))
149            self.assertEqual(1, len(qs))
150            self.assertEqual('P2', qs[0].name)
151
152        # Should return the first Parcel, which has the center point equal
153        # to the point in the City ForeignKey.
154        qs = Parcel.objects.filter(center1=F('city__location__point'))
155        self.assertEqual(1, len(qs))
156        self.assertEqual('P1', qs[0].name)
157
158        if not mysql:
159            # This time the city column should be wrapped in transformation SQL.
160            qs = Parcel.objects.filter(border2__contains=F('city__location__point'))
161            self.assertEqual(1, len(qs))
162            self.assertEqual('P1', qs[0].name)
163
164    def test07_values(self):
165        "Testing values() and values_list() and GeoQuerySets."
166        # GeoQuerySet and GeoValuesQuerySet, and GeoValuesListQuerySet respectively.
167        gqs = Location.objects.all()
168        gvqs = Location.objects.values()
169        gvlqs = Location.objects.values_list()
170
171        # Incrementing through each of the models, dictionaries, and tuples
172        # returned by the different types of GeoQuerySets.
173        for m, d, t in zip(gqs, gvqs, gvlqs):
174            # The values should be Geometry objects and not raw strings returned
175            # by the spatial database.
176            self.assertTrue(isinstance(d['point'], Geometry))
177            self.assertTrue(isinstance(t[1], Geometry))
178            self.assertEqual(m.point, d['point'])
179            self.assertEqual(m.point, t[1])
180
181    def test08_defer_only(self):
182        "Testing defer() and only() on Geographic models."
183        qs = Location.objects.all()
184        def_qs = Location.objects.defer('point')
185        for loc, def_loc in zip(qs, def_qs):
186            self.assertEqual(loc.point, def_loc.point)
187
188    def test09_pk_relations(self):
189        "Ensuring correct primary key column is selected across relations. See #10757."
190        # The expected ID values -- notice the last two location IDs
191        # are out of order.  Dallas and Houston have location IDs that differ
192        # from their PKs -- this is done to ensure that the related location
193        # ID column is selected instead of ID column for the city.
194        city_ids = (1, 2, 3, 4, 5)
195        loc_ids = (1, 2, 3, 5, 4)
196        ids_qs = City.objects.order_by('id').values('id', 'location__id')
197        for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids):
198            self.assertEqual(val_dict['id'], c_id)
199            self.assertEqual(val_dict['location__id'], l_id)
200
201    def test10_combine(self):
202        "Testing the combination of two GeoQuerySets.  See #10807."
203        buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1)
204        buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1)
205        qs1 = City.objects.filter(location__point__within=buf1)
206        qs2 = City.objects.filter(location__point__within=buf2)
207        combined = qs1 | qs2
208        names = [c.name for c in combined]
209        self.assertEqual(2, len(names))
210        self.assertTrue('Aurora' in names)
211        self.assertTrue('Kecksburg' in names)
212
213    def test11_geoquery_pickle(self):
214        "Ensuring GeoQuery objects are unpickled correctly.  See #10839."
215        import pickle
216        from django.contrib.gis.db.models.sql import GeoQuery
217        qs = City.objects.all()
218        q_str = pickle.dumps(qs.query)
219        q = pickle.loads(q_str)
220        self.assertEqual(GeoQuery, q.__class__)
221
222    # TODO: fix on Oracle -- get the following error because the SQL is ordered
223    # by a geometry object, which Oracle apparently doesn't like:
224    #  ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
225    @no_oracle
226    def test12a_count(self):
227        "Testing `Count` aggregate use with the `GeoManager` on geo-fields."
228        # The City, 'Fort Worth' uses the same location as Dallas.
229        dallas = City.objects.get(name='Dallas')
230
231        # Count annotation should be 2 for the Dallas location now.
232        loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id)
233        self.assertEqual(2, loc.num_cities)
234
235    def test12b_count(self):
236        "Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087."
237        # Should only be one author (Trevor Paglen) returned by this query, and
238        # the annotation should have 3 for the number of books, see #11087.
239        # Also testing with a `GeoValuesQuerySet`, see #11489.
240        qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
241        vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1)
242        self.assertEqual(1, len(qs))
243        self.assertEqual(3, qs[0].num_books)
244        self.assertEqual(1, len(vqs))
245        self.assertEqual(3, vqs[0]['num_books'])
246
247    # TODO: The phantom model does appear on Oracle.
248    @no_oracle
249    def test13_select_related_null_fk(self):
250        "Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381."
251        no_author = Book.objects.create(title='Without Author')
252        b = Book.objects.select_related('author').get(title='Without Author')
253        # Should be `None`, and not a 'dummy' model.
254        self.assertEqual(None, b.author)
255
256    @no_mysql
257    @no_oracle
258    @no_spatialite
259    def test14_collect(self):
260        "Testing the `collect` GeoQuerySet method and `Collect` aggregate."
261        # Reference query:
262        # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
263        #    "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
264        #    WHERE "relatedapp_city"."state" = 'TX';
265        ref_geom = GEOSGeometry('MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,-95.363151 29.763374,-96.801611 32.782057)')
266
267        c1 = City.objects.filter(state='TX').collect(field_name='location__point')
268        c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect']
269
270        for coll in (c1, c2):
271            # Even though Dallas and Ft. Worth share same point, Collect doesn't
272            # consolidate -- that's why 4 points in MultiPoint.
273            self.assertEqual(4, len(coll))
274            self.assertEqual(ref_geom, coll)
275
276    def test15_invalid_select_related(self):
277        "Testing doing select_related on the related name manager of a unique FK. See #13934."
278        qs = Article.objects.select_related('author__article')
279        # This triggers TypeError when `get_default_columns` has no `local_only`
280        # keyword.  The TypeError is swallowed if QuerySet is actually
281        # evaluated as list generation swallows TypeError in CPython.
282        sql = str(qs.query)
283
284    # TODO: Related tests for KML, GML, and distance lookups.