django.contrib.gis.geos.fromstr

Here are the examples of the python api django.contrib.gis.geos.fromstr taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

64 Examples 7

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_isvalid_lookup(self):
        invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))')
        State.objects.create(name='invalid', poly=invalid_geom)
        qs = State.objects.all()
        if oracle:
            # Kansas has adjacent vertices with distance 6.99244813842e-12
            # which is smaller than the default Oracle tolerance.
            qs = qs.exclude(name='Kansas')
            self.assertEqual(State.objects.filter(name='Kansas', poly__isvalid=False).count(), 1)
        self.assertEqual(qs.filter(poly__isvalid=False).count(), 1)
        self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1)

    @skipUnlessDBFeature("supports_left_right_lookups")

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_equals_lookups(self):
        "Testing the 'same_as' and 'equals' lookup types."
        pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326)
        c1 = City.objects.get(point=pnt)
        c2 = City.objects.get(point__same_as=pnt)
        c3 = City.objects.get(point__equals=pnt)
        for c in [c1, c2, c3]:
            self.assertEqual('Houston', c.name)

    @skipUnlessDBFeature("supports_null_geometries")

3 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_isvalid(self):
        valid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))')
        invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))')
        State.objects.create(name='valid', poly=valid_geom)
        State.objects.create(name='invalid', poly=invalid_geom)
        valid = State.objects.filter(name='valid').annotate(isvalid=functions.IsValid('poly')).first()
        invalid = State.objects.filter(name='invalid').annotate(isvalid=functions.IsValid('poly')).first()
        self.assertIs(valid.isvalid, True)
        self.assertIs(invalid.isvalid, False)

    @skipUnlessDBFeature("has_Area_function")

3 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_make_valid(self):
        invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))')
        State.objects.create(name='invalid', poly=invalid_geom)
        invalid = State.objects.filter(name='invalid').annotate(repaired=functions.MakeValid('poly')).first()
        self.assertIs(invalid.repaired.valid, True)
        self.assertEqual(invalid.repaired, fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))', srid=invalid.poly.srid))

    @skipUnlessDBFeature("has_MemSize_function")

