def test_textsymbolizer_pickle(): ts = mapnik2.TextSymbolizer(mapnik2.Expression('[Field_Name]'), 'Font Name', 8, mapnik2.Color('black')) eq_(str(ts.name), str(mapnik2.Expression('[Field_Name]'))) eq_(ts.face_name, 'Font Name') eq_(ts.text_size, 8) eq_(ts.fill, mapnik2.Color('black')) raise Todo("text_symbolizer pickling currently disabled") ts2 = pickle.loads(pickle.dumps(ts, pickle.HIGHEST_PROTOCOL)) eq_(ts.name, ts2.name) eq_(ts.face_name, ts2.face_name) eq_(ts.allow_overlap, ts2.allow_overlap) eq_(ts.displacement, ts2.displacement) eq_(ts.anchor, ts2.anchor) eq_(ts.fill, ts2.fill) eq_(ts.force_odd_labels, ts2.force_odd_labels) eq_(ts.halo_fill, ts2.halo_fill) eq_(ts.halo_radius, ts2.halo_radius) eq_(ts.label_placement, ts2.label_placement) eq_(ts.minimum_distance, ts2.minimum_distance) eq_(ts.text_ratio, ts2.text_ratio) eq_(ts.text_size, ts2.text_size) eq_(ts.wrap_width, ts2.wrap_width) eq_(ts.vertical_alignment, ts2.vertical_alignment) eq_(ts.label_spacing, ts2.label_spacing) eq_(ts.label_position_tolerance, ts2.label_position_tolerance) # 22.5 * M_PI/180.0 initialized by default assert_almost_equal(s.max_char_angle_delta, 0.39269908169872414) eq_(ts.wrap_character, ts2.wrap_character) eq_(ts.text_transform, ts2.text_transform) eq_(ts.line_spacing, ts2.line_spacing) eq_(ts.character_spacing, ts2.character_spacing) # r1341 eq_(ts.wrap_before, ts2.wrap_before) eq_(ts.horizontal_alignment, ts2.horizontal_alignment) eq_(ts.justify_alignment, ts2.justify_alignment) eq_(ts.opacity, ts2.opacity) # r2300 eq_(s.minimum_padding, 0.0) raise Todo( "FontSet pickling support needed: http://trac.mapnik2.org/ticket/348") eq_(ts.fontset, ts2.fontset)
def test_map_init_from_string(): map_string = '''<Map background-color="steelblue" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"> <Style name="My Style"> <Rule> <PolygonSymbolizer> <CssParameter name="fill">#f2eff9</CssParameter> </PolygonSymbolizer> <LineSymbolizer> <CssParameter name="stroke">rgb(50%,50%,50%)</CssParameter> <CssParameter name="stroke-width">0.1</CssParameter> </LineSymbolizer> </Rule> </Style> <Layer name="boundaries"> <StyleName>My Style</StyleName> <Datasource> <Parameter name="type">shape</Parameter> <Parameter name="file">../../demo/data/boundaries</Parameter> </Datasource> </Layer> </Map>''' m = mapnik2.Map(600, 300) mapnik2.load_map_from_string(m, map_string) mapnik2.load_map_from_string(m, map_string, False, "") mapnik2.load_map_from_string(m, map_string, True, "") raise(Todo("Need to write more map property tests in 'object_test.py'..."))
def test_shieldsymbolizer_init(): s = mapnik.ShieldSymbolizer( mapnik.Expression('[Field Name]'), 'DejaVu Sans Bold', 6, mapnik.Color('#000000'), mapnik.PathExpression('../data/images/dummy.png')) eq_(s.anchor, ( 0.0, 0.5, )) eq_(s.displacement, (0.0, 0.0)) eq_(s.allow_overlap, False) eq_(s.avoid_edges, False) eq_(s.character_spacing, 0) eq_(str(s.name), str(mapnik.Expression('[Field Name]'))) eq_(s.face_name, 'DejaVu Sans Bold') eq_(s.allow_overlap, False) eq_(s.fill, mapnik.Color('#000000')) eq_(s.force_odd_labels, False) eq_(s.halo_fill, mapnik.Color('rgb(255,255,255)')) eq_(s.halo_radius, 0) eq_(s.label_placement, mapnik.label_placement.POINT_PLACEMENT) eq_(s.minimum_distance, 0.0) eq_(s.text_ratio, 0) eq_(s.text_size, 6) eq_(s.wrap_width, 0) eq_(s.vertical_alignment, mapnik.vertical_alignment.MIDDLE) eq_(s.label_spacing, 0) eq_(s.label_position_tolerance, 0) # 22.5 * M_PI/180.0 initialized by default assert_almost_equal(s.max_char_angle_delta, 0.39269908169872414) eq_(s.wrap_character, ' ') eq_(s.text_transform, mapnik.text_transform.NONE) eq_(s.line_spacing, 0) eq_(s.character_spacing, 0) # r1341 eq_(s.wrap_before, False) eq_(s.horizontal_alignment, mapnik.horizontal_alignment.MIDDLE) eq_(s.justify_alignment, mapnik.justify_alignment.MIDDLE) eq_(s.opacity, 1.0) # r2300 eq_(s.minimum_padding, 0.0) # was mixed with s.opacity eq_(s.text_opacity, 1.0) eq_(s.shield_displacement, (0.0, 0.0)) # TODO - the pattern in bindings seems to be to get/set # strings for PathExpressions... should we pass objects? eq_(s.filename, '../data/images/dummy.png') eq_(s.transform, 'matrix(1, 0, 0, 1, 0, 0)') raise Todo( "FontSet pickling support needed: http://trac.mapnik.org/ticket/348") eq_(s.fontset, '')
def test_pointsymbolizer_pickle(): raise Todo("point_symbolizer pickling currently disabled") p = mapnik2.PointSymbolizer(mapnik2.PathExpression("../data/images/dummy.png")) p2 = pickle.loads(pickle.dumps(p,pickle.HIGHEST_PROTOCOL)) # image type, width, and height only used in contructor... eq_(p.filename, p2.filename) eq_(p.allow_overlap, p2.allow_overlap) eq_(p.opacity, p2.opacity) eq_(p.ignore_placement, p2.ignore_placement) eq_(p.placement, p2.placement)
def test_map_pickle(): # Fails due to scale() not matching, possibly other things raise (Todo("Map does not support pickling yet (Tickets #345).")) m = mapnik.Map(256, 256) eq_(pickle.loads(pickle.dumps(m)), m) m = mapnik.Map(256, 256, '+proj=latlong') eq_(pickle.loads(pickle.dumps(m)), m)
def test_render_points(): # Test for effectivenes of ticket #402 (borderline points get lost on reprojection) raise Todo("See: http://trac.mapnik2.org/ticket/402") if not mapnik2.has_pycairo(): return # create and populate point datasource (WGS84 lat-lon coordinates) places_ds = mapnik2.PointDatasource() places_ds.add_point(142.48, -38.38, 'Name', 'Westernmost Point') # westernmost places_ds.add_point(143.10, -38.60, 'Name', 'Southernmost Point') # southernmost # create layer/rule/style s = mapnik2.Style() r = mapnik2.Rule() symb = mapnik2.PointSymbolizer() symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84') lyr.datasource = places_ds lyr.styles.append('places_labels') # latlon bounding box corners ul_lonlat = mapnik2.Coord(142.30, -38.20) lr_lonlat = mapnik2.Coord(143.40, -38.80) # render for different projections projs = { 'latlon': '+proj=latlon +datum=WGS84', 'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs', 'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m', 'utm': '+proj=utm +zone=54 +datum=WGS84' } from cairo import SVGSurface for projdescr in projs.iterkeys(): m = mapnik2.Map(1000, 500, projs[projdescr]) m.append_style('places_labels', s) m.layers.append(lyr) p = mapnik2.Projection(projs[projdescr]) m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat))) # Render to SVG so that it can be checked how many points are there with string comparison import StringIO svg_memory_file = StringIO.StringIO() surface = SVGSurface(svg_memory_file, m.width, m.height) mapnik2.render(m, surface) surface.flush() surface.finish() svg = svg_memory_file.getvalue() svg_memory_file.close() num_points_present = len(places_ds.all_features()) num_points_rendered = svg.count('<image ') eq_( num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr))
def test_python_extended_constructor(self): try: from shapely.geometry import Point except ImportError: raise Todo("Make this test not dependant on shapely") f = self.makeOne(1, Point(3, 6), foo="bar") self.failUnlessEqual(f['foo'], 'bar') env = f.geometry.envelope() self.failUnlessEqual(env.minx, 3) self.failUnlessEqual(env.miny, 6)
def test_that_nonexistant_query_field_throws(**kwargs): raise Todo("fixme") ds = mapnik.Osm(file='../data/osm/nodes.osm') # ugh, more odd stuff hardcoded... eq_(len(ds.fields()), 5) eq_(ds.fields(), ['bicycle', 'foot', 'horse', 'name', 'width']) eq_(ds.field_types(), ['str', 'str', 'str', 'str', 'str']) query = mapnik.Query(ds.envelope()) for fld in ds.fields(): query.add_property_name(fld) # also add an invalid one, triggering throw query.add_property_name('bogus') fs = ds.features(query)
def test_map_init_from_string(): map_string = '''<Map background-color="steelblue" base="./" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"> <Style name="My Style"> <Rule> <PolygonSymbolizer> <CssParameter name="fill">#f2eff9</CssParameter> </PolygonSymbolizer> <LineSymbolizer> <CssParameter name="stroke">rgb(50%,50%,50%)</CssParameter> <CssParameter name="stroke-width">0.1</CssParameter> </LineSymbolizer> </Rule> </Style> <Layer name="boundaries"> <StyleName>My Style</StyleName> <Datasource> <Parameter name="type">shape</Parameter> <Parameter name="file">../../demo/data/boundaries</Parameter> </Datasource> </Layer> </Map>''' m = mapnik.Map(600, 300) eq_(m.base, '') try: mapnik.load_map_from_string(m, map_string) eq_(m.base, './') mapnik.load_map_from_string(m, map_string, False, "") # this "" will have no effect eq_(m.base, './') tmp_dir = tempfile.gettempdir() try: mapnik.load_map_from_string(m, map_string, False, tmp_dir) except RuntimeError: pass # runtime error expected because shapefile path should be wrong and datasource will throw eq_( m.base, tmp_dir ) # tmp_dir will be set despite the exception because load_map mostly worked m.base = 'foo' mapnik.load_map_from_string(m, map_string, True, ".") eq_(m.base, '.') raise (Todo( "Need to write more map property tests in 'object_test.py'...")) except RuntimeError, e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(e)
def test(): # TODO: Write a better test # 1. Construct map in memory # 2. Save map as XML # 3. Load map to a second object # 4. Compare both map objects map = mapnik.Map(256, 256) raise Todo( "map comparison is currently broken due to lacking relative paths support (#324,#340" ) def compare_map(in_map): mapnik.load_map(map, in_map) (handle, test_map) = tempfile.mkstemp(suffix='.xml', prefix='mapnik-temp-map1-') os.close(handle) (handle, test_map2) = tempfile.mkstemp(suffix='.xml', prefix='mapnik-temp-map2-') os.close(handle) if os.path.exists(test_map): os.remove(test_map) mapnik.save_map(map, test_map) new_map = mapnik.Map(256, 256) mapnik.load_map(new_map, test_map) open(test_map2, 'w').write(mapnik.save_map_to_string(new_map)) diff = ' diff %s %s' % (os.path.abspath(test_map), os.path.abspath(test_map2)) try: eq_(open(test_map).read(), open(test_map2).read()) except AssertionError, e: raise AssertionError( 'serialized map "%s" not the same after being reloaded, \ncompare with command:\n\n$%s' % (in_map, diff)) if os.path.exists(test_map): os.remove(test_map) else: # Fail, the map wasn't written return False
def test_feature_hit_count(): raise Todo("need to optimize multigeom bbox handling in shapeindex") # results in different results between shp and ogr! #bbox = (-14284551.8434, 2074195.1992, -7474929.8687, 8140237.7628) bbox = (1113194.91, 4512803.085, 2226389.82, 6739192.905) query = mapnik.Query(mapnik.Box2d(*bbox)) if 'ogr' in mapnik.DatasourceCache.instance().plugin_names(): ds1 = mapnik.Ogr(file='../data/shp/world_merc.shp', layer_by_index=0) for fld in ds1.fields(): query.add_property_name(fld) ds2 = mapnik.Shapefile(file='../data/shp/world_merc.shp') count1 = len(ds1.features(query).features) count2 = len(ds2.features(query).features) eq_( count1, count2, "Feature count differs between OGR driver (%s features) and Shapefile Driver (%s features) when querying the same bbox" % (count1, count2))
def test_add_feature(self): try: from shapely.geometry import Point except ImportError: raise Todo("Make this test not dependant on shapely") md = self.makeOne() self.failUnlessEqual(md.num_features(), 0) md.add_feature(self.makeFeature(Point(2, 3), foo='bar')) self.failUnlessEqual(md.num_features(), 1) from mapnik2 import Coord retrieved = md.features_at_point(Coord(2, 3)).features self.failUnlessEqual(len(retrieved), 1) f = retrieved[0] self.failUnlessEqual(f['foo'], 'bar') retrieved = md.features_at_point(Coord(20, 30)).features self.failUnlessEqual(len(retrieved), 0)
def test_add_wkb_geometry(self): try: from shapely.geometry import Point except ImportError: raise Todo("Make this test not dependant on shapely") def add_it(geometry): f = self.makeOne(1) self.failUnlessEqual(len(f.geometries), 0) f.add_geometry(geometry) self.failUnlessEqual(len(f.geometries), 1) env = f.geometry.envelope() self.failUnlessEqual(env.minx, 3) self.failUnlessEqual(env.minx, env.maxx) self.failUnlessEqual(env.miny, 6) self.failUnlessEqual(env.miny, env.maxy) geometries = (Point(3, 6), 'POINT(3 6)', Point(3, 6).wkb) for geom in geometries: add_it(geom)
def test_background_image_with_alpha_and_background_color_against_composited_control( ): m = mapnik.Map(10, 10) m.background = mapnik.Color('rgba(255,255,255,.5)') m.background_image = '../data/images/yellow_half_trans.png' im = mapnik.Image(m.width, m.height) mapnik.render(m, im) # create and composite the expected result im1 = mapnik.Image(10, 10) im1.background = mapnik.Color('rgba(255,255,255,.5)') im1.premultiply() im2 = mapnik.Image(10, 10) im2.background = mapnik.Color('rgba(255,255,0,.5)') im2.premultiply() im1.composite(im2) im1.demultiply() # compare image rendered (compositing in `agg_renderer<T>::setup`) # vs image composited via python bindings raise Todo("looks like we need to investigate PNG rounding when saving") eq_(get_unique_colors(im), get_unique_colors(im1))
def test_wkt_collection_flattening(): raise Todo("fixme or remove test") # currently fails as the MULTIPOLYGON inside will be returned as multiple polygons - not a huge deal - should we worry? wkt = "GEOMETRYCOLLECTION(POLYGON((1 1,2 1,2 2,1 2,1 1)),MULTIPOLYGON(((40 40,20 45,45 30,40 40)),((20 35,45 20,30 5,10 10,10 30,20 35),(30 20,20 25,20 15,30 20))),LINESTRING(2 3,3 4))" compare_wkt_from_wkt(wkt, 4)
def test_wkt_rounding(): raise Todo("fixme or remove test") # currently fails because we use output precision of 6 - should we make configurable? https://github.com/mapnik/mapnik/issues/1009 # if precision is set to 15 still fails due to very subtle rounding issues wkt = "POLYGON((7.904185417583761 54.180426336712856,7.89918053477129 54.178168035931542,7.897715691021261 54.182318426556606,7.893565300396205 54.183111883587891,7.89039147227129 54.187567449994106,7.885874870708761 54.190680242962827,7.879893425396261 54.193915106244049,7.894541862896233 54.194647528119134,7.900645378521233 54.190680242962827,7.904185417583761 54.180426336712856))" compare_wkt_from_wkt(wkt, 1)