def test_translation(self):
        """Test for metadata translation."""
        from safe.gui.tools.wizard_dialog import WizardDialog
        from safe.test.utilities import (
            clone_shp_layer, remove_vector_temp_file)
        from safe.test.utilities import BOUNDDATA

        from safe.test.utilities import get_qgis_app
        # Get QGis app handle
        # noinspection PyPep8Naming
        _, _, IFACE, PARENT = get_qgis_app()

        layer = clone_shp_layer(
            name='kabupaten_jakarta',
            include_keywords=True,
            source_directory=BOUNDDATA)
        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)
        expected_categories = ['keterpaparan', 'ancaman', 'agregasi']
        # noinspection PyTypeChecker
        self.check_list(expected_categories, dialog.lstCategories)

        self.check_current_text('agregasi', dialog.lstCategories)

        dialog.pbnNext.click()

        remove_vector_temp_file(layer.source())
Пример #2
0
def analysis_execution():

    from safe.test.utilities import get_qgis_app

    # get_qgis_app must be called before importing Analysis
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()

    from safe.utilities.analysis import Analysis
    from safe.utilities.keyword_io import KeywordIO

    analysis = Analysis()

    arg = AnalysisArguments.read_arguments()

    register_impact_functions()

    registry = ImpactFunctionManager().registry

    function = registry.get_instance(arg.impact_function_name)

    hazard_layer = safe_to_qgis_layer(read_layer(arg.hazard_filename))
    exposure_layer = safe_to_qgis_layer(read_layer(arg.exposure_filename))
    if arg.aggregation_filename:
        aggregation_layer = safe_to_qgis_layer(read_layer(
            arg.aggregation_filename))

    keywords_io = KeywordIO()

    try:
        analysis.map_canvas = IFACE.mapCanvas()
        analysis.hazard_layer = hazard_layer
        analysis.hazard_keyword = keywords_io.read_keywords(hazard_layer)
        analysis.exposure_layer = exposure_layer
        analysis.exposure_keyword = keywords_io.read_keywords(exposure_layer)
        if aggregation_layer:
            analysis.aggregation_layer = aggregation_layer
            analysis.aggregation_keyword = keywords_io.read_keywords(
                aggregation_layer)
        analysis.impact_function = function

        analysis.setup_analysis()
        print 'Setup analysis done'
        analysis.run_analysis()
        print 'Analysis done'
    except Exception as e:
        print e.message

    impact = analysis.impact_layer
    qgis_impact = safe_to_qgis_layer(impact)

    generate_styles(impact, qgis_impact)

    copy_impact_layer(impact, arg.impact_filename)
Пример #3
0
    def test_qgis_app_locale(self):
        """Test for qgis app locale."""

        from safe.definitions.constants import no_field
        self.assertEqual(no_field, u'No Field')

        # run qgis on bahasa
        _ = get_qgis_app('id', INASAFE_TEST)

        # test if string from inasafe module are translated
        from safe.definitions.constants import no_field
        self.assertNotEqual(no_field, u'No Field')

        expected_locale = 'id'
        self.assertEqual(locale(INASAFE_TEST), expected_locale)

        # check for bahasa translation
        expected_message = (
            'Tidak ada informasi gaya yang ditemukan pada lapisan %s')
        real_message = tr(
            'No styleInfo was found for layer %s')
        message = 'expected %s but got %s' % (expected_message, real_message)
        self.assertEqual(expected_message, real_message, message)

        # run qgis on english
        _ = get_qgis_app(qsetting=INASAFE_TEST)

        expected_locale = 'en'
        self.assertEqual(locale(INASAFE_TEST), expected_locale)

        # check for english translation
        expected_message = (
            'No styleInfo was found for layer %s')
        real_message = tr(
            'No styleInfo was found for layer %s')
        message = 'expected %s but got %s' % (expected_message, real_message)
        self.assertEqual(expected_message, real_message, message)

        # Set back to en
        os.environ['LANG'] = 'en'
