django/contrib/gis/geos/tests/test_geos.py
author Justin Bronn <jbronn@geodjango.org>
Sat Jan 31 15:18:50 2009 -0600 (3 years ago)
branchtrunk
changeset 138 466bece04a15
parent 125 d95f64667c2a
child 140 57acbf59090e
permissions -rw-r--r--
Merged in patch from Aryeh Leib Taurog for #9877, adapting as necessary.
     1 import random, unittest, sys
     2 from ctypes import ArgumentError
     3 from django.contrib.gis.geos import *
     4 from django.contrib.gis.geos.base import gdal, numpy
     5 from django.contrib.gis.tests.geometries import *
     6     
     7 class GEOSTest(unittest.TestCase):
     8 
     9     @property
    10     def null_srid(self):
    11         """
    12         Returns the proper null SRID depending on the GEOS version.
    13         See the comments in `test15_srid` for more details. 
    14         """
    15         info = geos_version_info()
    16         if info['version'] == '3.0.0' and info['release_candidate']:
    17             return -1
    18         else:
    19             return None
    20 
    21     def test01a_wkt(self):
    22         "Testing WKT output."
    23         for g in wkt_out:
    24             geom = fromstr(g.wkt)
    25             self.assertEqual(g.ewkt, geom.wkt)
    26 
    27     def test01b_hex(self):
    28         "Testing HEX output."
    29         for g in hex_wkt:
    30             geom = fromstr(g.wkt)
    31             self.assertEqual(g.hex, geom.hex)
    32 
    33     def test01c_kml(self):
    34         "Testing KML output."
    35         for tg in wkt_out:
    36             geom = fromstr(tg.wkt)
    37             kml = getattr(tg, 'kml', False)
    38             if kml: self.assertEqual(kml, geom.kml)
    39 
    40     def test01d_errors(self):
    41         "Testing the Error handlers."
    42         # string-based
    43         print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n"
    44         for err in errors:
    45             try:
    46                 g = fromstr(err.wkt)
    47             except (GEOSException, ValueError):
    48                 pass
    49 
    50         # Bad WKB
    51         self.assertRaises(GEOSException, GEOSGeometry, buffer('0'))
    52 
    53         print "\nEND - expecting GEOS_ERROR; safe to ignore.\n"
    54         
    55         class NotAGeometry(object):
    56             pass
    57         
    58         # Some other object
    59         self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
    60         # None
    61         self.assertRaises(TypeError, GEOSGeometry, None)
    62                 
    63     def test01e_wkb(self):
    64         "Testing WKB output."
    65         from binascii import b2a_hex
    66         for g in hex_wkt:
    67             geom = fromstr(g.wkt)
    68             wkb = geom.wkb
    69             self.assertEqual(b2a_hex(wkb).upper(), g.hex)
    70 
    71     def test01f_create_hex(self):
    72         "Testing creation from HEX."
    73         for g in hex_wkt:
    74             geom_h = GEOSGeometry(g.hex)
    75             # we need to do this so decimal places get normalised
    76             geom_t = fromstr(g.wkt)
    77             self.assertEqual(geom_t.wkt, geom_h.wkt)
    78 
    79     def test01g_create_wkb(self):
    80         "Testing creation from WKB."
    81         from binascii import a2b_hex
    82         for g in hex_wkt:
    83             wkb = buffer(a2b_hex(g.hex))
    84             geom_h = GEOSGeometry(wkb)
    85             # we need to do this so decimal places get normalised
    86             geom_t = fromstr(g.wkt)
    87             self.assertEqual(geom_t.wkt, geom_h.wkt)
    88 
    89     def test01h_ewkt(self):
    90         "Testing EWKT."
    91         srid = 32140
    92         for p in polygons:
    93             ewkt = 'SRID=%d;%s' % (srid, p.wkt)
    94             poly = fromstr(ewkt)
    95             self.assertEqual(srid, poly.srid)
    96             self.assertEqual(srid, poly.shell.srid)
    97             self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
    98     
    99     def test01i_json(self):
   100         "Testing GeoJSON input/output (via GDAL)."
   101         if not gdal or not gdal.GEOJSON: return
   102         for g in json_geoms:
   103             geom = GEOSGeometry(g.wkt)
   104             if not hasattr(g, 'not_equal'):
   105                 self.assertEqual(g.json, geom.json)
   106                 self.assertEqual(g.json, geom.geojson)
   107             self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))
   108 
   109     def test01j_eq(self):
   110         "Testing equivalence."
   111         p = fromstr('POINT(5 23)')
   112         self.assertEqual(p, p.wkt)
   113         self.assertNotEqual(p, 'foo')
   114         ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')
   115         self.assertEqual(ls, ls.wkt)
   116         self.assertNotEqual(p, 'bar')
   117         # Error shouldn't be raise on equivalence testing with 
   118         # an invalid type.
   119         for g in (p, ls):
   120             self.assertNotEqual(g, None)
   121             self.assertNotEqual(g, {'foo' : 'bar'})
   122             self.assertNotEqual(g, False)
   123 
   124     def test02a_points(self):
   125         "Testing Point objects."
   126         prev = fromstr('POINT(0 0)')
   127         for p in points:
   128             # Creating the point from the WKT
   129             pnt = fromstr(p.wkt)
   130             self.assertEqual(pnt.geom_type, 'Point')
   131             self.assertEqual(pnt.geom_typeid, 0)
   132             self.assertEqual(p.x, pnt.x)
   133             self.assertEqual(p.y, pnt.y)
   134             self.assertEqual(True, pnt == fromstr(p.wkt))
   135             self.assertEqual(False, pnt == prev)
   136 
   137             # Making sure that the point's X, Y components are what we expect
   138             self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
   139             self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
   140 
   141             # Testing the third dimension, and getting the tuple arguments
   142             if hasattr(p, 'z'):
   143                 self.assertEqual(True, pnt.hasz)
   144                 self.assertEqual(p.z, pnt.z)
   145                 self.assertEqual(p.z, pnt.tuple[2], 9)
   146                 tup_args = (p.x, p.y, p.z)
   147                 set_tup1 = (2.71, 3.14, 5.23)
   148                 set_tup2 = (5.23, 2.71, 3.14)
   149             else:
   150                 self.assertEqual(False, pnt.hasz)
   151                 self.assertEqual(None, pnt.z)
   152                 tup_args = (p.x, p.y)
   153                 set_tup1 = (2.71, 3.14)
   154                 set_tup2 = (3.14, 2.71)
   155 
   156             # Centroid operation on point should be point itself
   157             self.assertEqual(p.centroid, pnt.centroid.tuple)
   158 
   159             # Now testing the different constructors
   160             pnt2 = Point(tup_args)  # e.g., Point((1, 2))
   161             pnt3 = Point(*tup_args) # e.g., Point(1, 2)
   162             self.assertEqual(True, pnt == pnt2)
   163             self.assertEqual(True, pnt == pnt3)
   164 
   165             # Now testing setting the x and y
   166             pnt.y = 3.14
   167             pnt.x = 2.71
   168             self.assertEqual(3.14, pnt.y)
   169             self.assertEqual(2.71, pnt.x)
   170 
   171             # Setting via the tuple/coords property
   172             pnt.tuple = set_tup1
   173             self.assertEqual(set_tup1, pnt.tuple)
   174             pnt.coords = set_tup2
   175             self.assertEqual(set_tup2, pnt.coords)
   176             
   177             prev = pnt # setting the previous geometry
   178 
   179     def test02b_multipoints(self):
   180         "Testing MultiPoint objects."
   181         for mp in multipoints:
   182             mpnt = fromstr(mp.wkt)
   183             self.assertEqual(mpnt.geom_type, 'MultiPoint')
   184             self.assertEqual(mpnt.geom_typeid, 4)
   185 
   186             self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
   187             self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
   188 
   189             self.assertRaises(GEOSIndexError, mpnt.__getitem__, len(mpnt))
   190             self.assertEqual(mp.centroid, mpnt.centroid.tuple)
   191             self.assertEqual(mp.points, tuple(m.tuple for m in mpnt))
   192             for p in mpnt:
   193                 self.assertEqual(p.geom_type, 'Point')
   194                 self.assertEqual(p.geom_typeid, 0)
   195                 self.assertEqual(p.empty, False)
   196                 self.assertEqual(p.valid, True)
   197 
   198     def test03a_linestring(self):
   199         "Testing LineString objects."
   200         prev = fromstr('POINT(0 0)')
   201         for l in linestrings:
   202             ls = fromstr(l.wkt)
   203             self.assertEqual(ls.geom_type, 'LineString')
   204             self.assertEqual(ls.geom_typeid, 1)
   205             self.assertEqual(ls.empty, False)
   206             self.assertEqual(ls.ring, False)
   207             if hasattr(l, 'centroid'):
   208                 self.assertEqual(l.centroid, ls.centroid.tuple)
   209             if hasattr(l, 'tup'):
   210                 self.assertEqual(l.tup, ls.tuple)
   211                 
   212             self.assertEqual(True, ls == fromstr(l.wkt))
   213             self.assertEqual(False, ls == prev)
   214             self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
   215             prev = ls
   216 
   217             # Creating a LineString from a tuple, list, and numpy array
   218             self.assertEqual(ls, LineString(ls.tuple))  # tuple
   219             self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
   220             self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
   221             self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments
   222             if numpy: self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
   223 
   224     def test03b_multilinestring(self):
   225         "Testing MultiLineString objects."
   226         prev = fromstr('POINT(0 0)')
   227         for l in multilinestrings:
   228             ml = fromstr(l.wkt)
   229             self.assertEqual(ml.geom_type, 'MultiLineString')
   230             self.assertEqual(ml.geom_typeid, 5)
   231 
   232             self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
   233             self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
   234 
   235             self.assertEqual(True, ml == fromstr(l.wkt))
   236             self.assertEqual(False, ml == prev)
   237             prev = ml
   238 
   239             for ls in ml:
   240                 self.assertEqual(ls.geom_type, 'LineString')
   241                 self.assertEqual(ls.geom_typeid, 1)
   242                 self.assertEqual(ls.empty, False)
   243 
   244             self.assertRaises(GEOSIndexError, ml.__getitem__, len(ml))
   245             self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
   246             self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))
   247 
   248     def test04_linearring(self):
   249         "Testing LinearRing objects."
   250         for rr in linearrings:
   251             lr = fromstr(rr.wkt)
   252             self.assertEqual(lr.geom_type, 'LinearRing')
   253             self.assertEqual(lr.geom_typeid, 2)
   254             self.assertEqual(rr.n_p, len(lr))
   255             self.assertEqual(True, lr.valid)
   256             self.assertEqual(False, lr.empty)
   257 
   258             # Creating a LinearRing from a tuple, list, and numpy array
   259             self.assertEqual(lr, LinearRing(lr.tuple))
   260             self.assertEqual(lr, LinearRing(*lr.tuple))
   261             self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
   262             if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
   263     
   264     def test05a_polygons(self):
   265         "Testing Polygon objects."
   266 
   267         # Testing `from_bbox` class method
   268         bbox = (-180, -90, 180, 90)
   269         p = Polygon.from_bbox( bbox )
   270         self.assertEqual(bbox, p.extent)
   271 
   272         prev = fromstr('POINT(0 0)')
   273         for p in polygons:
   274             # Creating the Polygon, testing its properties.
   275             poly = fromstr(p.wkt)
   276             self.assertEqual(poly.geom_type, 'Polygon')
   277             self.assertEqual(poly.geom_typeid, 3)
   278             self.assertEqual(poly.empty, False)
   279             self.assertEqual(poly.ring, False)
   280             self.assertEqual(p.n_i, poly.num_interior_rings)
   281             self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
   282             self.assertEqual(p.n_p, poly.num_points)
   283 
   284             # Area & Centroid
   285             self.assertAlmostEqual(p.area, poly.area, 9)
   286             self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
   287             self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)
   288 
   289             # Testing the geometry equivalence
   290             self.assertEqual(True, poly == fromstr(p.wkt))
   291             self.assertEqual(False, poly == prev) # Should not be equal to previous geometry
   292             self.assertEqual(True, poly != prev)
   293 
   294             # Testing the exterior ring
   295             ring = poly.exterior_ring
   296             self.assertEqual(ring.geom_type, 'LinearRing')
   297             self.assertEqual(ring.geom_typeid, 2)
   298             if p.ext_ring_cs:
   299                 self.assertEqual(p.ext_ring_cs, ring.tuple)
   300                 self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
   301 
   302             # Testing __getitem__ and __setitem__ on invalid indices
   303             self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly))
   304             self.assertRaises(GEOSIndexError, poly.__setitem__, len(poly), False)
   305             self.assertRaises(GEOSIndexError, poly.__getitem__, -1)
   306 
   307             # Testing __iter__ 
   308             for r in poly:
   309                 self.assertEqual(r.geom_type, 'LinearRing')
   310                 self.assertEqual(r.geom_typeid, 2)
   311 
   312             # Testing polygon construction.
   313             self.assertRaises(TypeError, Polygon.__init__, 0, [1, 2, 3])
   314             self.assertRaises(TypeError, Polygon.__init__, 'foo')
   315             
   316             # Polygon(shell, (hole1, ... holeN))
   317             rings = tuple(r for r in poly)
   318             self.assertEqual(poly, Polygon(rings[0], rings[1:]))
   319             
   320             # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
   321             ring_tuples = tuple(r.tuple for r in poly)
   322             self.assertEqual(poly, Polygon(*ring_tuples))
   323 
   324             # Constructing with tuples of LinearRings.
   325             self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
   326             self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)
   327 
   328     def test05b_multipolygons(self):
   329         "Testing MultiPolygon objects."
   330         print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n"
   331         prev = fromstr('POINT (0 0)')
   332         for mp in multipolygons:
   333             mpoly = fromstr(mp.wkt)
   334             self.assertEqual(mpoly.geom_type, 'MultiPolygon')
   335             self.assertEqual(mpoly.geom_typeid, 6)
   336             self.assertEqual(mp.valid, mpoly.valid)
   337 
   338             if mp.valid:
   339                 self.assertEqual(mp.num_geom, mpoly.num_geom)
   340                 self.assertEqual(mp.n_p, mpoly.num_coords)
   341                 self.assertEqual(mp.num_geom, len(mpoly))
   342                 self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
   343                 for p in mpoly:
   344                     self.assertEqual(p.geom_type, 'Polygon')
   345                     self.assertEqual(p.geom_typeid, 3)
   346                     self.assertEqual(p.valid, True)
   347                 self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
   348 
   349         print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n"  
   350 
   351     def test06a_memory_hijinks(self):
   352         "Testing Geometry __del__() on rings and polygons."
   353         #### Memory issues with rings and polygons
   354 
   355         # These tests are needed to ensure sanity with writable geometries.
   356 
   357         # Getting a polygon with interior rings, and pulling out the interior rings
   358         poly = fromstr(polygons[1].wkt)
   359         ring1 = poly[0]
   360         ring2 = poly[1]
   361 
   362         # These deletes should be 'harmless' since they are done on child geometries
   363         del ring1 
   364         del ring2
   365         ring1 = poly[0]
   366         ring2 = poly[1]
   367 
   368         # Deleting the polygon
   369         del poly
   370 
   371         # Access to these rings is OK since they are clones.
   372         s1, s2 = str(ring1), str(ring2)
   373 
   374         # The previous hijinks tests are now moot because only clones are 
   375         # now used =)
   376 
   377     def test08_coord_seq(self):
   378         "Testing Coordinate Sequence objects."
   379         for p in polygons:
   380             if p.ext_ring_cs:
   381                 # Constructing the polygon and getting the coordinate sequence
   382                 poly = fromstr(p.wkt)
   383                 cs = poly.exterior_ring.coord_seq
   384 
   385                 self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
   386                 self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works
   387 
   388                 # Checks __getitem__ and __setitem__
   389                 for i in xrange(len(p.ext_ring_cs)):
   390                     c1 = p.ext_ring_cs[i] # Expected value
   391                     c2 = cs[i] # Value from coordseq
   392                     self.assertEqual(c1, c2)
   393 
   394                     # Constructing the test value to set the coordinate sequence with
   395                     if len(c1) == 2: tset = (5, 23)
   396                     else: tset = (5, 23, 8)
   397                     cs[i] = tset
   398                     
   399                     # Making sure every set point matches what we expect
   400                     for j in range(len(tset)):
   401                         cs[i] = tset
   402                         self.assertEqual(tset[j], cs[i][j])
   403 
   404     def test09_relate_pattern(self):
   405         "Testing relate() and relate_pattern()."
   406         g = fromstr('POINT (0 0)')
   407         self.assertRaises(GEOSException, g.relate_pattern, 0, 'invalid pattern, yo')
   408         for i in xrange(len(relate_geoms)):
   409             g_tup = relate_geoms[i]
   410             a = fromstr(g_tup[0].wkt)
   411             b = fromstr(g_tup[1].wkt)
   412             pat = g_tup[2]
   413             result = g_tup[3]
   414             self.assertEqual(result, a.relate_pattern(b, pat))
   415             self.assertEqual(pat, a.relate(b))
   416 
   417     def test10_intersection(self):
   418         "Testing intersects() and intersection()."
   419         for i in xrange(len(topology_geoms)):
   420             g_tup = topology_geoms[i]
   421             a = fromstr(g_tup[0].wkt)
   422             b = fromstr(g_tup[1].wkt)
   423             i1 = fromstr(intersect_geoms[i].wkt) 
   424             self.assertEqual(True, a.intersects(b))
   425             i2 = a.intersection(b)
   426             self.assertEqual(i1, i2)
   427             self.assertEqual(i1, a & b) # __and__ is intersection operator
   428             a &= b # testing __iand__
   429             self.assertEqual(i1, a)
   430 
   431     def test11_union(self):
   432         "Testing union()."
   433         for i in xrange(len(topology_geoms)):
   434             g_tup = topology_geoms[i]
   435             a = fromstr(g_tup[0].wkt)
   436             b = fromstr(g_tup[1].wkt)
   437             u1 = fromstr(union_geoms[i].wkt)
   438             u2 = a.union(b)
   439             self.assertEqual(u1, u2)
   440             self.assertEqual(u1, a | b) # __or__ is union operator
   441             a |= b # testing __ior__
   442             self.assertEqual(u1, a) 
   443 
   444     def test12_difference(self):
   445         "Testing difference()."
   446         for i in xrange(len(topology_geoms)):
   447             g_tup = topology_geoms[i]
   448             a = fromstr(g_tup[0].wkt)
   449             b = fromstr(g_tup[1].wkt)
   450             d1 = fromstr(diff_geoms[i].wkt)
   451             d2 = a.difference(b)
   452             self.assertEqual(d1, d2)
   453             self.assertEqual(d1, a - b) # __sub__ is difference operator
   454             a -= b # testing __isub__
   455             self.assertEqual(d1, a)
   456 
   457     def test13_symdifference(self):
   458         "Testing sym_difference()."
   459         for i in xrange(len(topology_geoms)):
   460             g_tup = topology_geoms[i]
   461             a = fromstr(g_tup[0].wkt)
   462             b = fromstr(g_tup[1].wkt)
   463             d1 = fromstr(sdiff_geoms[i].wkt)
   464             d2 = a.sym_difference(b)
   465             self.assertEqual(d1, d2)
   466             self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
   467             a ^= b # testing __ixor__
   468             self.assertEqual(d1, a)
   469 
   470     def test14_buffer(self):
   471         "Testing buffer()."
   472         for i in xrange(len(buffer_geoms)):
   473             g_tup = buffer_geoms[i]
   474             g = fromstr(g_tup[0].wkt)
   475 
   476             # The buffer we expect
   477             exp_buf = fromstr(g_tup[1].wkt)
   478 
   479             # Can't use a floating-point for the number of quadsegs.
   480             self.assertRaises(ArgumentError, g.buffer, g_tup[2], float(g_tup[3]))
   481 
   482             # Constructing our buffer
   483             buf = g.buffer(g_tup[2], g_tup[3])
   484             self.assertEqual(exp_buf.num_coords, buf.num_coords)
   485             self.assertEqual(len(exp_buf), len(buf))
   486 
   487             # Now assuring that each point in the buffer is almost equal
   488             for j in xrange(len(exp_buf)):
   489                 exp_ring = exp_buf[j]
   490                 buf_ring = buf[j]
   491                 self.assertEqual(len(exp_ring), len(buf_ring))
   492                 for k in xrange(len(exp_ring)):
   493                     # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
   494                     self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
   495                     self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
   496 
   497     def test15_srid(self):
   498         "Testing the SRID property and keyword."
   499         # Testing SRID keyword on Point
   500         pnt = Point(5, 23, srid=4326)
   501         self.assertEqual(4326, pnt.srid)
   502         pnt.srid = 3084
   503         self.assertEqual(3084, pnt.srid)
   504         self.assertRaises(ArgumentError, pnt.set_srid, '4326')
   505 
   506         # Testing SRID keyword on fromstr(), and on Polygon rings.
   507         poly = fromstr(polygons[1].wkt, srid=4269)
   508         self.assertEqual(4269, poly.srid)
   509         for ring in poly: self.assertEqual(4269, ring.srid)
   510         poly.srid = 4326
   511         self.assertEqual(4326, poly.shell.srid)
   512 
   513         # Testing SRID keyword on GeometryCollection
   514         gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)
   515         self.assertEqual(32021, gc.srid)
   516         for i in range(len(gc)): self.assertEqual(32021, gc[i].srid)
   517 
   518         # GEOS may get the SRID from HEXEWKB
   519         # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
   520         # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
   521         hex = '0101000020E610000000000000000014400000000000003740'
   522         p1 = fromstr(hex)
   523         self.assertEqual(4326, p1.srid)
   524 
   525         # In GEOS 3.0.0rc1-4  when the EWKB and/or HEXEWKB is exported,
   526         # the SRID information is lost and set to -1 -- this is not a
   527         # problem on the 3.0.0 version (another reason to upgrade).  
   528         exp_srid = self.null_srid
   529 
   530         p2 = fromstr(p1.hex)
   531         self.assertEqual(exp_srid, p2.srid)
   532         p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
   533         self.assertEqual(-1, p3.srid)
   534 
   535     def test16_mutable_geometries(self):
   536         "Testing the mutability of Polygons and Geometry Collections."
   537         ### Testing the mutability of Polygons ###
   538         for p in polygons:
   539             poly = fromstr(p.wkt)
   540 
   541             # Should only be able to use __setitem__ with LinearRing geometries.
   542             self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
   543 
   544             # Constructing the new shell by adding 500 to every point in the old shell.
   545             shell_tup = poly.shell.tuple
   546             new_coords = []
   547             for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.))
   548             new_shell = LinearRing(*tuple(new_coords))
   549 
   550             # Assigning polygon's exterior ring w/the new shell
   551             poly.exterior_ring = new_shell
   552             s = str(new_shell) # new shell is still accessible
   553             self.assertEqual(poly.exterior_ring, new_shell)
   554             self.assertEqual(poly[0], new_shell)
   555 
   556         ### Testing the mutability of Geometry Collections
   557         for tg in multipoints:
   558             mp = fromstr(tg.wkt)
   559             for i in range(len(mp)):
   560                 # Creating a random point.
   561                 pnt = mp[i]
   562                 new = Point(random.randint(1, 100), random.randint(1, 100))
   563                 # Testing the assignment
   564                 mp[i] = new
   565                 s = str(new) # what was used for the assignment is still accessible
   566                 self.assertEqual(mp[i], new)
   567                 self.assertEqual(mp[i].wkt, new.wkt)
   568                 self.assertNotEqual(pnt, mp[i])
   569 
   570         # MultiPolygons involve much more memory management because each
   571         # Polygon w/in the collection has its own rings.
   572         for tg in multipolygons:
   573             mpoly = fromstr(tg.wkt)
   574             for i in xrange(len(mpoly)):
   575                 poly = mpoly[i]
   576                 old_poly = mpoly[i]
   577                 # Offsetting the each ring in the polygon by 500.
   578                 for j in xrange(len(poly)):
   579                     r = poly[j]
   580                     for k in xrange(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.)
   581                     poly[j] = r
   582                 
   583                 self.assertNotEqual(mpoly[i], poly)
   584                 # Testing the assignment
   585                 mpoly[i] = poly
   586                 s = str(poly) # Still accessible
   587                 self.assertEqual(mpoly[i], poly)
   588                 self.assertNotEqual(mpoly[i], old_poly)
   589 
   590         # Extreme (!!) __setitem__ -- no longer works, have to detect
   591         # in the first object that __setitem__ is called in the subsequent
   592         # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?
   593         #mpoly[0][0][0] = (3.14, 2.71)
   594         #self.assertEqual((3.14, 2.71), mpoly[0][0][0])
   595         # Doing it more slowly..
   596         #self.assertEqual((3.14, 2.71), mpoly[0].shell[0])
   597         #del mpoly
   598     
   599     def test17_threed(self):
   600         "Testing three-dimensional geometries."
   601         # Testing a 3D Point
   602         pnt = Point(2, 3, 8)
   603         self.assertEqual((2.,3.,8.), pnt.coords)
   604         self.assertRaises(TypeError, pnt.set_coords, (1.,2.))
   605         pnt.coords = (1.,2.,3.)
   606         self.assertEqual((1.,2.,3.), pnt.coords)
   607 
   608         # Testing a 3D LineString
   609         ls = LineString((2., 3., 8.), (50., 250., -117.))
   610         self.assertEqual(((2.,3.,8.), (50.,250.,-117.)), ls.tuple)
   611         self.assertRaises(TypeError, ls.__setitem__, 0, (1.,2.))
   612         ls[0] = (1.,2.,3.)
   613         self.assertEqual((1.,2.,3.), ls[0])
   614             
   615     def test18_distance(self):
   616         "Testing the distance() function."
   617         # Distance to self should be 0. 
   618         pnt = Point(0, 0)
   619         self.assertEqual(0.0, pnt.distance(Point(0, 0)))
   620     
   621         # Distance should be 1
   622         self.assertEqual(1.0, pnt.distance(Point(0, 1)))
   623 
   624         # Distance should be ~ sqrt(2)
   625         self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
   626 
   627         # Distances are from the closest vertex in each geometry --
   628         #  should be 3 (distance from (2, 2) to (5, 2)).
   629         ls1 = LineString((0, 0), (1, 1), (2, 2))
   630         ls2 = LineString((5, 2), (6, 1), (7, 0))
   631         self.assertEqual(3, ls1.distance(ls2))
   632 
   633     def test19_length(self):
   634         "Testing the length property."
   635         # Points have 0 length.
   636         pnt = Point(0, 0)
   637         self.assertEqual(0.0, pnt.length)
   638         
   639         # Should be ~ sqrt(2)
   640         ls = LineString((0, 0), (1, 1))
   641         self.assertAlmostEqual(1.41421356237, ls.length, 11)
   642 
   643         # Should be circumfrence of Polygon
   644         poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
   645         self.assertEqual(4.0, poly.length)
   646 
   647         # Should be sum of each element's length in collection.
   648         mpoly = MultiPolygon(poly.clone(), poly)
   649         self.assertEqual(8.0, mpoly.length)
   650 
   651     def test20a_emptyCollections(self):
   652         "Testing empty geometries and collections."
   653         gc1 = GeometryCollection([])
   654         gc2 = fromstr('GEOMETRYCOLLECTION EMPTY')
   655         pnt = fromstr('POINT EMPTY')
   656         ls = fromstr('LINESTRING EMPTY')
   657         poly = fromstr('POLYGON EMPTY')
   658         mls = fromstr('MULTILINESTRING EMPTY')
   659         mpoly1 = fromstr('MULTIPOLYGON EMPTY')
   660         mpoly2 = MultiPolygon(())
   661 
   662         for g in [gc1, gc2, pnt, ls, poly, mls, mpoly1, mpoly2]:
   663             self.assertEqual(True, g.empty)
   664 
   665             # Testing len() and num_geom.
   666             if isinstance(g, Polygon):
   667                 self.assertEqual(1, len(g)) # Has one empty linear ring
   668                 self.assertEqual(1, g.num_geom)
   669                 self.assertEqual(0, len(g[0]))
   670             elif isinstance(g, (Point, LineString)):
   671                 self.assertEqual(1, g.num_geom)
   672                 self.assertEqual(0, len(g))
   673             else:
   674                 self.assertEqual(0, g.num_geom)
   675                 self.assertEqual(0, len(g))
   676 
   677             # Testing __getitem__ (doesn't work on Point or Polygon)
   678             if isinstance(g, Point):
   679                 self.assertRaises(GEOSIndexError, g.get_x)
   680             elif isinstance(g, Polygon):
   681                 lr = g.shell
   682                 self.assertEqual('LINEARRING EMPTY', lr.wkt)
   683                 self.assertEqual(0, len(lr))
   684                 self.assertEqual(True, lr.empty)
   685                 self.assertRaises(GEOSIndexError, lr.__getitem__, 0)
   686             else:
   687                 self.assertRaises(GEOSIndexError, g.__getitem__, 0)
   688 
   689     def test20b_collections_of_collections(self):
   690         "Testing GeometryCollection handling of other collections."
   691         # Creating a GeometryCollection WKT string composed of other 
   692         # collections and polygons.
   693         coll = [mp.wkt for mp in multipolygons if mp.valid]
   694         coll.extend([mls.wkt for mls in multilinestrings])
   695         coll.extend([p.wkt for p in polygons])
   696         coll.extend([mp.wkt for mp in multipoints])
   697         gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)
   698         
   699         # Should construct ok from WKT
   700         gc1 = GEOSGeometry(gc_wkt)
   701 
   702         # Should also construct ok from individual geometry arguments.
   703         gc2 = GeometryCollection(*tuple(g for g in gc1))
   704 
   705         # And, they should be equal.
   706         self.assertEqual(gc1, gc2)
   707 
   708     def test21_test_gdal(self):
   709         "Testing `ogr` and `srs` properties."
   710         if not gdal.HAS_GDAL: return
   711         g1 = fromstr('POINT(5 23)')
   712         self.assertEqual(True, isinstance(g1.ogr, gdal.OGRGeometry))
   713         self.assertEqual(g1.srs, None)
   714         
   715         g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)
   716         self.assertEqual(True, isinstance(g2.ogr, gdal.OGRGeometry))
   717         self.assertEqual(True, isinstance(g2.srs, gdal.SpatialReference))
   718         self.assertEqual(g2.hex, g2.ogr.hex)
   719         self.assertEqual('WGS 84', g2.srs.name)
   720 
   721     def test22_copy(self):
   722         "Testing use with the Python `copy` module."
   723         import copy
   724         poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')
   725         cpy1 = copy.copy(poly)
   726         cpy2 = copy.deepcopy(poly)
   727         self.assertNotEqual(poly._ptr, cpy1._ptr)
   728         self.assertNotEqual(poly._ptr, cpy2._ptr)
   729 
   730     def test23_transform(self):
   731         "Testing `transform` method."
   732         if not gdal.HAS_GDAL: return
   733         orig = GEOSGeometry('POINT (-104.609 38.255)', 4326)
   734         trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774)
   735 
   736         # Using a srid, a SpatialReference object, and a CoordTransform object
   737         # for transformations.
   738         t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
   739         t1.transform(trans.srid)
   740         t2.transform(gdal.SpatialReference('EPSG:2774'))
   741         ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774))
   742         t3.transform(ct)
   743 
   744         # Testing use of the `clone` keyword.
   745         k1 = orig.clone()
   746         k2 = k1.transform(trans.srid, clone=True)
   747         self.assertEqual(k1, orig)
   748         self.assertNotEqual(k1, k2)
   749 
   750         prec = 3
   751         for p in (t1, t2, t3, k2):
   752             self.assertAlmostEqual(trans.x, p.x, prec)
   753             self.assertAlmostEqual(trans.y, p.y, prec)
   754 
   755     def test24_extent(self):
   756         "Testing `extent` method."
   757         # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
   758         mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
   759         self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
   760         pnt = Point(5.23, 17.8)
   761         # Extent of points is just the point itself repeated.
   762         self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
   763         # Testing on the 'real world' Polygon.
   764         poly = fromstr(polygons[3].wkt)
   765         ring = poly.shell
   766         x, y = ring.x, ring.y
   767         xmin, ymin = min(x), min(y)
   768         xmax, ymax = max(x), max(y)
   769         self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
   770 
   771     def test25_pickle(self):
   772         "Testing pickling and unpickling support."
   773         # Using both pickle and cPickle -- just 'cause.
   774         import pickle, cPickle
   775 
   776         # Creating a list of test geometries for pickling, 
   777         # and setting the SRID on some of them.
   778         def get_geoms(lst, srid=None):
   779             return [GEOSGeometry(tg.wkt, srid) for tg in lst]
   780         tgeoms = get_geoms(points)
   781         tgeoms.extend(get_geoms(multilinestrings, 4326))
   782         tgeoms.extend(get_geoms(polygons, 3084))
   783         tgeoms.extend(get_geoms(multipolygons, 900913))
   784 
   785         # The SRID won't be exported in GEOS 3.0 release candidates.
   786         no_srid = self.null_srid == -1 
   787         for geom in tgeoms:
   788             s1, s2 = cPickle.dumps(geom), pickle.dumps(geom)
   789             g1, g2 = cPickle.loads(s1), pickle.loads(s2)
   790             for tmpg in (g1, g2):
   791                 self.assertEqual(geom, tmpg)
   792                 if not no_srid: self.assertEqual(geom.srid, tmpg.srid)
   793 
   794     def test26_prepared(self):
   795         "Testing PreparedGeometry support."
   796         if GEOS_PREPARE: return
   797         # Creating a simple multipolygon and getting a prepared version.
   798         mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
   799         prep = mpoly.prepared
   800 
   801         # A set of test points.
   802         pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
   803         covers = [True, True, False] # No `covers` op for regular GEOS geoms.
   804         for pnt, c in zip(pnts, covers):
   805             # Results should be the same (but faster)
   806             self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
   807             self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
   808             self.assertEqual(c, prep.covers(pnt))
   809 
   810 def suite():
   811     s = unittest.TestSuite()
   812     s.addTest(unittest.makeSuite(GEOSTest))
   813     return s
   814 
   815 def run(verbosity=2):
   816     unittest.TextTestRunner(verbosity=verbosity).run(suite())