Esempio n. 1
0
    def test_plugin_compatibility(self):
        """Default plugins perform as expected
        """

        # Get list of plugins
        plugin_list = get_plugins()
        assert len(plugin_list) > 0

        # Characterisation test to preserve the behaviour of
        # get_layer_descriptors. FIXME: I think we should change this to be
        # a dictionary of metadata entries (ticket #126).
        reference = [['lembang_schools',
                      {'layertype': 'vector',
                       'category': 'exposure',
                       'subcategory': 'building',
                       'title': 'lembang_schools'}],
                     ['shakemap_padang_20090930',
                      {'layertype': 'raster',
                       'category': 'hazard',
                       'subcategory': 'earthquake',
                       'title': 'shakemap_padang_20090930'}]]

        # Check plugins are returned
        metadata = reference
        annotated_plugins = [{'name': name,
                              'doc': f.__doc__,
                              'layers': compatible_layers(f, metadata)}
                             for name, f in plugin_list.items()]

        msg = 'No compatible layers returned'
        assert len(annotated_plugins) > 0, msg
Esempio n. 2
0
    def test_get_plugin_list(self):
        """It is possible to retrieve the list of functions
        """

        plugin_list = get_plugins()
        msg = ('No plugins were found, not even the built-in ones')
        assert len(plugin_list) > 0, msg
Esempio n. 3
0
    def test_build_form_minimum_needs(self):
        """Test that we can build a form by passing it a function and params.
        """
        function_id = 'Flood Evacuation Function Vector Hazard'
        function_list = get_plugins(function_id)
        assert len(function_list) == 1
        assert function_list[0].keys()[0] == function_id

        dialog = FunctionOptionsDialog()
        parameters = {
            'thresholds': [1.0],
            'postprocessors': {
                'Gender': {'on': True},
                'Age': {
                    'on': True,
                    'params': {
                        'youth_ratio': 0.263,
                        'elderly_ratio': 0.078,
                        'adult_ratio': 0.659}}}}

        dialog.build_form(parameters)

        assert dialog.tabWidget.count() == 2

        children = dialog.tabWidget.findChildren(QLineEdit)
        assert len(children) == 4
Esempio n. 4
0
 def test_single_get_plugins(self):
     """Named plugin can be retrieved
     """
     plugin_name = DEFAULT_PLUGINS[0]
     plugin_list = get_plugins(plugin_name)
     msg = ('No plugins were found matching %s' % plugin_name)
     assert len(plugin_list) > 0, msg
Esempio n. 5
0
    def test_get_plugin_list(self):
        """It is possible to retrieve the list of functions
        """

        plugin_list = get_plugins()
        msg = ('No plugins were found, not even the built-in ones')
        assert len(plugin_list) > 0, msg
Esempio n. 6
0
    def test_get_plugins(self):
        """Plugins can be collected."""
        os.environ['LANG'] = 'en'
        plugin_list = get_plugins()
        assert(len(plugin_list) > 0)

        # Obtain string representation
        string_rep = admissible_plugins_to_str(plugin_list)

        # Check each plugin
        for plugin in plugin_list.values():
            # Check that it's name appeears in string representation
            title = get_function_title(plugin)
            msg = ('Expected title %s in string representation: %s'
                   % (title, string_rep))
            assert title in string_rep, msg

            # Check that every plugin has a requires line
            requirements = requirements_collect(plugin)
            msg = 'There were no requirements in plugin %s' % plugin
            assert(len(requirements) > 0), msg

            for req_str in requirements:
                msg = 'All plugins should return True or False'
                assert(requirement_check({'category': 'hazard',
                                          'subcategory': 'earthquake',
                                          'layerType': 'raster'},
                                         req_str) in [True, False]), msg
Esempio n. 7
0
 def test_single_get_plugins(self):
     """Named plugin can be retrieved
     """
     plugin_name = DEFAULT_PLUGINS[0]
     plugin_list = get_plugins(plugin_name)
     msg = ('No plugins were found matching %s' % plugin_name)
     assert len(plugin_list) > 0, msg
