Exemple #1
0
 def writeSettings(self):
     if os.name == 'nt':
         settings = QSettings()
     else:
         settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat)
     settings.clear()
     for tunnel in self._tunnels:
         tunnel.writeSettings(settings)
Exemple #2
0
 def writeSettings(self):
     if os.name == 'nt':
         settings = QSettings()
     else:
         settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat)
     settings.clear()
     for tunnel in self._tunnels:
         tunnel.writeSettings(settings)
Exemple #3
0
def to_QSettings(config, clear=True):
	"""Convert ConfigObj to QSettings.
	Note that QSettings are automatically saved so this will overwrite any previous application settings."""
	settings = QSettings()
	if clear:
		settings.clear()

	def walk(section, key):
		"""Copy values from ConfigObj object to QSettings object."""
		if key not in section.defaults: # Don't copy default values
			settings.setValue('/'.join(section_path(section))+'/%s'%key, section[key])
	config.walk(walk)
	return settings
Exemple #4
0
def run(props):
    # Create a new Qt settings object using supplied application
    # and organisation name
    settings = QSettings(props.org, props.app)

    # Have the clear preferences parameter
    if props.clear:
        # Check if we can clear by force
        ok_to_clear = props.force
        # If not ask the user if we can
        if not ok_to_clear:
            ok_to_clear = get_verification(
                "This will clear all Qt preferences for %s (by %s)" %
                (props.app, props.org))

            # If so clear all Qt preferences in the selected application
        # and report back unless quiet is enabled
        if ok_to_clear:
            settings.clear()
            if not props.quiet:
                sys.stdout.write("Qt preferences cleared\n")
        else:
            if not props.quiet:
                sys.stdout.write("Qt preferences not cleared\n")

    # Have the set preference parameter
    if props.set != None:
        # Input data is in the form k=v, split this into a list of k and v
        data = props.set.split("=")

        # Check if we can set by force
        ok_to_set = props["force"]
        # If not ask the user if we can
        if not ok_to_set:
            ok_to_set = get_verification(
                "This will set Qt preference %s to %s for %s (by %s)" %
                (data[0], data[1], props.app, props.org))

            if ok_to_set:
                settings.setValue(data[0], data[1])
            if not props.quiet:
                sys.stdout.write("Set preference %s to %s\n" %
                                 (data[0], data[1]))
        else:
            if not props.quiet:
                sys.stdout.write("Preference not set\n")

    # Have the list all preferences parameter
    if props.list and not props.quiet:
        sys.stdout.write("All Keys:\n")
        print_all_keys(settings)
def run(props):
    # Create a new Qt settings object using supplied application
    # and organisation name
    settings = QSettings(props.org, props.app)

    # Have the clear preferences parameter
    if props.clear:
        # Check if we can clear by force
        ok_to_clear = props.force
        # If not ask the user if we can
        if not ok_to_clear:
            ok_to_clear = get_verification(
                    "This will clear all Qt preferences for %s (by %s)" % (props.app, props.org))

            # If so clear all Qt preferences in the selected application
        # and report back unless quiet is enabled
        if ok_to_clear:
            settings.clear()
            if not props.quiet:
                sys.stdout.write("Qt preferences cleared\n")
        else:
            if not props.quiet:
                sys.stdout.write("Qt preferences not cleared\n")

    # Have the set preference parameter
    if props.set != None:
        # Input data is in the form k=v, split this into a list of k and v
        data = props.set.split("=")

        # Check if we can set by force
        ok_to_set = props["force"]
        # If not ask the user if we can
        if not ok_to_set:
            ok_to_set = get_verification(
                    "This will set Qt preference %s to %s for %s (by %s)" %
                    (data[0], data[1], props.app, props.org))

            if ok_to_set:
                settings.setValue(data[0], data[1])
            if not props.quiet:
                sys.stdout.write("Set preference %s to %s\n" % (data[0], data[1]))
        else:
            if not props.quiet:
                sys.stdout.write("Preference not set\n")

    # Have the list all preferences parameter
    if props.list and not props.quiet:
        sys.stdout.write("All Keys:\n")
        print_all_keys(settings)
def to_QSettings(config, clear=True):
    """Convert ConfigObj to QSettings.
	Note that QSettings are automatically saved so this will overwrite any previous application settings."""
    settings = QSettings()
    if clear:
        settings.clear()

    def walk(section, key):
        """Copy values from ConfigObj object to QSettings object."""
        if key not in section.defaults:  # Don't copy default values
            settings.setValue('/'.join(section_path(section)) + '/%s' % key,
                              section[key])

    config.walk(walk)
    return settings
