def __init__(self, parent, plugin): QDialog.__init__(self, parent) self.setupUi(self) self.plugin = plugin self.mResult = "" self.progressBar.setRange(0, 0) self.progressBar.setFormat("%p%") self.labelName.setText(plugin["name"]) self.buttonBox.clicked.connect(self.abort) url = QUrl(plugin["download_url"]) fileName = plugin["filename"] tmpDir = QDir.tempPath() tmpPath = QDir.cleanPath(tmpDir + "/" + fileName) self.file = QFile(tmpPath) self.request = QNetworkRequest(url) authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"] if authcfg and isinstance(authcfg, basestring): if not QgsAuthManager.instance().updateNetworkRequest( self.request, authcfg.strip()): self.mResult = self.tr( "Update of network request with authentication " "credentials FAILED for configuration '{0}'").format( authcfg) self.request = None if self.request is not None: self.reply = QgsNetworkAccessManager.instance().get(self.request) self.reply.downloadProgress.connect(self.readProgress) self.reply.finished.connect(self.requestFinished) self.stateChanged(4)
def tempFolder(): tempDir = os.path.join(unicode(QDir.tempPath()), 'processing' + _tempFolderSuffix) if not QDir(tempDir).exists(): QDir().mkpath(tempDir) return unicode(os.path.abspath(tempDir))
def testComposition(self, page=0, pixelDiff=0): if self.mComposition is None: myMessage = "Composition not valid" return False, myMessage # load expected image self.setControlName("expected_" + self.mTestName) # get width/height, create image and render the composition to it outputImage = QImage(self.mSize, QImage.Format_RGB32) self.mComposition.setPlotStyle(QgsComposition.Print) outputImage.setDotsPerMeterX(self.mDotsPerMeter) outputImage.setDotsPerMeterY(self.mDotsPerMeter) QgsMultiRenderChecker.drawBackground(outputImage) p = QPainter(outputImage) self.mComposition.renderPage(p, page) p.end() renderedFilePath = QDir.tempPath() + QDir.separator() + QFileInfo( self.mTestName).baseName() + "_rendered.png" outputImage.save(renderedFilePath, "PNG") self.setRenderedImage(renderedFilePath) testResult = self.runTest(self.mTestName, pixelDiff) return testResult, self.report()
def __init__(self, parent, plugin): QDialog.__init__(self, parent) self.setupUi(self) self.plugin = plugin self.mResult = "" self.progressBar.setRange(0, 0) self.progressBar.setFormat("%p%") self.labelName.setText(plugin["name"]) self.buttonBox.clicked.connect(self.abort) url = QUrl(plugin["download_url"]) fileName = plugin["filename"] tmpDir = QDir.tempPath() tmpPath = QDir.cleanPath(tmpDir + "/" + fileName) self.file = QFile(tmpPath) self.request = QNetworkRequest(url) authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"] if authcfg and isinstance(authcfg, basestring): if not QgsAuthManager.instance().updateNetworkRequest( self.request, authcfg.strip()): self.mResult = self.tr( "Update of network request with authentication " "credentials FAILED for configuration '{0}'").format(authcfg) self.request = None if self.request is not None: self.reply = QgsNetworkAccessManager.instance().get(self.request) self.reply.downloadProgress.connect(self.readProgress) self.reply.finished.connect(self.requestFinished) self.stateChanged(4)
def testComposition(self, page=0, pixelDiff=0): if self.mComposition is None: myMessage = "Composition not valid" return False, myMessage # load expected image self.setControlName("expected_" + self.mTestName) # get width/height, create image and render the composition to it outputImage = QImage(self.mSize, QImage.Format_RGB32) self.mComposition.setPlotStyle(QgsComposition.Print) outputImage.setDotsPerMeterX(self.mDotsPerMeter) outputImage.setDotsPerMeterY(self.mDotsPerMeter) QgsMultiRenderChecker.drawBackground(outputImage) p = QPainter(outputImage) self.mComposition.renderPage(p, page) p.end() renderedFilePath = QDir.tempPath() + QDir.separator() + QFileInfo(self.mTestName).baseName() + "_rendered.png" outputImage.save(renderedFilePath, "PNG") self.setRenderedImage(renderedFilePath) testResult = self.runTest(self.mTestName, pixelDiff) return testResult, self.report()
def removeDir(path): result = "" if not QFile(path).exists(): result = QCoreApplication.translate( "QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path elif QFile(path).remove( ): # if it is only link, just remove it without resolving. pass else: fltr = QDir.Dirs | QDir.Files | QDir.Hidden iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories) while iterator.hasNext(): item = iterator.next() if QFile(item).remove(): pass fltr = QDir.Dirs | QDir.Hidden iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories) while iterator.hasNext(): item = iterator.next() if QDir().rmpath(item): pass if QFile(path).exists(): result = QCoreApplication.translate( "QgsPluginInstaller", "Failed to remove the directory:" ) + "\n" + path + "\n" + QCoreApplication.translate( "QgsPluginInstaller", "Check permissions or remove it manually") # restore plugin directory if removed by QDir().rmpath() pluginDir = qgis.utils.home_plugin_path if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) return result
def saveAsScriptFile(self, index=None): tabWidget = self.tabEditorWidget.currentWidget() if not index: index = self.tabEditorWidget.currentIndex() if not tabWidget.path: fileName = self.tabEditorWidget.tabText(index) + '.py' folder = self.settings.value("pythonConsole/lastDirPath", QDir.home()) pathFileName = os.path.join(folder, fileName) fileNone = True else: pathFileName = tabWidget.path fileNone = False saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As") filename = QFileDialog.getSaveFileName(self, saveAsFileTr, pathFileName, "Script file (*.py)") if filename: try: tabWidget.save(filename) except (IOError, OSError) as error: msgText = QCoreApplication.translate('PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) if fileNone: tabWidget.path = None else: tabWidget.path = pathFileName return if not fileNone: self.updateTabListScript(pathFileName, action='remove')
def testQgsCentroidFillSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsCentroidFillSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsCentroidFillSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'regular_star' mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#55aaff' mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#00ff00' mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsSVGFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSVGFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSVGFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'accommodation_camping.svg' mValue = os.path.basename(mSymbolLayer.svgFilePath()) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6 mValue = mSymbolLayer.patternWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsSvgMarkerSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSvgMarkerSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSvgMarkerSymbolLayerV2.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSvgMarkerSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'skull.svg' mValue = os.path.basename(mSymbolLayer.path()) print("VALUE", mSymbolLayer.path()) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 12 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 45 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def saveAsScriptFile(self, index=None): tabWidget = self.tabEditorWidget.currentWidget() if not index: index = self.tabEditorWidget.currentIndex() if not tabWidget.path: fileName = self.tabEditorWidget.tabText(index) + '.py' folder = self.settings.value("pythonConsole/lastDirPath", QDir.home()) pathFileName = os.path.join(folder, fileName) fileNone = True else: pathFileName = tabWidget.path fileNone = False saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As") filename = QFileDialog.getSaveFileName(self, saveAsFileTr, pathFileName, "Script file (*.py)") if filename: try: tabWidget.save(filename) except (IOError, OSError) as error: msgText = QCoreApplication.translate( 'PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}' ).format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) if fileNone: tabWidget.path = None else: tabWidget.path = pathFileName return if not fileNone: self.updateTabListScript(pathFileName, action='remove')
def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate( "QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options." ) self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write(reply.readAll()) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = qgis.utils.home_plugin_path tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove() try: unzip( unicode(tmpPath), unicode(pluginDir) ) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath( pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr( "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:" ) + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def testDateTimeWriteShapefile(self): """Check writing date and time fields to an ESRI shapefile.""" ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int&' 'field=date_f:date&field=time_f:time&field=dt_f:datetime'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10))) ft.setAttributes([1, QDate(2014, 3, 5), QTime(13, 45, 22), QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22))]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 dest_file_name = os.path.join(str(QDir.tempPath()), 'datetime.shp') print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') fields = created_layer.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('date_f')).type(), QVariant.Date) #shapefiles do not support time types, result should be string self.assertEqual(fields.at(fields.indexFromName('time_f')).type(), QVariant.String) #shapefiles do not support datetime types, result should be string self.assertEqual(fields.at(fields.indexFromName('dt_f')).type(), QVariant.String) f = created_layer.getFeatures(QgsFeatureRequest()).next() date_idx = created_layer.fieldNameIndex('date_f') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5)) time_idx = created_layer.fieldNameIndex('time_f') #shapefiles do not support time types assert isinstance(f.attributes()[time_idx], basestring) self.assertEqual(f.attributes()[time_idx], '13:45:22') #shapefiles do not support datetime types datetime_idx = created_layer.fieldNameIndex('dt_f') assert isinstance(f.attributes()[datetime_idx], basestring) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)).toString("yyyy/MM/dd hh:mm:ss.zzz"))
def testDateTimeWriteTabfile(self): """Check writing date and time fields to an MapInfo tabfile.""" ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int&' 'field=date_f:date&field=time_f:time&field=dt_f:datetime'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10))) ft.setAttributes([ 1, QDate(2014, 3, 5), QTime(13, 45, 22), QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)) ]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 dest_file_name = os.path.join(str(QDir.tempPath()), 'datetime.tab') crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'MapInfo File') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') fields = created_layer.dataProvider().fields() self.assertEqual( fields.at(fields.indexFromName('date_f')).type(), QVariant.Date) self.assertEqual( fields.at(fields.indexFromName('time_f')).type(), QVariant.Time) self.assertEqual( fields.at(fields.indexFromName('dt_f')).type(), QVariant.DateTime) f = created_layer.getFeatures(QgsFeatureRequest()).next() date_idx = created_layer.fieldNameIndex('date_f') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5)) time_idx = created_layer.fieldNameIndex('time_f') assert isinstance(f.attributes()[time_idx], QTime) self.assertEqual(f.attributes()[time_idx], QTime(13, 45, 22)) datetime_idx = created_layer.fieldNameIndex('dt_f') assert isinstance(f.attributes()[datetime_idx], QDateTime) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)))
def testStatistics(self): """Test zonal stats""" TEST_DATA_DIR = unitTestDataPath() + "/zonalstatistics/" myTempPath = QDir.tempPath() + "/" testDir = QDir(TEST_DATA_DIR) for f in testDir.entryList(QDir.Files): QFile.remove(myTempPath + f) QFile.copy(TEST_DATA_DIR + f, myTempPath + f) myVector = QgsVectorLayer(myTempPath + "polys.shp", "poly", "ogr") myRasterPath = myTempPath + "edge_problem.asc" zs = QgsZonalStatistics(myVector, myRasterPath, "", 1) zs.calculateStatistics(None) feat = QgsFeature() # validate statistics for each feature request = QgsFeatureRequest().setFilterFid(0) feat = next(myVector.getFeatures(request)) myMessage = ('Expected: %f\nGot: %f\n' % (12.0, feat[1])) assert feat[1] == 12.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (8.0, feat[2])) assert feat[2] == 8.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.666666666666667, feat[3])) assert abs(feat[3] - 0.666666666666667) < 0.00001, myMessage request.setFilterFid(1) feat = next(myVector.getFeatures(request)) myMessage = ('Expected: %f\nGot: %f\n' % (9.0, feat[1])) assert feat[1] == 9.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2])) assert feat[2] == 5.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.555555555555556, feat[3])) assert abs(feat[3] - 0.555555555555556) < 0.00001, myMessage request.setFilterFid(2) feat = next(myVector.getFeatures(request)) myMessage = ('Expected: %f\nGot: %f\n' % (6.0, feat[1])) assert feat[1] == 6.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2])) assert feat[2] == 5.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.833333333333333, feat[3])) assert abs(feat[3] - 0.833333333333333) < 0.00001, myMessage
def testPrintMapFromTemplate(self): """Test that we can get a map to render in the template.""" myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif') myFileInfo = QFileInfo(myPath) myRasterLayer = QgsRasterLayer(myFileInfo.filePath(), myFileInfo.completeBaseName()) myRenderer = QgsMultiBandColorRenderer( myRasterLayer.dataProvider(), 2, 3, 4 ) #mRasterLayer.setRenderer( rasterRenderer ) myPipe = myRasterLayer.pipe() assert myPipe.set(myRenderer), "Cannot set pipe renderer" QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer]) myMapRenderer = QgsMapRenderer() myLayerStringList = [] myLayerStringList.append(myRasterLayer.id()) myMapRenderer.setLayerSet(myLayerStringList) myMapRenderer.setProjectionsEnabled(False) myComposition = QgsComposition(myMapRenderer) myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt') myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # now render the map, first zooming to the raster extents myMap = myComposition.getComposerMapById(0) myMessage = ('Map 0 could not be found in template %s', myFile) assert myMap is not None, myMessage myExtent = myRasterLayer.extent() myMap.setNewExtent(myExtent) myImagePath = os.path.join(str(QDir.tempPath()), 'template_map_render_python.png') myPageNumber = 0 myImage = myComposition.printPageAsRaster(myPageNumber) myImage.save(myImagePath) assert os.path.exists(myImagePath), 'Map render was not created.' # Not sure if this is a predictable way to test but its quicker than # rendering. myFileSize = QFileInfo(myImagePath).size() myExpectedFileSize = 100000 myMessage = ('Expected file size to be greater than %s, got %s' ' for %s' % (myExpectedFileSize, myFileSize, myImagePath)) assert myFileSize > myExpectedFileSize, myMessage
def batchRun(self): exts = re.sub('\).*$', '', re.sub('^.*\(', '', self.formatCombo.currentText())).split(" ") if len(exts) > 0 and exts[0] != "*" and exts[0] != "*.*": outExt = exts[0].replace("*", "") else: outExt = ".tif" self.base.enableRun(False) self.base.setCursor(Qt.WaitCursor) inDir = self.getInputFileName() outDir = self.getOutputFileName() extensions = Utils.getRasterExtensions() workDir = QDir(inDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(extensions) files = workDir.entryList() self.inFiles = [] self.outFiles = [] for f in files: self.inFiles.append(inDir + "/" + f) if outDir is not None: outFile = re.sub("\.[a-zA-Z0-9]{2,4}", outExt, f) self.outFiles.append(outDir + "/" + outFile) self.errors = [] self.batchIndex = 0 self.batchTotal = len(self.inFiles) self.setProgressRange(self.batchTotal) self.runItem(self.batchIndex, self.batchTotal)
def testPrintMapFromTemplate(self): """Test that we can get a map to render in the template.""" myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif') myFileInfo = QFileInfo(myPath) myRasterLayer = QgsRasterLayer(myFileInfo.filePath(), myFileInfo.completeBaseName()) myRenderer = QgsMultiBandColorRenderer(myRasterLayer.dataProvider(), 2, 3, 4) #mRasterLayer.setRenderer( rasterRenderer ) myPipe = myRasterLayer.pipe() assert myPipe.set(myRenderer), "Cannot set pipe renderer" QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer]) myMapRenderer = QgsMapRenderer() myLayerStringList = [] myLayerStringList.append(myRasterLayer.id()) myMapRenderer.setLayerSet(myLayerStringList) myMapRenderer.setProjectionsEnabled(False) myComposition = QgsComposition(myMapRenderer) myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt') with open(myFile) as f: myTemplateContent = f.read() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # now render the map, first zooming to the raster extents myMap = myComposition.getComposerMapById(0) myMessage = ('Map 0 could not be found in template %s', myFile) assert myMap is not None, myMessage myExtent = myRasterLayer.extent() myMap.setNewExtent(myExtent) myImagePath = os.path.join(str(QDir.tempPath()), 'template_map_render_python.png') myPageNumber = 0 myImage = myComposition.printPageAsRaster(myPageNumber) myImage.save(myImagePath) assert os.path.exists(myImagePath), 'Map render was not created.' # Not sure if this is a predictable way to test but its quicker than # rendering. myFileSize = QFileInfo(myImagePath).size() myExpectedFileSize = 100000 myMessage = ('Expected file size to be greater than %s, got %s' ' for %s' % (myExpectedFileSize, myFileSize, myImagePath)) assert myFileSize > myExpectedFileSize, myMessage
def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr("Select the input directory with files to Warp")) if not inputDir: return self.inSelector.setFilename(inputDir) filter = Utils.getRasterExtensions() workDir = QDir(inputDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(filter) if len(workDir.entryList()) > 0: fl = inputDir + "/" + workDir.entryList()[0] self.sourceSRSEdit.setText(Utils.getRasterSRS(self, fl))
def testWrite(self): for name in glob.glob("%s/raster/*.tif" % self.testDataDir): baseName = os.path.basename(name) allOk = True ok = self.write("raster/%s" % baseName) if not ok: allOk = False reportFilePath = "%s/qgistest.html" % QDir.tempPath() reportFile = open(reportFilePath, 'a') reportFile.write(self.report) reportFile.close() assert allOk, "Raster file writer test failed"
def imageCheck(self, name, reference_image, image): self.report += "<h2>Render {}</h2>\n".format(name) temp_dir = QDir.tempPath() + '/' file_name = temp_dir + 'symbol_' + name + ".png" image.save(file_name, "PNG") checker = QgsRenderChecker() checker.setControlPathPrefix("symbolv2") checker.setControlName("expected_" + reference_image) checker.setRenderedImage(file_name) checker.setColorTolerance(2) result = checker.compareImages(name, 20) self.report += checker.report() print(self.report) return result
def testQgsSimpleLineSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSimpleLineSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSimpleLineSymbolLayerV2.createFromSld( mDoc.elementsByTagName('LineSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSimpleLineSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#aa007f' mValue = mSymbolLayer.color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 1.26 mValue = mSymbolLayer.width() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.RoundCap mValue = mSymbolLayer.penCapStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.MiterJoin mValue = mSymbolLayer.penJoinStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mValue = mSymbolLayer.useCustomDashPattern() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = [5.0, 2.0] mValue = mSymbolLayer.customDashVector() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.") self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write(reply.readAll()) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = qgis.utils.home_plugin_path tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove() try: unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath(pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def getAllInstalled(self, testLoad=True): """ Build the localCache """ self.localCache = {} # reversed list of the plugin paths: first system plugins -> then user plugins -> finally custom path(s) pluginPaths = list(plugin_paths) pluginPaths.reverse() for pluginsPath in pluginPaths: isTheSystemDir = (pluginPaths.index(pluginsPath) == 0) # The curent dir is the system plugins dir if isTheSystemDir: # temporarily add the system path as the first element to force loading the readonly plugins, even if masked by user ones. sys.path = [pluginsPath] + sys.path try: pluginDir = QDir(pluginsPath) pluginDir.setFilter(QDir.AllDirs) for key in pluginDir.entryList(): if key not in [".", ".."]: path = QDir.convertSeparators(pluginsPath + "/" + key) # readOnly = not QFileInfo(pluginsPath).isWritable() # On windows testing the writable status isn't reliable. readOnly = isTheSystemDir # Assume only the system plugins are not writable. # only test those not yet loaded. Loaded plugins already proved they're o.k. # failedToLoad = settings.value("/PythonPlugins/watchDog/" + key) is not None testLoadThis = testLoad and key not in qgis.utils.plugins plugin = self.getInstalledPlugin(key, path=path, readOnly=readOnly, testLoad=testLoadThis) self.localCache[key] = plugin if key in self.localCache.keys() and compareVersions(self.localCache[key]["version_installed"], plugin["version_installed"]) == 1: # An obsolete plugin in the "user" location is masking a newer one in the "system" location! self.obsoletePlugins += [key] except: # it's not necessary to stop if one of the dirs is inaccessible pass if isTheSystemDir: # remove the temporarily added path sys.path.remove(pluginsPath)
def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory(self, self.tr("Select the input directory with files to Warp")) if not inputDir: return self.inSelector.setFilename(inputDir) filter = Utils.getRasterExtensions() workDir = QDir(inputDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(filter) if len(workDir.entryList()) > 0: fl = inputDir + "/" + workDir.entryList()[0] self.sourceSRSEdit.setText(Utils.getRasterSRS(self, fl))
def writeShape(theMemoryLayer, theFileName): myFileName = os.path.join(str(QDir.tempPath()), theFileName) print(myFileName) # Explicitly giving all options, not really needed but nice for clarity myErrorMessage = '' myOptions = [] myLayerOptions = [] mySelectedOnlyFlag = False mySkipAttributesFlag = False myGeoCrs = QgsCoordinateReferenceSystem() myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) myResult = QgsVectorFileWriter.writeAsVectorFormat( theMemoryLayer, myFileName, 'utf-8', myGeoCrs, 'ESRI Shapefile', mySelectedOnlyFlag, myErrorMessage, myOptions, myLayerOptions, mySkipAttributesFlag) assert myResult == QgsVectorFileWriter.NoError
def testQgsPointPatternFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ # at the moment there is an empty createFromSld implementation # that return nulls mTestName = 'QgsPointPatternFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsPointPatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsPointPatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'triangle' mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ffaa00' mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ff007f' mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.subSymbol().symbolLayer(0).angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.subSymbol().symbolLayer(0).size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def unload(self): self.toolbox.setVisible(False) self.menu.deleteLater() # delete temporary output files folder = tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.configAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterMainWindowAction(self.commanderAction) removeMenus()
def testQgsEllipseSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsEllipseSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsEllipseSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsEllipseSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'circle' mValue = mSymbolLayer.symbolName() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ffff7f' mValue = mSymbolLayer.fillColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#aaaaff' mValue = mSymbolLayer.outlineColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 7 mValue = mSymbolLayer.symbolWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.symbolHeight() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def setMacOSXDefaultEnvironment(): # fix bug #3170: many GDAL Tools don't work in OS X standalone if platform.system() != "Darwin": return # QgsApplication.prefixPath() contains the path to qgis executable (i.e. .../Qgis.app/MacOS) # get the path to Qgis application folder qgis_app = u"%s/.." % QgsApplication.prefixPath() qgis_app = QDir(qgis_app).absolutePath() qgis_bin = u"%s/bin" % QgsApplication.prefixPath( ) # path to QGis bin folder qgis_python = u"%s/Resources/python" % qgis_app # path to QGis python folder # path to the GDAL framework within the Qgis application folder (QGis standalone only) qgis_standalone_gdal_path = u"%s/Frameworks/GDAL.framework" % qgis_app # path to the GDAL framework when installed as external framework gdal_versionsplit = unicode(GdalConfig.version()).split('.') gdal_base_path = u"/Library/Frameworks/GDAL.framework/Versions/%s.%s" % ( gdal_versionsplit[0], gdal_versionsplit[1]) if os.path.exists(qgis_standalone_gdal_path): # qgis standalone # GDAL executables are in the QGis bin folder if getGdalBinPath() == '': setGdalBinPath(qgis_bin) # GDAL pymods are in the QGis python folder if getGdalPymodPath() == '': setGdalPymodPath(qgis_python) # GDAL help is in the framework folder if getHelpPath() == '': setHelpPath(u"%s/Resources/doc" % qgis_standalone_gdal_path) elif os.path.exists(gdal_base_path): # all GDAL parts are in the GDAL framework folder if getGdalBinPath() == '': setGdalBinPath(u"%s/Programs" % gdal_base_path) if getGdalPymodPath() == '': setGdalPymodPath( u"%s/Python/%s.%s/site-packages" % (gdal_base_path, sys.version_info[0], sys.version_info[1])) if getHelpPath() == '': setHelpPath(u"%s/Resources/doc" % gdal_base_path)
def openScriptFile(self): lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath()) openFileTr = QCoreApplication.translate("PythonConsole", "Open File") fileList = QFileDialog.getOpenFileNames( self, openFileTr, lastDirPath, "Script file (*.py)") if fileList: for pyFile in fileList: for i in range(self.tabEditorWidget.count()): tabWidget = self.tabEditorWidget.widget(i) if tabWidget.path == pyFile: self.tabEditorWidget.setCurrentWidget(tabWidget) break else: tabName = QFileInfo(pyFile).fileName() self.tabEditorWidget.newTabEditor(tabName, pyFile) lastDirPath = QFileInfo(pyFile).path() self.settings.setValue("pythonConsole/lastDirPath", pyFile) self.updateTabListScript(pyFile, action='append')
def openScriptFile(self): lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath()) openFileTr = QCoreApplication.translate("PythonConsole", "Open File") fileList = QFileDialog.getOpenFileNames(self, openFileTr, lastDirPath, "Script file (*.py)") if fileList: for pyFile in fileList: for i in range(self.tabEditorWidget.count()): tabWidget = self.tabEditorWidget.widget(i) if tabWidget.path == pyFile: self.tabEditorWidget.setCurrentWidget(tabWidget) break else: tabName = QFileInfo(pyFile).fileName() self.tabEditorWidget.newTabEditor(tabName, pyFile) lastDirPath = QFileInfo(pyFile).path() self.settings.setValue("pythonConsole/lastDirPath", pyFile) self.updateTabListScript(pyFile, action='append')
def testQgsFontMarkerSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsFontMarkerSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsFontMarkerSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsFontMarkerSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'Arial' mValue = mSymbolLayer.fontFamily() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"M" mValue = mSymbolLayer.character() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6.23 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testWriteShapefileWithMultiConversion(self): """Check writing geometries to an ESRI shapefile with conversion to multi.""" ml = QgsVectorLayer(('Point?crs=epsg:4326&field=id:int'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('Point (1 2)')) ft.setAttributes([1]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 dest_file_name = os.path.join(str(QDir.tempPath()), 'to_multi.shp') crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', forceMulti=True) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() expWkt = 'MultiPoint ((1 2))' assert compareWkt( expWkt, wkt ), "saving geometry with multi conversion failed: mismatch Expected:\n%s\nGot:\n%s\n" % ( expWkt, wkt)
def testQgsLinePatternFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsLinePatternFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsLinePatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsLinePatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ff55ff' mValue = mSymbolLayer.color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 1.5 mValue = mSymbolLayer.lineWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 4 mValue = mSymbolLayer.distance() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 57 mValue = mSymbolLayer.lineAngle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsSimpleFillSymbolLayerV2(self): """Create a new style from a .sld file and match test. """ mTestName = 'QgsSimpleFillSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSimpleFillSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSimpleFillSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.SolidPattern mValue = mSymbolLayer.brushStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ffaa7f' mValue = mSymbolLayer.borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.DotLine mValue = mSymbolLayer.borderStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 0.26 mValue = mSymbolLayer.borderWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testWriteShapefileWithMultiConversion(self): """Check writing geometries to an ESRI shapefile with conversion to multi.""" ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('Point (1 2)')) ft.setAttributes([1]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 dest_file_name = os.path.join(str(QDir.tempPath()), 'to_multi.shp') print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', forceMulti=True) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() expWkt = 'MultiPoint ((1 2))' assert compareWkt(expWkt, wkt), "saving geometry with multi conversion failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testQgsSvgMarkerSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSvgMarkerSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSvgMarkerSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSvgMarkerSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'skull.svg' mValue = os.path.basename(mSymbolLayer.path()) print("VALUE", mSymbolLayer.path()) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 12 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 45 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory(self, self.tr("Select the input directory with files to Translate")) if not inputDir: return self.inSelector.setFilename(inputDir) filter = Utils.getRasterExtensions() workDir = QDir(inputDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(filter) # search for a valid SRS, then use it as default target SRS srs = '' for fname in workDir.entryList(): fl = inputDir + "/" + fname srs = Utils.getRasterSRS(self, fl) if srs: break self.targetSRSEdit.setText(srs)
def getAllInstalled(self, testLoad=True): """ Build the localCache """ self.localCache = {} # reversed list of the plugin paths: first system plugins -> then user plugins -> finally custom path(s) pluginPaths = list(plugin_paths) pluginPaths.reverse() for pluginsPath in pluginPaths: isTheSystemDir = (pluginPaths.index(pluginsPath) == 0 ) # The curent dir is the system plugins dir if isTheSystemDir: # temporarily add the system path as the first element to force loading the readonly plugins, even if masked by user ones. sys.path = [pluginsPath] + sys.path try: pluginDir = QDir(pluginsPath) pluginDir.setFilter(QDir.AllDirs) for key in pluginDir.entryList(): if key not in [".", ".."]: path = QDir.convertSeparators(pluginsPath + "/" + key) # readOnly = not QFileInfo(pluginsPath).isWritable() # On windows testing the writable status isn't reliable. readOnly = isTheSystemDir # Assume only the system plugins are not writable. # only test those not yet loaded. Loaded plugins already proved they're o.k. # failedToLoad = settings.value("/PythonPlugins/watchDog/" + key) is not None testLoadThis = testLoad and key not in qgis.utils.plugins plugin = self.getInstalledPlugin(key, path=path, readOnly=readOnly, testLoad=testLoadThis) self.localCache[key] = plugin if key in self.localCache.keys() and compareVersions( self.localCache[key]["version_installed"], plugin["version_installed"]) == 1: # An obsolete plugin in the "user" location is masking a newer one in the "system" location! self.obsoletePlugins += [key] except: # it's not necessary to stop if one of the dirs is inaccessible pass if isTheSystemDir: # remove the temporarily added path sys.path.remove(pluginsPath)
def testWriteShapefileWithAttributeSubsets(self): """Tests writing subsets of attributes to files.""" ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int&field=field1:int&field=field2:int&field=field3:int'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('Point (1 2)')) ft.setAttributes([1, 11, 12, 13]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 #first write out with all attributes dest_file_name = os.path.join(str(QDir.tempPath()), 'all_attributes.shp') crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', attributes=[]) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') self.assertEqual(created_layer.fields().count(), 4) f = next(created_layer.getFeatures(QgsFeatureRequest())) self.assertEqual(f['id'], 1) self.assertEqual(f['field1'], 11) self.assertEqual(f['field2'], 12) self.assertEqual(f['field3'], 13) #now test writing out only a subset of attributes dest_file_name = os.path.join(str(QDir.tempPath()), 'subset_attributes.shp') write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', attributes=[1, 3]) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') self.assertEqual(created_layer.fields().count(), 2) f = next(created_layer.getFeatures(QgsFeatureRequest())) self.assertEqual(f['field1'], 11) self.assertEqual(f['field3'], 13) #finally test writing no attributes dest_file_name = os.path.join(str(QDir.tempPath()), 'no_attributes.shp') write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', skipAttributeCreation=True) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') # expect only a default 'FID' field for shapefiles self.assertEqual(created_layer.fields().count(), 1) self.assertEqual(created_layer.fields()[0].name(), 'FID') # in this case we also check that the geometry exists, to make sure feature has been correctly written # even without attributes f = next(created_layer.getFeatures(QgsFeatureRequest())) g = f.geometry() wkt = g.exportToWkt() expWkt = 'Point (1 2)' assert compareWkt(expWkt, wkt), "geometry not saved correctly when saving without attributes : mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt) self.assertEqual(f['FID'], 0)
def getRasterFiles(path, recursive=False): rasters = [] if not QFileInfo(path).exists(): return rasters # TODO remove *.aux.xml _filter = getRasterExtensions() workDir = QDir(path) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(_filter) files = workDir.entryList() for f in files: rasters.append(path + "/" + f) if recursive: for myRoot, myDirs, myFiles in os.walk(unicode(path)): for dir in myDirs: workDir = QDir(myRoot + "/" + dir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(_filter) workFiles = workDir.entryList() for f in workFiles: rasters.append(myRoot + "/" + dir + "/" + f) return rasters
def testWriteShapefileWithAttributeSubsets(self): """Tests writing subsets of attributes to files.""" ml = QgsVectorLayer(( 'Point?crs=epsg:4326&field=id:int&field=field1:int&field=field2:int&field=field3:int' ), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('Point (1 2)')) ft.setAttributes([1, 11, 12, 13]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 #first write out with all attributes dest_file_name = os.path.join(str(QDir.tempPath()), 'all_attributes.shp') crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', attributes=[]) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') self.assertEqual(created_layer.fields().count(), 4) f = created_layer.getFeatures(QgsFeatureRequest()).next() self.assertEqual(f['id'], 1) self.assertEqual(f['field1'], 11) self.assertEqual(f['field2'], 12) self.assertEqual(f['field3'], 13) #now test writing out only a subset of attributes dest_file_name = os.path.join(str(QDir.tempPath()), 'subset_attributes.shp') write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', attributes=[1, 3]) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') self.assertEqual(created_layer.fields().count(), 2) f = created_layer.getFeatures(QgsFeatureRequest()).next() self.assertEqual(f['field1'], 11) self.assertEqual(f['field3'], 13) #finally test writing no attributes dest_file_name = os.path.join(str(QDir.tempPath()), 'subset_attributes.shp') write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', skipAttributeCreation=True) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') # expect only a default 'FID' field for shapefiles self.assertEqual(created_layer.fields().count(), 1) self.assertEqual(created_layer.fields()[0].name(), 'FID') # in this case we also check that the geometry exists, to make sure feature has been correctly written # even without attributes f = created_layer.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() expWkt = 'Point (1 2)' assert compareWkt( expWkt, wkt ), "geometry not saved correctly when saving without attributes : mismatch Expected:\n%s\nGot:\n%s\n" % ( expWkt, wkt) self.assertEqual(f['FID'], 0)
def testWriteShapefileWithZ(self): """Check writing geometries with Z dimension to an ESRI shapefile.""" #start by saving a memory layer and forcing z ml = QgsVectorLayer(('Point?crs=epsg:4326&field=id:int'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('PointZ (1 2 3)')) ft.setAttributes([1]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 # check with both a standard PointZ and 25d style Point25D type for t in [QgsWKBTypes.PointZ, QgsWKBTypes.Point25D]: dest_file_name = os.path.join( str(QDir.tempPath()), 'point_{}.shp'.format(QgsWKBTypes.displayString(t))) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', overrideGeometryType=t) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer( u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() expWkt = 'PointZ (1 2 3)' assert compareWkt( expWkt, wkt ), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % ( expWkt, wkt) #also try saving out the shapefile version again, as an extra test #this tests that saving a layer with z WITHOUT explicitly telling the writer to keep z values, #will stay retain the z values dest_file_name = os.path.join( str(QDir.tempPath()), 'point_{}_copy.shp'.format(QgsWKBTypes.displayString(t))) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( created_layer, dest_file_name, 'utf-8', crs, 'ESRI Shapefile') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer_from_shp = QgsVectorLayer( u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer_from_shp.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() assert compareWkt( expWkt, wkt ), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % ( expWkt, wkt)
eprint(out) if len(out) == 0: print("QGIS Test Runner - [WARNING] subprocess returned no output") print('='*60) print("QGIS Test Runner - %s bytes returned and finished with exit code: %s" % (len(out), 0 if ok else 1)) sys.exit(0 if ok else 1) else: # We are inside QGIS! # Start as soon as the initializationCompleted signal is fired from qgis.core import QgsApplication from PyQt.QtCore import QDir from qgis.utils import iface # Add current working dir to the python path sys.path.append(QDir.current().path()) def __run_test(): """ Run the test specified as last argument in the command line. """ eprint("QGIS Test Runner Inside - starting the tests ...") try: test_module_name = QgsApplication.instance().argv()[-1] function_name = __get_test_function(test_module_name) if function_name is None: eprint("QGIS Test Runner Inside - [ERROR] cannot load test function from %s" % test_module_name) function_name() except Exception, e: eprint("QGIS Test Runner Inside - [ERROR] Exception: %s" % e) app = QgsApplication.instance()
def testWriteShapefileWithZ(self): """Check writing geometries with Z dimension to an ESRI shapefile.""" #start by saving a memory layer and forcing z ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('PointZ (1 2 3)')) ft.setAttributes([1]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 # check with both a standard PointZ and 25d style Point25D type for t in [QgsWKBTypes.PointZ, QgsWKBTypes.Point25D]: dest_file_name = os.path.join(str(QDir.tempPath()), 'point_{}.shp'.format(QgsWKBTypes.displayString(t))) print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', overrideGeometryType=t) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() expWkt = 'PointZ (1 2 3)' assert compareWkt(expWkt, wkt), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt) #also try saving out the shapefile version again, as an extra test #this tests that saving a layer with z WITHOUT explicitly telling the writer to keep z values, #will stay retain the z values dest_file_name = os.path.join(str(QDir.tempPath()), 'point_{}_copy.shp'.format(QgsWKBTypes.displayString(t))) print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( created_layer, dest_file_name, 'utf-8', crs, 'ESRI Shapefile') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer_from_shp = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer_from_shp.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() assert compareWkt(expWkt, wkt), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def tearDown(self): report_file_path = "%s/qgistest.html" % QDir.tempPath() with open(report_file_path, 'a') as report_file: report_file.write(self.report)