Esempio n. 8
0
    def test_plugin_compatibility(self):
        """Default plugins perform as expected
        """

        # Get list of plugins
        plugin_list = get_plugins()
        assert len(plugin_list) > 0

        # Characterisation test to preserve the behaviour of
        # get_layer_descriptors. FIXME: I think we should change this to be
        # a dictionary of metadata entries (ticket #126).
        reference = [['lembang_schools',
                      {'layertype': 'vector',
                       'category': 'exposure',
                       'subcategory': 'building',
                       'title': 'lembang_schools'}],
                     ['shakemap_padang_20090930',
                      {'layertype': 'raster',
                       'category': 'hazard',
                       'subcategory': 'earthquake',
                       'title': 'shakemap_padang_20090930'}]]

        # Check plugins are returned
        metadata = reference
        annotated_plugins = [{'name': name,
                              'doc': f.__doc__,
                              'layers': compatible_layers(f, metadata)}
                             for name, f in plugin_list.items()]

        msg = 'No compatible layers returned'
        assert len(annotated_plugins) > 0, msg
Esempio n. 9
0
    def test_get_plugins(self):
        """Plugins can be collected."""
        os.environ['LANG'] = 'en'
        plugin_list = get_plugins()
        self.assertGreater(len(plugin_list), 0)

        # Obtain string representation
        string_rep = admissible_plugins_to_str(plugin_list)

        # Check each plugin
        for plugin in plugin_list.values():
            # Check that it's name appears in string representation
            title = get_function_title(plugin)
            message = ('Expected title %s in string representation: %s' %
                       (title, string_rep))
            assert title in string_rep, message

            # Check that every plugin has a requires line
            requirements = requirements_collect(plugin)
            message = 'There were no requirements in plugin %s' % plugin
            assert (len(requirements) > 0), message

            for required_string in requirements:
                message = 'All plugins should return True or False'
                assert (requirement_check(
                    {
                        'category': 'hazard',
                        'subcategory': 'earthquake',
                        'layerType': 'raster'
                    }, required_string) in [True, False]), message
Esempio n. 10
0
    def test_requirements_check(self):
        """Plugins are correctly filtered based on requirements."""
        plugin_list = get_plugins('BasicFunction')
        self.assertEqual(len(plugin_list), 1)

        requirements = requirements_collect(plugin_list[0].values()[0])
        message = 'Requirements are %s' % requirements
        assert (len(requirements) == 1), message
        for req_str in requirements:
            message = 'Should eval to True'
            assert (requirement_check({'category': 'hazard'}, req_str) is
                    True), message
            message = 'Should eval to False'
            assert (requirement_check({'broke': 'broke'}, req_str) is
                    False), message

        try:
            plugin_list = get_plugins('NotRegistered')
        except RuntimeError:
            pass
        else:
            message = 'Search should fail'
            raise Exception(message)
Esempio n. 11
0
    def test_requirements_check(self):
        """Plugins are correctly filtered based on requirements."""
        plugin_list = get_plugins('BasicFunction')
        self.assertEqual(len(plugin_list), 1)

        requirements = requirements_collect(plugin_list[0].values()[0])
        message = 'Requirements are %s' % requirements
        assert(len(requirements) == 1), message
        for req_str in requirements:
            message = 'Should eval to True'
            assert(requirement_check({'category': 'hazard'},
                                     req_str) is True), message
            message = 'Should eval to False'
            assert(requirement_check({'broke': 'broke'},
                                     req_str) is False), message

        try:
            plugin_list = get_plugins('NotRegistered')
        except RuntimeError:
            pass
        else:
            message = 'Search should fail'
            raise Exception(message)