Exemple #7
0
    def test_get_displacement_rate_and_affected_with_qsetting(self):
        """Test for get_displacement_rate and is_affected with QSettings."""
        # Create custom qsettings
        qsettings = QSettings('InaSAFETest')
        qsettings.clear()
        # Save the default profile to qsettings
        default_profile = generate_default_profile()
        set_setting('population_preference', default_profile, qsettings)

        # Check the default one first
        default_profile = generate_default_profile()
        class_key = flood_hazard_classes['classes'][0]['key']
        value = is_affected(hazard_flood['key'], flood_hazard_classes['key'],
                            class_key, qsettings)
        expected_value = default_profile[hazard_flood['key']][
            flood_hazard_classes['key']][class_key]['affected']
        self.assertEqual(value, expected_value)

        value = get_displacement_rate(hazard_flood['key'],
                                      flood_hazard_classes['key'], class_key,
                                      qsettings)
        expected_value = default_profile[hazard_flood['key']][
            flood_hazard_classes['key']][class_key]['displacement_rate']
        self.assertEqual(value, expected_value)

        # Change displacement rate
        new_displacement_rate = 1
        default_profile[hazard_flood['key']][
            flood_hazard_classes['key']][class_key]['displacement_rate'] = 1
        set_setting('population_preference', default_profile, qsettings)
        value = get_displacement_rate(hazard_flood['key'],
                                      flood_hazard_classes['key'], class_key,
                                      qsettings)
        self.assertEqual(value, new_displacement_rate)

        # Change affected value
        new_affected = False
        default_profile[hazard_flood['key']][
            flood_hazard_classes['key']][class_key]['affected'] = new_affected
        set_setting('population_preference', default_profile, qsettings)
        value = is_affected(hazard_flood['key'], flood_hazard_classes['key'],
                            class_key, qsettings)
        self.assertEqual(value, new_affected)
        value = get_displacement_rate(hazard_flood['key'],
                                      flood_hazard_classes['key'], class_key,
                                      qsettings)
        # Should be 0 since it's not affected
        self.assertEqual(value, 0)
Exemple #8
0
def moveSettingsToNewRoot():
    """Move all settings to one application file."""
    movelist = [[info.name, info.url, False], "metainfo", "snippets", "sessions", "sessiondata"]
    for moveitem in movelist:
        if isinstance(moveitem, basestring):
            moveitem = [moveitem, info.name, True]
        o = QSettings(moveitem[1], moveitem[0])
        o.setFallbacksEnabled(False)
        keys = o.allKeys()
        if len(keys) > 0:
            s = QSettings()
            if moveitem[2]:
                s.beginGroup(moveitem[0])
            for k in keys:
                s.setValue(k, o.value(k))
            o.clear()
Exemple #9
0
def moveSettingsToNewRoot():
    """Move all settings to one application file."""
    movelist = [[info.name, info.url, False], "metainfo", "snippets",
                "sessions", "sessiondata"]
    for moveitem in movelist:
        if isinstance(moveitem, basestring):
            moveitem = [moveitem, info.name, True]
        o = QSettings(moveitem[1], moveitem[0])
        o.setFallbacksEnabled(False)
        keys = o.allKeys()
        if len(keys) > 0:
            s = QSettings()
            if moveitem[2]:
                s.beginGroup(moveitem[0])
            for k in keys:
                s.setValue(k, o.value(k))
            o.clear()
class Storage:

	def __init__(self):
		self.settings = QSettings('Christian Dancke Tuen', 'Desktop Harmony')

	def write_settings(self, username, password, ip, port):
		self.settings.setValue('username', str(username))
		self.settings.setValue('password', str(password))
		self.settings.setValue('ip', str(ip))
		self.settings.setValue('port', str(port))
		del self.settings

	def remove_settings(self):
		self.settings.clear()

	def read_settings(self):
		username = self.settings.value('username')
		password = self.settings.value('password')
		ip = self.settings.value('ip')
		port = self.settings.value('port')
		return username, password, ip, port

	def read_username(self):
		if self.settings.contains('username'):
			return str(self.settings.value('username', type=str))
		else:
			return ""

	def read_password(self):
		if self.settings.contains('password'):
			return str(self.settings.value('password', type=str))
		else:
			return ""

	def read_ip(self):
		if self.settings.contains('ip'):
			return str(self.settings.value('ip', type=str))
		else:
			return ""

	def read_port(self):
		if self.settings.contains('port'):
			return str(self.settings.value('port', type=str))
		else:
			return "5222"
Exemple #11
0
def clear_settings():
    settings = QSettings(QSettings.SystemScope, 'TRADR', 'UGV')
    settings.clear()

    settings = QSettings(QSettings.SystemScope, 'TRADR', 'UAV')
    settings.clear()

    settings = QSettings(QSettings.SystemScope, 'TRADR', 'InField')
    settings.clear()

    settings = QSettings(QSettings.SystemScope, 'TRADR', 'CommandTable')
    settings.clear()
Exemple #12
0
class TestCloudPreferencesPage(TestCase):
    def setUp(self):
        self.app = QApplication(sys.argv)
        self.app.setOrganizationName("GNS3")
        self.app.setOrganizationDomain("gns3.net")
        self.app.setApplicationName("Testsuite")
        self.mw = MainWindow()
        self.settings = QSettings()

    def tearDown(self):
        del self.app
        self.settings.clear()

    def test_settings_groups(self):
        fake_settings = {'foo': 'bar'}

        self.mw.setCloudSettings(fake_settings, persist=True)
        self.assertIsNone(self.settings.value('foo'))
        self.settings.beginGroup(CLOUD_SETTINGS_GROUP)
        self.assertEqual(self.settings.value('foo'), 'bar')
        self.settings.endGroup()

        self.mw.setSettings(fake_settings)
        self.assertIsNone(self.settings.value('foo'))
        self.settings.beginGroup(self.mw.__class__.__name__)
        self.assertEqual(self.settings.value('foo'), 'bar')
        self.settings.endGroup()

    def test_cloud_settings_store(self):
        fake_settings = {'foo': 'bar'}

        self.mw.setCloudSettings(fake_settings, persist=True)
        self.settings.beginGroup(CLOUD_SETTINGS_GROUP)
        self.assertEqual(self.settings.value('foo'), 'bar')
        self.settings.endGroup()

        self.settings.clear()

        self.mw.setCloudSettings(fake_settings, persist=False)
        self.settings.beginGroup(CLOUD_SETTINGS_GROUP)
        self.assertIsNone(self.settings.value('foo'))
        self.settings.endGroup()
