tests.py 14 KB

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