test_geos.py 57 KB

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