class TestNeedsProfile(NeedsProfile):
    """Since we don't want to change the actual minimum needs settings in
    QSettings, we are using a mock profile.

    :param test_profile: The mock replacement of Minimum Needs
    """
    # noinspection PyMissingConstructor
    def __init__(self, test_profile='Test Minimum Needs Settings'):
        self.settings = QSettings(test_profile)
        self.settings.clear()
        self.settings = QSettings(test_profile)
        self.local = 'en'
        minimum_needs = self._defaults()
        minimum_needs['provenance'] = 'Test'
        minimum_needs['profile'] = 'Test'
        self._root_directory = None
        self.minimum_needs = minimum_needs

    def __del__(self):
        self.settings.clear()
Exemple #14
0
class TestNeedsProfile(NeedsProfile):
    """Since we don't want to change the actual minimum needs settings in
    QSettings, we are using a mock profile.

    :param test_profile: The mock replacement of Minimum Needs
    """
    # noinspection PyMissingConstructor
    def __init__(self, test_profile='Test Minimum Needs Settings'):
        self.settings = QSettings(test_profile)
        self.settings.clear()
        self.settings = QSettings(test_profile)
        self.local = 'en'
        minimum_needs = self._defaults()
        minimum_needs['provenance'] = 'Test'
        minimum_needs['profile'] = 'Test'
        self._root_directory = None
        self.minimum_needs = minimum_needs

    def __del__(self):
        self.settings.clear()
Exemple #15
0
class TestSettings(unittest.TestCase):
    """Test Settings"""

    def setUp(self):
        """Fixture run before all tests"""
        self.qsetting = QSettings('InaSAFETest')
        self.qsetting.clear()

    def tearDown(self):
        """Fixture run after each test"""
        # Make sure it's empty
        self.qsetting.clear()

    def test_get_value(self):
        """Test we can get a value from a QSettings."""
        # The expected type does not match the default value.
        try:
            self.assertEqual(
                'default_value',
                setting('test', 'default_value', bool, self.qsetting))
        except Exception:
            self.assertTrue(True)
        else:
            self.assertTrue(False)

        self.assertEqual(
            'default_value',
            setting('test', 'default_value', str, self.qsetting))

        self.assertIsNone(
            setting('test', None, str, self.qsetting))

        # Without default value.
        self.assertIsNone(setting('test', qsettings=self.qsetting))

    def test_inasafe_default_value_qsetting(self):
        """Test for set and get inasafe_default_value_qsetting."""
        # Make sure it's empty
        self.qsetting.clear()

        female_ratio_key = 'female_ratio'
        real_value = get_inasafe_default_value_qsetting(
            self.qsetting, RECENT, female_ratio_key)
        self.assertEqual(zero_default_value, real_value)

        female_ratio_value = 0.8
        set_inasafe_default_value_qsetting(
            self.qsetting, RECENT, female_ratio_key, female_ratio_value)
        real_value = get_inasafe_default_value_qsetting(
            self.qsetting, RECENT, female_ratio_key)
        self.assertEqual(female_ratio_value, real_value)

    def test_read_boolean_setting(self):
        """Test read developer mode setting."""
        set_setting(
            'developer_mode',
            inasafe_default_settings['developer_mode'])

        actual_setting = setting(
            'developer_mode', inasafe_default_settings['developer_mode'])
        self.assertFalse(actual_setting)

        set_setting(
            'developer_mode',
            not(inasafe_default_settings['developer_mode']))

        actual_setting = setting(
            'developer_mode', inasafe_default_settings['developer_mode'])
        self.assertTrue(actual_setting)
