Exemplo n.º 1
0
    def testRun(self):
        context = QgsProcessingContext()

        # try running an alg using processing.run - ownership of result layer should be transferred back to the caller
        res = processing.run('qgis:buffer',
                             {'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT},
                             context=context)
        self.assertIn('OUTPUT', res)
        # output should be the layer instance itself
        self.assertIsInstance(res['OUTPUT'], QgsVectorLayer)
        # Python should have ownership
        self.assertTrue(sip.ispyowned(res['OUTPUT']))
        del context
        gc.collect()
        self.assertFalse(sip.isdeleted(res['OUTPUT']))

        # now try using processing.run with is_child_algorithm = True. Ownership should remain with the context
        context = QgsProcessingContext()
        res = processing.run('qgis:buffer',
                             {'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT},
                             context=context, is_child_algorithm=True)
        self.assertIn('OUTPUT', res)
        # output should be a layer string reference, NOT the layer itself
        self.assertIsInstance(res['OUTPUT'], str)
        layer = context.temporaryLayerStore().mapLayer(res['OUTPUT'])
        self.assertIsInstance(layer, QgsVectorLayer)
        # context should have ownership
        self.assertFalse(sip.ispyowned(layer))
        del context
        gc.collect()
        self.assertTrue(sip.isdeleted(layer))
Exemplo n.º 2
0
    def testRun(self):
        context = QgsProcessingContext()

        # try running an alg using processing.run - ownership of result layer should be transferred back to the caller
        res = processing.run('qgis:buffer',
                             {'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT},
                             context=context)
        self.assertIn('OUTPUT', res)
        # output should be the layer instance itself
        self.assertIsInstance(res['OUTPUT'], QgsVectorLayer)
        # Python should have ownership
        self.assertTrue(sip.ispyowned(res['OUTPUT']))
        del context
        gc.collect()
        self.assertFalse(sip.isdeleted(res['OUTPUT']))

        # now try using processing.run with is_child_algorithm = True. Ownership should remain with the context
        context = QgsProcessingContext()
        res = processing.run('qgis:buffer',
                             {'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT},
                             context=context, is_child_algorithm=True)
        self.assertIn('OUTPUT', res)
        # output should be a layer string reference, NOT the layer itself
        self.assertIsInstance(res['OUTPUT'], str)
        layer = context.temporaryLayerStore().mapLayer(res['OUTPUT'])
        self.assertIsInstance(layer, QgsVectorLayer)
        # context should have ownership
        self.assertFalse(sip.ispyowned(layer))
        del context
        gc.collect()
        self.assertTrue(sip.isdeleted(layer))
Exemplo n.º 3
0
    def testFeatures(self):
        ProcessingConfig.initialize()

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # disable check for geometry validity
        prevInvalidGeoms = ProcessingConfig.getSetting(ProcessingConfig.FILTER_INVALID_GEOMETRIES)
        ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, 0)

        # test with all features
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 3)
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        # selection, but not using selected features
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # using selected features, but no selection
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.removeSelection()
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test that feature request is honored
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        features = vector.features(test_layer, QgsFeatureRequest().setFilterFids([1, 3, 5]))
        self.assertEqual(set([f.id() for f in features]), set([1, 3, 5]))

        # test that feature request is honored when using selections
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertTrue(all([not f.hasGeometry() for f in features]))
        features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)

        # test exception is raised when filtering invalid geoms
        #ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, 2)
        #test_layer_invalid_geoms = QgsVectorLayer(invalid_geometries(), 'test', 'ogr')
        #with self.assertRaises(GeoAlgorithmExecutionException):
        #    features = vector.features(test_layer_invalid_geoms)
        #    feats = [f for f in features]

        ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, prevInvalidGeoms)
Exemplo n.º 4
0
    def testUniqueValues(self):
        ProcessingConfig.initialize()

        # disable check for geometry validity
        prevInvalidGeoms = ProcessingConfig.getSetting(ProcessingConfig.FILTER_INVALID_GEOMETRIES)
        ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, 0)

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        v = vector.uniqueValues(test_layer, 2)
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # field by name
        v = vector.uniqueValues(test_layer, 'id2')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        v = vector.uniqueValues(test_layer, 'id')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([5, 7, 3]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)
        ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, prevInvalidGeoms)
Exemplo n.º 5
0
    def testFeatures(self):
        ProcessingConfig.initialize()

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # disable check for geometry validity
        prevInvalidGeoms = ProcessingConfig.getSetting(ProcessingConfig.FILTER_INVALID_GEOMETRIES)
        ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, 0)

        # test with all features
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 3)
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        # selection, but not using selected features
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # using selected features, but no selection
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.removeSelection()
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test that feature request is honored
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        features = vector.features(test_layer, QgsFeatureRequest().setFilterFids([1, 3, 5]))
        self.assertEqual(set([f.id() for f in features]), set([1, 3, 5]))

        # test that feature request is honored when using selections
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertTrue(all([not f.hasGeometry() for f in features]))
        features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)

        # test exception is raised when filtering invalid geoms
        #ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, 2)
        #test_layer_invalid_geoms = QgsVectorLayer(invalid_geometries(), 'test', 'ogr')
        #with self.assertRaises(GeoAlgorithmExecutionException):
        #    features = vector.features(test_layer_invalid_geoms)
        #    feats = [f for f in features]

        ProcessingConfig.setSettingValue(ProcessingConfig.FILTER_INVALID_GEOMETRIES, prevInvalidGeoms)
