tests.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. """
  2. Tests for geography support in PostGIS
  3. """
  4. from __future__ import unicode_literals
  5. import os
  6. from unittest import skipUnless
  7. from django.contrib.gis.db.models.functions import Area, Distance
  8. from django.contrib.gis.gdal import HAS_GDAL
  9. from django.contrib.gis.measure import D
  10. from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
  11. from django.utils._os import upath
  12. from django.utils.deprecation import RemovedInDjango20Warning
  13. from ..utils import oracle, postgis
  14. from .models import City, County, Zipcode
  15. @skipUnlessDBFeature("gis_enabled")
  16. class GeographyTest(TestCase):
  17. fixtures = ['initial']
  18. def test01_fixture_load(self):
  19. "Ensure geography features loaded properly."
  20. self.assertEqual(8, City.objects.count())
  21. @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
  22. def test02_distance_lookup(self):
  23. "Testing GeoQuerySet distance lookup support on non-point geography fields."
  24. z = Zipcode.objects.get(code='77002')
  25. cities1 = list(City.objects
  26. .filter(point__distance_lte=(z.poly, D(mi=500)))
  27. .order_by('name')
  28. .values_list('name', flat=True))
  29. cities2 = list(City.objects
  30. .filter(point__dwithin=(z.poly, D(mi=500)))
  31. .order_by('name')
  32. .values_list('name', flat=True))
  33. for cities in [cities1, cities2]:
  34. self.assertEqual(['Dallas', 'Houston', 'Oklahoma City'], cities)
  35. @skipUnlessDBFeature("has_distance_method", "supports_distance_geodetic")
  36. @ignore_warnings(category=RemovedInDjango20Warning)
  37. def test03_distance_method(self):
  38. "Testing GeoQuerySet.distance() support on non-point geography fields."
  39. # `GeoQuerySet.distance` is not allowed geometry fields.
  40. htown = City.objects.get(name='Houston')
  41. Zipcode.objects.distance(htown.point)
  42. @skipUnless(postgis, "This is a PostGIS-specific test")
  43. def test04_invalid_operators_functions(self):
  44. "Ensuring exceptions are raised for operators & functions invalid on geography fields."
  45. # Only a subset of the geometry functions & operator are available
  46. # to PostGIS geography types. For more information, visit:
  47. # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions
  48. z = Zipcode.objects.get(code='77002')
  49. # ST_Within not available.
  50. with self.assertRaises(ValueError):
  51. City.objects.filter(point__within=z.poly).count()
  52. # `@` operator not available.
  53. with self.assertRaises(ValueError):
  54. City.objects.filter(point__contained=z.poly).count()
  55. # Regression test for #14060, `~=` was never really implemented for PostGIS.
  56. htown = City.objects.get(name='Houston')
  57. with self.assertRaises(ValueError):
  58. City.objects.get(point__exact=htown.point)
  59. @skipUnless(HAS_GDAL, "GDAL is required.")
  60. def test05_geography_layermapping(self):
  61. "Testing LayerMapping support on models with geography fields."
  62. # There is a similar test in `layermap` that uses the same data set,
  63. # but the County model here is a bit different.
  64. from django.contrib.gis.utils import LayerMapping
  65. # Getting the shapefile and mapping dictionary.
  66. shp_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), '..', 'data'))
  67. co_shp = os.path.join(shp_path, 'counties', 'counties.shp')
  68. co_mapping = {'name': 'Name',
  69. 'state': 'State',
  70. 'mpoly': 'MULTIPOLYGON',
  71. }
  72. # Reference county names, number of polygons, and state names.
  73. names = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo']
  74. num_polys = [1, 2, 1, 19, 1] # Number of polygons for each.
  75. st_names = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado']
  76. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique='name')
  77. lm.save(silent=True, strict=True)
  78. for c, name, num_poly, state in zip(County.objects.order_by('name'), names, num_polys, st_names):
  79. self.assertEqual(4326, c.mpoly.srid)
  80. self.assertEqual(num_poly, len(c.mpoly))
  81. self.assertEqual(name, c.name)
  82. self.assertEqual(state, c.state)
  83. @skipUnlessDBFeature("has_area_method", "supports_distance_geodetic")
  84. @ignore_warnings(category=RemovedInDjango20Warning)
  85. def test06_geography_area(self):
  86. "Testing that Area calculations work on geography columns."
  87. # SELECT ST_Area(poly) FROM geogapp_zipcode WHERE code='77002';
  88. z = Zipcode.objects.area().get(code='77002')
  89. # Round to the nearest thousand as possible values (depending on
  90. # the database and geolib) include 5439084, 5439100, 5439101.
  91. rounded_value = z.area.sq_m
  92. rounded_value -= z.area.sq_m % 1000
  93. self.assertEqual(rounded_value, 5439000)
  94. @skipUnlessDBFeature("gis_enabled")
  95. class GeographyFunctionTests(TestCase):
  96. fixtures = ['initial']
  97. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  98. def test_distance_function(self):
  99. """
  100. Testing Distance() support on non-point geography fields.
  101. """
  102. if oracle:
  103. ref_dists = [0, 4899.68, 8081.30, 9115.15]
  104. else:
  105. ref_dists = [0, 4891.20, 8071.64, 9123.95]
  106. htown = City.objects.get(name='Houston')
  107. qs = Zipcode.objects.annotate(distance=Distance('poly', htown.point))
  108. for z, ref in zip(qs, ref_dists):
  109. self.assertAlmostEqual(z.distance.m, ref, 2)
  110. @skipUnlessDBFeature("has_Area_function", "supports_distance_geodetic")
  111. def test_geography_area(self):
  112. """
  113. Testing that Area calculations work on geography columns.
  114. """
  115. # SELECT ST_Area(poly) FROM geogapp_zipcode WHERE code='77002';
  116. z = Zipcode.objects.annotate(area=Area('poly')).get(code='77002')
  117. # Round to the nearest thousand as possible values (depending on
  118. # the database and geolib) include 5439084, 5439100, 5439101.
  119. rounded_value = z.area.sq_m
  120. rounded_value -= z.area.sq_m % 1000
  121. self.assertEqual(rounded_value, 5439000)