예제 #1
0
 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='foo',
                            theLabel='bar')
     myMap.addClassToLegend(myColour,
                            theMin=None,
                            theMax=None,
                            theCategory='foo',
                            theLabel='foo')
     myPath = os.path.join(getTempDir(), 'addClassToLegend.png')
     myMap.legend.save(myPath, 'PNG')
     myExpectedHash = None
     if  os.name is'nt':
         # windows renders fonts slightly differently
         myExpectedHash = '658e8dc0bf8b9a09b36994abf9242099'
     else:
         myExpectedHash = 'ea0702782c2ed5d950c427fbe1743858'
     assertHashForFile(myExpectedHash, myPath)
예제 #2
0
 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)
예제 #3
0
 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='foo',
                            theLabel='bar')
     myMap.addClassToLegend(myColour,
                            theMin=None,
                            theMax=None,
                            theCategory='foo',
                            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 = ['658e8dc0bf8b9a09b36994abf9242099',  # win
                         'ea0702782c2ed5d950c427fbe1743858',  # ub11.10
                         '944cee3eb9d916816b60ef41e8069683',  # ub12.04
                         # ub11.04-64 laptop
                         '4f98b1ddef2d72bd38b2f220ec7e01cc',
                         ]
     assertHashesForFile(myExpectedHashes, myPath)
예제 #4
0
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
예제 #5
0
 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
예제 #6
0
 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': 'Padang 2009 scenario'}
예제 #7
0
 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
예제 #8
0
 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')
     myExpectedHash = None
     if  os.name is'nt':
         # windows renders fonts slightly differently
         myExpectedHash = '658e8dc0bf8b9a09b36994abf9242099'
     else:
         myExpectedHash = '1fc706f7c08e7d3057a685f9e6c4df3f'
     assertHashForFile(myExpectedHash, myPath)
예제 #9
0
 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')
     myExpectedHash = None
     if  os.name is'nt':
         # windows renders fonts slightly differently
         myExpectedHash = '658e8dc0bf8b9a09b36994abf9242099'
     else:
         myExpectedHash = 'f2169dd3146aca6b30a10cddfb5ebf68'
     assertHashForFile(myExpectedHash, myPath)
예제 #10
0
    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
예제 #11
0
    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)
예제 #12
0
 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)
예제 #13
0
 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'))
예제 #14
0
 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 = ['658e8dc0bf8b9a09b36994abf9242099',  # win
                         '1fc706f7c08e7d3057a685f9e6c4df3f',  # ub11.10
                         '2845879db127ce81d85baaac0b2c11b7',  # ub12.04
                         # ub11.04-64 laptop
                         '6ab9f8cc2445d1e672fd5013ac76cce7',
                         ]
     assertHashesForFile(myExpectedHashes, myPath)
예제 #15
0
    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
예제 #16
0
 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')
     myExpectedHash = None
     # As we have discovered, different versions of Qt and
     # OS platforms cause different output, so hashes are a list
     # of 'known good' renders.
     myExpectedHashes = ['658e8dc0bf8b9a09b36994abf9242099',  # win
                         'f2169dd3146aca6b30a10cddfb5ebf68',  # ub11.10
                         'de6cbd59899d0077b11dd09c00a343e8',  # ub12.04
                         # ub11.04-64 laptop
                         '6f9a68611cad040d0a524f929361bb64',
                         ]
     assertHashesForFile(myExpectedHashes, myPath)
예제 #17
0
    def test_issue121(self):
        """Test that point symbol size can be set from style (issue 121).
        .. seealso:: https://github.com/AIFDR/inasafe/issues/121
        """
        # This dataset has all cells with value 1.3
        myLayer, myType = loadLayer('kecamatan_geo_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