Exemplo n.º 6
0
    def testRunAndLoadResults(self):
        QgsProject.instance().removeAllMapLayers()
        context = QgsProcessingContext()

        # try running an alg using processing.runAndLoadResults - ownership of result layer should be transferred to
        # project, and layer should be present in project
        res = processing.runAndLoadResults(
            'qgis:buffer', {
                'DISTANCE': 1,
                'INPUT': points(),
                'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
            },
            context=context)
        self.assertIn('OUTPUT', res)
        # output should be the layer path
        self.assertIsInstance(res['OUTPUT'], str)

        self.assertEqual(
            context.layersToLoadOnCompletion()[res['OUTPUT']].project,
            QgsProject.instance())
        layer = QgsProject.instance().mapLayer(res['OUTPUT'])
        self.assertIsInstance(layer, QgsVectorLayer)

        # Python should NOT have ownership
        self.assertFalse(sip.ispyowned(layer))
Exemplo n.º 7
0
 def testOptional(self):
     parent_name = "test_parent_layer"
     test_data = points()
     test_layer = QgsVectorLayer(test_data, parent_name, "ogr")
     parent = ParameterVector(parent_name, parent_name)
     parent.setValue(test_layer)
     parameter = ParameterTableField("myName", "myDesc", parent_name, optional=True)
Exemplo n.º 8
0
 def testOptional(self):
     parent_name = 'test_parent_layer'
     test_data = points()
     test_layer = QgsVectorLayer(test_data, parent_name, 'ogr')
     parent = ParameterVector(parent_name, parent_name)
     parent.setValue(test_layer)
     ParameterTableField('myName', 'myDesc', parent_name, optional=True)
Exemplo n.º 9
0
    def checkGrassIsInstalled(ignoreRegistrySettings=False):
        if ProcessingUtils.isWindows():
            path = GrassUtils.grassPath()
            if path == "":
                return "GRASS folder is not configured.\nPlease configure it before running SAGA algorithms."
            cmdpath = os.path.join(path, "bin", "r.out.gdal.exe")
            if not os.path.exists(cmdpath):
                return (
                    "The specified GRASS folder does not contain a valid set of GRASS modules.\n"
                    +
                    "Please, go to the processing settings dialog, and check that the GRASS\n"
                    + "folder is correctly configured")

        settings = QSettings()
        GRASS_INSTALLED = "/ProcessingQGIS/GrassInstalled"
        if not ignoreRegistrySettings:
            if settings.contains(GRASS_INSTALLED):
                return
        try:
            from processing import runalg
            result = runalg(
                "grass:v.voronoi", points(), False, False,
                "270778.60198,270855.745301,4458921.97814,4458983.8488", -1,
                0.0001, 0, None)
            if not os.path.exists(result['output']):
                return "It seems that GRASS is not correctly installed and configured in your system.\nPlease install it before running GRASS algorithms."
        except:
            s = traceback.format_exc()
            return "Error while checking GRASS installation. GRASS might not be correctly configured.\n" + s

        settings.setValue(GRASS_INSTALLED, True)
Exemplo n.º 10
0
 def testOptional(self):
     parent_name = 'test_parent_layer'
     test_data = points()
     test_layer = QgsVectorLayer(test_data, parent_name, 'ogr')
     parent = ParameterVector(parent_name, parent_name)
     parent.setValue(test_layer)
     ParameterTableField('myName', 'myDesc', parent_name, optional=True)
Exemplo n.º 11
0
    def checkGrassIsInstalled(ignoreRegistrySettings=False):
        if isWindows():
            path = GrassUtils.grassPath()
            if path == "":
                return "GRASS folder is not configured.\nPlease configure it before running SAGA algorithms."
            cmdpath = os.path.join(path, "bin","r.out.gdal.exe")
            if not os.path.exists(cmdpath):
                return ("The specified GRASS folder does not contain a valid set of GRASS modules.\n"
                        + "Please, go to the processing settings dialog, and check that the GRASS\n"
                        + "folder is correctly configured")

        settings = QSettings()
        GRASS_INSTALLED = "/ProcessingQGIS/GrassInstalled"
        if not ignoreRegistrySettings:
            if settings.contains(GRASS_INSTALLED):
                return
        try:
            from processing import runalg
            result = runalg("grass:v.voronoi", points(),False,False,"270778.60198,270855.745301,4458921.97814,4458983.8488",-1,0.0001, 0, None)
            if not os.path.exists(result['output']):
                return "It seems that GRASS is not correctly installed and configured in your system.\nPlease install it before running GRASS algorithms."
        except:
            s = traceback.format_exc()
            return "Error while checking GRASS installation. GRASS might not be correctly configured.\n" + s;

        settings.setValue(GRASS_INSTALLED, True)
