| 1 |
from io import StringIO |
| 2 |
|
| 3 |
from django.contrib.gis import gdal |
| 4 |
from django.contrib.gis.db.models import Extent, MakeLine, Union, functions |
| 5 |
from django.contrib.gis.geos import ( |
| 6 |
GeometryCollection, |
| 7 |
GEOSGeometry, |
| 8 |
LinearRing, |
| 9 |
LineString, |
| 10 |
MultiLineString, |
| 11 |
MultiPoint, |
| 12 |
MultiPolygon, |
| 13 |
Point, |
| 14 |
Polygon, |
| 15 |
fromstr, |
| 16 |
) |
| 17 |
from django.core.files.temp import NamedTemporaryFile |
| 18 |
from django.core.management import call_command |
| 19 |
from django.db import DatabaseError, NotSupportedError, connection |
| 20 |
from django.db.models import F, OuterRef, Subquery |
| 21 |
from django.test import TestCase, skipUnlessDBFeature |
| 22 |
from django.test.utils import CaptureQueriesContext |
| 23 |
|
| 24 |
from ..utils import skipUnlessGISLookup |
| 25 |
from .models import ( |
| 26 |
City, |
| 27 |
Country, |
| 28 |
Feature, |
| 29 |
MinusOneSRID, |
| 30 |
MultiFields, |
| 31 |
NonConcreteModel, |
| 32 |
PennsylvaniaCity, |
| 33 |
State, |
| 34 |
ThreeDimensionalFeature, |
| 35 |
Track, |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
class GeoModelTest(TestCase): |
| 40 |
fixtures = ["initial"] |
| 41 |
|
| 42 |
def test_fixtures(self): |
| 43 |
"Testing geographic model initialization from fixtures." |
| 44 |
# Ensuring that data was loaded from initial data fixtures. |
| 45 |
self.assertEqual(2, Country.objects.count()) |
| 46 |
self.assertEqual(8, City.objects.count()) |
| 47 |
self.assertEqual(2, State.objects.count()) |
| 48 |
|
| 49 |
def test_proxy(self): |
| 50 |
"Testing Lazy-Geometry support (using the GeometryProxy)." |
| 51 |
# Testing on a Point |
| 52 |
pnt = Point(0, 0) |
| 53 |
nullcity = City(name="NullCity", point=pnt) |
| 54 |
nullcity.save() |
| 55 |
|
| 56 |
# Making sure TypeError is thrown when trying to set with an |
| 57 |
# incompatible type. |
| 58 |
for bad in [5, 2.0, LineString((0, 0), (1, 1))]: |
| 59 |
with self.assertRaisesMessage(TypeError, "Cannot set"): |
| 60 |
nullcity.point = bad |
| 61 |
|
| 62 |
# Now setting with a compatible GEOS Geometry, saving, and ensuring |
| 63 |
# the save took, notice no SRID is explicitly set. |
| 64 |
new = Point(5, 23) |
| 65 |
nullcity.point = new |
| 66 |
|
| 67 |
# Ensuring that the SRID is automatically set to that of the |
| 68 |
# field after assignment, but before saving. |
| 69 |
self.assertEqual(4326, nullcity.point.srid) |
| 70 |
nullcity.save() |
| 71 |
|
| 72 |
# Ensuring the point was saved correctly after saving |
| 73 |
self.assertEqual(new, City.objects.get(name="NullCity").point) |
| 74 |
|
| 75 |
# Setting the X and Y of the Point |
| 76 |
nullcity.point.x = 23 |
| 77 |
nullcity.point.y = 5 |
| 78 |
# Checking assignments pre & post-save. |
| 79 |
self.assertNotEqual( |
| 80 |
Point(23, 5, srid=4326), City.objects.get(name="NullCity").point |
| 81 |
) |
| 82 |
nullcity.save() |
| 83 |
self.assertEqual( |
| 84 |
Point(23, 5, srid=4326), City.objects.get(name="NullCity").point |
| 85 |
) |
| 86 |
nullcity.delete() |
| 87 |
|
| 88 |
# Testing on a Polygon |
| 89 |
shell = LinearRing((0, 0), (0, 90), (100, 90), (100, 0), (0, 0)) |
| 90 |
inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) |
| 91 |
|
| 92 |
# Creating a State object using a built Polygon |
| 93 |
ply = Polygon(shell, inner) |
| 94 |
nullstate = State(name="NullState", poly=ply) |
| 95 |
self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None |
| 96 |
nullstate.save() |
| 97 |
|
| 98 |
ns = State.objects.get(name="NullState") |
| 99 |
self.assertEqual(connection.ops.Adapter._fix_polygon(ply), ns.poly) |
| 100 |
|
| 101 |
# Testing the `ogr` and `srs` lazy-geometry properties. |
| 102 |
self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry) |
| 103 |
self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) |
| 104 |
self.assertIsInstance(ns.poly.srs, gdal.SpatialReference) |
| 105 |
self.assertEqual("WGS 84", ns.poly.srs.name) |
| 106 |
|
| 107 |
# Changing the interior ring on the poly attribute. |
| 108 |
new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) |
| 109 |
ns.poly[1] = new_inner |
| 110 |
ply[1] = new_inner |
| 111 |
self.assertEqual(4326, ns.poly.srid) |
| 112 |
ns.save() |
| 113 |
self.assertEqual( |
| 114 |
connection.ops.Adapter._fix_polygon(ply), |
| 115 |
State.objects.get(name="NullState").poly, |
| 116 |
) |
| 117 |
ns.delete() |
| 118 |
|
| 119 |
@skipUnlessDBFeature("supports_transform") |
| 120 |
def test_lookup_insert_transform(self): |
| 121 |
"Testing automatic transform for lookups and inserts." |
| 122 |
# San Antonio in 'WGS84' (SRID 4326) |
| 123 |
sa_4326 = "POINT (-98.493183 29.424170)" |
| 124 |
wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 |
| 125 |
# San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857) |
| 126 |
other_srid_pnt = wgs_pnt.transform(3857, clone=True) |
| 127 |
# Constructing & querying with a point from a different SRID. Oracle |
| 128 |
# `SDO_OVERLAPBDYINTERSECT` operates differently from |
| 129 |
# `ST_Intersects`, so contains is used instead. |
| 130 |
if connection.ops.oracle: |
| 131 |
tx = Country.objects.get(mpoly__contains=other_srid_pnt) |
| 132 |
else: |
| 133 |
tx = Country.objects.get(mpoly__intersects=other_srid_pnt) |
| 134 |
self.assertEqual("Texas", tx.name) |
| 135 |
|
| 136 |
# Creating San Antonio. Remember the Alamo. |
| 137 |
sa = City.objects.create(name="San Antonio", point=other_srid_pnt) |
| 138 |
|
| 139 |
# Now verifying that San Antonio was transformed correctly |
| 140 |
sa = City.objects.get(name="San Antonio") |
| 141 |
self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) |
| 142 |
self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) |
| 143 |
|
| 144 |
# If the GeometryField SRID is -1, then we shouldn't perform any |
| 145 |
# transformation if the SRID of the input geometry is different. |
| 146 |
m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) |
| 147 |
m1.save() |
| 148 |
self.assertEqual(-1, m1.geom.srid) |
| 149 |
|
| 150 |
def test_createnull(self): |
| 151 |
"Testing creating a model instance and the geometry being None" |
| 152 |
c = City() |
| 153 |
self.assertIsNone(c.point) |
| 154 |
|
| 155 |
def test_geometryfield(self): |
| 156 |
"Testing the general GeometryField." |
| 157 |
Feature(name="Point", geom=Point(1, 1)).save() |
| 158 |
Feature(name="LineString", geom=LineString((0, 0), (1, 1), (5, 5))).save() |
| 159 |
Feature( |
| 160 |
name="Polygon", |
| 161 |
geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), |
| 162 |
).save() |
| 163 |
Feature( |
| 164 |
name="GeometryCollection", |
| 165 |
geom=GeometryCollection( |
| 166 |
Point(2, 2), |
| 167 |
LineString((0, 0), (2, 2)), |
| 168 |
Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), |
| 169 |
), |
| 170 |
).save() |
| 171 |
|
| 172 |
f_1 = Feature.objects.get(name="Point") |
| 173 |
self.assertIsInstance(f_1.geom, Point) |
| 174 |
self.assertEqual((1.0, 1.0), f_1.geom.tuple) |
| 175 |
f_2 = Feature.objects.get(name="LineString") |
| 176 |
self.assertIsInstance(f_2.geom, LineString) |
| 177 |
self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) |
| 178 |
|
| 179 |
f_3 = Feature.objects.get(name="Polygon") |
| 180 |
self.assertIsInstance(f_3.geom, Polygon) |
| 181 |
f_4 = Feature.objects.get(name="GeometryCollection") |
| 182 |
self.assertIsInstance(f_4.geom, GeometryCollection) |
| 183 |
self.assertEqual(f_3.geom, f_4.geom[2]) |
| 184 |
|
| 185 |
@skipUnlessDBFeature("supports_transform") |
| 186 |
def test_inherited_geofields(self): |
| 187 |
"Database functions on inherited Geometry fields." |
| 188 |
# Creating a Pennsylvanian city. |
| 189 |
PennsylvaniaCity.objects.create( |
| 190 |
name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)" |
| 191 |
) |
| 192 |
|
| 193 |
# All transformation SQL will need to be performed on the |
| 194 |
# _parent_ table. |
| 195 |
qs = PennsylvaniaCity.objects.annotate( |
| 196 |
new_point=functions.Transform("point", srid=32128) |
| 197 |
) |
| 198 |
|
| 199 |
self.assertEqual(1, qs.count()) |
| 200 |
for pc in qs: |
| 201 |
self.assertEqual(32128, pc.new_point.srid) |
| 202 |
|
| 203 |
def test_raw_sql_query(self): |
| 204 |
"Testing raw SQL query." |
| 205 |
cities1 = City.objects.all() |
| 206 |
point_select = connection.ops.select % "point" |
| 207 |
cities2 = list( |
| 208 |
City.objects.raw( |
| 209 |
"select id, name, %s as point from geoapp_city" % point_select |
| 210 |
) |
| 211 |
) |
| 212 |
self.assertEqual(len(cities1), len(cities2)) |
| 213 |
with self.assertNumQueries(0): # Ensure point isn't deferred. |
| 214 |
self.assertIsInstance(cities2[0].point, Point) |
| 215 |
|
| 216 |
def test_gis_query_as_string(self): |
| 217 |
"""GIS queries can be represented as strings.""" |
| 218 |
query = City.objects.filter(point__within=Polygon.from_bbox((0, 0, 2, 2))) |
| 219 |
self.assertIn( |
| 220 |
connection.ops.quote_name(City._meta.db_table), |
| 221 |
str(query.query), |
| 222 |
) |
| 223 |
|
| 224 |
def test_dumpdata_loaddata_cycle(self): |
| 225 |
""" |
| 226 |
Test a dumpdata/loaddata cycle with geographic data. |
| 227 |
""" |
| 228 |
out = StringIO() |
| 229 |
original_data = list(City.objects.order_by("name")) |
| 230 |
call_command("dumpdata", "geoapp.City", stdout=out) |
| 231 |
result = out.getvalue() |
| 232 |
houston = City.objects.get(name="Houston") |
| 233 |
self.assertIn('"point": "%s"' % houston.point.ewkt, result) |
| 234 |
|
| 235 |
# Reload now dumped data |
| 236 |
with NamedTemporaryFile(mode="w", suffix=".json") as tmp: |
| 237 |
tmp.write(result) |
| 238 |
tmp.seek(0) |
| 239 |
call_command("loaddata", tmp.name, verbosity=0) |
| 240 |
self.assertEqual(original_data, list(City.objects.order_by("name"))) |
| 241 |
|
| 242 |
@skipUnlessDBFeature("supports_empty_geometries") |
| 243 |
def test_empty_geometries(self): |
| 244 |
geometry_classes = [ |
| 245 |
Point, |
| 246 |
LineString, |
| 247 |
LinearRing, |
| 248 |
Polygon, |
| 249 |
MultiPoint, |
| 250 |
MultiLineString, |
| 251 |
MultiPolygon, |
| 252 |
GeometryCollection, |
| 253 |
] |
| 254 |
for klass in geometry_classes: |
| 255 |
g = klass(srid=4326) |
| 256 |
model_class = Feature |
| 257 |
if g.hasz: |
| 258 |
if not connection.features.supports_3d_storage: |
| 259 |
continue |
| 260 |
else: |
| 261 |
model_class = ThreeDimensionalFeature |
| 262 |
feature = model_class.objects.create(name=f"Empty {klass.__name__}", geom=g) |
| 263 |
feature.refresh_from_db() |
| 264 |
if klass is LinearRing: |
| 265 |
# LinearRing isn't representable in WKB, so GEOSGeomtry.wkb |
| 266 |
# uses LineString instead. |
| 267 |
g = LineString(srid=4326) |
| 268 |
self.assertEqual(feature.geom, g) |
| 269 |
self.assertEqual(feature.geom.srid, g.srid) |
| 270 |
|
| 271 |
|
| 272 |
class GeoLookupTest(TestCase): |
| 273 |
fixtures = ["initial"] |
| 274 |
|
| 275 |
def test_disjoint_lookup(self): |
| 276 |
"Testing the `disjoint` lookup type." |
| 277 |
ptown = City.objects.get(name="Pueblo") |
| 278 |
qs1 = City.objects.filter(point__disjoint=ptown.point) |
| 279 |
self.assertEqual(7, qs1.count()) |
| 280 |
qs2 = State.objects.filter(poly__disjoint=ptown.point) |
| 281 |
self.assertEqual(1, qs2.count()) |
| 282 |
self.assertEqual("Kansas", qs2[0].name) |
| 283 |
|
| 284 |
def test_contains_contained_lookups(self): |
| 285 |
"Testing the 'contained', 'contains', and 'bbcontains' lookup types." |
| 286 |
# Getting Texas, yes we were a country -- once ;) |
| 287 |
texas = Country.objects.get(name="Texas") |
| 288 |
|
| 289 |
# Seeing what cities are in Texas, should get Houston and Dallas, |
| 290 |
# and Oklahoma City because 'contained' only checks on the |
| 291 |
# _bounding box_ of the Geometries. |
| 292 |
if connection.features.supports_contained_lookup: |
| 293 |
qs = City.objects.filter(point__contained=texas.mpoly) |
| 294 |
self.assertEqual(3, qs.count()) |
| 295 |
cities = ["Houston", "Dallas", "Oklahoma City"] |
| 296 |
for c in qs: |
| 297 |
self.assertIn(c.name, cities) |
| 298 |
|
| 299 |
# Pulling out some cities. |
| 300 |
houston = City.objects.get(name="Houston") |
| 301 |
wellington = City.objects.get(name="Wellington") |
| 302 |
pueblo = City.objects.get(name="Pueblo") |
| 303 |
okcity = City.objects.get(name="Oklahoma City") |
| 304 |
lawrence = City.objects.get(name="Lawrence") |
| 305 |
|
| 306 |
# Now testing contains on the countries using the points for |
| 307 |
# Houston and Wellington. |
| 308 |
tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry |
| 309 |
nz = Country.objects.get( |
| 310 |
mpoly__contains=wellington.point.hex |
| 311 |
) # Query w/EWKBHEX |
| 312 |
self.assertEqual("Texas", tx.name) |
| 313 |
self.assertEqual("New Zealand", nz.name) |
| 314 |
|
| 315 |
# Testing `contains` on the states using the point for Lawrence. |
| 316 |
ks = State.objects.get(poly__contains=lawrence.point) |
| 317 |
self.assertEqual("Kansas", ks.name) |
| 318 |
|
| 319 |
# Pueblo and Oklahoma City (even though OK City is within the bounding |
| 320 |
# box of Texas) are not contained in Texas or New Zealand. |
| 321 |
self.assertEqual( |
| 322 |
len(Country.objects.filter(mpoly__contains=pueblo.point)), 0 |
| 323 |
) # Query w/GEOSGeometry object |
| 324 |
self.assertEqual( |
| 325 |
len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0 |
| 326 |
) # Query w/WKT |
| 327 |
|
| 328 |
# OK City is contained w/in bounding box of Texas. |
| 329 |
if connection.features.supports_bbcontains_lookup: |
| 330 |
qs = Country.objects.filter(mpoly__bbcontains=okcity.point) |
| 331 |
self.assertEqual(1, len(qs)) |
| 332 |
self.assertEqual("Texas", qs[0].name) |
| 333 |
|
| 334 |
@skipUnlessDBFeature("supports_crosses_lookup") |
| 335 |
def test_crosses_lookup(self): |
| 336 |
Track.objects.create(name="Line1", line=LineString([(-95, 29), (-60, 0)])) |
| 337 |
self.assertEqual( |
| 338 |
Track.objects.filter( |
| 339 |
line__crosses=LineString([(-95, 0), (-60, 29)]) |
| 340 |
).count(), |
| 341 |
1, |
| 342 |
) |
| 343 |
self.assertEqual( |
| 344 |
Track.objects.filter( |
| 345 |
line__crosses=LineString([(-95, 30), (0, 30)]) |
| 346 |
).count(), |
| 347 |
0, |
| 348 |
) |
| 349 |
|
| 350 |
@skipUnlessDBFeature("supports_isvalid_lookup") |
| 351 |
def test_isvalid_lookup(self): |
| 352 |
invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") |
| 353 |
State.objects.create(name="invalid", poly=invalid_geom) |
| 354 |
qs = State.objects.all() |
| 355 |
if connection.ops.oracle: |
| 356 |
# Kansas has adjacent vertices with distance 6.99244813842e-12 |
| 357 |
# which is smaller than the default Oracle tolerance. |
| 358 |
qs = qs.exclude(name="Kansas") |
| 359 |
self.assertEqual( |
| 360 |
State.objects.filter(name="Kansas", poly__isvalid=False).count(), 1 |
| 361 |
) |
| 362 |
self.assertEqual(qs.filter(poly__isvalid=False).count(), 1) |
| 363 |
self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1) |
| 364 |
|
| 365 |
@skipUnlessGISLookup("left", "right") |
| 366 |
def test_left_right_lookups(self): |
| 367 |
"Testing the 'left' and 'right' lookup types." |
| 368 |
# Left: A << B => true if xmax(A) < xmin(B) |
| 369 |
# Right: A >> B => true if xmin(A) > xmax(B) |
| 370 |
# See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. |
| 371 |
|
| 372 |
# Getting the borders for Colorado & Kansas |
| 373 |
co_border = State.objects.get(name="Colorado").poly |
| 374 |
ks_border = State.objects.get(name="Kansas").poly |
| 375 |
|
| 376 |
# Note: Wellington has an 'X' value of 174, so it will not be considered |
| 377 |
# to the left of CO. |
| 378 |
|
| 379 |
# These cities should be strictly to the right of the CO border. |
| 380 |
cities = [ |
| 381 |
"Houston", |
| 382 |
"Dallas", |
| 383 |
"Oklahoma City", |
| 384 |
"Lawrence", |
| 385 |
"Chicago", |
| 386 |
"Wellington", |
| 387 |
] |
| 388 |
qs = City.objects.filter(point__right=co_border) |
| 389 |
self.assertEqual(6, len(qs)) |
| 390 |
for c in qs: |
| 391 |
self.assertIn(c.name, cities) |
| 392 |
|
| 393 |
# These cities should be strictly to the right of the KS border. |
| 394 |
cities = ["Chicago", "Wellington"] |
| 395 |
qs = City.objects.filter(point__right=ks_border) |
| 396 |
self.assertEqual(2, len(qs)) |
| 397 |
for c in qs: |
| 398 |
self.assertIn(c.name, cities) |
| 399 |
|
| 400 |
# Note: Wellington has an 'X' value of 174, so it will not be considered |
| 401 |
# to the left of CO. |
| 402 |
vic = City.objects.get(point__left=co_border) |
| 403 |
self.assertEqual("Victoria", vic.name) |
| 404 |
|
| 405 |
cities = ["Pueblo", "Victoria"] |
| 406 |
qs = City.objects.filter(point__left=ks_border) |
| 407 |
self.assertEqual(2, len(qs)) |
| 408 |
for c in qs: |
| 409 |
self.assertIn(c.name, cities) |
| 410 |
|
| 411 |
@skipUnlessGISLookup("strictly_above", "strictly_below") |
| 412 |
def test_strictly_above_below_lookups(self): |
| 413 |
dallas = City.objects.get(name="Dallas") |
| 414 |
self.assertQuerySetEqual( |
| 415 |
City.objects.filter(point__strictly_above=dallas.point).order_by("name"), |
| 416 |
["Chicago", "Lawrence", "Oklahoma City", "Pueblo", "Victoria"], |
| 417 |
lambda b: b.name, |
| 418 |
) |
| 419 |
self.assertQuerySetEqual( |
| 420 |
City.objects.filter(point__strictly_below=dallas.point).order_by("name"), |
| 421 |
["Houston", "Wellington"], |
| 422 |
lambda b: b.name, |
| 423 |
) |
| 424 |
|
| 425 |
def test_equals_lookups(self): |
| 426 |
"Testing the 'same_as' and 'equals' lookup types." |
| 427 |
pnt = fromstr("POINT (-95.363151 29.763374)", srid=4326) |
| 428 |
c1 = City.objects.get(point=pnt) |
| 429 |
c2 = City.objects.get(point__same_as=pnt) |
| 430 |
c3 = City.objects.get(point__equals=pnt) |
| 431 |
for c in [c1, c2, c3]: |
| 432 |
self.assertEqual("Houston", c.name) |
| 433 |
|
| 434 |
@skipUnlessDBFeature("supports_null_geometries") |
| 435 |
def test_null_geometries(self): |
| 436 |
"Testing NULL geometry support, and the `isnull` lookup type." |
| 437 |
# Creating a state with a NULL boundary. |
| 438 |
State.objects.create(name="Puerto Rico") |
| 439 |
|
| 440 |
# Querying for both NULL and Non-NULL values. |
| 441 |
nullqs = State.objects.filter(poly__isnull=True) |
| 442 |
validqs = State.objects.filter(poly__isnull=False) |
| 443 |
|
| 444 |
# Puerto Rico should be NULL (it's a commonwealth unincorporated territory) |
| 445 |
self.assertEqual(1, len(nullqs)) |
| 446 |
self.assertEqual("Puerto Rico", nullqs[0].name) |
| 447 |
# GeometryField=None is an alias for __isnull=True. |
| 448 |
self.assertCountEqual(State.objects.filter(poly=None), nullqs) |
| 449 |
self.assertCountEqual(State.objects.exclude(poly=None), validqs) |
| 450 |
|
| 451 |
# The valid states should be Colorado & Kansas |
| 452 |
self.assertEqual(2, len(validqs)) |
| 453 |
state_names = [s.name for s in validqs] |
| 454 |
self.assertIn("Colorado", state_names) |
| 455 |
self.assertIn("Kansas", state_names) |
| 456 |
|
| 457 |
# Saving another commonwealth w/a NULL geometry. |
| 458 |
nmi = State.objects.create(name="Northern Mariana Islands", poly=None) |
| 459 |
self.assertIsNone(nmi.poly) |
| 460 |
|
| 461 |
# Assigning a geometry and saving -- then UPDATE back to NULL. |
| 462 |
nmi.poly = "POLYGON((0 0,1 0,1 1,1 0,0 0))" |
| 463 |
nmi.save() |
| 464 |
State.objects.filter(name="Northern Mariana Islands").update(poly=None) |
| 465 |
self.assertIsNone(State.objects.get(name="Northern Mariana Islands").poly) |
| 466 |
|
| 467 |
@skipUnlessDBFeature( |
| 468 |
"supports_null_geometries", "supports_crosses_lookup", "supports_relate_lookup" |
| 469 |
) |
| 470 |
def test_null_geometries_excluded_in_lookups(self): |
| 471 |
"""NULL features are excluded in spatial lookup functions.""" |
| 472 |
null = State.objects.create(name="NULL", poly=None) |
| 473 |
queries = [ |
| 474 |
("equals", Point(1, 1)), |
| 475 |
("disjoint", Point(1, 1)), |
| 476 |
("touches", Point(1, 1)), |
| 477 |
("crosses", LineString((0, 0), (1, 1), (5, 5))), |
| 478 |
("within", Point(1, 1)), |
| 479 |
("overlaps", LineString((0, 0), (1, 1), (5, 5))), |
| 480 |
("contains", LineString((0, 0), (1, 1), (5, 5))), |
| 481 |
("intersects", LineString((0, 0), (1, 1), (5, 5))), |
| 482 |
("relate", (Point(1, 1), "T*T***FF*")), |
| 483 |
("same_as", Point(1, 1)), |
| 484 |
("exact", Point(1, 1)), |
| 485 |
("coveredby", Point(1, 1)), |
| 486 |
("covers", Point(1, 1)), |
| 487 |
] |
| 488 |
for lookup, geom in queries: |
| 489 |
with self.subTest(lookup=lookup): |
| 490 |
self.assertNotIn( |
| 491 |
null, State.objects.filter(**{"poly__%s" % lookup: geom}) |
| 492 |
) |
| 493 |
|
| 494 |
def test_wkt_string_in_lookup(self): |
| 495 |
# Valid WKT strings don't emit error logs. |
| 496 |
with self.assertNoLogs("django.contrib.gis", "ERROR"): |
| 497 |
State.objects.filter(poly__intersects="LINESTRING(0 0, 1 1, 5 5)") |
| 498 |
|
| 499 |
@skipUnlessGISLookup("coveredby") |
| 500 |
def test_coveredby_lookup(self): |
| 501 |
poly = Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))) |
| 502 |
state = State.objects.create(name="Test", poly=poly) |
| 503 |
|
| 504 |
small_poly = Polygon(LinearRing((0, 0), (1, 4), (4, 4), (4, 1), (0, 0))) |
| 505 |
qs = State.objects.filter(poly__coveredby=small_poly) |
| 506 |
self.assertSequenceEqual(qs, []) |
| 507 |
|
| 508 |
large_poly = Polygon(LinearRing((0, 0), (-1, 6), (6, 6), (6, -1), (0, 0))) |
| 509 |
qs = State.objects.filter(poly__coveredby=large_poly) |
| 510 |
self.assertSequenceEqual(qs, [state]) |
| 511 |
|
| 512 |
if not connection.ops.oracle: |
| 513 |
# On Oracle, COVEREDBY doesn't match for EQUAL objects. |
| 514 |
qs = State.objects.filter(poly__coveredby=poly) |
| 515 |
self.assertSequenceEqual(qs, [state]) |
| 516 |
|
| 517 |
@skipUnlessGISLookup("covers") |
| 518 |
def test_covers_lookup(self): |
| 519 |
poly = Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))) |
| 520 |
state = State.objects.create(name="Test", poly=poly) |
| 521 |
|
| 522 |
small_poly = Polygon(LinearRing((0, 0), (1, 4), (4, 4), (4, 1), (0, 0))) |
| 523 |
qs = State.objects.filter(poly__covers=small_poly) |
| 524 |
self.assertSequenceEqual(qs, [state]) |
| 525 |
|
| 526 |
large_poly = Polygon(LinearRing((-1, -1), (-1, 6), (6, 6), (6, -1), (-1, -1))) |
| 527 |
qs = State.objects.filter(poly__covers=large_poly) |
| 528 |
self.assertSequenceEqual(qs, []) |
| 529 |
|
| 530 |
if not connection.ops.oracle: |
| 531 |
# On Oracle, COVERS doesn't match for EQUAL objects. |
| 532 |
qs = State.objects.filter(poly__covers=poly) |
| 533 |
self.assertSequenceEqual(qs, [state]) |
| 534 |
|
| 535 |
@skipUnlessDBFeature("supports_relate_lookup") |
| 536 |
def test_relate_lookup(self): |
| 537 |
"Testing the 'relate' lookup type." |
| 538 |
# To make things more interesting, we will have our Texas reference point in |
| 539 |
# different SRIDs. |
| 540 |
pnt1 = fromstr("POINT (649287.0363174 4177429.4494686)", srid=2847) |
| 541 |
pnt2 = fromstr("POINT(-98.4919715741052 29.4333344025053)", srid=4326) |
| 542 |
|
| 543 |
# Not passing in a geometry as first param raises a TypeError when |
| 544 |
# initializing the QuerySet. |
| 545 |
with self.assertRaises(ValueError): |
| 546 |
Country.objects.filter(mpoly__relate=(23, "foo")) |
| 547 |
|
| 548 |
# Making sure the right exception is raised for the given |
| 549 |
# bad arguments. |
| 550 |
for bad_args, e in [ |
| 551 |
((pnt1, 0), ValueError), |
| 552 |
((pnt2, "T*T***FF*", 0), ValueError), |
| 553 |
]: |
| 554 |
qs = Country.objects.filter(mpoly__relate=bad_args) |
| 555 |
with self.assertRaises(e): |
| 556 |
qs.count() |
| 557 |
|
| 558 |
contains_mask = "T*T***FF*" |
| 559 |
within_mask = "T*F**F***" |
| 560 |
intersects_mask = "T********" |
| 561 |
# Relate works differently on Oracle. |
| 562 |
if connection.ops.oracle: |
| 563 |
contains_mask = "contains" |
| 564 |
within_mask = "inside" |
| 565 |
# TODO: This is not quite the same as the PostGIS mask above |
| 566 |
intersects_mask = "overlapbdyintersect" |
| 567 |
|
| 568 |
# Testing contains relation mask. |
| 569 |
if connection.features.supports_transform: |
| 570 |
self.assertEqual( |
| 571 |
Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name, |
| 572 |
"Texas", |
| 573 |
) |
| 574 |
self.assertEqual( |
| 575 |
"Texas", Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name |
| 576 |
) |
| 577 |
|
| 578 |
# Testing within relation mask. |
| 579 |
ks = State.objects.get(name="Kansas") |
| 580 |
self.assertEqual( |
| 581 |
"Lawrence", City.objects.get(point__relate=(ks.poly, within_mask)).name |
| 582 |
) |
| 583 |
|
| 584 |
# Testing intersection relation mask. |
| 585 |
if not connection.ops.oracle: |
| 586 |
if connection.features.supports_transform: |
| 587 |
self.assertEqual( |
| 588 |
Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name, |
| 589 |
"Texas", |
| 590 |
) |
| 591 |
self.assertEqual( |
| 592 |
"Texas", Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name |
| 593 |
) |
| 594 |
self.assertEqual( |
| 595 |
"Lawrence", |
| 596 |
City.objects.get(point__relate=(ks.poly, intersects_mask)).name, |
| 597 |
) |
| 598 |
|
| 599 |
# With a complex geometry expression |
| 600 |
mask = "anyinteract" if connection.ops.oracle else within_mask |
| 601 |
self.assertFalse( |
| 602 |
City.objects.exclude( |
| 603 |
point__relate=(functions.Union("point", "point"), mask) |
| 604 |
) |
| 605 |
) |
| 606 |
|
| 607 |
def test_gis_lookups_with_complex_expressions(self): |
| 608 |
multiple_arg_lookups = { |
| 609 |
"dwithin", |
| 610 |
"relate", |
| 611 |
} # These lookups are tested elsewhere. |
| 612 |
lookups = connection.ops.gis_operators.keys() - multiple_arg_lookups |
| 613 |
self.assertTrue(lookups, "No lookups found") |
| 614 |
for lookup in lookups: |
| 615 |
with self.subTest(lookup): |
| 616 |
City.objects.filter( |
| 617 |
**{"point__" + lookup: functions.Union("point", "point")} |
| 618 |
).exists() |
| 619 |
|
| 620 |
def test_subquery_annotation(self): |
| 621 |
multifields = MultiFields.objects.create( |
| 622 |
city=City.objects.create(point=Point(1, 1)), |
| 623 |
point=Point(2, 2), |
| 624 |
poly=Polygon.from_bbox((0, 0, 2, 2)), |
| 625 |
) |
| 626 |
qs = MultiFields.objects.annotate( |
| 627 |
city_point=Subquery( |
| 628 |
City.objects.filter( |
| 629 |
id=OuterRef("city"), |
| 630 |
).values("point") |
| 631 |
), |
| 632 |
).filter( |
| 633 |
city_point__within=F("poly"), |
| 634 |
) |
| 635 |
self.assertEqual(qs.get(), multifields) |
| 636 |
|
| 637 |
|
| 638 |
class GeoQuerySetTest(TestCase): |
| 639 |
# TODO: GeoQuerySet is removed, organize these test better. |
| 640 |
fixtures = ["initial"] |
| 641 |
|
| 642 |
@skipUnlessDBFeature("supports_extent_aggr") |
| 643 |
def test_extent(self): |
| 644 |
""" |
| 645 |
Testing the `Extent` aggregate. |
| 646 |
""" |
| 647 |
# Reference query: |
| 648 |
# SELECT ST_extent(point) |
| 649 |
# FROM geoapp_city |
| 650 |
# WHERE (name='Houston' or name='Dallas');` |
| 651 |
# => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) |
| 652 |
expected = ( |
| 653 |
-96.8016128540039, |
| 654 |
29.7633724212646, |
| 655 |
-95.3631439208984, |
| 656 |
32.782058715820, |
| 657 |
) |
| 658 |
|
| 659 |
qs = City.objects.filter(name__in=("Houston", "Dallas")) |
| 660 |
extent = qs.aggregate(Extent("point"))["point__extent"] |
| 661 |
for val, exp in zip(extent, expected): |
| 662 |
self.assertAlmostEqual(exp, val, 4) |
| 663 |
self.assertIsNone( |
| 664 |
City.objects.filter(name=("Smalltown")).aggregate(Extent("point"))[ |
| 665 |
"point__extent" |
| 666 |
] |
| 667 |
) |
| 668 |
|
| 669 |
@skipUnlessDBFeature("supports_extent_aggr") |
| 670 |
def test_extent_with_limit(self): |
| 671 |
""" |
| 672 |
Testing if extent supports limit. |
| 673 |
""" |
| 674 |
extent1 = City.objects.aggregate(Extent("point"))["point__extent"] |
| 675 |
extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"] |
| 676 |
self.assertNotEqual(extent1, extent2) |
| 677 |
|
| 678 |
def test_make_line(self): |
| 679 |
""" |
| 680 |
Testing the `MakeLine` aggregate. |
| 681 |
""" |
| 682 |
if not connection.features.supports_make_line_aggr: |
| 683 |
with self.assertRaises(NotSupportedError): |
| 684 |
City.objects.aggregate(MakeLine("point")) |
| 685 |
return |
| 686 |
|
| 687 |
# MakeLine on an inappropriate field returns simply None |
| 688 |
self.assertIsNone(State.objects.aggregate(MakeLine("poly"))["poly__makeline"]) |
| 689 |
# Reference query: |
| 690 |
# SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; |
| 691 |
line = City.objects.aggregate(MakeLine("point"))["point__makeline"] |
| 692 |
ref_points = City.objects.values_list("point", flat=True) |
| 693 |
self.assertIsInstance(line, LineString) |
| 694 |
self.assertEqual(len(line), ref_points.count()) |
| 695 |
# Compare pairs of manually sorted points, as the default ordering is |
| 696 |
# flaky. |
| 697 |
for point, ref_city in zip(sorted(line), sorted(ref_points)): |
| 698 |
point_x, point_y = point |
| 699 |
self.assertAlmostEqual(point_x, ref_city.x, 5) |
| 700 |
self.assertAlmostEqual(point_y, ref_city.y, 5) |
| 701 |
|
| 702 |
@skipUnlessDBFeature("supports_union_aggr") |
| 703 |
def test_unionagg(self): |
| 704 |
""" |
| 705 |
Testing the `Union` aggregate. |
| 706 |
""" |
| 707 |
tx = Country.objects.get(name="Texas").mpoly |
| 708 |
# Houston, Dallas -- Ordering may differ depending on backend or GEOS version. |
| 709 |
union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") |
| 710 |
qs = City.objects.filter(point__within=tx) |
| 711 |
with self.assertRaises(ValueError): |
| 712 |
qs.aggregate(Union("name")) |
| 713 |
# Using `field_name` keyword argument in one query and specifying an |
| 714 |
# order in the other (which should not be used because this is |
| 715 |
# an aggregate method on a spatial column) |
| 716 |
u1 = qs.aggregate(Union("point"))["point__union"] |
| 717 |
u2 = qs.order_by("name").aggregate(Union("point"))["point__union"] |
| 718 |
self.assertTrue(union.equals(u1)) |
| 719 |
self.assertTrue(union.equals(u2)) |
| 720 |
qs = City.objects.filter(name="NotACity") |
| 721 |
self.assertIsNone(qs.aggregate(Union("point"))["point__union"]) |
| 722 |
|
| 723 |
@skipUnlessDBFeature("supports_union_aggr") |
| 724 |
def test_geoagg_subquery(self): |
| 725 |
tx = Country.objects.get(name="Texas") |
| 726 |
union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") |
| 727 |
# Use distinct() to force the usage of a subquery for aggregation. |
| 728 |
with CaptureQueriesContext(connection) as ctx: |
| 729 |
self.assertIs( |
| 730 |
union.equals( |
| 731 |
City.objects.filter(point__within=tx.mpoly) |
| 732 |
.distinct() |
| 733 |
.aggregate( |
| 734 |
Union("point"), |
| 735 |
)["point__union"], |
| 736 |
), |
| 737 |
True, |
| 738 |
) |
| 739 |
self.assertIn("subquery", ctx.captured_queries[0]["sql"]) |
| 740 |
|
| 741 |
@skipUnlessDBFeature("supports_tolerance_parameter") |
| 742 |
def test_unionagg_tolerance(self): |
| 743 |
City.objects.create( |
| 744 |
point=fromstr("POINT(-96.467222 32.751389)", srid=4326), |
| 745 |
name="Forney", |
| 746 |
) |
| 747 |
tx = Country.objects.get(name="Texas").mpoly |
| 748 |
# Tolerance is greater than distance between Forney and Dallas, that's |
| 749 |
# why Dallas is ignored. |
| 750 |
forney_houston = GEOSGeometry( |
| 751 |
"MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)", |
| 752 |
srid=4326, |
| 753 |
) |
| 754 |
self.assertIs( |
| 755 |
forney_houston.equals_exact( |
| 756 |
City.objects.filter(point__within=tx).aggregate( |
| 757 |
Union("point", tolerance=32000), |
| 758 |
)["point__union"], |
| 759 |
tolerance=10e-6, |
| 760 |
), |
| 761 |
True, |
| 762 |
) |
| 763 |
|
| 764 |
@skipUnlessDBFeature("supports_tolerance_parameter") |
| 765 |
def test_unionagg_tolerance_escaping(self): |
| 766 |
tx = Country.objects.get(name="Texas").mpoly |
| 767 |
with self.assertRaises(DatabaseError): |
| 768 |
City.objects.filter(point__within=tx).aggregate( |
| 769 |
Union("point", tolerance="0.05))), (((1"), |
| 770 |
) |
| 771 |
|
| 772 |
def test_within_subquery(self): |
| 773 |
""" |
| 774 |
Using a queryset inside a geo lookup is working (using a subquery) |
| 775 |
(#14483). |
| 776 |
""" |
| 777 |
tex_cities = City.objects.filter( |
| 778 |
point__within=Country.objects.filter(name="Texas").values("mpoly") |
| 779 |
).order_by("name") |
| 780 |
self.assertEqual( |
| 781 |
list(tex_cities.values_list("name", flat=True)), ["Dallas", "Houston"] |
| 782 |
) |
| 783 |
|
| 784 |
def test_non_concrete_field(self): |
| 785 |
NonConcreteModel.objects.create(point=Point(0, 0), name="name") |
| 786 |
list(NonConcreteModel.objects.all()) |
| 787 |
|
| 788 |
def test_values_srid(self): |
| 789 |
for c, v in zip(City.objects.all(), City.objects.values()): |
| 790 |
self.assertEqual(c.point.srid, v["point"].srid) |