Пример #1
0
def getQGISDbs(portlast=False):
    """Return all PostGIS connection settings stored in QGIS
    :return: connection dict() with name and other settings
            """
    settings = QSettings()
    settings.beginGroup('/PostgreSQL/connections')
    named_dbs = settings.childGroups()
    all_info = [
        i.split("/") + [str(settings.value(i))] for i in settings.allKeys()
        if settings.value(i) != NULL and settings.value(i) != ''
    ]

    query_columns = [
        'name', 'host', 'service', 'password', 'username', 'port', 'database'
    ]
    if portlast:
        query_columns = [
            'name', 'host', 'service', 'password', 'username', 'database',
            'port'
        ]

    all_info = [
        i for i in all_info
        if i[0] in named_dbs and i[2] != NULL and i[1] in query_columns
    ]
    dbs = dict([k, dict([i[1:] for i in list(g)])]
               for k, g in itertools.groupby(sorted(all_info),
                                             operator.itemgetter(0)))
    settings.endGroup()
    return dbs
Пример #2
0
def export_setting(file_path, qsettings=None):
    """Export InaSAFE's setting to a file.

    :param file_path: The file to write the exported setting.
    :type file_path: basestring

    :param qsettings: A custom QSettings to use. If it's not defined, it will
        use the default one.
    :type qsettings: qgis.PyQt.QtCore.QSettings

    :returns: A dictionary of the exported settings.
    :rtype: dict
    """
    inasafe_settings = {}

    if not qsettings:
        qsettings = QSettings()

    qsettings.beginGroup('inasafe')
    all_keys = qsettings.allKeys()
    qsettings.endGroup()

    for key in all_keys:
        inasafe_settings[key] = setting(key, qsettings=qsettings)

    def custom_default(obj):
        if obj is None or (hasattr(obj, 'isNull') and obj.isNull()):
            return ''
        raise TypeError

    with open(file_path, 'w') as json_file:
        json.dump(
            inasafe_settings, json_file, indent=2, default=custom_default)

    return inasafe_settings
Пример #3
0
def get_local_mergin_projects_info():
    """Get a list of local Mergin projects info from QSettings."""
    local_projects_info = []
    settings = QSettings()
    config_server = settings.value("Mergin/server", None)
    if config_server is None:
        return local_projects_info
    settings.beginGroup("Mergin/localProjects/")
    for key in settings.allKeys():
        # Expecting key in the following form: '<namespace>/<project_name>/path'
        # - needs project dir to load metadata
        key_parts = key.split("/")
        if len(key_parts) > 2 and key_parts[2] == "path":
            local_path = settings.value(key, None)
            # double check if the path exists - it might get deleted manually
            if local_path is None or not os.path.exists(local_path):
                continue
            # We also need the server the project was created for, but users may already have some projects created
            # without the server specified. In that case, let's assume it is currently defined server and also store
            # the info for later, when user will be able to change server config actively.
            server_key = f"{key_parts[0]}/{key_parts[1]}/server"
            proj_server = settings.value(server_key, None)
            if proj_server is None:
                proj_server = config_server
                settings.setValue(server_key, config_server)
            # project info = (path, project owner, project name, server)
            local_projects_info.append(
                (local_path, key_parts[0], key_parts[1], proj_server))
    return local_projects_info
Пример #4
0
def remove_xyz_connections():
    """ Remove all XYZ entries in the Browser """
    qs = QSettings()

    for k in sorted(qs.allKeys()):
        if "qgis/connections-xyz/" in k:
            qs.remove(k)

    iface.reloadConnections()
Пример #5
0
def remove_postgis_connections() -> None:
    """ Remove all entries under PostGIS in the Browser """
    qs = QSettings()

    for k in sorted(qs.allKeys()):
        if "PostgreSQL/connections/" in k:
            qs.remove(k)

    iface.reloadConnections()
Пример #6
0
    def get_parameters_conn(self, db_source):
        dict_conn = dict()
        settings = QSettings()
        settings.beginGroup(
            'Asistente-LADM-COL/db/{db_source}/{engine}/'.format(
                db_source=db_source, engine=self._engine))
        for key in settings.allKeys():
            dict_conn[key] = settings.value(key)

        settings.endGroup()
        return dict_conn
Пример #7
0
    def setupDatabaseConnectionSettings(self):
        self.dialogSettings.comboBoxUsedDBConnection.clear()
        self.dialogSettings.comboBoxUsedDBConnection.addItem("")

        settings = QSettings()
        settings.beginGroup(YleiskaavaSettings.PG_CONNECTIONS)
        keys = settings.allKeys()
        settings.endGroup()
        connections = sorted({key.split('/')[0] for key in keys if '/' in key})

        for conn in connections:
            # QgsMessageLog.logMessage('setupDatabaseConnectionSettings - connection: ' + conn, 'Yleiskaava-työkalu', Qgis.Info)
            self.dialogSettings.comboBoxUsedDBConnection.addItem(conn)

        self.readDatabaseConnectionSettings()
Пример #8
0
def get_postgis_connections():
    qs = QSettings()
    postgresql_connections = {}
    for k in sorted(qs.allKeys()):
        k = ru(k)
        if k.startswith('PostgreSQL'):
            cols = k.split('/')
            conn_name = cols[2]
            try:
                setting = cols[3]
            except IndexError:
                #utils.MessagebarAndLog.info(log_msg='Postgresql connection info: Setting ' + str(k) + " couldn't be read")
                continue
            value = qs.value(k)
            postgresql_connections.setdefault(conn_name, {})[setting] = value

    postgresql_connections= ru(postgresql_connections, keep_containers=True)
    return postgresql_connections