Exemplo n.º 12
0
    def testUniqueValues(self):
        ProcessingConfig.initialize()

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        v = vector.uniqueValues(test_layer, 2)
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # field by name
        v = vector.uniqueValues(test_layer, 'id2')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(
            ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        v = vector.uniqueValues(test_layer, 'id')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([5, 7, 3]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED,
                                         previous_value)
Exemplo n.º 13
0
    def testValues(self):
        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        res = vector.values(test_layer, 1)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # field by name
        res = vector.values(test_layer, 'id')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # two fields
        res = vector.values(test_layer, 1, 2)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name
        res = vector.values(test_layer, 'id', 'id2')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res['id2'], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name and index
        res = vector.values(test_layer, 'id', 2)
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])
Exemplo n.º 14
0
    def checkSagaIsInstalled(ignoreRegistrySettings=False):
        if ProcessingUtils.isWindows():
            path = SagaUtils.sagaPath()
            if path == "":
                return "SAGA folder is not configured.\nPlease configure it before running SAGA algorithms."
            cmdpath = os.path.join(path, "saga_cmd.exe")
            if not os.path.exists(cmdpath):
                return ("The specified SAGA folder does not contain a valid SAGA executable.\n"
                        + "Please, go to the processing settings dialog, and check that the SAGA\n"
                        + "folder is correctly configured")

        settings = QSettings()
        SAGA_INSTALLED = "/ProcessingQGIS/SagaInstalled"
        if not ignoreRegistrySettings:
            if settings.contains(SAGA_INSTALLED):
                return

        try:
            from processing import runalg
            result = runalg("saga:thiessenpolygons", points(), None)
            if not os.path.exists(result['POLYGONS']):
                return "It seems that SAGA is not correctly installed in your system.\nPlease install it before running SAGA algorithms."
        except:
            s = traceback.format_exc()
            return "Error while checking SAGA installation. SAGA might not be correctly configured.\n" + s;

        settings.setValue(SAGA_INSTALLED, True)
Exemplo n.º 15
0
    def testValues(self):
        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        res = vector.values(test_layer, 1)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # field by name
        res = vector.values(test_layer, 'id')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # two fields
        res = vector.values(test_layer, 1, 2)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name
        res = vector.values(test_layer, 'id', 'id2')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res['id2'], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name and index
        res = vector.values(test_layer, 'id', 2)
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])
Exemplo n.º 16
0
    def checkSagaIsInstalled(ignoreRegistrySettings=False):
        if ProcessingUtils.isWindows():
            path = SagaUtils.sagaPath()
            if path == "":
                return "SAGA folder is not configured.\nPlease configure it before running SAGA algorithms."
            cmdpath = os.path.join(path, "saga_cmd.exe")
            if not os.path.exists(cmdpath):
                return (
                    "The specified SAGA folder does not contain a valid SAGA executable.\n"
                    + "Please, go to the processing settings dialog, and check that the SAGA\n"
                    + "folder is correctly configured"
                )

        settings = QSettings()
        SAGA_INSTALLED = "/ProcessingQGIS/SagaInstalled"
        if not ignoreRegistrySettings:
            if settings.contains(SAGA_INSTALLED):
                return

        try:
            from processing import runalg

            result = runalg("saga:thiessenpolygons", points(), None)
            if not os.path.exists(result["POLYGONS"]):
                return "It seems that SAGA is not correctly installed in your system.\nPlease install it before running SAGA algorithms."
        except:
            s = traceback.format_exc()
            return "Error while checking SAGA installation. SAGA might not be correctly configured.\n" + s

        settings.setValue(SAGA_INSTALLED, True)
Exemplo n.º 17
0
    def checkGrassIsInstalled(ignorePreviousState=False):
        if isWindows():
            path = GrassUtils.grassPath()
            if path == "":
                return GrassUtils.tr(
                    "GRASS folder is not configured.\nPlease configure " "it before running GRASS algorithms."
                )
            cmdpath = os.path.join(path, "bin", "r.out.gdal.exe")
            if not os.path.exists(cmdpath):
                return GrassUtils.tr(
                    'The specified GRASS folder "{}" does not contain a valid '
                    "set of GRASS modules. Please, go to the Processing "
                    "settings dialog, and check that the GRASS folder is "
                    "correctly configured".format(os.path.join(path, "bin"))
                )

        if not ignorePreviousState:
            if GrassUtils.isGrassInstalled:
                return
        try:
            from processing import runalg

            result = runalg("grass:v.voronoi", points(), False, False, None, -1, 0.0001, 0, None)
            if not os.path.exists(result["output"]):
                return GrassUtils.tr(
                    "It seems that GRASS is not correctly installed and "
                    "configured in your system.\nPlease install it before "
                    "running GRASS algorithms."
                )
        except:
            return GrassUtils.tr(
                "Error while checking GRASS installation. GRASS might not " "be correctly configured.\n"
            )

        GrassUtils.isGrassInstalled = True
