1. """
    
  2. Tests for geography support in PostGIS
    
  3. """
    
  4. import os
    
  5. 
    
  6. from django.contrib.gis.db import models
    
  7. from django.contrib.gis.db.models.functions import Area, Distance
    
  8. from django.contrib.gis.measure import D
    
  9. from django.db import NotSupportedError, connection
    
  10. from django.db.models.functions import Cast
    
  11. from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
    
  12. 
    
  13. from ..utils import FuncTestMixin
    
  14. from .models import City, County, Zipcode
    
  15. 
    
  16. 
    
  17. class GeographyTest(TestCase):
    
  18.     fixtures = ["initial"]
    
  19. 
    
  20.     def test01_fixture_load(self):
    
  21.         "Ensure geography features loaded properly."
    
  22.         self.assertEqual(8, City.objects.count())
    
  23. 
    
  24.     @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
    
  25.     def test02_distance_lookup(self):
    
  26.         "Testing distance lookup support on non-point geography fields."
    
  27.         z = Zipcode.objects.get(code="77002")
    
  28.         cities1 = list(
    
  29.             City.objects.filter(point__distance_lte=(z.poly, D(mi=500)))
    
  30.             .order_by("name")
    
  31.             .values_list("name", flat=True)
    
  32.         )
    
  33.         cities2 = list(
    
  34.             City.objects.filter(point__dwithin=(z.poly, D(mi=500)))
    
  35.             .order_by("name")
    
  36.             .values_list("name", flat=True)
    
  37.         )
    
  38.         for cities in [cities1, cities2]:
    
  39.             self.assertEqual(["Dallas", "Houston", "Oklahoma City"], cities)
    
  40. 
    
  41.     def test04_invalid_operators_functions(self):
    
  42.         """
    
  43.         Exceptions are raised for operators & functions invalid on geography
    
  44.         fields.
    
  45.         """
    
  46.         if not connection.ops.postgis:
    
  47.             self.skipTest("This is a PostGIS-specific test.")
    
  48.         # Only a subset of the geometry functions & operator are available
    
  49.         # to PostGIS geography types.  For more information, visit:
    
  50.         # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions
    
  51.         z = Zipcode.objects.get(code="77002")
    
  52.         # ST_Within not available.
    
  53.         with self.assertRaises(ValueError):
    
  54.             City.objects.filter(point__within=z.poly).count()
    
  55.         # `@` operator not available.
    
  56.         with self.assertRaises(ValueError):
    
  57.             City.objects.filter(point__contained=z.poly).count()
    
  58. 
    
  59.         # Regression test for #14060, `~=` was never really implemented for PostGIS.
    
  60.         htown = City.objects.get(name="Houston")
    
  61.         with self.assertRaises(ValueError):
    
  62.             City.objects.get(point__exact=htown.point)
    
  63. 
    
  64.     def test05_geography_layermapping(self):
    
  65.         "Testing LayerMapping support on models with geography fields."
    
  66.         # There is a similar test in `layermap` that uses the same data set,
    
  67.         # but the County model here is a bit different.
    
  68.         from django.contrib.gis.utils import LayerMapping
    
  69. 
    
  70.         # Getting the shapefile and mapping dictionary.
    
  71.         shp_path = os.path.realpath(
    
  72.             os.path.join(os.path.dirname(__file__), "..", "data")
    
  73.         )
    
  74.         co_shp = os.path.join(shp_path, "counties", "counties.shp")
    
  75.         co_mapping = {
    
  76.             "name": "Name",
    
  77.             "state": "State",
    
  78.             "mpoly": "MULTIPOLYGON",
    
  79.         }
    
  80.         # Reference county names, number of polygons, and state names.
    
  81.         names = ["Bexar", "Galveston", "Harris", "Honolulu", "Pueblo"]
    
  82.         num_polys = [1, 2, 1, 19, 1]  # Number of polygons for each.
    
  83.         st_names = ["Texas", "Texas", "Texas", "Hawaii", "Colorado"]
    
  84. 
    
  85.         lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique="name")
    
  86.         lm.save(silent=True, strict=True)
    
  87. 
    
  88.         for c, name, num_poly, state in zip(
    
  89.             County.objects.order_by("name"), names, num_polys, st_names
    
  90.         ):
    
  91.             self.assertEqual(4326, c.mpoly.srid)
    
  92.             self.assertEqual(num_poly, len(c.mpoly))
    
  93.             self.assertEqual(name, c.name)
    
  94.             self.assertEqual(state, c.state)
    
  95. 
    
  96. 
    
  97. class GeographyFunctionTests(FuncTestMixin, TestCase):
    
  98.     fixtures = ["initial"]
    
  99. 
    
  100.     @skipUnlessDBFeature("supports_extent_aggr")
    
  101.     def test_cast_aggregate(self):
    
  102.         """
    
  103.         Cast a geography to a geometry field for an aggregate function that
    
  104.         expects a geometry input.
    
  105.         """
    
  106.         if not connection.features.supports_geography:
    
  107.             self.skipTest("This test needs geography support")
    
  108.         expected = (
    
  109.             -96.8016128540039,
    
  110.             29.7633724212646,
    
  111.             -95.3631439208984,
    
  112.             32.782058715820,
    
  113.         )
    
  114.         res = City.objects.filter(name__in=("Houston", "Dallas")).aggregate(
    
  115.             extent=models.Extent(Cast("point", models.PointField()))
    
  116.         )
    
  117.         for val, exp in zip(res["extent"], expected):
    
  118.             self.assertAlmostEqual(exp, val, 4)
    
  119. 
    
  120.     @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
    
  121.     def test_distance_function(self):
    
  122.         """
    
  123.         Testing Distance() support on non-point geography fields.
    
  124.         """
    
  125.         if connection.ops.oracle:
    
  126.             ref_dists = [0, 4899.68, 8081.30, 9115.15]
    
  127.         elif connection.ops.spatialite:
    
  128.             if connection.ops.spatial_version < (5,):
    
  129.                 # SpatiaLite < 5 returns non-zero distance for polygons and points
    
  130.                 # covered by that polygon.
    
  131.                 ref_dists = [326.61, 4899.68, 8081.30, 9115.15]
    
  132.             else:
    
  133.                 ref_dists = [0, 4899.68, 8081.30, 9115.15]
    
  134.         else:
    
  135.             ref_dists = [0, 4891.20, 8071.64, 9123.95]
    
  136.         htown = City.objects.get(name="Houston")
    
  137.         qs = Zipcode.objects.annotate(
    
  138.             distance=Distance("poly", htown.point),
    
  139.             distance2=Distance(htown.point, "poly"),
    
  140.         )
    
  141.         for z, ref in zip(qs, ref_dists):
    
  142.             self.assertAlmostEqual(z.distance.m, ref, 2)
    
  143. 
    
  144.         if connection.ops.postgis:
    
  145.             # PostGIS casts geography to geometry when distance2 is calculated.
    
  146.             ref_dists = [0, 4899.68, 8081.30, 9115.15]
    
  147.         for z, ref in zip(qs, ref_dists):
    
  148.             self.assertAlmostEqual(z.distance2.m, ref, 2)
    
  149. 
    
  150.         if not connection.ops.spatialite:
    
  151.             # Distance function combined with a lookup.
    
  152.             hzip = Zipcode.objects.get(code="77002")
    
  153.             self.assertEqual(qs.get(distance__lte=0), hzip)
    
  154. 
    
  155.     @skipUnlessDBFeature("has_Area_function", "supports_area_geodetic")
    
  156.     def test_geography_area(self):
    
  157.         """
    
  158.         Testing that Area calculations work on geography columns.
    
  159.         """
    
  160.         # SELECT ST_Area(poly) FROM geogapp_zipcode WHERE code='77002';
    
  161.         z = Zipcode.objects.annotate(area=Area("poly")).get(code="77002")
    
  162.         # Round to the nearest thousand as possible values (depending on
    
  163.         # the database and geolib) include 5439084, 5439100, 5439101.
    
  164.         rounded_value = z.area.sq_m
    
  165.         rounded_value -= z.area.sq_m % 1000
    
  166.         self.assertEqual(rounded_value, 5439000)
    
  167. 
    
  168.     @skipUnlessDBFeature("has_Area_function")
    
  169.     @skipIfDBFeature("supports_area_geodetic")
    
  170.     def test_geodetic_area_raises_if_not_supported(self):
    
  171.         with self.assertRaisesMessage(
    
  172.             NotSupportedError, "Area on geodetic coordinate systems not supported."
    
  173.         ):
    
  174.             Zipcode.objects.annotate(area=Area("poly")).get(code="77002")