test_geos.py 51 KB

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