Exemplo n.º 18
0
    def testUniqueValues(self):
        ProcessingConfig.initialize()

        # disable check for geometry validity
        prevInvalidGeoms = ProcessingConfig.getSetting(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES)
        ProcessingConfig.setSettingValue(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES, 0)

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        v = vector.uniqueValues(test_layer, 2)
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # field by name
        v = vector.uniqueValues(test_layer, 'id2')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(
            ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        v = vector.uniqueValues(test_layer, 'id')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([5, 7, 3]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED,
                                         previous_value)
        ProcessingConfig.setSettingValue(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES, prevInvalidGeoms)
Exemplo n.º 19
0
    def testUniqueValues(self):
        ProcessingConfig.initialize()

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        v = vector.uniqueValues(test_layer, 2)
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # field by name
        v = vector.uniqueValues(test_layer, 'id2')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([2, 1, 0]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        v = vector.uniqueValues(test_layer, 'id')
        self.assertEqual(len(v), len(set(v)))
        self.assertEqual(set(v), set([5, 7, 3]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)
Exemplo n.º 20
0
 def test_attributeValues(self):
     layer = processing.getobject(points())
     attributeValues = values(layer, "ID")
     i = 1
     for value in attributeValues['ID']:
         self.assertEqual(int(i), int(value))
         i += 1
     self.assertEquals(13, i)
Exemplo n.º 21
0
 def test_featuresWithSelection(self):
     layer = processing.getobject(points())
     feature = layer.getFeatures().next()
     selected = [feature.id()]
     layer.setSelectedFeatures(selected)
     features = processing.getfeatures(layer)
     self.assertEqual(1, len(features))
     layer.setSelectedFeatures([])
Exemplo n.º 22
0
 def test_attributeValues(self):
     layer = processing.getObject(points())
     attributeValues = values(layer, "ID")
     i = 1
     for value in attributeValues['ID']:
         self.assertEqual(int(i), int(value))
         i+=1
     self.assertEquals(13,i)
Exemplo n.º 23
0
 def test_featuresWithSelection(self):
     layer = processing.getObject(points())
     feature = layer.getFeatures().next()
     selected = [feature.id()]
     layer.setSelectedFeatures(selected)
     features = processing.features(layer)
     self.assertEqual(1, len(features))
     layer.setSelectedFeatures([])
Exemplo n.º 24
0
    def testFeatures(self):
        ProcessingConfig.initialize()

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # test with all features
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]),
                         set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(
            ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 3)
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        # selection, but not using selected features
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]),
                         set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # using selected features, but no selection
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.removeSelection()
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]),
                         set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test that feature request is honored
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        features = vector.features(
            test_layer,
            QgsFeatureRequest().setFilterFids([1, 3, 5]))
        self.assertEqual(set([f.id() for f in features]), set([1, 3, 5]))

        # test that feature request is honored when using selections
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(
            test_layer,
            QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertTrue(all([not f.hasGeometry() for f in features]))
        features = vector.features(
            test_layer,
            QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED,
                                         previous_value)
Exemplo n.º 25
0
    def testScriptCode(self):
        parent_name = 'test_parent_layer'
        test_data = points()
        test_layer = QgsVectorLayer(test_data, parent_name, 'ogr')  # NOQA
        parameter = ParameterTableField('myName', 'myDesc', parent_name)
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertIsInstance(result, ParameterTableField)

        parameter.optional = True
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertIsInstance(result, ParameterTableField)
        self.assertTrue(result.optional)
Exemplo n.º 26
0
    def testScriptCode(self):
        parent_name = "test_parent_layer"
        test_data = points()
        test_layer = QgsVectorLayer(test_data, parent_name, "ogr")
        parameter = ParameterTableField("myName", "myDesc", parent_name)
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertIsInstance(result, ParameterTableField)

        parameter.optional = True
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertIsInstance(result, ParameterTableField)
        self.assertTrue(result.optional)
Exemplo n.º 27
0
    def testScriptCode(self):
        parent_name = 'test_parent_layer'
        test_data = points()
        test_layer = QgsVectorLayer(test_data, parent_name, 'ogr')
        parameter = ParameterTableField(
            'myName', 'myDesc', parent_name)
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertTrue(isinstance(result, ParameterTableField))

        parameter.optional = True
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertTrue(isinstance(result, ParameterTableField))
        self.assertTrue(result.optional)
Exemplo n.º 28
0
    def testValues(self):
        ProcessingConfig.initialize()

        # disable check for geometry validity
        prevInvalidGeoms = ProcessingConfig.getSetting(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES)
        ProcessingConfig.setSettingValue(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES, 0)

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        res = vector.values(test_layer, 1)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # field by name
        res = vector.values(test_layer, 'id')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # two fields
        res = vector.values(test_layer, 1, 2)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name
        res = vector.values(test_layer, 'id', 'id2')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res['id2'], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name and index
        res = vector.values(test_layer, 'id', 2)
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # test with selected features
        previous_value = ProcessingConfig.getSetting(
            ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        res = vector.values(test_layer, 1)
        self.assertEqual(set(res[1]), set([5, 7, 3]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED,
                                         previous_value)
        ProcessingConfig.setSettingValue(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES, prevInvalidGeoms)
Exemplo n.º 29
0
    def testValues(self):
        ProcessingConfig.initialize()

        # disable check for geometry validity
        prevInvalidGeoms = ProcessingConfig.getSetting(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES)
        ProcessingConfig.setSettingValue(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES, 0)

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        res = vector.values(test_layer, 1)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # field by name
        res = vector.values(test_layer, 'id')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # two fields
        res = vector.values(test_layer, 1, 2)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name
        res = vector.values(test_layer, 'id', 'id2')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res['id2'], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name and index
        res = vector.values(test_layer, 'id', 2)
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # test with selected features
        previous_value = ProcessingConfig.getSetting(
            ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        res = vector.values(test_layer, 1)
        self.assertEqual(set(res[1]), set([5, 7, 3]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED,
                                         previous_value)
        ProcessingConfig.setSettingValue(
            ProcessingConfig.FILTER_INVALID_GEOMETRIES, prevInvalidGeoms)
Exemplo n.º 30
0
    def testFeatures(self):
        ProcessingConfig.initialize()

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # test with all features
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test with selected features
        previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 3)
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        # selection, but not using selected features
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # using selected features, but no selection
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.removeSelection()
        features = vector.features(test_layer)
        self.assertEqual(len(features), 9)
        self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8]))

        # test that feature request is honored
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
        features = vector.features(test_layer, QgsFeatureRequest().setFilterFids([1, 3, 5]))
        self.assertEqual(set([f.id() for f in features]), set([1, 3, 5]))

        # test that feature request is honored when using selections
        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
        test_layer.selectByIds([2, 4, 6])
        features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertTrue(all([not f.hasGeometry() for f in features]))
        features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
        self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))

        ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)