Пример #4
0
def main():
    """Main function to run the example."""
    def print_values(the_profile_widget):
        data = the_profile_widget.data
        from pprint import pprint
        pprint(data)

    def clear_widget(the_profile_widget):
        the_profile_widget.clear()

    def restore_data(the_profile_widget):
        the_profile_widget.clear()
        the_profile_widget.data = generate_default_profile()

    from safe.test.utilities import get_qgis_app
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

    default_profile = generate_default_profile()
    profile_widget = ProfileWidget(data=default_profile)

    get_result_button = QPushButton('Get result...')
    get_result_button.clicked.connect(
        partial(print_values, profile_widget))

    clear_button = QPushButton('Clear widget...')
    clear_button.clicked.connect(
        partial(clear_widget, profile_widget))

    restore_button = QPushButton('Restore data...')
    restore_button.clicked.connect(
        partial(restore_data, profile_widget))

    widget = QWidget()
    layout = QGridLayout()
    layout.addWidget(profile_widget)
    layout.addWidget(restore_button)
    layout.addWidget(get_result_button)
    layout.addWidget(clear_button)

    widget.setLayout(layout)

    widget.setFixedHeight(600)
    widget.setFixedWidth(800)
    widget.show()

    sys.exit(QGIS_APP.exec_())
Пример #5
0
    def test_hello_world_report(self):
        """Test for creating hello world report.

        .. versionadded:: 4.1
        """
        QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)
        output_folder = self.fixtures_dir('../output/hello_world_report')

        # sneaky monkey patch
        ImpactFunction.outputs = ['Not implemented']
        impact_function = ImpactFunction()

        template_metadata = ReportMetadata(
            metadata_dict=hello_world_metadata_html)

        impact_report = ImpactReport(
            iface=IFACE,
            template_metadata=template_metadata,
            impact_function=impact_function)

        impact_report.output_folder = output_folder

        impact_report.process_components()
Пример #6
0
from safe.definitions.hazard_classifications import (
    generic_hazard_classes,
    earthquake_mmi_scale,
    tsunami_hazard_classes,
    cyclone_au_bom_hazard_classes)
from safe.report.extractors.util import (
    layer_definition_type,
    layer_hazard_classification,
    resolve_from_dictionary,
    retrieve_exposure_classes_lists)
from safe.test.utilities import (
    load_layer,
    standard_data_path,
    get_qgis_app)

QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()

__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "*****@*****.**"
__revision__ = 'e54efb23cb33ed813dec3545321e0284b904e7a6'


LOGGER = logging.getLogger('InaSAFE')


