tests.py 27 KB

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