Esempio n. 12
0
    def test_build_form(self):
        """Test that we can build a form by passing it a function and params.
        """
        function_id = 'ITB Fatality Function'
        function_list = get_plugins(function_id)
        assert len(function_list) == 1
        assert function_list[0].keys()[0] == function_id

        dialog = FunctionOptionsDialog()

        # Define rice for minimum needs
        rice = ResourceParameter()
        rice.value = 2.8
        rice.frequency = 'weekly'
        rice.minimum_allowed_value = 1.4
        rice.maximum_allowed_value = 5.6
        rice.name = 'Rice'
        rice.unit.abbreviation = 'kg'
        rice.unit.name = 'kilogram'
        rice.unit.plural = 'kilograms'

        parameter = {
            'thresholds': [1.0],
            'postprocessors': {
                'Gender': {'on': True},
                'Age': {
                    'on': True,
                    'params': {
                        'youth_ratio': 0.263,
                        'elderly_ratio': 0.078,
                        'adult_ratio': 0.659
                    }
                }
            },
            'minimum needs': [rice]
        }

        dialog.build_form(parameter)

        message = 'There should be %s tabwidget but got %s' % (
            3, dialog.tabWidget.count())
        self.assertEqual(dialog.tabWidget.count(), 3, message)

        children = dialog.tabWidget.findChildren(QLineEdit)
        message = 'There should be %s QLineEdit but got %s' % (
            5, len(children))
        self.assertEqual(len(children), 5, message)
Esempio n. 13
0
 def save(self):
     """Save the minimum needs to the QSettings object.
     """
     # This needs to be imported here to avoid an inappropriate loading
     # sequence
     if not self.minimum_needs['resources']:
         return
     from safe.impact_functions.core import get_plugins
     self.settings.setValue('MinimumNeeds', self.minimum_needs)
     # Monkey patch all the impact functions
     for (_, plugin) in get_plugins().items():
         if not hasattr(plugin, 'parameters'):
             continue
         if 'minimum needs' in plugin.parameters:
             plugin.parameters['minimum needs'] = (
                 self.get_needs_parameters())
             plugin.parameters['provenance'] = self.provenance
Esempio n. 14
0
 def save(self):
     """Save the minimum needs to the QSettings object.
     """
     # This needs to be imported here to avoid an inappropriate loading
     # sequence
     if not self.minimum_needs['resources']:
         return
     from safe.impact_functions.core import get_plugins
     self.settings.setValue('MinimumNeeds', self.minimum_needs)
     # Monkey patch all the impact functions
     for (_, plugin) in get_plugins().items():
         if not hasattr(plugin, 'parameters'):
             continue
         if 'minimum needs' in plugin.parameters:
             plugin.parameters['minimum needs'] = (
                 self.get_needs_parameters())
             plugin.parameters['provenance'] = self.provenance
Esempio n. 15
0
def get_safe_impact_function(function_name=None):
    """Thin wrapper around the safe impact_functions function.

    :param function_name: Specific plugin name that should be fetched.
    :type function_name: str

    :returns: A safe impact function is returned
    :rtype: safe.impact.core.FunctionProvider

    """
    # Convert string to ASCII
    function_name = unicode(function_name)
    function_name = unicodedata.normalize(
        'NFKD', function_name).encode('ascii', 'ignore')
    try:
        return get_plugins(function_name)
    except:
        raise
Esempio n. 16
0
def get_safe_impact_function(function_name=None):
    """Thin wrapper around the safe impact_functions function.

    :param function_name: Specific plugin name that should be fetched.
    :type function_name: str

    :returns: A safe impact function is returned
    :rtype: safe.impact.core.FunctionProvider

    """
    # Convert string to ASCII
    function_name = unicode(function_name)
    function_name = unicodedata.normalize('NFKD', function_name).encode(
        'ascii', 'ignore')
    try:
        return get_plugins(function_name)
    except:
        raise
