def test_priority(self): env = "QGIS_OPTIONS_PATH" dpath = "conf0" QCoreApplication.setOrganizationName(dpath) # load settings os.environ[env] = self.testdata_path self.settings.load() # test conf self.assertTrue(self.settings.parallelRendering()) self.assertEqual(self.settings.maxThreads(), 3) # set environment variables and test priority env_pr = "QGIS_SERVER_PARALLEL_RENDERING" os.environ[env_pr] = "0" env_mt = "QGIS_SERVER_MAX_THREADS" os.environ[env_mt] = "5" self.settings.load() self.assertFalse(self.settings.parallelRendering()) self.assertEqual(self.settings.maxThreads(), 5) # clear environment os.environ.pop(env) os.environ.pop(env_pr) os.environ.pop(env_mt)
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme") QgsSettings().clear() start_app() # setup some fake connections settings = QgsSettings() key = 'qgis/connections-wms/test/' settings.setValue(key + 'url', 'aaa.bbb.com') settings.setValue(key + 'referer', 'my_ref') settings.setValue(key + 'ignoreGetMapURI', True) settings.setValue(key + 'ignoreGetFeatureInfoURI', True) settings.setValue(key + 'smoothPixmapTransform', True) settings.setValue(key + 'dpiMode', 4) settings.setValue(key + 'ignoreAxisOrientation', True) settings.setValue(key + 'invertAxisOrientation', True) key = 'qgis/connections-wfs/test/' settings.setValue(key + 'url', 'ccc.ddd.com') settings.setValue(key + 'version', '1.1.0') settings.setValue(key + 'maxnumfeatures', '47') settings.setValue(key + 'ignoreAxisOrientation', True) settings.setValue(key + 'invertAxisOrientation', True)
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsWFSProviderGUI.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsWFSProviderGUI") QgsSettings().clear() start_app()
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme") QSettings().clear() start_app()
def setUpClass(cls): """Runs at start.""" QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") QCoreApplication.setApplicationName("QGIS-TEST-%s" % uuid.uuid1()) qgis_app = start_app() # Installed plugins cls.installed_plugins = { 'MetaSearch': '0.3.5', 'QuickWKT': '3.1', 'db_manager': '0.1.20', 'firstaid': '2.1.1', 'InaSAFE': '5.0.0', 'ipyconsole': '1.8', 'plugin_reloader': '0.7.4', 'processing': '2.12.99', 'qgis-geocoding': '2.18', 'qgisce': '0.9', 'redistrict': '0.1' } data_path = os.path.join(TESTDATA_PATH, 'plugindependencies_data.json') with open(data_path) as f: cls.plugin_data = json.loads(f.read())
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsNewGeoPackageLayerDialog.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsNewGeoPackageLayerDialog") QgsSettings().clear() start_app() cls.basetestpath = tempfile.mkdtemp()
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme") QgsSettings().clear() QLocale.setDefault(QLocale(QLocale.English)) start_app()
def test_show_console(self): if os.name == 'nt': QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") QCoreApplication.setApplicationName("QGIS-TEST") my_console = console.show_console() my_console_widget = my_console.console
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsWFSProviderGUI.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsWFSProviderGUI") QSettings().clear() start_app() cls.basetestpath = tempfile.mkdtemp().replace('\\', '/')
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsProcessingInPlace.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsProcessingInPlace") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry()
def setUpClass(cls): QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsFontUtils.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsFontUtils") QgsSettings().clear() start_app() cls._family = getTestFontFamily() cls._has_style = QgsFontUtils.fontFamilyHasStyle
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsOGRProviderGpkg.com") QCoreApplication.setApplicationName("TestPyQgsOGRProviderGpkg") QgsSettings().clear() start_app() # Create test layer cls.basetestpath = tempfile.mkdtemp()
def setUpClass(cls): """Run before all tests""" # start ans setup server cls.setUpServer() # start a standalone qgis application QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsDBManagerPostgis.com") QCoreApplication.setApplicationName("TestPyQgsDBManagerPostgis") QgsSettings().clear() start_app()
def test_show_console(self): if os.name == 'nt': QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") QCoreApplication.setApplicationName("QGIS-TEST") QSettings().setValue('pythonConsole/contextHelpOnFirstLaunch', False) my_console = console.show_console() my_console_widget = my_console.console for action in my_console_widget.classMenu.actions(): action.trigger()
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsExportToPostgis.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsExportToPostgis") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry() # Create DB connection in the settings settings = QgsSettings() settings.beginGroup('/PostgreSQL/connections/qgis_test') settings.setValue('service', 'qgis_test') settings.setValue('database', 'qgis_test')
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsProcessingInPlace.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsProcessingInPlace") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry() fields = QgsFields() fields.append(QgsField('int_f', QVariant.Int)) cls.vl = QgsMemoryProviderUtils.createMemoryLayer( 'mylayer', fields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem(4326)) f1 = QgsFeature(cls.vl.fields()) f1['int_f'] = 1 f1.setGeometry(QgsGeometry.fromWkt('Point(9 45)')) f2 = QgsFeature(cls.vl.fields()) f2['int_f'] = 2 f2.setGeometry(QgsGeometry.fromWkt('Point(9.5 45.6)')) cls.vl.dataProvider().addFeatures([f1, f2]) assert cls.vl.isValid() assert cls.vl.featureCount() == 2 # Multipolygon layer cls.multipoly_vl = QgsMemoryProviderUtils.createMemoryLayer( 'mymultiplayer', fields, QgsWkbTypes.MultiPolygon, QgsCoordinateReferenceSystem(4326)) f3 = QgsFeature(cls.multipoly_vl.fields()) f3.setGeometry(QgsGeometry.fromWkt('MultiPolygon (((2.81856297539240419 41.98170998812887689, 2.81874467773035464 41.98167537995160359, 2.81879535908157752 41.98154066615795443, 2.81866433873670452 41.98144056064155905, 2.81848263699778379 41.98147516865246587, 2.81843195500470811 41.98160988234612034, 2.81856297539240419 41.98170998812887689)),((2.81898589063455907 41.9815711567298635, 2.81892080450418803 41.9816030048432367, 2.81884192631866437 41.98143737613141724, 2.8190679469505846 41.98142270931093378, 2.81898589063455907 41.9815711567298635)))')) f4 = QgsFeature(cls.multipoly_vl.fields()) f4.setGeometry(QgsGeometry.fromWkt('MultiPolygon (((2.81823679385631332 41.98133290154246566, 2.81830770255185703 41.98123540208609228, 2.81825871989355159 41.98112524362621656, 2.81813882853970243 41.98111258462271422, 2.81806791984415872 41.98121008407908761, 2.81811690250246416 41.98132024253896333, 2.81823679385631332 41.98133290154246566)),((2.81835835162010895 41.98123286963267731, 2.8183127674586852 41.98108725356146209, 2.8184520523963692 41.98115436357689134, 2.81835835162010895 41.98123286963267731)))')) cls.multipoly_vl.dataProvider().addFeatures([f3, f4]) assert cls.multipoly_vl.isValid() assert cls.multipoly_vl.featureCount() == 2 QgsProject.instance().addMapLayers([cls.vl, cls.multipoly_vl])
def test_options_path_conf1(self): env = "QGIS_OPTIONS_PATH" dpath = "conf1" ini = "{0}.ini".format(os.path.join(self.testdata_path, dpath)) QCoreApplication.setOrganizationName(dpath) # load settings os.environ[env] = self.testdata_path self.settings.load() # test ini file self.assertEqual(ini, self.settings.iniFile()) # test conf self.assertFalse(self.settings.parallelRendering()) self.assertEqual(self.settings.maxThreads(), 5) self.assertEqual(self.settings.cacheSize(), 52428800) self.assertEqual(self.settings.cacheDirectory(), "/tmp/mycache") # clear environment os.environ.pop(env)
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsDBManagerGpkg.com") QCoreApplication.setApplicationName("TestPyQgsDBManagerGpkg") QSettings().clear() start_app() cls.basetestpath = tempfile.mkdtemp() cls.test_gpkg = os.path.join(cls.basetestpath, 'TestPyQgsDBManagerGpkg.gpkg') ds = ogr.GetDriverByName('GPKG').CreateDataSource(cls.test_gpkg) lyr = ds.CreateLayer('testLayer', geom_type=ogr.wkbLineString, options=['SPATIAL_INDEX=NO']) cls.supportsAlterFieldDefn = lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 lyr.CreateField(ogr.FieldDefn('text_field', ogr.OFTString)) f = ogr.Feature(lyr.GetLayerDefn()) f['text_field'] = 'foo' f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(1 2,3 4)')) lyr.CreateFeature(f) f = None ds = None
def test_options_path_conf0(self): env = "QGIS_OPTIONS_PATH" dpath = "conf0" ini = "{0}.ini".format(os.path.join(self.testdata_path, dpath)) QCoreApplication.setOrganizationName(dpath) # load settings os.environ[env] = self.testdata_path self.settings.load() # test ini file self.assertEqual(ini, self.settings.iniFile()) # test conf self.assertTrue(self.settings.parallelRendering()) self.assertEqual(self.settings.maxThreads(), 3) self.assertEqual(self.settings.cacheSize(), 52428800) # default value when an empty string is indicated in ini file self.assertEqual(self.settings.cacheDirectory(), "cache") # clear environment os.environ.pop(env)
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme") QgsSettings().clear() start_app() # setup a fake connection settings = QgsSettings() key = QgsGeoNodeConnectionUtils.pathGeoNodeConnection() + '/test/' settings.setValue(key + 'wms/referer', 'my_ref') settings.setValue(key + 'wms/ignoreGetMapURI', True) settings.setValue(key + 'wms/ignoreGetFeatureInfoURI', True) settings.setValue(key + 'wms/smoothPixmapTransform', True) settings.setValue(key + 'wms/dpiMode', 4) settings.setValue(key + 'wms/ignoreAxisOrientation', True) settings.setValue(key + 'wms/invertAxisOrientation', True) settings.setValue(key + 'wfs/version', '1.1.0') settings.setValue(key + 'wfs/maxnumfeatures', '47') settings.setValue(key + 'wfs/ignoreAxisOrientation', True) settings.setValue(key + 'wfs/invertAxisOrientation', True)
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsPackageLayers.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsPackageLayers") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry() cls.tmp_dir = QTemporaryDir() cls.temp_path = os.path.join(cls.tmp_dir.path(), 'package_layers.gpkg') cls.temp_export_path = os.path.join(cls.tmp_dir.path(), 'package_layers_export.gpkg') # Create test DB """ Test data: Region 1 Province 1 City 1 City 2 Province 2 City 3 Region 2 Province 3 Province 4 City 4 """ ds = ogr.GetDriverByName('GPKG').CreateDataSource(cls.temp_path) lyr = ds.CreateLayer('region', geom_type=ogr.wkbNone) lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString)) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'region one' lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'region two' lyr.CreateFeature(f) lyr = ds.CreateLayer('province', geom_type=ogr.wkbNone) lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('region', ogr.OFTInteger)) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'province one' f['region'] = 1 lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'province two' f['region'] = 1 lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'province three' f['region'] = 2 lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'province four' f['region'] = 2 lyr.CreateFeature(f) lyr = ds.CreateLayer('city', geom_type=ogr.wkbNone) lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('province', ogr.OFTInteger)) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'city one' f['province'] = 1 lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'city two' f['province'] = 1 lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'city three' f['province'] = 2 lyr.CreateFeature(f) f = ogr.Feature(lyr.GetLayerDefn()) f['name'] = 'city four' f['province'] = 4 lyr.CreateFeature(f) f = None ds = None region = QgsVectorLayer(cls.temp_path + '|layername=region', 'region') province = QgsVectorLayer(cls.temp_path + '|layername=province', 'province') city = QgsVectorLayer(cls.temp_path + '|layername=city', 'city') QgsProject.instance().addMapLayers([region, province, city]) relMgr = QgsProject.instance().relationManager() rel = QgsRelation() rel.setId('rel1') rel.setName('province -> region') rel.setReferencingLayer(province.id()) rel.setReferencedLayer(region.id()) rel.addFieldPair('region', 'fid') assert rel.isValid() relMgr.addRelation(rel) rel = QgsRelation() rel.setId('rel2') rel.setName('city -> province') rel.setReferencingLayer(city.id()) rel.setReferencedLayer(province.id()) rel.addFieldPair('province', 'fid') assert rel.isValid() relMgr.addRelation(rel)
def get_qgis_app(): """ Start one QGIS application to test against. :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFload_standard_layersACE, PARENT) If QGIS is already running the handle to that app will be returned. """ try: from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas # pylint: disable=no-name-in-module # noinspection PyPackageRequirements from qgis.PyQt import QtGui, QtCore # pylint: disable=W0621 # noinspection PyPackageRequirements from qgis.PyQt.QtCore import QCoreApplication, QSettings from qgis.gui import QgisInterface except ImportError: return None, None, None, None global QGIS_APP # pylint: disable=W0603 if QGIS_APP is None: gui_flag = True # All test will run qgis in gui mode # AG: For testing purposes, we use our own configuration file instead # of using the QGIS apps conf of the host # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationName('QGIS') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationDomain('qgis.org') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setApplicationName('IsochronesTesting') # noinspection PyPep8Naming QGIS_APP = QgsApplication(sys.argv, gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() s = QGIS_APP.showSettings() # Save some settings settings = QSettings() settings.setValue('locale/overrideFlag', True) settings.setValue('locale/userLocale', 'en_US') # We disabled message bars for now for extent selector as # we don't have a main window to show them in TS - version 3.2 global PARENT # pylint: disable=W0603 if PARENT is None: # noinspection PyPep8Naming PARENT = QtGui.QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestQgsCoordinateTransformContext.com") QCoreApplication.setApplicationName("TestQgsCoordinateTransformContext") QgsSettings().clear()
def get_qgis_app(requested_locale='en_US', qsetting=''): """ Start one QGIS application to test against. :param locale: The locale we want the qgis to launch with. :type locale: str :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 from qgis.PyQt.QtCore import QSettings if qsetting: settings = QSettings(qsetting) else: settings = QSettings() try: current_locale = settings.value('locale/userLocale', 'en_US') except TypeError as e: pass locale_match = current_locale == requested_locale if iface and locale_match: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface try: from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas # pylint: disable=no-name-in-module # noinspection PyPackageRequirements from qgis.PyQt import QtWidgets, QtCore # pylint: disable=W0621 # noinspection PyPackageRequirements from qgis.PyQt.QtCore import QCoreApplication, QSettings except ImportError: return None, None, None, None if not QGIS_APP: gui_flag = True # All test will run qgis in gui mode # AG: For testing purposes, we use our own configuration file # instead of using the QGIS apps conf of the host # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationName('QGIS') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationDomain('qgis.org') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setApplicationName('QGIS3Testing') # noinspection PyPep8Naming if 'argv' in dir(sys): QGIS_APP = QgsApplication([p.encode('utf-8') for p in sys.argv], gui_flag) else: QGIS_APP = QgsApplication([], gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() s = QGIS_APP.showSettings() LOGGER.debug(s) if not locale_match: """Setup internationalisation for the plugin.""" locale_name = str(requested_locale).split('_')[0] os.environ['LANG'] = str(locale_name) i18n_path = os.path.join(os.path.dirname(__file__), '../') i18n_path = os.path.join(i18n_path, 'i18n') translation_path = os.path.join(i18n_path, '_' + str(locale_name) + '.qm') if os.path.exists(translation_path): if isinstance(QGIS_APP, sip.wrappertype): translator = QTranslator() else: translator = QTranslator(QGIS_APP) result = translator.load(translation_path) if not result: message = 'Failed to load translation for %s' % locale_name raise Exception(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(translator) if PARENT is None: # noinspection PyPep8Naming PARENT = QtWidgets.QWidget() if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) return QGIS_APP, CANVAS, IFACE, PARENT
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain(cls.__name__) QCoreApplication.setApplicationName(cls.__name__) start_app()
# Initialize PostgreSQL service connection file PGSERVICEFILE os.environ['PGSERVICEFILE'] = pg_service_file # Import QGIS AND QT modules from qgis.core import QgsApplication from qgis.PyQt.QtCore import QCoreApplication, QSettings from processing.core.Processing import Processing # Create QGIS app QgsApplication.setPrefixPath(qgisPrefixPath, True) app = QgsApplication([], False, qgisConfigPath) # Set QSettings format and path # needed so that db_manager plugin can read the settings from QGIS3.ini QCoreApplication.setOrganizationName(QgsApplication.QGIS_ORGANIZATION_NAME) QCoreApplication.setOrganizationDomain(QgsApplication.QGIS_ORGANIZATION_DOMAIN) QCoreApplication.setApplicationName(QgsApplication.QGIS_APPLICATION_NAME) QSettings.setDefaultFormat(QSettings.IniFormat) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, qgisConfigPath) # Init QGIS app.initQgis() # Initialize processing Processing.initialize() # Add Processing providers reg = app.processingRegistry() # lizsync provider from lizsync.processing.provider import LizsyncProvider
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsOapifProvider.com") QCoreApplication.setApplicationName("TestPyQgsOapifProvider") QgsSettings().clear() start_app() # On Windows we must make sure that any backslash in the path is # replaced by a forward slash so that QUrl can process it cls.basetestpath = tempfile.mkdtemp().replace('\\', '/') endpoint = cls.basetestpath + '/fake_qgis_http_endpoint' create_landing_page_api_collection(endpoint) items = { "type": "FeatureCollection", "features": [{ "type": "Feature", "id": "feat.1", "properties": { "pk": 1, "cnt": 100, "name": "Orange", "name2": "oranGe", "num_char": "1", "dt": "2020-05-03 12:13:14", "date": "2020-05-03", "time": "12:13:14" }, "geometry": { "type": "Point", "coordinates": [-70.332, 66.33] } }, { "type": "Feature", "id": "feat.2", "properties": { "pk": 2, "cnt": 200, "name": "Apple", "name2": "Apple", "num_char": "2", "dt": "2020-05-04 12:14:14", "date": "2020-05-04", "time": "12:14:14" }, "geometry": { "type": "Point", "coordinates": [-68.2, 70.8] } }, { "type": "Feature", "id": "feat.3", "properties": { "pk": 4, "cnt": 400, "name": "Honey", "name2": "Honey", "num_char": "4", "dt": "2021-05-04 13:13:14", "date": "2021-05-04", "time": "13:13:14" }, "geometry": { "type": "Point", "coordinates": [-65.32, 78.3] } }, { "type": "Feature", "id": "feat.4", "properties": { "pk": 3, "cnt": 300, "name": "Pear", "name2": "PEaR", "num_char": "3" }, "geometry": None }, { "type": "Feature", "id": "feat.5", "properties": { "pk": 5, "cnt": -200, "name": None, "name2": "NuLl", "num_char": "5", "dt": "2020-05-04 12:13:14", "date": "2020-05-02", "time": "12:13:01" }, "geometry": { "type": "Point", "coordinates": [-71.123, 78.23] } }] } # first items with open( sanitize( endpoint, '/collections/mycollection/items?limit=10&' + ACCEPT_ITEMS), 'wb') as f: f.write(json.dumps(items).encode('UTF-8')) # real page with open( sanitize( endpoint, '/collections/mycollection/items?limit=1000&' + ACCEPT_ITEMS), 'wb') as f: f.write(json.dumps(items).encode('UTF-8')) # Create test layer cls.vl = QgsVectorLayer( "url='http://" + endpoint + "' typename='mycollection'", 'test', 'OAPIF') assert cls.vl.isValid() cls.source = cls.vl.dataProvider()
def start_qgis_application( enable_gui: bool = False, enable_processing: bool = False, verbose: bool = False, cleanup: bool = True, logger: logging.Logger = None, logprefix: str = 'Qgis:', settings: Dict = None) -> 'qgis.core.QgsApplication': # noqa: F821 """ Start qgis application :param boolean enable_gui: Enable graphical interface, default to False :param boolean enable_processing: Enable processing, default to False :param boolean verbose: Output qgis settings, default to False :param boolean cleanup: Register atexit hook to close qgisapplication on exit(). Note that prevents qgis to segfault when exiting. Default to True. """ os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1' os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1' logger = logger or logging.getLogger() qgisPrefixPath = setup_qgis_paths() from qgis.PyQt.QtCore import QCoreApplication from qgis.core import Qgis, QgsApplication logger.info("Starting Qgis application: %s", Qgis.QGIS_VERSION) global version_info version_info = tuple( int(n) for n in Qgis.QGIS_VERSION.split('-')[0].split('.')) if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3": raise RuntimeError("You need QGIS3 (found %s)" % QgsApplication.QGIS_APPLICATION_NAME) if not enable_gui: # We MUST set the QT_QPA_PLATFORM to prevent # Qt trying to connect to display in containers if os.environ.get('DISPLAY') is None: logger.info("Setting offscreen mode") os.environ['QT_QPA_PLATFORM'] = 'offscreen' global qgis_application qgis_application = QgsApplication([], enable_gui) qgis_application.setPrefixPath(qgisPrefixPath, True) # From qgis server # Will enable us to read qgis setting file QCoreApplication.setOrganizationName(QgsApplication.QGIS_ORGANIZATION_NAME) QCoreApplication.setOrganizationDomain( QgsApplication.QGIS_ORGANIZATION_DOMAIN) QCoreApplication.setApplicationName(QgsApplication.QGIS_APPLICATION_NAME) qgis_application.initQgis() if cleanup: # Closing QgsApplication on exit will # prevent our app to segfault on exit() import atexit logger.info("%s Installing cleanup hook" % logprefix) @atexit.register def exitQgis(): global qgis_application if qgis_application: qgis_application.exitQgis() del qgis_application optpath = os.getenv('QGIS_OPTIONS_PATH') if optpath: # Log qgis settings load_qgis_settings(optpath, logger, verbose) if settings: # Initialize settings from qgis.core import QgsSettings qgsettings = QgsSettings() for k, v in settings.items(): qgsettings.setValue(k, v) if verbose: print(qgis_application.showSettings()) # Install logger hook install_logger_hook(logger, logprefix, verbose=verbose) logger.info("%s Qgis application initialized......" % logprefix) if enable_processing: init_qgis_processing() logger.info("%s QGis processing initialized" % logprefix) return qgis_application
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsWFSProvider.com") QCoreApplication.setApplicationName("TestPyQgsWFSProvider") QgsSettings().clear()
""" __author__ = 'Juergen E. Fischer' __date__ = 'June 2013' __copyright__ = '(C) 2013, Juergen E. Fischer' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '74f49ddd197ad05182f9e7ce59213663297f498e' from qgis.PyQt.QtCore import QCoreApplication, QSettings def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i + n] QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") QCoreApplication.setApplicationName("QGIS3") s = QSettings() ba = s.value("/UI/geometry").toByteArray() f = open("src/app/ui_defaults.h", "w") f.write("#ifndef UI_DEFAULTS_H\n#define UI_DEFAULTS_H\n\nstatic const unsigned char defaultUIgeometry[] =\n{\n") for chunk in chunks(ba, 16): f.write(" %s,\n" % ", ".join(map(lambda x: "0x%02x" % ord(x), chunk))) f.write("};\n\nstatic const unsigned char defaultUIstate[] =\n{\n")
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsAFSProvider.com") QCoreApplication.setApplicationName("TestPyQgsAFSProvider") QgsSettings().clear() start_app() # On Windows we must make sure that any backslash in the path is # replaced by a forward slash so that QUrl can process it cls.basetestpath = tempfile.mkdtemp().replace('\\', '/') endpoint = cls.basetestpath + '/fake_qgis_http_endpoint' with open(sanitize(endpoint, '?f=json'), 'wb') as f: f.write(""" {"currentVersion":10.22,"id":1,"name":"QGIS Test","type":"Feature Layer","description": "QGIS Provider Test Layer.\n","geometryType":"esriGeometryPoint","copyrightText":"","parentLayer":{"id":0,"name":"QGIS Tests"},"subLayers":[], "minScale":72225,"maxScale":0, "defaultVisibility":true, "extent":{"xmin":-71.123,"ymin":66.33,"xmax":-65.32,"ymax":78.3, "spatialReference":{"wkid":4326,"latestWkid":4326}}, "hasAttachments":false,"htmlPopupType":"esriServerHTMLPopupTypeAsHTMLText", "displayField":"LABEL","typeIdField":null, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "relationships":[],"canModifyLayer":false,"canScaleSymbols":false,"hasLabels":false, "capabilities":"Map,Query,Data","maxRecordCount":1000,"supportsStatistics":true, "supportsAdvancedQueries":true,"supportedQueryFormats":"JSON, AMF", "ownershipBasedAccessControlForFeatures":{"allowOthersToQuery":true},"useStandardizedQueries":true}""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json_where=OBJECTID=OBJECTID_returnIdsOnly=true'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 5, 3, 1, 2, 4 ] } """.encode('UTF-8')) # Create test layer cls.vl = QgsVectorLayer("url='http://" + endpoint + "' crs='epsg:4326'", 'test', 'arcgisfeatureserver') assert cls.vl.isValid() cls.source = cls.vl.dataProvider() with open(sanitize(endpoint, '/query?f=json&objectIds=5,3,1,2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false'), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 5, "pk": 5, "cnt": -200, "name": null, "name2":"NuLl", "num_char":"5" }, "geometry": { "x": -71.123, "y": 78.23 } }, { "attributes": { "OBJECTID": 3, "pk": 3, "cnt": 300, "name": "Pear", "name2":"PEaR", "num_char":"3" }, "geometry": null }, { "attributes": { "OBJECTID": 1, "pk": 1, "cnt": 100, "name": "Orange", "name2":"oranGe", "num_char":"1" }, "geometry": { "x": -70.332, "y": 66.33 } }, { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&objectIds=5,3,1,2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false&geometry=-71.123000,66.330000,-65.320000,78.300000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 5, "pk": 5, "cnt": -200, "name": null, "name2":"NuLl", "num_char":"5" }, "geometry": { "x": -71.123, "y": 78.23 } }, { "attributes": { "OBJECTID": 3, "pk": 3, "cnt": 300, "name": "Pear", "name2":"PEaR", "num_char":"3" }, "geometry": null }, { "attributes": { "OBJECTID": 1, "pk": 1, "cnt": 100, "name": "Orange", "name2":"oranGe", "num_char":"1" }, "geometry": { "x": -70.332, "y": 66.33 } }, { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-70.000000,67.000000,-60.000000,80.000000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-73.000000,70.000000,-63.000000,80.000000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-68.721119,68.177676,-64.678700,79.123755&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8'))
__author__ = 'Juergen E. Fischer' __date__ = 'June 2013' __copyright__ = '(C) 2013, Juergen E. Fischer' # This will get replaced with a git SHA1 when you do a git archive __revision__ = 'b4ba98dfd2ea8a2d264d209d7147b5dd40c7dcdc' from qgis.PyQt.QtCore import QCoreApplication, QSettings def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") QCoreApplication.setApplicationName("QGIS3") s = QSettings() ba = s.value("/UI/geometry").toByteArray() f = open("src/app/ui_defaults.h", "w") f.write( "#ifndef UI_DEFAULTS_H\n#define UI_DEFAULTS_H\n\nstatic const unsigned char defaultUIgeometry[] =\n{\n" ) for chunk in chunks(ba, 16): f.write(" %s,\n" % ", ".join(map(lambda x: "0x%02x" % ord(x), chunk)))
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsNewGeoPackageLayerDialog.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsNewGeoPackageLayerDialog") QgsSettings().clear()
def get_qgis_app(requested_locale='en_US', qsetting=''): """ Start one QGIS application to test against. :param locale: The locale we want the qgis to launch with. :type locale: str :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 from qgis.PyQt.QtCore import QSettings if qsetting: settings = QSettings(qsetting) else: settings = QSettings() default_user_directory = setting('defaultUserDirectory') current_locale = general_setting('locale/userLocale', default='en_US', qsettings=settings) locale_match = current_locale == requested_locale if iface and locale_match: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface try: from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas # pylint: disable=no-name-in-module # noinspection PyPackageRequirements from qgis.PyQt import QtWidgets, QtCore # pylint: disable=W0621 # noinspection PyPackageRequirements from qgis.PyQt.QtCore import QCoreApplication, QSettings from safe.test.qgis_interface import QgisInterface except ImportError: return None, None, None, None if qsetting: settings = QSettings(qsetting) else: settings = QSettings() if not QGIS_APP: gui_flag = True # All test will run qgis in gui mode # AG: For testing purposes, we use our own configuration file # instead of using the QGIS apps conf of the host # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationName('QGIS') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationDomain('qgis.org') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setApplicationName('QGIS2InaSAFETesting') # We disabled message bars for now for extent selector as # we don't have a main window to show them in TS - version 3.2 set_setting('show_extent_warnings', False, settings) set_setting('showRubberBands', True, settings) set_setting('show_extent_confirmations', False, settings) set_setting('analysis_extents_mode', HAZARD_EXPOSURE, settings) if default_user_directory: set_setting('defaultUserDirectory', default_user_directory, settings) # noinspection PyPep8Naming if 'argv' in dir(sys): QGIS_APP = QgsApplication([p.encode('utf-8') for p in sys.argv], gui_flag) else: QGIS_APP = QgsApplication([], gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() # Initialize processing processing.Processing.initialize() s = QGIS_APP.showSettings() LOGGER.debug(s) if not locale_match: """Setup internationalisation for the plugin.""" # Save some settings set_general_setting('locale/overrideFlag', True, settings) set_general_setting('locale/userLocale', requested_locale, settings) locale_name = str(requested_locale).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(locale_name) inasafe_translation_path = os.path.join( safe_dir('i18n'), 'inasafe_' + str(locale_name) + '.qm') if os.path.exists(inasafe_translation_path): if isinstance(QGIS_APP, sip.wrappertype): translator = QTranslator() else: translator = QTranslator(QGIS_APP) result = translator.load(inasafe_translation_path) if not result: message = 'Failed to load translation for %s' % locale_name raise Exception(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(translator) # at the end, reload InaSAFE modules so it will get translated too reload_inasafe_modules() if PARENT is None: # noinspection PyPep8Naming PARENT = QtWidgets.QWidget() if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
def get_qgis_app(requested_locale='en_US', qsetting=''): """ Start one QGIS application to test against. :param locale: The locale we want the qgis to launch with. :type locale: str :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 from qgis.PyQt.QtCore import QSettings if qsetting: settings = QSettings(qsetting) else: settings = QSettings() default_user_directory = setting('defaultUserDirectory') current_locale = general_setting( 'locale/userLocale', default='en_US', qsettings=settings) locale_match = current_locale == requested_locale if iface and locale_match: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface try: from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas # pylint: disable=no-name-in-module # noinspection PyPackageRequirements from qgis.PyQt import QtWidgets, QtCore # pylint: disable=W0621 # noinspection PyPackageRequirements from qgis.PyQt.QtCore import QCoreApplication, QSettings from safe.test.qgis_interface import QgisInterface except ImportError: return None, None, None, None if qsetting: settings = QSettings(qsetting) else: settings = QSettings() if not QGIS_APP: gui_flag = True # All test will run qgis in gui mode # AG: For testing purposes, we use our own configuration file # instead of using the QGIS apps conf of the host # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationName('QGIS') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationDomain('qgis.org') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setApplicationName('QGIS2InaSAFETesting') # We disabled message bars for now for extent selector as # we don't have a main window to show them in TS - version 3.2 set_setting('show_extent_warnings', False, settings) set_setting('showRubberBands', True, settings) set_setting('show_extent_confirmations', False, settings) set_setting('analysis_extents_mode', HAZARD_EXPOSURE, settings) if default_user_directory: set_setting( 'defaultUserDirectory', default_user_directory, settings) # noinspection PyPep8Naming if 'argv' in dir(sys): QGIS_APP = QgsApplication([p.encode('utf-8') for p in sys.argv], gui_flag) else: QGIS_APP = QgsApplication([], gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() # Initialize processing processing.Processing.initialize() s = QGIS_APP.showSettings() LOGGER.debug(s) if not locale_match: """Setup internationalisation for the plugin.""" # Save some settings set_general_setting('locale/overrideFlag', True, settings) set_general_setting('locale/userLocale', requested_locale, settings) locale_name = str(requested_locale).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(locale_name) inasafe_translation_path = os.path.join( safe_dir('i18n'), 'inasafe_' + str(locale_name) + '.qm') if os.path.exists(inasafe_translation_path): if isinstance(QGIS_APP, sip.wrappertype): translator = QTranslator() else: translator = QTranslator(QGIS_APP) result = translator.load(inasafe_translation_path) if not result: message = 'Failed to load translation for %s' % locale_name raise Exception(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(translator) # at the end, reload InaSAFE modules so it will get translated too reload_inasafe_modules() if PARENT is None: # noinspection PyPep8Naming PARENT = QtWidgets.QWidget() if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsAFSProvider.com") QCoreApplication.setApplicationName("TestPyQgsAFSProvider") QgsSettings().clear() start_app() # On Windows we must make sure that any backslash in the path is # replaced by a forward slash so that QUrl can process it cls.basetestpath = tempfile.mkdtemp().replace('\\', '/') endpoint = cls.basetestpath + '/fake_qgis_http_endpoint' with open(sanitize(endpoint, '?f=json'), 'wb') as f: f.write(""" {"currentVersion":10.22,"id":1,"name":"QGIS Test","type":"Feature Layer","description": "QGIS Provider Test Layer.\n","geometryType":"esriGeometryPoint","copyrightText":"","parentLayer":{"id":0,"name":"QGIS Tests"},"subLayers":[], "minScale":72225,"maxScale":0, "defaultVisibility":true, "extent":{"xmin":-71.123,"ymin":66.33,"xmax":-65.32,"ymax":78.3, "spatialReference":{"wkid":4326,"latestWkid":4326}}, "hasAttachments":false,"htmlPopupType":"esriServerHTMLPopupTypeAsHTMLText", "displayField":"LABEL","typeIdField":null, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "relationships":[],"canModifyLayer":false,"canScaleSymbols":false,"hasLabels":false, "capabilities":"Map,Query,Data","maxRecordCount":1000,"supportsStatistics":true, "supportsAdvancedQueries":true,"supportedQueryFormats":"JSON, AMF", "ownershipBasedAccessControlForFeatures":{"allowOthersToQuery":true},"useStandardizedQueries":true}""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json_where=OBJECTID=OBJECTID_returnIdsOnly=true'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 5, 3, 1, 2, 4 ] } """.encode('UTF-8')) # Create test layer cls.vl = QgsVectorLayer("url='http://" + endpoint + "' crs='epsg:4326'", 'test', 'arcgisfeatureserver') assert cls.vl.isValid() cls.source = cls.vl.dataProvider() with open(sanitize(endpoint, '/query?f=json&objectIds=5,3,1,2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false'), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 5, "pk": 5, "cnt": -200, "name": null, "name2":"NuLl", "num_char":"5" }, "geometry": { "x": -71.123, "y": 78.23 } }, { "attributes": { "OBJECTID": 3, "pk": 3, "cnt": 300, "name": "Pear", "name2":"PEaR", "num_char":"3" }, "geometry": null }, { "attributes": { "OBJECTID": 1, "pk": 1, "cnt": 100, "name": "Orange", "name2":"oranGe", "num_char":"1" }, "geometry": { "x": -70.332, "y": 66.33 } }, { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&objectIds=5,3,1,2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false&geometry=-71.123000,66.330000,-65.320000,78.300000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 5, "pk": 5, "cnt": -200, "name": null, "name2":"NuLl", "num_char":"5" }, "geometry": { "x": -71.123, "y": 78.23 } }, { "attributes": { "OBJECTID": 3, "pk": 3, "cnt": 300, "name": "Pear", "name2":"PEaR", "num_char":"3" }, "geometry": null }, { "attributes": { "OBJECTID": 1, "pk": 1, "cnt": 100, "name": "Orange", "name2":"oranGe", "num_char":"1" }, "geometry": { "x": -70.332, "y": 66.33 } }, { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&objectIds=2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false'), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-70.000000,67.000000,-60.000000,80.000000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-73.000000,70.000000,-63.000000,80.000000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8')) with open(sanitize(endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-68.721119,68.177676,-64.678700,79.123755&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects'), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8'))