Exemplo n.º 31
0
    def checkGrassIsInstalled(ignorePreviousState=False):
        if isWindows():
            path = GrassUtils.grassPath()
            if path == "":
                return "GRASS folder is not configured.\nPlease configure \
                        it before running GRASS algorithms."
            cmdpath = os.path.join(path, "bin", "r.out.gdal.exe")
            if not os.path.exists(cmdpath):
                return (
                    "The specified GRASS folder does not contain a valid \
                        set of GRASS modules.\n"
                    + "Please, go to the Processing settings dialog, and \
                        check that the GRASS\n"
                    + "folder is correctly configured"
                )

        if not ignorePreviousState:
            if GrassUtils.isGrassInstalled:
                return
        try:
            from processing import runalg

            result = runalg(
                "grass:v.voronoi",
                points(),
                False,
                False,
                "270778.60198,270855.745301,4458921.97814,4458983.8488",
                -1,
                0.0001,
                0,
                None,
            )
            if not os.path.exists(result["output"]):
                return "It seems that GRASS is not correctly installed and \
                    configured in your system.\nPlease install it before \
                    running GRASS algorithms."
        except:
            s = traceback.format_exc()
            return (
                "Error while checking GRASS installation. GRASS might not \
                be correctly configured.\n"
                + s
            )

        GrassUtils.isGrassInstalled = True