Пример #9
0
def get_postgis_connections():
    qs = QSettings()
    postgresql_connections = {}
    for k in sorted(qs.allKeys()):
        k = ru(k)
        if k.startswith('PostgreSQL'):
            cols = k.split('/')
            conn_name = cols[2]
            try:
                setting = cols[3]
            except IndexError:
                #utils.MessagebarAndLog.info(log_msg='Postgresql connection info: Setting ' + str(k) + " couldn't be read")
                continue
            value = qs.value(k)
            postgresql_connections.setdefault(conn_name, {})[setting] = value

    postgresql_connections = ru(postgresql_connections, keep_containers=True)
    return postgresql_connections
Пример #10
0
def getPostgisConnectionString(name):
    """

    :param name:
    :return:
    """
    connstring = ''
    settings = QSettings()
    settings.beginGroup('/PostgreSQL/connections/%s' % name)
    for item in settings.allKeys():
        if item in ('host', 'port', 'password', 'service'):
            if settings.value(item):
                connstring += "%s='%s' " % (item, settings.value(item))
        elif item == 'database':
            if settings.value(item):
                connstring += "dbname='%s' " % settings.value(item)
        elif item == 'username':
            if settings.value(item):
                connstring += "user='******' " % settings.value(item)
    return connstring
Пример #11
0
    def test_overwriteDefaultValues(self):
        """Test that unchanged values are not stored"""
        self.globalsettings.setValue('a_value_with_default', 'a value')
        self.globalsettings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'),
                         'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Now, set them with the same current value
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        # Check
        pure_settings = QSettings(self.settings.fileName(),
                                  QSettings.IniFormat)
        self.assertFalse('a_value_with_default' in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' in pure_settings.allKeys())

        # Set a changed value
        self.settings.setValue('a_value_with_default', 'a new value')
        self.settings.setValue('an_invalid_value', 'valid value')

        # Check
        self.assertTrue('a_value_with_default' in pure_settings.allKeys())
        self.assertTrue('an_invalid_value' in pure_settings.allKeys())

        self.assertEqual(self.settings.value('a_value_with_default'),
                         'a new value')
        self.assertEqual(self.settings.value('an_invalid_value'),
                         'valid value')

        # Re-set to original values
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'),
                         'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Check if they are gone
        pure_settings = QSettings(self.settings.fileName(),
                                  QSettings.IniFormat)
        self.assertFalse('a_value_with_default' not in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' not in pure_settings.allKeys())
Пример #12
0
def set_project_variables():
    """
    Sets project related mergin variables. Supposed to be called when any QGIS project is (re)loaded.
    If a loaded project is not a mergin project, it suppose to have custom variables without mergin variables by default.
    If a loaded project is invalid - doesnt have metadata, mergin variables are removed.
    """
    settings = QSettings()
    settings.beginGroup('Mergin/localProjects/')
    for key in settings.allKeys():
        # Expecting key in the following form: '<namespace>/<project_name>/path' - needs project dir to load metadata
        key_parts = key.split('/')
        if len(key_parts) > 2 and key_parts[2] == 'path':
            path = settings.value(key)
            if path == QgsProject.instance().absolutePath(
            ) or path + '/' in QgsProject.instance().absolutePath():
                try:
                    mp = MerginProject(path)
                    metadata = mp.metadata
                    write_project_variables(key_parts[0], key_parts[1],
                                            metadata.get("name"),
                                            metadata.get("version"))
                    return
                except InvalidProject:
                    remove_project_variables()
Пример #13
0
    def test_overwriteDefaultValues(self):
        """Test that unchanged values are not stored"""
        self.globalsettings.setValue('a_value_with_default', 'a value')
        self.globalsettings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Now, set them with the same current value
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        # Check
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' in pure_settings.allKeys())

        # Set a changed value
        self.settings.setValue('a_value_with_default', 'a new value')
        self.settings.setValue('an_invalid_value', 'valid value')

        # Check
        self.assertTrue('a_value_with_default' in pure_settings.allKeys())
        self.assertTrue('an_invalid_value' in pure_settings.allKeys())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a new value')
        self.assertEqual(self.settings.value('an_invalid_value'), 'valid value')

        # Re-set to original values
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Check if they are gone
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' not in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' not in pure_settings.allKeys())
Пример #14
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del(self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def addGroupToDefaults(self, prefix, kvp):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginGroup(prefix)
        for k, v in kvp.items():
            self.globalsettings.setValue(k, v)
        self.globalsettings.endGroup()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(self.settings.value('testqgissettings/doesnotexists', 'notexist'), 'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks', self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2', self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks', self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence_simple(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'), 'qgisrocks-1')

    def test_precedence_group(self):
        """Test if user can override a group value"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addGroupToDefaults('connections-xyz', {
            'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
            'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
        })
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override edit
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: the global value will be resumed!!!
        self.settings.beginGroup('connections-xyz')
        self.settings.remove('OSM')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a blank!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', '')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), '')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a None: will resume the global setting!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', None)
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1', 'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.settings.beginGroup('testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual('qgisrocks-1', self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4', self.settings.value('testqgissettings/names/name4'))

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_array_overrides(self):
        """Test if an array completely shadows the global one"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        # Now override!
        self.settings.beginWriteArray('testqgissettings')
        self.settings.setArrayIndex(0)
        self.settings.setValue('key', 'myqgisrocksmore1')
        self.settings.setArrayIndex(1)
        self.settings.setValue('key', 'myqgisrocksmore2')
        self.settings.endArray()

        # Check it!
        self.assertEqual(2, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(2):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1', 'provider1', section=QgsSettings.Providers)
        self.settings.setValue('key2', 'provider2', section=QgsSettings.Providers)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Core), 'core1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Core), 'core2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Server), 'server1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Server), 'server2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Plugins), 'plugins1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Plugins), 'plugins2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Misc), 'misc1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Misc), 'misc2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Auth), 'auth1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Auth), 'auth2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Providers), 'provider1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Providers), 'provider2')

        # Test default values on Section getter
        self.assertEqual(self.settings.value('key_not_exist', 'misc_not_exist', section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)
Пример #15
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        Path(path).touch()
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)
        self.globalsettings.sync()
        assert os.path.exists(self.globalsettings.fileName())

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del(self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def addGroupToDefaults(self, prefix, kvp):
        defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat)  # NOQA
        self.globalsettings.beginGroup(prefix)
        for k, v in kvp.items():
            self.globalsettings.setValue(k, v)
        self.globalsettings.endGroup()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(self.settings.value('testqgissettings/doesnotexists', 'notexist'), 'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks', self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2', self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks', self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence_simple(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'), 'qgisrocks-1')

    def test_precedence_group(self):
        """Test if user can override a group value"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addGroupToDefaults('connections-xyz', {
            'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
            'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
        })
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override edit
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: the global value will be resumed!!!
        self.settings.beginGroup('connections-xyz')
        self.settings.remove('OSM')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a blank!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', '')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), '')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a None: will resume the global setting!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', None)
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1', 'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(self.settings.group(), 'testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')
        self.settings.beginGroup('testqgissettings/names')
        self.assertEqual(self.settings.group(), 'testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')
        self.assertEqual('qgisrocks-1', self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4', self.settings.value('testqgissettings/names/name4'))

    def test_global_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.assertEqual(self.globalsettings.allKeys(), [])

        self.addToDefaults('testqgissettings/foo/first', 'qgis')
        self.addToDefaults('testqgissettings/foo/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(self.settings.group(), 'testqgissettings')
        self.assertEqual(['foo'], self.settings.childGroups())
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')

        self.settings.setValue('testqgissettings/bar/first', 'qgis')
        self.settings.setValue('testqgissettings/bar/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(sorted(['bar', 'foo']), sorted(self.settings.childGroups()))
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()

        self.globalsettings.remove('testqgissettings/foo')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['bar'], self.settings.childGroups())
        self.assertEqual([], self.settings.globalChildGroups())
        self.settings.endGroup()

    def test_group_section(self):
        # Test group by using Section
        self.settings.beginGroup('firstgroup', section=QgsSettings.Core)
        self.assertEqual(self.settings.group(), 'core/firstgroup')
        self.assertEqual([], self.settings.childGroups())
        self.settings.setValue('key', 'value')
        self.settings.setValue('key2/subkey1', 'subvalue1')
        self.settings.setValue('key2/subkey2', 'subvalue2')
        self.settings.setValue('key3', 'value3')

        self.assertEqual(['key', 'key2/subkey1', 'key2/subkey2', 'key3'], self.settings.allKeys())
        self.assertEqual(['key', 'key3'], self.settings.childKeys())
        self.assertEqual(['key2'], self.settings.childGroups())
        self.settings.endGroup()
        self.assertEqual(self.settings.group(), '')
        # Set value by writing the group manually
        self.settings.setValue('firstgroup/key4', 'value4', section=QgsSettings.Core)
        # Checking the value that have been set
        self.assertEqual(self.settings.value('firstgroup/key', section=QgsSettings.Core), 'value')
        self.assertEqual(self.settings.value('firstgroup/key2/subkey1', section=QgsSettings.Core), 'subvalue1')
        self.assertEqual(self.settings.value('firstgroup/key2/subkey2', section=QgsSettings.Core), 'subvalue2')
        self.assertEqual(self.settings.value('firstgroup/key3', section=QgsSettings.Core), 'value3')
        self.assertEqual(self.settings.value('firstgroup/key4', section=QgsSettings.Core), 'value4')
        # Clean up firstgroup
        self.settings.remove('firstgroup', section=QgsSettings.Core)

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_array_overrides(self):
        """Test if an array completely shadows the global one"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])
        self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size'])

        self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        # Now override!
        self.settings.beginWriteArray('testqgissettings')
        self.settings.setArrayIndex(0)
        self.settings.setValue('key', 'myqgisrocksmore1')
        self.settings.setArrayIndex(1)
        self.settings.setValue('key', 'myqgisrocksmore2')
        self.settings.endArray()

        # Check it!
        self.assertEqual(2, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(2):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1', 'provider1', section=QgsSettings.Providers)
        self.settings.setValue('key2', 'provider2', section=QgsSettings.Providers)

        # This is an overwrite of previous setting and it is intentional
        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Core), 'core1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Core), 'core2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Server), 'server1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Server), 'server2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Plugins), 'plugins1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Plugins), 'plugins2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Misc), 'misc1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Misc), 'misc2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Auth), 'auth1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Auth), 'auth2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Providers), 'provider1')
        self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Providers), 'provider2')

        # Test default values on Section getter
        self.assertEqual(self.settings.value('key_not_exist', 'misc_not_exist', section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)

        # Test remove by using Section
        self.settings.setValue('testQgisSettings/tempSection', True, section=QgsSettings.Core)
        self.assertEqual(self.settings.value('testQgisSettings/tempSection', section=QgsSettings.Core), True)
        self.settings.remove('testQgisSettings/temp', section=QgsSettings.Core)
        self.assertEqual(self.settings.value('testqQgisSettings/temp', section=QgsSettings.Core), None)

    def test_enumValue(self):
        self.settings.setValue('enum', 'LayerUnits')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits)
        self.settings.setValue('enum', 'dummy_setting')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels)
        self.assertEqual(type(self.settings.enumValue('enum', QgsTolerance.Pixels)), QgsTolerance.UnitType)

    def test_setEnumValue(self):
        self.settings.setValue('enum', 'LayerUnits')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits)
        self.settings.setEnumValue('enum', QgsTolerance.Pixels)
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels)

    def test_flagValue(self):
        pointAndLine = QgsMapLayerProxyModel.Filters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.LineLayer)
        pointAndPolygon = QgsMapLayerProxyModel.Filters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.PolygonLayer)

        self.settings.setValue('flag', 'PointLayer|PolygonLayer')
        self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndPolygon)
        self.settings.setValue('flag', 'dummy_setting')
        self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndLine)
        self.assertEqual(type(self.settings.flagValue('enum', pointAndLine)), QgsMapLayerProxyModel.Filters)

    def test_overwriteDefaultValues(self):
        """Test that unchanged values are not stored"""
        self.globalsettings.setValue('a_value_with_default', 'a value')
        self.globalsettings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Now, set them with the same current value
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        # Check
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' in pure_settings.allKeys())

        # Set a changed value
        self.settings.setValue('a_value_with_default', 'a new value')
        self.settings.setValue('an_invalid_value', 'valid value')

        # Check
        self.assertTrue('a_value_with_default' in pure_settings.allKeys())
        self.assertTrue('an_invalid_value' in pure_settings.allKeys())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a new value')
        self.assertEqual(self.settings.value('an_invalid_value'), 'valid value')

        # Re-set to original values
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Check if they are gone
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' not in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' not in pure_settings.allKeys())
Пример #16
0
# coding=utf-8
Пример #17
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings',
                                    'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(),
                                        QSettings.IniFormat)

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del (self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(),
                             QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(
            self.settings.value('testqgissettings/doesnotexists', 'notexist'),
            'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'),
                         'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'),
                         'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks',
                         self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2',
                         self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks',
                         self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'),
                         'qgisrocks-1')

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'),
                         'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'),
                         'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1',
                               'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'),
                         'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.settings.beginGroup('testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual('qgisrocks-1',
                         self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4',
                         self.settings.value('testqgissettings/names/name4'))

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key',
                                ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])
        self.assertEqual(self.globalsettings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])

        self.assertEqual(
            3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1',
                               'provider1',
                               section=QgsSettings.Providers)
        self.settings.setValue('key2',
                               'provider2',
                               section=QgsSettings.Providers)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Core),
            'core1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Core),
            'core2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Server),
            'server1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Server),
            'server2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Plugins),
            'plugins1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Plugins),
            'plugins2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Misc),
            'misc1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Misc),
            'misc2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Auth),
            'auth1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Auth),
            'auth2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Providers),
            'provider1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Providers),
            'provider2')

        # Test default values on Section getter
        self.assertEqual(
            self.settings.value('key_not_exist',
                                'misc_not_exist',
                                section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)
Пример #18
0
 def all_keys(self):
     settings = QSettings()
     settings.beginGroup(self.groupPath)
     return settings.allKeys()
Пример #19
0
class GWPluginExample(QObject):
    def __init__(self, iface):
        """ Constructor
        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Initialize instance attributes
        super(GWPluginExample, self).__init__()
        self.iface = iface
        self.plugin_toolbars = {}
        self.buttons = {}
        self.srid = None
        self.load_project = None
        self.dict_toolbars = {}
        self.dict_actions = {}
        self.actions_not_checkable = None
        self.available_layers = []
        self.btn_add_layers = None
        self.update_sql = None
        self.action = None
        self.action_info = None
        self.toolButton = None

    def unload(self, remove_modules=True):
        """ Removes plugin menu items and icons from QGIS GUI
            :param @remove_modules is True when plugin is disabled or reloaded
        """
        pass

    def initGui(self):
        """ Create the menu entries and toolbar icons inside the QGIS GUI """

        # Initialize plugin
        self.init_plugin()

    def init_plugin(self):
        """ Plugin main initialization function """

        # Initialize plugin global variables
        self.plugin_dir = os.path.dirname(__file__)
        self.icon_folder = self.plugin_dir + os.sep + 'icons' + os.sep + 'toolbars' + os.sep
        self.plugin_name = self.get_plugin_metadata('name',
                                                    'giswater_plugin_example')
        setting_file = os.path.join(self.plugin_dir, 'config', 'init.config')
        if not os.path.exists(setting_file):
            message = f"Config file not found at: {setting_file}"
            self.iface.messageBar().pushMessage("", message, 1, 20)
            return

        # Need init giswater global_vars if we can inherit from GwMaptool becouse example is loaded before giswater
        gw_global_vars.init_global(self.iface, self.iface.mapCanvas(),
                                   giswater_folder_path, self.plugin_name,
                                   None)

        global_vars.init_global(self.iface, self.iface.mapCanvas(),
                                self.plugin_dir, self.plugin_name, None)
        major_version = tools_qgis.get_major_version('1.1', self.plugin_dir)
        global_vars.roaming_user_dir = f'{tools_os.get_datadir()}{os.sep}{self.plugin_name.capitalize()}{os.sep}{major_version}'

        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        self.qgis_settings = QSettings()
        self.qgis_settings.setIniCodec(sys.getfilesystemencoding())

        # Manage section 'actions_list' of config file
        self.manage_section_actions_list()

        # Manage section 'toolbars' of config file
        self.manage_section_toolbars()

        # PROJECT_READ
        self.manage_toolbars()

    def manage_toolbars(self):
        """ Manage actions of the custom plugin toolbars.
        project_type in ('ws', 'ud')
        """

        self.create_toolbar('my_toolbar')

        # Manage action group of every toolbar
        parent = self.iface.mainWindow()
        for plugin_toolbar in list(self.plugin_toolbars.values()):
            ag = QActionGroup(parent)
            for index_action in plugin_toolbar.list_actions:
                button_def = self.settings.value(f"buttons_def/{index_action}")
                if button_def:
                    text = f'{index_action}_text'
                    icon_path = self.icon_folder + plugin_toolbar.toolbar_id + os.sep + index_action + ".png"
                    print(buttons, button_def, icon_path, button_def, text,
                          plugin_toolbar.toolbar, ag)
                    button = getattr(buttons,
                                     button_def)(icon_path, button_def, text,
                                                 plugin_toolbar.toolbar, ag)
                    self.buttons[index_action] = button

    def create_toolbar(self, toolbar_id):

        list_actions = self.settings.value(f"toolbars/{toolbar_id}")
        if list_actions is None:
            return

        if type(list_actions) != list:
            list_actions = [list_actions]

        toolbar_name = f'toolbar_{toolbar_id}_name'
        plugin_toolbar = PluginToolbar(toolbar_id, toolbar_name, True)

        # If the toolbar is ToC, add it to the Layes docker toolbar, else create a new toolbar
        if toolbar_id == "toc":
            plugin_toolbar.toolbar = self.iface.mainWindow().findChild(
                QDockWidget, 'Layers').findChildren(QToolBar)[0]
        else:
            plugin_toolbar.toolbar = self.iface.addToolBar(toolbar_name)

        plugin_toolbar.toolbar.setObjectName(toolbar_name)
        plugin_toolbar.list_actions = list_actions
        self.plugin_toolbars[toolbar_id] = plugin_toolbar

    def manage_section_actions_list(self):
        """ Manage section 'actions_list' of config file """

        # Dynamically get parameters defined in section 'actions_list'
        section = 'actions_not_checkable'
        self.settings.beginGroup(section)
        list_keys = self.settings.allKeys()
        self.settings.endGroup()

        for key in list_keys:
            list_values = self.settings.value(f"{section}/{key}")
            if list_values:
                self.dict_actions[key] = list_values
            else:
                print(
                    f"Parameter not set in section '{section}' of config file: '{key}'"
                )

        # Get list of actions not checkable (normally because they open a form)
        aux = []
        for list_actions in self.dict_actions.values():
            for elem in list_actions:
                aux.append(elem)

        self.actions_not_checkable = sorted(aux)

    def manage_section_toolbars(self):
        """ Manage section 'toolbars' of config file """

        # Dynamically get parameters defined in section 'toolbars'
        section = 'toolbars'
        self.settings.beginGroup(section)
        list_keys = self.settings.allKeys()
        self.settings.endGroup()
        for key in list_keys:
            list_values = self.settings.value(f"{section}/{key}")
            if list_values:
                # Check if list_values has only one value
                if type(list_values) is str:
                    list_values = [list_values]
                self.dict_toolbars[key] = list_values
            else:
                print(
                    f"Parameter not set in section '{section}' of config file: '{key}'"
                )

    def get_plugin_metadata(self, parameter, default_value):
        """ Get @parameter from metadata.txt file """

        # Check if metadata file exists
        metadata_file = os.path.join(self.plugin_dir, 'metadata.txt')
        if not os.path.exists(metadata_file):
            message = f"Metadata file not found: {metadata_file}"
            print(message)
            return default_value

        value = None
        try:
            metadata = configparser.ConfigParser()
            metadata.read(metadata_file)
            value = metadata.get('general', parameter)
        except configparser.NoOptionError:
            message = "Parameter not found: {parameter}"
            print(message)
            value = default_value
        finally:
            return value
def get_databases():
    d = {}
    qs = QSettings()

    # spatialite
    qs.beginGroup("SpatiaLite/connections")

    for db_entry in qs.allKeys():
        db_name, _ = os.path.split(db_entry)

        settings = {
            "key": os.path.basename(db_entry),
            "db_name": db_name,
            "combo_key":
            "spatialite: {0}".format(os.path.splitext(db_name)[0]),
            "db_type": "spatialite",
            "db_settings": {
                "db_path": qs.value(db_entry)
            },
        }

        d[settings["combo_key"]] = settings
    qs.endGroup()

    qs.beginGroup("PostgreSQL/connections")
    for db_entry in qs.allKeys():
        prefix, attribute = os.path.split(db_entry)
        db_name = qs.value(prefix + "/database")
        settings = {
            "key": db_entry,
            "db_name": db_name,
            "combo_key": "postgres: {0}".format(db_name),
            "db_type": "postgres",
            "db_settings": {
                "host": qs.value(prefix + "/host"),
                "port": qs.value(prefix + "/port"),
                "database": qs.value(prefix + "/database"),
                "username": qs.value(prefix + "/username"),
                "password": qs.value(prefix + "/password"),
            },
        }

        if qs.value(prefix + "/saveUsername") == u"true":
            settings["saveUsername"] = True
            settings["db_settings"]["username"] = qs.value(prefix +
                                                           "/username")
        else:
            settings["saveUsername"] = False

        if qs.value(prefix + "/savePassword") == u"true":
            settings["savePassword"] = True
            settings["db_settings"]["password"] = qs.value(prefix +
                                                           "/password")
        else:
            settings["savePassword"] = False

        d[settings["combo_key"]] = settings
    qs.endGroup()
    available_dbs = collections.OrderedDict(sorted(d.items()))

    return available_dbs
Пример #21
0
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

# PyQT
from qgis.PyQt.QtCore import QSettings

# QGIS Qt Application settings
qsettings = QSettings()
# list subgroups
print(qsettings.childGroups())

# get Isogeo settings
qsettings.beginGroup("isogeo")
print(qsettings.childGroups())
print(qsettings.allKeys())

# exit Isogeo settings
qsettings.endGroup()
Пример #22
0
# -*- coding: utf-8 -*-
#! python3  # noqa: E265

# PyQT
from qgis.PyQt.QtCore import QSettings

# QGIS Qt Application settings
qsettings = QSettings()
# list subgroups
print(qsettings.childGroups())

# get Isogeo settings
qsettings.beginGroup("isogeo")
print(qsettings.childGroups())
print(qsettings.allKeys())

# exit Isogeo settings
qsettings.endGroup()
Пример #23
0
class TestQgsSettings(unittest.TestCase):

    cnt = 0

    def setUp(self):
        self.cnt += 1
        h, path = tempfile.mkstemp('.ini')
        assert QgsSettings.setGlobalSettingsPath(path)
        self.settings = QgsSettings('testqgissettings',
                                    'testqgissettings%s' % self.cnt)
        self.globalsettings = QSettings(self.settings.globalSettingsPath(),
                                        QSettings.IniFormat)

    def tearDown(self):
        settings_file = self.settings.fileName()
        settings_default_file = self.settings.globalSettingsPath()
        del (self.settings)
        try:
            os.unlink(settings_file)
        except:
            pass
        try:
            os.unlink(settings_default_file)
        except:
            pass

    def addToDefaults(self, key, value):
        self.globalsettings.setValue(key, value)
        self.globalsettings.sync()

    def addArrayToDefaults(self, prefix, key, values):
        defaults = QSettings(self.settings.globalSettingsPath(),
                             QSettings.IniFormat)  # NOQA
        self.globalsettings.beginWriteArray(prefix)
        i = 0
        for v in values:
            self.globalsettings.setArrayIndex(i)
            self.globalsettings.setValue(key, v)
            i += 1
        self.globalsettings.endArray()
        self.globalsettings.sync()

    def addGroupToDefaults(self, prefix, kvp):
        defaults = QSettings(self.settings.globalSettingsPath(),
                             QSettings.IniFormat)  # NOQA
        self.globalsettings.beginGroup(prefix)
        for k, v in kvp.items():
            self.globalsettings.setValue(k, v)
        self.globalsettings.endGroup()
        self.globalsettings.sync()

    def test_basic_functionality(self):
        self.assertEqual(
            self.settings.value('testqgissettings/doesnotexists', 'notexist'),
            'notexist')
        self.settings.setValue('testqgissettings/name', 'qgisrocks')
        self.settings.sync()
        self.assertEqual(self.settings.value('testqgissettings/name'),
                         'qgisrocks')

    def test_defaults(self):
        self.assertIsNone(self.settings.value('testqgissettings/name'))
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.assertEqual(self.settings.value('testqgissettings/name'),
                         'qgisrocks')

    def test_allkeys(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')
        self.settings.setValue('nepoti/eman', 'osaple')

        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertIn('testqgissettings/name', self.settings.allKeys())
        self.assertIn('nepoti/eman', self.settings.allKeys())
        self.assertEqual('qgisrocks',
                         self.settings.value('testqgissettings/name'))
        self.assertEqual('qgisrocks2',
                         self.settings.value('testqgissettings/name2'))
        self.assertEqual('qgisrocks',
                         self.globalsettings.value('testqgissettings/name'))
        self.assertEqual('osaple', self.settings.value('nepoti/eman'))
        self.assertEqual(3, len(self.settings.allKeys()))
        self.assertEqual(2, len(self.globalsettings.allKeys()))

    def test_precedence_simple(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1')

        self.assertEqual(self.settings.value('testqgissettings/names/name1'),
                         'qgisrocks-1')

    def test_precedence_group(self):
        """Test if user can override a group value"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addGroupToDefaults(
            'connections-xyz', {
                'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
                'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
            })
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override edit
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue(
            'OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: the global value will be resumed!!!
        self.settings.beginGroup('connections-xyz')
        self.settings.remove('OSM')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a blank!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', '')
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'), '')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

        # Override remove: store a None: will resume the global setting!
        self.settings.beginGroup('connections-xyz')
        self.settings.setValue('OSM', None)
        self.settings.endGroup()

        # Check it again!
        self.settings.beginGroup('connections-xyz')
        self.assertEqual(self.settings.value('OSM'),
                         'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.assertEqual(self.settings.value('OSM-b'),
                         'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png')
        self.settings.endGroup()

    def test_uft8(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'),
                         'qgisrocks↓1')

        self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'),
                         'qgisrocks↓2')
        self.settings.setValue('testqgissettings/names/namèé↓1',
                               'qgisrocks↓-1')
        self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'),
                         'qgisrocks↓-1')

    def test_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1')
        self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2')
        self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3')
        self.addToDefaults('testqgissettings/name', 'qgisrocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['names'], self.settings.childGroups())

        self.settings.setValue('surnames/name1', 'qgisrocks-1')
        self.assertEqual(['surnames', 'names'], self.settings.childGroups())

        self.settings.setValue('names/name1', 'qgisrocks-1')
        self.assertEqual('qgisrocks-1', self.settings.value('names/name1'))
        self.settings.endGroup()
        self.settings.beginGroup('testqgissettings/names')
        self.settings.setValue('name4', 'qgisrocks-4')
        keys = sorted(self.settings.childKeys())
        self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4'])
        self.settings.endGroup()
        self.assertEqual('qgisrocks-1',
                         self.settings.value('testqgissettings/names/name1'))
        self.assertEqual('qgisrocks-4',
                         self.settings.value('testqgissettings/names/name4'))

    def test_global_groups(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.assertEqual(self.globalsettings.allKeys(), [])

        self.addToDefaults('testqgissettings/foo/first', 'qgis')
        self.addToDefaults('testqgissettings/foo/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['foo'], self.settings.childGroups())
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()

        self.settings.setValue('testqgissettings/bar/first', 'qgis')
        self.settings.setValue('testqgissettings/bar/last', 'rocks')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(sorted(['bar', 'foo']),
                         sorted(self.settings.childGroups()))
        self.assertEqual(['foo'], self.settings.globalChildGroups())
        self.settings.endGroup()

        self.globalsettings.remove('testqgissettings/foo')

        self.settings.beginGroup('testqgissettings')
        self.assertEqual(['bar'], self.settings.childGroups())
        self.assertEqual([], self.settings.globalChildGroups())
        self.settings.endGroup()

    def test_group_section(self):
        # Test group by using Section
        self.settings.beginGroup('firstgroup', section=QgsSettings.Core)
        self.assertEqual([], self.settings.childGroups())
        self.settings.setValue('key', 'value')
        self.settings.setValue('key2/subkey1', 'subvalue1')
        self.settings.setValue('key2/subkey2', 'subvalue2')
        self.settings.setValue('key3', 'value3')

        self.assertEqual(['key', 'key2/subkey1', 'key2/subkey2', 'key3'],
                         self.settings.allKeys())
        self.assertEqual(['key', 'key3'], self.settings.childKeys())
        self.assertEqual(['key2'], self.settings.childGroups())
        self.settings.endGroup()
        # Set value by writing the group manually
        self.settings.setValue('firstgroup/key4',
                               'value4',
                               section=QgsSettings.Core)
        # Checking the value that have been set
        self.assertEqual(
            self.settings.value('firstgroup/key', section=QgsSettings.Core),
            'value')
        self.assertEqual(
            self.settings.value('firstgroup/key2/subkey1',
                                section=QgsSettings.Core), 'subvalue1')
        self.assertEqual(
            self.settings.value('firstgroup/key2/subkey2',
                                section=QgsSettings.Core), 'subvalue2')
        self.assertEqual(
            self.settings.value('firstgroup/key3', section=QgsSettings.Core),
            'value3')
        self.assertEqual(
            self.settings.value('firstgroup/key4', section=QgsSettings.Core),
            'value4')
        # Clean up firstgroup
        self.settings.remove('firstgroup', section=QgsSettings.Core)

    def test_array(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key',
                                ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])
        self.assertEqual(self.globalsettings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])

        self.assertEqual(
            3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(3):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])

    def test_array_overrides(self):
        """Test if an array completely shadows the global one"""
        self.assertEqual(self.settings.allKeys(), [])
        self.addArrayToDefaults('testqgissettings', 'key',
                                ['qgisrocks1', 'qgisrocks2', 'qgisrocks3'])
        self.assertEqual(self.settings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])
        self.assertEqual(self.globalsettings.allKeys(), [
            'testqgissettings/1/key', 'testqgissettings/2/key',
            'testqgissettings/3/key', 'testqgissettings/size'
        ])

        self.assertEqual(
            3, self.globalsettings.beginReadArray('testqgissettings'))
        self.globalsettings.endArray()
        self.assertEqual(3, self.settings.beginReadArray('testqgissettings'))

        # Now override!
        self.settings.beginWriteArray('testqgissettings')
        self.settings.setArrayIndex(0)
        self.settings.setValue('key', 'myqgisrocksmore1')
        self.settings.setArrayIndex(1)
        self.settings.setValue('key', 'myqgisrocksmore2')
        self.settings.endArray()

        # Check it!
        self.assertEqual(2, self.settings.beginReadArray('testqgissettings'))

        values = []
        for i in range(2):
            self.settings.setArrayIndex(i)
            values.append(self.settings.value("key"))

        self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2'])

    def test_section_getters_setters(self):
        self.assertEqual(self.settings.allKeys(), [])

        self.settings.setValue('key1', 'core1', section=QgsSettings.Core)
        self.settings.setValue('key2', 'core2', section=QgsSettings.Core)

        self.settings.setValue('key1', 'server1', section=QgsSettings.Server)
        self.settings.setValue('key2', 'server2', section=QgsSettings.Server)

        self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui)
        self.settings.setValue('key2', 'gui2', QgsSettings.Gui)

        self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins)
        self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins)

        self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc)
        self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        self.settings.setValue('key1', 'app1', section=QgsSettings.App)
        self.settings.setValue('key2', 'app2', section=QgsSettings.App)

        self.settings.setValue('key1',
                               'provider1',
                               section=QgsSettings.Providers)
        self.settings.setValue('key2',
                               'provider2',
                               section=QgsSettings.Providers)

        self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth)
        self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth)

        # Test that the values are namespaced
        self.assertEqual(self.settings.value('core/key1'), 'core1')
        self.assertEqual(self.settings.value('core/key2'), 'core2')

        self.assertEqual(self.settings.value('server/key1'), 'server1')
        self.assertEqual(self.settings.value('server/key2'), 'server2')

        self.assertEqual(self.settings.value('gui/key1'), 'gui1')
        self.assertEqual(self.settings.value('gui/key2'), 'gui2')

        self.assertEqual(self.settings.value('plugins/key1'), 'plugins1')
        self.assertEqual(self.settings.value('plugins/key2'), 'plugins2')

        self.assertEqual(self.settings.value('misc/key1'), 'misc1')
        self.assertEqual(self.settings.value('misc/key2'), 'misc2')

        # Test getters
        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Core),
            'core1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Core),
            'core2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Server),
            'server1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Server),
            'server2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Plugins),
            'plugins1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Plugins),
            'plugins2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Misc),
            'misc1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Misc),
            'misc2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Auth),
            'auth1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Auth),
            'auth2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.App), 'app1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.App), 'app2')

        self.assertEqual(
            self.settings.value('key1', None, section=QgsSettings.Providers),
            'provider1')
        self.assertEqual(
            self.settings.value('key2', None, section=QgsSettings.Providers),
            'provider2')

        # Test default values on Section getter
        self.assertEqual(
            self.settings.value('key_not_exist',
                                'misc_not_exist',
                                section=QgsSettings.Misc), 'misc_not_exist')

    def test_contains(self):
        self.assertEqual(self.settings.allKeys(), [])
        self.addToDefaults('testqgissettings/name', 'qgisrocks1')
        self.addToDefaults('testqgissettings/name2', 'qgisrocks2')

        self.assertTrue(self.settings.contains('testqgissettings/name'))
        self.assertTrue(self.settings.contains('testqgissettings/name2'))

        self.settings.setValue('testqgissettings/name3', 'qgisrocks3')
        self.assertTrue(self.settings.contains('testqgissettings/name3'))

    def test_remove(self):
        self.settings.setValue('testQgisSettings/temp', True)
        self.assertEqual(self.settings.value('testQgisSettings/temp'), True)
        self.settings.remove('testQgisSettings/temp')
        self.assertEqual(self.settings.value('testqQgisSettings/temp'), None)

        # Test remove by using Section
        self.settings.setValue('testQgisSettings/tempSection',
                               True,
                               section=QgsSettings.Core)
        self.assertEqual(
            self.settings.value('testQgisSettings/tempSection',
                                section=QgsSettings.Core), True)
        self.settings.remove('testQgisSettings/temp', section=QgsSettings.Core)
        self.assertEqual(
            self.settings.value('testqQgisSettings/temp',
                                section=QgsSettings.Core), None)

    def test_enumValue(self):
        self.settings.setValue('enum', 'LayerUnits')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels),
                         QgsTolerance.LayerUnits)
        self.settings.setValue('enum', 'dummy_setting')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels),
                         QgsTolerance.Pixels)
        self.assertEqual(
            type(self.settings.enumValue('enum', QgsTolerance.Pixels)),
            QgsTolerance.UnitType)

    def test_setEnumValue(self):
        self.settings.setValue('enum', 'LayerUnits')
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels),
                         QgsTolerance.LayerUnits)
        self.settings.setEnumValue('enum', QgsTolerance.Pixels)
        self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels),
                         QgsTolerance.Pixels)

    def test_flagValue(self):
        pointAndLine = QgsMapLayerProxyModel.Filters(
            QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.LineLayer)
        pointAndPolygon = QgsMapLayerProxyModel.Filters(
            QgsMapLayerProxyModel.PointLayer
            | QgsMapLayerProxyModel.PolygonLayer)

        self.settings.setValue('flag', 'PointLayer|PolygonLayer')
        self.assertEqual(self.settings.flagValue('flag', pointAndLine),
                         pointAndPolygon)
        self.settings.setValue('flag', 'dummy_setting')
        self.assertEqual(self.settings.flagValue('flag', pointAndLine),
                         pointAndLine)
        self.assertEqual(type(self.settings.flagValue('enum', pointAndLine)),
                         QgsMapLayerProxyModel.Filters)
