tests.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. from django.contrib.gis.db.models.functions import (
  2. Area, Distance, Length, Perimeter, Transform, Union,
  3. )
  4. from django.contrib.gis.geos import GEOSGeometry, LineString, Point
  5. from django.contrib.gis.measure import D # alias for Distance
  6. from django.db import NotSupportedError, connection
  7. from django.db.models import (
  8. Case, Count, Exists, F, IntegerField, OuterRef, Q, Value, When,
  9. )
  10. from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
  11. from ..utils import FuncTestMixin
  12. from .models import (
  13. AustraliaCity, CensusZipcode, Interstate, SouthTexasCity, SouthTexasCityFt,
  14. SouthTexasInterstate, SouthTexasZipcode,
  15. )
  16. class DistanceTest(TestCase):
  17. fixtures = ['initial']
  18. def setUp(self):
  19. # A point we are testing distances with -- using a WGS84
  20. # coordinate that'll be implicitly transformed to that to
  21. # the coordinate system of the field, EPSG:32140 (Texas South Central
  22. # w/units in meters)
  23. self.stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
  24. # Another one for Australia
  25. self.au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326)
  26. def get_names(self, qs):
  27. cities = [c.name for c in qs]
  28. cities.sort()
  29. return cities
  30. def test_init(self):
  31. """
  32. Test initialization of distance models.
  33. """
  34. self.assertEqual(9, SouthTexasCity.objects.count())
  35. self.assertEqual(9, SouthTexasCityFt.objects.count())
  36. self.assertEqual(11, AustraliaCity.objects.count())
  37. self.assertEqual(4, SouthTexasZipcode.objects.count())
  38. self.assertEqual(4, CensusZipcode.objects.count())
  39. self.assertEqual(1, Interstate.objects.count())
  40. self.assertEqual(1, SouthTexasInterstate.objects.count())
  41. @skipUnlessDBFeature("supports_dwithin_lookup")
  42. def test_dwithin(self):
  43. """
  44. Test the `dwithin` lookup type.
  45. """
  46. # Distances -- all should be equal (except for the
  47. # degree/meter pair in au_cities, that's somewhat
  48. # approximate).
  49. tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]
  50. au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]
  51. # Expected cities for Australia and Texas.
  52. tx_cities = ['Downtown Houston', 'Southside Place']
  53. au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong']
  54. # Performing distance queries on two projected coordinate systems one
  55. # with units in meters and the other in units of U.S. survey feet.
  56. for dist in tx_dists:
  57. if isinstance(dist, tuple):
  58. dist1, dist2 = dist
  59. else:
  60. dist1 = dist2 = dist
  61. qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1))
  62. qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2))
  63. for qs in qs1, qs2:
  64. with self.subTest(dist=dist, qs=qs):
  65. self.assertEqual(tx_cities, self.get_names(qs))
  66. # With a complex geometry expression
  67. self.assertFalse(SouthTexasCity.objects.exclude(point__dwithin=(Union('point', 'point'), 0)))
  68. # Now performing the `dwithin` queries on a geodetic coordinate system.
  69. for dist in au_dists:
  70. with self.subTest(dist=dist):
  71. type_error = isinstance(dist, D) and not connection.ops.oracle
  72. if isinstance(dist, tuple):
  73. if connection.ops.oracle or connection.ops.spatialite:
  74. # Result in meters
  75. dist = dist[1]
  76. else:
  77. # Result in units of the field
  78. dist = dist[0]
  79. # Creating the query set.
  80. qs = AustraliaCity.objects.order_by('name')
  81. if type_error:
  82. # A ValueError should be raised on PostGIS when trying to
  83. # pass Distance objects into a DWithin query using a
  84. # geodetic field.
  85. with self.assertRaises(ValueError):
  86. AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count()
  87. else:
  88. self.assertEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
  89. @skipUnlessDBFeature("supports_distances_lookups")
  90. def test_distance_lookups(self):
  91. """
  92. Test the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.
  93. """
  94. # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole'
  95. # (thus, Houston and Southside place will be excluded as tested in
  96. # the `test02_dwithin` above).
  97. for model in [SouthTexasCity, SouthTexasCityFt]:
  98. stx_pnt = self.stx_pnt.transform(model._meta.get_field('point').srid, clone=True)
  99. qs = model.objects.filter(point__distance_gte=(stx_pnt, D(km=7))).filter(
  100. point__distance_lte=(stx_pnt, D(km=20)),
  101. )
  102. cities = self.get_names(qs)
  103. self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place'])
  104. # Doing a distance query using Polygons instead of a Point.
  105. z = SouthTexasZipcode.objects.get(name='77005')
  106. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275)))
  107. self.assertEqual(['77025', '77401'], self.get_names(qs))
  108. # If we add a little more distance 77002 should be included.
  109. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300)))
  110. self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))
  111. @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
  112. def test_geodetic_distance_lookups(self):
  113. """
  114. Test distance lookups on geodetic coordinate systems.
  115. """
  116. # Line is from Canberra to Sydney. Query is for all other cities within
  117. # a 100km of that line (which should exclude only Hobart & Adelaide).
  118. line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326)
  119. dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100)))
  120. expected_cities = [
  121. 'Batemans Bay', 'Canberra', 'Hillsdale',
  122. 'Melbourne', 'Mittagong', 'Shellharbour',
  123. 'Sydney', 'Thirroul', 'Wollongong',
  124. ]
  125. if connection.ops.spatialite:
  126. # SpatiaLite is less accurate and returns 102.8km for Batemans Bay.
  127. expected_cities.pop(0)
  128. self.assertEqual(expected_cities, self.get_names(dist_qs))
  129. msg = "2, 3, or 4-element tuple required for 'distance_lte' lookup."
  130. with self.assertRaisesMessage(ValueError, msg): # Too many params.
  131. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4', None)))
  132. with self.assertRaisesMessage(ValueError, msg): # Too few params.
  133. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
  134. msg = "For 4-element tuples the last argument must be the 'spheroid' directive."
  135. with self.assertRaisesMessage(ValueError, msg):
  136. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4')))
  137. # Getting all cities w/in 550 miles of Hobart.
  138. hobart = AustraliaCity.objects.get(name='Hobart')
  139. qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550)))
  140. cities = self.get_names(qs)
  141. self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])
  142. # Cities that are either really close or really far from Wollongong --
  143. # and using different units of distance.
  144. wollongong = AustraliaCity.objects.get(name='Wollongong')
  145. d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles.
  146. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
  147. gq1 = Q(point__distance_lte=(wollongong.point, d1))
  148. gq2 = Q(point__distance_gte=(wollongong.point, d2))
  149. qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2)
  150. # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
  151. # instead (we should get the same results b/c accuracy variance won't matter
  152. # in this test case).
  153. querysets = [qs1]
  154. if connection.features.has_DistanceSpheroid_function:
  155. gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
  156. gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
  157. qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4)
  158. querysets.append(qs2)
  159. for qs in querysets:
  160. cities = self.get_names(qs)
  161. self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
  162. @skipUnlessDBFeature("supports_distances_lookups")
  163. def test_distance_lookups_with_expression_rhs(self):
  164. stx_pnt = self.stx_pnt.transform(SouthTexasCity._meta.get_field('point').srid, clone=True)
  165. qs = SouthTexasCity.objects.filter(
  166. point__distance_lte=(stx_pnt, F('radius')),
  167. ).order_by('name')
  168. self.assertEqual(
  169. self.get_names(qs),
  170. ['Bellaire', 'Downtown Houston', 'Southside Place', 'West University Place']
  171. )
  172. # With a combined expression
  173. qs = SouthTexasCity.objects.filter(
  174. point__distance_lte=(stx_pnt, F('radius') * 2),
  175. ).order_by('name')
  176. self.assertEqual(len(qs), 5)
  177. self.assertIn('Pearland', self.get_names(qs))
  178. # With spheroid param
  179. if connection.features.supports_distance_geodetic:
  180. hobart = AustraliaCity.objects.get(name='Hobart')
  181. AustraliaCity.objects.update(ref_point=hobart.point)
  182. for ref_point in [hobart.point, F('ref_point')]:
  183. qs = AustraliaCity.objects.filter(
  184. point__distance_lte=(ref_point, F('radius') * 70, 'spheroid'),
  185. ).order_by('name')
  186. self.assertEqual(self.get_names(qs), ['Canberra', 'Hobart', 'Melbourne'])
  187. # With a complex geometry expression
  188. self.assertFalse(SouthTexasCity.objects.filter(point__distance_gt=(Union('point', 'point'), 0)))
  189. self.assertEqual(
  190. SouthTexasCity.objects.filter(point__distance_lte=(Union('point', 'point'), 0)).count(),
  191. SouthTexasCity.objects.count(),
  192. )
  193. @skipUnlessDBFeature('supports_distances_lookups')
  194. def test_distance_annotation_group_by(self):
  195. stx_pnt = self.stx_pnt.transform(
  196. SouthTexasCity._meta.get_field('point').srid,
  197. clone=True,
  198. )
  199. qs = SouthTexasCity.objects.annotate(
  200. relative_distance=Case(
  201. When(point__distance_lte=(stx_pnt, D(km=20)), then=Value(20)),
  202. default=Value(100),
  203. output_field=IntegerField(),
  204. ),
  205. ).values('relative_distance').annotate(count=Count('pk'))
  206. self.assertCountEqual(qs, [
  207. {'relative_distance': 20, 'count': 5},
  208. {'relative_distance': 100, 'count': 4},
  209. ])
  210. def test_mysql_geodetic_distance_error(self):
  211. if not connection.ops.mysql:
  212. self.skipTest('This is a MySQL-specific test.')
  213. msg = 'Only numeric values of degree units are allowed on geodetic distance queries.'
  214. with self.assertRaisesMessage(ValueError, msg):
  215. AustraliaCity.objects.filter(point__distance_lte=(Point(0, 0), D(m=100))).exists()
  216. @skipUnlessDBFeature('supports_dwithin_lookup')
  217. def test_dwithin_subquery(self):
  218. """dwithin lookup in a subquery using OuterRef as a parameter."""
  219. qs = CensusZipcode.objects.annotate(
  220. annotated_value=Exists(SouthTexasCity.objects.filter(
  221. point__dwithin=(OuterRef('poly'), D(m=10)),
  222. ))
  223. ).filter(annotated_value=True)
  224. self.assertEqual(self.get_names(qs), ['77002', '77025', '77401'])
  225. @skipUnlessDBFeature('supports_dwithin_lookup', 'supports_dwithin_distance_expr')
  226. def test_dwithin_with_expression_rhs(self):
  227. # LineString of Wollongong and Adelaide coords.
  228. ls = LineString(((150.902, -34.4245), (138.6, -34.9258)), srid=4326)
  229. qs = AustraliaCity.objects.filter(
  230. point__dwithin=(ls, F('allowed_distance')),
  231. ).order_by('name')
  232. self.assertEqual(
  233. self.get_names(qs),
  234. ['Adelaide', 'Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong'],
  235. )
  236. @skipIfDBFeature('supports_dwithin_distance_expr')
  237. def test_dwithin_with_expression_rhs_not_supported(self):
  238. ls = LineString(((150.902, -34.4245), (138.6, -34.9258)), srid=4326)
  239. msg = (
  240. 'This backend does not support expressions for specifying '
  241. 'distance in the dwithin lookup.'
  242. )
  243. with self.assertRaisesMessage(NotSupportedError, msg):
  244. list(AustraliaCity.objects.filter(
  245. point__dwithin=(ls, F('allowed_distance')),
  246. ))
  247. '''
  248. =============================
  249. Distance functions on PostGIS
  250. =============================
  251. | Projected Geometry | Lon/lat Geometry | Geography (4326)
  252. ST_Distance(geom1, geom2) | OK (meters) | :-( (degrees) | OK (meters)
  253. ST_Distance(geom1, geom2, use_spheroid=False) | N/A | N/A | OK (meters), less accurate, quick
  254. Distance_Sphere(geom1, geom2) | N/A | OK (meters) | N/A
  255. Distance_Spheroid(geom1, geom2, spheroid) | N/A | OK (meters) | N/A
  256. ST_Perimeter(geom1) | OK | :-( (degrees) | OK
  257. ================================
  258. Distance functions on SpatiaLite
  259. ================================
  260. | Projected Geometry | Lon/lat Geometry
  261. ST_Distance(geom1, geom2) | OK (meters) | N/A
  262. ST_Distance(geom1, geom2, use_ellipsoid=True) | N/A | OK (meters)
  263. ST_Distance(geom1, geom2, use_ellipsoid=False) | N/A | OK (meters), less accurate, quick
  264. Perimeter(geom1) | OK | :-( (degrees)
  265. ''' # NOQA
  266. class DistanceFunctionsTests(FuncTestMixin, TestCase):
  267. fixtures = ['initial']
  268. @skipUnlessDBFeature("has_Area_function")
  269. def test_area(self):
  270. # Reference queries:
  271. # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
  272. area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
  273. # Tolerance has to be lower for Oracle
  274. tol = 2
  275. for i, z in enumerate(SouthTexasZipcode.objects.annotate(area=Area('poly')).order_by('name')):
  276. self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
  277. @skipUnlessDBFeature("has_Distance_function")
  278. def test_distance_simple(self):
  279. """
  280. Test a simple distance query, with projected coordinates and without
  281. transformation.
  282. """
  283. lagrange = GEOSGeometry('POINT(805066.295722839 4231496.29461335)', 32140)
  284. houston = SouthTexasCity.objects.annotate(dist=Distance('point', lagrange)).order_by('id').first()
  285. tol = 2 if connection.ops.oracle else 5
  286. self.assertAlmostEqual(
  287. houston.dist.m,
  288. 147075.069813,
  289. tol
  290. )
  291. @skipUnlessDBFeature("has_Distance_function", "has_Transform_function")
  292. def test_distance_projected(self):
  293. """
  294. Test the `Distance` function on projected coordinate systems.
  295. """
  296. # The point for La Grange, TX
  297. lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
  298. # Reference distances in feet and in meters. Got these values from
  299. # using the provided raw SQL statements.
  300. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
  301. # FROM distapp_southtexascity;
  302. m_distances = [147075.069813, 139630.198056, 140888.552826,
  303. 138809.684197, 158309.246259, 212183.594374,
  304. 70870.188967, 165337.758878, 139196.085105]
  305. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
  306. # FROM distapp_southtexascityft;
  307. ft_distances = [482528.79154625, 458103.408123001, 462231.860397575,
  308. 455411.438904354, 519386.252102563, 696139.009211594,
  309. 232513.278304279, 542445.630586414, 456679.155883207]
  310. # Testing using different variations of parameters and using models
  311. # with different projected coordinate systems.
  312. dist1 = SouthTexasCity.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  313. dist2 = SouthTexasCityFt.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  314. dist_qs = [dist1, dist2]
  315. # Ensuring expected distances are returned for each distance queryset.
  316. for qs in dist_qs:
  317. for i, c in enumerate(qs):
  318. with self.subTest(c=c):
  319. self.assertAlmostEqual(m_distances[i], c.distance.m, -1)
  320. self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, -1)
  321. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  322. def test_distance_geodetic(self):
  323. """
  324. Test the `Distance` function on geodetic coordinate systems.
  325. """
  326. # Testing geodetic distance calculation with a non-point geometry
  327. # (a LineString of Wollongong and Shellharbour coords).
  328. ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326)
  329. # Reference query:
  330. # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
  331. # FROM distapp_australiacity ORDER BY name;
  332. distances = [1120954.92533513, 140575.720018241, 640396.662906304,
  333. 60580.9693849269, 972807.955955075, 568451.8357838,
  334. 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
  335. qs = AustraliaCity.objects.annotate(distance=Distance('point', ls)).order_by('name')
  336. for city, distance in zip(qs, distances):
  337. with self.subTest(city=city, distance=distance):
  338. # Testing equivalence to within a meter (kilometer on SpatiaLite).
  339. tol = -3 if connection.ops.spatialite else 0
  340. self.assertAlmostEqual(distance, city.distance.m, tol)
  341. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  342. def test_distance_geodetic_spheroid(self):
  343. tol = 2 if connection.ops.oracle else 4
  344. # Got the reference distances using the raw SQL statements:
  345. # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
  346. # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
  347. # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326))
  348. # FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
  349. spheroid_distances = [
  350. 60504.0628957201, 77023.9489850262, 49154.8867574404,
  351. 90847.4358768573, 217402.811919332, 709599.234564757,
  352. 640011.483550888, 7772.00667991925, 1047861.78619339,
  353. 1165126.55236034,
  354. ]
  355. sphere_distances = [
  356. 60580.9693849267, 77144.0435286473, 49199.4415344719,
  357. 90804.7533823494, 217713.384600405, 709134.127242793,
  358. 639828.157159169, 7786.82949717788, 1049204.06569028,
  359. 1162623.7238134,
  360. ]
  361. # Testing with spheroid distances first.
  362. hillsdale = AustraliaCity.objects.get(name='Hillsdale')
  363. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  364. distance=Distance('point', hillsdale.point, spheroid=True)
  365. ).order_by('id')
  366. for i, c in enumerate(qs):
  367. with self.subTest(c=c):
  368. self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
  369. if connection.ops.postgis or connection.ops.spatialite:
  370. # PostGIS uses sphere-only distances by default, testing these as well.
  371. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  372. distance=Distance('point', hillsdale.point)
  373. ).order_by('id')
  374. for i, c in enumerate(qs):
  375. with self.subTest(c=c):
  376. self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
  377. @skipIfDBFeature("supports_distance_geodetic")
  378. @skipUnlessDBFeature("has_Distance_function")
  379. def test_distance_function_raw_result(self):
  380. distance = Interstate.objects.annotate(
  381. d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)),
  382. ).first().d
  383. self.assertEqual(distance, 1)
  384. @skipUnlessDBFeature("has_Distance_function")
  385. def test_distance_function_d_lookup(self):
  386. qs = Interstate.objects.annotate(
  387. d=Distance(Point(0, 0, srid=3857), Point(0, 1, srid=3857)),
  388. ).filter(d=D(m=1))
  389. self.assertTrue(qs.exists())
  390. @skipUnlessDBFeature('supports_tolerance_parameter')
  391. def test_distance_function_tolerance_escaping(self):
  392. qs = Interstate.objects.annotate(
  393. d=Distance(
  394. Point(500, 500, srid=3857),
  395. Point(0, 0, srid=3857),
  396. tolerance='0.05) = 1 OR 1=1 OR (1+1',
  397. ),
  398. ).filter(d=D(m=1)).values('pk')
  399. msg = 'The tolerance parameter has the wrong type'
  400. with self.assertRaisesMessage(TypeError, msg):
  401. qs.exists()
  402. @skipUnlessDBFeature('supports_tolerance_parameter')
  403. def test_distance_function_tolerance(self):
  404. # Tolerance is greater than distance.
  405. qs = Interstate.objects.annotate(
  406. d=Distance(
  407. Point(0, 0, srid=3857),
  408. Point(1, 1, srid=3857),
  409. tolerance=1.5,
  410. ),
  411. ).filter(d=0).values('pk')
  412. self.assertIs(qs.exists(), True)
  413. @skipIfDBFeature("supports_distance_geodetic")
  414. @skipUnlessDBFeature("has_Distance_function")
  415. def test_distance_function_raw_result_d_lookup(self):
  416. qs = Interstate.objects.annotate(
  417. d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)),
  418. ).filter(d=D(m=1))
  419. msg = 'Distance measure is supplied, but units are unknown for result.'
  420. with self.assertRaisesMessage(ValueError, msg):
  421. list(qs)
  422. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function')
  423. def test_distance_transform(self):
  424. """
  425. Test the `Distance` function used with `Transform` on a geographic field.
  426. """
  427. # We'll be using a Polygon (created by buffering the centroid
  428. # of 77005 to 100m) -- which aren't allowed in geographic distance
  429. # queries normally, however our field has been transformed to
  430. # a non-geographic system.
  431. z = SouthTexasZipcode.objects.get(name='77005')
  432. # Reference query:
  433. # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140),
  434. # ST_GeomFromText('<buffer_wkt>', 32140))
  435. # FROM "distapp_censuszipcode";
  436. dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
  437. # Having our buffer in the SRID of the transformation and of the field
  438. # -- should get the same results. The first buffer has no need for
  439. # transformation SQL because it is the same SRID as what was given
  440. # to `transform()`. The second buffer will need to be transformed,
  441. # however.
  442. buf1 = z.poly.centroid.buffer(100)
  443. buf2 = buf1.transform(4269, clone=True)
  444. ref_zips = ['77002', '77025', '77401']
  445. for buf in [buf1, buf2]:
  446. qs = CensusZipcode.objects.exclude(name='77005').annotate(
  447. distance=Distance(Transform('poly', 32140), buf)
  448. ).order_by('name')
  449. self.assertEqual(ref_zips, sorted(c.name for c in qs))
  450. for i, z in enumerate(qs):
  451. self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
  452. @skipUnlessDBFeature("has_Distance_function")
  453. def test_distance_order_by(self):
  454. qs = SouthTexasCity.objects.annotate(distance=Distance('point', Point(3, 3, srid=32140))).order_by(
  455. 'distance'
  456. ).values_list('name', flat=True).filter(name__in=('San Antonio', 'Pearland'))
  457. self.assertSequenceEqual(qs, ['San Antonio', 'Pearland'])
  458. @skipUnlessDBFeature("has_Length_function")
  459. def test_length(self):
  460. """
  461. Test the `Length` function.
  462. """
  463. # Reference query (should use `length_spheroid`).
  464. # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
  465. # AUTHORITY["EPSG","7030"]]');
  466. len_m1 = 473504.769553813
  467. len_m2 = 4617.668
  468. if connection.features.supports_length_geodetic:
  469. qs = Interstate.objects.annotate(length=Length('path'))
  470. tol = 2 if connection.ops.oracle else 3
  471. self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
  472. # TODO: test with spheroid argument (True and False)
  473. else:
  474. # Does not support geodetic coordinate systems.
  475. with self.assertRaises(NotSupportedError):
  476. list(Interstate.objects.annotate(length=Length('path')))
  477. # Now doing length on a projected coordinate system.
  478. i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10')
  479. self.assertAlmostEqual(len_m2, i10.length.m, 2)
  480. self.assertTrue(
  481. SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists()
  482. )
  483. # Length with an explicit geometry value.
  484. qs = Interstate.objects.annotate(length=Length(i10.path))
  485. self.assertAlmostEqual(qs.first().length.m, len_m2, 2)
  486. @skipUnlessDBFeature("has_Perimeter_function")
  487. def test_perimeter(self):
  488. """
  489. Test the `Perimeter` function.
  490. """
  491. # Reference query:
  492. # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
  493. perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697]
  494. tol = 2 if connection.ops.oracle else 7
  495. qs = SouthTexasZipcode.objects.annotate(perimeter=Perimeter('poly')).order_by('name')
  496. for i, z in enumerate(qs):
  497. self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)
  498. # Running on points; should return 0.
  499. qs = SouthTexasCity.objects.annotate(perim=Perimeter('point'))
  500. for city in qs:
  501. self.assertEqual(0, city.perim.m)
  502. @skipUnlessDBFeature("has_Perimeter_function")
  503. def test_perimeter_geodetic(self):
  504. # Currently only Oracle supports calculating the perimeter on geodetic
  505. # geometries (without being transformed).
  506. qs1 = CensusZipcode.objects.annotate(perim=Perimeter('poly'))
  507. if connection.features.supports_perimeter_geodetic:
  508. self.assertAlmostEqual(qs1[0].perim.m, 18406.3818954314, 3)
  509. else:
  510. with self.assertRaises(NotSupportedError):
  511. list(qs1)
  512. # But should work fine when transformed to projected coordinates
  513. qs2 = CensusZipcode.objects.annotate(perim=Perimeter(Transform('poly', 32140))).filter(name='77002')
  514. self.assertAlmostEqual(qs2[0].perim.m, 18404.355, 3)
  515. @skipUnlessDBFeature("supports_null_geometries", "has_Area_function", "has_Distance_function")
  516. def test_measurement_null_fields(self):
  517. """
  518. Test the measurement functions on fields with NULL values.
  519. """
  520. # Creating SouthTexasZipcode w/NULL value.
  521. SouthTexasZipcode.objects.create(name='78212')
  522. # Performing distance/area queries against the NULL PolygonField,
  523. # and ensuring the result of the operations is None.
  524. htown = SouthTexasCity.objects.get(name='Downtown Houston')
  525. z = SouthTexasZipcode.objects.annotate(
  526. distance=Distance('poly', htown.point), area=Area('poly')
  527. ).get(name='78212')
  528. self.assertIsNone(z.distance)
  529. self.assertIsNone(z.area)