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)
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)
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 testFeatureSourceInput(self): # create a memory layer and add to project and context layer = QgsVectorLayer("Point?crs=epsg:3857&field=fldtxt:string&field=fldint:integer", "testmem", "memory") self.assertTrue(layer.isValid()) pr = layer.dataProvider() f = QgsFeature() f.setAttributes(["test", 123]) f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(100, 200))) f2 = QgsFeature() f2.setAttributes(["test2", 457]) f2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(110, 200))) self.assertTrue(pr.addFeatures([f, f2])) self.assertEqual(layer.featureCount(), 2) # select first feature layer.selectByIds([next(layer.getFeatures()).id()]) self.assertEqual(len(layer.selectedFeatureIds()), 1) QgsProject.instance().addMapLayer(layer) context = QgsProcessingContext() context.setProject(QgsProject.instance()) alg = QgsApplication.processingRegistry().createAlgorithmById('grass7:v.buffer') self.assertIsNotNone(alg) temp_file = os.path.join(self.temp_dir, 'grass_output_sel.shp') parameters = {'input': QgsProcessingFeatureSourceDefinition('testmem', True), 'cats': '', 'where': '', 'type': [0, 1, 4], 'distance': 1, 'minordistance': None, 'angle': 0, 'column': None, 'scale': 1, 'tolerance': 0.01, '-s': False, '-c': False, '-t': False, 'output': temp_file, 'GRASS_REGION_PARAMETER': None, 'GRASS_SNAP_TOLERANCE_PARAMETER': -1, 'GRASS_MIN_AREA_PARAMETER': 0.0001, 'GRASS_OUTPUT_TYPE_PARAMETER': 0, 'GRASS_VECTOR_DSCO': '', 'GRASS_VECTOR_LCO': ''} feedback = QgsProcessingFeedback() results, ok = alg.run(parameters, context, feedback) self.assertTrue(ok) self.assertTrue(os.path.exists(temp_file)) # make sure that layer has correct features res = QgsVectorLayer(temp_file, 'res') self.assertTrue(res.isValid()) self.assertEqual(res.featureCount(), 1) QgsProject.instance().removeMapLayer(layer)
def testFeatureSourceInput(self): # create a memory layer and add to project and context layer = QgsVectorLayer( "Point?crs=epsg:3857&field=fldtxt:string&field=fldint:integer", "testmem", "memory") self.assertTrue(layer.isValid()) pr = layer.dataProvider() f = QgsFeature() f.setAttributes(["test", 123]) f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(100, 200))) f2 = QgsFeature() f2.setAttributes(["test2", 457]) f2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(110, 200))) self.assertTrue(pr.addFeatures([f, f2])) self.assertEqual(layer.featureCount(), 2) # select first feature layer.selectByIds([next(layer.getFeatures()).id()]) self.assertEqual(len(layer.selectedFeatureIds()), 1) QgsProject.instance().addMapLayer(layer) context = QgsProcessingContext() context.setProject(QgsProject.instance()) alg = QgsApplication.processingRegistry().createAlgorithmById( 'grass7:v.buffer') self.assertIsNotNone(alg) temp_file = os.path.join(self.temp_dir, 'grass_output_sel.shp') parameters = { 'input': QgsProcessingFeatureSourceDefinition('testmem', True), 'type': [0, 1, 4], 'distance': 1, 'angle': 0, 'scale': 1, 'tolerance': 0.01, '-s': False, '-c': False, '-t': False, 'output': temp_file, 'GRASS_SNAP_TOLERANCE_PARAMETER': -1, 'GRASS_MIN_AREA_PARAMETER': 0.0001, 'GRASS_OUTPUT_TYPE_PARAMETER': 0 } feedback = QgsProcessingFeedback() results, ok = alg.run(parameters, context, feedback) self.assertTrue(ok) self.assertTrue(os.path.exists(temp_file)) # make sure that layer has correct features res = QgsVectorLayer(temp_file, 'res') self.assertTrue(res.isValid()) self.assertEqual(res.featureCount(), 1) QgsProject.instance().removeMapLayer(layer)
def testRepack(self): vl = QgsVectorLayer("{}|layerid=0".format(self.repackfile), "test", "ogr") ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression("pk=1"))] vl.selectByIds(ids) self.assertEqual(vl.selectedFeaturesIds(), ids) self.assertEqual(vl.pendingFeatureCount(), 5) self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteFeature(3)) self.assertTrue(vl.commitChanges()) self.assertTrue(vl.selectedFeatureCount() == 0 or vl.selectedFeatures()[0]["pk"] == 1)
def testRepack(self): vl = QgsVectorLayer('{}|layerid=0'.format(self.repackfile), 'test', 'ogr') ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression('pk=1'))] vl.selectByIds(ids) self.assertEqual(vl.selectedFeatureIds(), ids) self.assertEqual(vl.pendingFeatureCount(), 5) self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteFeature(3)) self.assertTrue(vl.commitChanges()) self.assertTrue(vl.selectedFeatureCount() == 0 or vl.selectedFeatures()[0]['pk'] == 1)
def testRepack(self): vl = QgsVectorLayer('{}|layerid=0'.format(self.repackfile), 'test', 'ogr') ids = [f.id() for f in vl.getFeatures(QgsFeatureRequest().setFilterExpression('pk=1'))] vl.selectByIds(ids) self.assertEqual(vl.selectedFeatureIds(), ids) self.assertEqual(vl.featureCount(), 5) self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteFeature(3)) self.assertTrue(vl.commitChanges()) self.assertTrue(vl.selectedFeatureCount() == 0 or vl.selectedFeatures()[0]['pk'] == 1)
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)
def testGetOgrCompatibleSourceFromFeatureSource(self): # create a memory layer and add to project and context layer = QgsVectorLayer( "Point?field=fldtxt:string&field=fldint:integer", "testmem", "memory") self.assertTrue(layer.isValid()) pr = layer.dataProvider() f = QgsFeature() f.setAttributes(["test", 123]) f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(100, 200))) f2 = QgsFeature() f2.setAttributes(["test2", 457]) f2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(100, 200))) self.assertTrue(pr.addFeatures([f, f2])) self.assertEqual(layer.featureCount(), 2) # select first feature layer.selectByIds([next(layer.getFeatures()).id()]) self.assertEqual(len(layer.selectedFeatureIds()), 1) QgsProject.instance().addMapLayer(layer) context = QgsProcessingContext() context.setProject(QgsProject.instance()) alg = QgsApplication.processingRegistry().createAlgorithmById( 'gdal:buffervectors') self.assertIsNotNone(alg) parameters = { 'INPUT': QgsProcessingFeatureSourceDefinition('testmem', True) } feedback = QgsProcessingFeedback() # check that memory layer is automatically saved out to geopackage when required by GDAL algorithms ogr_data_path, ogr_layer_name = alg.getOgrCompatibleSource( 'INPUT', parameters, context, feedback, executing=True) self.assertTrue(ogr_data_path) self.assertTrue(ogr_data_path.endswith('.gpkg')) self.assertTrue(os.path.exists(ogr_data_path)) self.assertTrue(ogr_layer_name) # make sure that layer has only selected feature res = QgsVectorLayer(ogr_data_path, 'res') self.assertTrue(res.isValid()) self.assertEqual(res.featureCount(), 1) QgsProject.instance().removeMapLayer(layer)
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)
def testValues(self): ProcessingConfig.initialize() test_data = points2() test_layer = QgsVectorLayer(test_data, 'test', 'ogr') # field by index res = vector.values(test_layer, 0) self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) # field by name res = vector.values(test_layer, 'id') self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) # two fields res = vector.values(test_layer, 0, 3) self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(res[3], [2, 1, 0, 2, 1, 0, 0, 0]) # two fields by name res = vector.values(test_layer, 'id', 'id_2') self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(res['id_2'], [2, 1, 0, 2, 1, 0, 0, 0]) # two fields by name and index res = vector.values(test_layer, 'id', 3) self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(res[3], [2, 1, 0, 2, 1, 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, 0) self.assertEqual(set(res[0]), set([5, 7, 3])) ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)
def testGetOgrCompatibleSourceFromFeatureSource(self): # create a memory layer and add to project and context layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", "testmem", "memory") self.assertTrue(layer.isValid()) pr = layer.dataProvider() f = QgsFeature() f.setAttributes(["test", 123]) f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(100, 200))) f2 = QgsFeature() f2.setAttributes(["test2", 457]) f2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(100, 200))) self.assertTrue(pr.addFeatures([f, f2])) self.assertEqual(layer.featureCount(), 2) # select first feature layer.selectByIds([next(layer.getFeatures()).id()]) self.assertEqual(len(layer.selectedFeatureIds()), 1) QgsProject.instance().addMapLayer(layer) context = QgsProcessingContext() context.setProject(QgsProject.instance()) alg = QgsApplication.processingRegistry().createAlgorithmById('gdal:buffervectors') self.assertIsNotNone(alg) parameters = {'INPUT': QgsProcessingFeatureSourceDefinition('testmem', True)} feedback = QgsProcessingFeedback() # check that memory layer is automatically saved out to shape when required by GDAL algorithms ogr_data_path, ogr_layer_name = alg.getOgrCompatibleSource('INPUT', parameters, context, feedback, executing=True) self.assertTrue(ogr_data_path) self.assertTrue(ogr_data_path.endswith('.shp')) self.assertTrue(os.path.exists(ogr_data_path)) self.assertTrue(ogr_layer_name) # make sure that layer has only selected feature res = QgsVectorLayer(ogr_data_path, 'res') self.assertTrue(res.isValid()) self.assertEqual(res.featureCount(), 1) QgsProject.instance().removeMapLayer(layer)
def testFeatures(self): ProcessingConfig.initialize() test_data = points2() test_layer = QgsVectorLayer(test_data, 'test', 'ogr') # test with all features features = vector.features(test_layer) self.assertEqual(len(features), 8) self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7])) # 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), 8) self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7])) # using selected features, but no selection ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True) test_layer.removeSelection() features = vector.features(test_layer) self.assertEqual(len(features), 8) self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7])) # 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)
def test_selected_feature_values_dynamic(self): """ Test that factory proactively updates when a selection changes, when desired """ layer_path = os.path.join(os.path.dirname(__file__), 'test_layer.shp') vl1 = QgsVectorLayer(layer_path, 'test_layer', 'ogr') vl1.setSubsetString('id < 10') self.assertTrue(vl1.isValid()) QgsProject.instance().addMapLayer(vl1) # not using selected features settings = PlotSettings('scatter') settings.properties['selected_features_only'] = False settings.source_layer_id = vl1.id() settings.properties['x_name'] = 'so4' settings.properties['y_name'] = 'ca' factory = PlotFactory(settings) spy = QSignalSpy(factory.plot_built) vl1.selectByIds([1, 3, 4]) self.assertEqual(len(spy), 0) # using selected features settings = PlotSettings('scatter') settings.properties['selected_features_only'] = True settings.source_layer_id = vl1.id() settings.properties['x_name'] = 'so4' settings.properties['y_name'] = 'ca' factory = PlotFactory(settings) spy = QSignalSpy(factory.plot_built) vl1.selectByIds([1]) self.assertEqual(len(spy), 1) self.assertEqual(factory.settings.x, [88]) self.assertEqual(factory.settings.y, [22.26]) vl1.selectByIds([1, 3, 4]) self.assertEqual(len(spy), 2) self.assertEqual(factory.settings.x, [88, 329, 319]) self.assertEqual(factory.settings.y, [22.26, 35.05, 46.64]) vl1.selectByIds([]) self.assertEqual(len(spy), 3) self.assertEqual(factory.settings.x, []) self.assertEqual(factory.settings.y, [])
def testValues(self): ProcessingConfig.initialize() test_data = points2() test_layer = QgsVectorLayer(test_data, 'test', 'ogr') # field by index res = vector.values(test_layer, 0) self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) # field by name res = vector.values(test_layer, 'id') self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) # two fields res = vector.values(test_layer, 0, 3) self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(res[3], [2, 1, 0, 2, 1, 0, 0, 0]) # two fields by name res = vector.values(test_layer, 'id', 'id_2') self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(res['id_2'], [2, 1, 0, 2, 1, 0, 0, 0]) # two fields by name and index res = vector.values(test_layer, 'id', 3) self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(res[3], [2, 1, 0, 2, 1, 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, 0) self.assertEqual(set(res[0]), set([5, 7, 3])) ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)
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]))
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)
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([]))
class TestVectorlayer(utils_for_tests.MidvattenTestSpatialiteDbSv): @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def create_vlayer(self, no_print=False): self.qgs = QgsApplication([], True) self.qgs.initQgis() dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] if not no_print: print("1. Valid vlayer '{}'".format(self.vlayer.isValid())) print("2. feature_ids: " + str(feature_ids)) print("5. QgsVectorLayer.getFeature(): " + str([self.vlayer.getFeature(x).id() for x in feature_ids])) print("6. QgsVectorLayer.getFeature() type: " + str([str(type(self.vlayer.getFeature(x))) for x in feature_ids])) print("7. QgsVectorLayer.getFeatures(): " + str([x.id() for x in self.vlayer.getFeatures(feature_ids)])) print("8. QgsVectorLayer.featureCount(): " + str(self.vlayer.featureCount())) def select_features(self, feature_ids=None, no_print=True): if feature_ids is None: features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) if not no_print: print("3. QgsVectorLayer.selectedFeatureIds: " + str(self.vlayer.selectedFeatureIds())) print("4. QgsVectorLayer.getSelectedFeatures: " + str([x.id() for x in self.vlayer.getSelectedFeatures()])) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def test_vlayer(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in [1, 2, 3]: db_utils.sql_alter_db('''INSERT INTO obs_points (obsid) VALUES ({})'''.format(str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getSelectedFeatures()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getFeatures(feature_ids)])) == reference_ids assert self.vlayer.featureCount() == 3 @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def test_vlayer_other_ints_ids(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in [4, 5, 6]: db_utils.sql_alter_db('''INSERT INTO obs_points (obsid) VALUES ({})'''.format(str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getSelectedFeatures()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getFeatures(feature_ids)])) == reference_ids assert self.vlayer.featureCount() == 3 @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def test_vlayer_strings(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in ['A', 'b', 'c1']: db_utils.sql_alter_db('''INSERT INTO obs_points (obsid) VALUES ('{}')'''.format(str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getSelectedFeatures()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getFeatures(feature_ids)])) == reference_ids assert self.vlayer.featureCount() == 3 @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def test_vlayer_1000_features(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor cur.execute('''BEGIN TRANSACTION;''') for obsid in range(1000): cur.execute('''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format(str(obsid))) cur.execute('''END TRANSACTION;''') self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, 1001)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getSelectedFeatures()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getFeatures(feature_ids)])) == reference_ids assert self.vlayer.featureCount() == len(reference_ids) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def test_vlayer_2000_ints(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor cur.execute('''BEGIN TRANSACTION;''') for obsid in range(2000): cur.execute('''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format(str(obsid))) cur.execute('''END TRANSACTION;''') self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, 2001)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getSelectedFeatures()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getFeatures(feature_ids)])) == reference_ids assert self.vlayer.featureCount() == len(reference_ids) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated.mock_instance_settings_database) def test_vlayer_2000_strings(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor obsids = [letter + str(_int) for letter in string.ascii_letters for _int in range(80)] cur.execute('''BEGIN TRANSACTION;''') for obsid in obsids: cur.execute('''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format(str(obsid))) cur.execute('''END TRANSACTION;''') dbconnection.commit() self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, len(obsids)+1)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) print(str(self.vlayer.featureCount())) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getSelectedFeatures()])) == reference_ids assert tuple(sorted([x.id() for x in self.vlayer.getFeatures(feature_ids)])) == reference_ids assert self.vlayer.featureCount() == len(reference_ids) def tearDown(self): QgsProject.instance().addMapLayer(self.vlayer) QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
class TestSectionPlot(utils_for_tests.MidvattenTestPostgisDbSv): """ The test doesn't go through the whole section plot unfortunately """ def setUp(self): super(TestSectionPlot, self).setUp() self.midvatten.ms.settingsdict['secplot_loaded_template'] = '' self.midvatten.ms.settingsdict['secplot_templates'] = '' self.midvatten.ms.settingsdict['secplotlocation'] = 0 def create_and_select_vlayer(self): self.midvatten.ms.settingsdict['secplotdrillstop'] = "%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_lines', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) QgsProject.instance().addMapLayer(self.vlayer) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] print(str(feature_ids)) self.vlayer.selectByIds(feature_ids) @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.drillstoplineEdit.setText("%berg%") self.myplot.draw_plot() self.selected_obsids = self.myplot.selected_obsids _test_plot_section(self) assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls) assert self.myplot.drillstoplineEdit.text() == '%berg%' assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']" assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called print("self.myplot.p {} self.myplot.labels {}".format(str(self.myplot.p), str(self.myplot.labels))) assert len(self.myplot.p) - 1 == len(self.myplot.labels) # The bars should not be labeled, so there is one less label than plot. @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_no_linelayer_message(self, mock_messagebar): @mock.patch('sectionplot.SectionPlot.do_it') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_sectionplot): mock_layer = mock.Mock(spec=QgsVectorLayer) mock_iface.mapCanvas.return_value.currentLayer.return_value = mock_layer mock_layer.selectedFeatureCount.return_value = 2 mock_geom = mock.Mock() mock_geom.wkbType.return_value = 'test' mock_feature = mock.Mock() mock_feature.geometry.return_value = mock_geom mock_layer.getFeatures.return_value = [mock_feature] self.midvatten.plot_section() _test(self) assert call.info(bar_msg='No line layer was selected. The stratigraphy bars will be lined up from south-north or west-east and no DEMS will be plotted.', duration=10) in mock_messagebar.mock_calls assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_with_string_obsid(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash with string obsid """ db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''') self.create_and_select_vlayer() print(str(self.vlayer.selectedFeatureCount())) @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.drillstoplineEdit.setText("%berg%") self.myplot.draw_plot() self.selected_obsids = self.myplot.selected_obsids _test_plot_section(self) assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls) assert self.myplot.drillstoplineEdit.text() == '%berg%' assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']" assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_with_depth(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section_with_depth(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot _test_plot_section_with_depth(self) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_with_w_levels(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_with_w_levels_duplicate_label(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.datetimetextEdit.append('2015') self.myplot.secplot_templates.loaded_template['wlevels_Axes_plot'] = {'2015': {'label': '1', 'linestyle': '-', 'linewidth': 1, 'marker': 'v', 'markersize': 6, 'zorder': 8}, '2015_2': {'label': '2', 'linestyle': '-', 'linewidth': 1, 'marker': 'v', 'markersize': 6, 'zorder': 8}, 'DEFAULT': {'label': 'DEFAULT', 'linestyle': '-', 'linewidth': 1, 'marker': 'v', 'markersize': 6, 'zorder': 8}} self.myplot.draw_plot() _test(self) print(str(mock_messagebar.mock_calls)) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called labels = [p.get_label() for p in self.myplot.p] assert anything_to_string_representation(labels) == '''["1", "2", "drillstop like %berg%", "_container0"]''' assert anything_to_string_representation(self.myplot.water_level_labels_duplicate_check) == '''["2015", "2015_2"]''' @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_length_along_slope(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(2 0, 10 10)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 0)', 3006))''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 midvatten.plot_section() self.myplot = midvatten.myplot self.myplot.drillstoplineEdit.setText("%berg%") self.myplot.draw_plot() _test(self.midvatten, self.vlayer) test_string = utils_for_tests.create_test_string(self.myplot.length_along) assert any([test_string == "[ 0. 0.62469505 1.87408514]", test_string == "[0. 0.62469505 1.87408514]"]) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_length_along(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(0 0, 1 0, 10 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 5)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 10)', 3006))''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 midvatten.plot_section() myplot = midvatten.myplot myplot.drillstoplineEdit.setText("%berg%") myplot.draw_plot() return myplot myplot = _test(self.midvatten, self.vlayer) test_string = utils_for_tests.create_test_string(myplot.length_along) assert any([test_string == "[ 1. 3. 5.]", test_string == "[1. 3. 5.]"]) assert mock.call.info(log_msg='Hidden features, obsids and length along section:\nP1;P2;P3\\1.0;3.0;5.0') in mock_messagebar.mock_calls assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_p_label_lengths(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.Stratigraphy_radioButton.setChecked(True) self.myplot.Legend_checkBox.setChecked(True) gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) print(str(mock_messagebar.mock_calls)) print(str(self.myplot.p)) print(str(self.myplot.labels)) assert len(self.myplot.skipped_bars) == len(self.myplot.labels) assert len(self.myplot.skipped_bars) == 2 #assert False @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_p_label_lengths_with_geology(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.Stratigraphy_radioButton.setChecked(True) self.myplot.Legend_checkBox.setChecked(True) gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) print(str(mock_messagebar.mock_calls)) print(str(self.myplot.p)) print(str(self.myplot.labels)) assert len(self.myplot.skipped_bars) == len(self.myplot.labels) assert len(self.myplot.skipped_bars) == 4 @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_p_label_lengths_with_geology_changed_label(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.secplot_templates.loaded_template['geology_Axes_bar'] = {'sand': {'label': 'sandtest', 'edgecolor': 'black', 'zorder': 5}, 'grus': {'label': 'grustest', 'edgecolor': 'black', 'zorder': 5}, 'DEFAULT': {'edgecolor': 'black', 'zorder': 5}} print("before: " + str(self.myplot.secplot_templates.loaded_template['geology_Axes_bar'])) self.myplot.Stratigraphy_radioButton.setChecked(True) self.myplot.Legend_checkBox.setChecked(True) gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) #print(str(mock_messagebar.mock_calls)) #print(str(self.myplot.p)) #print(str(self.myplot.labels)) labels = [p.get_label() for p in self.myplot.p] assert len(self.myplot.skipped_bars) == len(self.myplot.labels) assert len(self.myplot.skipped_bars) == 4 assert anything_to_string_representation(labels) == '''["sandtest", "grustest", "2015", "drillstop like %berg%", "_container2"]''' assert anything_to_string_representation(self.myplot.water_level_labels_duplicate_check) == '''["2015"]''' @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_p_label_lengths_with_geology_changed_label(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.secplot_templates.loaded_template['geology_Axes_bar'] = {'sand': {'label': 'sandtest', 'edgecolor': 'black', 'zorder': 5}, 'grus': {'label': 'grustest', 'edgecolor': 'black', 'zorder': 5}, 'DEFAULT': {'edgecolor': 'black', 'zorder': 5}} print("before: " + str(self.myplot.secplot_templates.loaded_template['geology_Axes_bar'])) self.myplot.Stratigraphy_radioButton.setChecked(True) self.myplot.Legend_checkBox.setChecked(True) gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) #print(str(mock_messagebar.mock_calls)) #print(str(self.myplot.p)) #print(str(self.myplot.labels)) labels = [p.get_label() for p in self.myplot.p] assert len(self.myplot.skipped_bars) == len(self.myplot.labels) assert len(self.myplot.skipped_bars) == 4 assert anything_to_string_representation(labels) == '''["sandtest", "grustest", "2015", "drillstop like %berg%", "_container2"]''' assert anything_to_string_representation(self.myplot.water_level_labels_duplicate_check) == '''["2015"]''' @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_with_w_levels_animation(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-02 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-03 00:00:00', '15', '200', '185')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.interactive_groupbox.setChecked(True) #self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() return self.myplot myplot = _test(self) print(str(mock_messagebar.mock_calls)) assert myplot.interactive_groupbox.isChecked() assert len(myplot.figure.axes) > 1 assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') def test_plot_section_obsids(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(1 0, 4 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, h_gs, length) VALUES ('P1', ST_GeomFromText('POINT(1 1)', 3006), 50, 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, h_gs, length) VALUES ('P2', ST_GeomFromText('POINT(2 2)', 3006), 70, '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, h_toc,length) VALUES ('P3', ST_GeomFromText('POINT(4 4)', 3006), 90, NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P3', 2, 1, 2, 'gravel')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.find_layer') @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames, mock_findlayer): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_findlayer.return_value.isEditable.return_value = False mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) #print(str(self.myplot.obsid_annotation)) assert str(self.myplot.obsid_annotation) == '''{'P1': (0.0, 50.0), 'P3': (3.0, 90.0), 'P2': (1.0, 183.0)}''' print(str(mock_messagebar.mock_calls)) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called
def main(): """reads in a pre-processed groundwater layer, with recharge-discharge (CSV) and returns tif Args: state(str): state for which well elevations must be obtained season(str): e.g. rech-96, disc-96 Returns: None: well elevations with locations stored in CSV as SHP """ state = sys.argv[1] season = sys.argv[2] dataPath = root.joinpath("data","groundwater") metaPath = root.joinpath("outputs","groundwater","csv",state+"_metadata.log") outputsPath = root.joinpath("outputs","groundwater") logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', handlers=[logging.FileHandler(str(metaPath))], ) logging.info("get Recharge-Discharge for '%s' dataset",state) # Initialize QGIS Application QgsApplication.setPrefixPath("G:\\Users\\Craig\\miniconda3\\envs\\geo_env\\Library\\python\\qgis", True) qgs = QgsApplication([], False) qgs.initQgis() # Append the path where QGIS processing plugin can be found sys.path.append('G:\\Users\\Craig\\miniconda3\\envs\\geo_env\\Library\\python\\plugins') import processing from processing.core.Processing import Processing Processing.initialize() feedback = QgsProcessingFeedback() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) # Get file with recharge-discharge values from previous step vectorPath = outputsPath.joinpath("shapefiles",state+"_processed_wRD.shp") print(vectorPath,vectorPath.exists()) vLayer = QgsVectorLayer(str(vectorPath), 'well_rech_disc_layer', 'ogr') #.setSubsetString(season + " IS NOT NULL") print("islayer valid:", vLayer.isValid()) # subset layer for the chosen season and choose only non null values filter = "\"" + season + "\"" + " IS NOT NULL" expr = QgsExpression(filter) subset = vLayer.getFeatures(QgsFeatureRequest(expr)) vLayer.selectByIds([k.id() for k in subset]) # why didn't direct selection work? addFeature (false) print(vLayer.selectedFeatureCount()) # write subsetted layer to shapefile subsetPath = outputsPath.joinpath("shapefiles","noNulls",state+"_"+season+"_noNulls.shp") _writer = QgsVectorFileWriter.writeAsVectorFormat(vLayer, str(subsetPath), "utf-8", vLayer.crs(), "ESRI Shapefile", onlySelected=True) # import subsetted layer subLayer = QgsVectorLayer(str(subsetPath), 'well_rech_disc_layer_nonulls', 'ogr') print("is sub layer valid:", subLayer.isValid()) # declare params for grid layer # https://gdal.org/tutorials/gdal_grid_tut.html params = { 'INPUT':subLayer, 'POWER':2, # FOR gridinversedistance # 'RADIUS':0.25, # FOR gridinversedistancenearestneighbor / gridlinear # 'RADIUS_1':0.25, # FOR gridinversedistance / gridnearestneighbor / gridaverage # 'RADIUS_2':0.25, # FOR gridinversedistance / gridnearestneighbor / gridaverage 'MAX_POINTS':12, # FOR gridinversedistance 'MIN_POINTS':1, # FOR gridinversedistance / gridaverage 'NODATA': -9999, 'Z_FIELD':season, 'OUTPUT':str(outputsPath.joinpath("tif","idw",state+"_"+season+"_grid_id_min_1_max_12_nonulls.tif")) } res = processing.run("gdal:gridinversedistance",params,feedback=feedback) print(res['OUTPUT'])
class TestStratigraphy(utils_for_tests.MidvattenTestPostgisDbSv): @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def create_and_select_vlayer(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() self.midvatten.ms.settingsdict['secplotdrillstop'] = "%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) print("1. Valid vlayer '{}'".format(self.vlayer.isValid())) print("2. feature_ids: " + str(feature_ids)) print("3. QgsVectorLayer.selectedFeatureIds: " + str(self.vlayer.selectedFeatureIds())) print("4. QgsVectorLayer.getSelectedFeatures: " + str([x.id() for x in self.vlayer.getSelectedFeatures()])) print("5. QgsVectorLayer.getFeature(): " + str([self.vlayer.getFeature(x).id() for x in feature_ids])) print("6. QgsVectorLayer.getFeature() type: " + str([str(type(self.vlayer.getFeature(x))) for x in feature_ids])) print("7. QgsVectorLayer.getFeatures(): " + str([x.id() for x in self.vlayer.getFeatures(feature_ids)])) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_stratigraphy(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''') self.create_and_select_vlayer() #print(str(self.vlayer.isValid())) #print(str(db_utils.sql_load_fr_db('select * from obs_points'))) #print(str(db_utils.sql_load_fr_db('select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) #print(str(mock_messagebar.mock_calls)) #print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation(repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation(utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 print(str(mock_messagebar.mock_calls)) assert len(mock_messagebar.mock_calls) == 0 assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("test_strata: " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_stratigraphy_with_other_obsid_numbers(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('8', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('9', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('10', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('8', 1, 0, 1, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('8', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''') self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() print(str(mock_skippopup.mock_calls)) test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation(repr(dlg.data['8'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['8'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"8": SURVEY('8', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('8', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_stratigraphy_with_string_obsid(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 1, 0, 1, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''') self.create_and_select_vlayer() print(str(self.vlayer.isValid())) print(str(db_utils.sql_load_fr_db('select * from obs_points'))) print(str(db_utils.sql_load_fr_db('select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) print(str(mock_messagebar.mock_calls)) print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation(repr(dlg.data['P1'])) test_strata = utils.anything_to_string_representation(utils.returnunicode(dlg.data['P1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 print(str(mock_messagebar.mock_calls)) assert len(mock_messagebar.mock_calls) == 0 assert test == """{"P1": SURVEY('P1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('P1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_stratigraphy_gap(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 2, 4.5, 'morän', 'morän', '3', 'j')''') self.create_and_select_vlayer() print(str(self.vlayer.isValid())) print(str(db_utils.sql_load_fr_db('select * from obs_points'))) print(str(db_utils.sql_load_fr_db('select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) print(str(mock_messagebar.mock_calls)) print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation(repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation(utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '', '', '', 1.000000-2.000000)", "strata(3, '3', 'morän', 'moran', 2.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_stratigraphy_missing_h_gs(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, h_gs, h_toc, geometry) VALUES ('2', NULL, 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('3', ST_GeomFromText('POINT(6720728 016569)', 3006))''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('2', 1, 0, 1, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('2', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('3', 1, 0, 2, 'sand', 'sand', '3', 'j')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('3', 2, 2, 6, 'morän', 'morän', '3', 'j')''') self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation(repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation(utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 1 print(str(mock_skippopup.mock_calls)) print(str(mock_messagebar.mock_calls)) assert mock_skippopup.mock_calls == [mock.call('Warning, h_gs is missing. See messagebar.')] assert mock_messagebar.mock_calls == [mock.call.warning(bar_msg="Obsid 2: using h_gs '' failed, using 'h_toc' instead.", duration=90, log_msg='False'), mock.call.warning(bar_msg="Obsid 3: using h_gs '' failed, using '-1' instead.", duration=90, log_msg='False')] print("test: " + test) assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>'), "2": SURVEY('2', 10.000000, '<QgsPointXY: POINT(6720727 16568)>'), "3": SURVEY('3', -1.000000, '<QgsPointXY: POINT(6720728 16569)>')}""" print("test_survey " + test_survey) assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' def tearDown(self): QgsProject.instance().addMapLayer(self.vlayer) QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
class FindPoints(QgsTask): def __init__(self, qpipelines, description='FindHds', debug=False): super().__init__(description, QgsTask.CanCancel) self.debug = debug if self.debug: self.hds_feature = QgsVectorLayer( 'C:/Users/jeferson.machado/Desktop/QGIS/shapes/hds_tracing.shp', "hds_tracing", "ogr") else: self.hds_feature = QgsProject.instance().mapLayersByName( 'hds_tracing')[0] self.idx_hds = QgsSpatialIndex( self.hds_feature.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries) self.__exception = None self.q_list_pipelines = qpipelines self.list_hds = [] def find_hds_by_nearest_neighbor(self, points_vertex): hds_nearest = self.idx_hds.nearestNeighbor( point=QgsPointXY(points_vertex), neighbors=10, maxDistance=25) if len(hds_nearest) > 0: for hd in hds_nearest: if hd not in self.list_hds: self.list_hds.append(hd) def split_line(self, p1, p2, pos, pipeline): geo = QgsGeometry.fromPolyline([p1, p2]) center = geo.centroid() pipeline.insert(pos, center.asPoint()) def get_points(self, pipeline): pipe = [ QgsPointXY(pipeline.vertexAt(i)) for i in range(pipeline.get().childCount()) ] distances = [] breakForce = 0 while True: if breakForce == 1000: break # check isCanceled() to handle cancellation if self.isCanceled(): return False increment = 0 pipeline = QgsGeometry.fromMultiPointXY(pipe) for i in range(len(pipe) - 1): p1 = pipeline.vertexAt(i) p2 = pipeline.vertexAt(i + 1) d = QgsDistanceArea() distance = d.measureLine(QgsPointXY(p1), QgsPointXY(p2)) distances.append(distance) if distance > 10: self.split_line(p1, p2, i + 1 + increment, pipe) increment += 1 breakForce += 1 if distances: if max(distances) <= 10: break distances.clear() return pipeline def run(self): try: while len(self.q_list_pipelines) > 0: pipeline = self.q_list_pipelines.pop(0) pipeline_geo = self.get_points(pipeline.geometry()) for i in range(0, len(pipeline_geo.get()) - 1): self.find_hds_by_nearest_neighbor(pipeline_geo.vertexAt(i)) except Exception as e: self.__exception = e return False return True def finished(self, result): if result: self.hds_feature.selectByIds(self.list_hds) QgsMessageLog.logMessage( f"Task {self.description()} has been executed correctly\n" f"HDS: {self.list_hds}", level=Qgis.Success) else: if self.__exception is None: QgsMessageLog.logMessage( f"Tracing {self.description()} not successful " f"but without exception " f"(probably the task was manually canceled by the user)", level=Qgis.Warning) else: QgsMessageLog.logMessage( f"Task {self.description()}" f"Exception: {self.__exception}", level=Qgis.Critical) raise self.__exception def cancel(self): QgsMessageLog.logMessage( f'TracingTrask {self.description()} was canceled', level=Qgis.Info) super().cancel()
class TestSectionPlot(utils_for_tests.MidvattenTestPostgisDbSv): """ The test doesn't go through the whole section plot unfortunately """ @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def setUp(self): super(TestSectionPlot, self).setUp() self.midvatten.ms.settingsdict['secplot_loaded_template'] = '' self.midvatten.ms.settingsdict['secplot_templates'] = '' self.midvatten.ms.settingsdict['secplotlocation'] = 0 @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def create_and_select_vlayer(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() self.midvatten.ms.settingsdict['secplotdrillstop'] = "%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_lines', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''') self.create_and_select_vlayer() @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.drillstoplineEdit.setText("%berg%") self.myplot.draw_plot() self.selected_obsids = self.myplot.selected_obsids _test_plot_section(self) assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls) assert self.myplot.drillstoplineEdit.text() == '%berg%' assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']" assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called assert len(self.myplot.p) == len(self.myplot.Labels) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_with_string_obsid(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash with string obsid """ db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(6720728 016569)', 3006))''') self.create_and_select_vlayer() print(str(self.vlayer.selectedFeatureCount())) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.midvatten.ms = self.ms self.myplot = self.midvatten.myplot self.myplot.drillstoplineEdit.setText("%berg%") self.myplot.draw_plot() self.selected_obsids = self.myplot.selected_obsids _test_plot_section(self) assert """call.info(log_msg='Settings {""" in str(mock_messagebar.mock_calls) assert self.myplot.drillstoplineEdit.text() == '%berg%' assert utils_for_tests.create_test_string(self.myplot.selected_obsids) == "['P1' 'P2' 'P3']" assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_with_depth(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test_plot_section_with_depth(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot _test_plot_section_with_depth(self) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_with_w_levels(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_length_along_slope(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(2 0, 10 10)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 0)', 3006))''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 midvatten.plot_section() self.myplot = midvatten.myplot self.myplot.drillstoplineEdit.setText("%berg%") self.myplot.draw_plot() _test(self.midvatten, self.vlayer) test_string = utils_for_tests.create_test_string(self.myplot.LengthAlong) assert any([test_string == "[ 0. 0.62469505 1.87408514]", test_string == "[0. 0.62469505 1.87408514]"]) assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_length_along(self, mock_messagebar): """For now, the test only initiates the plot. Check that it does not crash """ db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('L1', ST_GeomFromText('LineString(0 0, 1 0, 10 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P1', ST_GeomFromText('POINT(1 0)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P2', ST_GeomFromText('POINT(3 5)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry) VALUES ('P3', ST_GeomFromText('POINT(5 10)', 3006))''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(midvatten, vlayer, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 midvatten.plot_section() myplot = midvatten.myplot myplot.drillstoplineEdit.setText("%berg%") myplot.draw_plot() return myplot myplot = _test(self.midvatten, self.vlayer) test_string = utils_for_tests.create_test_string(myplot.LengthAlong) assert any([test_string == "[ 1. 3. 5.]", test_string == "[1. 3. 5.]"]) assert mock.call.info(log_msg='Hidden features, obsids and length along section:\nP1;P2;P3\\1.0;3.0;5.0') in mock_messagebar.mock_calls assert not mock_messagebar.warning.called assert not mock_messagebar.critical.called @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_p_label_lengths(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.Stratigraphy_checkBox.setChecked(True) gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) print(str(mock_messagebar.mock_calls)) print(str(self.myplot.p)) print(str(self.myplot.Labels)) assert len(self.myplot.skipped_bars) == len(self.myplot.Labels) assert len(self.myplot.skipped_bars) == 2 #assert False @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch('db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections) def test_plot_section_p_label_lengths_with_geology(self, mock_messagebar): db_utils.sql_alter_db('''INSERT INTO obs_lines (obsid, geometry) VALUES ('1', ST_GeomFromText('LINESTRING(633466.711659 6720684.24498, 633599.530455 6720727.016568)', 3006))''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P1', ST_GeomFromText('POINT(633466 711659)', 3006), 2)''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P2', ST_GeomFromText('POINT(6720727 016568)', 3006), '1')''') db_utils.sql_alter_db('''INSERT INTO obs_points (obsid, geometry, length) VALUES ('P3', ST_GeomFromText('POINT(6720727 016568)', 3006), NULL)''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P1', '2015-01-01 00:00:00', '15', '200', '185')''') db_utils.sql_alter_db('''INSERT INTO w_levels (obsid, date_time, meas, h_toc, level_masl) VALUES ('P2', '2015-01-01 00:00:00', '17', '200', '183')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 1, 0, 1, 'sand')''') db_utils.sql_alter_db('''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('P1', 2, 1, 2, 'gravel')''') self.create_and_select_vlayer() @mock.patch('midvatten_utils.getselectedobjectnames', autospec=True) @mock.patch('qgis.utils.iface', autospec=True) def _test(self, mock_iface, mock_getselectedobjectnames): mock_iface.mapCanvas.return_value.currentLayer.return_value = self.vlayer mock_getselectedobjectnames.return_value = ('P1', 'P2', 'P3') mock_mapcanvas = mock_iface.mapCanvas.return_value mock_mapcanvas.layerCount.return_value = 0 self.midvatten.plot_section() self.myplot = self.midvatten.myplot self.myplot.Stratigraphy_checkBox.setChecked(True) gui_utils.set_combobox(self.myplot.wlvltableComboBox, 'w_levels') self.myplot.datetimetextEdit.append('2015') self.myplot.draw_plot() _test(self) print(str(mock_messagebar.mock_calls)) print(str(self.myplot.p)) print(str(self.myplot.Labels)) assert len(self.myplot.skipped_bars) == len(self.myplot.Labels) assert len(self.myplot.skipped_bars) == 4 def tearDown(self): QgsProject.instance().addMapLayer(self.vlayer) QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
class TestVectorlayer(utils_for_tests.MidvattenTestSpatialiteDbSv): def create_vlayer(self, no_print=False): dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) QgsProject.instance().addMapLayer(self.vlayer) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] if not no_print: print("1. Valid vlayer '{}'".format(self.vlayer.isValid())) print("2. feature_ids: " + str(feature_ids)) print("5. QgsVectorLayer.getFeature(): " + str([self.vlayer.getFeature(x).id() for x in feature_ids])) print("6. QgsVectorLayer.getFeature() type: " + str( [str(type(self.vlayer.getFeature(x))) for x in feature_ids])) print("7. QgsVectorLayer.getFeatures(): " + str([x.id() for x in self.vlayer.getFeatures(feature_ids)])) print("8. QgsVectorLayer.featureCount(): " + str(self.vlayer.featureCount())) def select_features(self, feature_ids=None, no_print=True): if feature_ids is None: features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) if not no_print: print("3. QgsVectorLayer.selectedFeatureIds: " + str(self.vlayer.selectedFeatureIds())) print("4. QgsVectorLayer.getSelectedFeatures: " + str([x.id() for x in self.vlayer.getSelectedFeatures()])) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) def test_vlayer(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in [1, 2, 3]: db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid) VALUES ({})'''.format( str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) def test_vlayer_other_ints_ids(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in [4, 5, 6]: db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid) VALUES ({})'''.format( str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) def test_vlayer_strings(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in ['A', 'b', 'c1']: db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid) VALUES ('{}')'''.format( str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) def test_vlayer_1000_features(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor cur.execute('''BEGIN TRANSACTION;''') for obsid in range(1000): cur.execute( '''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format( str(obsid))) cur.execute('''END TRANSACTION;''') self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, 1001)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) def test_vlayer_2000_ints(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor cur.execute('''BEGIN TRANSACTION;''') for obsid in range(2000): cur.execute( '''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format( str(obsid))) cur.execute('''END TRANSACTION;''') self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, 2001)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) def test_vlayer_2000_strings(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor obsids = [ letter + str(_int) for letter in string.ascii_letters for _int in range(80) ] cur.execute('''BEGIN TRANSACTION;''') for obsid in obsids: cur.execute( '''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format( str(obsid))) cur.execute('''END TRANSACTION;''') dbconnection.commit() self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, len(obsids) + 1)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) print(str(self.vlayer.featureCount())) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids
class TestStratigraphy(utils_for_tests.MidvattenTestPostgisDbSv): @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def create_and_select_vlayer(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() self.midvatten.ms.settingsdict['secplotdrillstop'] = "%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) print("1. Valid vlayer '{}'".format(self.vlayer.isValid())) print("2. feature_ids: " + str(feature_ids)) print("3. QgsVectorLayer.selectedFeatureIds: " + str(self.vlayer.selectedFeatureIds())) print("4. QgsVectorLayer.getSelectedFeatures: " + str([x.id() for x in self.vlayer.getSelectedFeatures()])) print("5. QgsVectorLayer.getFeature(): " + str([self.vlayer.getFeature(x).id() for x in feature_ids])) print("6. QgsVectorLayer.getFeature() type: " + str([str(type(self.vlayer.getFeature(x))) for x in feature_ids])) print("7. QgsVectorLayer.getFeatures(): " + str([x.id() for x in self.vlayer.getFeatures(feature_ids)])) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() #print(str(self.vlayer.isValid())) #print(str(db_utils.sql_load_fr_db('select * from obs_points'))) #print(str(db_utils.sql_load_fr_db('select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) #print(str(mock_messagebar.mock_calls)) #print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 print(str(mock_messagebar.mock_calls)) assert len(mock_messagebar.mock_calls) == 0 assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("test_strata: " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy_with_other_obsid_numbers(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('8', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('9', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('10', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('8', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('8', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() print(str(mock_skippopup.mock_calls)) test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['8'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['8'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"8": SURVEY('8', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('8', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy_with_string_obsid(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() print(str(self.vlayer.isValid())) print(str(db_utils.sql_load_fr_db('select * from obs_points'))) print(str(db_utils.sql_load_fr_db('select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) print(str(mock_messagebar.mock_calls)) print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['P1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['P1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 print(str(mock_messagebar.mock_calls)) assert len(mock_messagebar.mock_calls) == 0 assert test == """{"P1": SURVEY('P1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('P1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy_gap(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 2, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() print(str(self.vlayer.isValid())) print(str(db_utils.sql_load_fr_db('select * from obs_points'))) print(str(db_utils.sql_load_fr_db('select * from stratigraphy'))) dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) print(str(mock_messagebar.mock_calls)) print(str(mock_skippopup.mock_calls)) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '', '', '', 1.000000-2.000000)", "strata(3, '3', 'morän', 'moran', 2.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests. MidvattenTestPostgisNotCreated.mock_instance_settings_database) @mock.patch( 'db_utils.get_postgis_connections', utils_for_tests.MidvattenTestPostgisNotCreated.mock_postgis_connections ) def test_stratigraphy_missing_h_gs(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, h_toc, geometry) VALUES ('2', NULL, 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, geometry) VALUES ('3', ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('2', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('2', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('3', 1, 0, 2, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('3', 2, 2, 6, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 1 print(str(mock_skippopup.mock_calls)) print(str(mock_messagebar.mock_calls)) assert mock_skippopup.mock_calls == [ mock.call('Warning, h_gs is missing. See messagebar.') ] assert mock_messagebar.mock_calls == [ mock.call.warning( bar_msg="Obsid 2: using h_gs '' failed, using 'h_toc' instead.", duration=90, log_msg='False'), mock.call.warning( bar_msg="Obsid 3: using h_gs '' failed, using '-1' instead.", duration=90, log_msg='False') ] print("test: " + test) assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>'), "2": SURVEY('2', 10.000000, '<QgsPointXY: POINT(6720727 16568)>'), "3": SURVEY('3', -1.000000, '<QgsPointXY: POINT(6720728 16569)>')}""" print("test_survey " + test_survey) assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' def tearDown(self): QgsProject.instance().addMapLayer(self.vlayer) QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
f"(probably the task was manually canceled by the user)", level=Qgis.Warning) else: QgsMessageLog.logMessage( f"Task {self.description()}" f"Exception: {self.__exception}", level=Qgis.Critical) raise self.__exception def cancel(self): QgsMessageLog.logMessage( f'TracingTrask {self.description()} was canceled', level=Qgis.Info) super().cancel() if __name__ == '__main__': path_to_pipeline_layer = "C:\\Users\\jeferson.machado\\Desktop\\QGIS\\shapes\\rede_agua_tracing.shp" pipelines = QgsVectorLayer(path_to_pipeline_layer, "Pipeline layer", "ogr") if not pipelines.isValid(): print("Layer failed to load!") else: QgsProject.instance().addMapLayer(pipelines) pipes_ids = [6495] pipelines.selectByIds(pipes_ids) qlist_pipes = [x for x in pipelines.getSelectedFeatures()] find_p = FindPoints(qlist_pipes, debug=True) find_p.run()