class TestReportUtil(unittest.TestCase):

    def setUp(self):
        self.maxDiff = None
        self.layer_paths_list = [
Пример #7
0
 def setUp(self):
     from safe.test.utilities import get_qgis_app
     QGIS_APP, CANVAS, self.iface, PARENT = get_qgis_app(
         qsetting=INASAFE_TEST)
Пример #8
0
def main():
    """Main function to run the example."""
    from safe.test.utilities import get_qgis_app
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

    options = OrderedDict([
        (DO_NOT_REPORT,
         {
             'label': 'Do not report',
             'value': None,
             'type': STATIC,
             'constraint': {}
         }),
        (GLOBAL_DEFAULT,
         {
             'label': 'Global default',
             'value': 0.5,
             'type': STATIC,
             'constraint': {}
         }),
        (CUSTOM_VALUE,
         {
             'label': 'Custom',
             'value': 0.7,  # Taken from keywords / recent value
             'type': SINGLE_DYNAMIC,
             'constraint':
                 {
                     'min': 0,
                     'max': 1
                 }
         }),
        (FIELDS,
         {
             'label': 'Ratio fields',
             'value': ['field A', 'field B', 'field C'],  # Taken from keywords
             'type': MULTIPLE_DYNAMIC,
             'constraint': {}
         })
    ])

    default_value_parameter = GroupSelectParameter()
    default_value_parameter.name = 'Group Select parameter'
    default_value_parameter.help_text = 'Help text'
    default_value_parameter.description = 'Description'
    default_value_parameter.options = options
    default_value_parameter.selected = 'ratio fields'

    parameters = [
        default_value_parameter
    ]

    extra_parameters = [
        (GroupSelectParameter, GroupSelectParameterWidget)
    ]

    parameter_container = ParameterContainer(
        parameters, extra_parameters=extra_parameters)
    parameter_container.setup_ui()

    widget = QWidget()
    layout = QGridLayout()
    layout.addWidget(parameter_container)

    def show_error_message(parent, exception):
        """Generate error message to handle parameter errors

        :param parent: The widget as a parent of message box
        :type parent: QWidget
        :param exception: python Exception or Error
        :type exception: Exception
        """
        box = QMessageBox()
        box.critical(parent, 'Error occured', str(exception))

    def show_parameter(the_parameter_container):
        """Print the value of parameter.

        :param the_parameter_container: A parameter container
        :type the_parameter_container: ParameterContainer
        """
        def show_parameter_value(a_parameter):
            if isinstance(a_parameter, GroupParameter):
                for param in a_parameter.value:
                    show_parameter_value(param)
            else:
                print((a_parameter.guid, a_parameter.name, a_parameter.value))

        try:
            the_parameters = the_parameter_container.get_parameters()
            if the_parameters:
                for parameter in the_parameters:
                    show_parameter_value(parameter)
        except Exception as inst:
            show_error_message(parameter_container, inst)

    print_button = QPushButton('Print Result')
    # noinspection PyUnresolvedReferences
    print_button.clicked.connect(
        partial(show_parameter, the_parameter_container=parameter_container))

    layout.addWidget(print_button)

    widget.setLayout(layout)
    widget.setGeometry(0, 0, 500, 500)

    widget.show()

    sys.exit(QGIS_APP.exec_())
import unittest
import os

# This is to enable API V2
# noinspection PyUnresolvedReferences
import qgis  # pylint: disable=unused-import
# noinspection PyPackageRequirements
from qgis.PyQt.QtWidgets import QDialogButtonBox

from safe.definitions.constants import INASAFE_TEST
from safe.gui.tools.shake_grid.shakemap_converter_dialog import (
    ShakemapConverterDialog)
from safe.common.utilities import unique_filename, temp_dir
from safe.test.utilities import standard_data_path, get_qgis_app

QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "*****@*****.**"
__revision__ = 'bd00bfeac510722b427544b186bfa10861749e51'


class TestShakemapImporter(unittest.TestCase):
    """Test class to facilitate importing shakemaps."""

    def test_init_dialog(self):
        """Test for showing table in the first."""
        shakemap_converter_dialog = ShakemapConverterDialog(PARENT, IFACE)
        msg = 'Dialog is failed to create'
        self.assertIsNotNone(shakemap_converter_dialog, msg)
    def test_existing_complex_keywords(self):
        """Test for existing complex keywords in wizard in locale mode."""
        from safe.gui.tools.wizard_dialog import WizardDialog
        from safe.test.utilities import (
            clone_shp_layer, remove_vector_temp_file)
        layer = clone_shp_layer(
            name='tsunami_polygon', include_keywords=True, source_directory='')

        from safe.test.utilities import get_qgis_app
        # Get QGis app handle
        # noinspection PyPep8Naming
        _, _, IFACE, PARENT = get_qgis_app()
        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # select hazard
        self.select_from_list_widget('ancaman', dialog.lstCategories)
        dialog.pbnNext.click()

        # select volcano
        self.select_from_list_widget('gunung berapi', dialog.lstSubcategories)
        dialog.pbnNext.click()

        # select volcano categorical unit
        self.select_from_list_widget('Kategori gunung berapi', dialog.lstUnits)
        dialog.pbnNext.click()

        # select GRIDCODE
        self.select_from_list_widget('GRIDCODE', dialog.lstFields)
        dialog.pbnNext.click()

        unit = dialog.selected_unit()
        default_classes = unit['classes']
        unassigned_values = []  # no need to check actually, not save in file
        assigned_values = {
            'low': ['5.0'],
            'medium': ['3.0', '4.0'],
            'high': ['2.0']
        }
        dialog.populate_classified_values(
            unassigned_values, assigned_values, default_classes)
        dialog.pbnNext.click()

        source = 'Source'
        source_scale = 'Source Scale'
        source_url = 'Source Url'
        source_date = 'Source Date'

        dialog.leSource.setText(source)
        dialog.leSource_scale.setText(source_scale)
        dialog.leSource_url.setText(source_url)
        dialog.leSource_date.setText(source_date)
        dialog.pbnNext.click()  # next
        dialog.pbnNext.click()  # finish

        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # step 1 of 7 - select category
        self.check_current_text('ancaman', dialog.lstCategories)

        # Click Next
        dialog.pbnNext.click()

        # step 2 of 7 - select subcategory
        # noinspection PyTypeChecker
        self.check_current_text('gunung berapi', dialog.lstSubcategories)

        # Click Next
        dialog.pbnNext.click()

        # step 3 of 7 - select volcano units
        self.check_current_text('Kategori gunung berapi', dialog.lstUnits)

        # Click Next
        dialog.pbnNext.click()

        # step 4 of 7 - select field
        self.check_current_text('GRIDCODE', dialog.lstFields)

        # Click Next
        dialog.pbnNext.click()

        for index in range(dialog.lstUniqueValues.count()):
            message = ('%s Should be in unassigned values' %
                       dialog.lstUniqueValues.item(index).text())
            self.assertIn(
                dialog.lstUniqueValues.item(index).text(),
                unassigned_values,
                message)
        real_assigned_values = dialog.selected_mapping()
        self.assertDictEqual(real_assigned_values, assigned_values)

        # Click Next
        dialog.pbnNext.click()

        # step 6 of 7 - enter source
        message = ('Invalid Next button state in step 6! Disabled while '
                   'source is optional')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)

        message = 'Source should be %s' % source
        self.assertEqual(dialog.leSource.text(), source, message)
        message = 'Source Url should be %s' % source_url
        self.assertEqual(dialog.leSource_url.text(), source_url, message)
        message = 'Source Date should be %s' % source_date
        self.assertEqual(dialog.leSource_date.text(), source_date, message)
        message = 'Source Scale should be %s' % source_scale
        self.assertEqual(dialog.leSource_scale.text(), source_scale, message)
        dialog.pbnNext.click()

        dialog.pbnCancel.click()

        remove_vector_temp_file(layer.source())
