test_geos.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. import ctypes
  2. import itertools
  3. import json
  4. import math
  5. import pickle
  6. import random
  7. from binascii import a2b_hex
  8. from io import BytesIO
  9. from unittest import mock, skipIf
  10. from django.contrib.gis import gdal
  11. from django.contrib.gis.geos import (
  12. GeometryCollection,
  13. GEOSException,
  14. GEOSGeometry,
  15. LinearRing,
  16. LineString,
  17. MultiLineString,
  18. MultiPoint,
  19. MultiPolygon,
  20. Point,
  21. Polygon,
  22. fromfile,
  23. fromstr,
  24. )
  25. from django.contrib.gis.geos.libgeos import geos_version_tuple
  26. from django.contrib.gis.shortcuts import numpy
  27. from django.template import Context
  28. from django.template.engine import Engine
  29. from django.test import SimpleTestCase
  30. from ..test_data import TestDataMixin
  31. class GEOSTest(SimpleTestCase, TestDataMixin):
  32. def test_wkt(self):
  33. "Testing WKT output."
  34. for g in self.geometries.wkt_out:
  35. geom = fromstr(g.wkt)
  36. if geom.hasz:
  37. self.assertEqual(g.ewkt, geom.wkt)
  38. def test_wkt_invalid(self):
  39. msg = "String input unrecognized as WKT EWKT, and HEXEWKB."
  40. with self.assertRaisesMessage(ValueError, msg):
  41. fromstr("POINT(٠٠١ ٠)")
  42. with self.assertRaisesMessage(ValueError, msg):
  43. fromstr("SRID=٧٥٨٣;POINT(100 0)")
  44. def test_hex(self):
  45. "Testing HEX output."
  46. for g in self.geometries.hex_wkt:
  47. geom = fromstr(g.wkt)
  48. self.assertEqual(g.hex, geom.hex.decode())
  49. def test_hexewkb(self):
  50. "Testing (HEX)EWKB output."
  51. # For testing HEX(EWKB).
  52. ogc_hex = b"01010000000000000000000000000000000000F03F"
  53. ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040"
  54. # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`
  55. hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F"
  56. # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`
  57. hexewkb_3d = (
  58. b"01010000A0E61000000000000000000000000000000000F03F0000000000000040"
  59. )
  60. pnt_2d = Point(0, 1, srid=4326)
  61. pnt_3d = Point(0, 1, 2, srid=4326)
  62. # OGC-compliant HEX will not have SRID value.
  63. self.assertEqual(ogc_hex, pnt_2d.hex)
  64. self.assertEqual(ogc_hex_3d, pnt_3d.hex)
  65. # HEXEWKB should be appropriate for its dimension -- have to use an
  66. # a WKBWriter w/dimension set accordingly, else GEOS will insert
  67. # garbage into 3D coordinate if there is none.
  68. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
  69. self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
  70. self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True)
  71. # Same for EWKB.
  72. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
  73. self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
  74. # Redundant sanity check.
  75. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
  76. @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required")
  77. def test_4d_hexewkb(self):
  78. ogc_hex_4d = (
  79. b"01010000C00000000000000000000000000000"
  80. b"F03F00000000000000400000000000000000"
  81. )
  82. hexewkb_4d = (
  83. b"01010000E0E61000000000000000000000000000000000"
  84. b"F03F00000000000000400000000000000000"
  85. )
  86. pnt_4d = Point(0, 1, 2, 0, srid=4326)
  87. self.assertEqual(ogc_hex_4d, pnt_4d.hex)
  88. self.assertEqual(hexewkb_4d, pnt_4d.hexewkb)
  89. self.assertIs(GEOSGeometry(hexewkb_4d).hasm, True)
  90. self.assertEqual(memoryview(a2b_hex(hexewkb_4d)), pnt_4d.ewkb)
  91. def test_kml(self):
  92. "Testing KML output."
  93. for tg in self.geometries.wkt_out:
  94. geom = fromstr(tg.wkt)
  95. kml = getattr(tg, "kml", False)
  96. if kml:
  97. self.assertEqual(kml, geom.kml)
  98. def test_errors(self):
  99. "Testing the Error handlers."
  100. # string-based
  101. for err in self.geometries.errors:
  102. with self.assertRaises((GEOSException, ValueError)):
  103. fromstr(err.wkt)
  104. # Bad WKB
  105. with self.assertRaises(GEOSException):
  106. GEOSGeometry(memoryview(b"0"))
  107. class NotAGeometry:
  108. pass
  109. # Some other object
  110. with self.assertRaises(TypeError):
  111. GEOSGeometry(NotAGeometry())
  112. # None
  113. with self.assertRaises(TypeError):
  114. GEOSGeometry(None)
  115. def test_wkb(self):
  116. "Testing WKB output."
  117. for g in self.geometries.hex_wkt:
  118. geom = fromstr(g.wkt)
  119. wkb = geom.wkb
  120. self.assertEqual(wkb.hex().upper(), g.hex)
  121. def test_create_hex(self):
  122. "Testing creation from HEX."
  123. for g in self.geometries.hex_wkt:
  124. geom_h = GEOSGeometry(g.hex)
  125. # we need to do this so decimal places get normalized
  126. geom_t = fromstr(g.wkt)
  127. self.assertEqual(geom_t.wkt, geom_h.wkt)
  128. def test_create_wkb(self):
  129. "Testing creation from WKB."
  130. for g in self.geometries.hex_wkt:
  131. wkb = memoryview(bytes.fromhex(g.hex))
  132. geom_h = GEOSGeometry(wkb)
  133. # we need to do this so decimal places get normalized
  134. geom_t = fromstr(g.wkt)
  135. self.assertEqual(geom_t.wkt, geom_h.wkt)
  136. def test_ewkt(self):
  137. "Testing EWKT."
  138. srids = (-1, 32140)
  139. for srid in srids:
  140. for p in self.geometries.polygons:
  141. ewkt = "SRID=%d;%s" % (srid, p.wkt)
  142. poly = fromstr(ewkt)
  143. self.assertEqual(srid, poly.srid)
  144. self.assertEqual(srid, poly.shell.srid)
  145. self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
  146. def test_json(self):
  147. "Testing GeoJSON input/output (via GDAL)."
  148. for g in self.geometries.json_geoms:
  149. geom = GEOSGeometry(g.wkt)
  150. if not hasattr(g, "not_equal"):
  151. # Loading jsons to prevent decimal differences
  152. self.assertEqual(json.loads(g.json), json.loads(geom.json))
  153. self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
  154. self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json))
  155. def test_json_srid(self):
  156. geojson_data = {
  157. "type": "Point",
  158. "coordinates": [2, 49],
  159. "crs": {
  160. "type": "name",
  161. "properties": {"name": "urn:ogc:def:crs:EPSG::4322"},
  162. },
  163. }
  164. self.assertEqual(
  165. GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322)
  166. )
  167. def test_fromfile(self):
  168. "Testing the fromfile() factory."
  169. ref_pnt = GEOSGeometry("POINT(5 23)")
  170. wkt_f = BytesIO()
  171. wkt_f.write(ref_pnt.wkt.encode())
  172. wkb_f = BytesIO()
  173. wkb_f.write(bytes(ref_pnt.wkb))
  174. # Other tests use `fromfile()` on string filenames so those
  175. # aren't tested here.
  176. for fh in (wkt_f, wkb_f):
  177. fh.seek(0)
  178. pnt = fromfile(fh)
  179. self.assertEqual(ref_pnt, pnt)
  180. def test_eq(self):
  181. "Testing equivalence."
  182. p = fromstr("POINT(5 23)")
  183. self.assertEqual(p, p.wkt)
  184. self.assertNotEqual(p, "foo")
  185. ls = fromstr("LINESTRING(0 0, 1 1, 5 5)")
  186. self.assertEqual(ls, ls.wkt)
  187. self.assertNotEqual(p, "bar")
  188. self.assertEqual(p, "POINT(5.0 23.0)")
  189. # Error shouldn't be raise on equivalence testing with
  190. # an invalid type.
  191. for g in (p, ls):
  192. self.assertIsNotNone(g)
  193. self.assertNotEqual(g, {"foo": "bar"})
  194. self.assertIsNot(g, False)
  195. def test_hash(self):
  196. point_1 = Point(5, 23)
  197. point_2 = Point(5, 23, srid=4326)
  198. point_3 = Point(5, 23, srid=32632)
  199. multipoint_1 = MultiPoint(point_1, srid=4326)
  200. multipoint_2 = MultiPoint(point_2)
  201. multipoint_3 = MultiPoint(point_3)
  202. self.assertNotEqual(hash(point_1), hash(point_2))
  203. self.assertNotEqual(hash(point_1), hash(point_3))
  204. self.assertNotEqual(hash(point_2), hash(point_3))
  205. self.assertNotEqual(hash(multipoint_1), hash(multipoint_2))
  206. self.assertEqual(hash(multipoint_2), hash(multipoint_3))
  207. self.assertNotEqual(hash(multipoint_1), hash(point_1))
  208. self.assertNotEqual(hash(multipoint_2), hash(point_2))
  209. self.assertNotEqual(hash(multipoint_3), hash(point_3))
  210. def test_eq_with_srid(self):
  211. "Testing non-equivalence with different srids."
  212. p0 = Point(5, 23)
  213. p1 = Point(5, 23, srid=4326)
  214. p2 = Point(5, 23, srid=32632)
  215. # GEOS
  216. self.assertNotEqual(p0, p1)
  217. self.assertNotEqual(p1, p2)
  218. # EWKT
  219. self.assertNotEqual(p0, p1.ewkt)
  220. self.assertNotEqual(p1, p0.ewkt)
  221. self.assertNotEqual(p1, p2.ewkt)
  222. # Equivalence with matching SRIDs
  223. self.assertEqual(p2, p2)
  224. self.assertEqual(p2, p2.ewkt)
  225. # WKT contains no SRID so will not equal
  226. self.assertNotEqual(p2, p2.wkt)
  227. # SRID of 0
  228. self.assertEqual(p0, "SRID=0;POINT (5 23)")
  229. self.assertNotEqual(p1, "SRID=0;POINT (5 23)")
  230. @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required")
  231. def test_equals_identical(self):
  232. tests = [
  233. # Empty inputs of different types are not equals_identical.
  234. ("POINT EMPTY", "LINESTRING EMPTY", False),
  235. # Empty inputs of different dimensions are not equals_identical.
  236. ("POINT EMPTY", "POINT Z EMPTY", False),
  237. # Non-empty inputs of different dimensions are not equals_identical.
  238. ("POINT Z (1 2 3)", "POINT M (1 2 3)", False),
  239. ("POINT ZM (1 2 3 4)", "POINT Z (1 2 3)", False),
  240. # Inputs with different structure are not equals_identical.
  241. ("LINESTRING (1 1, 2 2)", "MULTILINESTRING ((1 1, 2 2))", False),
  242. # Inputs with different types are not equals_identical.
  243. (
  244. "GEOMETRYCOLLECTION (LINESTRING (1 1, 2 2))",
  245. "MULTILINESTRING ((1 1, 2 2))",
  246. False,
  247. ),
  248. # Same lines are equals_identical.
  249. ("LINESTRING M (1 1 0, 2 2 1)", "LINESTRING M (1 1 0, 2 2 1)", True),
  250. # Different lines are not equals_identical.
  251. ("LINESTRING M (1 1 0, 2 2 1)", "LINESTRING M (1 1 1, 2 2 1)", False),
  252. # Same polygons are equals_identical.
  253. ("POLYGON ((0 0, 1 0, 1 1, 0 0))", "POLYGON ((0 0, 1 0, 1 1, 0 0))", True),
  254. # Different polygons are not equals_identical.
  255. ("POLYGON ((0 0, 1 0, 1 1, 0 0))", "POLYGON ((1 0, 1 1, 0 0, 1 0))", False),
  256. # Different polygons (number of holes) are not equals_identical.
  257. (
  258. "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1))",
  259. (
  260. "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1), "
  261. "(3 3, 4 3, 4 4, 3 3))"
  262. ),
  263. False,
  264. ),
  265. # Same collections are equals_identical.
  266. (
  267. "MULTILINESTRING ((1 1, 2 2), (2 2, 3 3))",
  268. "MULTILINESTRING ((1 1, 2 2), (2 2, 3 3))",
  269. True,
  270. ),
  271. # Different collections (structure) are not equals_identical.
  272. (
  273. "MULTILINESTRING ((1 1, 2 2), (2 2, 3 3))",
  274. "MULTILINESTRING ((2 2, 3 3), (1 1, 2 2))",
  275. False,
  276. ),
  277. ]
  278. for g1, g2, is_equal_identical in tests:
  279. with self.subTest(g1=g1, g2=g2):
  280. self.assertIs(
  281. fromstr(g1).equals_identical(fromstr(g2)), is_equal_identical
  282. )
  283. @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required")
  284. def test_infinite_values_equals_identical(self):
  285. # Input with identical infinite values are equals_identical.
  286. g1 = Point(x=float("nan"), y=math.inf)
  287. g2 = Point(x=float("nan"), y=math.inf)
  288. self.assertIs(g1.equals_identical(g2), True)
  289. @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.11.0")
  290. def test_equals_identical_geos_version(self):
  291. g1 = fromstr("POINT (1 2 3)")
  292. g2 = fromstr("POINT (1 2 3)")
  293. msg = "GEOSGeometry.equals_identical() requires GEOS >= 3.12.0"
  294. with self.assertRaisesMessage(GEOSException, msg):
  295. g1.equals_identical(g2)
  296. @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required")
  297. def test_hasm(self):
  298. pnt_xym = fromstr("POINT M (5 23 8)")
  299. self.assertTrue(pnt_xym.hasm)
  300. pnt_xyzm = fromstr("POINT (5 23 8 0)")
  301. self.assertTrue(pnt_xyzm.hasm)
  302. @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.11.0")
  303. def test_hasm_geos_version(self):
  304. p = fromstr("POINT (1 2 3)")
  305. msg = "GEOSGeometry.hasm requires GEOS >= 3.12.0."
  306. with self.assertRaisesMessage(GEOSException, msg):
  307. p.hasm
  308. def test_points(self):
  309. "Testing Point objects."
  310. prev = fromstr("POINT(0 0)")
  311. for p in self.geometries.points:
  312. # Creating the point from the WKT
  313. pnt = fromstr(p.wkt)
  314. self.assertEqual(pnt.geom_type, "Point")
  315. self.assertEqual(pnt.geom_typeid, 0)
  316. self.assertEqual(pnt.dims, 0)
  317. self.assertEqual(p.x, pnt.x)
  318. self.assertEqual(p.y, pnt.y)
  319. self.assertEqual(pnt, fromstr(p.wkt))
  320. self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__.
  321. # Making sure that the point's X, Y components are what we expect
  322. self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
  323. self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
  324. # Testing the third dimension, and getting the tuple arguments
  325. if hasattr(p, "z"):
  326. self.assertIs(pnt.hasz, True)
  327. self.assertEqual(p.z, pnt.z)
  328. self.assertEqual(p.z, pnt.tuple[2], 9)
  329. tup_args = (p.x, p.y, p.z)
  330. set_tup1 = (2.71, 3.14, 5.23)
  331. set_tup2 = (5.23, 2.71, 3.14)
  332. else:
  333. self.assertIs(pnt.hasz, False)
  334. self.assertIsNone(pnt.z)
  335. tup_args = (p.x, p.y)
  336. set_tup1 = (2.71, 3.14)
  337. set_tup2 = (3.14, 2.71)
  338. # Centroid operation on point should be point itself
  339. self.assertEqual(p.centroid, pnt.centroid.tuple)
  340. # Now testing the different constructors
  341. pnt2 = Point(tup_args) # e.g., Point((1, 2))
  342. pnt3 = Point(*tup_args) # e.g., Point(1, 2)
  343. self.assertEqual(pnt, pnt2)
  344. self.assertEqual(pnt, pnt3)
  345. # Now testing setting the x and y
  346. pnt.y = 3.14
  347. pnt.x = 2.71
  348. self.assertEqual(3.14, pnt.y)
  349. self.assertEqual(2.71, pnt.x)
  350. # Setting via the tuple/coords property
  351. pnt.tuple = set_tup1
  352. self.assertEqual(set_tup1, pnt.tuple)
  353. pnt.coords = set_tup2
  354. self.assertEqual(set_tup2, pnt.coords)
  355. prev = pnt # setting the previous geometry
  356. def test_point_reverse(self):
  357. point = GEOSGeometry("POINT(144.963 -37.8143)", 4326)
  358. self.assertEqual(point.srid, 4326)
  359. point.reverse()
  360. self.assertEqual(point.ewkt, "SRID=4326;POINT (-37.8143 144.963)")
  361. def test_multipoints(self):
  362. "Testing MultiPoint objects."
  363. for mp in self.geometries.multipoints:
  364. mpnt = fromstr(mp.wkt)
  365. self.assertEqual(mpnt.geom_type, "MultiPoint")
  366. self.assertEqual(mpnt.geom_typeid, 4)
  367. self.assertEqual(mpnt.dims, 0)
  368. self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
  369. self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
  370. with self.assertRaises(IndexError):
  371. mpnt.__getitem__(len(mpnt))
  372. self.assertEqual(mp.centroid, mpnt.centroid.tuple)
  373. self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))
  374. for p in mpnt:
  375. self.assertEqual(p.geom_type, "Point")
  376. self.assertEqual(p.geom_typeid, 0)
  377. self.assertIs(p.empty, False)
  378. self.assertIs(p.valid, True)
  379. def test_linestring(self):
  380. "Testing LineString objects."
  381. prev = fromstr("POINT(0 0)")
  382. for line in self.geometries.linestrings:
  383. ls = fromstr(line.wkt)
  384. self.assertEqual(ls.geom_type, "LineString")
  385. self.assertEqual(ls.geom_typeid, 1)
  386. self.assertEqual(ls.dims, 1)
  387. self.assertIs(ls.empty, False)
  388. self.assertIs(ls.ring, False)
  389. if hasattr(line, "centroid"):
  390. self.assertEqual(line.centroid, ls.centroid.tuple)
  391. if hasattr(line, "tup"):
  392. self.assertEqual(line.tup, ls.tuple)
  393. self.assertEqual(ls, fromstr(line.wkt))
  394. self.assertIs(ls == prev, False) # Use assertIs() to test __eq__.
  395. with self.assertRaises(IndexError):
  396. ls.__getitem__(len(ls))
  397. prev = ls
  398. # Creating a LineString from a tuple, list, and numpy array
  399. self.assertEqual(ls, LineString(ls.tuple)) # tuple
  400. self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
  401. self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
  402. # Point individual arguments
  403. self.assertEqual(
  404. ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt
  405. )
  406. if numpy:
  407. self.assertEqual(
  408. ls, LineString(numpy.array(ls.tuple))
  409. ) # as numpy array
  410. with self.assertRaisesMessage(
  411. TypeError, "Each coordinate should be a sequence (list or tuple)"
  412. ):
  413. LineString((0, 0))
  414. with self.assertRaisesMessage(
  415. ValueError, "LineString requires at least 2 points, got 1."
  416. ):
  417. LineString([(0, 0)])
  418. if numpy:
  419. with self.assertRaisesMessage(
  420. ValueError, "LineString requires at least 2 points, got 1."
  421. ):
  422. LineString(numpy.array([(0, 0)]))
  423. with mock.patch("django.contrib.gis.geos.linestring.numpy", False):
  424. with self.assertRaisesMessage(
  425. TypeError, "Invalid initialization input for LineStrings."
  426. ):
  427. LineString("wrong input")
  428. # Test __iter__().
  429. self.assertEqual(
  430. list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)]
  431. )
  432. def test_linestring_reverse(self):
  433. line = GEOSGeometry("LINESTRING(144.963 -37.8143,151.2607 -33.887)", 4326)
  434. self.assertEqual(line.srid, 4326)
  435. line.reverse()
  436. self.assertEqual(
  437. line.ewkt, "SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)"
  438. )
  439. def test_is_counterclockwise(self):
  440. lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0))
  441. self.assertIs(lr.is_counterclockwise, True)
  442. lr.reverse()
  443. self.assertIs(lr.is_counterclockwise, False)
  444. msg = "Orientation of an empty LinearRing cannot be determined."
  445. with self.assertRaisesMessage(ValueError, msg):
  446. LinearRing().is_counterclockwise
  447. def test_is_counterclockwise_geos_error(self):
  448. with mock.patch("django.contrib.gis.geos.prototypes.cs_is_ccw") as mocked:
  449. mocked.return_value = 0
  450. mocked.func_name = "GEOSCoordSeq_isCCW"
  451. msg = 'Error encountered in GEOS C function "GEOSCoordSeq_isCCW".'
  452. with self.assertRaisesMessage(GEOSException, msg):
  453. LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise
  454. def test_multilinestring(self):
  455. "Testing MultiLineString objects."
  456. prev = fromstr("POINT(0 0)")
  457. for line in self.geometries.multilinestrings:
  458. ml = fromstr(line.wkt)
  459. self.assertEqual(ml.geom_type, "MultiLineString")
  460. self.assertEqual(ml.geom_typeid, 5)
  461. self.assertEqual(ml.dims, 1)
  462. self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9)
  463. self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9)
  464. self.assertEqual(ml, fromstr(line.wkt))
  465. self.assertIs(ml == prev, False) # Use assertIs() to test __eq__.
  466. prev = ml
  467. for ls in ml:
  468. self.assertEqual(ls.geom_type, "LineString")
  469. self.assertEqual(ls.geom_typeid, 1)
  470. self.assertIs(ls.empty, False)
  471. with self.assertRaises(IndexError):
  472. ml.__getitem__(len(ml))
  473. self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
  474. self.assertEqual(
  475. ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml))
  476. )
  477. def test_linearring(self):
  478. "Testing LinearRing objects."
  479. for rr in self.geometries.linearrings:
  480. lr = fromstr(rr.wkt)
  481. self.assertEqual(lr.geom_type, "LinearRing")
  482. self.assertEqual(lr.geom_typeid, 2)
  483. self.assertEqual(lr.dims, 1)
  484. self.assertEqual(rr.n_p, len(lr))
  485. self.assertIs(lr.valid, True)
  486. self.assertIs(lr.empty, False)
  487. # Creating a LinearRing from a tuple, list, and numpy array
  488. self.assertEqual(lr, LinearRing(lr.tuple))
  489. self.assertEqual(lr, LinearRing(*lr.tuple))
  490. self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
  491. if numpy:
  492. self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
  493. with self.assertRaisesMessage(
  494. ValueError, "LinearRing requires at least 4 points, got 3."
  495. ):
  496. LinearRing((0, 0), (1, 1), (0, 0))
  497. with self.assertRaisesMessage(
  498. ValueError, "LinearRing requires at least 4 points, got 1."
  499. ):
  500. LinearRing([(0, 0)])
  501. if numpy:
  502. with self.assertRaisesMessage(
  503. ValueError, "LinearRing requires at least 4 points, got 1."
  504. ):
  505. LinearRing(numpy.array([(0, 0)]))
  506. def test_linearring_json(self):
  507. self.assertJSONEqual(
  508. LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json,
  509. '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}',
  510. )
  511. def test_polygons_from_bbox(self):
  512. "Testing `from_bbox` class method."
  513. bbox = (-180, -90, 180, 90)
  514. p = Polygon.from_bbox(bbox)
  515. self.assertEqual(bbox, p.extent)
  516. # Testing numerical precision
  517. x = 3.14159265358979323
  518. bbox = (0, 0, 1, x)
  519. p = Polygon.from_bbox(bbox)
  520. y = p.extent[-1]
  521. self.assertEqual(format(x, ".13f"), format(y, ".13f"))
  522. def test_polygons(self):
  523. "Testing Polygon objects."
  524. prev = fromstr("POINT(0 0)")
  525. for p in self.geometries.polygons:
  526. # Creating the Polygon, testing its properties.
  527. poly = fromstr(p.wkt)
  528. self.assertEqual(poly.geom_type, "Polygon")
  529. self.assertEqual(poly.geom_typeid, 3)
  530. self.assertEqual(poly.dims, 2)
  531. self.assertIs(poly.empty, False)
  532. self.assertIs(poly.ring, False)
  533. self.assertEqual(p.n_i, poly.num_interior_rings)
  534. self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
  535. self.assertEqual(p.n_p, poly.num_points)
  536. # Area & Centroid
  537. self.assertAlmostEqual(p.area, poly.area, 9)
  538. self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
  539. self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)
  540. # Testing the geometry equivalence
  541. self.assertEqual(poly, fromstr(p.wkt))
  542. # Should not be equal to previous geometry
  543. self.assertIs(poly == prev, False) # Use assertIs() to test __eq__.
  544. self.assertIs(poly != prev, True) # Use assertIs() to test __ne__.
  545. # Testing the exterior ring
  546. ring = poly.exterior_ring
  547. self.assertEqual(ring.geom_type, "LinearRing")
  548. self.assertEqual(ring.geom_typeid, 2)
  549. if p.ext_ring_cs:
  550. self.assertEqual(p.ext_ring_cs, ring.tuple)
  551. self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
  552. # Testing __getitem__ and __setitem__ on invalid indices
  553. with self.assertRaises(IndexError):
  554. poly.__getitem__(len(poly))
  555. with self.assertRaises(IndexError):
  556. poly.__setitem__(len(poly), False)
  557. with self.assertRaises(IndexError):
  558. poly.__getitem__(-1 * len(poly) - 1)
  559. # Testing __iter__
  560. for r in poly:
  561. self.assertEqual(r.geom_type, "LinearRing")
  562. self.assertEqual(r.geom_typeid, 2)
  563. # Testing polygon construction.
  564. with self.assertRaises(TypeError):
  565. Polygon(0, [1, 2, 3])
  566. with self.assertRaises(TypeError):
  567. Polygon("foo")
  568. # Polygon(shell, (hole1, ... holeN))
  569. ext_ring, *int_rings = poly
  570. self.assertEqual(poly, Polygon(ext_ring, int_rings))
  571. # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
  572. ring_tuples = tuple(r.tuple for r in poly)
  573. self.assertEqual(poly, Polygon(*ring_tuples))
  574. # Constructing with tuples of LinearRings.
  575. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
  576. self.assertEqual(
  577. poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt
  578. )
  579. def test_polygons_templates(self):
  580. # Accessing Polygon attributes in templates should work.
  581. engine = Engine()
  582. template = engine.from_string("{{ polygons.0.wkt }}")
  583. polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]]
  584. content = template.render(Context({"polygons": polygons}))
  585. self.assertIn("MULTIPOLYGON (((100", content)
  586. def test_polygon_comparison(self):
  587. p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  588. p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
  589. self.assertGreater(p1, p2)
  590. self.assertLess(p2, p1)
  591. p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
  592. p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
  593. self.assertGreater(p4, p3)
  594. self.assertLess(p3, p4)
  595. def test_multipolygons(self):
  596. "Testing MultiPolygon objects."
  597. fromstr("POINT (0 0)")
  598. for mp in self.geometries.multipolygons:
  599. mpoly = fromstr(mp.wkt)
  600. self.assertEqual(mpoly.geom_type, "MultiPolygon")
  601. self.assertEqual(mpoly.geom_typeid, 6)
  602. self.assertEqual(mpoly.dims, 2)
  603. self.assertEqual(mp.valid, mpoly.valid)
  604. if mp.valid:
  605. self.assertEqual(mp.num_geom, mpoly.num_geom)
  606. self.assertEqual(mp.n_p, mpoly.num_coords)
  607. self.assertEqual(mp.num_geom, len(mpoly))
  608. with self.assertRaises(IndexError):
  609. mpoly.__getitem__(len(mpoly))
  610. for p in mpoly:
  611. self.assertEqual(p.geom_type, "Polygon")
  612. self.assertEqual(p.geom_typeid, 3)
  613. self.assertIs(p.valid, True)
  614. self.assertEqual(
  615. mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt
  616. )
  617. def test_memory_hijinks(self):
  618. "Testing Geometry __del__() on rings and polygons."
  619. # #### Memory issues with rings and poly
  620. # These tests are needed to ensure sanity with writable geometries.
  621. # Getting a polygon with interior rings, and pulling out the interior rings
  622. poly = fromstr(self.geometries.polygons[1].wkt)
  623. ring1 = poly[0]
  624. ring2 = poly[1]
  625. # These deletes should be 'harmless' since they are done on child geometries
  626. del ring1
  627. del ring2
  628. ring1 = poly[0]
  629. ring2 = poly[1]
  630. # Deleting the polygon
  631. del poly
  632. # Access to these rings is OK since they are clones.
  633. str(ring1)
  634. str(ring2)
  635. def test_coord_seq(self):
  636. "Testing Coordinate Sequence objects."
  637. for p in self.geometries.polygons:
  638. if p.ext_ring_cs:
  639. # Constructing the polygon and getting the coordinate sequence
  640. poly = fromstr(p.wkt)
  641. cs = poly.exterior_ring.coord_seq
  642. self.assertEqual(
  643. p.ext_ring_cs, cs.tuple
  644. ) # done in the Polygon test too.
  645. self.assertEqual(
  646. len(p.ext_ring_cs), len(cs)
  647. ) # Making sure __len__ works
  648. # Checks __getitem__ and __setitem__
  649. for i in range(len(p.ext_ring_cs)):
  650. c1 = p.ext_ring_cs[i] # Expected value
  651. c2 = cs[i] # Value from coordseq
  652. self.assertEqual(c1, c2)
  653. # Constructing the test value to set the coordinate sequence with
  654. if len(c1) == 2:
  655. tset = (5, 23)
  656. else:
  657. tset = (5, 23, 8)
  658. cs[i] = tset
  659. # Making sure every set point matches what we expect
  660. for j in range(len(tset)):
  661. cs[i] = tset
  662. self.assertEqual(tset[j], cs[i][j])
  663. def test_relate_pattern(self):
  664. "Testing relate() and relate_pattern()."
  665. g = fromstr("POINT (0 0)")
  666. with self.assertRaises(GEOSException):
  667. g.relate_pattern(0, "invalid pattern, yo")
  668. for rg in self.geometries.relate_geoms:
  669. a = fromstr(rg.wkt_a)
  670. b = fromstr(rg.wkt_b)
  671. self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern))
  672. self.assertEqual(rg.pattern, a.relate(b))
  673. def test_intersection(self):
  674. "Testing intersects() and intersection()."
  675. for i in range(len(self.geometries.topology_geoms)):
  676. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  677. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  678. i1 = fromstr(self.geometries.intersect_geoms[i].wkt)
  679. self.assertIs(a.intersects(b), True)
  680. i2 = a.intersection(b)
  681. self.assertTrue(i1.equals(i2))
  682. self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator
  683. a &= b # testing __iand__
  684. self.assertTrue(i1.equals(a))
  685. def test_union(self):
  686. "Testing union()."
  687. for i in range(len(self.geometries.topology_geoms)):
  688. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  689. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  690. u1 = fromstr(self.geometries.union_geoms[i].wkt)
  691. u2 = a.union(b)
  692. self.assertTrue(u1.equals(u2))
  693. self.assertTrue(u1.equals(a | b)) # __or__ is union operator
  694. a |= b # testing __ior__
  695. self.assertTrue(u1.equals(a))
  696. def test_unary_union(self):
  697. "Testing unary_union."
  698. for i in range(len(self.geometries.topology_geoms)):
  699. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  700. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  701. u1 = fromstr(self.geometries.union_geoms[i].wkt)
  702. u2 = GeometryCollection(a, b).unary_union
  703. self.assertTrue(u1.equals(u2))
  704. def test_difference(self):
  705. "Testing difference()."
  706. for i in range(len(self.geometries.topology_geoms)):
  707. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  708. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  709. d1 = fromstr(self.geometries.diff_geoms[i].wkt)
  710. d2 = a.difference(b)
  711. self.assertTrue(d1.equals(d2))
  712. self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator
  713. a -= b # testing __isub__
  714. self.assertTrue(d1.equals(a))
  715. def test_symdifference(self):
  716. "Testing sym_difference()."
  717. for i in range(len(self.geometries.topology_geoms)):
  718. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  719. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  720. d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)
  721. d2 = a.sym_difference(b)
  722. self.assertTrue(d1.equals(d2))
  723. self.assertTrue(
  724. d1.equals(a ^ b)
  725. ) # __xor__ is symmetric difference operator
  726. a ^= b # testing __ixor__
  727. self.assertTrue(d1.equals(a))
  728. def test_buffer(self):
  729. bg = self.geometries.buffer_geoms[0]
  730. g = fromstr(bg.wkt)
  731. # Can't use a floating-point for the number of quadsegs.
  732. with self.assertRaises(ctypes.ArgumentError):
  733. g.buffer(bg.width, quadsegs=1.1)
  734. self._test_buffer(self.geometries.buffer_geoms, "buffer")
  735. def test_buffer_with_style(self):
  736. bg = self.geometries.buffer_with_style_geoms[0]
  737. g = fromstr(bg.wkt)
  738. # Can't use a floating-point for the number of quadsegs.
  739. with self.assertRaises(ctypes.ArgumentError):
  740. g.buffer_with_style(bg.width, quadsegs=1.1)
  741. # Can't use a floating-point for the end cap style.
  742. with self.assertRaises(ctypes.ArgumentError):
  743. g.buffer_with_style(bg.width, end_cap_style=1.2)
  744. # Can't use a end cap style that is not in the enum.
  745. with self.assertRaises(GEOSException):
  746. g.buffer_with_style(bg.width, end_cap_style=55)
  747. # Can't use a floating-point for the join style.
  748. with self.assertRaises(ctypes.ArgumentError):
  749. g.buffer_with_style(bg.width, join_style=1.3)
  750. # Can't use a join style that is not in the enum.
  751. with self.assertRaises(GEOSException):
  752. g.buffer_with_style(bg.width, join_style=66)
  753. self._test_buffer(
  754. itertools.chain(
  755. self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms
  756. ),
  757. "buffer_with_style",
  758. )
  759. def _test_buffer(self, geometries, buffer_method_name):
  760. for bg in geometries:
  761. g = fromstr(bg.wkt)
  762. # The buffer we expect
  763. exp_buf = fromstr(bg.buffer_wkt)
  764. # Constructing our buffer
  765. buf_kwargs = {
  766. kwarg_name: getattr(bg, kwarg_name)
  767. for kwarg_name in (
  768. "width",
  769. "quadsegs",
  770. "end_cap_style",
  771. "join_style",
  772. "mitre_limit",
  773. )
  774. if hasattr(bg, kwarg_name)
  775. }
  776. buf = getattr(g, buffer_method_name)(**buf_kwargs)
  777. self.assertEqual(exp_buf.num_coords, buf.num_coords)
  778. self.assertEqual(len(exp_buf), len(buf))
  779. # Now assuring that each point in the buffer is almost equal
  780. for j in range(len(exp_buf)):
  781. exp_ring = exp_buf[j]
  782. buf_ring = buf[j]
  783. self.assertEqual(len(exp_ring), len(buf_ring))
  784. for k in range(len(exp_ring)):
  785. # Asserting the X, Y of each point are almost equal (due to
  786. # floating point imprecision).
  787. self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
  788. self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
  789. def test_covers(self):
  790. poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)))
  791. self.assertTrue(poly.covers(Point(5, 5)))
  792. self.assertFalse(poly.covers(Point(100, 100)))
  793. def test_closed(self):
  794. ls_closed = LineString((0, 0), (1, 1), (0, 0))
  795. ls_not_closed = LineString((0, 0), (1, 1))
  796. self.assertFalse(ls_not_closed.closed)
  797. self.assertTrue(ls_closed.closed)
  798. def test_srid(self):
  799. "Testing the SRID property and keyword."
  800. # Testing SRID keyword on Point
  801. pnt = Point(5, 23, srid=4326)
  802. self.assertEqual(4326, pnt.srid)
  803. pnt.srid = 3084
  804. self.assertEqual(3084, pnt.srid)
  805. with self.assertRaises(ctypes.ArgumentError):
  806. pnt.srid = "4326"
  807. # Testing SRID keyword on fromstr(), and on Polygon rings.
  808. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269)
  809. self.assertEqual(4269, poly.srid)
  810. for ring in poly:
  811. self.assertEqual(4269, ring.srid)
  812. poly.srid = 4326
  813. self.assertEqual(4326, poly.shell.srid)
  814. # Testing SRID keyword on GeometryCollection
  815. gc = GeometryCollection(
  816. Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021
  817. )
  818. self.assertEqual(32021, gc.srid)
  819. for i in range(len(gc)):
  820. self.assertEqual(32021, gc[i].srid)
  821. # GEOS may get the SRID from HEXEWKB
  822. # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
  823. # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
  824. hex = "0101000020E610000000000000000014400000000000003740"
  825. p1 = fromstr(hex)
  826. self.assertEqual(4326, p1.srid)
  827. p2 = fromstr(p1.hex)
  828. self.assertIsNone(p2.srid)
  829. p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
  830. self.assertEqual(-1, p3.srid)
  831. # Testing that geometry SRID could be set to its own value
  832. pnt_wo_srid = Point(1, 1)
  833. pnt_wo_srid.srid = pnt_wo_srid.srid
  834. # Input geometries that have an SRID.
  835. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid)
  836. self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid)
  837. with self.assertRaisesMessage(
  838. ValueError, "Input geometry already has SRID: %d." % pnt.srid
  839. ):
  840. GEOSGeometry(pnt.ewkt, srid=1)
  841. with self.assertRaisesMessage(
  842. ValueError, "Input geometry already has SRID: %d." % pnt.srid
  843. ):
  844. GEOSGeometry(pnt.ewkb, srid=1)
  845. def test_custom_srid(self):
  846. """Test with a null srid and a srid unknown to GDAL."""
  847. for srid in [None, 999999]:
  848. pnt = Point(111200, 220900, srid=srid)
  849. self.assertTrue(
  850. pnt.ewkt.startswith(
  851. ("SRID=%s;" % srid if srid else "") + "POINT (111200"
  852. )
  853. )
  854. self.assertIsInstance(pnt.ogr, gdal.OGRGeometry)
  855. self.assertIsNone(pnt.srs)
  856. # Test conversion from custom to a known srid
  857. c2w = gdal.CoordTransform(
  858. gdal.SpatialReference(
  859. "+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +datum=WGS84 "
  860. "+units=m +no_defs"
  861. ),
  862. gdal.SpatialReference(4326),
  863. )
  864. new_pnt = pnt.transform(c2w, clone=True)
  865. self.assertEqual(new_pnt.srid, 4326)
  866. self.assertAlmostEqual(new_pnt.x, 1, 1)
  867. self.assertAlmostEqual(new_pnt.y, 2, 1)
  868. def test_mutable_geometries(self):
  869. "Testing the mutability of Polygons and Geometry Collections."
  870. # ### Testing the mutability of Polygons ###
  871. for p in self.geometries.polygons:
  872. poly = fromstr(p.wkt)
  873. # Should only be able to use __setitem__ with LinearRing geometries.
  874. with self.assertRaises(TypeError):
  875. poly.__setitem__(0, LineString((1, 1), (2, 2)))
  876. # Constructing the new shell by adding 500 to every point in the old shell.
  877. shell_tup = poly.shell.tuple
  878. new_coords = []
  879. for point in shell_tup:
  880. new_coords.append((point[0] + 500.0, point[1] + 500.0))
  881. new_shell = LinearRing(*tuple(new_coords))
  882. # Assigning polygon's exterior ring w/the new shell
  883. poly.exterior_ring = new_shell
  884. str(new_shell) # new shell is still accessible
  885. self.assertEqual(poly.exterior_ring, new_shell)
  886. self.assertEqual(poly[0], new_shell)
  887. # ### Testing the mutability of Geometry Collections
  888. for tg in self.geometries.multipoints:
  889. mp = fromstr(tg.wkt)
  890. for i in range(len(mp)):
  891. # Creating a random point.
  892. pnt = mp[i]
  893. new = Point(random.randint(21, 100), random.randint(21, 100))
  894. # Testing the assignment
  895. mp[i] = new
  896. str(new) # what was used for the assignment is still accessible
  897. self.assertEqual(mp[i], new)
  898. self.assertEqual(mp[i].wkt, new.wkt)
  899. self.assertNotEqual(pnt, mp[i])
  900. # MultiPolygons involve much more memory management because each
  901. # Polygon w/in the collection has its own rings.
  902. for tg in self.geometries.multipolygons:
  903. mpoly = fromstr(tg.wkt)
  904. for i in range(len(mpoly)):
  905. poly = mpoly[i]
  906. old_poly = mpoly[i]
  907. # Offsetting the each ring in the polygon by 500.
  908. for j in range(len(poly)):
  909. r = poly[j]
  910. for k in range(len(r)):
  911. r[k] = (r[k][0] + 500.0, r[k][1] + 500.0)
  912. poly[j] = r
  913. self.assertNotEqual(mpoly[i], poly)
  914. # Testing the assignment
  915. mpoly[i] = poly
  916. str(poly) # Still accessible
  917. self.assertEqual(mpoly[i], poly)
  918. self.assertNotEqual(mpoly[i], old_poly)
  919. # Extreme (!!) __setitem__ -- no longer works, have to detect
  920. # in the first object that __setitem__ is called in the subsequent
  921. # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?
  922. # mpoly[0][0][0] = (3.14, 2.71)
  923. # self.assertEqual((3.14, 2.71), mpoly[0][0][0])
  924. # Doing it more slowly..
  925. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0])
  926. # del mpoly
  927. def test_point_list_assignment(self):
  928. p = Point(0, 0)
  929. p[:] = (1, 2, 3)
  930. self.assertEqual(p, Point(1, 2, 3))
  931. p[:] = ()
  932. self.assertEqual(p.wkt, Point())
  933. p[:] = (1, 2)
  934. self.assertEqual(p.wkt, Point(1, 2))
  935. with self.assertRaises(ValueError):
  936. p[:] = (1,)
  937. with self.assertRaises(ValueError):
  938. p[:] = (1, 2, 3, 4, 5)
  939. def test_linestring_list_assignment(self):
  940. ls = LineString((0, 0), (1, 1))
  941. ls[:] = ()
  942. self.assertEqual(ls, LineString())
  943. ls[:] = ((0, 0), (1, 1), (2, 2))
  944. self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2)))
  945. with self.assertRaises(ValueError):
  946. ls[:] = (1,)
  947. def test_linearring_list_assignment(self):
  948. ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))
  949. ls[:] = ()
  950. self.assertEqual(ls, LinearRing())
  951. ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
  952. self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  953. with self.assertRaises(ValueError):
  954. ls[:] = ((0, 0), (1, 1), (2, 2))
  955. def test_polygon_list_assignment(self):
  956. pol = Polygon()
  957. pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),)
  958. self.assertEqual(
  959. pol,
  960. Polygon(
  961. ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),
  962. ),
  963. )
  964. pol[:] = ()
  965. self.assertEqual(pol, Polygon())
  966. def test_geometry_collection_list_assignment(self):
  967. p = Point()
  968. gc = GeometryCollection()
  969. gc[:] = [p]
  970. self.assertEqual(gc, GeometryCollection(p))
  971. gc[:] = ()
  972. self.assertEqual(gc, GeometryCollection())
  973. def test_threed(self):
  974. "Testing three-dimensional geometries."
  975. # Testing a 3D Point
  976. pnt = Point(2, 3, 8)
  977. self.assertEqual((2.0, 3.0, 8.0), pnt.coords)
  978. with self.assertRaises(TypeError):
  979. pnt.tuple = (1.0, 2.0)
  980. pnt.coords = (1.0, 2.0, 3.0)
  981. self.assertEqual((1.0, 2.0, 3.0), pnt.coords)
  982. # Testing a 3D LineString
  983. ls = LineString((2.0, 3.0, 8.0), (50.0, 250.0, -117.0))
  984. self.assertEqual(((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)), ls.tuple)
  985. with self.assertRaises(TypeError):
  986. ls.__setitem__(0, (1.0, 2.0))
  987. ls[0] = (1.0, 2.0, 3.0)
  988. self.assertEqual((1.0, 2.0, 3.0), ls[0])
  989. def test_distance(self):
  990. "Testing the distance() function."
  991. # Distance to self should be 0.
  992. pnt = Point(0, 0)
  993. self.assertEqual(0.0, pnt.distance(Point(0, 0)))
  994. # Distance should be 1
  995. self.assertEqual(1.0, pnt.distance(Point(0, 1)))
  996. # Distance should be ~ sqrt(2)
  997. self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
  998. # Distances are from the closest vertex in each geometry --
  999. # should be 3 (distance from (2, 2) to (5, 2)).
  1000. ls1 = LineString((0, 0), (1, 1), (2, 2))
  1001. ls2 = LineString((5, 2), (6, 1), (7, 0))
  1002. self.assertEqual(3, ls1.distance(ls2))
  1003. def test_length(self):
  1004. "Testing the length property."
  1005. # Points have 0 length.
  1006. pnt = Point(0, 0)
  1007. self.assertEqual(0.0, pnt.length)
  1008. # Should be ~ sqrt(2)
  1009. ls = LineString((0, 0), (1, 1))
  1010. self.assertAlmostEqual(1.41421356237, ls.length, 11)
  1011. # Should be circumference of Polygon
  1012. poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  1013. self.assertEqual(4.0, poly.length)
  1014. # Should be sum of each element's length in collection.
  1015. mpoly = MultiPolygon(poly.clone(), poly)
  1016. self.assertEqual(8.0, mpoly.length)
  1017. def test_emptyCollections(self):
  1018. "Testing empty geometries and collections."
  1019. geoms = [
  1020. GeometryCollection([]),
  1021. fromstr("GEOMETRYCOLLECTION EMPTY"),
  1022. GeometryCollection(),
  1023. fromstr("POINT EMPTY"),
  1024. Point(),
  1025. fromstr("LINESTRING EMPTY"),
  1026. LineString(),
  1027. fromstr("POLYGON EMPTY"),
  1028. Polygon(),
  1029. fromstr("MULTILINESTRING EMPTY"),
  1030. MultiLineString(),
  1031. fromstr("MULTIPOLYGON EMPTY"),
  1032. MultiPolygon(()),
  1033. MultiPolygon(),
  1034. ]
  1035. if numpy:
  1036. geoms.append(LineString(numpy.array([])))
  1037. for g in geoms:
  1038. self.assertIs(g.empty, True)
  1039. # Testing len() and num_geom.
  1040. if isinstance(g, Polygon):
  1041. self.assertEqual(1, len(g)) # Has one empty linear ring
  1042. self.assertEqual(1, g.num_geom)
  1043. self.assertEqual(0, len(g[0]))
  1044. elif isinstance(g, (Point, LineString)):
  1045. self.assertEqual(1, g.num_geom)
  1046. self.assertEqual(0, len(g))
  1047. else:
  1048. self.assertEqual(0, g.num_geom)
  1049. self.assertEqual(0, len(g))
  1050. # Testing __getitem__ (doesn't work on Point or Polygon)
  1051. if isinstance(g, Point):
  1052. # IndexError is not raised in GEOS 3.8.0.
  1053. if geos_version_tuple() != (3, 8, 0):
  1054. with self.assertRaises(IndexError):
  1055. g.x
  1056. elif isinstance(g, Polygon):
  1057. lr = g.shell
  1058. self.assertEqual("LINEARRING EMPTY", lr.wkt)
  1059. self.assertEqual(0, len(lr))
  1060. self.assertIs(lr.empty, True)
  1061. with self.assertRaises(IndexError):
  1062. lr.__getitem__(0)
  1063. else:
  1064. with self.assertRaises(IndexError):
  1065. g.__getitem__(0)
  1066. def test_collection_dims(self):
  1067. gc = GeometryCollection([])
  1068. self.assertEqual(gc.dims, -1)
  1069. gc = GeometryCollection(Point(0, 0))
  1070. self.assertEqual(gc.dims, 0)
  1071. gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0))
  1072. self.assertEqual(gc.dims, 1)
  1073. gc = GeometryCollection(
  1074. LineString((0, 0), (1, 1)),
  1075. Polygon(((0, 0), (0, 1), (1, 1), (0, 0))),
  1076. Point(0, 0),
  1077. )
  1078. self.assertEqual(gc.dims, 2)
  1079. def test_collections_of_collections(self):
  1080. "Testing GeometryCollection handling of other collections."
  1081. # Creating a GeometryCollection WKT string composed of other
  1082. # collections and polygons.
  1083. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid]
  1084. coll.extend(mls.wkt for mls in self.geometries.multilinestrings)
  1085. coll.extend(p.wkt for p in self.geometries.polygons)
  1086. coll.extend(mp.wkt for mp in self.geometries.multipoints)
  1087. gc_wkt = "GEOMETRYCOLLECTION(%s)" % ",".join(coll)
  1088. # Should construct ok from WKT
  1089. gc1 = GEOSGeometry(gc_wkt)
  1090. # Should also construct ok from individual geometry arguments.
  1091. gc2 = GeometryCollection(*tuple(g for g in gc1))
  1092. # And, they should be equal.
  1093. self.assertEqual(gc1, gc2)
  1094. def test_gdal(self):
  1095. "Testing `ogr` and `srs` properties."
  1096. g1 = fromstr("POINT(5 23)")
  1097. self.assertIsInstance(g1.ogr, gdal.OGRGeometry)
  1098. self.assertIsNone(g1.srs)
  1099. g1_3d = fromstr("POINT(5 23 8)")
  1100. self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry)
  1101. self.assertEqual(g1_3d.ogr.z, 8)
  1102. g2 = fromstr("LINESTRING(0 0, 5 5, 23 23)", srid=4326)
  1103. self.assertIsInstance(g2.ogr, gdal.OGRGeometry)
  1104. self.assertIsInstance(g2.srs, gdal.SpatialReference)
  1105. self.assertEqual(g2.hex, g2.ogr.hex)
  1106. self.assertEqual("WGS 84", g2.srs.name)
  1107. @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required")
  1108. def test_gdal_4d(self):
  1109. g1_4d = fromstr("POINT(5 23 8 0)")
  1110. self.assertIsInstance(g1_4d.ogr, gdal.OGRGeometry)
  1111. self.assertEqual(g1_4d.ogr.m, 0)
  1112. def test_copy(self):
  1113. "Testing use with the Python `copy` module."
  1114. import copy
  1115. poly = GEOSGeometry(
  1116. "POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))"
  1117. )
  1118. cpy1 = copy.copy(poly)
  1119. cpy2 = copy.deepcopy(poly)
  1120. self.assertNotEqual(poly._ptr, cpy1._ptr)
  1121. self.assertNotEqual(poly._ptr, cpy2._ptr)
  1122. def test_transform(self):
  1123. "Testing `transform` method."
  1124. orig = GEOSGeometry("POINT (-104.609 38.255)", 4326)
  1125. trans = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774)
  1126. # Using a srid, a SpatialReference object, and a CoordTransform object
  1127. # for transformations.
  1128. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
  1129. t1.transform(trans.srid)
  1130. t2.transform(gdal.SpatialReference("EPSG:2774"))
  1131. ct = gdal.CoordTransform(
  1132. gdal.SpatialReference("WGS84"), gdal.SpatialReference(2774)
  1133. )
  1134. t3.transform(ct)
  1135. # Testing use of the `clone` keyword.
  1136. k1 = orig.clone()
  1137. k2 = k1.transform(trans.srid, clone=True)
  1138. self.assertEqual(k1, orig)
  1139. self.assertNotEqual(k1, k2)
  1140. # Different PROJ versions use different transformations, all are
  1141. # correct as having a 1 meter accuracy.
  1142. prec = -1
  1143. for p in (t1, t2, t3, k2):
  1144. self.assertAlmostEqual(trans.x, p.x, prec)
  1145. self.assertAlmostEqual(trans.y, p.y, prec)
  1146. def test_transform_3d(self):
  1147. p3d = GEOSGeometry("POINT (5 23 100)", 4326)
  1148. p3d.transform(2774)
  1149. self.assertAlmostEqual(p3d.z, 100, 3)
  1150. def test_transform_noop(self):
  1151. """Testing `transform` method (SRID match)"""
  1152. # transform() should no-op if source & dest SRIDs match,
  1153. # regardless of whether GDAL is available.
  1154. g = GEOSGeometry("POINT (-104.609 38.255)", 4326)
  1155. gt = g.tuple
  1156. g.transform(4326)
  1157. self.assertEqual(g.tuple, gt)
  1158. self.assertEqual(g.srid, 4326)
  1159. g = GEOSGeometry("POINT (-104.609 38.255)", 4326)
  1160. g1 = g.transform(4326, clone=True)
  1161. self.assertEqual(g1.tuple, g.tuple)
  1162. self.assertEqual(g1.srid, 4326)
  1163. self.assertIsNot(g1, g, "Clone didn't happen")
  1164. def test_transform_nosrid(self):
  1165. """Testing `transform` method (no SRID or negative SRID)"""
  1166. g = GEOSGeometry("POINT (-104.609 38.255)", srid=None)
  1167. with self.assertRaises(GEOSException):
  1168. g.transform(2774)
  1169. g = GEOSGeometry("POINT (-104.609 38.255)", srid=None)
  1170. with self.assertRaises(GEOSException):
  1171. g.transform(2774, clone=True)
  1172. g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1)
  1173. with self.assertRaises(GEOSException):
  1174. g.transform(2774)
  1175. g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1)
  1176. with self.assertRaises(GEOSException):
  1177. g.transform(2774, clone=True)
  1178. def test_extent(self):
  1179. "Testing `extent` method."
  1180. # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
  1181. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
  1182. self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
  1183. pnt = Point(5.23, 17.8)
  1184. # Extent of points is just the point itself repeated.
  1185. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
  1186. # Testing on the 'real world' Polygon.
  1187. poly = fromstr(self.geometries.polygons[3].wkt)
  1188. ring = poly.shell
  1189. x, y = ring.x, ring.y
  1190. xmin, ymin = min(x), min(y)
  1191. xmax, ymax = max(x), max(y)
  1192. self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
  1193. def test_pickle(self):
  1194. "Testing pickling and unpickling support."
  1195. # Creating a list of test geometries for pickling,
  1196. # and setting the SRID on some of them.
  1197. def get_geoms(lst, srid=None):
  1198. return [GEOSGeometry(tg.wkt, srid) for tg in lst]
  1199. tgeoms = get_geoms(self.geometries.points)
  1200. tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326))
  1201. tgeoms.extend(get_geoms(self.geometries.polygons, 3084))
  1202. tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857))
  1203. tgeoms.append(Point(srid=4326))
  1204. tgeoms.append(Point())
  1205. for geom in tgeoms:
  1206. s1 = pickle.dumps(geom)
  1207. g1 = pickle.loads(s1)
  1208. self.assertEqual(geom, g1)
  1209. self.assertEqual(geom.srid, g1.srid)
  1210. def test_prepared(self):
  1211. "Testing PreparedGeometry support."
  1212. # Creating a simple multipolygon and getting a prepared version.
  1213. mpoly = GEOSGeometry(
  1214. "MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))"
  1215. )
  1216. prep = mpoly.prepared
  1217. # A set of test points.
  1218. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
  1219. for pnt in pnts:
  1220. # Results should be the same (but faster)
  1221. self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
  1222. self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
  1223. self.assertEqual(mpoly.covers(pnt), prep.covers(pnt))
  1224. self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)")))
  1225. self.assertTrue(prep.disjoint(Point(-5, -5)))
  1226. poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))
  1227. self.assertTrue(prep.overlaps(poly))
  1228. poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))
  1229. self.assertTrue(prep.touches(poly))
  1230. poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1)))
  1231. self.assertTrue(prep.within(poly))
  1232. # Original geometry deletion should not crash the prepared one (#21662)
  1233. del mpoly
  1234. self.assertTrue(prep.covers(Point(5, 5)))
  1235. def test_line_merge(self):
  1236. "Testing line merge support"
  1237. ref_geoms = (
  1238. fromstr("LINESTRING(1 1, 1 1, 3 3)"),
  1239. fromstr("MULTILINESTRING((1 1, 3 3), (3 3, 4 2))"),
  1240. )
  1241. ref_merged = (
  1242. fromstr("LINESTRING(1 1, 3 3)"),
  1243. fromstr("LINESTRING (1 1, 3 3, 4 2)"),
  1244. )
  1245. for geom, merged in zip(ref_geoms, ref_merged):
  1246. self.assertEqual(merged, geom.merged)
  1247. def test_valid_reason(self):
  1248. "Testing IsValidReason support"
  1249. g = GEOSGeometry("POINT(0 0)")
  1250. self.assertTrue(g.valid)
  1251. self.assertIsInstance(g.valid_reason, str)
  1252. self.assertEqual(g.valid_reason, "Valid Geometry")
  1253. g = GEOSGeometry("LINESTRING(0 0, 0 0)")
  1254. self.assertFalse(g.valid)
  1255. self.assertIsInstance(g.valid_reason, str)
  1256. self.assertTrue(
  1257. g.valid_reason.startswith("Too few points in geometry component")
  1258. )
  1259. def test_linearref(self):
  1260. "Testing linear referencing"
  1261. ls = fromstr("LINESTRING(0 0, 0 10, 10 10, 10 0)")
  1262. mls = fromstr("MULTILINESTRING((0 0, 0 10), (10 0, 10 10))")
  1263. self.assertEqual(ls.project(Point(0, 20)), 10.0)
  1264. self.assertEqual(ls.project(Point(7, 6)), 24)
  1265. self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3)
  1266. self.assertEqual(ls.interpolate(10), Point(0, 10))
  1267. self.assertEqual(ls.interpolate(24), Point(10, 6))
  1268. self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10))
  1269. self.assertEqual(mls.project(Point(0, 20)), 10)
  1270. self.assertEqual(mls.project(Point(7, 6)), 16)
  1271. self.assertEqual(mls.interpolate(9), Point(0, 9))
  1272. self.assertEqual(mls.interpolate(17), Point(10, 7))
  1273. def test_deconstructible(self):
  1274. """
  1275. Geometry classes should be deconstructible.
  1276. """
  1277. point = Point(4.337844, 50.827537, srid=4326)
  1278. path, args, kwargs = point.deconstruct()
  1279. self.assertEqual(path, "django.contrib.gis.geos.point.Point")
  1280. self.assertEqual(args, (4.337844, 50.827537))
  1281. self.assertEqual(kwargs, {"srid": 4326})
  1282. ls = LineString(((0, 0), (1, 1)))
  1283. path, args, kwargs = ls.deconstruct()
  1284. self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString")
  1285. self.assertEqual(args, (((0, 0), (1, 1)),))
  1286. self.assertEqual(kwargs, {})
  1287. ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326)
  1288. path, args, kwargs = ls2.deconstruct()
  1289. self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString")
  1290. self.assertEqual(args, ([Point(0, 0), Point(1, 1)],))
  1291. self.assertEqual(kwargs, {"srid": 4326})
  1292. ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
  1293. int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))
  1294. poly = Polygon(ext_coords, int_coords)
  1295. path, args, kwargs = poly.deconstruct()
  1296. self.assertEqual(path, "django.contrib.gis.geos.polygon.Polygon")
  1297. self.assertEqual(args, (ext_coords, int_coords))
  1298. self.assertEqual(kwargs, {})
  1299. lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))
  1300. path, args, kwargs = lr.deconstruct()
  1301. self.assertEqual(path, "django.contrib.gis.geos.linestring.LinearRing")
  1302. self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0)))
  1303. self.assertEqual(kwargs, {})
  1304. mp = MultiPoint(Point(0, 0), Point(1, 1))
  1305. path, args, kwargs = mp.deconstruct()
  1306. self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPoint")
  1307. self.assertEqual(args, (Point(0, 0), Point(1, 1)))
  1308. self.assertEqual(kwargs, {})
  1309. ls1 = LineString((0, 0), (1, 1))
  1310. ls2 = LineString((2, 2), (3, 3))
  1311. mls = MultiLineString(ls1, ls2)
  1312. path, args, kwargs = mls.deconstruct()
  1313. self.assertEqual(path, "django.contrib.gis.geos.collections.MultiLineString")
  1314. self.assertEqual(args, (ls1, ls2))
  1315. self.assertEqual(kwargs, {})
  1316. p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0)))
  1317. p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1)))
  1318. mp = MultiPolygon(p1, p2)
  1319. path, args, kwargs = mp.deconstruct()
  1320. self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPolygon")
  1321. self.assertEqual(args, (p1, p2))
  1322. self.assertEqual(kwargs, {})
  1323. poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0)))
  1324. gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
  1325. path, args, kwargs = gc.deconstruct()
  1326. self.assertEqual(path, "django.contrib.gis.geos.collections.GeometryCollection")
  1327. self.assertEqual(
  1328. args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
  1329. )
  1330. self.assertEqual(kwargs, {})
  1331. def test_subclassing(self):
  1332. """
  1333. GEOSGeometry subclass may itself be subclassed without being forced-cast
  1334. to the parent class during `__init__`.
  1335. """
  1336. class ExtendedPolygon(Polygon):
  1337. def __init__(self, *args, data=0, **kwargs):
  1338. super().__init__(*args, **kwargs)
  1339. self._data = data
  1340. def __str__(self):
  1341. return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt)
  1342. ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3)
  1343. self.assertEqual(type(ext_poly), ExtendedPolygon)
  1344. # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__).
  1345. self.assertEqual(
  1346. str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))"
  1347. )
  1348. self.assertJSONEqual(
  1349. ext_poly.json,
  1350. '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}',
  1351. )
  1352. def test_geos_version_tuple(self):
  1353. versions = (
  1354. (b"3.0.0rc4-CAPI-1.3.3", (3, 0, 0)),
  1355. (b"3.0.0-CAPI-1.4.1", (3, 0, 0)),
  1356. (b"3.4.0dev-CAPI-1.8.0", (3, 4, 0)),
  1357. (b"3.4.0dev-CAPI-1.8.0 r0", (3, 4, 0)),
  1358. (b"3.6.2-CAPI-1.10.2 4d2925d6", (3, 6, 2)),
  1359. )
  1360. for version_string, version_tuple in versions:
  1361. with self.subTest(version_string=version_string):
  1362. with mock.patch(
  1363. "django.contrib.gis.geos.libgeos.geos_version",
  1364. lambda: version_string,
  1365. ):
  1366. self.assertEqual(geos_version_tuple(), version_tuple)
  1367. def test_from_gml(self):
  1368. self.assertEqual(
  1369. GEOSGeometry("POINT(0 0)"),
  1370. GEOSGeometry.from_gml(
  1371. '<gml:Point gml:id="p21" '
  1372. 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
  1373. ' <gml:pos srsDimension="2">0 0</gml:pos>'
  1374. "</gml:Point>"
  1375. ),
  1376. )
  1377. def test_from_ewkt(self):
  1378. self.assertEqual(
  1379. GEOSGeometry.from_ewkt("SRID=1;POINT(1 1)"), Point(1, 1, srid=1)
  1380. )
  1381. self.assertEqual(GEOSGeometry.from_ewkt("POINT(1 1)"), Point(1, 1))
  1382. def test_from_ewkt_empty_string(self):
  1383. msg = "Expected WKT but got an empty string."
  1384. with self.assertRaisesMessage(ValueError, msg):
  1385. GEOSGeometry.from_ewkt("")
  1386. with self.assertRaisesMessage(ValueError, msg):
  1387. GEOSGeometry.from_ewkt("SRID=1;")
  1388. def test_from_ewkt_invalid_srid(self):
  1389. msg = "EWKT has invalid SRID part."
  1390. with self.assertRaisesMessage(ValueError, msg):
  1391. GEOSGeometry.from_ewkt("SRUD=1;POINT(1 1)")
  1392. with self.assertRaisesMessage(ValueError, msg):
  1393. GEOSGeometry.from_ewkt("SRID=WGS84;POINT(1 1)")
  1394. def test_fromstr_scientific_wkt(self):
  1395. self.assertEqual(GEOSGeometry("POINT(1.0e-1 1.0e+1)"), Point(0.1, 10))
  1396. def test_normalize(self):
  1397. multipoint = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1))
  1398. normalized = MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0))
  1399. # Geometry is normalized in-place and nothing is returned.
  1400. multipoint_1 = multipoint.clone()
  1401. self.assertIsNone(multipoint_1.normalize())
  1402. self.assertEqual(multipoint_1, normalized)
  1403. # If the `clone` keyword is set, then the geometry is not modified and
  1404. # a normalized clone of the geometry is returned instead.
  1405. multipoint_2 = multipoint.normalize(clone=True)
  1406. self.assertEqual(multipoint_2, normalized)
  1407. self.assertNotEqual(multipoint, normalized)
  1408. def test_make_valid(self):
  1409. poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))")
  1410. self.assertIs(poly.valid, False)
  1411. valid_poly = poly.make_valid()
  1412. self.assertIs(valid_poly.valid, True)
  1413. self.assertNotEqual(valid_poly, poly)
  1414. valid_poly2 = valid_poly.make_valid()
  1415. self.assertIs(valid_poly2.valid, True)
  1416. self.assertEqual(valid_poly, valid_poly2)
  1417. def test_empty_point(self):
  1418. p = Point(srid=4326)
  1419. self.assertEqual(p.ogr.ewkt, p.ewkt)
  1420. self.assertEqual(p.transform(2774, clone=True), Point(srid=2774))
  1421. p.transform(2774)
  1422. self.assertEqual(p, Point(srid=2774))
  1423. def test_linestring_iter(self):
  1424. ls = LineString((0, 0), (1, 1))
  1425. it = iter(ls)
  1426. # Step into CoordSeq iterator.
  1427. next(it)
  1428. ls[:] = []
  1429. with self.assertRaises(IndexError):
  1430. next(it)