test_functions.py 33 KB

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