__author__ = '*****@*****.**'
__date__ = '11/12/2015'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
                 'Disaster Reduction')

import unittest

from safe.impact_functions.impact_function_manager import ImpactFunctionManager
from safe.impact_functions.earthquake.itb_earthquake_fatality_model\
    .impact_function import ITBFatalityFunction
from safe.test.utilities import test_data_path
from safe.storage.core import read_layer
from safe.test.utilities import get_qgis_app, clip_layers
from safe.storage.safe_layer import SafeLayer

QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()


class TestITBEarthquakeFatalityFunction(unittest.TestCase):
    """Test for Earthquake on Population Impact Function."""

    def setUp(self):
        registry = ImpactFunctionManager().registry
        registry.clear()
        registry.register(ITBFatalityFunction)

    def test_run(self):
        """TestITEarthquakeFatalityFunction: Test running the IF."""
        # FIXME(Hyeuk): test requires more realistic hazard and population data
        eq_path = test_data_path('hazard', 'earthquake.tif')
        population_path = test_data_path(
Пример #12
0
# coding=utf-8

import unittest

from qgis.core import QgsRectangle

from safe.definitions.constants import INASAFE_TEST
from safe.test.utilities import get_qgis_app, load_test_raster_layer
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

from safe.gis.raster.clip_bounding_box import clip_by_extent

__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "*****@*****.**"
__revision__ = 'fdf1afffab4271e5fbb873566278d5b4a7ff5722'


class TestClipRaster(unittest.TestCase):
    """Tests for clipping a raster layer with an extent."""
    def test_clip_raster(self):
        """Test we can clip a raster layer."""
        layer = load_test_raster_layer('gisv4', 'hazard', 'earthquake.asc')
        expected = QgsRectangle(106.75, -6.2, 106.80, -6.1)
        new_layer = clip_by_extent(layer, expected)

        extent = new_layer.extent()
        self.assertAlmostEqual(expected.xMinimum(), extent.xMinimum(), 0)
        self.assertAlmostEqual(expected.xMaximum(), extent.xMaximum(), 0)
        self.assertAlmostEqual(expected.yMinimum(), extent.yMinimum(), 0)
        self.assertAlmostEqual(expected.yMaximum(), extent.yMaximum(), 0)
Пример #13
0
def main():
    """Main function to run the example."""
    from safe.test.utilities import get_qgis_app
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

    options = OrderedDict([
        (DO_NOT_REPORT, {
            'label': 'Do not report',
            'value': None,
            'type': STATIC,
            'constraint': {}
        }),
        (GLOBAL_DEFAULT, {
            'label': 'Global default',
            'value': 0.5,
            'type': STATIC,
            'constraint': {}
        }),
        (
            CUSTOM_VALUE,
            {
                'label': 'Custom',
                'value': 0.7,  # Taken from keywords / recent value
                'type': SINGLE_DYNAMIC,
                'constraint': {
                    'min': 0,
                    'max': 1
                }
            }),
        (
            FIELDS,
            {
                'label': 'Ratio fields',
                'value': ['field A', 'field B',
                          'field C'],  # Taken from keywords
                'type': MULTIPLE_DYNAMIC,
                'constraint': {}
            })
    ])

    default_value_parameter = GroupSelectParameter()
    default_value_parameter.name = 'Group Select parameter'
    default_value_parameter.help_text = 'Help text'
    default_value_parameter.description = 'Description'
    default_value_parameter.options = options
    default_value_parameter.selected = 'ratio fields'

    parameters = [default_value_parameter]

    extra_parameters = [(GroupSelectParameter, GroupSelectParameterWidget)]

    parameter_container = ParameterContainer(parameters,
                                             extra_parameters=extra_parameters)
    parameter_container.setup_ui()

    widget = QWidget()
    layout = QGridLayout()
    layout.addWidget(parameter_container)

    def show_error_message(parent, exception):
        """Generate error message to handle parameter errors

        :param parent: The widget as a parent of message box
        :type parent: QWidget
        :param exception: python Exception or Error
        :type exception: Exception
        """
        box = QMessageBox()
        box.critical(parent, 'Error occured', str(exception))

    def show_parameter(the_parameter_container):
        """Print the value of parameter.

        :param the_parameter_container: A parameter container
        :type the_parameter_container: ParameterContainer
        """
        def show_parameter_value(a_parameter):
            if isinstance(a_parameter, GroupParameter):
                for param in a_parameter.value:
                    show_parameter_value(param)
            else:
                # print(a_parameter.guid, a_parameter.name, a_parameter.value)
                pass

        try:
            the_parameters = the_parameter_container.get_parameters()
            if the_parameters:
                for parameter in the_parameters:
                    show_parameter_value(parameter)
        except Exception as inst:
            show_error_message(parameter_container, inst)

    print_button = QPushButton('Print Result')
    # noinspection PyUnresolvedReferences
    print_button.clicked.connect(
        partial(show_parameter, the_parameter_container=parameter_container))

    layout.addWidget(print_button)

    widget.setLayout(layout)
    widget.setGeometry(0, 0, 500, 500)

    widget.show()

    sys.exit(QGIS_APP.exec_())
    def test_existing_complex_keywords(self):
        """Test for existing complex keywords in wizard in locale mode."""
        from safe.gui.tools.wizard_dialog import WizardDialog
        from safe.test.utilities import clone_shp_layer, remove_vector_temp_file

        layer = clone_shp_layer(name="tsunami_polygon", include_keywords=True, source_directory="")

        from safe.test.utilities import get_qgis_app

        # Get QGis app handle
        # noinspection PyPep8Naming
        _, _, IFACE, PARENT = get_qgis_app()
        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # select hazard
        self.select_from_list_widget("ancaman", dialog.lstCategories)
        dialog.pbnNext.click()

        # select volcano
        self.select_from_list_widget("gunung berapi", dialog.lstSubcategories)
        dialog.pbnNext.click()

        # select volcano categorical unit
        self.select_from_list_widget("Kategori gunung berapi", dialog.lstUnits)
        dialog.pbnNext.click()

        # select GRIDCODE
        self.select_from_list_widget("GRIDCODE", dialog.lstFields)
        dialog.pbnNext.click()

        unit = dialog.selected_unit()
        default_classes = unit["classes"]
        unassigned_values = []  # no need to check actually, not save in file
        assigned_values = {"low": ["5.0"], "medium": ["3.0", "4.0"], "high": ["2.0"]}
        dialog.populate_classified_values(unassigned_values, assigned_values, default_classes)
        dialog.pbnNext.click()

        source = "Source"
        source_scale = "Source Scale"
        source_url = "Source Url"
        source_date = QDateTime.fromString("06-12-2015 12:30", "dd-MM-yyyy HH:mm")

        dialog.leSource.setText(source)
        dialog.leSource_scale.setText(source_scale)
        dialog.leSource_url.setText(source_url)
        dialog.leSource_date.seDateTime(source_date)
        dialog.pbnNext.click()  # next
        dialog.pbnNext.click()  # finish

        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # step 1 of 7 - select category
        self.check_current_text("ancaman", dialog.lstCategories)

        # Click Next
        dialog.pbnNext.click()

        # step 2 of 7 - select subcategory
        # noinspection PyTypeChecker
        self.check_current_text("gunung berapi", dialog.lstSubcategories)

        # Click Next
        dialog.pbnNext.click()

        # step 3 of 7 - select volcano units
        self.check_current_text("Kategori gunung berapi", dialog.lstUnits)

        # Click Next
        dialog.pbnNext.click()

        # step 4 of 7 - select field
        self.check_current_text("GRIDCODE", dialog.lstFields)

        # Click Next
        dialog.pbnNext.click()

        for index in range(dialog.lstUniqueValues.count()):
            message = "%s Should be in unassigned values" % dialog.lstUniqueValues.item(index).text()
            self.assertIn(dialog.lstUniqueValues.item(index).text(), unassigned_values, message)
        real_assigned_values = dialog.selected_mapping()
        self.assertDictEqual(real_assigned_values, assigned_values)

        # Click Next
        dialog.pbnNext.click()

        # step 6 of 7 - enter source
        message = "Invalid Next button state in step 6! Disabled while " "source is optional"
        self.assertTrue(dialog.pbnNext.isEnabled(), message)

        message = "Source should be %s" % source
        self.assertEqual(dialog.leSource.text(), source, message)
        message = "Source Url should be %s" % source_url
        self.assertEqual(dialog.leSource_url.text(), source_url, message)
        message = "Source Date should be %s" % source_date.toString("dd-MM-yyyy HH:mm")
        self.assertEqual(dialog.leSource_date.dateTime(), source_date, message)
        message = "Source Scale should be %s" % source_scale
        self.assertEqual(dialog.leSource_scale.text(), source_scale, message)
        dialog.pbnNext.click()

        dialog.pbnCancel.click()

        remove_vector_temp_file(layer.source())
Пример #15
0
 def setUp(self):
     from safe.test.utilities import get_qgis_app
     QGIS_APP, CANVAS, self.iface, PARENT = get_qgis_app(
         qsetting=INASAFE_TEST)
    def test_existing_complex_keywords(self):
        """Test for existing complex keywords in wizard in locale mode."""
        from safe.test.utilities import (clone_shp_layer,
                                         remove_vector_temp_file)
        layer = clone_shp_layer(name='tsunami_polygon',
                                include_keywords=True,
                                source_directory='')

        from safe.test.utilities import get_qgis_app
        # Get Qgis app handle
        # noinspection PyPep8Naming
        _, _, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

        from safe.gui.tools.wizard.wizard_dialog import WizardDialog

        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # select hazard
        self.select_from_list_widget('ancaman',
                                     dialog.step_kw_purpose.lstCategories)
        dialog.pbnNext.click()

        # select volcano
        self.select_from_list_widget(
            'gunung berapi', dialog.step_kw_subcategory.lstSubcategories)
        dialog.pbnNext.click()

        # select volcano categorical unit
        self.select_from_list_widget('Kategori gunung berapi',
                                     dialog.step_kw_unit.lstUnits)
        dialog.pbnNext.click()

        # select GRIDCODE
        self.select_from_list_widget('GRIDCODE',
                                     dialog.step_kw_field.lstFields)
        dialog.pbnNext.click()

        unit = dialog.step_kw_unit.selected_unit()
        default_classes = unit['classes']
        unassigned_values = []  # no need to check actually, not save in file
        assigned_values = {
            'low': ['5.0'],
            'medium': ['3.0', '4.0'],
            'high': ['2.0']
        }
        dialog.step_kw_classify.populate_classified_values(
            unassigned_values, assigned_values, default_classes)
        dialog.pbnNext.click()

        source = 'Source'
        source_scale = 'Source Scale'
        source_url = 'Source Url'
        source_date = QDateTime.fromString('06-12-2015 12:30',
                                           'dd-MM-yyyy HH:mm')

        dialog.step_kw_source.leSource.setText(source)
        dialog.step_kw_source.leSource_scale.setText(source_scale)
        dialog.step_kw_source.leSource_url.setText(source_url)
        dialog.step_kw_source.leSource_date.seDateTime(source_date)
        dialog.pbnNext.click()  # next
        dialog.pbnNext.click()  # finish

        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # step 1 of 7 - select category
        self.check_current_text('ancaman',
                                dialog.step_kw_purpose.lstCategories)

        # Click Next
        dialog.pbnNext.click()

        # step 2 of 7 - select subcategory
        # noinspection PyTypeChecker
        self.check_current_text('gunung berapi',
                                dialog.step_kw_subcategory.lstSubcategories)

        # Click Next
        dialog.pbnNext.click()

        # step 3 of 7 - select volcano units
        self.check_current_text('Kategori gunung berapi',
                                dialog.step_kw_unit.lstUnits)

        # Click Next
        dialog.pbnNext.click()

        # step 4 of 7 - select field
        self.check_current_text('GRIDCODE', dialog.step_kw_field.lstFields)

        # Click Next
        dialog.pbnNext.click()

        for index in range(dialog.step_classify.lstUniqueValues.count()):
            message = ('%s Should be in unassigned values' %
                       dialog.step_classify.lstUniqueValues.item(index).text())
            self.assertIn(
                dialog.step_classify.lstUniqueValues.item(index).text(),
                unassigned_values, message)
        real_assigned_values = dialog.step_classify.selected_mapping()
        self.assertDictEqual(real_assigned_values, assigned_values)

        # Click Next
        dialog.pbnNext.click()

        # step 6 of 7 - enter source
        message = ('Invalid Next button state in step 6! Disabled while '
                   'source is optional')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)

        message = 'Source should be %s' % source
        self.assertEqual(dialog.step_kw_source.leSource.text(), source,
                         message)
        message = 'Source Url should be %s' % source_url
        self.assertEqual(dialog.step_kw_source.leSource_url.text(), source_url,
                         message)
        message = 'Source Date should be %s' % source_date.toString(
            'dd-MM-yyyy HH:mm')
        self.assertEqual(dialog.step_kw_source.leSource_date.dateTime(),
                         source_date, message)
        message = 'Source Scale should be %s' % source_scale
        self.assertEqual(dialog.step_kw_source.leSource_scale.text(),
                         source_scale, message)
        dialog.pbnNext.click()

        dialog.pbnCancel.click()

        remove_vector_temp_file(layer.source())