class TestOptionsDialog(unittest.TestCase):

    """Test Options Dialog"""

    def setUp(self):
        """Fixture run before all tests"""
        self.qsetting = QSettings('InaSAFETest')
        self.qsetting.clear()

    def tearDown(self):
        """Fixture run after each test."""
        # Make sure it's empty
        self.qsetting.clear()

    def test_setup_dialog(self):
        """Test Setup Options Dialog."""
        dialog = OptionsDialog(
            parent=PARENT, iface=IFACE, qsetting='InaSAFETest')
        self.assertIsNotNone(dialog)

        # Check default values
        self.assertEqual(
            dialog.cbxVisibleLayersOnly.isChecked(),
            inasafe_default_settings['visibleLayersOnlyFlag'])
        self.assertEqual(
            dialog.cbxSetLayerNameFromTitle.isChecked(),
            inasafe_default_settings['set_layer_from_title_flag'])
        self.assertEqual(
            dialog.cbxZoomToImpact.isChecked(),
            inasafe_default_settings['setZoomToImpactFlag'])
        self.assertEqual(
            dialog.cbxHideExposure.isChecked(),
            inasafe_default_settings['setHideExposureFlag'])
        self.assertEqual(
            dialog.cbxUseSelectedFeaturesOnly.isChecked(),
            inasafe_default_settings['useSelectedFeaturesOnly'])
        self.assertEqual(
            dialog.leKeywordCachePath.text(),
            inasafe_default_settings['keywordCachePath'])
        self.assertEqual(
            dialog.template_warning_checkbox.isChecked(),
            inasafe_default_settings['template_warning_verbose'])
        self.assertEqual(
            dialog.organisation_on_dock_checkbox.isChecked(),
            inasafe_default_settings['showOrganisationLogoInDockFlag'])
        self.assertEqual(
            dialog.cbxDevMode.isChecked(),
            inasafe_default_settings['developer_mode'])

        self.assertEqual(
            dialog.leNorthArrowPath.text(), default_north_arrow_path())
        self.assertEqual(
            dialog.leOrganisationLogoPath.text(), supporters_logo_path())
        self.assertEqual(dialog.leReportTemplatePath.text(), '')
        self.assertEqual(dialog.txtDisclaimer.toPlainText(), disclaimer())
        self.assertEqual(
            dialog.leUserDirectoryPath.text(), temp_dir('impacts'))

        self.assertEqual(
            dialog.iso19115_organization_le.text(),
            inasafe_default_settings['ISO19115_ORGANIZATION'])
        self.assertEqual(
            dialog.iso19115_url_le.text(),
            inasafe_default_settings['ISO19115_URL'])
        self.assertEqual(
            dialog.iso19115_email_le.text(),
            inasafe_default_settings['ISO19115_EMAIL'])
        self.assertEqual(
            dialog.iso19115_license_le.text(),
            inasafe_default_settings['ISO19115_LICENSE'])

    def test_update_settings(self):
        """Test update InaSAFE Option works."""
        # Create new option dialog
        dialog = OptionsDialog(
            parent=PARENT, iface=IFACE, qsetting='InaSAFETest')

        # Update some state
        new_state = not inasafe_default_settings['visibleLayersOnlyFlag']
        dialog.cbxVisibleLayersOnly.setChecked(new_state)

        new_organization = 'Super Organization'
        dialog.iso19115_organization_le.setText(new_organization)

        # Accept the dialog
        dialog.accept()

        # Check the value in QSettings
        # Next two lines a hack because windows qsettings returns a string
        # rather than a bool...TS
        value = self.qsetting.value('inasafe/visibleLayersOnlyFlag')
        if value == u'false':
            value = False
        if value == u'true':
            value = True
        self.assertEquals(
            new_state, value)
        self.assertEqual(
            new_organization,
            self.qsetting.value('inasafe/ISO19115_ORGANIZATION'))

        # Open the options dialog
        dialog = OptionsDialog(
            iface=IFACE, parent=PARENT, qsetting='InaSAFETest')

        # Check the state of the dialog after save the settings
        self.assertEqual(new_state, dialog.cbxVisibleLayersOnly.isChecked())
        self.assertEqual(
            new_organization, dialog.iso19115_organization_le.text())
