tests.py 15 KB

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