PageRenderTime 1212ms CodeModel.GetById 149ms app.highlight 951ms RepoModel.GetById 98ms app.codeStats 1ms

/django/contrib/gis/geos/tests/test_geos.py

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