class TestOptionsDialog(unittest.TestCase):
    """Test Options Dialog."""
    def setUp(self):
        """Fixture run before all tests."""
        self.qsetting = QSettings('InaSAFETest')
        self.qsetting.clear()

    def tearDown(self):
        """Fixture run after each test."""
        # Make sure it's empty
        self.qsetting.clear()

    def test_setup_dialog(self):
        """Test Setup Options Dialog."""
        dialog = OptionsDialog(parent=PARENT,
                               iface=IFACE,
                               qsetting='InaSAFETest')
        self.assertIsNotNone(dialog)

        # Check default values
        self.assertEqual(dialog.cbxVisibleLayersOnly.isChecked(),
                         inasafe_default_settings['visibleLayersOnlyFlag'])
        self.assertEqual(dialog.cbxSetLayerNameFromTitle.isChecked(),
                         inasafe_default_settings['set_layer_from_title_flag'])
        self.assertEqual(dialog.cbxZoomToImpact.isChecked(),
                         inasafe_default_settings['setZoomToImpactFlag'])
        self.assertEqual(dialog.cbxHideExposure.isChecked(),
                         inasafe_default_settings['setHideExposureFlag'])
        self.assertEqual(dialog.cbxUseSelectedFeaturesOnly.isChecked(),
                         inasafe_default_settings['useSelectedFeaturesOnly'])
        self.assertEqual(dialog.leKeywordCachePath.text(),
                         inasafe_default_settings['keywordCachePath'])
        self.assertEqual(dialog.template_warning_checkbox.isChecked(),
                         inasafe_default_settings['template_warning_verbose'])
        self.assertEqual(
            dialog.organisation_on_dock_checkbox.isChecked(),
            inasafe_default_settings['showOrganisationLogoInDockFlag'])
        self.assertEqual(dialog.cbxDevMode.isChecked(),
                         inasafe_default_settings['developer_mode'])

        self.assertEqual(dialog.leNorthArrowPath.text(),
                         default_north_arrow_path())
        self.assertEqual(dialog.organisation_logo_path_line_edit.text(),
                         supporters_logo_path())
        self.assertEqual(dialog.leReportTemplatePath.text(), '')
        self.assertEqual(dialog.txtDisclaimer.toPlainText(), disclaimer())
        self.assertEqual(dialog.leUserDirectoryPath.text(),
                         temp_dir('impacts'))

        self.assertEqual(dialog.organisation_line_edit.text(),
                         inasafe_default_settings['ISO19115_ORGANIZATION'])
        self.assertEqual(dialog.website_line_edit.text(),
                         inasafe_default_settings['ISO19115_URL'])
        self.assertEqual(dialog.email_line_edit.text(),
                         inasafe_default_settings['ISO19115_EMAIL'])
        self.assertEqual(dialog.license_line_edit.text(),
                         inasafe_default_settings['ISO19115_LICENSE'])

    def test_update_settings(self):
        """Test update InaSAFE Option works."""
        # Create new option dialog
        dialog = OptionsDialog(parent=PARENT,
                               iface=IFACE,
                               qsetting='InaSAFETest')

        # Update some state
        new_state = not inasafe_default_settings['visibleLayersOnlyFlag']
        dialog.cbxVisibleLayersOnly.setChecked(new_state)

        new_organization = 'Super Organization'
        dialog.organisation_line_edit.setText(new_organization)

        # Accept the dialog
        dialog.accept()

        # Check the value in QSettings
        # Next two lines a hack because windows qsettings returns a string
        # rather than a bool...TS
        value = self.qsetting.value('inasafe/visibleLayersOnlyFlag')
        if value == u'false':
            value = False
        if value == u'true':
            value = True
        self.assertEquals(new_state, value)
        self.assertEqual(new_organization,
                         self.qsetting.value('inasafe/ISO19115_ORGANIZATION'))

        # Open the options dialog
        dialog = OptionsDialog(iface=IFACE,
                               parent=PARENT,
                               qsetting='InaSAFETest')

        # Check the state of the dialog after save the settings
        self.assertEqual(new_state, dialog.cbxVisibleLayersOnly.isChecked())
        self.assertEqual(new_organization,
                         dialog.organisation_line_edit.text())

    def test_mode(self):
        """Test for checking that the state is correct for the mode.

        If your test is failed, perhaps one the following is the cause:
        1. You add / remove tab in the options.
        2. You rename the tab's name.
        3. The function show_welcome_dialog or show_option_dialog is changed
        """
        # Welcome mode
        dialog = OptionsDialog(parent=PARENT, iface=IFACE)
        dialog.show_welcome_dialog()

        expected_tabs = [
            dialog.welcome_tab, dialog.organisation_profile_tab,
            dialog.preference_tab
        ]

        message = 'Tab count should be %d in welcome dialog.' % len(
            expected_tabs)
        self.assertEqual(dialog.tabWidget.count(), len(expected_tabs), message)

        message = 'Current tab index should be 0.'
        self.assertEqual(dialog.tabWidget.currentIndex(), 0, message)

        for index, expected_tab in enumerate(expected_tabs):
            dialog.tabWidget.setCurrentIndex(index)
            message = 'Current tab should be %s.' % expected_tab.objectName()
            current_tab = dialog.tabWidget.currentWidget()
            self.assertEqual(current_tab, expected_tab, message)

        # Usual option mode
        dialog = OptionsDialog(parent=PARENT, iface=IFACE)
        dialog.show_option_dialog()

        expected_tabs = [
            dialog.organisation_profile_tab, dialog.preference_tab,
            dialog.gis_environment_tab, dialog.earthquake_tab,
            dialog.template_option_tab, dialog.demographic_defaults_tab,
            dialog.advanced_tab
        ]

        message = 'Tab count should be %d in welcome dialog.' % len(
            expected_tabs)
        self.assertEqual(dialog.tabWidget.count(), len(expected_tabs), message)

        message = 'Current tab index should be 0.'
        self.assertEqual(dialog.tabWidget.currentIndex(), 0, message)

        for index, expected_tab in enumerate(expected_tabs):
            dialog.tabWidget.setCurrentIndex(index)
            message = 'Current tab should be %s.' % expected_tab.objectName()
            current_tab = dialog.tabWidget.currentWidget()
            self.assertEqual(current_tab, expected_tab, message)