Esempio n. 17
0
    def Xtest_dynamic_translation_function_title(self):
        """Test for dynamic translations for function title."""
        plugins_dict = get_plugins()
        plugin_name = 'Volcano Building Impact'
        message = '%s not found in %s' % (plugin_name, str(plugins_dict))
        self.assertIn(plugin_name, plugins_dict, message)
        function = plugins_dict[plugin_name]

        # English
        function_title = get_function_title(function)
        expected_title = 'Be affected'
        message = 'Expected %s but I got %s' % (expected_title, function_title)
        self.assertEqual(expected_title, function_title, message)

        # Indonesia
        os.environ['LANG'] = 'id'
        function_title = get_function_title(function)
        expected_title = 'Terkena dampak'
        message = ('expected %s but got %s, in lang = %s' %
                   (expected_title, function_title, os.environ['LANG']))
        self.assertEqual(expected_title, function_title, message)

        # Set back to en
        os.environ['LANG'] = 'en'
Esempio n. 18
0
 def test_single_get_plugins(self):
     """Named plugin can be retrieved"""
     plugin_name = 'ITBFatalityFunction'
     plugin_list = get_plugins(plugin_name)
     message = 'No plugins were found matching %s' % plugin_name
     assert len(plugin_list) > 0, message
Esempio n. 19
0
 def test_single_get_plugins(self):
     """Named plugin can be retrieved"""
     plugin_name = 'ITBFatalityFunction'
     plugin_list = get_plugins(plugin_name)
     message = 'No plugins were found matching %s' % plugin_name
     assert len(plugin_list) > 0, message
Esempio n. 20
0
    QCoreApplication.installTranslator(translator)

# MONKEYPATCHING safe.defaults.get_defaults to use get_defaults
# see safe_qgis.utilities.defaults for more details
try:
    import safe.defaults
    from safe_qgis.utilities.defaults import get_defaults

    safe.defaults.get_defaults = lambda the_default=None: get_defaults(
        the_default)

    from safe.impact_functions.core import get_plugins
    from safe_qgis.tools.minimum_needs.needs_profile import NeedsProfile
    # Monkey patch all the impact functions
    minimum_needs = NeedsProfile()
    for (name, plugin) in get_plugins().items():
        if not hasattr(plugin, 'parameters'):
            continue
        if 'minimum needs' in plugin.parameters:
            plugin.parameters['minimum needs'] = (
                minimum_needs.get_needs_parameters())
            plugin.parameters['provenance'] = minimum_needs.provenance

    # When upgrading, using the plugin manager, you may get an error when
    # doing the following import, so we wrap it in a try except
    # block and then display a friendly message to restart QGIS
    from safe_qgis.utilities.custom_logging import setup_logger
    setup_logger()
except ImportError:
    # Note we use translate directly but the string may still not translate
    # at this early stage since the i18n setup routines have not been called
Esempio n. 21
0
    QCoreApplication.installTranslator(translator)

# MONKEYPATCHING safe.defaults.get_defaults to use get_defaults
# see safe_qgis.utilities.defaults for more details
try:
    import safe.defaults
    from safe_qgis.utilities.defaults import get_defaults

    safe.defaults.get_defaults = lambda the_default=None: get_defaults(
        the_default)

    from safe.impact_functions.core import get_plugins
    from safe_qgis.tools.minimum_needs.needs_profile import NeedsProfile
    # Monkey patch all the impact functions
    minimum_needs = NeedsProfile()
    for (name, plugin) in get_plugins().items():
        if not hasattr(plugin, 'parameters'):
            continue
        if 'minimum needs' in plugin.parameters:
            plugin.parameters['minimum needs'] = (
                minimum_needs.get_needs_parameters())
            plugin.parameters['provenance'] = minimum_needs.provenance

    # When upgrading, using the plugin manager, you may get an error when
    # doing the following import, so we wrap it in a try except
    # block and then display a friendly message to restart QGIS
    from safe_qgis.utilities.custom_logging import setup_logger
    setup_logger()
except ImportError:
    # Note we use translate directly but the string may still not translate
    # at this early stage since the i18n setup routines have not been called