def Xtest_renderTable(self): """Test that html renders nicely. Commented out for now until we work out how to get webkit to do offscreen rendering nicely.""" myFilename = 'test_floodimpact.tif' myLayer, myType = loadLayer(myFilename) CANVAS.refresh() del myType myMessage = 'Layer is not valid: %s' % myFilename assert myLayer.isValid(), myMessage myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myPixmap = myMap.renderImpactTable() assert myPixmap is not None myExpectedWidth = 500 myExpectedHeight = 300 myMessage = 'Invalid width - got %s expected %s' % ( myPixmap.width(), myExpectedWidth) assert myPixmap.width() == myExpectedWidth, myMessage myMessage = 'Invalid height - got %s expected %s' % ( myPixmap.height(), myExpectedHeight) assert myPixmap.height() == myExpectedHeight myPath = os.path.join(getTempDir(), 'renderImpactTable.png') myPixmap.save(myPath, 'PNG') myExpectedHash = 'c9164d5c2bb85c6081905456ab827f3e' assertHashForFile(myExpectedHash, myPath)
def loadLayers(theLayerList, theClearFlag=True, DIR=TESTDATA): """Helper function to load layers as defined in a python list.""" # First unload any layers that may already be loaded if theClearFlag: for myLayer in QgsMapLayerRegistry.instance().mapLayers(): QgsMapLayerRegistry.instance().removeMapLayer(myLayer) # Now go ahead and load our layers myExposureLayerCount = 0 myHazardLayerCount = 0 myCanvasLayers = [] # Now create our new layers for myFile in theLayerList: myLayer, myType = loadLayer(myFile, DIR) if myType == 'hazard': myHazardLayerCount += 1 elif myType == 'exposure': myExposureLayerCount += 1 # Add layer to the registry (that QGis knows about) QgsMapLayerRegistry.instance().addMapLayer(myLayer) # Create Map Canvas Layer Instance and add to list myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # Quickly add any existing CANVAS layers to our list first for myLayer in CANVAS.layers(): myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # now load all these layers in the CANVAS CANVAS.setLayerSet(myCanvasLayers) DOCK.getLayers() # Add MCL's to the CANVAS return myHazardLayerCount, myExposureLayerCount
def test_addClassToLegend(self): """Test we can add a class to the map legend.""" myLayer, myType = loadLayer('test_shakeimpact.shp') del myType myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myMap.legend = None myColour = QtGui.QColor(12, 34, 126) myMap.addClassToLegend(myColour, theMin=None, theMax=None, theCategory=None, theLabel='bar') myMap.addClassToLegend(myColour, theMin=None, theMax=None, theCategory=None, theLabel='foo') myPath = os.path.join(getTempDir(), 'addClassToLegend.png') myMap.legend.save(myPath, 'PNG') # As we have discovered, different versions of Qt and # OS platforms cause different output, so hashes are a list # of 'known good' renders. myExpectedHashes = ['', # win '67c0f45792318298664dd02cc0ac94c3', # ub12.04xiner 'ea0702782c2ed5d950c427fbe1743858', # ub11.10-64 '53e0ba1144e071ad41756595d29bf444', # ub12.04 '0681c3587305074bc9272f456fb4dd09', # ub12.04 xvfb # ub11.04-64 laptop '', ] assertHashesForFile(myExpectedHashes, myPath)
def test_getMapTitle(self): """Getting the map title from the keywords""" myLayer, myType = loadLayer('test_floodimpact.tif') del myType myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myTitle = myMap.getMapTitle() myExpectedTitle = 'Penduduk yang Mungkin dievakuasi' myMessage = 'Expected: %s\nGot:\n %s' % (myExpectedTitle, myTitle) assert myTitle == myExpectedTitle, myMessage
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, myType = loadLayer('population_padang_1.asc') del myType myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myTitle = myMap.getMapTitle() myExpectedTitle = None myMessage = 'Expected: %s\nGot:\n %s' % (myExpectedTitle, myTitle) assert myTitle == myExpectedTitle, myMessage
def setUp(self): self.keywordIO = ISKeywordIO() myUri = QgsDataSourceURI() myUri.setDatabase(os.path.join(TESTDATA, 'jk.sqlite')) myUri.setDataSource('', 'osm_buildings', 'Geometry') self.sqliteLayer = QgsVectorLayer(myUri.uri(), 'OSM Buildings', 'spatialite') myHazardPath = os.path.join(HAZDATA, 'Shakemap_Padang_2009.asc') self.fileRasterLayer, myType = loadLayer(myHazardPath, DIR=None) del myType self.fileVectorLayer, myType = loadLayer('Padang_WGS84.shp') del myType self.expectedSqliteKeywords = {'category': 'exposure', 'datatype': 'OSM', 'subcategory': 'building'} self.expectedVectorKeywords = {'category': 'exposure', 'datatype': 'itb', 'subcategory': 'building'} self.expectedRasterKeywords = {'category': 'hazard', 'subcategory': 'earthquake', 'unit': 'MMI', 'title': ('An earthquake in Padang ' 'like in 2009')}
def test_renderTemplate(self): """Test that load template works""" #Use the template from our resources bundle myInPath = ':/plugins/inasafe/basic.qpt' myLayer, myType = loadLayer('test_shakeimpact.shp') del myType myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = ISMap(IFACE) setJakartaGeoExtent() myMap.setImpactLayer(myLayer) myOutPath = os.path.join(getTempDir(), 'outTemplate.pdf') if os.path.exists(myOutPath): os.remove(myOutPath) myMap.renderTemplate(myInPath, myOutPath) assert os.path.exists(myOutPath)
def test_inasafeMap(self): """Test making a pdf using the ISMap class.""" myLayer, myType = loadLayer('test_shakeimpact.shp') del myType myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = ISMap(IFACE) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap.setImpactLayer(myLayer) myPath = os.path.join(getTempDir(), 'outCustom.pdf') if os.path.exists(myPath): os.remove(myPath) myMap.makePdf(myPath) assert os.path.exists(myPath) # ,, note:: Template writing is experimental myMap.writeTemplate(os.path.join(getTempDir(), 'template.qpt'))
def addSymbolToLegend(self): """Test we can add a symbol to the legend.""" myLayer, myType = loadLayer('test_floodimpact.tif') del myType myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myMap.legend = None mySymbol = QgsSymbol() mySymbol.setColor(QtGui.QColor(12, 34, 56)) myMap.addSymbolToLegend(mySymbol, theMin=0, theMax=2, theCategory=None, theLabel='Foo') myPath = os.path.join(getTempDir(), 'addSymbolToLegend.png') myMap.legend.save(myPath, 'PNG') myExpectedHash = '1234' assertHashForFile(myExpectedHash, 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 = loadLayer('issue58.tif') myMessage = ('Unexpected category for issue58.tif.\nGot:' ' %s\nExpected: undefined' % myType) assert myType == 'undefined', myMessage DOCK.layerChanged(myLayer) DOCK.saveState() myHtml = DOCK.state['report'] myExpectedString = '4229' myMessage = "%s\nDoes not contain:\n%s" % ( myHtml, myExpectedString) assert myExpectedString in myHtml, myMessage
def test_getRasterLegend(self): """Getting a legend for a raster layer works.""" myLayer, myType = loadLayer('test_floodimpact.tif') del myType myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myMap.getRasterLegend() myPath = os.path.join(getTempDir(), 'getRasterLegend.png') myMap.legend.save(myPath, 'PNG') # As we have discovered, different versions of Qt and # OS platforms cause different output, so hashes are a list # of 'known good' renders. myExpectedHashes = ['', # win '9ead6ce0ac789adc65a6f00bd2d1f709', # ub12.04xiner '84bc3d518e3a0504f8dc36dfd620394e', # ub11.10-64 'b68ccc328de852f0c66b8abe43eab3da', # ub12.04 'cd5fb96f6c5926085d251400dd3b4928', # ub12.04 xvfb # ub11.04-64 laptop '', ] assertHashesForFile(myExpectedHashes, myPath)
def test_getVectorLegend(self): """Getting a legend for a vector layer works.""" myLayer, myType = loadLayer('test_shakeimpact.shp') del myType myMap = ISMap(IFACE) myMap.setImpactLayer(myLayer) myMap.getVectorLegend() myPath = os.path.join(getTempDir(), 'getVectorLegend.png') myMap.legend.save(myPath, 'PNG') # As we have discovered, different versions of Qt and # OS platforms cause different output, so hashes are a list # of 'known good' renders. myExpectedHashes = ['', # win 'd0c3071c4babe7db4f9762b311d61184', # ub12.04 xinr 'b94cfd8a10d709ff28466ada425f24c8', # ub11.10-64 '00dc58aa50867de9b617ccfab0d13f21', # ub12.04 'e65853e217a4c9b0c2f303dd2aadb373', # ub12.04 xvfb # ub11.04-64 laptop '', ] assertHashesForFile(myExpectedHashes, myPath)
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 = loadLayer('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: setVectorStyle(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_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, myType = loadLayer('issue126.tif') del myType # Note the float quantity values below myStyleInfo = {} 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)] myMessage = ('Setting style info with float based ranges should fail ' 'gracefully.') try: setRasterStyle(myLayer, myStyleInfo) except: raise Exception(myMessage) # Now validate the transparency values were set to 255 because # they are floats and we cant specify pixel ranges to floats myValue1 = myLayer.rasterTransparency().alphaValue(1.1) myValue2 = myLayer.rasterTransparency().alphaValue(1.4) myMessage = ('Transparency should be ignored when style class' ' quantities are floats') assert myValue1 == myValue2 == 255, myMessage # Now run the same test again myStyleInfo['style_classes'] = [ dict(colour='#38A800', quantity=2, transparency=100), dict(colour='#38A800', quantity=4, transparency=0), dict(colour='#79C900', quantity=10, transparency=0)] myMessage = ('Setting style info with generate valid transparent ' 'pixel entries.') try: setRasterStyle(myLayer, myStyleInfo) except: raise Exception(myMessage) # Now validate the transparency values were set to 255 because # they are floats and we cant specify pixel ranges to floats myValue1 = myLayer.rasterTransparency().alphaValue(1) myValue2 = myLayer.rasterTransparency().alphaValue(3) myMessage1 = myMessage + 'Expected 0 got %i' % myValue1 myMessage2 = myMessage + 'Expected 255 got %i' % myValue2 assert myValue1 == 0, myMessage1 assert myValue2 == 255, myMessage2 # Verify that setRasterStyle doesn't break when floats coincide with # integers # See https://github.com/AIFDR/inasafe/issues/126#issuecomment-5978416 myStyleInfo['style_classes'] = [ dict(colour='#38A800', quantity=2.0, transparency=100), dict(colour='#38A800', quantity=4.0, transparency=0), dict(colour='#79C900', quantity=10.0, transparency=0)] myMessage = ('Broken: Setting style info with generate valid ' 'transparent ' 'floating point pixel entries such as 2.0, 3.0') try: setRasterStyle(myLayer, myStyleInfo) except Exception, e: raise Exception(myMessage + ': ' + str(e))