3 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_transform(self):
        # Pre-transformed points for Houston and Pueblo.
        ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774)
        prec = 3  # Precision is low due to version variations in PROJ and GDAL.

        # Asserting the result of the transform operation with the values in
        #  the pre-transformed points.
        h = City.objects.annotate(pt=functions.Transform('point', ptown.srid)).get(name='Pueblo')
        self.assertEqual(2774, h.pt.srid)
        self.assertAlmostEqual(ptown.x, h.pt.x, prec)
        self.assertAlmostEqual(ptown.y, h.pt.y, prec)

    @skipUnlessDBFeature("has_Translate_function")

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_wkt(self):
        "Testing WKT output."
        for g in self.geometries.wkt_out:
            geom = fromstr(g.wkt)
            if geom.hasz:
                self.assertEqual(g.ewkt, geom.wkt)

    def test_hex(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_hex(self):
        "Testing HEX output."
        for g in self.geometries.hex_wkt:
            geom = fromstr(g.wkt)
            self.assertEqual(g.hex, geom.hex.decode())

    def test_hexewkb(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_kml(self):
        "Testing KML output."
        for tg in self.geometries.wkt_out:
            geom = fromstr(tg.wkt)
            kml = getattr(tg, 'kml', False)
            if kml:
                self.assertEqual(kml, geom.kml)

    def test_errors(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_wkb(self):
        "Testing WKB output."
        for g in self.geometries.hex_wkt:
            geom = fromstr(g.wkt)
            wkb = geom.wkb
            self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex)

    def test_create_hex(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_create_hex(self):
        "Testing creation from HEX."
        for g in self.geometries.hex_wkt:
            geom_h = GEOSGeometry(g.hex)
            # we need to do this so decimal places get normalized
            geom_t = fromstr(g.wkt)
            self.assertEqual(geom_t.wkt, geom_h.wkt)

    def test_create_wkb(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_create_wkb(self):
        "Testing creation from WKB."
        for g in self.geometries.hex_wkt:
            wkb = six.memoryview(a2b_hex(g.hex.encode()))
            geom_h = GEOSGeometry(wkb)
            # we need to do this so decimal places get normalized
            geom_t = fromstr(g.wkt)
            self.assertEqual(geom_t.wkt, geom_h.wkt)

    def test_ewkt(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_ewkt(self):
        "Testing EWKT."
        srids = (-1, 32140)
        for srid in srids:
            for p in self.geometries.polygons:
                ewkt = 'SRID=%d;%s' % (srid, p.wkt)
                poly = fromstr(ewkt)
                self.assertEqual(srid, poly.srid)
                self.assertEqual(srid, poly.shell.srid)
                self.assertEqual(srid, fromstr(poly.ewkt).srid)  # Checking export

    def test_json(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_eq(self):
        "Testing equivalence."
        p = fromstr('POINT(5 23)')
        self.assertEqual(p, p.wkt)
        self.assertNotEqual(p, 'foo')
        ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')
        self.assertEqual(ls, ls.wkt)
        self.assertNotEqual(p, 'bar')
        # Error shouldn't be raise on equivalence testing with
        # an invalid type.
        for g in (p, ls):
            self.assertNotEqual(g, None)
            self.assertNotEqual(g, {'foo': 'bar'})
            self.assertNotEqual(g, False)

    def test_eq_with_srid(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_polygons_templates(self):
        # Accessing Polygon attributes in templates should work.
        engine = Engine()
        template = engine.from_string('{{ polygons.0.wkt }}')
        polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]]
        content = template.render(Context({'polygons': polygons}))
        self.assertIn('MULTIPOLYGON (((100', content)

    def test_polygon_comparison(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_relate_pattern(self):
        "Testing relate() and relate_pattern()."
        g = fromstr('POINT (0 0)')
        with self.assertRaises(GEOSException):
            g.relate_pattern(0, 'invalid pattern, yo')
        for rg in self.geometries.relate_geoms:
            a = fromstr(rg.wkt_a)
            b = fromstr(rg.wkt_b)
            self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern))
            self.assertEqual(rg.pattern, a.relate(b))

    def test_intersection(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_intersection(self):
        "Testing intersects() and intersection()."
        for i in range(len(self.geometries.topology_geoms)):
            a = fromstr(self.geometries.topology_geoms[i].wkt_a)
            b = fromstr(self.geometries.topology_geoms[i].wkt_b)
            i1 = fromstr(self.geometries.intersect_geoms[i].wkt)
            self.assertIs(a.intersects(b), True)
            i2 = a.intersection(b)
            self.assertEqual(i1, i2)
            self.assertEqual(i1, a & b)  # __and__ is intersection operator
            a &= b  # testing __iand__
            self.assertEqual(i1, a)

    def test_union(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_union(self):
        "Testing union()."
        for i in range(len(self.geometries.topology_geoms)):
            a = fromstr(self.geometries.topology_geoms[i].wkt_a)
            b = fromstr(self.geometries.topology_geoms[i].wkt_b)
            u1 = fromstr(self.geometries.union_geoms[i].wkt)
            u2 = a.union(b)
            self.assertEqual(u1, u2)
            self.assertEqual(u1, a | b)  # __or__ is union operator
            a |= b  # testing __ior__
            self.assertEqual(u1, a)

    def test_unary_union(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_unary_union(self):
        "Testing unary_union."
        for i in range(len(self.geometries.topology_geoms)):
            a = fromstr(self.geometries.topology_geoms[i].wkt_a)
            b = fromstr(self.geometries.topology_geoms[i].wkt_b)
            u1 = fromstr(self.geometries.union_geoms[i].wkt)
            u2 = GeometryCollection(a, b).unary_union
            self.assertTrue(u1.equals(u2))

    def test_difference(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_difference(self):
        "Testing difference()."
        for i in range(len(self.geometries.topology_geoms)):
            a = fromstr(self.geometries.topology_geoms[i].wkt_a)
            b = fromstr(self.geometries.topology_geoms[i].wkt_b)
            d1 = fromstr(self.geometries.diff_geoms[i].wkt)
            d2 = a.difference(b)
            self.assertEqual(d1, d2)
            self.assertEqual(d1, a - b)  # __sub__ is difference operator
            a -= b  # testing __isub__
            self.assertEqual(d1, a)

    def test_symdifference(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_symdifference(self):
        "Testing sym_difference()."
        for i in range(len(self.geometries.topology_geoms)):
            a = fromstr(self.geometries.topology_geoms[i].wkt_a)
            b = fromstr(self.geometries.topology_geoms[i].wkt_b)
            d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)
            d2 = a.sym_difference(b)
            self.assertEqual(d1, d2)
            self.assertEqual(d1, a ^ b)  # __xor__ is symmetric difference operator
            a ^= b  # testing __ixor__
            self.assertEqual(d1, a)

    def test_buffer(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_gdal(self):
        "Testing `ogr` and `srs` properties."
        g1 = fromstr('POINT(5 23)')
        self.assertIsInstance(g1.ogr, gdal.OGRGeometry)
        self.assertIsNone(g1.srs)

        g1_3d = fromstr('POINT(5 23 8)')
        self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry)
        self.assertEqual(g1_3d.ogr.z, 8)

        g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)
        self.assertIsInstance(g2.ogr, gdal.OGRGeometry)
        self.assertIsInstance(g2.srs, gdal.SpatialReference)
        self.assertEqual(g2.hex, g2.ogr.hex)
        self.assertEqual('WGS 84', g2.srs.name)

    def test_copy(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_extent(self):
        "Testing `extent` method."
        # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
        mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
        self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
        pnt = Point(5.23, 17.8)
        # Extent of points is just the point itself repeated.
        self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
        # Testing on the 'real world' Polygon.
        poly = fromstr(self.geometries.polygons[3].wkt)
        ring = poly.shell
        x, y = ring.x, ring.y
        xmin, ymin = min(x), min(y)
        xmax, ymax = max(x), max(y)
        self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)

    def test_pickle(self):

3 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_line_merge(self):
        "Testing line merge support"
        ref_geoms = (fromstr('LINESTRING(1 1, 1 1, 3 3)'),
                     fromstr('MULTILINESTRING((1 1, 3 3), (3 3, 4 2))'),
                     )
        ref_merged = (fromstr('LINESTRING(1 1, 3 3)'),
                      fromstr('LINESTRING (1 1, 3 3, 4 2)'),
                      )
        for geom, merged in zip(ref_geoms, ref_merged):
            self.assertEqual(merged, geom.merged)

    def test_valid_reason(self):

3 Source : test_geos_mutation.py
with Apache License 2.0
from gethue

    def test01_PointMutations(self):
        'Testing Point mutations'
        for p in (Point(1, 2, 3), fromstr('POINT (1 2 3)')):
            self.assertEqual(p._get_single_external(1), 2.0, 'Point _get_single_external')

            # _set_single
            p._set_single(0, 100)
            self.assertEqual(p.coords, (100.0, 2.0, 3.0), 'Point _set_single')

            # _set_list
            p._set_list(2, (50, 3141))
            self.assertEqual(p.coords, (50.0, 3141.0), 'Point _set_list')

    def test02_PointExceptions(self):

3 Source : test_geos_mutation.py
with Apache License 2.0
from gethue

    def test03_PointApi(self):
        'Testing Point API'
        q = Point(4, 5, 3)
        for p in (Point(1, 2, 3), fromstr('POINT (1 2 3)')):
            p[0:2] = [4, 5]
            for f in geos_function_tests:
                self.assertEqual(f(q), f(p), 'Point ' + f.__name__)

    def test04_LineStringMutations(self):

3 Source : test_geos_mutation.py
with Apache License 2.0
from gethue

    def test04_LineStringMutations(self):
        'Testing LineString mutations'
        for ls in (LineString((1, 0), (4, 1), (6, -1)),
                   fromstr('LINESTRING (1 0,4 1,6 -1)')):
            self.assertEqual(ls._get_single_external(1), (4.0, 1.0), 'LineString _get_single_external')

            # _set_single
            ls._set_single(0, (-50, 25))
            self.assertEqual(ls.coords, ((-50.0, 25.0), (4.0, 1.0), (6.0, -1.0)), 'LineString _set_single')

            # _set_list
            ls._set_list(2, ((-50.0, 25.0), (6.0, -1.0)))
            self.assertEqual(ls.coords, ((-50.0, 25.0), (6.0, -1.0)), 'LineString _set_list')

            lsa = LineString(ls.coords)
            for f in geos_function_tests:
                self.assertEqual(f(lsa), f(ls), 'LineString ' + f.__name__)

    def test05_Polygon(self):

3 Source : test_geos_mutation.py
with Apache License 2.0
from gethue

    def test06_Collection(self):
        'Testing Collection mutations'
        points = (
            MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))),
            fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)'),
        )
        for mp in points:
            self.assertEqual(mp._get_single_external(2), Point(5, -4), 'Collection _get_single_external')

            mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1))))
            self.assertEqual(mp.coords, ((5.0, 5.0), (3.0, -2.0), (8.0, 1.0)), 'Collection _set_list')

            lsa = MultiPoint(*map(Point, ((5, 5), (3, -2), (8, 1))))
            for f in geos_function_tests:
                self.assertEqual(f(lsa), f(mp), 'MultiPoint ' + f.__name__)

