def test_zip_input_file_not_exist(self): f0 = os.path.join(unitTestDataPath(), 'multipoint.shp') f1 = os.path.join(unitTestDataPath(), 'fake.shp') f2 = os.path.join(unitTestDataPath(), 'joins.qgs') rc = QgsZipUtils.zip(tmpPath(), [f0, f1, f2]) self.assertFalse(rc)
def test_zip_ok(self): f0 = os.path.join(unitTestDataPath(), 'multipoint.shp') f1 = os.path.join(unitTestDataPath(), 'lines.shp') f2 = os.path.join(unitTestDataPath(), 'joins.qgs') rc = QgsZipUtils.zip(tmpPath(), [f0, f1, f2]) self.assertTrue(rc)
def test_zip_file_empty(self): f0 = os.path.join(unitTestDataPath(), 'multipoint.shp') f1 = os.path.join(unitTestDataPath(), 'lines.shp') f2 = os.path.join(unitTestDataPath(), 'joins.qgs') rc = QgsZipUtils.zip("", [f0, f1, f2]) self.assertFalse(rc)
def setUpClass(cls): """Run before all tests: Creates an auth configuration""" cls.port = QGIS_SERVER_ENDPOINT_PORT # Clean env just to be sure env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] for ev in env_vars: try: del os.environ[ev] except KeyError: pass cls.testdata_path = unitTestDataPath('qgis_server') cls.certsdata_path = os.path.join(unitTestDataPath('auth_system'), 'certs_keys') cls.project_path = os.path.join(cls.testdata_path, "test_project.qgs") # cls.hostname = 'localhost' cls.protocol = 'https' cls.hostname = '127.0.0.1' cls.setUpAuth() server_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'qgis_wrapped_server.py') cls.server = subprocess.Popen([sys.executable, server_path], env=os.environ, stdout=subprocess.PIPE) line = cls.server.stdout.readline() cls.port = int(re.findall(b':(\d+)', line)[0]) assert cls.port != 0 # Wait for the server process to start assert waitServer('%s://%s:%s' % (cls.protocol, cls.hostname, cls.port)), "Server is not responding! %s://%s:%s" % (cls.protocol, cls.hostname, cls.port)
def testEmbedding(self): """Test embedding large SVGs """ w = QgsImageSourceLineEdit() spy = QSignalSpy(w.sourceChanged) w.setSource('source') self.assertEqual(w.source(), 'source') self.assertEqual(len(spy), 1) self.assertEqual(spy[0][0], 'source') b64 = 'base64:' + ''.join(['x'] * 1000000) w.setSource(b64) self.assertEqual(w.source(), b64) self.assertEqual(len(spy), 2) self.assertEqual(spy[1][0], b64) w.setSource(os.path.join(unitTestDataPath(), 'landsat.tif')) self.assertEqual(w.source(), os.path.join(unitTestDataPath(), 'landsat.tif')) self.assertEqual(len(spy), 3) self.assertEqual(spy[2][0], os.path.join(unitTestDataPath(), 'landsat.tif')) w.setSource(b64) self.assertEqual(w.source(), b64) self.assertEqual(len(spy), 4) self.assertEqual(spy[3][0], b64) w.setSource('') self.assertEqual(w.source(), '') self.assertEqual(len(spy), 5) self.assertEqual(spy[4][0], '')
def setUpClass(cls): """Run before all tests""" cls.port = QGIS_SERVER_WFST_DEFAULT_PORT cls.testdata_path = unitTestDataPath('wfs_transactional') + '/' # Create tmp folder cls.temp_path = tempfile.mkdtemp() cls.testdata_path = cls.temp_path + '/' + 'wfs_transactional' + '/' copytree(unitTestDataPath('wfs_transactional') + '/', cls.temp_path + '/' + 'wfs_transactional') cls.project_path = cls.temp_path + '/' + 'wfs_transactional' + '/' + \ 'wfs_transactional.qgs' assert os.path.exists(cls.project_path), "Project not found: %s" % \ cls.project_path # Clean env just to be sure env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] for ev in env_vars: try: del os.environ[ev] except KeyError: pass # Clear all test layers for ln in ['test_point', 'test_polygon', 'test_linestring']: cls._clearLayer(ln) os.environ['QGIS_SERVER_DEFAULT_PORT'] = str(cls.port) server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen(['python', server_path], env=os.environ) sleep(2)
def test_zip_unzip_ok(self): zip = tmpPath() f0 = os.path.join(unitTestDataPath(), 'multipoint.shp') f1 = os.path.join(unitTestDataPath(), 'lines.shp') f2 = os.path.join(unitTestDataPath(), 'joins.qgs') rc = QgsZipUtils.zip(zip, [f0, f1, f2]) self.assertTrue(rc) outDir = QTemporaryDir() rc, files = QgsZipUtils.unzip(zip, outDir.path()) self.assertTrue(rc) self.assertEqual(len(files), 3)
def test_zip_file_yet_exist(self): zip = QTemporaryFile() zip.open() zip.close() os.remove(zip.fileName()) f0 = os.path.join(unitTestDataPath(), 'multipoint.shp') f1 = os.path.join(unitTestDataPath(), 'lines.shp') f2 = os.path.join(unitTestDataPath(), 'joins.qgs') rc = QgsZipUtils.zip(zip.fileName(), [f0, f1, f2]) self.assertTrue(rc) rc = QgsZipUtils.zip(zip.fileName(), [f0, f1, f2]) self.assertFalse(rc)
def setUp(self): """Create the server instance""" self.testdata_path = unitTestDataPath('qgis_server') + '/' d = unitTestDataPath('qgis_server_accesscontrol') + '/' self.projectPath = os.path.join(d, "project.qgs") # Clean env just to be sure env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] for ev in env_vars: try: del os.environ[ev] except KeyError: pass self.server = QgsServer()
def testSelectByExpression(self): """ Test selecting by expression """ layer = QgsVectorLayer(os.path.join(unitTestDataPath(), 'points.shp'), 'Points', 'ogr') # SetSelection layer.selectByExpression('"Class"=\'B52\' and "Heading" > 10 and "Heading" <70', QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([10, 11])) # check that existing selection is cleared layer.selectByExpression('"Class"=\'Biplane\'', QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([1, 5, 6, 7, 8])) # SetSelection no matching layer.selectByExpression('"Class"=\'A380\'', QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([])) # AddToSelection layer.selectByExpression('"Importance"=3', QgsVectorLayer.AddToSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([0, 2, 3, 4, 14])) layer.selectByExpression('"Importance"=4', QgsVectorLayer.AddToSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([0, 2, 3, 4, 13, 14])) # IntersectSelection layer.selectByExpression('"Heading"<100', QgsVectorLayer.IntersectSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([0, 2, 3, 4])) layer.selectByExpression('"Cabin Crew"=1', QgsVectorLayer.IntersectSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3])) # RemoveFromSelection layer.selectByExpression('"Heading"=85', QgsVectorLayer.RemoveFromSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([3])) layer.selectByExpression('"Heading"=95', QgsVectorLayer.RemoveFromSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([]))
def testValidRelationAfterChangingStyle(self): # load project myPath = os.path.join(unitTestDataPath(), 'relations.qgs') QgsProject.instance().read(myPath) # get referenced layer relations = QgsProject.instance().relationManager().relations() relation = relations[list(relations.keys())[0]] referencedLayer = relation.referencedLayer() # check that the relation is valid valid = False for tab in referencedLayer.editFormConfig().tabs(): for t in tab.children(): if (t.type() == QgsAttributeEditorElement.AeTypeRelation): valid = t.relation().isValid() self.assertTrue(valid) # update style referencedLayer.styleManager().setCurrentStyle("custom") # check that the relation is still valid referencedLayer = relation.referencedLayer() valid = False for tab in referencedLayer.editFormConfig().tabs(): for t in tab.children(): if (t.type() == QgsAttributeEditorElement.AeTypeRelation): valid = t.relation().isValid() self.assertTrue(valid)
def testFormUi(self): layer = self.createLayer() config = layer.editFormConfig() config.setLayout(QgsEditFormConfig.GeneratedLayout) self.assertEqual(config.layout(), QgsEditFormConfig.GeneratedLayout) uiLocal = os.path.join( unitTestDataPath(), '/qgis_local_server/layer_attribute_form.ui') config.setUiForm(uiLocal) self.assertEqual(config.layout(), QgsEditFormConfig.UiFileLayout) config.setLayout(QgsEditFormConfig.GeneratedLayout) self.assertEqual(config.layout(), QgsEditFormConfig.GeneratedLayout) uiUrl = 'http://localhost:' + \ str(self.port) + '/qgis_local_server/layer_attribute_form.ui' config.setUiForm(uiUrl) self.assertEqual(config.layout(), QgsEditFormConfig.UiFileLayout) content = QgsApplication.networkContentFetcherRegistry().fetch(uiUrl) self.assertTrue(content is not None) while True: if content.status() in (QgsFetchedContent.Finished, QgsFetchedContent.Failed): break app.processEvents() self.assertEqual(content.status(), QgsFetchedContent.Finished)
def setUp(self): """Create the server instance""" self.fontFamily = QgsFontUtils.standardTestFontFamily() QgsFontUtils.loadStandardTestFonts(['All']) d = unitTestDataPath('qgis_server_accesscontrol') + '/' self._project_path = os.path.join(d, "project.qgs")
def setUpClass(cls): """Run before all tests""" cls.port = QGIS_SERVER_WFST_PORT # Create tmp folder cls.temp_path = tempfile.mkdtemp() cls.testdata_path = cls.temp_path + '/' + 'wfs_transactional' + '/' copytree(unitTestDataPath('wfs_transactional') + '/', cls.temp_path + '/' + 'wfs_transactional') cls.project_path = cls.temp_path + '/' + 'wfs_transactional' + '/' + \ 'wfs_transactional.qgs' assert os.path.exists(cls.project_path), "Project not found: %s" % \ cls.project_path # Clean env just to be sure env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] for ev in env_vars: try: del os.environ[ev] except KeyError: pass # Clear all test layers for ln in ['test_point', 'test_polygon', 'test_linestring']: cls._clearLayer(ln) os.environ['QGIS_SERVER_PORT'] = str(cls.port) server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen([sys.executable, server_path], env=os.environ, stdout=subprocess.PIPE) line = cls.server.stdout.readline() cls.port = int(re.findall(b':(\d+)', line)[0]) assert cls.port != 0 # Wait for the server process to start assert waitServer('http://127.0.0.1:%s' % cls.port), "Server is not responding!"
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 testIdentify(self): myPath = os.path.join(unitTestDataPath(), 'landsat.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage myPoint = QgsPoint(786690, 3345803) #print 'Extents: %s' % myRasterLayer.extent().toString() #myResult, myRasterValues = myRasterLayer.identify(myPoint) #assert myResult myRasterValues = myRasterLayer.dataProvider().identify(myPoint, QgsRasterDataProvider.IdentifyFormatValue ) assert len( myRasterValues ) > 0 # Get the name of the first band myBand = myRasterValues.keys()[0] #myExpectedName = QString('Band 1') myExpectedBand = 1 myMessage = 'Expected "%s" got "%s" for first raster band name' % ( myExpectedBand, myBand) assert myExpectedBand == myBand, myMessage # Convert each band value to a list of ints then to a string myValues = myRasterValues.values() myIntValues = [] for myValue in myValues: #myIntValues.append(int(str(myValue))) myIntValues.append( myValue.toInt()[0] ) myValues = str(myIntValues) myExpectedValues = '[127, 141, 112, 72, 86, 126, 156, 211, 170]' myMessage = 'Expected: %s\nGot: %s' % (myValues, myExpectedValues) self.assertEquals(myValues, myExpectedValues, myMessage)
def testLoadPalettedClassDataFromFile(self): # bad file classes = QgsPalettedRasterRenderer.classDataFromFile('ajdhjashjkdh kjahjkdhk') self.assertEqual(len(classes), 0) # good file! path = os.path.join(unitTestDataPath('raster'), 'test.clr') classes = QgsPalettedRasterRenderer.classDataFromFile(path) self.assertEqual(len(classes), 10) self.assertEqual(classes[0].value, 1) self.assertEqual(classes[0].color.name(), '#000000') self.assertEqual(classes[0].color.alpha(), 255) self.assertEqual(classes[1].value, 2) self.assertEqual(classes[1].color.name(), '#c8c8c8') self.assertEqual(classes[2].value, 3) self.assertEqual(classes[2].color.name(), '#006e00') self.assertEqual(classes[3].value, 4) self.assertEqual(classes[3].color.name(), '#6e4100') self.assertEqual(classes[4].value, 5) self.assertEqual(classes[4].color.name(), '#0000ff') self.assertEqual(classes[4].color.alpha(), 255) self.assertEqual(classes[5].value, 6) self.assertEqual(classes[5].color.name(), '#0059ff') self.assertEqual(classes[6].value, 7) self.assertEqual(classes[6].color.name(), '#00aeff') self.assertEqual(classes[7].value, 8) self.assertEqual(classes[7].color.name(), '#00fff6') self.assertEqual(classes[8].value, 9) self.assertEqual(classes[8].color.name(), '#eeff00') self.assertEqual(classes[9].value, 10) self.assertEqual(classes[9].color.name(), '#ffb600')
def testSetDataSource(self): """Test change data source""" temp_dir = QTemporaryDir() options = QgsDataProvider.ProviderOptions() myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() layer = QgsRasterLayer(myPath, myBaseName) renderer = QgsSingleBandGrayRenderer(layer.dataProvider(), 2) image = layer.previewAsImage(QSize(400, 400)) self.assertFalse(image.isNull()) self.assertTrue(image.save(os.path.join(temp_dir.path(), 'expected.png'), "PNG")) layer.setDataSource(myPath.replace('4326.tif', '4326-BAD_SOURCE.tif'), 'bad_layer', 'gdal', options) self.assertFalse(layer.isValid()) image = layer.previewAsImage(QSize(400, 400)) self.assertTrue(image.isNull()) layer.setDataSource(myPath.replace('4326-BAD_SOURCE.tif', '4326.tif'), 'bad_layer', 'gdal', options) self.assertTrue(layer.isValid()) image = layer.previewAsImage(QSize(400, 400)) self.assertFalse(image.isNull()) self.assertTrue(image.save(os.path.join(temp_dir.path(), 'actual.png'), "PNG")) self.assertTrue(filecmp.cmp(os.path.join(temp_dir.path(), 'actual.png'), os.path.join(temp_dir.path(), 'expected.png')), False)
def testLayerRemovalBeforeRun(self): """test behavior when layer is removed before task begins""" path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, "test") self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = create_temp_filename('remove_layer.tif') writer = QgsRasterFileWriter(tmp) task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs()) task.writeComplete.connect(self.onSuccess) task.errorOccurred.connect(self.onFail) # remove layer raster_layer = None QgsApplication.taskManager().addTask(task) while not self.success and not self.fail: QCoreApplication.processEvents() # in this case will still get a positive result - since the pipe is cloned before the task # begins the task is no longer dependent on the original layer self.assertTrue(self.success) self.assertFalse(self.fail) self.assertTrue(os.path.exists(tmp))
def testPalettedColorTableToClassData(self): entries = [QgsColorRampShader.ColorRampItem(5, QColor(255, 0, 0), 'item1'), QgsColorRampShader.ColorRampItem(3, QColor(0, 255, 0), 'item2'), QgsColorRampShader.ColorRampItem(6, QColor(0, 0, 255), 'item3'), ] classes = QgsPalettedRasterRenderer.colorTableToClassData(entries) self.assertEqual(classes[0].value, 5) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[2].value, 6) self.assertEqual(classes[0].label, 'item1') self.assertEqual(classes[1].label, 'item2') self.assertEqual(classes[2].label, 'item3') self.assertEqual(classes[0].color.name(), '#ff0000') self.assertEqual(classes[1].color.name(), '#00ff00') self.assertEqual(classes[2].color.name(), '#0000ff') # test #13263 path = os.path.join(unitTestDataPath('raster'), 'hub13263.vrt') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) self.assertTrue(layer.isValid(), 'Raster not loaded: {}'.format(path)) classes = QgsPalettedRasterRenderer.colorTableToClassData(layer.dataProvider().colorTable(1)) self.assertEqual(len(classes), 4) classes = QgsPalettedRasterRenderer.colorTableToClassData(layer.dataProvider().colorTable(15)) self.assertEqual(len(classes), 256)
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 setUp(self): """Run before each test.""" self.testDataDir = unitTestDataPath() print("****************************************************") print(("In method", self._testMethodName)) print("****************************************************") pass
def setUp(self): self.testdata_path = unitTestDataPath('qgis_server_project') + '/' self.prj = QgsProject() prjPath = os.path.join(self.testdata_path, "project.qgs") self.prj.setFileName(prjPath) self.prj.read()
def test_FeatureCount(self): myPath = os.path.join(unitTestDataPath(), 'lines.shp') myLayer = QgsVectorLayer(myPath, 'Lines', 'ogr') myCount = myLayer.featureCount() myExpectedCount = 6 myMessage = '\nExpected: %s\nGot: %s' % (myCount, myExpectedCount) assert myCount == myExpectedCount, myMessage
def testOneBandRaster(self): path = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) self.assertTrue(layer) combo = QgsRasterBandComboBox() combo.setLayer(layer) self.assertEqual(combo.layer(), layer) self.assertEqual(combo.currentBand(), 1) self.assertEqual(combo.count(), 1) combo.setShowNotSetOption(True) self.assertEqual(combo.currentBand(), 1) self.assertEqual(combo.count(), 2) combo.setBand(-1) self.assertEqual(combo.currentBand(), -1) combo.setBand(1) self.assertEqual(combo.currentBand(), 1) combo.setShowNotSetOption(False) self.assertEqual(combo.currentBand(), 1) self.assertEqual(combo.count(), 1)
def testSelectByRect(self): """ Test selecting by rectangle """ layer = QgsVectorLayer(os.path.join(unitTestDataPath(), 'points.shp'), 'Points', 'ogr') # SetSelection layer.selectByRect(QgsRectangle(-112, 30, -94, 45), QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3, 7, 10, 11, 15])) # check that existing selection is cleared layer.selectByRect(QgsRectangle(-112, 30, -94, 37), QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3, 10, 15])) # SetSelection no matching layer.selectByRect(QgsRectangle(112, 30, 115, 45), QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([])) # AddToSelection layer.selectByRect(QgsRectangle(-112, 30, -94, 37), QgsVectorLayer.AddToSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3, 10, 15])) layer.selectByRect(QgsRectangle(-112, 37, -94, 45), QgsVectorLayer.AddToSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3, 7, 10, 11, 15])) # IntersectSelection layer.selectByRect(QgsRectangle(-112, 30, -94, 37), QgsVectorLayer.IntersectSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3, 10, 15])) layer.selectByIds([2, 10, 13]) layer.selectByRect(QgsRectangle(-112, 30, -94, 37), QgsVectorLayer.IntersectSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 10])) # RemoveFromSelection layer.selectByRect(QgsRectangle(-112, 30, -94, 45), QgsVectorLayer.SetSelection) layer.selectByRect(QgsRectangle(-112, 30, -94, 37), QgsVectorLayer.RemoveFromSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([7, 11])) layer.selectByRect(QgsRectangle(-112, 30, -94, 45), QgsVectorLayer.RemoveFromSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([]))
def testSimplifyIssue4189(self): """Test we can simplify a complex geometry. Note: there is a ticket related to this issue here: http://hub.qgis.org/issues/4189 Backstory: Ole Nielson pointed out an issue to me (Tim Sutton) where simplify ftools was dropping features. This test replicates that issues. Interestingly we could replicate the issue in PostGIS too: - doing straight simplify returned no feature - transforming to UTM49, then simplify with e.g. 200 threshold is ok - as above with 500 threshold drops the feature pgsql2shp -f /tmp/dissolve500.shp gis 'select *, transform(simplify(transform(geom,32649),500), 4326) as simplegeom from dissolve;' """ myWKTFile = file(os.path.join(unitTestDataPath('wkt'), 'simplify_error.wkt'), 'rt') myWKT = myWKTFile.readline() myWKTFile.close() print myWKT myGeometry = QgsGeometry().fromWkt(myWKT) assert myGeometry is not None myStartLength = len(myWKT) myTolerance = 0.00001 mySimpleGeometry = myGeometry.simplify(myTolerance) myEndLength = len(mySimpleGeometry.exportToWkt()) myMessage = 'Before simplify: %i\nAfter simplify: %i\n : Tolerance %e' % ( myStartLength, myEndLength, myTolerance) myMinimumLength = len('POLYGON(())') assert myEndLength > myMinimumLength, myMessage
def testSelectByIds(self): """ Test selecting by ID""" layer = QgsVectorLayer(os.path.join(unitTestDataPath(), 'points.shp'), 'Points', 'ogr') # SetSelection layer.selectByIds([1, 3, 5, 7], QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([1, 3, 5, 7])) # check that existing selection is cleared layer.selectByIds([2, 4, 6], QgsVectorLayer.SetSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 4, 6])) # AddToSelection layer.selectByIds([3, 5], QgsVectorLayer.AddToSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([2, 3, 4, 5, 6])) layer.selectByIds([1], QgsVectorLayer.AddToSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([1, 2, 3, 4, 5, 6])) # IntersectSelection layer.selectByIds([1, 3, 5, 6], QgsVectorLayer.IntersectSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([1, 3, 5, 6])) layer.selectByIds([1, 2, 5, 6], QgsVectorLayer.IntersectSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([1, 5, 6])) # RemoveFromSelection layer.selectByIds([2, 6, 7], QgsVectorLayer.RemoveFromSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([1, 5])) layer.selectByIds([1, 5], QgsVectorLayer.RemoveFromSelection) self.assertEqual(set(layer.selectedFeaturesIds()), set([]))
def _img_diff_error(self, response, headers, image, max_diff=100, max_size_diff=QSize(), unittest_data_path='control_images'): reference_path = unitTestDataPath(unittest_data_path) + '/qgis_server/' + image + '/' + image + '.png' self.store_reference(reference_path, response) self.assertEqual( headers.get("Content-Type"), "image/png", "Content type is wrong: %s\n%s" % (headers.get("Content-Type"), response)) test, report = self._img_diff(response, image, max_diff, max_size_diff) with open(os.path.join(tempfile.gettempdir(), image + "_result.png"), "rb") as rendered_file: encoded_rendered_file = base64.b64encode(rendered_file.read()) if not os.environ.get('ENCODED_OUTPUT'): message = "Image is wrong\: rendered file %s/%s_result.png" % (tempfile.gettempdir(), image) else: message = "Image is wrong\n%s\nImage:\necho '%s' | base64 -d >%s/%s_result.png" % ( report, encoded_rendered_file.strip().decode('utf8'), tempfile.gettempdir(), image ) # If the failure is in image sizes the diff file will not exists. if os.path.exists(os.path.join(tempfile.gettempdir(), image + "_result_diff.png")): with open(os.path.join(tempfile.gettempdir(), image + "_result_diff.png"), "rb") as diff_file: if not os.environ.get('ENCODED_OUTPUT'): message = "Image is wrong\: diff file %s/%s_result_diff.png" % (tempfile.gettempdir(), image) else: encoded_diff_file = base64.b64encode(diff_file.read()) message += "\nDiff:\necho '%s' | base64 -d > %s/%s_result_diff.png" % ( encoded_diff_file.strip().decode('utf8'), tempfile.gettempdir(), image ) self.assertTrue(test, message)
def testQgsSvgMarkerSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSvgMarkerSymbolLayer' 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 = QgsSvgMarkerSymbolLayer.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSvgMarkerSymbolLayer("")) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = '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 setUp(self): self.testDataDir = unitTestDataPath() self.success = False self.fail = False self.ids = None self.task = None
def testGdb(self): """ Test opening a GDB database layer""" gdb_path = os.path.join(unitTestDataPath(), 'test_gdb.gdb') for i in range(3): l = QgsVectorLayer(gdb_path + '|layerid=' + str(i), 'test', 'ogr') self.assertTrue(l.isValid())
def testTransparency(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage renderer = QgsSingleBandGrayRenderer(myRasterLayer.dataProvider(), 1) myRasterLayer.setRenderer(renderer) myRasterLayer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum, QgsRasterMinMaxOrigin.MinMax) myContrastEnhancement = myRasterLayer.renderer().contrastEnhancement() # print ("myContrastEnhancement.minimumValue = %.17g" % # myContrastEnhancement.minimumValue()) # print ("myContrastEnhancement.maximumValue = %.17g" % # myContrastEnhancement.maximumValue()) # Unfortunately the minimum/maximum values calculated in C++ and Python # are slightly different (e.g. 3.3999999521443642e+38 x # 3.3999999521444001e+38) # It is not clear where the precision is lost. # We set the same values as C++. myContrastEnhancement.setMinimumValue(-3.3319999287625854e+38) myContrastEnhancement.setMaximumValue(3.3999999521443642e+38) #myType = myRasterLayer.dataProvider().dataType(1); #myEnhancement = QgsContrastEnhancement(myType); myTransparentSingleValuePixelList = [] rasterTransparency = QgsRasterTransparency() myTransparentPixel1 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel1.min = -2.5840000772112106e+38 myTransparentPixel1.max = -1.0879999684602689e+38 myTransparentPixel1.percentTransparent = 50 myTransparentSingleValuePixelList.append(myTransparentPixel1) myTransparentPixel2 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel2.min = 1.359999960575336e+37 myTransparentPixel2.max = 9.520000231087593e+37 myTransparentPixel2.percentTransparent = 70 myTransparentSingleValuePixelList.append(myTransparentPixel2) rasterTransparency.setTransparentSingleValuePixelList( myTransparentSingleValuePixelList) rasterRenderer = myRasterLayer.renderer() assert rasterRenderer rasterRenderer.setRasterTransparency(rasterTransparency) QgsProject.instance().addMapLayers([myRasterLayer, ]) myMapSettings = QgsMapSettings() myMapSettings.setLayers([myRasterLayer]) myMapSettings.setExtent(myRasterLayer.extent()) myChecker = QgsRenderChecker() myChecker.setControlName("expected_raster_transparency") myChecker.setMapSettings(myMapSettings) myResultFlag = myChecker.runTest("raster_transparency_python") assert myResultFlag, "Raster transparency rendering test failed"
def testPaletted(self): """ test paletted raster renderer with raster with color table""" path = os.path.join(unitTestDataPath('raster'), 'with_color_table.tif') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) self.assertTrue(layer.isValid(), 'Raster not loaded: {}'.format(path)) renderer = QgsPalettedRasterRenderer(layer.dataProvider(), 1, [QgsPalettedRasterRenderer.Class(1, QColor(0, 255, 0), 'class 2'), QgsPalettedRasterRenderer.Class(3, QColor(255, 0, 0), 'class 1')]) self.assertEqual(renderer.nColors(), 2) self.assertEqual(renderer.usesBands(), [1]) # test labels self.assertEqual(renderer.label(1), 'class 2') self.assertEqual(renderer.label(3), 'class 1') self.assertFalse(renderer.label(101)) # test legend symbology - should be sorted by value legend = renderer.legendSymbologyItems() self.assertEqual(legend[0][0], 'class 2') self.assertEqual(legend[1][0], 'class 1') self.assertEqual(legend[0][1].name(), '#00ff00') self.assertEqual(legend[1][1].name(), '#ff0000') # test retrieving classes classes = renderer.classes() self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'class 1') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') # test set label # bad index renderer.setLabel(1212, 'bad') renderer.setLabel(3, 'new class') self.assertEqual(renderer.label(3), 'new class') # color ramp r = QgsLimitedRandomColorRamp(5) renderer.setSourceColorRamp(r) self.assertEqual(renderer.sourceColorRamp().type(), 'random') self.assertEqual(renderer.sourceColorRamp().count(), 5) # clone new_renderer = renderer.clone() classes = new_renderer.classes() self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'new class') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') self.assertEqual(new_renderer.sourceColorRamp().type(), 'random') self.assertEqual(new_renderer.sourceColorRamp().count(), 5) # write to xml and read doc = QDomDocument('testdoc') elem = doc.createElement('qgis') renderer.writeXml(doc, elem) restored = QgsPalettedRasterRenderer.create(elem.firstChild().toElement(), layer.dataProvider()) self.assertTrue(restored) self.assertEqual(restored.usesBands(), [1]) classes = restored.classes() self.assertTrue(classes) self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'new class') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') self.assertEqual(restored.sourceColorRamp().type(), 'random') self.assertEqual(restored.sourceColorRamp().count(), 5) # render test layer.setRenderer(renderer) ms = QgsMapSettings() ms.setLayers([layer]) ms.setExtent(layer.extent()) checker = QgsRenderChecker() checker.setControlName("expected_paletted_renderer") checker.setMapSettings(ms) self.assertTrue(checker.runTest("expected_paletted_renderer"), "Paletted rendering test failed")
def test_wfs3_collections_html(self): """Test WFS3 API collections in html format""" request = QgsBufferServerRequest('http://server.qgis.org/wfs3/collections.html') project = QgsProject() project.read(unitTestDataPath('qgis_server') + '/test_project.qgs') self.compareApi(request, project, 'test_wfs3_collections_project.html')
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") myRaster = QgsRasterLayer(myTempPath + "edge_problem.asc", "raster", "gdal") zs = QgsZonalStatistics(myVector, myRaster, "", 1, QgsZonalStatistics.All) 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 myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[4])) assert feat[4] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.47140452079103201, feat[5])) assert abs(feat[5] - 0.47140452079103201) < 0.00001, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[6])) assert feat[6] == 0.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[7])) assert feat[7] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[8])) assert feat[8] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[9])) assert feat[9] == 0.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[10])) assert feat[10] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (2.0, feat[11])) assert feat[11] == 2.0, 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 myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[4])) assert feat[4] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.49690399499995302, feat[5])) assert abs(feat[5] - 0.49690399499995302) < 0.00001, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[6])) assert feat[6] == 0.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[7])) assert feat[7] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[8])) assert feat[8] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[9])) assert feat[9] == 0.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[10])) assert feat[10] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (2.0, feat[11])) assert feat[11] == 2.0, 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 myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[4])) assert feat[4] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.372677996249965, feat[5])) assert abs(feat[5] - 0.372677996249965) < 0.00001, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[6])) assert feat[6] == 0.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[7])) assert feat[7] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[8])) assert feat[8] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.0, feat[9])) assert feat[9] == 0.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (1.0, feat[10])) assert feat[10] == 1.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (2.0, feat[11])) assert feat[11] == 2.0, myMessage
__copyright__ = 'Copyright 2017, The QGIS Project' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '6792d236c97b3fe3a5761dee1462729322bb5f84' import qgis # NOQA import os from qgis.core import QgsRectangle, QgsCoordinateReferenceSystem, QgsVectorLayer, QgsProject, QgsFeature, QgsGeometry from qgis.gui import QgsExtentGroupBox from qgis.PyQt.QtTest import QSignalSpy from qgis.testing import start_app, unittest from utilities import unitTestDataPath start_app() TEST_DATA_DIR = unitTestDataPath() class TestQgsExtentGroupBox(unittest.TestCase): def testGettersSetters(self): """ test widget getters/setters """ w = qgis.gui.QgsExtentGroupBox() w.setOriginalExtent(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem('epsg:3111')) self.assertEqual(w.originalExtent(), QgsRectangle(1, 2, 3, 4)) self.assertEqual(w.originalCrs().authid(), 'EPSG:3111') w.setCurrentExtent(QgsRectangle(11, 12, 13, 14), QgsCoordinateReferenceSystem('epsg:3113')) self.assertEqual(w.currentExtent(), QgsRectangle(11, 12, 13, 14))
def test_wfs3_field_filters_star(self): """Test field filters""" project = QgsProject() project.read(unitTestDataPath('qgis_server') + '/test_project.qgs') request = QgsBufferServerRequest('http://server.qgis.org/wfs3/collections/testlayer3/items?name=tw*') self.compareApi(request, project, 'test_wfs3_collections_items_testlayer3_name_eq_tw_star.json')
def testWriteSld(self): """Test SLD generation for the XMLS fields geneerated at RasterLayer level and not to the deeper renderer level.""" myPath = os.path.join(unitTestDataPath(), 'landsat.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage # do generic export with default layer values dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = root.elementsByTagName('sld:LayerFeatureConstraints') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = element.elementsByTagName('sld:FeatureTypeConstraint') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = root.elementsByTagName('sld:UserStyle') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() name = element.firstChildElement('sld:Name') self.assertFalse(name.isNull()) self.assertEqual(name.text(), 'landsat') abstract = element.firstChildElement('sld:Abstract') self.assertTrue(abstract.isNull()) title = element.firstChildElement('sld:Title') self.assertTrue(title.isNull()) featureTypeStyle = element.firstChildElement('sld:FeatureTypeStyle') self.assertFalse(featureTypeStyle.isNull()) rule = featureTypeStyle.firstChildElement('sld:Rule') self.assertFalse(rule.isNull()) temp = rule.firstChildElement('sld:MinScaleDenominator') self.assertTrue(temp.isNull()) temp = rule.firstChildElement('sld:MaxScaleDenominator') self.assertTrue(temp.isNull()) rasterSymbolizer = rule.firstChildElement('sld:RasterSymbolizer') self.assertFalse(rule.isNull()) vendorOptions = rasterSymbolizer.elementsByTagName('sld:VendorOption') self.assertTrue(vendorOptions.size() == 0) # set no default values and check exported sld myRasterLayer.setName('') myRasterLayer.setAbstract('fake') myRasterLayer.setTitle('fake') dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = root.elementsByTagName('sld:LayerFeatureConstraints') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = element.elementsByTagName('sld:FeatureTypeConstraint') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = root.elementsByTagName('sld:UserStyle') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() # no generated if empty name = element.firstChildElement('sld:Name') self.assertTrue(name.isNull()) # generated if not empty abstract = element.firstChildElement('sld:Abstract') self.assertFalse(abstract.isNull()) self.assertEqual(abstract.text(), 'fake') title = element.firstChildElement('sld:Title') self.assertFalse(title.isNull()) self.assertEqual(title.text(), 'fake') # if setScaleBasedVisibility is true print scales myRasterLayer.setScaleBasedVisibility(True) myRasterLayer.setMaximumScale(0.0001) myRasterLayer.setMinimumScale(0.01) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:Rule') self.assertEqual(len(elements), 1) rule = elements.at(0).toElement() self.assertFalse(rule.isNull()) temp = rule.firstChildElement('sld:MinScaleDenominator') self.assertFalse(temp.isNull()) self.assertEqual(temp.text(), '0.0001') temp = rule.firstChildElement('sld:MaxScaleDenominator') self.assertFalse(temp.isNull()) self.assertEqual(temp.text(), '0.01') # check non default hueSaturationFilter values hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleLightness) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'lightness') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleLuminosity) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'luminosity') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleAverage) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'average') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleOff) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', None) # manage colorize vendorOption tags hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(True) hue.setColorizeStrength(50) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', '1') self.assertVendorOption(element, 'colorizeRed', '255') self.assertVendorOption(element, 'colorizeGreen', '128') self.assertVendorOption(element, 'colorizeBlue', '128') self.assertVendorOption(element, 'colorizeStrength', '0.5') self.assertVendorOption(element, 'saturation', '0.498039') # other hue non default values, no colorize and saturation = 0 hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(False) hue.setSaturation(0) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', None) self.assertVendorOption(element, 'colorizeRed', None) self.assertVendorOption(element, 'colorizeGreen', None) self.assertVendorOption(element, 'colorizeBlue', None) self.assertVendorOption(element, 'colorizeStrength', None) self.assertVendorOption(element, 'saturation', None) self.assertVendorOption(element, 'brightness', None) self.assertVendorOption(element, 'contrast', None) # other hue non default values, no colorize and saturation = 100 hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(False) hue.setSaturation(100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', None) self.assertVendorOption(element, 'colorizeRed', None) self.assertVendorOption(element, 'colorizeGreen', None) self.assertVendorOption(element, 'colorizeBlue', None) self.assertVendorOption(element, 'colorizeStrength', None) self.assertVendorOption(element, 'saturation', '1') hue.setSaturation(-100) dom, root, errorMessage = self.layerToSld(myRasterLayer) self.assertVendorOption(root, 'saturation', '0') # brightness filter default values dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertTrue(myRasterLayer.brightnessFilter().brightness() == 0) self.assertTrue(myRasterLayer.brightnessFilter().contrast() == 0) self.assertVendorOption(element, 'brightness', None) self.assertVendorOption(element, 'contrast', None) # brightness filter no default values bf = myRasterLayer.brightnessFilter() bf.setBrightness(-255) bf.setContrast(-100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'brightness', '0') self.assertVendorOption(element, 'contrast', '0') bf.setBrightness(255) bf.setContrast(100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'brightness', '1') self.assertVendorOption(element, 'contrast', '1')
def setUpClass(cls): """Run before all tests: Creates an auth configuration""" cls.port = QGIS_POSTGRES_SERVER_PORT cls.username = '******' cls.password = '******' cls.dbname = 'test_basic' cls.tempfolder = QGIS_PG_TEST_PATH cls.certsdata_path = os.path.join(unitTestDataPath('auth_system'), 'certs_keys') cls.hostname = 'localhost' cls.data_path = os.path.join(cls.tempfolder, 'data') os.mkdir(cls.data_path) cls.setUpAuth() subprocess.check_call([ os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'initdb'), '-D', cls.data_path ]) # Disable SSL verification for setup operations env = dict(os.environ) env['PGSSLMODE'] = 'disable' cls.server = subprocess.Popen([ os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'postgres'), '-D', cls.data_path, '-c', "config_file=%s" % cls.pg_conf ], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait max 10 secs for the server to start end = time.time() + 10 while True: line = cls.server.stderr.readline() print(line) if line.find(b"database system is ready to accept") != -1: break if time.time() > end: raise Exception("Timeout connecting to PostgreSQL") # Create a DB subprocess.check_call([ os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'createdb'), '-h', 'localhost', '-p', cls.port, 'test_basic' ], env=env) # Inject test SQL from test path test_sql = os.path.join(unitTestDataPath('provider'), 'testdata_pg.sql') subprocess.check_call([ os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'psql'), '-h', 'localhost', '-p', cls.port, '-f', test_sql, cls.dbname ], env=env) # Create a role subprocess.check_call([ os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'psql'), '-h', 'localhost', '-p', cls.port, '-c', 'CREATE ROLE "%s" WITH SUPERUSER LOGIN PASSWORD \'%s\'' % (cls.username, cls.password), cls.dbname ], env=env)
def testOgcApiHandler(self): """Test OGC API Handler""" project = QgsProject() project.read(unitTestDataPath('qgis_server') + '/test_project.qgs') request = QgsBufferServerRequest('http://server.qgis.org/wfs3/collections/testlayer%20èé/items?limit=-1') response = QgsBufferServerResponse() ctx = QgsServerApiContext('/services/api1', request, response, project, self.server.serverInterface()) h = Handler1() self.assertTrue(h.staticPath(ctx).endswith('/resources/server/api/ogc/static')) self.assertEqual(h.path(), QtCore.QRegularExpression("/handlerone")) self.assertEqual(h.description(), 'The first handler ever') self.assertEqual(h.operationId(), 'handlerOne') self.assertEqual(h.summary(), 'First of its name') self.assertEqual(h.linkTitle(), 'Handler One Link Title') self.assertEqual(h.linkType(), QgsServerOgcApi.data) with self.assertRaises(QgsServerApiBadRequestException) as ex: h.handleRequest(ctx) self.assertEqual(str(ex.exception), 'Missing required argument: \'value1\'') r = ctx.response() self.assertEqual(r.data(), '') with self.assertRaises(QgsServerApiBadRequestException) as ex: h.values(ctx) self.assertEqual(str(ex.exception), 'Missing required argument: \'value1\'') # Add handler to API and test for /api2 ctx = QgsServerApiContext('/services/api2', request, response, project, self.server.serverInterface()) api = QgsServerOgcApi(self.server.serverInterface(), '/api2', 'apitwo', 'a second api', '1.2') api.registerHandler(h) # Add a second handler (will be tested later) h2 = Handler2() api.registerHandler(h2) ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api1')) with self.assertRaises(QgsServerApiBadRequestException) as ex: api.executeRequest(ctx) self.assertEqual(str(ex.exception), 'Requested URI does not match any registered API handler') ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api2')) with self.assertRaises(QgsServerApiBadRequestException) as ex: api.executeRequest(ctx) self.assertEqual(str(ex.exception), 'Requested URI does not match any registered API handler') ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api2/handlerone')) with self.assertRaises(QgsServerApiBadRequestException) as ex: api.executeRequest(ctx) self.assertEqual(str(ex.exception), 'Missing required argument: \'value1\'') ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api2/handlerone?value1=not+a+double')) with self.assertRaises(QgsServerApiBadRequestException) as ex: api.executeRequest(ctx) self.assertEqual(str(ex.exception), 'Argument \'value1\' could not be converted to Double') ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api2/handlerone?value1=1.2345')) params = h.values(ctx) self.assertEqual(params, {'value1': 1.2345}) api.executeRequest(ctx) self.assertEqual(json.loads(bytes(ctx.response().data()))['value1'], 1.2345) # Test path fragments extraction ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api2/handlertwo/00/555?value1=1.2345')) params = h2.values(ctx) self.assertEqual(params, {'code1': '00', 'value1': 1.2345, 'value2': None}) # Test string encoding ctx.request().setUrl(QtCore.QUrl('http://www.qgis.org/services/api2/handlertwo/00/555?value1=1.2345&value2=a%2Fstring%20some')) params = h2.values(ctx) self.assertEqual(params, {'code1': '00', 'value1': 1.2345, 'value2': 'a/string some'}) # Test links self.assertEqual(h2.href(ctx), 'http://www.qgis.org/services/api2/handlertwo/00/555?value1=1.2345&value2=a%2Fstring%20some') self.assertEqual(h2.href(ctx, '/extra'), 'http://www.qgis.org/services/api2/handlertwo/00/555/extra?value1=1.2345&value2=a%2Fstring%20some') self.assertEqual(h2.href(ctx, '/extra', 'json'), 'http://www.qgis.org/services/api2/handlertwo/00/555/extra.json?value1=1.2345&value2=a%2Fstring%20some') # Test template path self.assertTrue(h2.templatePath(ctx).endswith('/resources/server/api/ogc/templates/services/api2/handlerTwo.html'))
def setUpClass(cls): cls.zipDir = os.path.join(unitTestDataPath(), "zip")
def test_wfs3_collection_items_limit(self): """Test WFS3 API item limits""" project = QgsProject() project.read(unitTestDataPath('qgis_server') + '/test_project.qgs') request = QgsBufferServerRequest('http://server.qgis.org/wfs3/collections/testlayer%20èé/items?limit=1') self.compareApi(request, project, 'test_wfs3_collections_items_testlayer_èé_limit_1.json')
def testCase(self): self.TEST_DATA_DIR = unitTestDataPath() tmppath = tempfile.mkdtemp() for file in glob.glob( os.path.join(self.TEST_DATA_DIR, 'france_parts.*')): shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath) vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp") mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") QgsProject.instance().addMapLayers([mVectorLayer]) self.layers = [mVectorLayer] # create layout with layout map # select epsg:2154 crs = QgsCoordinateReferenceSystem() crs.createFromSrid(2154) QgsProject.instance().setCrs(crs) self.layout = QgsPrintLayout(QgsProject.instance()) self.layout.initializeDefaults() # fix the renderer, fill with green props = {"color": "0,127,0", 'outline_color': 'black'} fillSymbol = QgsFillSymbol.createSimple(props) renderer = QgsSingleSymbolRenderer(fillSymbol) mVectorLayer.setRenderer(renderer) # the atlas map self.atlas_map = QgsLayoutItemMap(self.layout) self.atlas_map.attemptSetSceneRect(QRectF(20, 20, 130, 130)) self.atlas_map.setFrameEnabled(True) self.atlas_map.setLayers([mVectorLayer]) self.layout.addLayoutItem(self.atlas_map) # the atlas self.atlas = self.layout.atlas() self.atlas.setCoverageLayer(mVectorLayer) self.atlas.setEnabled(True) # an overview self.overview = QgsLayoutItemMap(self.layout) self.overview.attemptSetSceneRect(QRectF(180, 20, 50, 50)) self.overview.setFrameEnabled(True) self.overview.overview().setLinkedMap(self.atlas_map) self.overview.setLayers([mVectorLayer]) self.layout.addLayoutItem(self.overview) nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887) self.overview.setExtent(nextent) # set the fill symbol of the overview map props2 = {"color": "127,0,0,127", 'outline_color': 'black'} fillSymbol2 = QgsFillSymbol.createSimple(props2) self.overview.overview().setFrameSymbol(fillSymbol2) # header label self.mLabel1 = QgsLayoutItemLabel(self.layout) self.layout.addLayoutItem(self.mLabel1) self.mLabel1.setText("[% \"NAME_1\" %] area") self.mLabel1.setFont(QgsFontUtils.getStandardTestFont()) self.mLabel1.adjustSizeToText() self.mLabel1.attemptSetSceneRect(QRectF(150, 5, 60, 15)) self.mLabel1.setMarginX(1) self.mLabel1.setMarginY(1) # feature number label self.mLabel2 = QgsLayoutItemLabel(self.layout) self.layout.addLayoutItem(self.mLabel2) self.mLabel2.setText( "# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]") self.mLabel2.setFont(QgsFontUtils.getStandardTestFont()) self.mLabel2.adjustSizeToText() self.mLabel2.attemptSetSceneRect(QRectF(150, 200, 60, 15)) self.mLabel2.setMarginX(1) self.mLabel2.setMarginY(1) self.filename_test() self.autoscale_render_test() self.fixedscale_render_test() self.predefinedscales_render_test() self.hidden_render_test() self.legend_test() self.rotation_test() shutil.rmtree(tmppath, True)
def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) self.testDataDir = unitTestDataPath() self.report = "<h1>Python Raster File Writer Tests</h1>\n"
class TestQgsPalLabeling(unittest.TestCase): _TestDataDir = unitTestDataPath() _PalDataDir = os.path.join(_TestDataDir, 'labeling') _PalFeaturesDb = os.path.join(_PalDataDir, 'pal_features_v3.sqlite') _TestFont = getTestFont() # Roman at 12 pt """:type: QFont""" _MapRegistry = None """:type: QgsProject""" _MapSettings = None """:type: QgsMapSettings""" _Canvas = None """:type: QgsMapCanvas""" _Pal = None """:type: QgsPalLabeling""" _BaseSetup = False @classmethod def setUpClass(cls): """Run before all tests""" # qgis iface cls._Iface = get_iface() cls._Canvas = cls._Iface.mapCanvas() # verify that spatialite provider is available msg = '\nSpatialite provider not found, SKIPPING TEST SUITE' # noinspection PyArgumentList res = 'spatialite' in QgsProviderRegistry.instance().providerList() assert res, msg cls._TestFunction = '' cls._TestGroup = '' cls._TestGroupPrefix = '' cls._TestGroupAbbr = '' cls._TestGroupCanvasAbbr = '' cls._TestImage = '' cls._TestMapSettings = None cls._Mismatch = 0 cls._Mismatches = dict() cls._ColorTol = 0 cls._ColorTols = dict() # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL # noinspection PyArgumentList cls._MapRegistry = QgsProject.instance() cls._MapSettings = cls.getBaseMapSettings() osize = cls._MapSettings.outputSize() cls._Canvas.resize(QSize(osize.width(), osize.height())) # necessary? # set color to match render test comparisons background cls._Canvas.setCanvasColor(cls._MapSettings.backgroundColor()) cls.setDefaultEngineSettings() msg = ('\nCould not initialize PAL labeling engine, ' 'SKIPPING TEST SUITE') assert cls._Pal, msg cls._BaseSetup = True @classmethod def tearDownClass(cls): """Run after all tests""" def setUp(self): """Run before each test.""" TestQgsPalLabeling.setDefaultEngineSettings() self.lyr = self.defaultLayerSettings() @classmethod def setDefaultEngineSettings(cls): """Restore default settings for pal labeling""" cls._Pal = QgsPalLabeling() @classmethod def removeAllLayers(cls): cls._MapSettings.setLayers([]) cls._MapRegistry.removeAllMapLayers() @classmethod def removeMapLayer(cls, layer): if layer is None: return lyr_id = layer.id() cls._MapRegistry.removeMapLayer(lyr_id) ms_layers = cls._MapSettings.layers() if layer in ms_layers: ms_layers.remove(layer) cls._MapSettings.setLayers(ms_layers) @classmethod def getTestFont(cls): return QFont(cls._TestFont) @classmethod def loadFeatureLayer(cls, table, chk=False): if chk and cls._MapRegistry.mapLayersByName(table): return uri = QgsDataSourceUri() uri.setDatabase(cls._PalFeaturesDb) uri.setDataSource('', table, 'geometry') vlayer = QgsVectorLayer(uri.uri(), table, 'spatialite') # .qml should contain only style for symbology vlayer.loadNamedStyle( os.path.join(cls._PalDataDir, '{0}.qml'.format(table))) # qDebug('render_lyr = {0}'.format(repr(vlayer))) cls._MapRegistry.addMapLayer(vlayer) # place new layer on top of render stack render_lyrs = [vlayer] render_lyrs.extend(cls._MapSettings.layers()) # qDebug('render_lyrs = {0}'.format(repr(render_lyrs))) cls._MapSettings.setLayers(render_lyrs) # zoom to aoi cls._MapSettings.setExtent(cls.aoiExtent()) cls._Canvas.zoomToFullExtent() return vlayer @classmethod def aoiExtent(cls): """Area of interest extent, which matches output aspect ratio""" uri = QgsDataSourceUri() uri.setDatabase(cls._PalFeaturesDb) uri.setDataSource('', 'aoi', 'geometry') aoilayer = QgsVectorLayer(uri.uri(), 'aoi', 'spatialite') return aoilayer.extent() @classmethod def getBaseMapSettings(cls): """ :rtype: QgsMapSettings """ ms = QgsMapSettings() crs = QgsCoordinateReferenceSystem() """:type: QgsCoordinateReferenceSystem""" # default for labeling test data: WGS 84 / UTM zone 13N crs.createFromSrid(32613) ms.setBackgroundColor(QColor(152, 219, 249)) ms.setOutputSize(QSize(420, 280)) ms.setOutputDpi(72) ms.setFlag(QgsMapSettings.Antialiasing, True) ms.setFlag(QgsMapSettings.UseAdvancedEffects, False) ms.setFlag(QgsMapSettings.ForceVectorOutput, False) # no caching? ms.setDestinationCrs(crs) ms.setExtent(cls.aoiExtent()) return ms def cloneMapSettings(self, oms): """ :param QgsMapSettings oms: Other QgsMapSettings :rtype: QgsMapSettings """ ms = QgsMapSettings() ms.setBackgroundColor(oms.backgroundColor()) ms.setOutputSize(oms.outputSize()) ms.setOutputDpi(oms.outputDpi()) ms.setFlags(oms.flags()) ms.setDestinationCrs(oms.destinationCrs()) ms.setExtent(oms.extent()) ms.setOutputImageFormat(oms.outputImageFormat()) ms.setLayers(oms.layers()) return ms def configTest(self, prefix, abbr): """Call in setUp() function of test subclass""" self._TestGroupPrefix = prefix self._TestGroupAbbr = abbr # insert test's Class.function marker into debug output stream # this helps visually track down the start of a test's debug output testid = self.id().split('.') self._TestGroup = testid[1] self._TestFunction = testid[2] testheader = '\n#####_____ {0}.{1} _____#####\n'.\ format(self._TestGroup, self._TestFunction) qDebug(testheader) # define the shorthand name of the test (to minimize file name length) self._Test = '{0}_{1}'.format(self._TestGroupAbbr, self._TestFunction.replace('test_', '')) def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in test data sources font = self.getTestFont() font.setPointSize(32) format = lyr.format() format.setFont(font) format.setNamedStyle('Roman') format.setSize(32) format.setSizeUnit(QgsUnitTypes.RenderPoints) format.buffer().setJoinStyle(Qt.BevelJoin) lyr.setFormat(format) return lyr @staticmethod def settingsDict(lyr): """Return a dict of layer-level labeling settings .. note:: QgsPalLayerSettings is not a QObject, so we can not collect current object properties, and the public properties of the C++ obj can't be listed with __dict__ or vars(). So, we sniff them out relative to their naming convention (camelCase), as reported by dir(). """ res = {} for attr in dir(lyr): if attr[0].islower() and not attr.startswith("__"): value = getattr(lyr, attr) if not isinstance(value, collections.Callable): res[attr] = value return res def controlImagePath(self, grpprefix=''): if not grpprefix: grpprefix = self._TestGroupPrefix return os.path.join(self._TestDataDir, 'control_images', 'expected_' + grpprefix, self._Test, self._Test + '.png') def saveControlImage(self, tmpimg=''): # don't save control images for RenderVsOtherOutput (Vs) tests, since # those control images belong to a different test result if ('PAL_CONTROL_IMAGE' not in os.environ or 'Vs' in self._TestGroup): return imgpath = self.controlImagePath() testdir = os.path.dirname(imgpath) if not os.path.exists(testdir): os.makedirs(testdir) imgbasepath = \ os.path.join(testdir, os.path.splitext(os.path.basename(imgpath))[0]) # remove any existing control images for f in glob.glob(imgbasepath + '.*'): if os.path.exists(f): os.remove(f) qDebug('Control image for {0}.{1}'.format(self._TestGroup, self._TestFunction)) if not tmpimg: # TODO: this can be deprecated, when per-base-test-class rendering # in checkTest() is verified OK for all classes qDebug('Rendering control to: {0}'.format(imgpath)) ms = self._MapSettings # class settings """:type: QgsMapSettings""" settings_type = 'Class' if self._TestMapSettings is not None: ms = self._TestMapSettings # per test settings settings_type = 'Test' qDebug('MapSettings type: {0}'.format(settings_type)) img = renderMapToImage(ms, parallel=False) """:type: QImage""" tmpimg = getTempfilePath('png') if not img.save(tmpimg, 'png'): os.unlink(tmpimg) raise OSError('Control not created for: {0}'.format(imgpath)) if tmpimg and os.path.exists(tmpimg): qDebug('Copying control to: {0}'.format(imgpath)) shutil.copyfile(tmpimg, imgpath) else: raise OSError('Control not copied to: {0}'.format(imgpath)) def renderCheck(self, mismatch=0, colortol=0, imgpath='', grpprefix=''): """Check rendered map canvas or existing image against control image :mismatch: number of pixels different from control, and still valid :colortol: maximum difference for each color component including alpha :imgpath: existing image; if present, skips rendering canvas :grpprefix: compare test image/rendering against different test group """ if not grpprefix: grpprefix = self._TestGroupPrefix chk = QgsMultiRenderChecker() chk.setControlPathPrefix('expected_' + grpprefix) chk.setControlName(self._Test) if imgpath: chk.setRenderedImage(imgpath) ms = self._MapSettings # class settings if self._TestMapSettings is not None: ms = self._TestMapSettings # per test settings chk.setMapSettings(ms) chk.setColorTolerance(colortol) # noinspection PyUnusedLocal res = chk.runTest(self._Test, mismatch) if PALREPORT and not res: # don't report ok checks testname = self._TestGroup + ' . ' + self._Test PALREPORTS[testname] = chk.report() msg = '\nRender check failed for "{0}"'.format(self._Test) return res, msg def checkTest(self, **kwargs): """Intended to be overridden in subclasses""" pass
def setUp(self): self.settings = QgsServerSettings() self.testdata_path = unitTestDataPath("qgis_server_settings")
def testIteration(self): p = QgsProject() vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp") vector_layer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") self.assertTrue(vector_layer.isValid()) p.addMapLayer(vector_layer) l = QgsPrintLayout(p) atlas = l.atlas() atlas.setEnabled(True) atlas.setCoverageLayer(vector_layer) atlas_feature_changed_spy = QSignalSpy(atlas.featureChanged) context_changed_spy = QSignalSpy(l.reportContext().changed) self.assertTrue(atlas.beginRender()) self.assertTrue(atlas.first()) self.assertEqual(len(atlas_feature_changed_spy), 1) self.assertEqual(len(context_changed_spy), 1) self.assertEqual(atlas.currentFeatureNumber(), 0) self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie') self.assertEqual(l.reportContext().layer(), vector_layer) f1 = l.reportContext().feature() self.assertTrue(atlas.next()) self.assertEqual(len(atlas_feature_changed_spy), 2) self.assertEqual(len(context_changed_spy), 2) self.assertEqual(atlas.currentFeatureNumber(), 1) self.assertEqual(l.reportContext().feature()[4], 'Bretagne') f2 = l.reportContext().feature() self.assertTrue(atlas.next()) self.assertEqual(len(atlas_feature_changed_spy), 3) self.assertEqual(len(context_changed_spy), 3) self.assertEqual(atlas.currentFeatureNumber(), 2) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') f3 = l.reportContext().feature() self.assertTrue(atlas.next()) self.assertEqual(len(atlas_feature_changed_spy), 4) self.assertEqual(len(context_changed_spy), 4) self.assertEqual(atlas.currentFeatureNumber(), 3) self.assertEqual(l.reportContext().feature()[4], 'Centre') f4 = l.reportContext().feature() self.assertFalse(atlas.next()) self.assertTrue(atlas.seekTo(2)) self.assertEqual(len(atlas_feature_changed_spy), 5) self.assertEqual(len(context_changed_spy), 5) self.assertEqual(atlas.currentFeatureNumber(), 2) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') self.assertTrue(atlas.last()) self.assertEqual(len(atlas_feature_changed_spy), 6) self.assertEqual(len(context_changed_spy), 6) self.assertEqual(atlas.currentFeatureNumber(), 3) self.assertEqual(l.reportContext().feature()[4], 'Centre') self.assertTrue(atlas.previous()) self.assertEqual(len(atlas_feature_changed_spy), 7) self.assertEqual(len(context_changed_spy), 7) self.assertEqual(atlas.currentFeatureNumber(), 2) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') self.assertTrue(atlas.previous()) self.assertTrue(atlas.previous()) self.assertEqual(len(atlas_feature_changed_spy), 9) self.assertFalse(atlas.previous()) self.assertEqual(len(atlas_feature_changed_spy), 9) self.assertTrue(atlas.endRender()) self.assertEqual(len(atlas_feature_changed_spy), 10) self.assertTrue(atlas.seekTo(f1)) self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie') self.assertTrue(atlas.seekTo(f4)) self.assertEqual(l.reportContext().feature()[4], 'Centre') self.assertTrue(atlas.seekTo(f3)) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') self.assertTrue(atlas.seekTo(f2)) self.assertEqual(l.reportContext().feature()[4], 'Bretagne') self.assertFalse(atlas.seekTo(QgsFeature(5)))
def testPalettedClassDataFromLayer(self): # no layer classes = QgsPalettedRasterRenderer.classDataFromRaster(None, 1) self.assertFalse(classes) # 10 class layer path = os.path.join(unitTestDataPath('raster'), 'with_color_table.tif') info = QFileInfo(path) base_name = info.baseName() layer10 = QgsRasterLayer(path, base_name) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 1) self.assertEqual(len(classes), 10) self.assertEqual(classes[0].value, 1) self.assertEqual(classes[0].label, '1') self.assertEqual(classes[1].value, 2) self.assertEqual(classes[1].label, '2') self.assertEqual(classes[2].value, 3) self.assertEqual(classes[2].label, '3') self.assertEqual(classes[3].value, 4) self.assertEqual(classes[3].label, '4') self.assertEqual(classes[4].value, 5) self.assertEqual(classes[4].label, '5') self.assertEqual(classes[5].value, 6) self.assertEqual(classes[5].label, '6') self.assertEqual(classes[6].value, 7) self.assertEqual(classes[6].label, '7') self.assertEqual(classes[7].value, 8) self.assertEqual(classes[7].label, '8') self.assertEqual(classes[8].value, 9) self.assertEqual(classes[8].label, '9') self.assertEqual(classes[9].value, 10) self.assertEqual(classes[9].label, '10') # bad band self.assertFalse(QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 10101010)) # with ramp r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200)) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 1, r) self.assertEqual(len(classes), 10) self.assertEqual(classes[0].color.name(), '#c80000') self.assertEqual(classes[1].color.name(), '#b21600') self.assertEqual(classes[2].color.name(), '#9c2c00') self.assertEqual(classes[3].color.name(), '#854200') self.assertEqual(classes[4].color.name(), '#6f5900') self.assertEqual(classes[5].color.name(), '#596f00') self.assertEqual(classes[6].color.name(), '#428500') self.assertEqual(classes[7].color.name(), '#2c9c00') self.assertEqual(classes[8].color.name(), '#16b200') self.assertEqual(classes[9].color.name(), '#00c800') # 30 class layer path = os.path.join(unitTestDataPath('raster'), 'unique_1.tif') info = QFileInfo(path) base_name = info.baseName() layer10 = QgsRasterLayer(path, base_name) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 1) self.assertEqual(len(classes), 30) expected = [11, 21, 22, 24, 31, 82, 2002, 2004, 2014, 2019, 2027, 2029, 2030, 2080, 2081, 2082, 2088, 2092, 2097, 2098, 2099, 2105, 2108, 2110, 2114, 2118, 2126, 2152, 2184, 2220] self.assertEqual([c.value for c in classes], expected) # bad layer path = os.path.join(unitTestDataPath('raster'), 'hub13263.vrt') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer.dataProvider(), 1) self.assertFalse(classes)
from qgis.core import QgsAuthCertUtils, QgsPkiBundle, QgsAuthMethodConfig, QgsAuthMethod, QgsAuthConfigSslServer, QgsApplication from qgis.gui import QgsAuthEditorWidgets from qgis.PyQt.QtCore import QFileInfo, qDebug from qgis.PyQt.QtNetwork import QSsl, QSslError, QSslCertificate, QSslSocket from qgis.PyQt.QtTest import QTest from qgis.PyQt.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout from qgis.testing import start_app, unittest from utilities import unitTestDataPath AUTHDBDIR = tempfile.mkdtemp() os.environ['QGIS_AUTH_DB_DIR_PATH'] = AUTHDBDIR start_app() TESTDATA = os.path.join(unitTestDataPath(), 'auth_system') PKIDATA = os.path.join(TESTDATA, 'certs_keys') class TestQgsAuthManager(unittest.TestCase): @classmethod def setUpClass(cls): cls.authm = QgsApplication.authManager() assert not cls.authm.isDisabled(), cls.authm.disabledMessage() cls.mpass = '******' # master password db1 = QFileInfo( cls.authm.authenticationDatabasePath()).canonicalFilePath() db2 = QFileInfo(AUTHDBDIR + '/qgis-auth.db').canonicalFilePath() msg = 'Auth db temp path does not match db path of manager'
def setUpClass(cls): cls.testdatapath = unitTestDataPath('qgis_server_security') + '/' cls.db = os.path.join(cls.testdatapath, 'db.sqlite') cls.db_clone = os.path.join(cls.testdatapath, 'db_clone.sqlite') cls.project = os.path.join(cls.testdatapath, 'project.qgs') cls.app = QgsApplication([], False)