2
0

test_geos.py 50 KB

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