3 Source : tests.py
with Apache License 2.0
from lumanjiao

    def test_equals_lookups(self):
        "Testing the 'same_as' and 'equals' lookup types."
        pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326)
        c1 = City.objects.get(point=pnt)
        c2 = City.objects.get(point__same_as=pnt)
        c3 = City.objects.get(point__equals=pnt)
        for c in [c1, c2, c3]: self.assertEqual('Houston', c.name)

    @no_mysql

0 Source : process_upload.py
with MIT License
from acdh-oeaw

def import_shapes(shapefiles, source):
    adm_scheme, _ = SkosConceptScheme.objects.get_or_create(dc_title="administrative_unit")
    temp_spatial_ids = []
    for x in shapefiles:
        df = gp.read_file(x).to_crs({'proj': 'longlat', 'ellps': 'WGS84', 'datum': 'WGS84'})
        for i, row in df.iterrows():
            add_data = {}
            if row['geometry'].geom_type == 'MultiPolygon':
                mp = row['geometry'].wkt
            else:
                mp = geos.MultiPolygon(fromstr(row['geometry'].wkt))
            spat, _ = TempSpatial.objects.get_or_create(
                        start_date=row['start_date'],
                        end_date=row['end_date'],
                        date_accuracy=row['date_acc'],
                        geom=mp
                    )
            try:
                try:
                    adm, _ = SkosConcept.objects.get_or_create(
                        pref_label=row['adm_type']
                    )
                except IntegrityError:
                    adm, _ = SkosConcept.objects.get_or_create(
                        pref_label="unknown adm"
                    )
            except KeyError:
                adm, _ = SkosConcept.objects.get_or_create(
                    pref_label="unknown adm"
                )
            if adm is not None:
                adm.scheme.add(adm_scheme)
                spat.administrative_unit = adm
            try:
                if row['name']:
                    spat.name = row['name']
            except KeyError:
                pass
            try:
                if row['name_alt']:
                    spat.alt_name = row['name_alt']
            except KeyError:
                pass
            try:
                if row['id']:
                    spat.orig_id = row['id']
            except KeyError:
                pass
            try:
                if row['wiki_id']:
                    spat.wikidata_id = row['wiki_id']
            except KeyError:
                pass
            for x in list(df.keys()):
                if x not in mandatory_keys:
                    add_data[x] = row[x]
            spat.additional_data = json.dumps(add_data)
            spat.source = source
            try:
                spat.save()
                temp_spatial_ids.append(spat.id)
            except Exception as e:
                print(e)

    return temp_spatial_ids