Exemple #18
0
class TestSettings(unittest.TestCase):
    """Test Settings."""

    def setUp(self):
        """Fixture run before all tests."""
        self.qsettings = QSettings('InaSAFETest')
        self.qsettings.clear()

    def tearDown(self):
        """Fixture run after each test."""
        # Make sure it's empty
        self.qsettings.clear()

    def test_read_write_setting(self):
        """Test read and write setting."""
        # General Setting
        set_general_setting('key', 'value', self.qsettings)
        self.assertEqual(
            'value', general_setting('key', qsettings=self.qsettings))
        delete_general_setting('key', qsettings=self.qsettings)
        self.assertEqual('default', general_setting(
            'key', default='default', qsettings=self.qsettings))

        set_general_setting('key', 'True', self.qsettings)
        self.assertEqual(
            'True',
            general_setting(
                'key', qsettings=self.qsettings, expected_type=str))
        self.assertEqual(
            True,
            general_setting(
                'key', qsettings=self.qsettings, expected_type=bool))
        delete_general_setting('key', qsettings=self.qsettings)
        self.assertEqual('default', general_setting(
            'key', default='default', qsettings=self.qsettings))

        set_general_setting('key', 'false', self.qsettings)
        self.assertEqual(
            'false',
            general_setting(
                'key', qsettings=self.qsettings, expected_type=str))
        self.assertEqual(
            False,
            general_setting(
                'key', qsettings=self.qsettings, expected_type=bool))
        delete_general_setting('key', qsettings=self.qsettings)
        self.assertEqual('default', general_setting(
            'key', default='default', qsettings=self.qsettings))

        # Under InaSAFE scope
        set_setting('key', 'value', self.qsettings)
        self.assertEqual('value', setting('key', qsettings=self.qsettings))
        delete_setting('key', qsettings=self.qsettings)
        self.assertEqual('default', setting(
            'key', default='default', qsettings=self.qsettings))

        # Using InaSAFE setting default
        key = 'developer_mode'
        actual_value = inasafe_default_settings.get(key)
        self.assertEqual(actual_value, setting(key, qsettings=self.qsettings))

    def test_read_write_dictionary(self):
        """Test for reading and writing dictionary in QSettings."""
        dictionary = {
            'a': 'a',
            'b': 1,
            'c': {
                'd': True,
                'e': {
                    'f': 1.0,
                    'g': 2
                }
            }
        }
        set_setting('key', dictionary, self.qsettings)
        value = setting('key', qsettings=self.qsettings)
        self.assertDictEqual(dictionary, value)

        profile_dictionary = generate_default_profile()
        set_setting('population_preference', profile_dictionary, self.qsettings)
        value = setting('population_preference', qsettings=self.qsettings)
        self.assertDictEqual(profile_dictionary, value)

    def test_export_import_setting(self):
        """Test for export_setting method."""
        profile_file = unique_filename(suffix='.json', dir='population_preference')
        original_settings = {
            'key': 'value',
            'key_bool': True,
            'population_preference': generate_default_profile(),
            'key_int': 1,
            'key_float': 2.0
        }
        # Write
        for key, value in original_settings.items():
            set_setting(key, value, self.qsettings)
        # Export
        inasafe_settings = export_setting(profile_file, self.qsettings)
        # Check result
        self.assertTrue(os.path.exists(profile_file))
        self.assertEqual(inasafe_settings['key'], 'value')
        self.assertEqual(
            inasafe_settings['population_preference'], generate_default_profile())
        # Import
        read_setting = import_setting(profile_file, self.qsettings)
        self.assertDictEqual(inasafe_settings, read_setting)
        self.assertDictEqual(original_settings, read_setting)
Exemple #19
0
class TestOptionsDialog(unittest.TestCase):
    """Test Options Dialog"""
    def setUp(self):
        """Fixture run before all tests"""
        self.qsetting = QSettings('InaSAFETest')
        self.qsetting.clear()

    def tearDown(self):
        """Fixture run after each test."""
        # Make sure it's empty
        self.qsetting.clear()

    def test_setup_dialog(self):
        """Test Setup Options Dialog."""
        dialog = OptionsDialog(parent=PARENT,
                               iface=IFACE,
                               qsetting='InaSAFETest')
        self.assertIsNotNone(dialog)

        # Check default values
        self.assertEqual(dialog.cbxVisibleLayersOnly.isChecked(),
                         inasafe_default_settings['visibleLayersOnlyFlag'])
        self.assertEqual(dialog.cbxSetLayerNameFromTitle.isChecked(),
                         inasafe_default_settings['set_layer_from_title_flag'])
        self.assertEqual(dialog.cbxZoomToImpact.isChecked(),
                         inasafe_default_settings['setZoomToImpactFlag'])
        self.assertEqual(dialog.cbxHideExposure.isChecked(),
                         inasafe_default_settings['setHideExposureFlag'])
        self.assertEqual(dialog.cbxUseSelectedFeaturesOnly.isChecked(),
                         inasafe_default_settings['useSelectedFeaturesOnly'])
        self.assertEqual(dialog.leKeywordCachePath.text(),
                         inasafe_default_settings['keywordCachePath'])
        self.assertEqual(dialog.template_warning_checkbox.isChecked(),
                         inasafe_default_settings['template_warning_verbose'])
        self.assertEqual(
            dialog.organisation_on_dock_checkbox.isChecked(),
            inasafe_default_settings['showOrganisationLogoInDockFlag'])
        self.assertEqual(dialog.cbxDevMode.isChecked(),
                         inasafe_default_settings['developer_mode'])

        self.assertEqual(dialog.leNorthArrowPath.text(),
                         default_north_arrow_path())
        self.assertEqual(dialog.leOrganisationLogoPath.text(),
                         supporters_logo_path())
        self.assertEqual(dialog.leReportTemplatePath.text(), '')
        self.assertEqual(dialog.txtDisclaimer.toPlainText(), disclaimer())
        self.assertEqual(dialog.leUserDirectoryPath.text(),
                         temp_dir('impacts'))

        self.assertEqual(dialog.iso19115_organization_le.text(),
                         inasafe_default_settings['ISO19115_ORGANIZATION'])
        self.assertEqual(dialog.iso19115_url_le.text(),
                         inasafe_default_settings['ISO19115_URL'])
        self.assertEqual(dialog.iso19115_email_le.text(),
                         inasafe_default_settings['ISO19115_EMAIL'])
        self.assertEqual(dialog.iso19115_license_le.text(),
                         inasafe_default_settings['ISO19115_LICENSE'])

    def test_update_settings(self):
        """Test update InaSAFE Option works."""
        # Create new option dialog
        dialog = OptionsDialog(parent=PARENT,
                               iface=IFACE,
                               qsetting='InaSAFETest')

        # Update some state
        new_state = not inasafe_default_settings['visibleLayersOnlyFlag']
        dialog.cbxVisibleLayersOnly.setChecked(new_state)

        new_organization = 'Super Organization'
        dialog.iso19115_organization_le.setText(new_organization)

        # Accept the dialog
        dialog.accept()

        # Check the value in QSettings
        # Next two lines a hack because windows qsettings returns a string
        # rather than a bool...TS
        value = self.qsetting.value('inasafe/visibleLayersOnlyFlag')
        if value == u'false':
            value = False
        if value == u'true':
            value = True
        self.assertEquals(new_state, value)
        self.assertEqual(new_organization,
                         self.qsetting.value('inasafe/ISO19115_ORGANIZATION'))

        # Open the options dialog
        dialog = OptionsDialog(iface=IFACE,
                               parent=PARENT,
                               qsetting='InaSAFETest')

        # Check the state of the dialog after save the settings
        self.assertEqual(new_state, dialog.cbxVisibleLayersOnly.isChecked())
        self.assertEqual(new_organization,
                         dialog.iso19115_organization_le.text())
