tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. from __future__ import unicode_literals
  2. from django.contrib.gis.db.models import Collect, Count, Extent, F, Union
  3. from django.contrib.gis.geometry.backend import Geometry
  4. from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point
  5. from django.db import connection
  6. from django.test import TestCase, skipUnlessDBFeature
  7. from django.test.utils import override_settings
  8. from django.utils import timezone
  9. from ..utils import no_oracle
  10. from .models import (
  11. Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel,
  12. )
  13. @skipUnlessDBFeature("gis_enabled")
  14. class RelatedGeoModelTest(TestCase):
  15. fixtures = ['initial']
  16. def test02_select_related(self):
  17. "Testing `select_related` on geographic models (see #7126)."
  18. qs1 = City.objects.order_by('id')
  19. qs2 = City.objects.order_by('id').select_related()
  20. qs3 = City.objects.order_by('id').select_related('location')
  21. # Reference data for what's in the fixtures.
  22. cities = (
  23. ('Aurora', 'TX', -97.516111, 33.058333),
  24. ('Roswell', 'NM', -104.528056, 33.387222),
  25. ('Kecksburg', 'PA', -79.460734, 40.18476),
  26. )
  27. for qs in (qs1, qs2, qs3):
  28. for ref, c in zip(cities, qs):
  29. nm, st, lon, lat = ref
  30. self.assertEqual(nm, c.name)
  31. self.assertEqual(st, c.state)
  32. self.assertEqual(Point(lon, lat, srid=c.location.point.srid), c.location.point)
  33. @skipUnlessDBFeature("has_transform_method")
  34. def test03_transform_related(self):
  35. "Testing the `transform` GeoQuerySet method on related geographic models."
  36. # All the transformations are to state plane coordinate systems using
  37. # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot).
  38. tol = 0
  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. # Each city transformed to the SRID of their state plane coordinate system.
  44. transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'),
  45. ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'),
  46. ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'),
  47. )
  48. for name, srid, wkt in transformed:
  49. # Doing this implicitly sets `select_related` select the location.
  50. # TODO: Fix why this breaks on Oracle.
  51. qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point'))
  52. check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
  53. # Relations more than one level deep can be queried.
  54. self.assertEqual(list(Parcel.objects.transform(srid, field_name='city__location__point')), [])
  55. @skipUnlessDBFeature("supports_extent_aggr")
  56. def test_related_extent_aggregate(self):
  57. "Testing the `Extent` aggregate 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 New Mexico (Roswell).
  61. all_extent = (-104.528056, 29.763374, -79.460734, 40.18476)
  62. txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476)
  63. e1 = City.objects.aggregate(Extent('location__point'))['location__point__extent']
  64. e2 = City.objects.exclude(state='NM').aggregate(Extent('location__point'))['location__point__extent']
  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):
  71. self.assertAlmostEqual(ref_val, e_val, tol)
  72. @skipUnlessDBFeature("supports_extent_aggr")
  73. def test_related_extent_annotate(self):
  74. """
  75. Test annotation with Extent GeoAggregate.
  76. """
  77. cities = City.objects.annotate(points_extent=Extent('location__point')).order_by('name')
  78. tol = 4
  79. self.assertAlmostEqual(
  80. cities[0].points_extent,
  81. (-97.516111, 33.058333, -97.516111, 33.058333),
  82. tol
  83. )
  84. @skipUnlessDBFeature("has_unionagg_method")
  85. def test_related_union_aggregate(self):
  86. "Testing the `Union` aggregate on related geographic models."
  87. # This combines the Extent and Union aggregates into one query
  88. aggs = City.objects.aggregate(Union('location__point'))
  89. # These are the points that are components of the aggregate geographic
  90. # union that is returned. Each point # corresponds to City PK.
  91. p1 = Point(-104.528056, 33.387222)
  92. p2 = Point(-97.516111, 33.058333)
  93. p3 = Point(-79.460734, 40.18476)
  94. p4 = Point(-96.801611, 32.782057)
  95. p5 = Point(-95.363151, 29.763374)
  96. # The second union aggregate is for a union
  97. # query that includes limiting information in the WHERE clause (in other
  98. # words a `.filter()` precedes the call to `.aggregate(Union()`).
  99. ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326)
  100. ref_u2 = MultiPoint(p2, p3, srid=4326)
  101. u1 = City.objects.aggregate(Union('location__point'))['location__point__union']
  102. u2 = City.objects.exclude(
  103. name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'),
  104. ).aggregate(Union('location__point'))['location__point__union']
  105. u3 = aggs['location__point__union']
  106. self.assertEqual(type(u1), MultiPoint)
  107. self.assertEqual(type(u3), MultiPoint)
  108. # Ordering of points in the result of the union is not defined and
  109. # implementation-dependent (DB backend, GEOS version)
  110. self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1})
  111. self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2})
  112. self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3})
  113. def test05_select_related_fk_to_subclass(self):
  114. "Testing that calling select_related on a query over a model with an FK to a model subclass works"
  115. # Regression test for #9752.
  116. list(DirectoryEntry.objects.all().select_related())
  117. def test06_f_expressions(self):
  118. "Testing F() expressions on GeometryFields."
  119. # Constructing a dummy parcel border and getting the City instance for
  120. # assigning the FK.
  121. b1 = GEOSGeometry(
  122. 'POLYGON((-97.501205 33.052520,-97.501205 33.052576,'
  123. '-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))',
  124. srid=4326
  125. )
  126. pcity = City.objects.get(name='Aurora')
  127. # First parcel has incorrect center point that is equal to the City;
  128. # it also has a second border that is different from the first as a
  129. # 100ft buffer around the City.
  130. c1 = pcity.location.point
  131. c2 = c1.transform(2276, clone=True)
  132. b2 = c2.buffer(100)
  133. Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2)
  134. # Now creating a second Parcel where the borders are the same, just
  135. # in different coordinate systems. The center points are also the
  136. # same (but in different coordinate systems), and this time they
  137. # actually correspond to the centroid of the border.
  138. c1 = b1.centroid
  139. c2 = c1.transform(2276, clone=True)
  140. Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1)
  141. # Should return the second Parcel, which has the center within the
  142. # border.
  143. qs = Parcel.objects.filter(center1__within=F('border1'))
  144. self.assertEqual(1, len(qs))
  145. self.assertEqual('P2', qs[0].name)
  146. if connection.features.supports_transform:
  147. # This time center2 is in a different coordinate system and needs
  148. # to be wrapped in transformation SQL.
  149. qs = Parcel.objects.filter(center2__within=F('border1'))
  150. self.assertEqual(1, len(qs))
  151. self.assertEqual('P2', qs[0].name)
  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. if connection.features.supports_transform:
  158. # This time the city column should be wrapped in transformation SQL.
  159. qs = Parcel.objects.filter(border2__contains=F('city__location__point'))
  160. self.assertEqual(1, len(qs))
  161. self.assertEqual('P1', qs[0].name)
  162. def test07_values(self):
  163. "Testing values() and values_list() and GeoQuerySets."
  164. gqs = Location.objects.all()
  165. gvqs = Location.objects.values()
  166. gvlqs = Location.objects.values_list()
  167. # Incrementing through each of the models, dictionaries, and tuples
  168. # returned by the different types of GeoQuerySets.
  169. for m, d, t in zip(gqs, gvqs, gvlqs):
  170. # The values should be Geometry objects and not raw strings returned
  171. # by the spatial database.
  172. self.assertIsInstance(d['point'], Geometry)
  173. self.assertIsInstance(t[1], Geometry)
  174. self.assertEqual(m.point, d['point'])
  175. self.assertEqual(m.point, t[1])
  176. @override_settings(USE_TZ=True)
  177. def test_07b_values(self):
  178. "Testing values() and values_list() with aware datetime. See #21565."
  179. Event.objects.create(name="foo", when=timezone.now())
  180. list(Event.objects.values_list('when'))
  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. def test09_pk_relations(self):
  188. "Ensuring correct primary key column is selected across relations. See #10757."
  189. # The expected ID values -- notice the last two location IDs
  190. # are out of order. Dallas and Houston have location IDs that differ
  191. # from their PKs -- this is done to ensure that the related location
  192. # ID column is selected instead of ID column for the city.
  193. city_ids = (1, 2, 3, 4, 5)
  194. loc_ids = (1, 2, 3, 5, 4)
  195. ids_qs = City.objects.order_by('id').values('id', 'location__id')
  196. for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids):
  197. self.assertEqual(val_dict['id'], c_id)
  198. self.assertEqual(val_dict['location__id'], l_id)
  199. # TODO: fix on Oracle -- qs2 returns an empty result for an unknown reason
  200. @no_oracle
  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.assertIn('Aurora', names)
  211. self.assertIn('Kecksburg', names)
  212. # TODO: fix on Oracle -- get the following error because the SQL is ordered
  213. # by a geometry object, which Oracle apparently doesn't like:
  214. # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
  215. @no_oracle
  216. def test12a_count(self):
  217. "Testing `Count` aggregate on geo-fields."
  218. # The City, 'Fort Worth' uses the same location as Dallas.
  219. dallas = City.objects.get(name='Dallas')
  220. # Count annotation should be 2 for the Dallas location now.
  221. loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id)
  222. self.assertEqual(2, loc.num_cities)
  223. def test12b_count(self):
  224. "Testing `Count` aggregate on non geo-fields."
  225. # Should only be one author (Trevor Paglen) returned by this query, and
  226. # the annotation should have 3 for the number of books, see #11087.
  227. # Also testing with a values(), see #11489.
  228. qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
  229. vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1)
  230. self.assertEqual(1, len(qs))
  231. self.assertEqual(3, qs[0].num_books)
  232. self.assertEqual(1, len(vqs))
  233. self.assertEqual(3, vqs[0]['num_books'])
  234. # TODO: fix on Oracle -- get the following error because the SQL is ordered
  235. # by a geometry object, which Oracle apparently doesn't like:
  236. # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
  237. @no_oracle
  238. def test13c_count(self):
  239. "Testing `Count` aggregate with `.values()`. See #15305."
  240. qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities')
  241. self.assertEqual(1, len(qs))
  242. self.assertEqual(2, qs[0]['num_cities'])
  243. self.assertIsInstance(qs[0]['point'], GEOSGeometry)
  244. # TODO: The phantom model does appear on Oracle.
  245. @no_oracle
  246. def test13_select_related_null_fk(self):
  247. "Testing `select_related` on a nullable ForeignKey."
  248. Book.objects.create(title='Without Author')
  249. b = Book.objects.select_related('author').get(title='Without Author')
  250. # Should be `None`, and not a 'dummy' model.
  251. self.assertIsNone(b.author)
  252. @skipUnlessDBFeature("supports_collect_aggr")
  253. def test_collect(self):
  254. """
  255. Testing the `Collect` aggregate.
  256. """
  257. # Reference query:
  258. # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
  259. # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
  260. # WHERE "relatedapp_city"."state" = 'TX';
  261. ref_geom = GEOSGeometry(
  262. 'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,'
  263. '-95.363151 29.763374,-96.801611 32.782057)'
  264. )
  265. coll = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect']
  266. # Even though Dallas and Ft. Worth share same point, Collect doesn't
  267. # consolidate -- that's why 4 points in MultiPoint.
  268. self.assertEqual(4, len(coll))
  269. self.assertTrue(ref_geom.equals(coll))
  270. def test15_invalid_select_related(self):
  271. "Testing doing select_related on the related name manager of a unique FK. See #13934."
  272. qs = Article.objects.select_related('author__article')
  273. # This triggers TypeError when `get_default_columns` has no `local_only`
  274. # keyword. The TypeError is swallowed if QuerySet is actually
  275. # evaluated as list generation swallows TypeError in CPython.
  276. str(qs.query)
  277. def test16_annotated_date_queryset(self):
  278. "Ensure annotated date querysets work if spatial backend is used. See #14648."
  279. birth_years = [dt.year for dt in
  280. list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))]
  281. birth_years.sort()
  282. self.assertEqual([1950, 1974], birth_years)
  283. # TODO: Related tests for KML, GML, and distance lookups.