0 Source : tests.py
with Apache License 2.0
from gethue

    def test_lookup_insert_transform(self):
        "Testing automatic transform for lookups and inserts."
        # San Antonio in 'WGS84' (SRID 4326)
        sa_4326 = 'POINT (-98.493183 29.424170)'
        wgs_pnt = fromstr(sa_4326, srid=4326)  # Our reference point in WGS84
        # San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857)
        other_srid_pnt = wgs_pnt.transform(3857, clone=True)
        # Constructing & querying with a point from a different SRID. Oracle
        # `SDO_OVERLAPBDYINTERSECT` operates differently from
        # `ST_Intersects`, so contains is used instead.
        if oracle:
            tx = Country.objects.get(mpoly__contains=other_srid_pnt)
        else:
            tx = Country.objects.get(mpoly__intersects=other_srid_pnt)
        self.assertEqual('Texas', tx.name)

        # Creating San Antonio.  Remember the Alamo.
        sa = City.objects.create(name='San Antonio', point=other_srid_pnt)

        # Now verifying that San Antonio was transformed correctly
        sa = City.objects.get(name='San Antonio')
        self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
        self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)

        # If the GeometryField SRID is -1, then we shouldn't perform any
        # transformation if the SRID of the input geometry is different.
        m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
        m1.save()
        self.assertEqual(-1, m1.geom.srid)

    def test_createnull(self):

0 Source : tests.py
with Apache License 2.0
from gethue

    def test_relate_lookup(self):
        "Testing the 'relate' lookup type."
        # To make things more interesting, we will have our Texas reference point in
        # different SRIDs.
        pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847)
        pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326)

        # Not passing in a geometry as first param should
        # raise a type error when initializing the GeoQuerySet
        with self.assertRaises(ValueError):
            Country.objects.filter(mpoly__relate=(23, 'foo'))

        # Making sure the right exception is raised for the given
        # bad arguments.
        for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]:
            qs = Country.objects.filter(mpoly__relate=bad_args)
            with self.assertRaises(e):
                qs.count()

        # Relate works differently for the different backends.
        if postgis or spatialite:
            contains_mask = 'T*T***FF*'
            within_mask = 'T*F**F***'
            intersects_mask = 'T********'
        elif oracle:
            contains_mask = 'contains'
            within_mask = 'inside'
            # TODO: This is not quite the same as the PostGIS mask above
            intersects_mask = 'overlapbdyintersect'

        # Testing contains relation mask.
        self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name)
        self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name)

        # Testing within relation mask.
        ks = State.objects.get(name='Kansas')
        self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name)

        # Testing intersection relation mask.
        if not oracle:
            self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name)
            self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name)
            self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name)


@ignore_warnings(category=RemovedInDjango20Warning)

0 Source : tests.py
with Apache License 2.0
from gethue

    def test_point_on_surface(self):
        "Testing the `point_on_surface` GeoQuerySet method."
        # Reference values.
        if oracle:
            # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05))
            # FROM GEOAPP_COUNTRY;
            ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326),
                   'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326),
                   }

        else:
            # Using GEOSGeometry to compute the reference point on surface values
            # -- since PostGIS also uses GEOS these should be the same.
            ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface,
                   'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface
                   }

        for c in Country.objects.point_on_surface():
            if spatialite:
                # XXX This seems to be a WKT-translation-related precision issue?
                tol = 0.00001
            else:
                tol = 0.000000001
            self.assertTrue(ref[c.name].equals_exact(c.point_on_surface, tol))

    @skipUnlessDBFeature("has_reverse_method")

0 Source : tests.py
with Apache License 2.0
from gethue

    def test_snap_to_grid(self):
        "Testing GeoQuerySet.snap_to_grid()."
        # Let's try and break snap_to_grid() with bad combinations of arguments.
        for bad_args in ((), range(3), range(5)):
            with self.assertRaises(ValueError):
                Country.objects.snap_to_grid(*bad_args)
        for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))):
            with self.assertRaises(TypeError):
                Country.objects.snap_to_grid(*bad_args)

        # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
        # from the world borders dataset he provides.
        wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,'
               '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,'
               '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,'
               '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,'
               '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,'
               '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,'
               '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,'
               '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))')
        Country.objects.create(name='San Marino', mpoly=fromstr(wkt))

        # Because floating-point arithmetic isn't exact, we set a tolerance
        # to pass into GEOS `equals_exact`.
        tol = 0.000000001

        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country"
        # WHERE "geoapp_country"."name" = 'San Marino';
        ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))')
        self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol))

        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country"
        # WHERE "geoapp_country"."name" = 'San Marino';
        ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))')
        self.assertTrue(
            ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol)
        )

        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country"
        # WHERE "geoapp_country"."name" = 'San Marino';
        ref = fromstr(
            'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))'
        )
        self.assertTrue(
            ref.equals_exact(
                Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid,
                tol
            )
        )

    @skipUnlessDBFeature("has_svg_method")

