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