Пример #24
0
# Sample script for QGIS Init Script
# This script will add a demo WMS endpoint


from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsMessageLog, Qgis
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=Qgis.Info)

WMS_URL="http://demo.boundlessgeo.com/geoserver/wms"
WMS_NAME="Boundlessgeo Geoserver Demo"

settings = QSettings()

if "Qgis/WMS/%s/authcfg" % WMS_NAME not in settings.allKeys():
    settings.setValue("qgis/WMS/%s/authcfg" % WMS_NAME, "")
    settings.setValue("qgis/WMS/%s/username" % WMS_NAME, "")
    settings.setValue("qgis/WMS/%s/password" % WMS_NAME, "")
    settings.setValue("qgis/connections-wms/%s/dpiMode" % WMS_NAME, 7)
    settings.setValue("qgis/connections-wms/%s/ignoreAxisOrientation" % WMS_NAME, False)
    settings.setValue("qgis/connections-wms/%s/ignoreGetFeatureInfoURI" % WMS_NAME, False)
    settings.setValue("qgis/connections-wms/%s/ignoreGetMapURI" % WMS_NAME, False)
    settings.setValue("qgis/connections-wms/%s/invertAxisOrientation" % WMS_NAME, False)
    settings.setValue("qgis/connections-wms/%s/referer" % WMS_NAME, "")
    settings.setValue("qgis/connections-wms/%s/smoothPixmapTransform" % WMS_NAME, "")
    settings.setValue("qgis/connections-wms/%s/url" % WMS_NAME, WMS_URL)
    QgsMessageLog.logMessage("WMS %s has been successfully installed" % WMS_NAME, tag="Init script", level=Qgis.Info)
else:
    QgsMessageLog.logMessage("WMS %s was already installed" % WMS_NAME,  tag="Init script", level=Qgis.Info)