0 Source : tests.py
with Apache License 2.0
from gethue

    def test_transform(self):
        "Testing the transform() GeoQuerySet method."
        # Pre-transformed points for Houston and Pueblo.
        htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084)
        ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774)
        prec = 3  # Precision is low due to version variations in PROJ and GDAL.

        # Asserting the result of the transform operation with the values in
        #  the pre-transformed points.  Oracle does not have the 3084 SRID.
        if not oracle:
            h = City.objects.transform(htown.srid).get(name='Houston')
            self.assertEqual(3084, h.point.srid)
            self.assertAlmostEqual(htown.x, h.point.x, prec)
            self.assertAlmostEqual(htown.y, h.point.y, prec)

        p1 = City.objects.transform(ptown.srid, field_name='point').get(name='Pueblo')
        p2 = City.objects.transform(srid=ptown.srid).get(name='Pueblo')
        for p in [p1, p2]:
            self.assertEqual(2774, p.point.srid)
            self.assertAlmostEqual(ptown.x, p.point.x, prec)
            self.assertAlmostEqual(ptown.y, p.point.y, prec)

    @skipUnlessDBFeature("has_translate_method")

0 Source : tests.py
with Apache License 2.0
from gethue

    def test_unionagg_tolerance(self):
        City.objects.create(
            point=fromstr('POINT(-96.467222 32.751389)', srid=4326),
            name='Forney',
        )
        tx = Country.objects.get(name='Texas').mpoly
        # Tolerance is greater than distance between Forney and Dallas, that's
        # why Dallas is ignored.
        forney_houston = GEOSGeometry(
            'MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)',
            srid=4326,
        )
        self.assertIs(
            forney_houston.equals(
                City.objects.filter(point__within=tx).aggregate(
                    Union('point', tolerance=32000),
                )['point__union'],
            ),
            True,
        )

    @unittest.skipUnless(

0 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_point_on_surface(self):
        # Reference values.
        if oracle:
            # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05))
            # FROM GEOAPP_COUNTRY;
            ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326),
                   'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326),
                   }
        else:
            # Using GEOSGeometry to compute the reference point on surface values
            # -- since PostGIS also uses GEOS these should be the same.
            ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface,
                   'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface
                   }

        qs = Country.objects.annotate(point_on_surface=functions.PointOnSurface('mpoly'))
        for country in qs:
            tol = 0.00001  # SpatiaLite might have WKT-translation-related precision issues
            self.assertTrue(ref[country.name].equals_exact(country.point_on_surface, tol))

    @skipUnlessDBFeature("has_Reverse_function")

0 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_snap_to_grid(self):
        # Let's try and break snap_to_grid() with bad combinations of arguments.
        for bad_args in ((), range(3), range(5)):
            with self.assertRaises(ValueError):
                Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args))
        for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))):
            with self.assertRaises(TypeError):
                Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args))

        # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
        # from the world borders dataset he provides.
        wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,'
               '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,'
               '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,'
               '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,'
               '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,'
               '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,'
               '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,'
               '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))')
        Country.objects.create(name='San Marino', mpoly=fromstr(wkt))

        # Because floating-point arithmetic isn't exact, we set a tolerance
        # to pass into GEOS `equals_exact`.
        tol = 0.000000001

        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country"
        # WHERE "geoapp_country"."name" = 'San Marino';
        ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))')
        self.assertTrue(
            ref.equals_exact(
                Country.objects.annotate(
                    snap=functions.SnapToGrid('mpoly', 0.1)
                ).get(name='San Marino').snap,
                tol
            )
        )

        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country"
        # WHERE "geoapp_country"."name" = 'San Marino';
        ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))')
        self.assertTrue(
            ref.equals_exact(
                Country.objects.annotate(
                    snap=functions.SnapToGrid('mpoly', 0.05, 0.23)
                ).get(name='San Marino').snap,
                tol
            )
        )

        # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country"
        # WHERE "geoapp_country"."name" = 'San Marino';
        ref = fromstr(
            'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))'
        )
        self.assertTrue(
            ref.equals_exact(
                Country.objects.annotate(
                    snap=functions.SnapToGrid('mpoly', 0.05, 0.23, 0.5, 0.17)
                ).get(name='San Marino').snap,
                tol
            )
        )

    @skipUnlessDBFeature("has_SymDifference_function")

