Debian Codegraph @

tests/gis_tests/geoapp/test_functions.py

raw
1 import json
2 import math
3 import re
4 from decimal import Decimal
5
6 from django.contrib.gis.db.models import GeometryField, PolygonField, functions
7 from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon, fromstr
8 from django.contrib.gis.measure import Area
9 from django.db import NotSupportedError, connection
10 from django.db.models import IntegerField, Sum, Value
11 from django.test import TestCase, skipUnlessDBFeature
12
13 from ..utils import FuncTestMixin
14 from .models import City, Country, CountryWebMercator, ManyPointModel, State, Track
15
16
17 class GISFunctionsTests(FuncTestMixin, TestCase):
18 """
19 Testing functions from django/contrib/gis/db/models/functions.py.
20 Area/Distance/Length/Perimeter are tested in distapp/tests.
21
22 Please keep the tests in function's alphabetic order.
23 """
24
25 fixtures = ["initial"]
26
27 def test_asgeojson(self):
28 if not connection.features.has_AsGeoJSON_function:
29 with self.assertRaises(NotSupportedError):
30 list(Country.objects.annotate(json=functions.AsGeoJSON("mpoly")))
31 return
32
33 pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
34 houston_json = json.loads(
35 '{"type":"Point","crs":{"type":"name","properties":'
36 '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
37 )
38 victoria_json = json.loads(
39 '{"type":"Point",'
40 '"bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
41 '"coordinates":[-123.305196,48.462611]}'
42 )
43 chicago_json = json.loads(
44 '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
45 '"bbox":[-87.65018,41.85039,-87.65018,41.85039],'
46 '"coordinates":[-87.65018,41.85039]}'
47 )
48 if "crs" in connection.features.unsupported_geojson_options:
49 del houston_json["crs"]
50 del chicago_json["crs"]
51 if "bbox" in connection.features.unsupported_geojson_options:
52 del chicago_json["bbox"]
53 del victoria_json["bbox"]
54 if "precision" in connection.features.unsupported_geojson_options:
55 chicago_json["coordinates"] = [-87.650175, 41.850385]
56
57 # Precision argument should only be an integer
58 with self.assertRaises(TypeError):
59 City.objects.annotate(geojson=functions.AsGeoJSON("point", precision="foo"))
60
61 # Reference queries and values.
62 # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0)
63 # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo';
64 self.assertJSONEqual(
65 pueblo_json,
66 City.objects.annotate(geojson=functions.AsGeoJSON("point"))
67 .get(name="Pueblo")
68 .geojson,
69 )
70
71 # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city"
72 # WHERE "geoapp_city"."name" = 'Houston';
73 # This time we want to include the CRS by using the `crs` keyword.
74 self.assertJSONEqual(
75 City.objects.annotate(json=functions.AsGeoJSON("point", crs=True))
76 .get(name="Houston")
77 .json,
78 houston_json,
79 )
80
81 # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city"
82 # WHERE "geoapp_city"."name" = 'Houston';
83 # This time we include the bounding box by using the `bbox` keyword.
84 self.assertJSONEqual(
85 City.objects.annotate(geojson=functions.AsGeoJSON("point", bbox=True))
86 .get(name="Victoria")
87 .geojson,
88 victoria_json,
89 )
90
91 # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city"
92 # WHERE "geoapp_city"."name" = 'Chicago';
93 # Finally, we set every available keyword.
94 # MariaDB doesn't limit the number of decimals in bbox.
95 if connection.ops.mariadb:
96 chicago_json["bbox"] = [-87.650175, 41.850385, -87.650175, 41.850385]
97 try:
98 self.assertJSONEqual(
99 City.objects.annotate(
100 geojson=functions.AsGeoJSON(
101 "point", bbox=True, crs=True, precision=5
102 )
103 )
104 .get(name="Chicago")
105 .geojson,
106 chicago_json,
107 )
108 except AssertionError:
109 # Give a second chance with different coords rounding.
110 chicago_json["coordinates"][1] = 41.85038
111 self.assertJSONEqual(
112 City.objects.annotate(
113 geojson=functions.AsGeoJSON(
114 "point", bbox=True, crs=True, precision=5
115 )
116 )
117 .get(name="Chicago")
118 .geojson,
119 chicago_json,
120 )
121
122 @skipUnlessDBFeature("has_AsGeoJSON_function")
123 def test_asgeojson_option_0(self):
124 p1 = Point(1, 1, srid=4326)
125 p2 = Point(-87.65018, 41.85039, srid=4326)
126 obj = ManyPointModel.objects.create(
127 point1=p1,
128 point2=p2,
129 point3=p2.transform(3857, clone=True),
130 )
131 self.assertJSONEqual(
132 ManyPointModel.objects.annotate(geojson=functions.AsGeoJSON("point3"))
133 .get(pk=obj.pk)
134 .geojson,
135 # GeoJSON without CRS.
136 json.loads(
137 '{"type":"Point","coordinates":[-9757173.40553877, 5138594.87034608]}'
138 ),
139 )
140
141 @skipUnlessDBFeature("has_AsGML_function")
142 def test_asgml(self):
143 # Should throw a TypeError when trying to obtain GML from a
144 # non-geometry field.
145 qs = City.objects.all()
146 with self.assertRaises(TypeError):
147 qs.annotate(gml=functions.AsGML("name"))
148 ptown = City.objects.annotate(gml=functions.AsGML("point", precision=9)).get(
149 name="Pueblo"
150 )
151
152 if connection.ops.oracle:
153 # No precision parameter for Oracle :-/
154 gml_regex = re.compile(
155 r'^<gml:Point srsName="EPSG:4326" '
156 r'xmlns:gml="http://www.opengis.net/gml">'
157 r'<gml:coordinates decimal="\." cs="," ts=" ">'
158 r"-104.60925\d+,38.25500\d+ "
159 r"</gml:coordinates></gml:Point>"
160 )
161 else:
162 gml_regex = re.compile(
163 r'^<gml:Point srsName="(urn:ogc:def:crs:)?EPSG:4326"><gml:coordinates>'
164 r"-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>"
165 )
166 self.assertTrue(gml_regex.match(ptown.gml))
167 self.assertIn(
168 '<gml:pos srsDimension="2">',
169 City.objects.annotate(gml=functions.AsGML("point", version=3))
170 .get(name="Pueblo")
171 .gml,
172 )
173
174 @skipUnlessDBFeature("has_AsKML_function")
175 def test_askml(self):
176 # Should throw a TypeError when trying to obtain KML from a
177 # non-geometry field.
178 with self.assertRaises(TypeError):
179 City.objects.annotate(kml=functions.AsKML("name"))
180
181 # Ensuring the KML is as expected.
182 ptown = City.objects.annotate(kml=functions.AsKML("point", precision=9)).get(
183 name="Pueblo"
184 )
185 self.assertEqual(
186 "<Point><coordinates>-104.609252,38.255001</coordinates></Point>", ptown.kml
187 )
188
189 @skipUnlessDBFeature("has_AsSVG_function")
190 def test_assvg(self):
191 with self.assertRaises(TypeError):
192 City.objects.annotate(svg=functions.AsSVG("point", precision="foo"))
193 # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo';
194 svg1 = 'cx="-104.609252" cy="-38.255001"'
195 # Even though relative, only one point so it's practically the same except for
196 # the 'c' letter prefix on the x,y values.
197 svg2 = svg1.replace("c", "")
198 self.assertEqual(
199 svg1,
200 City.objects.annotate(svg=functions.AsSVG("point")).get(name="Pueblo").svg,
201 )
202 self.assertEqual(
203 svg2,
204 City.objects.annotate(svg=functions.AsSVG("point", relative=5))
205 .get(name="Pueblo")
206 .svg,
207 )
208
209 @skipUnlessDBFeature("has_AsWKB_function")
210 def test_aswkb(self):
211 wkb = (
212 City.objects.annotate(
213 wkb=functions.AsWKB(Point(1, 2, srid=4326)),
214 )
215 .first()
216 .wkb
217 )
218 # WKB is either XDR or NDR encoded.
219 self.assertIn(
220 bytes(wkb),
221 (
222 b"\x00\x00\x00\x00\x01?\xf0\x00\x00\x00\x00\x00\x00@\x00\x00"
223 b"\x00\x00\x00\x00\x00",
224 b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00"
225 b"\x00\x00\x00\x00\x00@",
226 ),
227 )
228
229 @skipUnlessDBFeature("has_AsWKT_function")
230 def test_aswkt(self):
231 wkt = (
232 City.objects.annotate(
233 wkt=functions.AsWKT(Point(1, 2, srid=4326)),
234 )
235 .first()
236 .wkt
237 )
238 self.assertEqual(
239 wkt, "POINT (1.0 2.0)" if connection.ops.oracle else "POINT(1 2)"
240 )
241
242 @skipUnlessDBFeature("has_Azimuth_function")
243 def test_azimuth(self):
244 # Returns the azimuth in radians.
245 azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(1, 1, srid=4326))
246 self.assertAlmostEqual(
247 City.objects.annotate(azimuth=azimuth_expr).first().azimuth,
248 math.pi / 4,
249 places=2,
250 )
251 # Returns None if the two points are coincident.
252 azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(0, 0, srid=4326))
253 self.assertIsNone(City.objects.annotate(azimuth=azimuth_expr).first().azimuth)
254
255 @skipUnlessDBFeature("has_BoundingCircle_function")
256 def test_bounding_circle(self):
257 def circle_num_points(num_seg):
258 # num_seg is the number of segments per quarter circle.
259 return (4 * num_seg) + 1
260
261 if connection.ops.postgis:
262 expected_area = 169
263 elif connection.ops.spatialite:
264 expected_area = 168
265 else: # Oracle.
266 expected_area = 171
267 country = Country.objects.annotate(
268 circle=functions.BoundingCircle("mpoly")
269 ).order_by("name")[0]
270 self.assertAlmostEqual(country.circle.area, expected_area, 0)
271 if connection.ops.postgis:
272 # By default num_seg=48.
273 self.assertEqual(country.circle.num_points, circle_num_points(48))
274
275 tests = [12, Value(12, output_field=IntegerField())]
276 for num_seq in tests:
277 with self.subTest(num_seq=num_seq):
278 country = Country.objects.annotate(
279 circle=functions.BoundingCircle("mpoly", num_seg=num_seq),
280 ).order_by("name")[0]
281 if connection.ops.postgis:
282 self.assertGreater(country.circle.area, 168.4, 0)
283 self.assertLess(country.circle.area, 169.5, 0)
284 self.assertEqual(country.circle.num_points, circle_num_points(12))
285 else:
286 self.assertAlmostEqual(country.circle.area, expected_area, 0)
287
288 @skipUnlessDBFeature("has_Centroid_function")
289 def test_centroid(self):
290 qs = State.objects.exclude(poly__isnull=True).annotate(
291 centroid=functions.Centroid("poly")
292 )
293 tol = (
294 1.8 if connection.ops.mysql else (0.1 if connection.ops.oracle else 0.00001)
295 )
296 for state in qs:
297 self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol))
298
299 with self.assertRaisesMessage(
300 TypeError, "'Centroid' takes exactly 1 argument (2 given)"
301 ):
302 State.objects.annotate(centroid=functions.Centroid("poly", "poly"))
303
304 @skipUnlessDBFeature("has_Difference_function")
305 def test_difference(self):
306 geom = Point(5, 23, srid=4326)
307 qs = Country.objects.annotate(diff=functions.Difference("mpoly", geom))
308 # Oracle does something screwy with the Texas geometry.
309 if connection.ops.oracle:
310 qs = qs.exclude(name="Texas")
311
312 for c in qs:
313 self.assertTrue(c.mpoly.difference(geom).equals(c.diff))
314
315 @skipUnlessDBFeature("has_Difference_function", "has_Transform_function")
316 def test_difference_mixed_srid(self):
317 """Testing with mixed SRID (Country has default 4326)."""
318 geom = Point(556597.4, 2632018.6, srid=3857) # Spherical Mercator
319 qs = Country.objects.annotate(difference=functions.Difference("mpoly", geom))
320 # Oracle does something screwy with the Texas geometry.
321 if connection.ops.oracle:
322 qs = qs.exclude(name="Texas")
323 for c in qs:
324 self.assertTrue(c.mpoly.difference(geom).equals(c.difference))
325
326 @skipUnlessDBFeature("has_Envelope_function")
327 def test_envelope(self):
328 countries = Country.objects.annotate(envelope=functions.Envelope("mpoly"))
329 for country in countries:
330 self.assertTrue(country.envelope.equals(country.mpoly.envelope))
331
332 @skipUnlessDBFeature("has_ForcePolygonCW_function")
333 def test_force_polygon_cw(self):
334 rings = (
335 ((0, 0), (5, 0), (0, 5), (0, 0)),
336 ((1, 1), (1, 3), (3, 1), (1, 1)),
337 )
338 rhr_rings = (
339 ((0, 0), (0, 5), (5, 0), (0, 0)),
340 ((1, 1), (3, 1), (1, 3), (1, 1)),
341 )
342 State.objects.create(name="Foo", poly=Polygon(*rings))
343 st = State.objects.annotate(
344 force_polygon_cw=functions.ForcePolygonCW("poly")
345 ).get(name="Foo")
346 self.assertEqual(rhr_rings, st.force_polygon_cw.coords)
347
348 @skipUnlessDBFeature("has_FromWKB_function")
349 def test_fromwkb(self):
350 g = Point(56.811078, 60.608647)
351 pt1, pt2 = City.objects.values_list(
352 functions.FromWKB(Value(g.wkb.tobytes())),
353 functions.FromWKB(Value(g.wkb.tobytes()), srid=4326),
354 )[0]
355 self.assertIs(g.equals_exact(pt1, 0.00001), True)
356 self.assertIsNone(pt1.srid)
357 self.assertEqual(pt2.srid, 4326)
358
359 @skipUnlessDBFeature("has_FromWKT_function")
360 def test_fromwkt(self):
361 g = Point(56.811078, 60.608647)
362 pt1, pt2 = City.objects.values_list(
363 functions.FromWKT(Value(g.wkt)),
364 functions.FromWKT(Value(g.wkt), srid=4326),
365 )[0]
366 self.assertIs(g.equals_exact(pt1, 0.00001), True)
367 self.assertIsNone(pt1.srid)
368 self.assertEqual(pt2.srid, 4326)
369
370 @skipUnlessDBFeature("has_GeoHash_function")
371 def test_geohash(self):
372 # Reference query:
373 # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston';
374 # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston';
375 ref_hash = "9vk1mfq8jx0c8e0386z6"
376 h1 = City.objects.annotate(geohash=functions.GeoHash("point")).get(
377 name="Houston"
378 )
379 h2 = City.objects.annotate(geohash=functions.GeoHash("point", precision=5)).get(
380 name="Houston"
381 )
382 self.assertEqual(ref_hash, h1.geohash[: len(ref_hash)])
383 self.assertEqual(ref_hash[:5], h2.geohash)
384
385 @skipUnlessDBFeature("has_GeometryDistance_function")
386 def test_geometry_distance(self):
387 point = Point(-90, 40, srid=4326)
388 qs = City.objects.annotate(
389 distance=functions.GeometryDistance("point", point)
390 ).order_by("distance")
391 distances = (
392 2.99091995527296,
393 5.33507274054713,
394 9.33852187483721,
395 9.91769193646233,
396 11.556465744884,
397 14.713098433352,
398 34.3635252198568,
399 276.987855073372,
400 )
401 for city, expected_distance in zip(qs, distances):
402 with self.subTest(city=city):
403 self.assertAlmostEqual(city.distance, expected_distance)
404
405 @skipUnlessDBFeature("has_Intersection_function")
406 def test_intersection(self):
407 geom = Point(5, 23, srid=4326)
408 qs = Country.objects.annotate(inter=functions.Intersection("mpoly", geom))
409 for c in qs:
410 if connection.features.empty_intersection_returns_none:
411 self.assertIsNone(c.inter)
412 else:
413 self.assertIs(c.inter.empty, True)
414
415 @skipUnlessDBFeature("supports_empty_geometries", "has_IsEmpty_function")
416 def test_isempty(self):
417 empty = City.objects.create(name="Nowhere", point=Point(srid=4326))
418 City.objects.create(name="Somewhere", point=Point(6.825, 47.1, srid=4326))
419 self.assertSequenceEqual(
420 City.objects.annotate(isempty=functions.IsEmpty("point")).filter(
421 isempty=True
422 ),
423 [empty],
424 )
425 self.assertSequenceEqual(City.objects.filter(point__isempty=True), [empty])
426
427 @skipUnlessDBFeature("has_IsValid_function")
428 def test_isvalid(self):
429 valid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))")
430 invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))")
431 State.objects.create(name="valid", poly=valid_geom)
432 State.objects.create(name="invalid", poly=invalid_geom)
433 valid = (
434 State.objects.filter(name="valid")
435 .annotate(isvalid=functions.IsValid("poly"))
436 .first()
437 )
438 invalid = (
439 State.objects.filter(name="invalid")
440 .annotate(isvalid=functions.IsValid("poly"))
441 .first()
442 )
443 self.assertIs(valid.isvalid, True)
444 self.assertIs(invalid.isvalid, False)
445
446 @skipUnlessDBFeature("has_Area_function")
447 def test_area_with_regular_aggregate(self):
448 # Create projected country objects, for this test to work on all backends.
449 for c in Country.objects.all():
450 CountryWebMercator.objects.create(
451 name=c.name, mpoly=c.mpoly.transform(3857, clone=True)
452 )
453 # Test in projected coordinate system
454 qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area("mpoly")))
455 # Some backends (e.g. Oracle) cannot group by multipolygon values, so
456 # defer such fields in the aggregation query.
457 for c in qs.defer("mpoly"):
458 result = c.area_sum
459 # If the result is a measure object, get value.
460 if isinstance(result, Area):
461 result = result.sq_m
462 self.assertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0)
463
464 @skipUnlessDBFeature("has_Area_function")
465 def test_area_lookups(self):
466 # Create projected countries so the test works on all backends.
467 CountryWebMercator.objects.bulk_create(
468 CountryWebMercator(name=c.name, mpoly=c.mpoly.transform(3857, clone=True))
469 for c in Country.objects.all()
470 )
471 qs = CountryWebMercator.objects.annotate(area=functions.Area("mpoly"))
472 self.assertEqual(
473 qs.get(area__lt=Area(sq_km=500000)),
474 CountryWebMercator.objects.get(name="New Zealand"),
475 )
476
477 with self.assertRaisesMessage(
478 ValueError, "AreaField only accepts Area measurement objects."
479 ):
480 qs.get(area__lt=500000)
481
482 @skipUnlessDBFeature("has_ClosestPoint_function")
483 def test_closest_point(self):
484 qs = Country.objects.annotate(
485 closest_point=functions.ClosestPoint("mpoly", functions.Centroid("mpoly"))
486 )
487 for country in qs:
488 self.assertIsInstance(country.closest_point, Point)
489 self.assertEqual(
490 country.mpoly.intersection(country.closest_point),
491 country.closest_point,
492 )
493
494 @skipUnlessDBFeature("has_LineLocatePoint_function")
495 def test_line_locate_point(self):
496 pos_expr = functions.LineLocatePoint(
497 LineString((0, 0), (0, 3), srid=4326), Point(0, 1, srid=4326)
498 )
499 self.assertAlmostEqual(
500 State.objects.annotate(pos=pos_expr).first().pos, 0.3333333
501 )
502
503 @skipUnlessDBFeature("has_MakeValid_function")
504 def test_make_valid(self):
505 invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))")
506 State.objects.create(name="invalid", poly=invalid_geom)
507 invalid = (
508 State.objects.filter(name="invalid")
509 .annotate(repaired=functions.MakeValid("poly"))
510 .first()
511 )
512 self.assertIs(invalid.repaired.valid, True)
513 self.assertTrue(
514 invalid.repaired.equals(
515 fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))", srid=invalid.poly.srid)
516 )
517 )
518
519 @skipUnlessDBFeature("has_MakeValid_function")
520 def test_make_valid_multipolygon(self):
521 invalid_geom = fromstr(
522 "POLYGON((0 0, 0 1 , 1 1 , 1 0, 0 0), (10 0, 10 1, 11 1, 11 0, 10 0))"
523 )
524 State.objects.create(name="invalid", poly=invalid_geom)
525 invalid = (
526 State.objects.filter(name="invalid")
527 .annotate(
528 repaired=functions.MakeValid("poly"),
529 )
530 .get()
531 )
532 self.assertIs(invalid.repaired.valid, True)
533 self.assertTrue(
534 invalid.repaired.equals(
535 fromstr(
536 "MULTIPOLYGON (((0 0, 0 1, 1 1, 1 0, 0 0)), "
537 "((10 0, 10 1, 11 1, 11 0, 10 0)))",
538 srid=invalid.poly.srid,
539 )
540 )
541 )
542 self.assertEqual(len(invalid.repaired), 2)
543
544 @skipUnlessDBFeature("has_MakeValid_function")
545 def test_make_valid_output_field(self):
546 # output_field is GeometryField instance because different geometry
547 # types can be returned.
548 output_field = functions.MakeValid(
549 Value(Polygon(), PolygonField(srid=42)),
550 ).output_field
551 self.assertIs(output_field.__class__, GeometryField)
552 self.assertEqual(output_field.srid, 42)
553
554 @skipUnlessDBFeature("has_MemSize_function")
555 def test_memsize(self):
556 ptown = City.objects.annotate(size=functions.MemSize("point")).get(
557 name="Pueblo"
558 )
559 # Exact value depends on database and version.
560 self.assertTrue(20 <= ptown.size <= 105)
561
562 @skipUnlessDBFeature("has_NumGeom_function")
563 def test_num_geom(self):
564 # Both 'countries' only have two geometries.
565 for c in Country.objects.annotate(num_geom=functions.NumGeometries("mpoly")):
566 self.assertEqual(2, c.num_geom)
567
568 qs = City.objects.filter(point__isnull=False).annotate(
569 num_geom=functions.NumGeometries("point")
570 )
571 for city in qs:
572 # The results for the number of geometries on non-collections
573 # depends on the database.
574 if connection.ops.mysql or connection.ops.mariadb:
575 self.assertIsNone(city.num_geom)
576 else:
577 self.assertEqual(1, city.num_geom)
578
579 @skipUnlessDBFeature("has_NumPoint_function")
580 def test_num_points(self):
581 coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
582 Track.objects.create(name="Foo", line=LineString(coords))
583 qs = Track.objects.annotate(num_points=functions.NumPoints("line"))
584 self.assertEqual(qs.first().num_points, 2)
585 mpoly_qs = Country.objects.annotate(num_points=functions.NumPoints("mpoly"))
586 if not connection.features.supports_num_points_poly:
587 for c in mpoly_qs:
588 self.assertIsNone(c.num_points)
589 return
590
591 for c in mpoly_qs:
592 self.assertEqual(c.mpoly.num_points, c.num_points)
593
594 for c in City.objects.annotate(num_points=functions.NumPoints("point")):
595 self.assertEqual(c.num_points, 1)
596
597 @skipUnlessDBFeature("has_PointOnSurface_function")
598 def test_point_on_surface(self):
599 qs = Country.objects.annotate(
600 point_on_surface=functions.PointOnSurface("mpoly")
601 )
602 for country in qs:
603 self.assertTrue(country.mpoly.intersection(country.point_on_surface))
604
605 @skipUnlessDBFeature("has_Reverse_function")
606 def test_reverse_geom(self):
607 coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
608 Track.objects.create(name="Foo", line=LineString(coords))
609 track = Track.objects.annotate(reverse_geom=functions.Reverse("line")).get(
610 name="Foo"
611 )
612 coords.reverse()
613 self.assertEqual(tuple(coords), track.reverse_geom.coords)
614
615 @skipUnlessDBFeature("has_Scale_function")
616 def test_scale(self):
617 xfac, yfac = 2, 3
618 tol = 5 # The low precision tolerance is for SpatiaLite
619 qs = Country.objects.annotate(scaled=functions.Scale("mpoly", xfac, yfac))
620 for country in qs:
621 for p1, p2 in zip(country.mpoly, country.scaled):
622 for r1, r2 in zip(p1, p2):
623 for c1, c2 in zip(r1.coords, r2.coords):
624 self.assertAlmostEqual(c1[0] * xfac, c2[0], tol)
625 self.assertAlmostEqual(c1[1] * yfac, c2[1], tol)
626 # Test float/Decimal values
627 qs = Country.objects.annotate(
628 scaled=functions.Scale("mpoly", 1.5, Decimal("2.5"))
629 )
630 self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area)
631
632 @skipUnlessDBFeature("has_SnapToGrid_function")
633 def test_snap_to_grid(self):
634 # Let's try and break snap_to_grid() with bad combinations of arguments.
635 for bad_args in ((), range(3), range(5)):
636 with self.assertRaises(ValueError):
637 Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args))
638 for bad_args in (("1.0",), (1.0, None), tuple(map(str, range(4)))):
639 with self.assertRaises(TypeError):
640 Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args))
641
642 # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
643 # from the world borders dataset he provides.
644 wkt = (
645 "MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,"
646 "12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,"
647 "12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,"
648 "12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,"
649 "12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,"
650 "12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,"
651 "12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,"
652 "12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))"
653 )
654 Country.objects.create(name="San Marino", mpoly=fromstr(wkt))
655
656 # Because floating-point arithmetic isn't exact, we set a tolerance
657 # to pass into GEOS `equals_exact`.
658 tol = 0.000000001
659
660 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1))
661 # FROM "geoapp_country"
662 # WHERE "geoapp_country"."name" = 'San Marino';
663 ref = fromstr("MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))")
664 self.assertTrue(
665 ref.equals_exact(
666 Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.1))
667 .get(name="San Marino")
668 .snap,
669 tol,
670 )
671 )
672
673 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23))
674 # FROM "geoapp_country"
675 # WHERE "geoapp_country"."name" = 'San Marino';
676 ref = fromstr(
677 "MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))"
678 )
679 self.assertTrue(
680 ref.equals_exact(
681 Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.05, 0.23))
682 .get(name="San Marino")
683 .snap,
684 tol,
685 )
686 )
687
688 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23))
689 # FROM "geoapp_country"
690 # WHERE "geoapp_country"."name" = 'San Marino';
691 ref = fromstr(
692 "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,"
693 "12.45 43.87,12.4 43.87)))"
694 )
695 self.assertTrue(
696 ref.equals_exact(
697 Country.objects.annotate(
698 snap=functions.SnapToGrid("mpoly", 0.05, 0.23, 0.5, 0.17)
699 )
700 .get(name="San Marino")
701 .snap,
702 tol,
703 )
704 )
705
706 @skipUnlessDBFeature("has_SymDifference_function")
707 def test_sym_difference(self):
708 geom = Point(5, 23, srid=4326)
709 qs = Country.objects.annotate(
710 sym_difference=functions.SymDifference("mpoly", geom)
711 )
712 # Oracle does something screwy with the Texas geometry.
713 if connection.ops.oracle:
714 qs = qs.exclude(name="Texas")
715 for country in qs:
716 self.assertTrue(
717 country.mpoly.sym_difference(geom).equals(country.sym_difference)
718 )
719
720 @skipUnlessDBFeature("has_Transform_function")
721 def test_transform(self):
722 # Pre-transformed points for Houston and Pueblo.
723 ptown = fromstr("POINT(992363.390841912 481455.395105533)", srid=2774)
724
725 # Asserting the result of the transform operation with the values in
726 # the pre-transformed points.
727 h = City.objects.annotate(pt=functions.Transform("point", ptown.srid)).get(
728 name="Pueblo"
729 )
730 self.assertEqual(2774, h.pt.srid)
731 # Precision is low due to version variations in PROJ and GDAL.
732 self.assertLess(ptown.x - h.pt.x, 1)
733 self.assertLess(ptown.y - h.pt.y, 1)
734
735 @skipUnlessDBFeature("has_Translate_function")
736 def test_translate(self):
737 xfac, yfac = 5, -23
738 qs = Country.objects.annotate(
739 translated=functions.Translate("mpoly", xfac, yfac)
740 )
741 for c in qs:
742 for p1, p2 in zip(c.mpoly, c.translated):
743 for r1, r2 in zip(p1, p2):
744 for c1, c2 in zip(r1.coords, r2.coords):
745 # The low precision is for SpatiaLite
746 self.assertAlmostEqual(c1[0] + xfac, c2[0], 5)
747 self.assertAlmostEqual(c1[1] + yfac, c2[1], 5)
748
749 # Some combined function tests
750 @skipUnlessDBFeature(
751 "has_Difference_function",
752 "has_Intersection_function",
753 "has_SymDifference_function",
754 "has_Union_function",
755 )
756 def test_diff_intersection_union(self):
757 geom = Point(5, 23, srid=4326)
758 qs = Country.objects.annotate(
759 difference=functions.Difference("mpoly", geom),
760 sym_difference=functions.SymDifference("mpoly", geom),
761 union=functions.Union("mpoly", geom),
762 intersection=functions.Intersection("mpoly", geom),
763 )
764
765 if connection.ops.oracle:
766 # Should be able to execute the queries; however, they won't be the same
767 # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or
768 # SpatiaLite).
769 return
770 for c in qs:
771 self.assertTrue(c.mpoly.difference(geom).equals(c.difference))
772 if connection.features.empty_intersection_returns_none:
773 self.assertIsNone(c.intersection)
774 else:
775 self.assertIs(c.intersection.empty, True)
776 self.assertTrue(c.mpoly.sym_difference(geom).equals(c.sym_difference))
777 self.assertTrue(c.mpoly.union(geom).equals(c.union))
778
779 @skipUnlessDBFeature("has_Union_function")
780 def test_union(self):
781 """Union with all combinations of geometries/geometry fields."""
782 geom = Point(-95.363151, 29.763374, srid=4326)
783
784 union = (
785 City.objects.annotate(union=functions.Union("point", geom))
786 .get(name="Dallas")
787 .union
788 )
789 expected = fromstr(
790 "MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)", srid=4326
791 )
792 self.assertTrue(expected.equals(union))
793
794 union = (
795 City.objects.annotate(union=functions.Union(geom, "point"))
796 .get(name="Dallas")
797 .union
798 )
799 self.assertTrue(expected.equals(union))
800
801 union = (
802 City.objects.annotate(union=functions.Union("point", "point"))
803 .get(name="Dallas")
804 .union
805 )
806 expected = GEOSGeometry("POINT(-96.801611 32.782057)", srid=4326)
807 self.assertTrue(expected.equals(union))
808
809 union = (
810 City.objects.annotate(union=functions.Union(geom, geom))
811 .get(name="Dallas")
812 .union
813 )
814 self.assertTrue(geom.equals(union))
815
816 @skipUnlessDBFeature("has_Union_function", "has_Transform_function")
817 def test_union_mixed_srid(self):
818 """The result SRID depends on the order of parameters."""
819 geom = Point(61.42915, 55.15402, srid=4326)
820 geom_3857 = geom.transform(3857, clone=True)
821 tol = 0.001
822
823 for city in City.objects.annotate(union=functions.Union("point", geom_3857)):
824 expected = city.point | geom
825 self.assertTrue(city.union.equals_exact(expected, tol))
826 self.assertEqual(city.union.srid, 4326)
827
828 for city in City.objects.annotate(union=functions.Union(geom_3857, "point")):
829 expected = geom_3857 | city.point.transform(3857, clone=True)
830 self.assertTrue(expected.equals_exact(city.union, tol))
831 self.assertEqual(city.union.srid, 3857)
832
833 def test_argument_validation(self):
834 with self.assertRaisesMessage(
835 ValueError, "SRID is required for all geometries."
836 ):
837 City.objects.annotate(geo=functions.GeoFunc(Point(1, 1)))
838
839 msg = "GeoFunc function requires a GeometryField in position 1, got CharField."
840 with self.assertRaisesMessage(TypeError, msg):
841 City.objects.annotate(geo=functions.GeoFunc("name"))
842
843 msg = "GeoFunc function requires a geometric argument in position 1."
844 with self.assertRaisesMessage(TypeError, msg):
845 City.objects.annotate(union=functions.GeoFunc(1, "point")).get(
846 name="Dallas"
847 )