def setUp(self): self.keyword_io = KeywordIO() uri = QgsDataSourceURI() uri.setDatabase(os.path.join(TESTDATA, 'jk.sqlite')) uri.setDataSource('', 'osm_buildings', 'Geometry') self.sqlite_layer = QgsVectorLayer( uri.uri(), 'OSM Buildings', 'spatialite') hazard_path = os.path.join(HAZDATA, 'Shakemap_Padang_2009.asc') self.raster_layer, layer_type = load_layer( hazard_path, directory=None) del layer_type self.vector_layer, layer_type = load_layer('Padang_WGS84.shp') del layer_type self.expected_sqlite_keywords = { 'category': 'exposure', 'datatype': 'OSM', 'subcategory': 'building'} self.expected_vector_keywords = { 'category': 'exposure', 'datatype': 'itb', 'subcategory': 'structure', 'title': 'Padang WGS84'} self.expected_raster_keywords = { 'category': 'hazard', 'source': 'USGS', 'subcategory': 'earthquake', 'unit': 'MMI', 'title': ('An earthquake in Padang ' 'like in 2009')}
def test_zonal_with_exact_cell_boundaries(self): """Test that zonal stats returns the expected output.""" myRasterLayer, _ = load_layer(os.path.join( UNITDATA, 'other', 'tenbytenraster.asc')) # Note this is a matrix of 11x11 polys - one per cell # and one poly extending beyond to the right of each row # and one poly extending beyond the bottom of each col myVectorLayer, _ = load_layer(os.path.join( UNITDATA, 'other', 'ten_by_ten_raster_as_polys.shp')) myResult = calculate_zonal_stats( raster_layer=myRasterLayer, polygon_layer=myVectorLayer) myExpectedResult = { 0L: {'count': 1.0, 'sum': 0.0, 'mean': 0.0}, # TL polygon 9L: {'count': 1.0, 'sum': 9.0, 'mean': 9.0}, # TR polygon 25L: {'count': 1.0, 'sum': 3.0, 'mean': 3.0}, # Central polygon 88L: {'count': 1.0, 'sum': 0.0, 'mean': 0.0}, # BL polygon 108L: {'count': 1.0, 'sum': 9.0, 'mean': 9.0}} # BR polygon # We will just check TL, TR, Middle, BL and BR cells myResult = { 0L: myResult[0L], 9L: myResult[9L], 25L: myResult[25L], 88L: myResult[88L], 108L: myResult[108L]} self.maxDiff = None self.assertDictEqual(myExpectedResult, myResult)
def register_layers(self): """Register needed layers to QgsMapLayerRegistry.""" # Register 4 impact layers and aggregation layer self.population_entire_jakarta_layer, _ = load_layer( population_entire_jakarta_impact_path, directory=None) self.building_entire_jakarta_layer, _ = load_layer( building_entire_jakarta_impact_path, directory=None) self.population_district_jakarta_layer, _ = load_layer( population_district_jakarta_impact_path, directory=None) self.building_district_jakarta_layer, _ = load_layer( building_district_jakarta_impact_path, directory=None) self.district_jakarta_layer, _ = load_layer( district_jakarta_boundary_path, directory=None) layer_list = [self.population_entire_jakarta_layer, self.population_district_jakarta_layer, self.building_entire_jakarta_layer, self.building_district_jakarta_layer, self.district_jakarta_layer] # noinspection PyArgumentList self.map_layer_registry.addMapLayers(layer_list)
def test_zonal_with_exact_cell_boundaries(self): """Test that zonal stats returns the expected output.""" raster_layer, _ = load_layer(os.path.join( UNITDATA, 'other', 'tenbytenraster.asc')) # Note this is a matrix of 11x11 polygons - one per cell # and one poly extending beyond to the right of each row # and one poly extending beyond the bottom of each col vector_layer, _ = load_layer(os.path.join( UNITDATA, 'other', 'ten_by_ten_raster_as_polys.shp')) result = calculate_zonal_stats( raster_layer=raster_layer, polygon_layer=vector_layer) expected_result = { 0L: {'count': 1.0, 'sum': 0.0, 'mean': 0.0}, # TL polygon 9L: {'count': 1.0, 'sum': 9.0, 'mean': 9.0}, # TR polygon 25L: {'count': 1.0, 'sum': 3.0, 'mean': 3.0}, # Central polygon 88L: {'count': 1.0, 'sum': 0.0, 'mean': 0.0}, # BL polygon 108L: {'count': 1.0, 'sum': 9.0, 'mean': 9.0}} # BR polygon # We will just check TL, TR, Middle, BL and BR cells result = { 0L: result[0L], 9L: result[9L], 25L: result[25L], 88L: result[88L], 108L: result[108L]} # noinspection PyPep8Naming self.maxDiff = None self.assertDictEqual(expected_result, result)
def test_transparency_of_minimum_value(self): """Test that transparency of minimum value works when set to 100% """ # This dataset has all cells with value 1.3 myLayer, _ = load_layer('issue126.tif') # Note the float quantity values below myStyleInfo = {'style_classes': [ {'colour': '#FFFFFF', 'transparency': 100, 'quantity': 0.0}, {'colour': '#38A800', 'quantity': 0.038362596547925065, 'transparency': 0, 'label': u'Rendah [0 orang/sel]'}, {'colour': '#79C900', 'transparency': 0, 'quantity': 0.07672519309585013}, {'colour': '#CEED00', 'transparency': 0, 'quantity': 0.1150877896437752}, {'colour': '#FFCC00', 'quantity': 0.15345038619170026, 'transparency': 0, 'label': u'Sedang [0 orang/sel]'}, {'colour': '#FF6600', 'transparency': 0, 'quantity': 0.19181298273962533}, {'colour': '#FF0000', 'transparency': 0, 'quantity': 0.23017557928755039}, {'colour': '#7A0000', 'quantity': 0.26853817583547546, 'transparency': 0, 'label': u'Tinggi [0 orang/sel]'}]} try: setRasterStyle(myLayer, myStyleInfo) except Exception, e: myMessage = '\nCould not create raster style' e.args = (e.args[0] + myMessage,) raise
def test_issue121(self): """Test that point symbol size can be set from style (issue 121). .. seealso:: https://github.com/AIFDR/inasafe/issues/121 """ myLayer, myType = load_layer('kecamatan_jakarta_osm_centroids.shp') del myType # Note the float quantity values below myStyleInfo = {'target_field': 'KEPADATAN', 'style_classes': [ {'opacity': 1, 'max': 200, 'colour': '#fecc5c', 'min': 45, 'label': 'Low', 'size': 1}, {'opacity': 1, 'max': 350, 'colour': '#fd8d3c', 'min': 201, 'label': 'Medium', 'size': 2}, {'opacity': 1, 'max': 539, 'colour': '#f31a1c', 'min': 351, 'label': 'High', 'size': 3}]} myMessage = 'Setting style with point sizes should work.' try: set_vector_graduated_style(myLayer, myStyleInfo) except: raise Exception(myMessage) # Now validate the size values were set as expected # new symbology - subclass of QgsFeatureRendererV2 class myRenderer = myLayer.rendererV2() myType = myRenderer.type() assert myType == 'graduatedSymbol' mySize = 1 for myRange in myRenderer.ranges(): mySymbol = myRange.symbol() mySymbolLayer = mySymbol.symbolLayer(0) myActualSize = mySymbolLayer.size() myMessage = (('Expected symbol layer 0 for range %s to have' ' a size of %s, got %s') % (mySize, mySize, myActualSize)) assert mySize == myActualSize, myMessage mySize += 1
def test_getVectorLegend(self): """Getting a legend for a vector layer works. @note This test is not related do thousand separator since we insert our own legend notes and our own layer. """ myLayer, _ = load_layer('test_shakeimpact.shp') myMapLegend = MapLegend( myLayer, theLegendNotes='Thousand separator represented by \',\'', theLegendUnits='(people per cell)') myImage = myMapLegend.getVectorLegend() myPath = unique_filename( prefix='getVectorLegend', suffix='.png', dir=temp_dir('test')) myImage.save(myPath, 'PNG') LOGGER.debug(myPath) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. myTolerance = 0 # to allow for version number changes in disclaimer myFlag, myMessage = check_images( 'getVectorLegend', myPath, myTolerance) myMessage += ('\nWe want these images to match, if they do already ' 'copy the test image generated to create a new control ' 'image.') assert myFlag, myMessage
def test_addSymbolToLegend(self): """Test we can add a symbol to the legend.""" myLayer, _ = load_layer('test_floodimpact.tif') myMapLegend = MapLegend(myLayer) mySymbol = QgsSymbol() mySymbol.setColor(QtGui.QColor(12, 34, 56)) myMapLegend.addSymbolToLegend( mySymbol, theMin=0, # expect 2.0303 in legend theMax=2.02030, theLabel='Foo') myPath = unique_filename( prefix='addSymbolToLegend', suffix='.png', dir=temp_dir('test')) myMapLegend.getLegend().save(myPath, 'PNG') LOGGER.debug(myPath) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. myTolerance = 0 # to allow for version number changes in disclaimer myFlag, myMessage = check_images('addSymbolToLegend', myPath, myTolerance) myMessage += ('\nWe want these images to match, if they do already ' 'copy the test image generated to create a new control ' 'image.') assert myFlag, myMessage
def test_renderComposition(self): """Test making an image of the map only.""" LOGGER.info("Testing renderComposition") myLayer, _ = load_layer("test_shakeimpact.shp") myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myMap.compose_map() myImagePath, myControlImage, myTargetArea = myMap.render() LOGGER.debug(myImagePath) assert myControlImage is not None myDimensions = [myTargetArea.left(), myTargetArea.top(), myTargetArea.bottom(), myTargetArea.right()] myExpectedDimensions = [0.0, 0.0, 3507.0, 2480.0] myMessage = "Expected target area to be %s, got %s" % (str(myExpectedDimensions), str(myDimensions)) assert myExpectedDimensions == myDimensions, myMessage myMessage = "Rendered output does not exist" assert os.path.exists(myImagePath), myMessage # Beta version and version changes can introduce a few extra chars # into the metadata section so we set a reasonable tolerance to cope # with this. myTolerance = 8000 myFlag, myMessage = check_images("renderComposition", myImagePath, myTolerance) assert myFlag, myMessage
def test_issue_121(self): """Test that point symbol size can be set from style (issue 121). .. seealso:: https://github.com/AIFDR/inasafe/issues/121 """ layer, layer_type = load_layer('kecamatan_jakarta_osm_centroids.shp') del layer_type # Note the float quantity values below style_info = {'target_field': 'KEPADATAN', 'style_classes': [ {'opacity': 1, 'max': 200, 'colour': '#fecc5c', 'min': 45, 'label': 'Low', 'size': 1}, {'opacity': 1, 'max': 350, 'colour': '#fd8d3c', 'min': 201, 'label': 'Medium', 'size': 2}, {'opacity': 1, 'max': 539, 'colour': '#f31a1c', 'min': 351, 'label': 'High', 'size': 3}]} print 'Setting style with point sizes should work.' set_vector_graduated_style(layer, style_info) # Now validate the size values were set as expected # new symbology - subclass of QgsFeatureRendererV2 class renderer = layer.rendererV2() layer_type = renderer.type() assert layer_type == 'graduatedSymbol' size = 1 for renderer_range in renderer.ranges(): symbol = renderer_range.symbol() symbol_layer = symbol.symbolLayer(0) actual_size = symbol_layer.size() message = (( 'Expected symbol layer 0 for range %s to have' ' a size of %s, got %s') % (size, size, actual_size)) assert size == actual_size, message size += 1
def test_printImpactTable(self): """Test that we can render html from impact table keywords.""" LOGGER.debug('InaSAFE HtmlRenderer testing printImpactTable') myFilename = 'test_floodimpact.tif' myLayer, _ = load_layer(myFilename) myMessage = 'Layer is not valid: %s' % myFilename assert myLayer.isValid(), myMessage myPageDpi = 300 myHtmlRenderer = HtmlRenderer(myPageDpi) myPath = unique_filename(prefix='impactTable', suffix='.pdf', dir=temp_dir('test')) myKeywordIO = KeywordIO() myKeywords = myKeywordIO.read_keywords(myLayer) myPath = myHtmlRenderer.print_impact_table(myKeywords, filename=myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size myExpectedSizes = [20936, # as rendered on linux ub 12.04 64 21523, # as rendered on linux ub 12.10 64 20605, # as rendered on linux ub 13.04 64 21527, # as rendered on Jenkins post 22 June 2013 377191, # as rendered on OSX 252699L, # as rendered on Windows 7 64 bit 251782L, # as rendered on Windows 8 64 bit amd 21491, # as rendered on Slackware64 14.0 ] print 'Output pdf to %s' % myPath self.assertIn(mySize, myExpectedSizes)
def test_add_class_to_legend(self): """Test we can add a class to the map legend.""" layer, _ = load_layer('test_shakeimpact.shp') map_legend = MapLegend(layer) colour = QtGui.QColor(12, 34, 126) map_legend.add_class( colour, label='bar') map_legend.add_class( colour, label='foo') path = unique_filename( prefix='addClassToLegend', suffix='.png', dir=temp_dir('test')) map_legend.get_legend().save(path, 'PNG') LOGGER.debug(path) # As we have discovered, different versions of Qt and # OS platforms cause different output, so place any other possible # variants in the safe_qgis/test_data/test_images/ dir e.g. # addClassToLegend-variantUbuntu13.04.png tolerance = 0 # to allow for version number changes in disclaimer flag, message = check_images( 'addClassToLegend', path, tolerance) message += ( '\nWe want these images to match, if they do already copy the test' ' image generated to create a new control image.') self.assertTrue(flag, message)
def test_add_symbol_to_legend(self): """Test we can add a symbol to the legend.""" layer, _ = load_layer('test_floodimpact.tif') map_legend = MapLegend(layer) symbol = QgsFillSymbolV2() symbol.setColor(QtGui.QColor(12, 34, 56)) map_legend.add_symbol( symbol, minimum=0, # expect 2.0303 in legend maximum=2.02030, label='Foo') path = unique_filename( prefix='addSymbolToLegend', suffix='.png', dir=temp_dir('test')) map_legend.get_legend().save(path, 'PNG') LOGGER.debug(path) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. tolerance = 0 # to allow for version number changes in disclaimer flag, message = check_images( 'addSymbolToLegend', path, tolerance) message += ( '\nWe want these images to match, if they do already, copy the ' 'test image generated to create a new control image.') self.assertTrue(flag, message)
def test_get_legend(self): """Getting a legend for a generic layer works.""" LOGGER.debug('test_get_legend called') layer, _ = load_layer('test_shakeimpact.shp') map_legend = MapLegend(layer) self.assertTrue(map_legend.layer is not None) legend = map_legend.get_legend() path = unique_filename( prefix='getLegend', suffix='.png', dir=temp_dir('test')) legend.save(path, 'PNG') LOGGER.debug(path) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. tolerance = 0 # to allow for version number changes in disclaimer flag, message = check_images('getLegend', path, tolerance) message += ( '\nWe want these images to match, if they do already ' 'copy the test image generated to create a new control ' 'image.') self.assertTrue(flag, message) LOGGER.debug('test_getLegend done')
def test_defaultTemplate(self): """Test that loading default template works""" LOGGER.info('Testing defaultTemplate') myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myPath = unique_filename(prefix='mapDefaultTemplateTest', suffix='.pdf', dir=temp_dir('test')) myMap.make_pdf(myPath) LOGGER.debug(myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. myExpectedSizes = [ 400350, # Slackware64 14.0 ] myMessage = '%s\nExpected rendered map pdf to be in %s, got %s' % ( myPath, myExpectedSizes, mySize) self.assertIn(mySize, myExpectedSizes, myMessage)
def test_get_vector_legend(self): """Getting a legend for a vector layer works. .. note:: This test is not related do thousand separator since we insert our own legend notes and our own layer. """ layer, _ = load_layer('test_shakeimpact.shp') map_legend = MapLegend( layer, legend_notes='Thousand separator represented by \',\'', legend_units='(people per cell)') image = map_legend.vector_legend() path = unique_filename( prefix='getVectorLegend', suffix='.png', dir=temp_dir('test')) image.save(path, 'PNG') LOGGER.debug(path) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. tolerance = 0 # to allow for version number changes in disclaimer flag, message = check_images( 'getVectorLegend', path, tolerance) message += ( '\nWe want these images to match, if they do already ' 'copy the test image generated to create a new control image.') self.assertTrue(flag, message)
def test_zonal(self): """Test that zonal stats returns the expected output.""" myRasterLayer, _ = load_layer(os.path.join( UNITDATA, 'other', 'tenbytenraster.asc')) myVectorLayer, _ = load_layer(os.path.join( UNITDATA, 'other', 'zonal_polygons.shp')) myResult = calculate_zonal_stats( raster_layer=myRasterLayer, polygon_layer=myVectorLayer) myExpectedResult = { 0L: {'count': 4, 'sum': 34.0, 'mean': 8.5}, # BR polygon 1L: {'count': 9, 'sum': 36.0, 'mean': 4.0}, # center polygon 2L: {'count': 4, 'sum': 2.0, 'mean': 0.5}, # TL polygon 3L: {'count': 4, 'sum': 2.0, 'mean': 0.5}, # BL Polygon 4L: {'count': 4, 'sum': 34.0, 'mean': 8.5}} # TR polygon self.maxDiff = None self.assertDictEqual(myExpectedResult, myResult)
def test_getMapTitle(self): """Getting the map title from the keywords""" myLayer, _ = load_layer('test_floodimpact.tif') myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myTitle = myMap.map_title() myExpectedTitle = 'Penduduk yang Mungkin dievakuasi' myMessage = 'Expected: %s\nGot:\n %s' % (myExpectedTitle, myTitle) assert myTitle == myExpectedTitle, myMessage
def test_get_map_title(self): """Getting the map title from the keywords""" layer, _ = load_layer('test_floodimpact.tif') report = Map(IFACE) report.set_impact_layer(layer) title = report.map_title() expected_title = 'Penduduk yang Mungkin dievakuasi' message = 'Expected: %s\nGot:\n %s' % (expected_title, title) assert title == expected_title, message
def test_zonal(self): """Test that zonal stats returns the expected output.""" raster_layer, _ = load_layer(os.path.join( UNITDATA, 'other', 'tenbytenraster.asc')) vector_layer, _ = load_layer(os.path.join( UNITDATA, 'other', 'zonal_polygons.shp')) result = calculate_zonal_stats( raster_layer=raster_layer, polygon_layer=vector_layer) expected_result = { 0L: {'count': 4, 'sum': 34.0, 'mean': 8.5}, # BR polygon 1L: {'count': 9, 'sum': 36.0, 'mean': 4.0}, # center polygon 2L: {'count': 4, 'sum': 2.0, 'mean': 0.5}, # TL polygon 3L: {'count': 4, 'sum': 2.0, 'mean': 0.5}, # BL Polygon 4L: {'count': 4, 'sum': 34.0, 'mean': 8.5}} # TR polygon # noinspection PyPep8Naming self.maxDiff = None self.assertDictEqual(expected_result, result)
def test_issue121(self): """Test that point symbol size can be set from style (issue 121). .. seealso:: https://github.com/AIFDR/inasafe/issues/121 """ myLayer, myType = load_layer('kecamatan_jakarta_osm_centroids.shp') del myType # Note the float quantity values below myStyleInfo = { 'target_field': 'KEPADATAN', 'style_classes': [{ 'opacity': 1, 'max': 200, 'colour': '#fecc5c', 'min': 45, 'label': 'Low', 'size': 1 }, { 'opacity': 1, 'max': 350, 'colour': '#fd8d3c', 'min': 201, 'label': 'Medium', 'size': 2 }, { 'opacity': 1, 'max': 539, 'colour': '#f31a1c', 'min': 351, 'label': 'High', 'size': 3 }] } myMessage = 'Setting style with point sizes should work.' try: set_vector_graduated_style(myLayer, myStyleInfo) except: raise Exception(myMessage) # Now validate the size values were set as expected if myLayer.isUsingRendererV2(): # new symbology - subclass of QgsFeatureRendererV2 class myRenderer = myLayer.rendererV2() myType = myRenderer.type() assert myType == 'graduatedSymbol' mySize = 1 for myRange in myRenderer.ranges(): mySymbol = myRange.symbol() mySymbolLayer = mySymbol.symbolLayer(0) myActualSize = mySymbolLayer.size() myMessage = (('Expected symbol layer 0 for range %s to have' ' a size of %s, got %s') % (mySize, mySize, myActualSize)) assert mySize == myActualSize, myMessage mySize += 1
def test_handle_missing_map_title(self): """Missing map title from the keywords fails gracefully""" # TODO running OSM Buildngs with Pendudk Jakarta # wasthrowing an error when requesting map title # that this test wasnt replicating well layer, _ = load_layer('population_padang_1.asc') report = Map(IFACE) report.set_impact_layer(layer) title = report.map_title() expected_title = None message = 'Expected: %s\nGot:\n %s' % (expected_title, title) assert title == expected_title, message
def test_handleMissingMapTitle(self): """Missing map title from the keywords fails gracefully""" # TODO running OSM Buildngs with Pendudk Jakarta # wasthrowing an error when requesting map title # that this test wasnt replicating well myLayer, _ = load_layer('population_padang_1.asc') myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myTitle = myMap.map_title() myExpectedTitle = None myMessage = 'Expected: %s\nGot:\n %s' % (myExpectedTitle, myTitle) assert myTitle == myExpectedTitle, myMessage
def test_issue_121(self): """Test that point symbol size can be set from style (issue 121). .. seealso:: https://github.com/AIFDR/inasafe/issues/121 """ layer, layer_type = load_layer('kecamatan_jakarta_osm_centroids.shp') del layer_type # Note the float quantity values below style_info = { 'target_field': 'KEPADATAN', 'style_classes': [{ 'opacity': 1, 'max': 200, 'colour': '#fecc5c', 'min': 45, 'label': 'Low', 'size': 1 }, { 'opacity': 1, 'max': 350, 'colour': '#fd8d3c', 'min': 201, 'label': 'Medium', 'size': 2 }, { 'opacity': 1, 'max': 539, 'colour': '#f31a1c', 'min': 351, 'label': 'High', 'size': 3 }] } print 'Setting style with point sizes should work.' set_vector_graduated_style(layer, style_info) # Now validate the size values were set as expected # new symbology - subclass of QgsFeatureRendererV2 class renderer = layer.rendererV2() layer_type = renderer.type() assert layer_type == 'graduatedSymbol' size = 1 for renderer_range in renderer.ranges(): symbol = renderer_range.symbol() symbol_layer = symbol.symbolLayer(0) actual_size = symbol_layer.size() message = (('Expected symbol layer 0 for range %s to have' ' a size of %s, got %s') % (size, size, actual_size)) assert size == actual_size, message size += 1
def test_zonal(self): """Test that zonal stats returns the expected output.""" raster_layer, _ = load_layer( os.path.join(UNITDATA, 'other', 'tenbytenraster.asc')) vector_layer, _ = load_layer( os.path.join(UNITDATA, 'other', 'zonal_polygons.shp')) result = calculate_zonal_stats(raster_layer=raster_layer, polygon_layer=vector_layer) expected_result = { 0L: { 'count': 4, 'sum': 34.0, 'mean': 8.5 }, # BR polygon 1L: { 'count': 9, 'sum': 36.0, 'mean': 4.0 }, # center polygon 2L: { 'count': 4, 'sum': 2.0, 'mean': 0.5 }, # TL polygon 3L: { 'count': 4, 'sum': 2.0, 'mean': 0.5 }, # BL Polygon 4L: { 'count': 4, 'sum': 34.0, 'mean': 8.5 } } # TR polygon # noinspection PyPep8Naming self.maxDiff = None self.assertDictEqual(expected_result, result)
def test_custom_logo(self): """Test that setting user-defined logo works.""" LOGGER.info('Testing custom_logo') layer, _ = load_layer('test_shakeimpact.shp') canvas_layer = QgsMapCanvasLayer(layer) CANVAS.setLayerSet([canvas_layer]) rect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(rect) CANVAS.refresh() report = Map(IFACE) report.set_impact_layer(layer) report.set_organisation_logo(":/plugins/inasafe/logo-flower.png") out_path = unique_filename(prefix='mapCustomLogoTest', suffix='.pdf', dir=temp_dir('test')) report.make_pdf(out_path) LOGGER.debug(out_path) message = 'Rendered output does not exist: %s' % out_path self.assertTrue(os.path.exists(out_path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. out_size = os.stat(out_path).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. expected_sizes = [ 402083, # Ubuntu 13.04_64 400563, # Ubuntu 13.10_64 450385, # Ubuntu 14.04_64 AG 413193, # Ubuntu 14.04_64 TS pycharm 416313, # Ubuntu 14.04_64 TS make - TODO why is this? 419483, # Ubuntu 14.04_64 MB pycharm 413193, # Ubuntu 14.04_64 MB make - TODO why is this? 418847, # Ubuntu 14.04_64 IS pycharm 412764, # Ubuntu 14.04_64 IS make - TODO why is this? 367934, # Slackware64 14.0 82263, # Linux Mint 14_64 85418, # Windows 7 32bit 88779, # Windows 7 64bit 436118, # Jenkins ub 12.04 433856, # Travis ] message = '%s\nExpected rendered map pdf to be in %s, got %s' % ( out_path, expected_sizes, out_size) self.assertIn(out_size, expected_sizes, message)
def register_layers(self): """Register needed layers to QgsMapLayerRegistry.""" # Register 4 impact layers and aggregation layer self.population_entire_jakarta_layer, _ = load_layer( population_entire_jakarta_impact_path, directory=None) self.building_entire_jakarta_layer, _ = load_layer( building_entire_jakarta_impact_path, directory=None) self.population_district_jakarta_layer, _ = load_layer( population_district_jakarta_impact_path, directory=None) self.building_district_jakarta_layer, _ = load_layer( building_district_jakarta_impact_path, directory=None) self.district_jakarta_layer, _ = load_layer( district_jakarta_boundary_path, directory=None) layer_list = [ self.population_entire_jakarta_layer, self.population_district_jakarta_layer, self.building_entire_jakarta_layer, self.building_district_jakarta_layer, self.district_jakarta_layer ] # noinspection PyArgumentList self.map_layer_registry.addMapLayers(layer_list)
def test_default_template(self): """Test that loading default template works""" LOGGER.info('Testing default_template') layer, _ = load_layer('test_shakeimpact.shp') canvas_layer = QgsMapCanvasLayer(layer) CANVAS.setLayerSet([canvas_layer]) rect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(rect) CANVAS.refresh() report = Map(IFACE) report.set_impact_layer(layer) out_path = unique_filename( prefix='mapDefaultTemplateTest', suffix='.pdf', dir=temp_dir('test')) report.make_pdf(out_path) LOGGER.debug(out_path) message = 'Rendered output does not exist: %s' % out_path self.assertTrue(os.path.exists(out_path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. out_size = os.stat(out_path).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. expected_sizes = [ 405359, # Ubuntu 13.04_64 427172, # Ubuntu 13.10_64 468836, # Ubuntu 14.04_64 AG 431844, # Ubuntu 14.04_64 TS - pycharm 431873, # Ubuntu 14.04_64 TS - make - TODO why is this? 437994, # Ubuntu 14.04_64 MB - pycharm 431844, # Ubuntu 14.04_64 MB - make - TODO why is this? 434596, # Ubuntu 14.04_64 MB - pycharm 428339, # Ubuntu 14.04_64 MB - make - TODO why is this? 414589, # Slackware64 14.0 144542, # Linux Mint 14_64 148267, # Windows 7 32 150412, # Windows 7 64 448270, # UB 12.04 Jenkins 448241, # Travis ] message = '%s\nExpected rendered map pdf to be in %s, got %s' % ( out_path, expected_sizes, out_size) self.assertIn(out_size, expected_sizes, message)
def test_custom_logo(self): """Test that setting user-defined logo works.""" LOGGER.info('Testing custom_logo') layer, _ = load_layer('test_shakeimpact.shp') canvas_layer = QgsMapCanvasLayer(layer) CANVAS.setLayerSet([canvas_layer]) rect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(rect) CANVAS.refresh() report = Map(IFACE) report.set_impact_layer(layer) report.set_organisation_logo(":/plugins/inasafe/logo-flower.png") out_path = unique_filename( prefix='mapCustomLogoTest', suffix='.pdf', dir=temp_dir('test')) report.make_pdf(out_path) LOGGER.debug(out_path) message = 'Rendered output does not exist: %s' % out_path self.assertTrue(os.path.exists(out_path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. out_size = os.stat(out_path).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. expected_sizes = [ 402083, # Ubuntu 13.04_64 400563, # Ubuntu 13.10_64 450385, # Ubuntu 14.04_64 AG 413193, # Ubuntu 14.04_64 TS pycharm 416313, # Ubuntu 14.04_64 TS make - TODO why is this? 419483, # Ubuntu 14.04_64 MB pycharm 413193, # Ubuntu 14.04_64 MB make - TODO why is this? 419036, # Ubuntu 14.04_64 IS pycharm 412764, # Ubuntu 14.04_64 IS make - TODO why is this? 367934, # Slackware64 14.0 82263, # Linux Mint 14_64 85418, # Windows 7 32bit 88779, # Windows 7 64bit 436118, # Jenkins ub 12.04 432703, # Travis ] message = '%s\nExpected rendered map pdf to be in %s, got %s' % ( out_path, expected_sizes, out_size) self.assertIn(out_size, expected_sizes, message)
def Xtest_renderTemplate(self): """Test that load template works""" # Use the template from our resources bundle myInPath = ":/plugins/inasafe/basic.qpt" myLayer, _ = load_layer("test_shakeimpact.shp") myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = Map(IFACE) set_jakarta_extent() myMap.set_impact_layer(myLayer) myPath = unique_filename(prefix="outTemplate", suffix=".pdf", dir=temp_dir("test")) LOGGER.debug(myPath) myMap.render_template(myInPath, myPath) assert os.path.exists(myPath)
def test_default_template(self): """Test that loading default template works""" LOGGER.info('Testing default_template') layer, _ = load_layer('test_shakeimpact.shp') canvas_layer = QgsMapCanvasLayer(layer) CANVAS.setLayerSet([canvas_layer]) rect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(rect) CANVAS.refresh() report = Map(IFACE) report.set_impact_layer(layer) out_path = unique_filename(prefix='mapDefaultTemplateTest', suffix='.pdf', dir=temp_dir('test')) report.make_pdf(out_path) LOGGER.debug(out_path) message = 'Rendered output does not exist: %s' % out_path self.assertTrue(os.path.exists(out_path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. out_size = os.stat(out_path).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. expected_sizes = [ 405359, # Ubuntu 13.04_64 427172, # Ubuntu 13.10_64 468836, # Ubuntu 14.04_64 AG 431844, # Ubuntu 14.04_64 TS - pycharm 431873, # Ubuntu 14.04_64 TS - make - TODO why is this? 437994, # Ubuntu 14.04_64 MB - pycharm 431844, # Ubuntu 14.04_64 MB - make - TODO why is this? 434420, # Ubuntu 14.04_64 IS - pycharm 428339, # Ubuntu 14.04_64 IS - make - TODO why is this? 414589, # Slackware64 14.0 144542, # Linux Mint 14_64 148267, # Windows 7 32 150412, # Windows 7 64 448270, # UB 12.04 Jenkins 449448, # Travis ] message = '%s\nExpected rendered map pdf to be in %s, got %s' % ( out_path, expected_sizes, out_size) self.assertIn(out_size, expected_sizes, message)
def Xtest_renderTemplate(self): """Test that load template works""" #Use the template from our resources bundle myInPath = ':/plugins/inasafe/basic.qpt' myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = Map(IFACE) set_jakarta_extent() myMap.set_impact_layer(myLayer) myPath = unique_filename(prefix='outTemplate', suffix='.pdf', dir=temp_dir('test')) LOGGER.debug(myPath) myMap.render_template(myInPath, myPath) assert os.path.exists(myPath)
def test_layerChanged(self): """Test the metadata is updated as the user highlights different QGIS layers. For inasafe outputs, the table of results should be shown See also https://github.com/AIFDR/inasafe/issues/58 """ myLayer, myType = load_layer('issue58.tif') myMessage = ('Unexpected category for issue58.tif.\nGot:' ' %s\nExpected: undefined' % myType) assert myType == 'undefined', myMessage DOCK.layer_changed(myLayer) DOCK.save_state() myHtml = DOCK.state['report'] myExpectedString = '4229' myMessage = "%s\nDoes not contain:\n%s" % (myHtml, myExpectedString) assert myExpectedString in myHtml, myMessage
def test_printToPdf(self): """Test making a pdf of the map - this is the most typical use of map. """ LOGGER.info('Testing printToPdf') myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myMap.compose_map() myPath = unique_filename(prefix='mapPdfTest', suffix='.pdf', dir=temp_dir('test')) myMap.make_pdf(myPath) LOGGER.debug(myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. myExpectedSizes = [ 441541, # as rendered on ub 13.04 post 17 May 2013 441563, # as rendered on ub 13.04 18 Jul 2013 447217, # Nadia Linux Mint 14 447144, # as rendered on Jenkins post 29 July 2013 447172, # Windows 7 SP1 AMD64 446839, # Windows 8 AMD64 post 27 Aug 2013 234138, # OSX 10.8 444421, # Slackware64 14.0 ] myMessage = '%s\nExpected rendered map pdf to be in %s, got %s' % ( myPath, myExpectedSizes, mySize) self.assertIn(mySize, myExpectedSizes, myMessage)
def test_layerChanged(self): """Test the metadata is updated as the user highlights different QGIS layers. For inasafe outputs, the table of results should be shown See also https://github.com/AIFDR/inasafe/issues/58 """ myLayer, myType = load_layer('issue58.tif') myMessage = ('Unexpected category for issue58.tif.\nGot:' ' %s\nExpected: undefined' % myType) assert myType == 'undefined', myMessage DOCK.layer_changed(myLayer) DOCK.save_state() myHtml = DOCK.state['report'] myExpectedString = '4229' myMessage = "%s\nDoes not contain:\n%s" % ( myHtml, myExpectedString) assert myExpectedString in myHtml, myMessage
def test_print_impact_table(self): """Test that we can render html from impact table keywords.""" LOGGER.debug('InaSAFE HtmlRenderer testing printImpactTable') file_name = 'test_floodimpact.tif' layer, _ = load_layer(file_name) message = 'Layer is not valid: %s' % file_name self.assertTrue(layer.isValid(), message) page_dpi = 300 html_renderer = HtmlRenderer(page_dpi) path = unique_filename( prefix='impact_table', suffix='.pdf', dir=temp_dir('test')) keyword_io = KeywordIO() keywords = keyword_io.read_keywords(layer) path = html_renderer.print_impact_table(keywords, filename=path) message = 'Rendered output does not exist: %s' % path self.assertTrue(os.path.exists(path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. size = os.stat(path).st_size expected_sizes = [ 20936, # as rendered on linux ub 12.04 64 21523, # as rendered on linux ub 12.10 64 20605, # as rendered on linux ub 13.04 64 13965, # as rendered on linux ub 13.10 64 14220, # as rendered on linux ub 13.04 64 MB 11085, # as rendered on linux ub 14.04 64 AG 17306, # as rendered on linux ub 14.04_64 TS 17127, # as rendered on linux ub 14.04_64 MB 17295, # as rendered on linux ub 14.04_64 IS 18665, # as rendered on Jenkins per 19 June 2014 377191, # as rendered on OSX 17556, # as rendered on Windows 7_32 16163L, # as rendered on Windows 7 64 bit Ultimate i3 251782L, # as rendered on Windows 8 64 bit amd 21491, # as rendered on Slackware64 14.0 18667, # as rendered on Linux Mint 14_64 ] print 'Output pdf to %s' % path self.assertIn(size, expected_sizes)
def test_print_impact_table(self): """Test that we can render html from impact table keywords.""" LOGGER.debug('InaSAFE HtmlRenderer testing printImpactTable') file_name = 'test_floodimpact.tif' layer, _ = load_layer(file_name) message = 'Layer is not valid: %s' % file_name self.assertTrue(layer.isValid(), message) page_dpi = 300 html_renderer = HtmlRenderer(page_dpi) path = unique_filename(prefix='impact_table', suffix='.pdf', dir=temp_dir('test')) keyword_io = KeywordIO() keywords = keyword_io.read_keywords(layer) path = html_renderer.print_impact_table(keywords, filename=path) message = 'Rendered output does not exist: %s' % path self.assertTrue(os.path.exists(path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. size = os.stat(path).st_size expected_sizes = [ 20936, # as rendered on linux ub 12.04 64 21523, # as rendered on linux ub 12.10 64 20605, # as rendered on linux ub 13.04 64 13965, # as rendered on linux ub 13.10 64 14220, # as rendered on linux ub 13.04 64 MB 11085, # as rendered on linux ub 14.04 64 AG 17306, # as rendered on linux ub 14.04_64 TS 17127, # as rendered on linux ub 14.04_64 MB 17295, # as rendered on linux ub 14.04_64 IS 18665, # as rendered on Jenkins per 19 June 2014 377191, # as rendered on OSX 17556, # as rendered on Windows 7_32 16163L, # as rendered on Windows 7 64 bit Ultimate i3 251782L, # as rendered on Windows 8 64 bit amd 21491, # as rendered on Slackware64 14.0 18667, # as rendered on Linux Mint 14_64 ] print 'Output pdf to %s' % path self.assertIn(size, expected_sizes)
def test_layerChanged(self): """Test the metadata is updated as the user highlights different QGIS layers. For inasafe outputs, the table of results should be shown See also https://github.com/AIFDR/inasafe/issues/58 """ layer, layer_type = load_layer('issue58.tif') message = ( 'Unexpected category for issue58.tif.\nGot:' ' %s\nExpected: undefined' % layer_type) self.assertTrue(layer_type == 'undefined', message) DOCK.layer_changed(layer) DOCK.save_state() html = DOCK.state['report'] expected = '4229' message = "%s\nDoes not contain:\n%s" % ( html, expected) self.assertTrue(expected in html, message)
def test_issue126(self): """Test that non integer transparency ranges fail gracefully. .. seealso:: https://github.com/AIFDR/inasafe/issues/126 """ # This dataset has all cells with value 1.3 myLayer, _ = load_layer('issue126.tif') # Note the float quantity values below myStyleInfo = {'style_classes': [ dict(colour='#38A800', quantity=1.1, transparency=100), dict(colour='#38A800', quantity=1.4, transparency=0), dict(colour='#79C900', quantity=10.1, transparency=0)]} try: setRasterStyle(myLayer, myStyleInfo) except Exception, e: myMessage = ( 'Setting style info with float based ranges should fail ' 'gracefully.') e.args = (e.args[0] + myMessage,) raise
def test_getRasterLegend(self): """Getting a legend for a raster layer works.""" myLayer, _ = load_layer('test_floodimpact.tif') myMapLegend = MapLegend(myLayer) myImage = myMapLegend.raster_legend() myPath = unique_filename(prefix='getRasterLegend', suffix='.png', dir=temp_dir('test')) myImage.save(myPath, 'PNG') LOGGER.debug(myPath) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. myTolerance = 0 # to allow for version number changes in disclaimer myFlag, myMessage = check_images('getRasterLegend', myPath, myTolerance) myMessage += ( '\nWe want these images to match, if they do already copy the test' ' image generated to create a new control image.') assert myFlag, myMessage
def test_getRasterLegend(self): """Getting a legend for a raster layer works.""" myLayer, _ = load_layer('test_floodimpact.tif') myMapLegend = MapLegend(myLayer) myImage = myMapLegend.raster_legend() myPath = unique_filename( prefix='getRasterLegend', suffix='.png', dir=temp_dir('test')) myImage.save(myPath, 'PNG') LOGGER.debug(myPath) # As we have discovered, different versions of Qt and # OS platforms cause different output, so myControlImages is a list # of 'known good' renders. myTolerance = 0 # to allow for version number changes in disclaimer myFlag, myMessage = check_images( 'getRasterLegend', myPath, myTolerance) myMessage += ( '\nWe want these images to match, if they do already copy the test' ' image generated to create a new control image.') assert myFlag, myMessage
def test_renderComposition(self): """Test making an image of the map only.""" LOGGER.info('Testing renderComposition') myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myMap.compose_map() myImagePath, myControlImage, myTargetArea = myMap.render() LOGGER.debug(myImagePath) assert myControlImage is not None myDimensions = [ myTargetArea.left(), myTargetArea.top(), myTargetArea.bottom(), myTargetArea.right() ] myExpectedDimensions = [0.0, 0.0, 3507.0, 2480.0] myMessage = 'Expected target area to be %s, got %s' % ( str(myExpectedDimensions), str(myDimensions)) assert myExpectedDimensions == myDimensions, myMessage myMessage = 'Rendered output does not exist' assert os.path.exists(myImagePath), myMessage # Beta version and version changes can introduce a few extra chars # into the metadata section so we set a reasonable tolerance to cope # with this. myTolerance = 8000 myFlag, myMessage = check_images('renderComposition', myImagePath, myTolerance) assert myFlag, myMessage
def test_printToPdf(self): """Test making a pdf of the map - this is the most typical use of map. """ LOGGER.info('Testing printToPdf') myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myMap.compose_map() myPath = unique_filename(prefix='mapPdfTest', suffix='.pdf', dir=temp_dir('test')) myMap.make_pdf(myPath) LOGGER.debug(myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size myExpectedSizes = [ 441541, # as rendered on ub 13.04 post 17 May 2013 441428, # as rendered on ub 13.04 5 Jul 2013 447217, # Nadia Linux Mint 14 447051, # as rendered on Jenkins post 24 April 2013 447138, # Windows 7 SP1 AMD64 233989, # OSX 10.8 ] myMessage = '%s\nExpected rendered map pdf to be in %s, got %s' % ( myPath, myExpectedSizes, mySize) self.assertIn(mySize, myExpectedSizes, myMessage)
def test_issue230(self): """Verify that we give informative errors when style is not correct .. seealso:: https://github.com/AIFDR/inasafe/issues/230 """ myPath = test_data_path('impact') myVectorLayer, myType = load_layer('polygons_for_styling.shp', myPath) del myType myStyle = {'legend_title': u'Population Count', 'target_field': 'population', 'style_classes': [{'transparency': 0, 'min': [0], # <-- intentionally broken list not number! 'max': 139904.08186340332, 'colour': '#FFFFFF', 'size': 1, 'label': u'Nil'}, {'transparency': 0, 'min': 139904.08186340332, 'max': 279808.16372680664, 'colour': '#38A800', 'size': 1, 'label': u'Low'}, {'transparency': 0, 'min': 279808.16372680664, 'max': 419712.24559020996, 'colour': '#79C900', 'size': 1, 'label': u'Low'}, {'transparency': 0, 'min': 419712.24559020996, 'max': 559616.32745361328, 'colour': '#CEED00', 'size': 1, 'label': u'Low'}, {'transparency': 0, 'min': 559616.32745361328, 'max': 699520.4093170166, 'colour': '#FFCC00', 'size': 1, 'label': u'Medium'}, {'transparency': 0, 'min': 699520.4093170166, 'max': 839424.49118041992, 'colour': '#FF6600', 'size': 1, 'label': u'Medium'}, {'transparency': 0, 'min': 839424.49118041992, 'max': 979328.57304382324, 'colour': '#FF0000', 'size': 1, 'label': u'Medium'}, {'transparency': 0, 'min': 979328.57304382324, 'max': 1119232.6549072266, 'colour': '#7A0000', 'size': 1, 'label': u'High'}]} try: set_vector_graduated_style(myVectorLayer, myStyle) except StyleError: # Exactly what should have happened return except Exception, e: print str(e)