0 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_union(self):
        geom = Point(-95.363151, 29.763374, srid=4326)
        ptown = City.objects.annotate(union=functions.Union('point', geom)).get(name='Dallas')
        expected = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)', srid=4326)
        self.assertTrue(expected.equals(ptown.union))

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_errors(self):
        "Testing the Error handlers."
        # string-based
        for err in self.geometries.errors:
            with self.assertRaises((GEOSException, ValueError)):
                fromstr(err.wkt)

        # Bad WKB
        with self.assertRaises(GEOSException):
            GEOSGeometry(six.memoryview(b'0'))

        class NotAGeometry(object):
            pass

        # Some other object
        with self.assertRaises(TypeError):
            GEOSGeometry(NotAGeometry())
        # None
        with self.assertRaises(TypeError):
            GEOSGeometry(None)

    def test_wkb(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_points(self):
        "Testing Point objects."
        prev = fromstr('POINT(0 0)')
        for p in self.geometries.points:
            # Creating the point from the WKT
            pnt = fromstr(p.wkt)
            self.assertEqual(pnt.geom_type, 'Point')
            self.assertEqual(pnt.geom_typeid, 0)
            self.assertEqual(pnt.dims, 0)
            self.assertEqual(p.x, pnt.x)
            self.assertEqual(p.y, pnt.y)
            self.assertEqual(pnt, fromstr(p.wkt))
            self.assertEqual(False, pnt == prev)  # Use assertEqual to test __eq__

            # Making sure that the point's X, Y components are what we expect
            self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
            self.assertAlmostEqual(p.y, pnt.tuple[1], 9)

            # Testing the third dimension, and getting the tuple arguments
            if hasattr(p, 'z'):
                self.assertIs(pnt.hasz, True)
                self.assertEqual(p.z, pnt.z)
                self.assertEqual(p.z, pnt.tuple[2], 9)
                tup_args = (p.x, p.y, p.z)
                set_tup1 = (2.71, 3.14, 5.23)
                set_tup2 = (5.23, 2.71, 3.14)
            else:
                self.assertIs(pnt.hasz, False)
                self.assertIsNone(pnt.z)
                tup_args = (p.x, p.y)
                set_tup1 = (2.71, 3.14)
                set_tup2 = (3.14, 2.71)

            # Centroid operation on point should be point itself
            self.assertEqual(p.centroid, pnt.centroid.tuple)

            # Now testing the different constructors
            pnt2 = Point(tup_args)  # e.g., Point((1, 2))
            pnt3 = Point(*tup_args)  # e.g., Point(1, 2)
            self.assertEqual(pnt, pnt2)
            self.assertEqual(pnt, pnt3)

            # Now testing setting the x and y
            pnt.y = 3.14
            pnt.x = 2.71
            self.assertEqual(3.14, pnt.y)
            self.assertEqual(2.71, pnt.x)

            # Setting via the tuple/coords property
            pnt.tuple = set_tup1
            self.assertEqual(set_tup1, pnt.tuple)
            pnt.coords = set_tup2
            self.assertEqual(set_tup2, pnt.coords)

            prev = pnt  # setting the previous geometry

    def test_multipoints(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_multipoints(self):
        "Testing MultiPoint objects."
        for mp in self.geometries.multipoints:
            mpnt = fromstr(mp.wkt)
            self.assertEqual(mpnt.geom_type, 'MultiPoint')
            self.assertEqual(mpnt.geom_typeid, 4)
            self.assertEqual(mpnt.dims, 0)

            self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
            self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)

            with self.assertRaises(IndexError):
                mpnt.__getitem__(len(mpnt))
            self.assertEqual(mp.centroid, mpnt.centroid.tuple)
            self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))
            for p in mpnt:
                self.assertEqual(p.geom_type, 'Point')
                self.assertEqual(p.geom_typeid, 0)
                self.assertIs(p.empty, False)
                self.assertIs(p.valid, True)

    def test_linestring(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_linestring(self):
        "Testing LineString objects."
        prev = fromstr('POINT(0 0)')
        for l in self.geometries.linestrings:
            ls = fromstr(l.wkt)
            self.assertEqual(ls.geom_type, 'LineString')
            self.assertEqual(ls.geom_typeid, 1)
            self.assertEqual(ls.dims, 1)
            self.assertIs(ls.empty, False)
            self.assertIs(ls.ring, False)
            if hasattr(l, 'centroid'):
                self.assertEqual(l.centroid, ls.centroid.tuple)
            if hasattr(l, 'tup'):
                self.assertEqual(l.tup, ls.tuple)

            self.assertEqual(ls, fromstr(l.wkt))
            self.assertEqual(False, ls == prev)  # Use assertEqual to test __eq__
            with self.assertRaises(IndexError):
                ls.__getitem__(len(ls))
            prev = ls

            # Creating a LineString from a tuple, list, and numpy array
            self.assertEqual(ls, LineString(ls.tuple))  # tuple
            self.assertEqual(ls, LineString(*ls.tuple))  # as individual arguments
            self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple]))  # as list
            # Point individual arguments
            self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt)
            if numpy:
                self.assertEqual(ls, LineString(numpy.array(ls.tuple)))  # as numpy array

        with self.assertRaisesMessage(TypeError, 'Each coordinate should be a sequence (list or tuple)'):
            LineString((0, 0))

        with self.assertRaisesMessage(ValueError, 'LineString requires at least 2 points, got 1.'):
            LineString([(0, 0)])

        if numpy:
            with self.assertRaisesMessage(ValueError, 'LineString requires at least 2 points, got 1.'):
                LineString(numpy.array([(0, 0)]))

        with mock.patch('django.contrib.gis.geos.linestring.numpy', False):
            with self.assertRaisesMessage(TypeError, 'Invalid initialization input for LineStrings.'):
                LineString('wrong input')

    def test_multilinestring(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_multilinestring(self):
        "Testing MultiLineString objects."
        prev = fromstr('POINT(0 0)')
        for l in self.geometries.multilinestrings:
            ml = fromstr(l.wkt)
            self.assertEqual(ml.geom_type, 'MultiLineString')
            self.assertEqual(ml.geom_typeid, 5)
            self.assertEqual(ml.dims, 1)

            self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
            self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)

            self.assertEqual(ml, fromstr(l.wkt))
            self.assertEqual(False, ml == prev)  # Use assertEqual to test __eq__
            prev = ml

            for ls in ml:
                self.assertEqual(ls.geom_type, 'LineString')
                self.assertEqual(ls.geom_typeid, 1)
                self.assertIs(ls.empty, False)

            with self.assertRaises(IndexError):
                ml.__getitem__(len(ml))
            self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
            self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))

    def test_linearring(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_linearring(self):
        "Testing LinearRing objects."
        for rr in self.geometries.linearrings:
            lr = fromstr(rr.wkt)
            self.assertEqual(lr.geom_type, 'LinearRing')
            self.assertEqual(lr.geom_typeid, 2)
            self.assertEqual(lr.dims, 1)
            self.assertEqual(rr.n_p, len(lr))
            self.assertIs(lr.valid, True)
            self.assertIs(lr.empty, False)

            # Creating a LinearRing from a tuple, list, and numpy array
            self.assertEqual(lr, LinearRing(lr.tuple))
            self.assertEqual(lr, LinearRing(*lr.tuple))
            self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
            if numpy:
                self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))

        with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 3.'):
            LinearRing((0, 0), (1, 1), (0, 0))

        with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 1.'):
            LinearRing([(0, 0)])

        if numpy:
            with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 1.'):
                LinearRing(numpy.array([(0, 0)]))

    def test_polygons_from_bbox(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_polygons(self):
        "Testing Polygon objects."

        prev = fromstr('POINT(0 0)')
        for p in self.geometries.polygons:
            # Creating the Polygon, testing its properties.
            poly = fromstr(p.wkt)
            self.assertEqual(poly.geom_type, 'Polygon')
            self.assertEqual(poly.geom_typeid, 3)
            self.assertEqual(poly.dims, 2)
            self.assertIs(poly.empty, False)
            self.assertIs(poly.ring, False)
            self.assertEqual(p.n_i, poly.num_interior_rings)
            self.assertEqual(p.n_i + 1, len(poly))  # Testing __len__
            self.assertEqual(p.n_p, poly.num_points)

            # Area & Centroid
            self.assertAlmostEqual(p.area, poly.area, 9)
            self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
            self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)

            # Testing the geometry equivalence
            self.assertEqual(poly, fromstr(p.wkt))
            # Should not be equal to previous geometry
            self.assertEqual(False, poly == prev)  # Use assertEqual to test __eq__
            self.assertNotEqual(poly, prev)  # Use assertNotEqual to test __ne__

            # Testing the exterior ring
            ring = poly.exterior_ring
            self.assertEqual(ring.geom_type, 'LinearRing')
            self.assertEqual(ring.geom_typeid, 2)
            if p.ext_ring_cs:
                self.assertEqual(p.ext_ring_cs, ring.tuple)
                self.assertEqual(p.ext_ring_cs, poly[0].tuple)  # Testing __getitem__

            # Testing __getitem__ and __setitem__ on invalid indices
            with self.assertRaises(IndexError):
                poly.__getitem__(len(poly))
            with self.assertRaises(IndexError):
                poly.__setitem__(len(poly), False)
            with self.assertRaises(IndexError):
                poly.__getitem__(-1 * len(poly) - 1)

            # Testing __iter__
            for r in poly:
                self.assertEqual(r.geom_type, 'LinearRing')
                self.assertEqual(r.geom_typeid, 2)

            # Testing polygon construction.
            with self.assertRaises(TypeError):
                Polygon(0, [1, 2, 3])
            with self.assertRaises(TypeError):
                Polygon('foo')

            # Polygon(shell, (hole1, ... holeN))
            rings = tuple(r for r in poly)
            self.assertEqual(poly, Polygon(rings[0], rings[1:]))

            # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
            ring_tuples = tuple(r.tuple for r in poly)
            self.assertEqual(poly, Polygon(*ring_tuples))

            # Constructing with tuples of LinearRings.
            self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
            self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)

    def test_polygons_templates(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_multipolygons(self):
        "Testing MultiPolygon objects."
        fromstr('POINT (0 0)')
        for mp in self.geometries.multipolygons:
            mpoly = fromstr(mp.wkt)
            self.assertEqual(mpoly.geom_type, 'MultiPolygon')
            self.assertEqual(mpoly.geom_typeid, 6)
            self.assertEqual(mpoly.dims, 2)
            self.assertEqual(mp.valid, mpoly.valid)

            if mp.valid:
                self.assertEqual(mp.num_geom, mpoly.num_geom)
                self.assertEqual(mp.n_p, mpoly.num_coords)
                self.assertEqual(mp.num_geom, len(mpoly))
                with self.assertRaises(IndexError):
                    mpoly.__getitem__(len(mpoly))
                for p in mpoly:
                    self.assertEqual(p.geom_type, 'Polygon')
                    self.assertEqual(p.geom_typeid, 3)
                    self.assertIs(p.valid, True)
                self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)

    def test_memory_hijinks(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_memory_hijinks(self):
        "Testing Geometry __del__() on rings and polygons."
        # #### Memory issues with rings and poly

        # These tests are needed to ensure sanity with writable geometries.

        # Getting a polygon with interior rings, and pulling out the interior rings
        poly = fromstr(self.geometries.polygons[1].wkt)
        ring1 = poly[0]
        ring2 = poly[1]

        # These deletes should be 'harmless' since they are done on child geometries
        del ring1
        del ring2
        ring1 = poly[0]
        ring2 = poly[1]

        # Deleting the polygon
        del poly

        # Access to these rings is OK since they are clones.
        str(ring1)
        str(ring2)

    def test_coord_seq(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_coord_seq(self):
        "Testing Coordinate Sequence objects."
        for p in self.geometries.polygons:
            if p.ext_ring_cs:
                # Constructing the polygon and getting the coordinate sequence
                poly = fromstr(p.wkt)
                cs = poly.exterior_ring.coord_seq

                self.assertEqual(p.ext_ring_cs, cs.tuple)  # done in the Polygon test too.
                self.assertEqual(len(p.ext_ring_cs), len(cs))  # Making sure __len__ works

                # Checks __getitem__ and __setitem__
                for i in range(len(p.ext_ring_cs)):
                    c1 = p.ext_ring_cs[i]  # Expected value
                    c2 = cs[i]  # Value from coordseq
                    self.assertEqual(c1, c2)

                    # Constructing the test value to set the coordinate sequence with
                    if len(c1) == 2:
                        tset = (5, 23)
                    else:
                        tset = (5, 23, 8)
                    cs[i] = tset

                    # Making sure every set point matches what we expect
                    for j in range(len(tset)):
                        cs[i] = tset
                        self.assertEqual(tset[j], cs[i][j])

    def test_relate_pattern(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_buffer(self):
        "Testing buffer()."
        for bg in self.geometries.buffer_geoms:
            g = fromstr(bg.wkt)

            # The buffer we expect
            exp_buf = fromstr(bg.buffer_wkt)
            quadsegs = bg.quadsegs
            width = bg.width

            # Can't use a floating-point for the number of quadsegs.
            with self.assertRaises(ctypes.ArgumentError):
                g.buffer(width, float(quadsegs))

            # Constructing our buffer
            buf = g.buffer(width, quadsegs)
            self.assertEqual(exp_buf.num_coords, buf.num_coords)
            self.assertEqual(len(exp_buf), len(buf))

            # Now assuring that each point in the buffer is almost equal
            for j in range(len(exp_buf)):
                exp_ring = exp_buf[j]
                buf_ring = buf[j]
                self.assertEqual(len(exp_ring), len(buf_ring))
                for k in range(len(exp_ring)):
                    # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
                    self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
                    self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)

    def test_covers(self):

0 Source : test_geos.py
with Apache License 2.0
from gethue

    def test_srid(self):
        "Testing the SRID property and keyword."
        # Testing SRID keyword on Point
        pnt = Point(5, 23, srid=4326)
        self.assertEqual(4326, pnt.srid)
        pnt.srid = 3084
        self.assertEqual(3084, pnt.srid)
        with self.assertRaises(ctypes.ArgumentError):
            pnt.srid = '4326'

        # Testing SRID keyword on fromstr(), and on Polygon rings.
        poly = fromstr(self.geometries.polygons[1].wkt, srid=4269)
        self.assertEqual(4269, poly.srid)
        for ring in poly:
            self.assertEqual(4269, ring.srid)
        poly.srid = 4326
        self.assertEqual(4326, poly.shell.srid)

        # Testing SRID keyword on GeometryCollection
        gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)
        self.assertEqual(32021, gc.srid)
        for i in range(len(gc)):
            self.assertEqual(32021, gc[i].srid)

        # GEOS may get the SRID from HEXEWKB
        # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
        # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
        hex = '0101000020E610000000000000000014400000000000003740'
        p1 = fromstr(hex)
        self.assertEqual(4326, p1.srid)

        p2 = fromstr(p1.hex)
        self.assertIsNone(p2.srid)
        p3 = fromstr(p1.hex, srid=-1)  # -1 is intended.
        self.assertEqual(-1, p3.srid)

        # Testing that geometry SRID could be set to its own value
        pnt_wo_srid = Point(1, 1)
        pnt_wo_srid.srid = pnt_wo_srid.srid

    def test_custom_srid(self):

See More Examples