Exemple #20
0
class TestSettings(unittest.TestCase):
    """Test Settings"""
    def setUp(self):
        """Fixture run before all tests"""
        self.qsetting = QSettings('InaSAFETest')
        self.qsetting.clear()

    def tearDown(self):
        """Fixture run after each test"""
        # Make sure it's empty
        self.qsetting.clear()

    def test_get_value(self):
        """Test we can get a value from a QSettings."""
        # The expected type does not match the default value.
        try:
            self.assertEqual(
                'default_value',
                setting('test', 'default_value', bool, self.qsetting))
        except Exception:
            self.assertTrue(True)
        else:
            self.assertTrue(False)

        self.assertEqual('default_value',
                         setting('test', 'default_value', str, self.qsetting))

        self.assertIsNone(setting('test', None, str, self.qsetting))

        # Without default value.
        self.assertIsNone(setting('test', qsettings=self.qsetting))

    def test_inasafe_default_value_qsetting(self):
        """Test for set and get inasafe_default_value_qsetting."""
        # Make sure it's empty
        self.qsetting.clear()

        female_ratio_key = 'female_ratio'
        real_value = get_inasafe_default_value_qsetting(
            self.qsetting, RECENT, female_ratio_key)
        self.assertEqual(zero_default_value, real_value)

        female_ratio_value = 0.8
        set_inasafe_default_value_qsetting(self.qsetting, RECENT,
                                           female_ratio_key,
                                           female_ratio_value)
        real_value = get_inasafe_default_value_qsetting(
            self.qsetting, RECENT, female_ratio_key)
        self.assertEqual(female_ratio_value, real_value)

    def test_read_boolean_setting(self):
        """Test read developer mode setting."""
        set_setting('developer_mode',
                    inasafe_default_settings['developer_mode'])

        actual_setting = setting('developer_mode',
                                 inasafe_default_settings['developer_mode'])
        self.assertFalse(actual_setting)

        set_setting('developer_mode',
                    not (inasafe_default_settings['developer_mode']))

        actual_setting = setting('developer_mode',
                                 inasafe_default_settings['developer_mode'])
        self.assertTrue(actual_setting)
