PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

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

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