tests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. from __future__ import unicode_literals
  2. import os
  3. import re
  4. from unittest import skipUnless
  5. from django.contrib.gis.db.models import Extent3D, Union
  6. from django.contrib.gis.db.models.functions import (
  7. AsGeoJSON, AsKML, Length, Perimeter, Scale, Translate,
  8. )
  9. from django.contrib.gis.gdal import HAS_GDAL
  10. from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon
  11. from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
  12. from django.utils._os import upath
  13. from django.utils.deprecation import (
  14. RemovedInDjango20Warning, RemovedInDjango110Warning,
  15. )
  16. from .models import (
  17. City3D, Interstate2D, Interstate3D, InterstateProj2D, InterstateProj3D,
  18. MultiPoint3D, Point2D, Point3D, Polygon2D, Polygon3D,
  19. )
  20. if HAS_GDAL:
  21. from django.contrib.gis.utils import LayerMapping, LayerMapError
  22. data_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), '..', 'data'))
  23. city_file = os.path.join(data_path, 'cities', 'cities.shp')
  24. vrt_file = os.path.join(data_path, 'test_vrt', 'test_vrt.vrt')
  25. # The coordinates of each city, with Z values corresponding to their
  26. # altitude in meters.
  27. city_data = (
  28. ('Houston', (-95.363151, 29.763374, 18)),
  29. ('Dallas', (-96.801611, 32.782057, 147)),
  30. ('Oklahoma City', (-97.521157, 34.464642, 380)),
  31. ('Wellington', (174.783117, -41.315268, 14)),
  32. ('Pueblo', (-104.609252, 38.255001, 1433)),
  33. ('Lawrence', (-95.235060, 38.971823, 251)),
  34. ('Chicago', (-87.650175, 41.850385, 181)),
  35. ('Victoria', (-123.305196, 48.462611, 15)),
  36. )
  37. # Reference mapping of city name to its altitude (Z value).
  38. city_dict = {name: coords for name, coords in city_data}
  39. # 3D freeway data derived from the National Elevation Dataset:
  40. # http://seamless.usgs.gov/products/9arc.php
  41. interstate_data = (
  42. ('I-45',
  43. 'LINESTRING(-95.3708481 29.7765870 11.339,-95.3694580 29.7787980 4.536,'
  44. '-95.3690305 29.7797359 9.762,-95.3691886 29.7812450 12.448,'
  45. '-95.3696447 29.7850144 10.457,-95.3702511 29.7868518 9.418,'
  46. '-95.3706724 29.7881286 14.858,-95.3711632 29.7896157 15.386,'
  47. '-95.3714525 29.7936267 13.168,-95.3717848 29.7955007 15.104,'
  48. '-95.3717719 29.7969804 16.516,-95.3717305 29.7982117 13.923,'
  49. '-95.3717254 29.8000778 14.385,-95.3719875 29.8013539 15.160,'
  50. '-95.3720575 29.8026785 15.544,-95.3721321 29.8040912 14.975,'
  51. '-95.3722074 29.8050998 15.688,-95.3722779 29.8060430 16.099,'
  52. '-95.3733818 29.8076750 15.197,-95.3741563 29.8103686 17.268,'
  53. '-95.3749458 29.8129927 19.857,-95.3763564 29.8144557 15.435)',
  54. (11.339, 4.536, 9.762, 12.448, 10.457, 9.418, 14.858,
  55. 15.386, 13.168, 15.104, 16.516, 13.923, 14.385, 15.16,
  56. 15.544, 14.975, 15.688, 16.099, 15.197, 17.268, 19.857,
  57. 15.435),
  58. ),
  59. )
  60. # Bounding box polygon for inner-loop of Houston (in projected coordinate
  61. # system 32140), with elevation values from the National Elevation Dataset
  62. # (see above).
  63. bbox_data = (
  64. 'POLYGON((941527.97 4225693.20,962596.48 4226349.75,963152.57 4209023.95,'
  65. '942051.75 4208366.38,941527.97 4225693.20))',
  66. (21.71, 13.21, 9.12, 16.40, 21.71)
  67. )
  68. class Geo3DLoadingHelper(object):
  69. def _load_interstate_data(self):
  70. # Interstate (2D / 3D and Geographic/Projected variants)
  71. for name, line, exp_z in interstate_data:
  72. line_3d = GEOSGeometry(line, srid=4269)
  73. line_2d = LineString([l[:2] for l in line_3d.coords], srid=4269)
  74. # Creating a geographic and projected version of the
  75. # interstate in both 2D and 3D.
  76. Interstate3D.objects.create(name=name, line=line_3d)
  77. InterstateProj3D.objects.create(name=name, line=line_3d)
  78. Interstate2D.objects.create(name=name, line=line_2d)
  79. InterstateProj2D.objects.create(name=name, line=line_2d)
  80. def _load_city_data(self):
  81. for name, pnt_data in city_data:
  82. City3D.objects.create(name=name, point=Point(*pnt_data, srid=4326))
  83. def _load_polygon_data(self):
  84. bbox_wkt, bbox_z = bbox_data
  85. bbox_2d = GEOSGeometry(bbox_wkt, srid=32140)
  86. bbox_3d = Polygon(tuple((x, y, z) for (x, y), z in zip(bbox_2d[0].coords, bbox_z)), srid=32140)
  87. Polygon2D.objects.create(name='2D BBox', poly=bbox_2d)
  88. Polygon3D.objects.create(name='3D BBox', poly=bbox_3d)
  89. @skipUnless(HAS_GDAL, "GDAL is required for Geo3DTest.")
  90. @skipUnlessDBFeature("gis_enabled", "supports_3d_storage")
  91. class Geo3DTest(Geo3DLoadingHelper, TestCase):
  92. """
  93. Only a subset of the PostGIS routines are 3D-enabled, and this TestCase
  94. tries to test the features that can handle 3D and that are also
  95. available within GeoDjango. For more information, see the PostGIS docs
  96. on the routines that support 3D:
  97. http://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_3D_Functions
  98. """
  99. def test_3d_hasz(self):
  100. """
  101. Make sure data is 3D and has expected Z values -- shouldn't change
  102. because of coordinate system.
  103. """
  104. self._load_interstate_data()
  105. for name, line, exp_z in interstate_data:
  106. interstate = Interstate3D.objects.get(name=name)
  107. interstate_proj = InterstateProj3D.objects.get(name=name)
  108. for i in [interstate, interstate_proj]:
  109. self.assertTrue(i.line.hasz)
  110. self.assertEqual(exp_z, tuple(i.line.z))
  111. self._load_city_data()
  112. for name, pnt_data in city_data:
  113. city = City3D.objects.get(name=name)
  114. z = pnt_data[2]
  115. self.assertTrue(city.point.hasz)
  116. self.assertEqual(z, city.point.z)
  117. def test_3d_polygons(self):
  118. """
  119. Test the creation of polygon 3D models.
  120. """
  121. self._load_polygon_data()
  122. p3d = Polygon3D.objects.get(name='3D BBox')
  123. self.assertTrue(p3d.poly.hasz)
  124. self.assertIsInstance(p3d.poly, Polygon)
  125. self.assertEqual(p3d.poly.srid, 32140)
  126. def test_3d_layermapping(self):
  127. """
  128. Testing LayerMapping on 3D models.
  129. """
  130. point_mapping = {'point': 'POINT'}
  131. mpoint_mapping = {'mpoint': 'MULTIPOINT'}
  132. # The VRT is 3D, but should still be able to map sans the Z.
  133. lm = LayerMapping(Point2D, vrt_file, point_mapping, transform=False)
  134. lm.save()
  135. self.assertEqual(3, Point2D.objects.count())
  136. # The city shapefile is 2D, and won't be able to fill the coordinates
  137. # in the 3D model -- thus, a LayerMapError is raised.
  138. self.assertRaises(LayerMapError, LayerMapping,
  139. Point3D, city_file, point_mapping, transform=False)
  140. # 3D model should take 3D data just fine.
  141. lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False)
  142. lm.save()
  143. self.assertEqual(3, Point3D.objects.count())
  144. # Making sure LayerMapping.make_multi works right, by converting
  145. # a Point25D into a MultiPoint25D.
  146. lm = LayerMapping(MultiPoint3D, vrt_file, mpoint_mapping, transform=False)
  147. lm.save()
  148. self.assertEqual(3, MultiPoint3D.objects.count())
  149. @ignore_warnings(category=RemovedInDjango20Warning)
  150. def test_kml(self):
  151. """
  152. Test GeoQuerySet.kml() with Z values.
  153. """
  154. self._load_city_data()
  155. h = City3D.objects.kml(precision=6).get(name='Houston')
  156. # KML should be 3D.
  157. # `SELECT ST_AsKML(point, 6) FROM geo3d_city3d WHERE name = 'Houston';`
  158. ref_kml_regex = re.compile(r'^<Point><coordinates>-95.363\d+,29.763\d+,18</coordinates></Point>$')
  159. self.assertTrue(ref_kml_regex.match(h.kml))
  160. @ignore_warnings(category=RemovedInDjango20Warning)
  161. def test_geojson(self):
  162. """
  163. Test GeoQuerySet.geojson() with Z values.
  164. """
  165. self._load_city_data()
  166. h = City3D.objects.geojson(precision=6).get(name='Houston')
  167. # GeoJSON should be 3D
  168. # `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';`
  169. ref_json_regex = re.compile(r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$')
  170. self.assertTrue(ref_json_regex.match(h.geojson))
  171. @skipUnlessDBFeature("supports_3d_functions")
  172. def test_union(self):
  173. """
  174. Testing the Union aggregate of 3D models.
  175. """
  176. # PostGIS query that returned the reference EWKT for this test:
  177. # `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;`
  178. self._load_city_data()
  179. ref_ewkt = (
  180. 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,'
  181. '-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,'
  182. '-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)'
  183. )
  184. ref_union = GEOSGeometry(ref_ewkt)
  185. union = City3D.objects.aggregate(Union('point'))['point__union']
  186. self.assertTrue(union.hasz)
  187. # Ordering of points in the resulting geometry may vary between implementations
  188. self.assertSetEqual({p.ewkt for p in ref_union}, {p.ewkt for p in union})
  189. @skipUnlessDBFeature("supports_3d_functions")
  190. @ignore_warnings(category=RemovedInDjango110Warning)
  191. def test_extent(self):
  192. """
  193. Testing the Extent3D aggregate for 3D models.
  194. """
  195. self._load_city_data()
  196. # `SELECT ST_Extent3D(point) FROM geo3d_city3d;`
  197. ref_extent3d = (-123.305196, -41.315268, 14, 174.783117, 48.462611, 1433)
  198. extent1 = City3D.objects.aggregate(Extent3D('point'))['point__extent3d']
  199. extent2 = City3D.objects.extent3d()
  200. def check_extent3d(extent3d, tol=6):
  201. for ref_val, ext_val in zip(ref_extent3d, extent3d):
  202. self.assertAlmostEqual(ref_val, ext_val, tol)
  203. for e3d in [extent1, extent2]:
  204. check_extent3d(e3d)
  205. self.assertIsNone(City3D.objects.none().extent3d())
  206. self.assertIsNone(City3D.objects.none().aggregate(Extent3D('point'))['point__extent3d'])
  207. @ignore_warnings(category=RemovedInDjango20Warning)
  208. @skipUnlessDBFeature("supports_3d_functions")
  209. def test_perimeter(self):
  210. """
  211. Testing GeoQuerySet.perimeter() on 3D fields.
  212. """
  213. self._load_polygon_data()
  214. # Reference query for values below:
  215. # `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly) FROM geo3d_polygon3d;`
  216. ref_perim_3d = 76859.2620451
  217. ref_perim_2d = 76859.2577803
  218. tol = 6
  219. self.assertAlmostEqual(ref_perim_2d,
  220. Polygon2D.objects.perimeter().get(name='2D BBox').perimeter.m,
  221. tol)
  222. self.assertAlmostEqual(ref_perim_3d,
  223. Polygon3D.objects.perimeter().get(name='3D BBox').perimeter.m,
  224. tol)
  225. @ignore_warnings(category=RemovedInDjango20Warning)
  226. @skipUnlessDBFeature("supports_3d_functions")
  227. def test_length(self):
  228. """
  229. Testing GeoQuerySet.length() on 3D fields.
  230. """
  231. # ST_Length_Spheroid Z-aware, and thus does not need to use
  232. # a separate function internally.
  233. # `SELECT ST_Length_Spheroid(line, 'SPHEROID["GRS 1980",6378137,298.257222101]')
  234. # FROM geo3d_interstate[2d|3d];`
  235. self._load_interstate_data()
  236. tol = 3
  237. ref_length_2d = 4368.1721949481
  238. ref_length_3d = 4368.62547052088
  239. self.assertAlmostEqual(ref_length_2d,
  240. Interstate2D.objects.length().get(name='I-45').length.m,
  241. tol)
  242. self.assertAlmostEqual(ref_length_3d,
  243. Interstate3D.objects.length().get(name='I-45').length.m,
  244. tol)
  245. # Making sure `ST_Length3D` is used on for a projected
  246. # and 3D model rather than `ST_Length`.
  247. # `SELECT ST_Length(line) FROM geo3d_interstateproj2d;`
  248. ref_length_2d = 4367.71564892392
  249. # `SELECT ST_Length3D(line) FROM geo3d_interstateproj3d;`
  250. ref_length_3d = 4368.16897234101
  251. self.assertAlmostEqual(ref_length_2d,
  252. InterstateProj2D.objects.length().get(name='I-45').length.m,
  253. tol)
  254. self.assertAlmostEqual(ref_length_3d,
  255. InterstateProj3D.objects.length().get(name='I-45').length.m,
  256. tol)
  257. @ignore_warnings(category=RemovedInDjango20Warning)
  258. @skipUnlessDBFeature("supports_3d_functions")
  259. def test_scale(self):
  260. """
  261. Testing GeoQuerySet.scale() on Z values.
  262. """
  263. self._load_city_data()
  264. # Mapping of City name to reference Z values.
  265. zscales = (-3, 4, 23)
  266. for zscale in zscales:
  267. for city in City3D.objects.scale(1.0, 1.0, zscale):
  268. self.assertEqual(city_dict[city.name][2] * zscale, city.scale.z)
  269. @ignore_warnings(category=RemovedInDjango20Warning)
  270. @skipUnlessDBFeature("supports_3d_functions")
  271. def test_translate(self):
  272. """
  273. Testing GeoQuerySet.translate() on Z values.
  274. """
  275. self._load_city_data()
  276. ztranslations = (5.23, 23, -17)
  277. for ztrans in ztranslations:
  278. for city in City3D.objects.translate(0, 0, ztrans):
  279. self.assertEqual(city_dict[city.name][2] + ztrans, city.translate.z)
  280. @skipUnless(HAS_GDAL, "GDAL is required for Geo3DTest.")
  281. @skipUnlessDBFeature("gis_enabled", "supports_3d_functions")
  282. class Geo3DFunctionsTests(Geo3DLoadingHelper, TestCase):
  283. def test_kml(self):
  284. """
  285. Test KML() function with Z values.
  286. """
  287. self._load_city_data()
  288. h = City3D.objects.annotate(kml=AsKML('point', precision=6)).get(name='Houston')
  289. # KML should be 3D.
  290. # `SELECT ST_AsKML(point, 6) FROM geo3d_city3d WHERE name = 'Houston';`
  291. ref_kml_regex = re.compile(r'^<Point><coordinates>-95.363\d+,29.763\d+,18</coordinates></Point>$')
  292. self.assertTrue(ref_kml_regex.match(h.kml))
  293. def test_geojson(self):
  294. """
  295. Test GeoJSON() function with Z values.
  296. """
  297. self._load_city_data()
  298. h = City3D.objects.annotate(geojson=AsGeoJSON('point', precision=6)).get(name='Houston')
  299. # GeoJSON should be 3D
  300. # `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';`
  301. ref_json_regex = re.compile(r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$')
  302. self.assertTrue(ref_json_regex.match(h.geojson))
  303. def test_perimeter(self):
  304. """
  305. Testing Perimeter() function on 3D fields.
  306. """
  307. self._load_polygon_data()
  308. # Reference query for values below:
  309. # `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly) FROM geo3d_polygon3d;`
  310. ref_perim_3d = 76859.2620451
  311. ref_perim_2d = 76859.2577803
  312. tol = 6
  313. poly2d = Polygon2D.objects.annotate(perimeter=Perimeter('poly')).get(name='2D BBox')
  314. self.assertAlmostEqual(ref_perim_2d, poly2d.perimeter.m, tol)
  315. poly3d = Polygon3D.objects.annotate(perimeter=Perimeter('poly')).get(name='3D BBox')
  316. self.assertAlmostEqual(ref_perim_3d, poly3d.perimeter.m, tol)
  317. def test_length(self):
  318. """
  319. Testing Length() function on 3D fields.
  320. """
  321. # ST_Length_Spheroid Z-aware, and thus does not need to use
  322. # a separate function internally.
  323. # `SELECT ST_Length_Spheroid(line, 'SPHEROID["GRS 1980",6378137,298.257222101]')
  324. # FROM geo3d_interstate[2d|3d];`
  325. self._load_interstate_data()
  326. tol = 3
  327. ref_length_2d = 4368.1721949481
  328. ref_length_3d = 4368.62547052088
  329. inter2d = Interstate2D.objects.annotate(length=Length('line')).get(name='I-45')
  330. self.assertAlmostEqual(ref_length_2d, inter2d.length.m, tol)
  331. inter3d = Interstate3D.objects.annotate(length=Length('line')).get(name='I-45')
  332. self.assertAlmostEqual(ref_length_3d, inter3d.length.m, tol)
  333. # Making sure `ST_Length3D` is used on for a projected
  334. # and 3D model rather than `ST_Length`.
  335. # `SELECT ST_Length(line) FROM geo3d_interstateproj2d;`
  336. ref_length_2d = 4367.71564892392
  337. # `SELECT ST_Length3D(line) FROM geo3d_interstateproj3d;`
  338. ref_length_3d = 4368.16897234101
  339. inter2d = InterstateProj2D.objects.annotate(length=Length('line')).get(name='I-45')
  340. self.assertAlmostEqual(ref_length_2d, inter2d.length.m, tol)
  341. inter3d = InterstateProj3D.objects.annotate(length=Length('line')).get(name='I-45')
  342. self.assertAlmostEqual(ref_length_3d, inter3d.length.m, tol)
  343. def test_scale(self):
  344. """
  345. Testing Scale() function on Z values.
  346. """
  347. self._load_city_data()
  348. # Mapping of City name to reference Z values.
  349. zscales = (-3, 4, 23)
  350. for zscale in zscales:
  351. for city in City3D.objects.annotate(scale=Scale('point', 1.0, 1.0, zscale)):
  352. self.assertEqual(city_dict[city.name][2] * zscale, city.scale.z)
  353. def test_translate(self):
  354. """
  355. Testing Translate() function on Z values.
  356. """
  357. self._load_city_data()
  358. ztranslations = (5.23, 23, -17)
  359. for ztrans in ztranslations:
  360. for city in City3D.objects.annotate(translate=Translate('point', 0, 0, ztrans)):
  361. self.assertEqual(city_dict[city.name][2] + ztrans, city.translate.z)