Exemple #21
0
class Properties:

    SETTING_GOOGLE_URL = 'google.url'

    SETTING_GOOGLE_COUNTRY = 'google.country'
    GOOGLE_COUNTRY_CN = QString(u'简体中文 (China)')
    GOOGLE_COUNTRY_HK = QString(u'香港版 (Hong Kong)')
    GOOGLE_COUNTRY_CAN = QString(u'Canada')
    GOOGLE_COUNTRY_UK = QString(u'U.K.')
    GOOGLE_COUNTRY_US = QString(u'U.S.')
    GOOGLE_COUNTRY_DEFAULT = GOOGLE_COUNTRY_US

    SETTING_APP_LOCALE = "app.locale"

    # See list from http://docs.python.org/library/codecs.html
    ENCODING_BIG5HK = "big5hkscs"
    ENCODING_GBK = "gbk"
    ENCODING_UTF8 = "utf_8"

    LANGUAGE_ZH_CN = u"简体中文"
    LANGUAGE_ZH_HK = u"繁體中文"
    LANGUAGE_EN_US = "English"

    LOCALE_ZH_CN = QLocale(QLocale.Chinese, QLocale.China)
    LOCALE_ZH_HK = QLocale(QLocale.Chinese, QLocale.HongKong)
    LOCALE_EN_US = QLocale(QLocale.English, QLocale.UnitedStates)

    SETTING_IS_PORTRAIT_MODE = "is_portrait_mode"
    DEFAULT_IS_PORTRAIT_MODE = True

    SETTING_UPDATE_INTERVAL = "update_interval"
    DEFAULT_UPDATE_INTERVAL = 8

    def __init__(self, application):
        '''
        @param application string
        '''
        self.qSettings = QSettings("cheungs", application)

        # Map locale to Google country
        self.googleCountries = {}
        self.googleCountries[QLocale.China] = self.GOOGLE_COUNTRY_CN
        self.googleCountries[QLocale.HongKong] = self.GOOGLE_COUNTRY_HK
        self.googleCountries[QLocale.Canada] = self.GOOGLE_COUNTRY_CAN
        self.googleCountries[QLocale.UnitedKingdom] = self.GOOGLE_COUNTRY_UK
        self.googleCountries[QLocale.UnitedStates] = self.GOOGLE_COUNTRY_US

        self.googleUrls = {}
        self.googleUrls[self.GOOGLE_COUNTRY_CN] = 'www.google.com.cn'
        self.googleUrls[self.GOOGLE_COUNTRY_HK] = 'www.google.com.hk'
        self.googleUrls[self.GOOGLE_COUNTRY_CAN] = 'www.google.ca'
        self.googleUrls[self.GOOGLE_COUNTRY_UK] = 'www.google.co.uk'
        self.googleUrls[self.GOOGLE_COUNTRY_US] = 'www.google.com'

        self.encodings = {}
        self.encodings[self.GOOGLE_COUNTRY_CN] = self.ENCODING_GBK
        self.encodings[self.GOOGLE_COUNTRY_HK] = self.ENCODING_BIG5HK
        self.encodings[self.GOOGLE_COUNTRY_CAN] = self.ENCODING_UTF8
        self.encodings[self.GOOGLE_COUNTRY_UK] = self.ENCODING_UTF8
        self.encodings[self.GOOGLE_COUNTRY_US] = self.ENCODING_UTF8

        self.appLanguages = {}
        self.appLanguages[self.LOCALE_ZH_CN.name()] = self.LANGUAGE_ZH_CN
        self.appLanguages[self.LOCALE_ZH_HK.name()] = self.LANGUAGE_ZH_HK
        self.appLanguages[self.LOCALE_EN_US.name()] = self.LANGUAGE_EN_US

    def clear(self):
        self.qSettings.clear()

    def getGoogleCountry(self, qLocale = None):
        '''
        Precedence: QSettings -> qLocale -> System Locale
        '''
        googleCountry = self.qSettings.value(self.SETTING_GOOGLE_COUNTRY).toString()
        if googleCountry is not None and googleCountry != "":
            return googleCountry

        if qLocale is None:
            qLocale = QLocale.system().country()

        if self.googleCountries.has_key(qLocale):
            googleCountry = self.googleCountries[qLocale]
        else:
            googleCountry = self.GOOGLE_COUNTRY_DEFAULT

        return googleCountry

    def getGoogleUrl(self):
        country = self.getGoogleCountry()

        if self.googleUrls.has_key(country):
            url = self.googleUrls[country]
        else:
            url = self.googleUrls[self.GOOGLE_COUNTRY_DEFAULT]

        return url

    def getEncoding(self):
        country = self.getGoogleCountry()

        if self.encodings.has_key(country):
            enc = self.encodings[country]
        else:
            enc = self.encodings[self.GOOGLE_COUNTRY_DEFAULT]

        return enc

    def setGoogleCountryUrl(self, gCountry, gUrl):
        self.qSettings.setValue(self.SETTING_GOOGLE_URL, QString(gUrl))
        self.qSettings.setValue(self.SETTING_GOOGLE_COUNTRY, QString(gCountry))

    def setAppLocale(self, qLocale):
        self.qSettings.setValue(self.SETTING_APP_LOCALE, qLocale)

    def getAppLanguage(self):

        appLocale = self.getAppLocale()
        return self.appLanguages[appLocale.name()]

    def getAppLocale(self):
        '''
        Precedence: QSettings -> System Locale
        '''
        qSetting = self.qSettings.value(self.SETTING_APP_LOCALE)
        if qSetting is not None and \
           not qSetting.isNull() and \
           qSetting.type() == QVariant.Locale:
            return qSetting.toLocale()
        else:
            sysLocale = QLocale.system()
            if self.appLanguages.has_key(sysLocale.name()):
                return sysLocale
            else:
                return self.LOCALE_EN_US

    def isPortraitMode(self):

        qSetting = self.qSettings.value(self.SETTING_IS_PORTRAIT_MODE)
        if qSetting is not None and not qSetting.isNull():
            return qSetting.toBool()

        return self.DEFAULT_IS_PORTRAIT_MODE

    def setPortraitMode(self, trueFalse):
        self.qSettings.setValue(self.SETTING_IS_PORTRAIT_MODE, trueFalse)

    def getUpdateInterval(self):

        qSetting = self.qSettings.value(self.SETTING_UPDATE_INTERVAL)
        if qSetting is not None and not qSetting.isNull():
            return qSetting.toInt()[0]

        return self.DEFAULT_UPDATE_INTERVAL

    def setUpdateInterval(self, updateInterval):
        self.qSettings.setValue(self.SETTING_UPDATE_INTERVAL, updateInterval)