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