test_geos.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. from __future__ import unicode_literals
  2. import ctypes
  3. import json
  4. import random
  5. import unittest
  6. from binascii import a2b_hex, b2a_hex
  7. from io import BytesIO
  8. from unittest import skipUnless
  9. from django.contrib.gis.gdal import HAS_GDAL
  10. from django.contrib.gis.geos import HAS_GEOS
  11. from django.contrib.gis.shortcuts import numpy
  12. from django.utils import six
  13. from django.utils.encoding import force_bytes
  14. from django.utils.six.moves import range
  15. from ..test_data import TestDataMixin
  16. if HAS_GEOS:
  17. from django.contrib.gis.geos import (
  18. GEOSException, GEOSIndexError, GEOSGeometry, GeometryCollection, Point,
  19. MultiPoint, Polygon, MultiPolygon, LinearRing, LineString,
  20. MultiLineString, fromfile, fromstr, geos_version_info,
  21. )
  22. from django.contrib.gis.geos.base import gdal, GEOSBase
  23. @skipUnless(HAS_GEOS, "Geos is required.")
  24. class GEOSTest(unittest.TestCase, TestDataMixin):
  25. def test_base(self):
  26. "Tests out the GEOSBase class."
  27. # Testing out GEOSBase class, which provides a `ptr` property
  28. # that abstracts out access to underlying C pointers.
  29. class FakeGeom1(GEOSBase):
  30. pass
  31. # This one only accepts pointers to floats
  32. c_float_p = ctypes.POINTER(ctypes.c_float)
  33. class FakeGeom2(GEOSBase):
  34. ptr_type = c_float_p
  35. # Default ptr_type is `c_void_p`.
  36. fg1 = FakeGeom1()
  37. # Default ptr_type is C float pointer
  38. fg2 = FakeGeom2()
  39. # These assignments are OK -- None is allowed because
  40. # it's equivalent to the NULL pointer.
  41. fg1.ptr = ctypes.c_void_p()
  42. fg1.ptr = None
  43. fg2.ptr = c_float_p(ctypes.c_float(5.23))
  44. fg2.ptr = None
  45. # Because pointers have been set to NULL, an exception should be
  46. # raised when we try to access it. Raising an exception is
  47. # preferable to a segmentation fault that commonly occurs when
  48. # a C method is given a NULL memory reference.
  49. for fg in (fg1, fg2):
  50. # Equivalent to `fg.ptr`
  51. self.assertRaises(GEOSException, fg._get_ptr)
  52. # Anything that is either not None or the acceptable pointer type will
  53. # result in a TypeError when trying to assign it to the `ptr` property.
  54. # Thus, memory addresses (integers) and pointers of the incorrect type
  55. # (in `bad_ptrs`) will not be allowed.
  56. bad_ptrs = (5, ctypes.c_char_p(b'foobar'))
  57. for bad_ptr in bad_ptrs:
  58. # Equivalent to `fg.ptr = bad_ptr`
  59. self.assertRaises(TypeError, fg1._set_ptr, bad_ptr)
  60. self.assertRaises(TypeError, fg2._set_ptr, bad_ptr)
  61. def test_wkt(self):
  62. "Testing WKT output."
  63. for g in self.geometries.wkt_out:
  64. geom = fromstr(g.wkt)
  65. if geom.hasz and geos_version_info()['version'] >= '3.3.0':
  66. self.assertEqual(g.ewkt, geom.wkt)
  67. def test_hex(self):
  68. "Testing HEX output."
  69. for g in self.geometries.hex_wkt:
  70. geom = fromstr(g.wkt)
  71. self.assertEqual(g.hex, geom.hex.decode())
  72. def test_hexewkb(self):
  73. "Testing (HEX)EWKB output."
  74. # For testing HEX(EWKB).
  75. ogc_hex = b'01010000000000000000000000000000000000F03F'
  76. ogc_hex_3d = b'01010000800000000000000000000000000000F03F0000000000000040'
  77. # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`
  78. hexewkb_2d = b'0101000020E61000000000000000000000000000000000F03F'
  79. # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`
  80. hexewkb_3d = b'01010000A0E61000000000000000000000000000000000F03F0000000000000040'
  81. pnt_2d = Point(0, 1, srid=4326)
  82. pnt_3d = Point(0, 1, 2, srid=4326)
  83. # OGC-compliant HEX will not have SRID value.
  84. self.assertEqual(ogc_hex, pnt_2d.hex)
  85. self.assertEqual(ogc_hex_3d, pnt_3d.hex)
  86. # HEXEWKB should be appropriate for its dimension -- have to use an
  87. # a WKBWriter w/dimension set accordingly, else GEOS will insert
  88. # garbage into 3D coordinate if there is none.
  89. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
  90. self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
  91. self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz)
  92. # Same for EWKB.
  93. self.assertEqual(six.memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
  94. self.assertEqual(six.memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
  95. # Redundant sanity check.
  96. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
  97. def test_kml(self):
  98. "Testing KML output."
  99. for tg in self.geometries.wkt_out:
  100. geom = fromstr(tg.wkt)
  101. kml = getattr(tg, 'kml', False)
  102. if kml:
  103. self.assertEqual(kml, geom.kml)
  104. def test_errors(self):
  105. "Testing the Error handlers."
  106. # string-based
  107. for err in self.geometries.errors:
  108. with self.assertRaises((GEOSException, ValueError)):
  109. fromstr(err.wkt)
  110. # Bad WKB
  111. self.assertRaises(GEOSException, GEOSGeometry, six.memoryview(b'0'))
  112. class NotAGeometry(object):
  113. pass
  114. # Some other object
  115. self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
  116. # None
  117. self.assertRaises(TypeError, GEOSGeometry, None)
  118. def test_wkb(self):
  119. "Testing WKB output."
  120. for g in self.geometries.hex_wkt:
  121. geom = fromstr(g.wkt)
  122. wkb = geom.wkb
  123. self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex)
  124. def test_create_hex(self):
  125. "Testing creation from HEX."
  126. for g in self.geometries.hex_wkt:
  127. geom_h = GEOSGeometry(g.hex)
  128. # we need to do this so decimal places get normalized
  129. geom_t = fromstr(g.wkt)
  130. self.assertEqual(geom_t.wkt, geom_h.wkt)
  131. def test_create_wkb(self):
  132. "Testing creation from WKB."
  133. for g in self.geometries.hex_wkt:
  134. wkb = six.memoryview(a2b_hex(g.hex.encode()))
  135. geom_h = GEOSGeometry(wkb)
  136. # we need to do this so decimal places get normalized
  137. geom_t = fromstr(g.wkt)
  138. self.assertEqual(geom_t.wkt, geom_h.wkt)
  139. def test_ewkt(self):
  140. "Testing EWKT."
  141. srids = (-1, 32140)
  142. for srid in srids:
  143. for p in self.geometries.polygons:
  144. ewkt = 'SRID=%d;%s' % (srid, p.wkt)
  145. poly = fromstr(ewkt)
  146. self.assertEqual(srid, poly.srid)
  147. self.assertEqual(srid, poly.shell.srid)
  148. self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
  149. @skipUnless(HAS_GDAL, "GDAL is required.")
  150. def test_json(self):
  151. "Testing GeoJSON input/output (via GDAL)."
  152. for g in self.geometries.json_geoms:
  153. geom = GEOSGeometry(g.wkt)
  154. if not hasattr(g, 'not_equal'):
  155. # Loading jsons to prevent decimal differences
  156. self.assertEqual(json.loads(g.json), json.loads(geom.json))
  157. self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
  158. self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))
  159. def test_fromfile(self):
  160. "Testing the fromfile() factory."
  161. ref_pnt = GEOSGeometry('POINT(5 23)')
  162. wkt_f = BytesIO()
  163. wkt_f.write(force_bytes(ref_pnt.wkt))
  164. wkb_f = BytesIO()
  165. wkb_f.write(bytes(ref_pnt.wkb))
  166. # Other tests use `fromfile()` on string filenames so those
  167. # aren't tested here.
  168. for fh in (wkt_f, wkb_f):
  169. fh.seek(0)
  170. pnt = fromfile(fh)
  171. self.assertEqual(ref_pnt, pnt)
  172. def test_eq(self):
  173. "Testing equivalence."
  174. p = fromstr('POINT(5 23)')
  175. self.assertEqual(p, p.wkt)
  176. self.assertNotEqual(p, 'foo')
  177. ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')
  178. self.assertEqual(ls, ls.wkt)
  179. self.assertNotEqual(p, 'bar')
  180. # Error shouldn't be raise on equivalence testing with
  181. # an invalid type.
  182. for g in (p, ls):
  183. self.assertNotEqual(g, None)
  184. self.assertNotEqual(g, {'foo': 'bar'})
  185. self.assertNotEqual(g, False)
  186. def test_points(self):
  187. "Testing Point objects."
  188. prev = fromstr('POINT(0 0)')
  189. for p in self.geometries.points:
  190. # Creating the point from the WKT
  191. pnt = fromstr(p.wkt)
  192. self.assertEqual(pnt.geom_type, 'Point')
  193. self.assertEqual(pnt.geom_typeid, 0)
  194. self.assertEqual(p.x, pnt.x)
  195. self.assertEqual(p.y, pnt.y)
  196. self.assertEqual(True, pnt == fromstr(p.wkt))
  197. self.assertEqual(False, pnt == prev)
  198. # Making sure that the point's X, Y components are what we expect
  199. self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
  200. self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
  201. # Testing the third dimension, and getting the tuple arguments
  202. if hasattr(p, 'z'):
  203. self.assertEqual(True, pnt.hasz)
  204. self.assertEqual(p.z, pnt.z)
  205. self.assertEqual(p.z, pnt.tuple[2], 9)
  206. tup_args = (p.x, p.y, p.z)
  207. set_tup1 = (2.71, 3.14, 5.23)
  208. set_tup2 = (5.23, 2.71, 3.14)
  209. else:
  210. self.assertEqual(False, pnt.hasz)
  211. self.assertEqual(None, pnt.z)
  212. tup_args = (p.x, p.y)
  213. set_tup1 = (2.71, 3.14)
  214. set_tup2 = (3.14, 2.71)
  215. # Centroid operation on point should be point itself
  216. self.assertEqual(p.centroid, pnt.centroid.tuple)
  217. # Now testing the different constructors
  218. pnt2 = Point(tup_args) # e.g., Point((1, 2))
  219. pnt3 = Point(*tup_args) # e.g., Point(1, 2)
  220. self.assertEqual(True, pnt == pnt2)
  221. self.assertEqual(True, pnt == pnt3)
  222. # Now testing setting the x and y
  223. pnt.y = 3.14
  224. pnt.x = 2.71
  225. self.assertEqual(3.14, pnt.y)
  226. self.assertEqual(2.71, pnt.x)
  227. # Setting via the tuple/coords property
  228. pnt.tuple = set_tup1
  229. self.assertEqual(set_tup1, pnt.tuple)
  230. pnt.coords = set_tup2
  231. self.assertEqual(set_tup2, pnt.coords)
  232. prev = pnt # setting the previous geometry
  233. def test_multipoints(self):
  234. "Testing MultiPoint objects."
  235. for mp in self.geometries.multipoints:
  236. mpnt = fromstr(mp.wkt)
  237. self.assertEqual(mpnt.geom_type, 'MultiPoint')
  238. self.assertEqual(mpnt.geom_typeid, 4)
  239. self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
  240. self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
  241. self.assertRaises(GEOSIndexError, mpnt.__getitem__, len(mpnt))
  242. self.assertEqual(mp.centroid, mpnt.centroid.tuple)
  243. self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))
  244. for p in mpnt:
  245. self.assertEqual(p.geom_type, 'Point')
  246. self.assertEqual(p.geom_typeid, 0)
  247. self.assertEqual(p.empty, False)
  248. self.assertEqual(p.valid, True)
  249. def test_linestring(self):
  250. "Testing LineString objects."
  251. prev = fromstr('POINT(0 0)')
  252. for l in self.geometries.linestrings:
  253. ls = fromstr(l.wkt)
  254. self.assertEqual(ls.geom_type, 'LineString')
  255. self.assertEqual(ls.geom_typeid, 1)
  256. self.assertEqual(ls.empty, False)
  257. self.assertEqual(ls.ring, False)
  258. if hasattr(l, 'centroid'):
  259. self.assertEqual(l.centroid, ls.centroid.tuple)
  260. if hasattr(l, 'tup'):
  261. self.assertEqual(l.tup, ls.tuple)
  262. self.assertEqual(True, ls == fromstr(l.wkt))
  263. self.assertEqual(False, ls == prev)
  264. self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
  265. prev = ls
  266. # Creating a LineString from a tuple, list, and numpy array
  267. self.assertEqual(ls, LineString(ls.tuple)) # tuple
  268. self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
  269. self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
  270. # Point individual arguments
  271. self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt)
  272. if numpy:
  273. self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
  274. def test_multilinestring(self):
  275. "Testing MultiLineString objects."
  276. prev = fromstr('POINT(0 0)')
  277. for l in self.geometries.multilinestrings:
  278. ml = fromstr(l.wkt)
  279. self.assertEqual(ml.geom_type, 'MultiLineString')
  280. self.assertEqual(ml.geom_typeid, 5)
  281. self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
  282. self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
  283. self.assertEqual(True, ml == fromstr(l.wkt))
  284. self.assertEqual(False, ml == prev)
  285. prev = ml
  286. for ls in ml:
  287. self.assertEqual(ls.geom_type, 'LineString')
  288. self.assertEqual(ls.geom_typeid, 1)
  289. self.assertEqual(ls.empty, False)
  290. self.assertRaises(GEOSIndexError, ml.__getitem__, len(ml))
  291. self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
  292. self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))
  293. def test_linearring(self):
  294. "Testing LinearRing objects."
  295. for rr in self.geometries.linearrings:
  296. lr = fromstr(rr.wkt)
  297. self.assertEqual(lr.geom_type, 'LinearRing')
  298. self.assertEqual(lr.geom_typeid, 2)
  299. self.assertEqual(rr.n_p, len(lr))
  300. self.assertEqual(True, lr.valid)
  301. self.assertEqual(False, lr.empty)
  302. # Creating a LinearRing from a tuple, list, and numpy array
  303. self.assertEqual(lr, LinearRing(lr.tuple))
  304. self.assertEqual(lr, LinearRing(*lr.tuple))
  305. self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
  306. if numpy:
  307. self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
  308. def test_polygons_from_bbox(self):
  309. "Testing `from_bbox` class method."
  310. bbox = (-180, -90, 180, 90)
  311. p = Polygon.from_bbox(bbox)
  312. self.assertEqual(bbox, p.extent)
  313. # Testing numerical precision
  314. x = 3.14159265358979323
  315. bbox = (0, 0, 1, x)
  316. p = Polygon.from_bbox(bbox)
  317. y = p.extent[-1]
  318. self.assertEqual(format(x, '.13f'), format(y, '.13f'))
  319. def test_polygons(self):
  320. "Testing Polygon objects."
  321. prev = fromstr('POINT(0 0)')
  322. for p in self.geometries.polygons:
  323. # Creating the Polygon, testing its properties.
  324. poly = fromstr(p.wkt)
  325. self.assertEqual(poly.geom_type, 'Polygon')
  326. self.assertEqual(poly.geom_typeid, 3)
  327. self.assertEqual(poly.empty, False)
  328. self.assertEqual(poly.ring, False)
  329. self.assertEqual(p.n_i, poly.num_interior_rings)
  330. self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
  331. self.assertEqual(p.n_p, poly.num_points)
  332. # Area & Centroid
  333. self.assertAlmostEqual(p.area, poly.area, 9)
  334. self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
  335. self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)
  336. # Testing the geometry equivalence
  337. self.assertEqual(True, poly == fromstr(p.wkt))
  338. self.assertEqual(False, poly == prev) # Should not be equal to previous geometry
  339. self.assertEqual(True, poly != prev)
  340. # Testing the exterior ring
  341. ring = poly.exterior_ring
  342. self.assertEqual(ring.geom_type, 'LinearRing')
  343. self.assertEqual(ring.geom_typeid, 2)
  344. if p.ext_ring_cs:
  345. self.assertEqual(p.ext_ring_cs, ring.tuple)
  346. self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
  347. # Testing __getitem__ and __setitem__ on invalid indices
  348. self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly))
  349. self.assertRaises(GEOSIndexError, poly.__setitem__, len(poly), False)
  350. self.assertRaises(GEOSIndexError, poly.__getitem__, -1 * len(poly) - 1)
  351. # Testing __iter__
  352. for r in poly:
  353. self.assertEqual(r.geom_type, 'LinearRing')
  354. self.assertEqual(r.geom_typeid, 2)
  355. # Testing polygon construction.
  356. self.assertRaises(TypeError, Polygon, 0, [1, 2, 3])
  357. self.assertRaises(TypeError, Polygon, 'foo')
  358. # Polygon(shell, (hole1, ... holeN))
  359. rings = tuple(r for r in poly)
  360. self.assertEqual(poly, Polygon(rings[0], rings[1:]))
  361. # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
  362. ring_tuples = tuple(r.tuple for r in poly)
  363. self.assertEqual(poly, Polygon(*ring_tuples))
  364. # Constructing with tuples of LinearRings.
  365. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
  366. self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)
  367. def test_polygon_comparison(self):
  368. p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  369. p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
  370. self.assertGreater(p1, p2)
  371. self.assertLess(p2, p1)
  372. p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
  373. p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
  374. self.assertGreater(p4, p3)
  375. self.assertLess(p3, p4)
  376. def test_multipolygons(self):
  377. "Testing MultiPolygon objects."
  378. fromstr('POINT (0 0)')
  379. for mp in self.geometries.multipolygons:
  380. mpoly = fromstr(mp.wkt)
  381. self.assertEqual(mpoly.geom_type, 'MultiPolygon')
  382. self.assertEqual(mpoly.geom_typeid, 6)
  383. self.assertEqual(mp.valid, mpoly.valid)
  384. if mp.valid:
  385. self.assertEqual(mp.num_geom, mpoly.num_geom)
  386. self.assertEqual(mp.n_p, mpoly.num_coords)
  387. self.assertEqual(mp.num_geom, len(mpoly))
  388. self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
  389. for p in mpoly:
  390. self.assertEqual(p.geom_type, 'Polygon')
  391. self.assertEqual(p.geom_typeid, 3)
  392. self.assertEqual(p.valid, True)
  393. self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
  394. def test_memory_hijinks(self):
  395. "Testing Geometry __del__() on rings and polygons."
  396. # #### Memory issues with rings and poly
  397. # These tests are needed to ensure sanity with writable geometries.
  398. # Getting a polygon with interior rings, and pulling out the interior rings
  399. poly = fromstr(self.geometries.polygons[1].wkt)
  400. ring1 = poly[0]
  401. ring2 = poly[1]
  402. # These deletes should be 'harmless' since they are done on child geometries
  403. del ring1
  404. del ring2
  405. ring1 = poly[0]
  406. ring2 = poly[1]
  407. # Deleting the polygon
  408. del poly
  409. # Access to these rings is OK since they are clones.
  410. str(ring1)
  411. str(ring2)
  412. def test_coord_seq(self):
  413. "Testing Coordinate Sequence objects."
  414. for p in self.geometries.polygons:
  415. if p.ext_ring_cs:
  416. # Constructing the polygon and getting the coordinate sequence
  417. poly = fromstr(p.wkt)
  418. cs = poly.exterior_ring.coord_seq
  419. self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
  420. self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works
  421. # Checks __getitem__ and __setitem__
  422. for i in range(len(p.ext_ring_cs)):
  423. c1 = p.ext_ring_cs[i] # Expected value
  424. c2 = cs[i] # Value from coordseq
  425. self.assertEqual(c1, c2)
  426. # Constructing the test value to set the coordinate sequence with
  427. if len(c1) == 2:
  428. tset = (5, 23)
  429. else:
  430. tset = (5, 23, 8)
  431. cs[i] = tset
  432. # Making sure every set point matches what we expect
  433. for j in range(len(tset)):
  434. cs[i] = tset
  435. self.assertEqual(tset[j], cs[i][j])
  436. def test_relate_pattern(self):
  437. "Testing relate() and relate_pattern()."
  438. g = fromstr('POINT (0 0)')
  439. self.assertRaises(GEOSException, g.relate_pattern, 0, 'invalid pattern, yo')
  440. for rg in self.geometries.relate_geoms:
  441. a = fromstr(rg.wkt_a)
  442. b = fromstr(rg.wkt_b)
  443. self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern))
  444. self.assertEqual(rg.pattern, a.relate(b))
  445. def test_intersection(self):
  446. "Testing intersects() and intersection()."
  447. for i in range(len(self.geometries.topology_geoms)):
  448. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  449. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  450. i1 = fromstr(self.geometries.intersect_geoms[i].wkt)
  451. self.assertEqual(True, a.intersects(b))
  452. i2 = a.intersection(b)
  453. self.assertEqual(i1, i2)
  454. self.assertEqual(i1, a & b) # __and__ is intersection operator
  455. a &= b # testing __iand__
  456. self.assertEqual(i1, a)
  457. def test_union(self):
  458. "Testing union()."
  459. for i in range(len(self.geometries.topology_geoms)):
  460. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  461. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  462. u1 = fromstr(self.geometries.union_geoms[i].wkt)
  463. u2 = a.union(b)
  464. self.assertEqual(u1, u2)
  465. self.assertEqual(u1, a | b) # __or__ is union operator
  466. a |= b # testing __ior__
  467. self.assertEqual(u1, a)
  468. def test_difference(self):
  469. "Testing difference()."
  470. for i in range(len(self.geometries.topology_geoms)):
  471. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  472. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  473. d1 = fromstr(self.geometries.diff_geoms[i].wkt)
  474. d2 = a.difference(b)
  475. self.assertEqual(d1, d2)
  476. self.assertEqual(d1, a - b) # __sub__ is difference operator
  477. a -= b # testing __isub__
  478. self.assertEqual(d1, a)
  479. def test_symdifference(self):
  480. "Testing sym_difference()."
  481. for i in range(len(self.geometries.topology_geoms)):
  482. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  483. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  484. d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)
  485. d2 = a.sym_difference(b)
  486. self.assertEqual(d1, d2)
  487. self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
  488. a ^= b # testing __ixor__
  489. self.assertEqual(d1, a)
  490. def test_buffer(self):
  491. "Testing buffer()."
  492. for bg in self.geometries.buffer_geoms:
  493. g = fromstr(bg.wkt)
  494. # The buffer we expect
  495. exp_buf = fromstr(bg.buffer_wkt)
  496. quadsegs = bg.quadsegs
  497. width = bg.width
  498. # Can't use a floating-point for the number of quadsegs.
  499. self.assertRaises(ctypes.ArgumentError, g.buffer, width, float(quadsegs))
  500. # Constructing our buffer
  501. buf = g.buffer(width, quadsegs)
  502. self.assertEqual(exp_buf.num_coords, buf.num_coords)
  503. self.assertEqual(len(exp_buf), len(buf))
  504. # Now assuring that each point in the buffer is almost equal
  505. for j in range(len(exp_buf)):
  506. exp_ring = exp_buf[j]
  507. buf_ring = buf[j]
  508. self.assertEqual(len(exp_ring), len(buf_ring))
  509. for k in range(len(exp_ring)):
  510. # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
  511. self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
  512. self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
  513. def test_srid(self):
  514. "Testing the SRID property and keyword."
  515. # Testing SRID keyword on Point
  516. pnt = Point(5, 23, srid=4326)
  517. self.assertEqual(4326, pnt.srid)
  518. pnt.srid = 3084
  519. self.assertEqual(3084, pnt.srid)
  520. self.assertRaises(ctypes.ArgumentError, pnt.set_srid, '4326')
  521. # Testing SRID keyword on fromstr(), and on Polygon rings.
  522. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269)
  523. self.assertEqual(4269, poly.srid)
  524. for ring in poly:
  525. self.assertEqual(4269, ring.srid)
  526. poly.srid = 4326
  527. self.assertEqual(4326, poly.shell.srid)
  528. # Testing SRID keyword on GeometryCollection
  529. gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)
  530. self.assertEqual(32021, gc.srid)
  531. for i in range(len(gc)):
  532. self.assertEqual(32021, gc[i].srid)
  533. # GEOS may get the SRID from HEXEWKB
  534. # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
  535. # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
  536. hex = '0101000020E610000000000000000014400000000000003740'
  537. p1 = fromstr(hex)
  538. self.assertEqual(4326, p1.srid)
  539. p2 = fromstr(p1.hex)
  540. self.assertIsNone(p2.srid)
  541. p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
  542. self.assertEqual(-1, p3.srid)
  543. @skipUnless(HAS_GDAL, "GDAL is required.")
  544. def test_custom_srid(self):
  545. """ Test with a srid unknown from GDAL """
  546. pnt = Point(111200, 220900, srid=999999)
  547. self.assertTrue(pnt.ewkt.startswith("SRID=999999;POINT (111200.0"))
  548. self.assertIsInstance(pnt.ogr, gdal.OGRGeometry)
  549. self.assertIsNone(pnt.srs)
  550. # Test conversion from custom to a known srid
  551. c2w = gdal.CoordTransform(
  552. gdal.SpatialReference(
  553. '+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 '
  554. '+datum=WGS84 +units=m +no_defs'
  555. ),
  556. gdal.SpatialReference(4326))
  557. new_pnt = pnt.transform(c2w, clone=True)
  558. self.assertEqual(new_pnt.srid, 4326)
  559. self.assertAlmostEqual(new_pnt.x, 1, 3)
  560. self.assertAlmostEqual(new_pnt.y, 2, 3)
  561. def test_mutable_geometries(self):
  562. "Testing the mutability of Polygons and Geometry Collections."
  563. # ### Testing the mutability of Polygons ###
  564. for p in self.geometries.polygons:
  565. poly = fromstr(p.wkt)
  566. # Should only be able to use __setitem__ with LinearRing geometries.
  567. self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
  568. # Constructing the new shell by adding 500 to every point in the old shell.
  569. shell_tup = poly.shell.tuple
  570. new_coords = []
  571. for point in shell_tup:
  572. new_coords.append((point[0] + 500., point[1] + 500.))
  573. new_shell = LinearRing(*tuple(new_coords))
  574. # Assigning polygon's exterior ring w/the new shell
  575. poly.exterior_ring = new_shell
  576. str(new_shell) # new shell is still accessible
  577. self.assertEqual(poly.exterior_ring, new_shell)
  578. self.assertEqual(poly[0], new_shell)
  579. # ### Testing the mutability of Geometry Collections
  580. for tg in self.geometries.multipoints:
  581. mp = fromstr(tg.wkt)
  582. for i in range(len(mp)):
  583. # Creating a random point.
  584. pnt = mp[i]
  585. new = Point(random.randint(21, 100), random.randint(21, 100))
  586. # Testing the assignment
  587. mp[i] = new
  588. str(new) # what was used for the assignment is still accessible
  589. self.assertEqual(mp[i], new)
  590. self.assertEqual(mp[i].wkt, new.wkt)
  591. self.assertNotEqual(pnt, mp[i])
  592. # MultiPolygons involve much more memory management because each
  593. # Polygon w/in the collection has its own rings.
  594. for tg in self.geometries.multipolygons:
  595. mpoly = fromstr(tg.wkt)
  596. for i in range(len(mpoly)):
  597. poly = mpoly[i]
  598. old_poly = mpoly[i]
  599. # Offsetting the each ring in the polygon by 500.
  600. for j in range(len(poly)):
  601. r = poly[j]
  602. for k in range(len(r)):
  603. r[k] = (r[k][0] + 500., r[k][1] + 500.)
  604. poly[j] = r
  605. self.assertNotEqual(mpoly[i], poly)
  606. # Testing the assignment
  607. mpoly[i] = poly
  608. str(poly) # Still accessible
  609. self.assertEqual(mpoly[i], poly)
  610. self.assertNotEqual(mpoly[i], old_poly)
  611. # Extreme (!!) __setitem__ -- no longer works, have to detect
  612. # in the first object that __setitem__ is called in the subsequent
  613. # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?
  614. # mpoly[0][0][0] = (3.14, 2.71)
  615. # self.assertEqual((3.14, 2.71), mpoly[0][0][0])
  616. # Doing it more slowly..
  617. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0])
  618. # del mpoly
  619. def test_threed(self):
  620. "Testing three-dimensional geometries."
  621. # Testing a 3D Point
  622. pnt = Point(2, 3, 8)
  623. self.assertEqual((2., 3., 8.), pnt.coords)
  624. self.assertRaises(TypeError, pnt.set_coords, (1., 2.))
  625. pnt.coords = (1., 2., 3.)
  626. self.assertEqual((1., 2., 3.), pnt.coords)
  627. # Testing a 3D LineString
  628. ls = LineString((2., 3., 8.), (50., 250., -117.))
  629. self.assertEqual(((2., 3., 8.), (50., 250., -117.)), ls.tuple)
  630. self.assertRaises(TypeError, ls.__setitem__, 0, (1., 2.))
  631. ls[0] = (1., 2., 3.)
  632. self.assertEqual((1., 2., 3.), ls[0])
  633. def test_distance(self):
  634. "Testing the distance() function."
  635. # Distance to self should be 0.
  636. pnt = Point(0, 0)
  637. self.assertEqual(0.0, pnt.distance(Point(0, 0)))
  638. # Distance should be 1
  639. self.assertEqual(1.0, pnt.distance(Point(0, 1)))
  640. # Distance should be ~ sqrt(2)
  641. self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
  642. # Distances are from the closest vertex in each geometry --
  643. # should be 3 (distance from (2, 2) to (5, 2)).
  644. ls1 = LineString((0, 0), (1, 1), (2, 2))
  645. ls2 = LineString((5, 2), (6, 1), (7, 0))
  646. self.assertEqual(3, ls1.distance(ls2))
  647. def test_length(self):
  648. "Testing the length property."
  649. # Points have 0 length.
  650. pnt = Point(0, 0)
  651. self.assertEqual(0.0, pnt.length)
  652. # Should be ~ sqrt(2)
  653. ls = LineString((0, 0), (1, 1))
  654. self.assertAlmostEqual(1.41421356237, ls.length, 11)
  655. # Should be circumference of Polygon
  656. poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  657. self.assertEqual(4.0, poly.length)
  658. # Should be sum of each element's length in collection.
  659. mpoly = MultiPolygon(poly.clone(), poly)
  660. self.assertEqual(8.0, mpoly.length)
  661. def test_emptyCollections(self):
  662. "Testing empty geometries and collections."
  663. gc1 = GeometryCollection([])
  664. gc2 = fromstr('GEOMETRYCOLLECTION EMPTY')
  665. pnt = fromstr('POINT EMPTY')
  666. ls = fromstr('LINESTRING EMPTY')
  667. poly = fromstr('POLYGON EMPTY')
  668. mls = fromstr('MULTILINESTRING EMPTY')
  669. mpoly1 = fromstr('MULTIPOLYGON EMPTY')
  670. mpoly2 = MultiPolygon(())
  671. for g in [gc1, gc2, pnt, ls, poly, mls, mpoly1, mpoly2]:
  672. self.assertEqual(True, g.empty)
  673. # Testing len() and num_geom.
  674. if isinstance(g, Polygon):
  675. self.assertEqual(1, len(g)) # Has one empty linear ring
  676. self.assertEqual(1, g.num_geom)
  677. self.assertEqual(0, len(g[0]))
  678. elif isinstance(g, (Point, LineString)):
  679. self.assertEqual(1, g.num_geom)
  680. self.assertEqual(0, len(g))
  681. else:
  682. self.assertEqual(0, g.num_geom)
  683. self.assertEqual(0, len(g))
  684. # Testing __getitem__ (doesn't work on Point or Polygon)
  685. if isinstance(g, Point):
  686. self.assertRaises(GEOSIndexError, g.get_x)
  687. elif isinstance(g, Polygon):
  688. lr = g.shell
  689. self.assertEqual('LINEARRING EMPTY', lr.wkt)
  690. self.assertEqual(0, len(lr))
  691. self.assertEqual(True, lr.empty)
  692. self.assertRaises(GEOSIndexError, lr.__getitem__, 0)
  693. else:
  694. self.assertRaises(GEOSIndexError, g.__getitem__, 0)
  695. def test_collections_of_collections(self):
  696. "Testing GeometryCollection handling of other collections."
  697. # Creating a GeometryCollection WKT string composed of other
  698. # collections and polygons.
  699. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid]
  700. coll.extend(mls.wkt for mls in self.geometries.multilinestrings)
  701. coll.extend(p.wkt for p in self.geometries.polygons)
  702. coll.extend(mp.wkt for mp in self.geometries.multipoints)
  703. gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)
  704. # Should construct ok from WKT
  705. gc1 = GEOSGeometry(gc_wkt)
  706. # Should also construct ok from individual geometry arguments.
  707. gc2 = GeometryCollection(*tuple(g for g in gc1))
  708. # And, they should be equal.
  709. self.assertEqual(gc1, gc2)
  710. @skipUnless(HAS_GDAL, "GDAL is required.")
  711. def test_gdal(self):
  712. "Testing `ogr` and `srs` properties."
  713. g1 = fromstr('POINT(5 23)')
  714. self.assertIsInstance(g1.ogr, gdal.OGRGeometry)
  715. self.assertIsNone(g1.srs)
  716. g1_3d = fromstr('POINT(5 23 8)')
  717. self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry)
  718. self.assertEqual(g1_3d.ogr.z, 8)
  719. g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)
  720. self.assertIsInstance(g2.ogr, gdal.OGRGeometry)
  721. self.assertIsInstance(g2.srs, gdal.SpatialReference)
  722. self.assertEqual(g2.hex, g2.ogr.hex)
  723. self.assertEqual('WGS 84', g2.srs.name)
  724. def test_copy(self):
  725. "Testing use with the Python `copy` module."
  726. import copy
  727. poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')
  728. cpy1 = copy.copy(poly)
  729. cpy2 = copy.deepcopy(poly)
  730. self.assertNotEqual(poly._ptr, cpy1._ptr)
  731. self.assertNotEqual(poly._ptr, cpy2._ptr)
  732. @skipUnless(HAS_GDAL, "GDAL is required to transform geometries")
  733. def test_transform(self):
  734. "Testing `transform` method."
  735. orig = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  736. trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774)
  737. # Using a srid, a SpatialReference object, and a CoordTransform object
  738. # for transformations.
  739. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
  740. t1.transform(trans.srid)
  741. t2.transform(gdal.SpatialReference('EPSG:2774'))
  742. ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774))
  743. t3.transform(ct)
  744. # Testing use of the `clone` keyword.
  745. k1 = orig.clone()
  746. k2 = k1.transform(trans.srid, clone=True)
  747. self.assertEqual(k1, orig)
  748. self.assertNotEqual(k1, k2)
  749. prec = 3
  750. for p in (t1, t2, t3, k2):
  751. self.assertAlmostEqual(trans.x, p.x, prec)
  752. self.assertAlmostEqual(trans.y, p.y, prec)
  753. @skipUnless(HAS_GDAL, "GDAL is required to transform geometries")
  754. def test_transform_3d(self):
  755. p3d = GEOSGeometry('POINT (5 23 100)', 4326)
  756. p3d.transform(2774)
  757. self.assertEqual(p3d.z, 100)
  758. @skipUnless(HAS_GDAL, "GDAL is required.")
  759. def test_transform_noop(self):
  760. """ Testing `transform` method (SRID match) """
  761. # transform() should no-op if source & dest SRIDs match,
  762. # regardless of whether GDAL is available.
  763. if gdal.HAS_GDAL:
  764. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  765. gt = g.tuple
  766. g.transform(4326)
  767. self.assertEqual(g.tuple, gt)
  768. self.assertEqual(g.srid, 4326)
  769. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  770. g1 = g.transform(4326, clone=True)
  771. self.assertEqual(g1.tuple, g.tuple)
  772. self.assertEqual(g1.srid, 4326)
  773. self.assertIsNot(g1, g, "Clone didn't happen")
  774. old_has_gdal = gdal.HAS_GDAL
  775. try:
  776. gdal.HAS_GDAL = False
  777. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  778. gt = g.tuple
  779. g.transform(4326)
  780. self.assertEqual(g.tuple, gt)
  781. self.assertEqual(g.srid, 4326)
  782. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  783. g1 = g.transform(4326, clone=True)
  784. self.assertEqual(g1.tuple, g.tuple)
  785. self.assertEqual(g1.srid, 4326)
  786. self.assertIsNot(g1, g, "Clone didn't happen")
  787. finally:
  788. gdal.HAS_GDAL = old_has_gdal
  789. def test_transform_nosrid(self):
  790. """ Testing `transform` method (no SRID or negative SRID) """
  791. g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
  792. self.assertRaises(GEOSException, g.transform, 2774)
  793. g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
  794. self.assertRaises(GEOSException, g.transform, 2774, clone=True)
  795. g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
  796. self.assertRaises(GEOSException, g.transform, 2774)
  797. g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
  798. self.assertRaises(GEOSException, g.transform, 2774, clone=True)
  799. @skipUnless(HAS_GDAL, "GDAL is required.")
  800. def test_transform_nogdal(self):
  801. """ Testing `transform` method (GDAL not available) """
  802. old_has_gdal = gdal.HAS_GDAL
  803. try:
  804. gdal.HAS_GDAL = False
  805. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  806. self.assertRaises(GEOSException, g.transform, 2774)
  807. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  808. self.assertRaises(GEOSException, g.transform, 2774, clone=True)
  809. finally:
  810. gdal.HAS_GDAL = old_has_gdal
  811. def test_extent(self):
  812. "Testing `extent` method."
  813. # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
  814. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
  815. self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
  816. pnt = Point(5.23, 17.8)
  817. # Extent of points is just the point itself repeated.
  818. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
  819. # Testing on the 'real world' Polygon.
  820. poly = fromstr(self.geometries.polygons[3].wkt)
  821. ring = poly.shell
  822. x, y = ring.x, ring.y
  823. xmin, ymin = min(x), min(y)
  824. xmax, ymax = max(x), max(y)
  825. self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
  826. def test_pickle(self):
  827. "Testing pickling and unpickling support."
  828. # Using both pickle and cPickle -- just 'cause.
  829. from django.utils.six.moves import cPickle
  830. import pickle
  831. # Creating a list of test geometries for pickling,
  832. # and setting the SRID on some of them.
  833. def get_geoms(lst, srid=None):
  834. return [GEOSGeometry(tg.wkt, srid) for tg in lst]
  835. tgeoms = get_geoms(self.geometries.points)
  836. tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326))
  837. tgeoms.extend(get_geoms(self.geometries.polygons, 3084))
  838. tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857))
  839. for geom in tgeoms:
  840. s1, s2 = cPickle.dumps(geom), pickle.dumps(geom)
  841. g1, g2 = cPickle.loads(s1), pickle.loads(s2)
  842. for tmpg in (g1, g2):
  843. self.assertEqual(geom, tmpg)
  844. self.assertEqual(geom.srid, tmpg.srid)
  845. def test_prepared(self):
  846. "Testing PreparedGeometry support."
  847. # Creating a simple multipolygon and getting a prepared version.
  848. mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
  849. prep = mpoly.prepared
  850. # A set of test points.
  851. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
  852. covers = [True, True, False] # No `covers` op for regular GEOS geoms.
  853. for pnt, c in zip(pnts, covers):
  854. # Results should be the same (but faster)
  855. self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
  856. self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
  857. self.assertEqual(c, prep.covers(pnt))
  858. if geos_version_info()['version'] > '3.3.0':
  859. self.assertTrue(prep.crosses(fromstr('LINESTRING(1 1, 15 15)')))
  860. self.assertTrue(prep.disjoint(Point(-5, -5)))
  861. poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))
  862. self.assertTrue(prep.overlaps(poly))
  863. poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))
  864. self.assertTrue(prep.touches(poly))
  865. poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1)))
  866. self.assertTrue(prep.within(poly))
  867. # Original geometry deletion should not crash the prepared one (#21662)
  868. del mpoly
  869. self.assertTrue(prep.covers(Point(5, 5)))
  870. def test_line_merge(self):
  871. "Testing line merge support"
  872. ref_geoms = (fromstr('LINESTRING(1 1, 1 1, 3 3)'),
  873. fromstr('MULTILINESTRING((1 1, 3 3), (3 3, 4 2))'),
  874. )
  875. ref_merged = (fromstr('LINESTRING(1 1, 3 3)'),
  876. fromstr('LINESTRING (1 1, 3 3, 4 2)'),
  877. )
  878. for geom, merged in zip(ref_geoms, ref_merged):
  879. self.assertEqual(merged, geom.merged)
  880. def test_valid_reason(self):
  881. "Testing IsValidReason support"
  882. g = GEOSGeometry("POINT(0 0)")
  883. self.assertTrue(g.valid)
  884. self.assertIsInstance(g.valid_reason, six.string_types)
  885. self.assertEqual(g.valid_reason, "Valid Geometry")
  886. g = GEOSGeometry("LINESTRING(0 0, 0 0)")
  887. self.assertFalse(g.valid)
  888. self.assertIsInstance(g.valid_reason, six.string_types)
  889. self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
  890. @skipUnless(HAS_GEOS, "Geos is required.")
  891. def test_linearref(self):
  892. "Testing linear referencing"
  893. ls = fromstr('LINESTRING(0 0, 0 10, 10 10, 10 0)')
  894. mls = fromstr('MULTILINESTRING((0 0, 0 10), (10 0, 10 10))')
  895. self.assertEqual(ls.project(Point(0, 20)), 10.0)
  896. self.assertEqual(ls.project(Point(7, 6)), 24)
  897. self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3)
  898. self.assertEqual(ls.interpolate(10), Point(0, 10))
  899. self.assertEqual(ls.interpolate(24), Point(10, 6))
  900. self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10))
  901. self.assertEqual(mls.project(Point(0, 20)), 10)
  902. self.assertEqual(mls.project(Point(7, 6)), 16)
  903. self.assertEqual(mls.interpolate(9), Point(0, 9))
  904. self.assertEqual(mls.interpolate(17), Point(10, 7))
  905. def test_geos_version(self):
  906. """Testing the GEOS version regular expression."""
  907. from django.contrib.gis.geos.libgeos import version_regex
  908. versions = [('3.0.0rc4-CAPI-1.3.3', '3.0.0', '1.3.3'),
  909. ('3.0.0-CAPI-1.4.1', '3.0.0', '1.4.1'),
  910. ('3.4.0dev-CAPI-1.8.0', '3.4.0', '1.8.0'),
  911. ('3.4.0dev-CAPI-1.8.0 r0', '3.4.0', '1.8.0')]
  912. for v_init, v_geos, v_capi in versions:
  913. m = version_regex.match(v_init)
  914. self.assertTrue(m, msg="Unable to parse the version string '%s'" % v_init)
  915. self.assertEqual(m.group('version'), v_geos)
  916. self.assertEqual(m.group('capi_version'), v_capi)