def getRasterLegend(self): """Get the legend for a raster layer as an image. Args: None Returns: An image representing the layer's legend. self.legend is also populated Raises: An InvalidLegendLayer will be raised if a legend cannot be created from the layer. """ LOGGER.debug("InaSAFE Map Legend getRasterLegend called") # test if QGIS 1.8.0 or older # see issue #259 if qgisVersion() <= 10800: myShader = self.layer.rasterShader().rasterShaderFunction() myRampItems = myShader.colorRampItemList() myLastValue = 0 # Making an assumption here... LOGGER.debug("Source: %s" % self.layer.source()) for myItem in myRampItems: myValue = myItem.value myLabel = myItem.label myColor = myItem.color print "Value: %s Label %s" % (myValue, myLabel) self.addClassToLegend(myColor, theMin=myLastValue, theMax=myValue, theLabel=myLabel) myLastValue = myValue else: # TODO implement QGIS2.0 variant # In master branch, use QgsRasterRenderer::rasterRenderer() to # get/set how a raster is displayed. pass return self.legendImage
def test_Issue71(self): """Test issue #71 in github - cbo changes should update ok button.""" # See https://github.com/AIFDR/inasafe/issues/71 # Push OK with the left mouse button print 'Using QGIS: %s' % qgisVersion() self.tearDown() myButton = DOCK.pbnRunStop # First part of scenario should have enabled run myFileList = [ join(HAZDATA, 'Flood_Current_Depth_Jakarta_geographic.asc'), join(TESTDATA, 'Population_Jakarta_geographic.asc') ] myHazardLayerCount, myExposureLayerCount = loadLayers( myFileList, theDataDirectory=None) myMessage = ('Incorrect number of Hazard layers: expected 1 got %s' % myHazardLayerCount) assert myHazardLayerCount == 1, myMessage myMessage = ('Incorrect number of Exposure layers: expected 1 got %s' % myExposureLayerCount) assert myExposureLayerCount == 1, myMessage myMessage = 'Run button was not enabled' assert myButton.isEnabled(), myMessage # Second part of scenario - run disabled when adding invalid layer # and select it - run should be disabled myFileList = ['issue71.tif'] # This layer has incorrect keywords myClearFlag = False myHazardLayerCount, myExposureLayerCount = (loadLayers( myFileList, myClearFlag)) # set exposure to : Population Density Estimate (5kmx5km) QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Down) QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Enter) myDict = getUiState(DOCK) myExpectedDict = { 'Run Button Enabled': False, 'Impact Function Id': '', 'Impact Function Title': '', 'Hazard': 'A flood in Jakarta like in 2007', 'Exposure': 'Population density (5kmx5km)' } myMessage = ('Run button was not disabled when exposure set to \n%s' '\nUI State: \n%s\nExpected State:\n%s\n%s') % ( DOCK.cboExposure.currentText(), myDict, myExpectedDict, combosToString(DOCK)) assert myExpectedDict == myDict, myMessage # Now select again a valid layer and the run button # should be enabled QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Up) QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Enter) myMessage = ('Run button was not enabled when exposure set to \n%s' % DOCK.cboExposure.currentText()) assert myButton.isEnabled(), myMessage
def test_Issue71(self): """Test issue #71 in github - cbo changes should update ok button.""" # See https://github.com/AIFDR/inasafe/issues/71 # Push OK with the left mouse button print 'Using QGIS: %s' % qgisVersion() self.tearDown() myButton = DOCK.pbnRunStop # First part of scenario should have enabled run myFileList = [join(HAZDATA, 'Flood_Current_Depth_Jakarta_geographic.asc'), join(TESTDATA, 'Population_Jakarta_geographic.asc')] myHazardLayerCount, myExposureLayerCount = loadLayers(myFileList, theDataDirectory=None) myMessage = ('Incorrect number of Hazard layers: expected 1 got %s' % myHazardLayerCount) assert myHazardLayerCount == 1, myMessage myMessage = ('Incorrect number of Exposure layers: expected 1 got %s' % myExposureLayerCount) assert myExposureLayerCount == 1, myMessage myMessage = 'Run button was not enabled' assert myButton.isEnabled(), myMessage # Second part of scenario - run disabled when adding invalid layer # and select it - run should be disabled myFileList = ['issue71.tif'] # This layer has incorrect keywords myClearFlag = False myHazardLayerCount, myExposureLayerCount = ( loadLayers(myFileList, myClearFlag)) # set exposure to : Population Density Estimate (5kmx5km) QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Down) QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Enter) myDict = getUiState(DOCK) myExpectedDict = {'Run Button Enabled': False, 'Impact Function Id': '', 'Impact Function Title': '', 'Hazard': 'A flood in Jakarta like in 2007', 'Exposure': 'Population density (5kmx5km)'} myMessage = ('Run button was not disabled when exposure set to \n%s' '\nUI State: \n%s\nExpected State:\n%s\n%s') % ( DOCK.cboExposure.currentText(), myDict, myExpectedDict, combosToString(DOCK)) assert myExpectedDict == myDict, myMessage # Now select again a valid layer and the run button # should be enabled QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Up) QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Enter) myMessage = ('Run button was not enabled when exposure set to \n%s' % DOCK.cboExposure.currentText()) assert myButton.isEnabled(), myMessage
def test_issue_160(self): """Test that multipart features can be used in a scenario - issue #160 """ myExposure = os.path.join(UNITDATA, 'exposure', 'buildings_osm_4326.shp') myHazard = os.path.join(UNITDATA, 'hazard', 'multipart_polygons_osm_4326.shp') # See https://github.com/AIFDR/inasafe/issues/71 # Push OK with the left mouse button print 'Using QGIS: %s' % qgisVersion() self.tearDown() myButton = DOCK.pbnRunStop # First part of scenario should have enabled run myFileList = [myHazard, myExposure] myHazardLayerCount, myExposureLayerCount = loadLayers(myFileList, theDataDirectory=TESTDATA) myMessage = ('Incorrect number of Hazard layers: expected 1 got %s' % myHazardLayerCount) assert myHazardLayerCount == 1, myMessage myMessage = ('Incorrect number of Exposure layers: expected 1 got %s' % myExposureLayerCount) assert myExposureLayerCount == 1, myMessage myMessage = 'Run button was not enabled' assert myButton.isEnabled(), myMessage # Second part of scenario - run disabled when adding invalid layer # and select it - run should be disabled myFileList = ['issue71.tif'] # This layer has incorrect keywords myClearFlag = False myHazardLayerCount, myExposureLayerCount = ( loadLayers(myFileList, myClearFlag)) myResult, myMessage = setupScenario( theHazard='multipart_polygons_osm_4326', theExposure='buildings_osm_4326', theFunction='Be temporarily closed', theFunctionId='Flood Building Impact Function') assert myResult, myMessage # Enable on-the-fly reprojection setCanvasCrs(GEOCRS, True) IFACE.mapCanvas().setExtent( QgsRectangle(106.788, -6.193, 106.853, -6.167)) # Press RUN QTest.mouseClick(myButton, QtCore.Qt.LeftButton) myResult = DOCK.wvResults.page().currentFrame().toPlainText() myMessage = 'Result not as expected: %s' % myResult assert '68' in myResult, myMessage
def test_issue_160(self): """Test that multipart features can be used in a scenario - issue #160 """ myExposure = os.path.join(UNITDATA, 'exposure', 'buildings_osm_4326.shp') myHazard = os.path.join(UNITDATA, 'hazard', 'multipart_polygons_osm_4326.shp') # See https://github.com/AIFDR/inasafe/issues/71 # Push OK with the left mouse button print 'Using QGIS: %s' % qgisVersion() self.tearDown() myButton = DOCK.pbnRunStop # First part of scenario should have enabled run myFileList = [myHazard, myExposure] myHazardLayerCount, myExposureLayerCount = loadLayers( myFileList, theDataDirectory=TESTDATA) myMessage = ('Incorrect number of Hazard layers: expected 1 got %s' % myHazardLayerCount) assert myHazardLayerCount == 1, myMessage myMessage = ('Incorrect number of Exposure layers: expected 1 got %s' % myExposureLayerCount) assert myExposureLayerCount == 1, myMessage myMessage = 'Run button was not enabled' assert myButton.isEnabled(), myMessage # Second part of scenario - run disabled when adding invalid layer # and select it - run should be disabled myFileList = ['issue71.tif'] # This layer has incorrect keywords myClearFlag = False myHazardLayerCount, myExposureLayerCount = (loadLayers( myFileList, myClearFlag)) myResult, myMessage = setupScenario( theHazard='multipart_polygons_osm_4326', theExposure='buildings_osm_4326', theFunction='Be temporarily closed', theFunctionId='Flood Building Impact Function') assert myResult, myMessage # Enable on-the-fly reprojection setCanvasCrs(GEOCRS, True) IFACE.mapCanvas().setExtent( QgsRectangle(106.788, -6.193, 106.853, -6.167)) # Press RUN QTest.mouseClick(myButton, QtCore.Qt.LeftButton) myResult = DOCK.wvResults.page().currentFrame().toPlainText() myMessage = 'Result not as expected: %s' % myResult assert '68' in myResult, myMessage
def makeKeywordlessLayer(): """Helper function that returns a single predefined keywordless layer""" myFile = 'keywordless_layer.tif' myBasePath = unitTestDataPath('hazard') myPath = os.path.abspath(os.path.join(myBasePath, myFile)) myTitle = 'Keywordless Layer' myLayer = QgsRasterLayer(myPath, myTitle) if qgisVersion() >= 10800: # 1.8 or newer QgsMapLayerRegistry.instance().addMapLayers([myLayer]) else: QgsMapLayerRegistry.instance().addMapLayer(myLayer) return myLayer
def makePadangLayer(): """Helper function that returns a single predefined layer""" myFile = 'Shakemap_Padang_2009.asc' myPath = os.path.join(HAZDATA, myFile) myTitle = readKeywordsFromFile(myPath, 'title') # myTitle = 'An earthquake in Padang like in 2009' myLayer = QgsRasterLayer(myPath, myTitle) if qgisVersion() >= 10800: # 1.8 or newer QgsMapLayerRegistry.instance().addMapLayers([myLayer]) else: QgsMapLayerRegistry.instance().addMapLayer(myLayer) return myLayer
def test_windowsDrawingArtifacts(self): """Test that windows rendering does not make artifacts""" # sometimes spurious lines are drawn on the layout LOGGER.info('Testing windowsDrawingArtifacts') myPath = unique_filename(prefix='artifacts', suffix='.pdf', dir=temp_dir('test')) myMap = Map(IFACE) setupPrinter(myPath) myMap.setupComposition() myImage = QtGui.QImage(10, 10, QtGui.QImage.Format_RGB32) myImage.setDotsPerMeterX(dpiToMeters(300)) myImage.setDotsPerMeterY(dpiToMeters(300)) #myImage.fill(QtGui.QColor(250, 250, 250)) # Look at the output, you will see antialiasing issues around some # of the boxes drawn... # myImage.fill(QtGui.QColor(200, 200, 200)) myImage.fill(200 + 200 * 256 + 200 * 256 * 256) myFilename = os.path.join(temp_dir(), 'greyBox') myImage.save(myFilename, 'PNG') for i in range(10, 190, 10): myPicture = QgsComposerPicture(myMap.composition) myPicture.setPictureFile(myFilename) if qgisVersion() >= 10800: # 1.8 or newer myPicture.setFrameEnabled(False) else: myPicture.setFrame(False) myPicture.setItemPosition(i, # x i, # y 10, # width 10) # height myMap.composition.addItem(myPicture) # Same drawing drawn directly as a pixmap myPixmapItem = myMap.composition.addPixmap( QtGui.QPixmap.fromImage(myImage)) myPixmapItem.setOffset(i, i + 20) # Same drawing using our drawImage Helper myWidthMM = 1 myMap.drawImage(myImage, myWidthMM, i, i + 40) myImagePath, _, _ = myMap.renderComposition() # when this test no longer matches our broken render hash # we know the issue is fixed myControlImages = ['windowsArtifacts.png'] myTolerance = 0 myFlag, myMessage = checkImages(myControlImages, myImagePath, myTolerance) myMessage += ('\nWe want these images to match, if they do not ' 'there may be rendering artifacts in windows.\n') assert myFlag, myMessage
def test_windowsDrawingArtifacts(self): """Test that windows rendering does not make artifacts""" # sometimes spurious lines are drawn on the layout LOGGER.info('Testing windowsDrawingArtifacts') myPath = unique_filename(prefix='artifacts', suffix='.pdf', dir=temp_dir('test')) myMap = Map(IFACE) setupPrinter(myPath) myMap.setupComposition() myImage = QtGui.QImage(10, 10, QtGui.QImage.Format_RGB32) myImage.setDotsPerMeterX(dpiToMeters(300)) myImage.setDotsPerMeterY(dpiToMeters(300)) #myImage.fill(QtGui.QColor(250, 250, 250)) # Look at the output, you will see antialiasing issues around some # of the boxes drawn... # myImage.fill(QtGui.QColor(200, 200, 200)) myImage.fill(200 + 200 * 256 + 200 * 256 * 256) myFilename = os.path.join(temp_dir(), 'greyBox') myImage.save(myFilename, 'PNG') for i in range(10, 190, 10): myPicture = QgsComposerPicture(myMap.composition) myPicture.setPictureFile(myFilename) if qgisVersion() >= 10800: # 1.8 or newer myPicture.setFrameEnabled(False) else: myPicture.setFrame(False) myPicture.setItemPosition(i, # x i, # y 10, # width 10) # height myMap.composition.addItem(myPicture) # Same drawing drawn directly as a pixmap myPixmapItem = myMap.composition.addPixmap( QtGui.QPixmap.fromImage(myImage)) myPixmapItem.setOffset(i, i + 20) # Same drawing using our drawImage Helper myWidthMM = 1 myMap.drawImage(myImage, myWidthMM, i, i + 40) myImagePath, _, _ = myMap.renderComposition() # when this test no longer matches our broken render hash # we know the issue is fixed myTolerance = 0 myFlag, myMessage = checkImages('windowsArtifacts.png', myImagePath, myTolerance) myMessage += ('\nWe want these images to match, if they do not ' 'there may be rendering artifacts in windows.\n') assert myFlag, myMessage
def makePolygonLayer(): """Helper function that returns a single predefined layer""" myFile = 'kabupaten_jakarta_singlepart_3_good_attr.shp' myPath = os.path.join(TESTDATA, myFile) try: myTitle = readKeywordsFromFile(myPath, 'title') except KeywordNotFoundError: myTitle = 'kabupaten_jakarta_singlepart_3_good_attr' myLayer = QgsVectorLayer(myPath, myTitle, 'ogr') if qgisVersion() >= 10800: # 1.8 or newer QgsMapLayerRegistry.instance().addMapLayers([myLayer]) else: QgsMapLayerRegistry.instance().addMapLayer(myLayer) return myLayer
def drawLogo(self, theTopOffset): """Add a picture containing the logo to the map top left corner Args: theTopOffset - vertical offset at which the logo shoudl be drawn Returns: None Raises: None """ myLogo = QgsComposerPicture(self.composition) myLogo.setPictureFile(":/plugins/inasafe/bnpb_logo.png") myLogo.setItemPosition(self.pageMargin, theTopOffset, 10, 10) if qgisVersion() >= 10800: # 1.8 or newer myLogo.setFrameEnabled(self.showFramesFlag) else: myLogo.setFrame(self.showFramesFlag) myLogo.setZValue(1) # To ensure it overlays graticule markers self.composition.addItem(myLogo)
def drawLogo(self, theTopOffset): """Add a picture containing the logo to the map top left corner Args: theTopOffset - vertical offset at which the logo shoudl be drawn Returns: None Raises: None """ myLogo = QgsComposerPicture(self.composition) myLogo.setPictureFile(':/plugins/inasafe/bnpb_logo.png') myLogo.setItemPosition(self.pageMargin, theTopOffset, 10, 10) if qgisVersion() >= 10800: # 1.8 or newer myLogo.setFrameEnabled(self.showFramesFlag) else: myLogo.setFrame(self.showFramesFlag) myLogo.setZValue(1) # To ensure it overlays graticule markers self.composition.addItem(myLogo)
def makePadangLayerClone(): """Helper function that copies padang keyword for testing and return it.""" mySourceFileName = 'Shakemap_Padang_2009' myExts = ['.asc', '.asc.aux.xml', '.keywords', '.lic', '.prj', '.qml', '.sld'] myFileName = unique_filename() # copy to temp file for ext in myExts: mySourcePath = os.path.join(HAZDATA, mySourceFileName + ext) myDestPath = os.path.join(HAZDATA, myFileName + ext) shutil.copy2(mySourcePath, myDestPath) # return a single predefined layer myFile = myFileName + '.asc' myPath = os.path.join(HAZDATA, myFile) myTitle = readKeywordsFromFile(myPath, 'title') myLayer = QgsRasterLayer(myPath, myTitle) if qgisVersion() >= 10800: # 1.8 or newer QgsMapLayerRegistry.instance().addMapLayers([myLayer]) else: QgsMapLayerRegistry.instance().addMapLayer(myLayer) return myLayer, myFileName
def areKeywordsFileBased(self, theLayer): """Find out if keywords should be read/written to file or our keywords db. Args: * theLayer - A QGIS QgsMapLayer instance. Returns: True if keywords are storedin a file next to the dataset, else False if the dataset is remove e.g. a database. Raises: None """ # determine which keyword lookup system to use (file base or cache db) # based on the layer's provider type. True indicates we should use the # datasource as a file and look for a keywords file, false and we look # in the keywords db. myProviderType = None myVersion = qgisVersion() # check for old raster api with qgis < 1.8 # ..todo:: Add test for plugin layers too if myVersion < 10800 and theLayer.type() == QgsMapLayer.RasterLayer: myProviderType = str(theLayer.providerKey()) else: myProviderType = str(theLayer.providerType()) myProviderDict = { "ogr": True, "gdal": True, "gpx": False, "wms": False, "spatialite": False, "delimitedtext": True, "postgres": False, } myFileBasedKeywords = False if myProviderType in myProviderDict: myFileBasedKeywords = myProviderDict[myProviderType] return myFileBasedKeywords
def makePadangLayerClone(): """Helper function that copies padang keyword for testing and return it.""" mySourceFileName = 'Shakemap_Padang_2009' myExts = [ '.asc', '.asc.aux.xml', '.keywords', '.lic', '.prj', '.qml', '.sld' ] myFileName = unique_filename() # copy to temp file for ext in myExts: mySourcePath = os.path.join(HAZDATA, mySourceFileName + ext) myDestPath = os.path.join(HAZDATA, myFileName + ext) shutil.copy2(mySourcePath, myDestPath) # return a single predefined layer myFile = myFileName + '.asc' myPath = os.path.join(HAZDATA, myFile) myTitle = readKeywordsFromFile(myPath, 'title') myLayer = QgsRasterLayer(myPath, myTitle) if qgisVersion() >= 10800: # 1.8 or newer QgsMapLayerRegistry.instance().addMapLayers([myLayer]) else: QgsMapLayerRegistry.instance().addMapLayer(myLayer) return myLayer, myFileName
def areKeywordsFileBased(self, theLayer): """Find out if keywords should be read/written to file or our keywords db. Args: * theLayer - A QGIS QgsMapLayer instance. Returns: True if keywords are storedin a file next to the dataset, else False if the dataset is remove e.g. a database. Raises: None """ # determine which keyword lookup system to use (file base or cache db) # based on the layer's provider type. True indicates we should use the # datasource as a file and look for a keywords file, false and we look # in the keywords db. myProviderType = None myVersion = qgisVersion() # check for old raster api with qgis < 1.8 # ..todo:: Add test for plugin layers too if (myVersion < 10800 and theLayer.type() == QgsMapLayer.RasterLayer): myProviderType = str(theLayer.providerKey()) else: myProviderType = str(theLayer.providerType()) myProviderDict = { 'ogr': True, 'gdal': True, 'gpx': False, 'wms': False, 'spatialite': False, 'delimitedtext': True, 'postgres': False } myFileBasedKeywords = False if myProviderType in myProviderDict: myFileBasedKeywords = myProviderDict[myProviderType] return myFileBasedKeywords
def getRasterLegend(self): """Get the legend for a raster layer as an image. Args: None Returns: An image representing the layer's legend. self.legend is also populated Raises: An InvalidLegendLayer will be raised if a legend cannot be created from the layer. """ LOGGER.debug('InaSAFE Map Legend getRasterLegend called') # test if QGIS 1.8.0 or older # see issue #259 if qgisVersion() <= 10800: myShader = self.layer.rasterShader().rasterShaderFunction() myRampItems = myShader.colorRampItemList() myLastValue = 0 # Making an assumption here... LOGGER.debug('Source: %s' % self.layer.source()) for myItem in myRampItems: myValue = myItem.value myLabel = myItem.label myColor = myItem.color self.addClassToLegend(myColor, theMin=myLastValue, theMax=myValue, theLabel=myLabel, theType='rasterStyle') myLastValue = myValue else: #TODO implement QGIS2.0 variant #In master branch, use QgsRasterRenderer::rasterRenderer() to # get/set how a raster is displayed. pass self.addLegendNotes() return self.legendImage
def test_getQgisVersion(self): """Test we can get the version of QGIS""" myVersion = qgisVersion() myMessage = 'Got version %s of QGIS, but at least 107000 is needed' assert myVersion > 10700, myMessage
def test_clipGeometry(self): """Test that we can clip a geometry using another geometry.""" myGeometry = QgsGeometry.fromPolyline([ QgsPoint(10, 10), QgsPoint(20, 20), QgsPoint(30, 30), QgsPoint(40, 40)]) myClipPolygon = QgsGeometry.fromPolygon([[ QgsPoint(20, 20), QgsPoint(20, 30), QgsPoint(30, 30), QgsPoint(30, 20), QgsPoint(20, 20)]]) myResult = clipGeometry(myClipPolygon, myGeometry) if qgisVersion() > 10800: myExpectedWkt = 'LINESTRING(20.0 20.0, 30.0 30.0)' else: myExpectedWkt = ('LINESTRING(20.000000 20.000000, ' '30.000000 30.000000)') # There should only be one feature that intersects this clip # poly so this assertion should work. self.assertEqual(myExpectedWkt, str(myResult.exportToWkt())) # Now poly on poly clip test myClipPolygon = QgsGeometry.fromWkt( 'POLYGON((106.8218 -6.1842,106.8232 -6.1842,' '106.82304963 -6.18317148,106.82179736 -6.18314774,' '106.8218 -6.1842))') myGeometry = QgsGeometry.fromWkt( 'POLYGON((106.8216869 -6.1852067,106.8213233 -6.1843051,' '106.8212891 -6.1835559,106.8222566 -6.1835184,' '106.8227557 -6.1835076,106.8228588 -6.1851204,' '106.8216869 -6.1852067))') myResult = clipGeometry(myClipPolygon, myGeometry) if qgisVersion() > 10800: myExpectedWkt = ( 'POLYGON((106.82179833 -6.18353616,106.8222566 -6.1835184,' '106.8227557 -6.1835076,106.82279996 -6.1842,' '106.8218 -6.1842,106.82179833 -6.18353616))') else: myExpectedWkt = ( 'POLYGON((106.821798 -6.183536,106.822257 -6.183518,' '106.822756 -6.183508,106.822800 -6.184200,' '106.821800 -6.184200,106.821798 -6.183536))') # There should only be one feature that intersects this clip # poly so this assertion should work. self.assertEqual(myExpectedWkt, str(myResult.exportToWkt())) # Now point on poly test clip myGeometry = QgsGeometry.fromWkt('POINT(106.82241 -6.18369)') myResult = clipGeometry(myClipPolygon, myGeometry) if qgisVersion() > 10800: myExpectedWkt = 'POINT(106.82241 -6.18369)' else: myExpectedWkt = 'POINT(106.822410 -6.183690)' # There should only be one feature that intersects this clip # poly so this assertion should work. self.assertEqual(myExpectedWkt, str(myResult.exportToWkt()))
def test_clipGeometry(self): """Test that we can clip a geometry using another geometry.""" myGeometry = QgsGeometry.fromPolyline([ QgsPoint(10, 10), QgsPoint(20, 20), QgsPoint(30, 30), QgsPoint(40, 40) ]) myClipPolygon = QgsGeometry.fromPolygon([[ QgsPoint(20, 20), QgsPoint(20, 30), QgsPoint(30, 30), QgsPoint(30, 20), QgsPoint(20, 20) ]]) myResult = clipGeometry(myClipPolygon, myGeometry) if qgisVersion() > 10800: myExpectedWkt = 'LINESTRING(20.0 20.0, 30.0 30.0)' else: myExpectedWkt = ('LINESTRING(20.000000 20.000000, ' '30.000000 30.000000)') # There should only be one feature that intersects this clip # poly so this assertion should work. self.assertEqual(myExpectedWkt, str(myResult.exportToWkt())) # Now poly on poly clip test myClipPolygon = QgsGeometry.fromWkt( 'POLYGON((106.8218 -6.1842,106.8232 -6.1842,' '106.82304963 -6.18317148,106.82179736 -6.18314774,' '106.8218 -6.1842))') myGeometry = QgsGeometry.fromWkt( 'POLYGON((106.8216869 -6.1852067,106.8213233 -6.1843051,' '106.8212891 -6.1835559,106.8222566 -6.1835184,' '106.8227557 -6.1835076,106.8228588 -6.1851204,' '106.8216869 -6.1852067))') myResult = clipGeometry(myClipPolygon, myGeometry) if qgisVersion() > 10800: myExpectedWkt = ( 'POLYGON((106.82179833 -6.18353616,106.8222566 -6.1835184,' '106.8227557 -6.1835076,106.82279996 -6.1842,' '106.8218 -6.1842,106.82179833 -6.18353616))') else: myExpectedWkt = ( 'POLYGON((106.821798 -6.183536,106.822257 -6.183518,' '106.822756 -6.183508,106.822800 -6.184200,' '106.821800 -6.184200,106.821798 -6.183536))') # There should only be one feature that intersects this clip # poly so this assertion should work. self.assertEqual(myExpectedWkt, str(myResult.exportToWkt())) # Now point on poly test clip myGeometry = QgsGeometry.fromWkt('POINT(106.82241 -6.18369)') myResult = clipGeometry(myClipPolygon, myGeometry) if qgisVersion() > 10800: myExpectedWkt = 'POINT(106.82241 -6.18369)' else: myExpectedWkt = 'POINT(106.822410 -6.183690)' # There should only be one feature that intersects this clip # poly so this assertion should work. self.assertEqual(myExpectedWkt, str(myResult.exportToWkt()))