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