Exemplo n.º 32
0
 def test_qgiscountpointsinpolygon(self):
     outputs=processing.runalg("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS", self.getOutputFile())
     output=outputs['OUTPUT']
     layer=QGisLayers.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_A','POLY_ST_A','NUMPOINTS']
     expectedtypes=['Integer','Real','String','Real']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.getfeatures(layer)
     self.assertEqual(2, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["1","1.1","string a","6"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 33
0
 def testWrongformat(self):
     outputs=processing.runalg("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS",getTempFilename("wrongext"))
     output=outputs['OUTPUT']
     self.assertTrue(output.endswith('shp'))
     layer=dataobjects.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_A','POLY_ST_A','NUMPOINTS']
     expectedtypes=['Integer','Real','String','Real']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.features(layer)
     self.assertEqual(2, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["1","1.1","string a","6.0"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 34
0
    def checkGrass7IsInstalled(ignorePreviousState=False):
        if isWindows():
            path = Grass7Utils.grassPath()
            if path == '':
                return Grass7Utils.tr(
                    'GRASS GIS 7 folder is not configured. Please configure '
                    'it before running GRASS GIS 7 algorithms.')
            cmdpath = os.path.join(path, 'bin', 'r.out.gdal.exe')
            if not os.path.exists(cmdpath):
                return Grass7Utils.tr(
                    'The specified GRASS 7 folder "{}" does not contain '
                    'a valid set of GRASS 7 modules.\nPlease, go to the '
                    'Processing settings dialog, and check that the '
                    'GRASS 7\nfolder is correctly configured'.format(
                        os.path.join(path, 'bin')))

        if not ignorePreviousState:
            if Grass7Utils.isGrass7Installed:
                return
        try:
            from processing import runalg
            result = runalg(
                'grass7:v.voronoi',
                points(),
                False,
                False,
                '270778.60198,270855.745301,4458921.97814,4458983.8488',
                -1,
                0.0001,
                0,
                None,
            )
            if not os.path.exists(result['output']):
                return Grass7Utils.tr(
                    'It seems that GRASS GIS 7 is not correctly installed and '
                    'configured in your system.\nPlease install it before '
                    'running GRASS GIS 7 algorithms.')
        except:
            return Grass7Utils.tr(
                'Error while checking GRASS GIS 7 installation. GRASS GIS 7 '
                'might not be correctly configured.\n')

        Grass7Utils.isGrass7Installed = True
Exemplo n.º 35
0
 def testWrongformat(self):
     outputs=processing.runalg("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS",ProcessingUtils.getTempFilename("wrongext"))
     output=outputs['OUTPUT']
     self.assertTrue(output.endswith('shp'))
     layer=QGisLayers.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_A','POLY_ST_A','NUMPOINTS']
     expectedtypes=['Integer','Real','String','Real']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.getfeatures(layer)
     self.assertEqual(2, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["1","1.1","string a","6.0"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 36
0
    def checkGrass7IsInstalled(ignorePreviousState=False):
        if isWindows():
            path = Grass7Utils.grassPath()
            if path == '':
                return Grass7Utils.tr(
                    'GRASS GIS 7 folder is not configured. Please configure '
                    'it before running GRASS GIS 7 algorithms.')
            cmdpath = os.path.join(path, 'bin', 'r.out.gdal.exe')
            if not os.path.exists(cmdpath):
                return Grass7Utils.tr(
                    'The specified GRASS 7 folder "{}" does not contain '
                    'a valid set of GRASS 7 modules.\nPlease, go to the '
                    'Processing settings dialog, and check that the '
                    'GRASS 7\nfolder is correctly configured'.format(
                        os.path.join(path, 'bin')))

        if not ignorePreviousState:
            if Grass7Utils.isGrass7Installed:
                return
        try:
            from processing import run
            result = run(
                'grass7:v.voronoi',
                points(),
                False,
                False,
                None,
                -1,
                0.0001,
                0,
                None,
            )
            if not os.path.exists(result['output']):
                return Grass7Utils.tr(
                    'It seems that GRASS GIS 7 is not correctly installed and '
                    'configured in your system.\nPlease install it before '
                    'running GRASS GIS 7 algorithms.')
        except:
            return Grass7Utils.tr(
                'Error while checking GRASS GIS 7 installation. GRASS GIS 7 '
                'might not be correctly configured.\n')

        Grass7Utils.isGrass7Installed = True
Exemplo n.º 37
0
    def testRunAndLoadResults(self):
        QgsProject.instance().removeAllMapLayers()
        context = QgsProcessingContext()

        # try running an alg using processing.runAndLoadResults - ownership of result layer should be transferred to
        # project, and layer should be present in project
        res = processing.runAndLoadResults('qgis:buffer',
                                           {'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT},
                                           context=context)
        self.assertIn('OUTPUT', res)
        # output should be the layer path
        self.assertIsInstance(res['OUTPUT'], str)

        self.assertEqual(context.layersToLoadOnCompletion()[res['OUTPUT']].project, QgsProject.instance())
        layer = QgsProject.instance().mapLayer(res['OUTPUT'])
        self.assertIsInstance(layer, QgsVectorLayer)

        # Python should NOT have ownership
        self.assertFalse(sip.ispyowned(layer))
Exemplo n.º 38
0
    def checkGrassIsInstalled(ignorePreviousState=False):
        if isWindows():
            path = GrassUtils.grassPath()
            if path == '':
                return GrassUtils.tr(
                    'GRASS folder is not configured.\nPlease configure '
                    'it before running GRASS algorithms.')
            cmdpath = os.path.join(path, 'bin', 'r.out.gdal.exe')
            if not os.path.exists(cmdpath):
                return GrassUtils.tr(
                    'The specified GRASS folder "{}" does not contain a valid '
                    'set of GRASS modules. Please, go to the Processing '
                    'settings dialog, and check that the GRASS folder is '
                    'correctly configured'.format(os.path.join(path, 'bin')))

        if not ignorePreviousState:
            if GrassUtils.isGrassInstalled:
                return
        try:
            from processing import runalg
            result = runalg(
                'grass:v.voronoi',
                points(),
                False,
                False,
                '270778.60198,270855.745301,4458921.97814,4458983.8488',
                -1,
                0.0001,
                0,
                None,
            )
            if not os.path.exists(result['output']):
                return GrassUtils.tr(
                    'It seems that GRASS is not correctly installed and '
                    'configured in your system.\nPlease install it before '
                    'running GRASS algorithms.')
        except:
            return GrassUtils.tr(
                'Error while checking GRASS installation. GRASS might not '
                'be correctly configured.\n')

        GrassUtils.isGrassInstalled = True
Exemplo n.º 39
0
    def checkGrassIsInstalled(ignorePreviousState=False):
        if isWindows():
            path = GrassUtils.grassPath()
            if path == '':
                return GrassUtils.tr(
                    'GRASS folder is not configured.\nPlease configure '
                    'it before running GRASS algorithms.')
            cmdpath = os.path.join(path, 'bin', 'r.out.gdal.exe')
            if not os.path.exists(cmdpath):
                return GrassUtils.tr(
                    'The specified GRASS folder "{}" does not contain a valid '
                    'set of GRASS modules. Please, go to the Processing '
                    'settings dialog, and check that the GRASS folder is '
                    'correctly configured'.format(os.path.join(path, 'bin')))

        if not ignorePreviousState:
            if GrassUtils.isGrassInstalled:
                return
        try:
            from processing import runalg
            result = runalg(
                'grass:v.voronoi',
                points(),
                False,
                False,
                None,
                -1,
                0.0001,
                0,
                None,
            )
            if not os.path.exists(result['output']):
                return GrassUtils.tr(
                    'It seems that GRASS is not correctly installed and '
                    'configured in your system.\nPlease install it before '
                    'running GRASS algorithms.')
        except:
            return GrassUtils.tr(
                'Error while checking GRASS installation. GRASS might not '
                'be correctly configured.\n')

        GrassUtils.isGrassInstalled = True
Exemplo n.º 40
0
    def checkGrass7IsInstalled(ignorePreviousState=False):
        if isWindows():
            path = Grass7Utils.grassPath()
            if path == '':
                return 'GRASS GIS 7 folder is not configured.\nPlease configure \
                        it before running GRASS GIS 7 algorithms.'

            cmdpath = os.path.join(path, 'bin', 'r.out.gdal.exe')
            if not os.path.exists(cmdpath):
                return 'The specified GRASS GIS 7 folder does not contain a valid \
                        set of GRASS GIS 7 modules.\n' \
                        + 'Please, go to the Processing settings dialog, and \
                        check that the GRASS GIS 7\n' \
                        + 'folder is correctly configured'

        if not ignorePreviousState:
            if Grass7Utils.isGrass7Installed:
                return
        try:
            from processing import runalg
            result = runalg(
                'grass7:v.voronoi',
                points(),
                False,
                False,
                '270778.60198,270855.745301,4458921.97814,4458983.8488',
                -1,
                0.0001,
                0,
                None,
            )
            if not os.path.exists(result['output']):
                return 'It seems that GRASS GIS 7 is not correctly installed and \
                    configured in your system.\nPlease install it before \
                    running GRASS GIS 7 algorithms.'

        except:
            s = traceback.format_exc()
            return 'Error while checking GRASS GIS 7 installation. GRASS GIS 7 might not \
                be correctly configured.\n' + s

        Grass7Utils.isGrass7Installed = True
Exemplo n.º 41
0
 def test_modeleroptionalfield(self):
     outputs = processing.runalg('modeler:optionalfield', points(), None)
     output = outputs['OUTPUT_ALG0']
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['id', 'value', 'area', 'perim']
     expectedtypes = ['Integer', 'String', 'Real', 'Real']
     names = [unicode(f.name()) for f in fields]
     types = [unicode(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(1, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ['0', 'all', '3592.818848', '230.989919']
     values = [unicode(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POLYGON((270839.46818665 4458921.97813894,270778.60197966 4458935.96883677,270786.54279065 4458980.04784113,270803.15756434 4458983.84880322,270839.65586926 4458983.16267036,270855.74530134 4458940.79948673,270839.46818665 4458921.97813894))'
     self.assertEqual(wkt, unicode(feature.geometry().exportToWkt()))
Exemplo n.º 42
0
 def test_qgiscountpointsinpolygon(self):
     outputs = processing.runalg('qgis:countpointsinpolygon', polygons(),
                                 points(), 'NUMPOINTS',
                                 self.getOutputFile())
     output = outputs['OUTPUT']
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['ID', 'POLY_NUM_A', 'POLY_ST_A', 'NUMPOINTS']
     expectedtypes = ['Integer', 'Real', 'String', 'Real']
     names = [unicode(f.name()) for f in fields]
     types = [unicode(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(2, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ['1', '1.1', 'string a', '6']
     values = [unicode(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 43
0
 def test_qgiscountpointsinpolygon(self):
     outputs = processing.runalg('qgis:countpointsinpolygon', polygons(),
                                 points(), 'NUMPOINTS',
                                 self.getOutputFile())
     output = outputs['OUTPUT']
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['ID', 'POLY_NUM_A', 'POLY_ST_A', 'NUMPOINTS']
     expectedtypes = ['Integer', 'Real', 'String', 'Real']
     names = [unicode(f.name()) for f in fields]
     types = [unicode(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(2, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ['1', '1.1', 'string a', '6']
     values = [unicode(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 44
0
 def test_qgiscountpointsinpolygon(self):
     outputs = processing.runalg(
         "qgis:countpointsinpolygon", polygons(), points(), "NUMPOINTS", self.getOutputFile()
     )
     output = outputs["OUTPUT"]
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ["ID", "POLY_NUM_A", "POLY_ST_A", "NUMPOINTS"]
     expectedtypes = ["Integer", "Real", "String", "Real"]
     names = [unicode(f.name()) for f in fields]
     types = [unicode(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(2, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["1", "1.1", "string a", "6"]
     values = [unicode(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 45
0
 def test_modeleroptionalfield(self):
     outputs = processing.runalg("modeler:optionalfield", points(), None)
     output = outputs["OUTPUT_ALG0"]
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ["id", "value", "area", "perim"]
     expectedtypes = ["Integer", "String", "Real", "Real"]
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(1, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["0", "all", "3592.818848", "230.989919"]
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = "POLYGON((270839.46818665 4458921.97813894,270778.60197966 4458935.96883677,270786.54279065 4458980.04784113,270803.15756434 4458983.84880322,270839.65586926 4458983.16267036,270855.74530134 4458940.79948673,270839.46818665 4458921.97813894))"
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 46
0
 def test_modelersagagrass(self):
     outputs = processing.runalg("modeler:sagagrass", points(), None)
     output = outputs["CENTROIDS_ALG1"]
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ["CAT"]
     expectedtypes = ["Real"]
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(12, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["1"]
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = "POINT(270839.65586926 4458983.16267036)"
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 47
0
 def test_modeleroptionalfield(self):
     outputs = processing.runalg('modeler:optionalfield', points(), None)
     output = outputs['OUTPUT_ALG0']
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['id', 'value', 'area', 'perim']
     expectedtypes = ['Integer', 'String', 'Real', 'Real']
     names = [unicode(f.name()) for f in fields]
     types = [unicode(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(1, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ['0', 'all', '3592.818848', '230.989919']
     values = [unicode(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POLYGON((270839.46818665 4458921.97813894,270778.60197966 4458935.96883677,270786.54279065 4458980.04784113,270803.15756434 4458983.84880322,270839.65586926 4458983.16267036,270855.74530134 4458940.79948673,270839.46818665 4458921.97813894))'
     self.assertEqual(wkt, unicode(feature.geometry().exportToWkt()))
Exemplo n.º 48
0
 def test_modelersagagrass(self):
     outputs = processing.runalg('modeler:sagagrass', points(), None)
     output = outputs['CENTROIDS_ALG1']
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['CAT']
     expectedtypes = ['Real']
     names = [unicode(f.name()) for f in fields]
     types = [unicode(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(12, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ['1']
     values = [unicode(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POINT(270839.65586926 4458983.16267036)'
     self.assertEqual(wkt, unicode(feature.geometry().exportToWkt()))
Exemplo n.º 49
0
 def testWrongformat(self):
     outputs = processing.runalg('qgis:countpointsinpolygon', polygons(),
                                 points(), 'NUMPOINTS',
                                 getTempFilename('wrongext'))
     output = outputs['OUTPUT']
     self.assertTrue(output.endswith('shp'))
     layer = dataobjects.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['ID', 'POLY_NUM_A', 'POLY_ST_A', 'NUMPOINTS']
     expectedtypes = ['Integer', 'Real', 'String', 'Real']
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.features(layer)
     self.assertEqual(2, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ['1', '1.1', 'string a', '6.0']
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 50
0
    def checkGrassIsInstalled(ignorePreviousState=False):
        if isWindows():
            path = GrassUtils.grassPath()
            if path == '':
                return 'GRASS folder is not configured.\nPlease configure \
                        it before running GRASS algorithms.'
            cmdpath = os.path.join(path, 'bin', 'r.out.gdal.exe')
            if not os.path.exists(cmdpath):
                return 'The specified GRASS folder does not contain a valid \
                        set of GRASS modules.\n' \
                        + 'Please, go to the Processing settings dialog, and \
                        check that the GRASS\n' \
                        + 'folder is correctly configured'

        if not ignorePreviousState:
            if GrassUtils.isGrassInstalled:
                return
        try:
            from processing import runalg
            result = runalg(
                'grass:v.voronoi',
                points(),
                False,
                False,
                '270778.60198,270855.745301,4458921.97814,4458983.8488',
                -1,
                0.0001,
                0,
                None,
                )
            if not os.path.exists(result['output']):
                return 'It seems that GRASS is not correctly installed and \
                    configured in your system.\nPlease install it before \
                    running GRASS algorithms.'
        except:
            return 'Error while checking GRASS installation. GRASS might not \
                be correctly configured.\n' + s

        GrassUtils.isGrassInstalled = True
Exemplo n.º 51
0
    def testValues(self):
        context = QgsProcessingContext()

        # disable check for geometry validity
        context.setFlags(QgsProcessingContext.Flags(0))

        test_data = points()
        test_layer = QgsVectorLayer(test_data, 'test', 'ogr')

        # field by index
        res = vector.values(test_layer, context, 1)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # field by name
        res = vector.values(test_layer, context, 'id')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])

        # two fields
        res = vector.values(test_layer, context, 1, 2)
        self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name
        res = vector.values(test_layer, context, 'id', 'id2')
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res['id2'], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # two fields by name and index
        res = vector.values(test_layer, context, 'id', 2)
        self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0])

        # test with selected features
        context.setFlags(QgsProcessingContext.UseSelectionIfPresent)
        test_layer.selectByIds([2, 4, 6])
        res = vector.values(test_layer, context, 1)
        self.assertEqual(set(res[1]), set([5, 7, 3]))
Exemplo n.º 52
0
 def test_runandload(self):
     processing.runandload("qgis:countpointsinpolygon", polygons(),
                           points(), "NUMPOINTS", None)
     layer = getfromname("Result")
     self.assertIsNotNone(layer)
Exemplo n.º 53
0
 def test_runandload(self):
     processing.runandload('qgis:countpointsinpolygon', polygons(),
                           points(), 'NUMPOINTS', None)
     layer = getObjectFromName('Result')
     self.assertIsNotNone(layer)
Exemplo n.º 54
0
 def test_featuresWithoutSelection(self):
     layer = processing.getobject(points())
     features = processing.getfeatures(layer)
     self.assertEqual(12, len(features))
Exemplo n.º 55
0
 def test_runandload(self):
     processing.runandload("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS", None)
     layer = getObjectFromName("Result")
     self.assertIsNotNone(layer)
Exemplo n.º 56
0
 def test_getobject(self):
     layer = processing.getobject(points())
     self.assertIsNotNone(layer)
     layer = processing.getobject("points")
     self.assertIsNotNone(layer)
Exemplo n.º 57
0
 def test_featuresWithoutSelection(self):
     layer = processing.getObject(points())
     features = processing.features(layer)
     self.assertEqual(12, len(features))