test_geos.py 55 KB

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