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