Пример #1
0
    def test_automatic_file_processing(self):
        # get into a specific folder
        self.controller.load_file(
            os.path.join(unittest_data_path, 'image_001.tif'))
        self.assertEqual(str(self.widget.img_filename_txt.text()),
                         'image_001.tif')
        self.assertEqual(self.controller.working_dir['image'],
                         unittest_data_path)

        # enable autoprocessing:
        QTest.mouseClick(self.widget.autoprocess_cb,
                         QtCore.Qt.LeftButton,
                         pos=QtCore.QPoint(
                             2,
                             self.widget.autoprocess_cb.height() / 2.0))
        self.assertFalse(self.controller._directory_watcher.signalsBlocked())

        self.assertTrue(self.widget.autoprocess_cb.isChecked())
        shutil.copy2(os.path.join(unittest_data_path, 'image_001.tif'),
                     os.path.join(unittest_data_path, 'image_003.tif'))

        self.controller._directory_watcher._file_system_watcher.directoryChanged.emit(
            unittest_data_path)

        self.assertEqual('image_003.tif',
                         str(self.widget.img_filename_txt.text()))
Пример #2
0
    def test_on_radPostprocessing_toggled(self):
        """Test hazard radio button toggle behaviour works"""
        myLayer = makePolygonLayer()
        myDefaults = getDefaults()
        myDialog = KeywordsDialog(PARENT, IFACE, theLayer=myLayer)
        myButton = myDialog.radPostprocessing
        myButton.setChecked(False)
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myMessage = ('Toggling the postprocessing radio did not add a '
                     'category to the keywords list.')
        assert myDialog.getValueForKey(
            'category') == 'postprocessing', myMessage

        myMessage = ('Toggling the postprocessing radio did not add an '
                     'aggregation attribute to the keywords list.')
        assert myDialog.getValueForKey(
            myDefaults['AGGR_ATTR_KEY']) == 'KAB_NAME', myMessage

        myMessage = ('Toggling the postprocessing radio did not add a '
                     'female ratio attribute to the keywords list.')

        assert myDialog.getValueForKey(
            myDefaults['FEM_RATIO_ATTR_KEY']) == \
               myDialog.tr('Use default'), myMessage

        myMessage = ('Toggling the postprocessing radio did not add a '
                     'female ratio default value to the keywords list.')
        assert float(myDialog.getValueForKey(
            myDefaults['FEM_RATIO_KEY'])) == \
               myDefaults['FEM_RATIO'], myMessage
Пример #3
0
    def test_drag_drop_file(self):
        """
        Test dropping multiple files on the tab widget.
        :return:

        http://stackoverflow.com/questions/11500844/qtest-its-possible-to-test-dragdrop
        http://wiki.qt.io/Drag_and_Drop_of_files
        """
        #
        pre_cnt = self.form.documents_tabWidget.count()
        # D&D events take MIME data and for files need URLs
        mime_files = QMimeData()
        files = [QUrl().fromLocalFile(os.path.join(self.data_dir, 'lorem.txt')),
                 QUrl().fromLocalFile(os.path.join(self.data_dir, 'utf8_test.txt'))]
        mime_files.setUrls(files)
        # Drag the files
        action = Qt.MoveAction
        target = self.form.documents_tabWidget.rect().center()
        drag_drop = QDropEvent(target, action, mime_files, Qt.LeftButton, Qt.NoModifier)
        drag_drop.acceptProposedAction()
        # Drop the files
        self.form.documents_tabWidget.dropEvent(drag_drop)
        QTest.qWait(200)  # Give the GUI time to load the data
        # Check the new tabs
        post_cnt = self.form.documents_tabWidget.count()
        self.assertEqual(post_cnt, pre_cnt + len(files))
        self.assertEqual(self.form.documents_tabWidget.widget(1).filename, 'lorem.txt')
        self.assertEqual(self.form.documents_tabWidget.widget(2).filename, 'utf8_test.txt')
Пример #4
0
 def test_esc_on_widget_closes(self):
     QTest.keyClick(core.mainWindow(), Qt.Key_F, Qt.ControlModifier)
     widget = self._findSearchController()._widget
     self.assertFalse(widget.isHidden())
     
     QTest.keyClick(widget, Qt.Key_Escape)
     self.assertTrue(widget.isHidden())
Пример #5
0
    def test_esc_on_widget_closes(self):
        QTest.keyClick(core.mainWindow(), Qt.Key_F, Qt.ControlModifier)
        widget = _findSearchController()._widget
        self.assertFalse(widget.isHidden())

        QTest.keyClick(widget, Qt.Key_Escape)
        self.assertTrue(widget.isHidden())
 def test_reset(self):
     self.assertEqual(self.test_uploader.fileLine.text(), '')
     self.assertEqual(self.test_uploader.dropdowns[0].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.dropdowns[1].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.dropdowns[2].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.dropdowns[3].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.countSlide.value(), 0.0)
     self.assertEqual(self.test_uploader.totalZoom.value(), 1)
     self.assertEqual(str(self.test_uploader.slideID.text()), '')
     self.assertEqual(str(self.test_uploader.otherComments.toPlainText()), '')
     self.assertFalse(self.test_uploader.uploadImage())
     test = uploadSuccesses[0]
     self.test_uploader.fileLine.setText(test[2])
     self.test_uploader.dropdowns[0].setCurrentIndex(test[0][1])
     self.test_uploader.dropdowns[1].setCurrentIndex(test[0][2])
     self.test_uploader.dropdowns[2].setCurrentIndex(test[0][3])
     self.test_uploader.dropdowns[3].setCurrentIndex(test[0][4])
     self.test_uploader.countSlide.setValue(test[0][5])
     self.test_uploader.totalZoom.setValue(test[0][6])
     self.test_uploader.slideID.setText(test[0][7])
     self.test_uploader.otherComments.setText(test[0][8])
     self.assertTrue(self.test_uploader.uploadImage())
     QTest.mouseClick(self.test_uploader.resetButton, Qt.LeftButton)
     self.assertEqual(self.test_uploader.fileLine.text(), '')
     self.assertEqual(self.test_uploader.dropdowns[0].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.dropdowns[1].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.dropdowns[2].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.dropdowns[3].currentText(), '<Please select one>')
     self.assertEqual(self.test_uploader.countSlide.value(), 0.0)
     self.assertEqual(self.test_uploader.totalZoom.value(), 1)
     self.assertEqual(str(self.test_uploader.slideID.text()), '')
     self.assertEqual(str(self.test_uploader.otherComments.toPlainText()), '')
Пример #7
0
    def test_on_pbnAdvanced_toggled(self):
        """Test advanced button toggle behaviour works"""
        makePadangLayer()
        myDialog = KeywordsDialog(PARENT, IFACE)
        myButton = myDialog.pbnAdvanced
        myButton.setChecked(False)
        # noinspection PyArgumentList
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myState = myDialog.grpAdvanced.isHidden()
        myExpectedState = False
        myMessage = ('Advanced options did not become visible when'
                     ' the advanced button was clicked\nGot'
                     '%s\nExpected\n%s\n' % (myState, myExpectedState))

        assert myState == myExpectedState, myMessage

        # Now hide advanced again and test...
        # noinspection PyArgumentList
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myState = myDialog.grpAdvanced.isHidden()
        myExpectedState = True

        myMessage = ('Advanced options did not become hidden when'
                     ' the advanced button was clicked again\nGot'
                     '%s\nExpected\n%s\n' % (myState, myExpectedState))
        assert not myDialog.grpAdvanced.isVisible(), myMessage
Пример #8
0
    def test_gui_to_model_connection(self):
        self.controller.load_data_file(
            os.path.join(unittest_files_path, 'temper_009.spe'))

        self.assertGreater(len(self.model.ds_data_spectrum), 0)
        self.assertGreater(len(self.model.us_data_spectrum), 0)

        ds_x, ds_y = self.model.ds_data_spectrum.data
        us_x, us_y = self.model.us_data_spectrum.data

        QTest.mouseClick(self.widget.load_next_data_file_btn,
                         QtCore.Qt.LeftButton)

        ds_x_1, ds_y_1 = self.model.ds_data_spectrum.data
        us_x_1, us_y_1 = self.model.us_data_spectrum.data

        self.array_almost_equal(ds_x, ds_x_1)
        self.array_not_almost_equal(ds_y, ds_y_1)

        self.array_almost_equal(us_x, us_x_1)
        self.array_not_almost_equal(us_y, us_y_1)

        QTest.mouseClick(self.widget.load_previous_data_file_btn,
                         QtCore.Qt.LeftButton)

        ds_x_2, ds_y_2 = self.model.ds_data_spectrum.data
        us_x_2, us_y_2 = self.model.us_data_spectrum.data

        self.array_almost_equal(ds_x, ds_x_2)
        self.array_almost_equal(ds_y, ds_y_2)
        self.array_almost_equal(us_x, us_x_2)
        self.array_almost_equal(us_y, us_y_2)
Пример #9
0
    def test_connect_actions_with_action_link_and_apply_button(self):
        fun = sys._getframe().f_code.co_name
        print "Run: %s.%s() " % (self.__class__.__name__, fun)
        form = NodeDlg()
        form.ui = Ui_NodeDlg()
        form.ui.applyPushButton = QPushButton(form)
        form.ui.linkDSPushButton = QPushButton(form)
        form.show()
        self.assertEqual(
            form.connectExternalActions(self.myAction,
                                        externalDSLink=self.myAction2), None)
        self.assertEqual(form.node, None)
        self.assertEqual(form.root, None)
        self.assertEqual(form.view, None)
        self.assertEqual(form.subItems, [])
        self.assertTrue(isinstance(form.ui, Ui_NodeDlg))
        self.assertEqual(form.externalApply, self.myAction)
        self.assertEqual(form.externalDSLink, self.myAction2)
        self.performed = False
        self.performed2 = False

        QTest.mouseClick(form.ui.applyPushButton, Qt.LeftButton)
        self.assertEqual(self.performed, True)
        self.assertEqual(self.performed2, False)
        QTest.mouseClick(form.ui.linkDSPushButton, Qt.LeftButton)
        self.assertEqual(self.performed, True)
        self.assertEqual(self.performed2, True)

        self.assertEqual(form.result(), 0)
Пример #10
0
    def test_issue45(self):
        """Points near the edge of a raster hazard layer are interpolated OK"""

        myButton = DOCK.pbnRunStop
        setCanvasCrs(GEOCRS, True)
        setYogyaGeoExtent()

        myMessage = 'Run button was not enabled'
        assert myButton.isEnabled(), myMessage

        myResult, myMessage = setupScenario(
            theHazard='An earthquake in Yogyakarta like in 2006',
            theExposure='OSM Building Polygons',
            theFunction='Earthquake Guidelines Function',
            theFunctionId='Earthquake Guidelines Function')
        assert myResult, myMessage

        # This is the where nosetest sometims hangs when running the
        # guitest suite (Issue #103)
        # The QTest.mouseClick call some times never returns when run
        # with nosetest, but OK when run normally.
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()

        # Check that none of these  get a NaN value:
        assert 'Unknown' in myResult

        myMessage = ('Some buildings returned by Earthquake guidelines '
                     'function '
                     'had NaN values. Result: \n %s' % myResult)
        assert 'Unknown (NaN):	196' not in myResult, myMessage
Пример #11
0
    def test_pyepics_connection_is_working(self):
        try:
            import epics
        except ImportError:
            return
        QTest.mouseClick(self.widget.connect_to_epics_cb,
                         QtCore.Qt.LeftButton,
                         pos=QtCore.QPoint(
                             self.widget.connect_to_epics_cb.width() - 2,
                             self.widget.connect_to_epics_cb.height() / 2))

        self.load_pimax_example_and_setting()

        self.assertAlmostEqual(self.model.ds_temperature,
                               epics.caget('13IDD:ds_las_temp.VAL'))
        self.assertAlmostEqual(self.model.us_temperature,
                               epics.caget('13IDD:us_las_temp.VAL'))

        self.assertAlmostEqual(self.model.ds_roi_max,
                               float(epics.caget('13IDD:dn_t_int.VAL')))
        self.assertAlmostEqual(self.model.us_roi_max,
                               float(epics.caget('13IDD:up_t_int.VAL')))

        self.load_single_frame_file_and_calibration()

        self.assertAlmostEqual(self.model.ds_temperature,
                               epics.caget('13IDD:ds_las_temp.VAL'))
        self.assertAlmostEqual(self.model.us_temperature,
                               epics.caget('13IDD:us_las_temp.VAL'))

        self.assertAlmostEqual(self.model.ds_roi_max,
                               float(epics.caget('13IDD:dn_t_int.VAL')))
        self.assertAlmostEqual(self.model.us_roi_max,
                               float(epics.caget('13IDD:up_t_int.VAL')))
Пример #12
0
    def test_runCategorizedHazardBuildingImpact(self):
        """Flood function runs in GUI with Flood in Jakarta hazard data
            Uses DKI buildings exposure data."""

        myResult, myMessage = setupScenario(
            theHazard='Flood in Jakarta',
            theExposure='DKI buildings',
            theFunction='Be affected',
            theFunctionId='Categorised Hazard Building Impact Function')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        setCanvasCrs(GEOCRS, True)
        setJakartaGeoExtent()

        # Press RUN
        myButton = DOCK.pbnRunStop
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()

        myMessage = 'Result not as expected: %s' % myResult
        # This is the expected number of building might be affected
        assert '535' in myResult, myMessage
        assert '453' in myResult, myMessage
        assert '436' in myResult, myMessage
Пример #13
0
    def test_runFloodPopulationImpactFunction_scaling(self):
        """Flood function runs in GUI with 5x5km population data
           Raster on raster based function runs as expected with scaling."""

        myResult, myMessage = setupScenario(
            theHazard='A flood in Jakarta like in 2007',
            theExposure='People',
            theFunction='Need evacuation',
            theFunctionId='Flood Evacuation Function')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        setCanvasCrs(GEOCRS, True)
        setJakartaGeoExtent()

        # Press RUN
        myButton = DOCK.pbnRunStop
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()

        myMessage = 'Result not as expected: %s' % myResult

        # Check numbers are OK (within expected errors from resampling)
        assert '10484' in myResult, myMessage
        assert '977' in myResult, myMessage  # These are expected impact number
Пример #14
0
    def test_runFloodPopulationImpactFunction(self):
        """Flood function runs in GUI with Jakarta data
           Raster on raster based function runs as expected."""

        # Push OK with the left mouse button
        myButton = DOCK.pbnRunStop

        myMessage = 'Run button was not enabled'
        assert myButton.isEnabled(), myMessage

        myResult, myMessage = setupScenario(
            theHazard='A flood in Jakarta like in 2007',
            theExposure='Penduduk Jakarta',
            theFunction='HKVtest',
            theFunctionId='HKVtest')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        setCanvasCrs(GEOCRS, True)
        setJakartaGeoExtent()

        # Press RUN
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()

        # Check that the number is as what was calculated by
        # Marco Hartman form HKV
        myMessage = 'Result not as expected: %s' % myResult
        # This is the expected impact number
        assert '2480' in myResult, myMessage
Пример #15
0
    def test_checkAggregationAttribute1Attr(self):
        """Aggregation attribute is chosen correctly when there is only
        one attr available."""
        myRunButton = DOCK.pbnRunStop
        myFileList = ['kabupaten_jakarta_singlepart_1_good_attr.shp']
        #add additional layers
        load_layers(myFileList, clear_flag=False, data_directory=TESTDATA)
        myAttrKey = defaults('AGGR_ATTR_KEY')

        # with 1 good aggregation attribute using
        # kabupaten_jakarta_singlepart_1_good_attr.shp
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_layer='kabupaten jakarta singlepart 1 good attr')
        assert myResult, myMessage
        # Press RUN
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
        DOCK.runtimeKeywordsDialog.accept()
        print myAttrKey
        print DOCK.aggregator.attributes
        myAttribute = DOCK.aggregator.attributes[myAttrKey]
        myMessage = ('The aggregation should be KAB_NAME. Found: %s' %
                     myAttribute)
        self.assertEqual(myAttribute, 'KAB_NAME', myMessage)
Пример #16
0
    def test_carbon(self):
        file_path = os.path.join(FILE_BASE, 'carbon_biophysical.json')
        model_ui = modelui.ModelUI(file_path, True)

        # since we need to test both carbon biophysical and valuation, we need
        # to check the checkbox to actually trigger the calculation of
        # sequestration so that the valuation component can be run.
        checkbox = model_ui.allElements['calc_sequestration']
        checkbox.setValue(True)
        #QTest.mouseClick(checkbox, Qt.MouseButton(1))
        QTest.qWait(500)  # so that validation can finish for enabled elements.

        files_to_check = [
            'Output/tot_C_cur.tif', 'Output/tot_C_fut.tif',
            'Output/sequest.tif', 'Intermediate/bio_hwp_cur.tif',
            'Intermediate/bio_hwp_fut.tif', 'Intermediate/c_hwp_cur.tif',
            'Intermediate/c_hwp_fut.tif', 'Intermediate/vol_hwp_cur.tif',
            'Intermediate/vol_hwp_fut.tif'
        ]
        self.click_through_model(model_ui, files_to_check)

        # Now that we've run the carbon biophysical model and checked that all
        # required files exist, do the same steps with carbon valuation.
        file_path = os.path.join(FILE_BASE, 'carbon_valuation.json')
        valuation_ui = modelui.ModelUI(file_path, True)

        # The sequestration file field needs to be set to contain the URI of the
        # sequestration raster output from the biophysical model.
        sequest_element = valuation_ui.allElements['sequest_uri']
        sequest_element.setValue(
            os.path.join(self.workspace, 'Output', 'sequest.tif'))

        # only one output file to check!
        files_to_check = ['Output/value_seq.tif']
        self.click_through_model(valuation_ui, files_to_check)
Пример #17
0
    def test_phase_name_difference_after_modified(self):
        self.main_controller = MainController(use_settings=False)
        self.main_controller.calibration_model.integrate_1d = self.calibration_model.integrate_1d
        self.main_controller.calibration_controller.load_calibration(os.path.join(data_path, 'LaB6_40keV_MarCCD.poni'),
                                                                     update_all=False)
        self.main_controller.calibration_controller.set_calibrant(7)
        self.main_controller.calibration_controller.load_img(os.path.join(data_path, 'LaB6_40keV_MarCCD.tif'))
        self.main_controller.widget.tabWidget.setCurrentIndex(2)
        self.main_controller.widget.integration_widget.tabWidget.setCurrentIndex(3)
        self.main_controller.integration_controller.phase_controller.add_btn_click_callback(
            os.path.join(jcpds_path, 'au_Anderson.jcpds'))

        # Erwin starts the software loads Gold and wants to see what is in the jcpds file, however since he does not
        # change anything the names every are the same...

        self.phase_controller = self.main_controller.integration_controller.phase_controller
        self.jcpds_editor_controller = self.phase_controller.jcpds_editor_controller
        self.jcpds_widget = self.jcpds_editor_controller.widget
        self.jcpds_phase = self.main_controller.phase_model.phases[0]
        self.jcpds_in_spec = self.main_controller.integration_controller.widget.pattern_widget.phases[0]

        self.assertEqual('au_Anderson', self.jcpds_phase.name)
        self.assertEqual('au_Anderson', str(self.phase_controller.widget.phase_tw.item(0, 2).text()))
        self.phase_controller.widget.phase_tw.selectRow(0)
        QTest.mouseClick(self.phase_controller.widget.phase_edit_btn, QtCore.Qt.LeftButton)
        QtGui.QApplication.processEvents()
        self.assertEqual('au_Anderson', self.jcpds_phase.name)
        self.assertEqual('au_Anderson', str(self.phase_controller.widget.phase_tw.item(0, 2).text()))
Пример #18
0
    def test_runEarthQuakeGuidelinesFunction(self):
        """GUI runs with Shakemap 2009 and Padang Buildings"""

        # Push OK with the left mouse button
        clearmyDock()
        loadStandardLayers()
        myButton = DOCK.pbnRunStop
        setCanvasCrs(GEOCRS, True)
        setPadangGeoExtent()
        myMessage = 'Run button was not enabled'
        assert myButton.isEnabled(), myMessage

        myDict = getUiState(DOCK)
        expectDict = {'Hazard': 'Shakemap_Padang_2009',
                        'Exposure': 'Padang_WGS84',
                        'Impact Function': 'Earthquake Guidelines Function',
                        'Run Button Enabled': True}
        myMessage = 'Got unexpected state: %s' % str(myDict)
        assert myDict == expectDict, myMessage

        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()
        # Expected output:
        #Buildings    Total
        #All:    3160
        #Low damage (10-25%):    0
        #Medium damage (25-50%):    0
        #Pre merge of clip on steroids branch:
        #High damage (50-100%):    3160
        # Post merge of clip on steoids branch:
        #High damage (50-100%):    2993
        myMessage = ('Unexpected result returned for Earthquake guidelines'
               'function. Expected:\n "All" count of 2993, '
               'received: \n %s' % myResult)
        assert '2993' in myResult, myMessage
Пример #19
0
    def test_automatic_calibration3(self):
        self.calibration_controller.load_img('Data/CeO2_Oct24_2014_001_0000.tif')
        QTest.mouseClick(self.calibration_view.automatic_peak_num_inc_cb, QtCore.Qt.LeftButton)

        self.assertFalse(self.calibration_view.automatic_peak_num_inc_cb.isChecked())
        self.calibration_controller.search_peaks(517.664434674, 647.529865592)
        self.calibration_controller.search_peaks(667.380513299, 525.252854758)
        self.calibration_controller.search_peaks(671.110095329, 473.571503774)
        self.calibration_controller.search_peaks(592.788872703, 350.495296791)
        self.calibration_controller.search_peaks(387.395462348, 390.987901686)
        self.calibration_controller.search_peaks(367.94835605, 554.290314848)

        self.calibration_controller.view.sv_wavelength_txt.setText('0.406626')
        self.calibration_controller.view.sv_distance_txt.setText('200')
        self.calibration_controller.view.sv_pixel_width_txt.setText('172')
        self.calibration_controller.view.sv_pixel_height_txt.setText('172')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(4)

        start_values = self.calibration_view.get_start_values()
        self.assertAlmostEqual(start_values['wavelength'], 0.406626e-10)
        self.assertAlmostEqual(start_values['pixel_height'], 172e-6)
        self.assertAlmostEqual(start_values['pixel_width'], 172e-6)
        self.calibration_controller.load_calibrant()
        self.assertAlmostEqual(self.calibration_data.calibrant.wavelength, 0.406626e-10)

        QTest.mouseClick(self.calibration_view.integrate_btn, QtCore.Qt.LeftButton)
        calibration_parameter = self.calibration_data.get_calibration_parameter()[0]

        self.assertAlmostEqual(calibration_parameter['dist'], .2086, places=4)
Пример #20
0
    def test_activating_interpolation(self):
        #without interpolation S(Q) should have no values below
        q, sq = self.data.sq_spectrum.data
        self.assertGreater(q[0], 1)

        #when turning interpolation on, it should automatically interpolate sq of to zero and recalculate everything

        QTest.mouseClick(self.interpolation_widget.activate_cb, QtCore.Qt.LeftButton,
                         pos=QtCore.QPoint(2,self.interpolation_widget.activate_cb.height()/2))
        QtGui.QApplication.processEvents()
        self.assertTrue(self.interpolation_widget.activate_cb.isChecked())

        q, sq = self.data.sq_spectrum.data
        self.assertLess(q[0], 1)

        #using a linear interpolation to zero the sum between 0 and 0.5 should be always different from 0:
        self.assertNotAlmostEqual(np.sum(sq[np.where(q<0.4)]), 0)

        #now switching on spline interpolation and test for 0 values below the cutoff
        QTest.mouseClick(self.interpolation_widget.spline_interpolation_rb, QtCore.Qt.LeftButton,
                          pos=QtCore.QPoint(2,self.interpolation_widget.spline_interpolation_rb.height()/2))
        QtGui.QApplication.processEvents()
        self.assertTrue(self.interpolation_widget.spline_interpolation_rb.isChecked())

        q, sq = self.data.sq_spectrum.data
        self.assertAlmostEqual(np.sum(sq[np.where(q<0.5)]), 0)
Пример #21
0
    def testPublishLayersDialog(self):
        # test the content of the GUI
        for idx, ws in enumerate(self.cat.get_workspaces()):
            if ws.name == WORKSPACE:
                wsIdx = idx
            if ws.name == WORKSPACEB:
                wsIdxB = idx
        dialog = PublishLayersDialog(self.cat)
        self.assertEquals(5, dialog.table.columnCount())
        self.assertEquals(8, dialog.table.rowCount())

        # test that cancel return an empty list of layer to publish
        dialog = PublishLayersDialog(self.cat)
        cancelWidget = dialog.buttonBox.button(dialog.buttonBox.Cancel)
        QTest.mouseClick(cancelWidget, Qt.LeftButton)
        self.assertIsNone(dialog.topublish)

        # check that returned layers in the correct workspaces
        # step 1: set first two layer to publish
        dialog.table.item(0, 0).setCheckState(Qt.Checked)
        dialog.table.item(1, 0).setCheckState(Qt.Checked)
        # step 2: set WS where to publish
        dialog.table.cellWidget(0, 1).setCurrentIndex(wsIdx)
        dialog.table.cellWidget(1, 1).setCurrentIndex(wsIdxB)
        # step 3: press ok
        okWidget = dialog.buttonBox.button(dialog.buttonBox.Ok)
        QTest.mouseClick(okWidget, Qt.LeftButton)
        # step 4: last check
        self.assertIsNotNone(dialog.topublish)
        self.assertEquals(WORKSPACE, dialog.topublish[0][1].name)
        self.assertEquals(WORKSPACEB, dialog.topublish[1][1].name)
Пример #22
0
 def testEnterUrl(self):
     webtab = self.mainwin.tab_widget.currentWidget()
     #QTest.keyClicks(webtab.webkit, "LA", Qt.ControlModifier)
     QTest.keyClicks(webtab.address_bar, "http://theospark.net")
     QTest.keyClick(webtab.address_bar, "J", Qt.ControlModifier)
     #QTest.keyClick(webtab.address_bar, Qt.Key_Return)
     self.assertEqual(webtab.address_bar.text(), "http://theospark.net")
Пример #23
0
 def tearDown(self):
   ''' Clean up after the test
   '''
   # Close the form
   self.form.close()
   QTest.qWait(100)
   self.form = None
Пример #24
0
 def test_showHelp(self):
     """Test that help button works"""
     myDialog = KeywordsDialog(PARENT, IFACE)
     myButton = myDialog.buttonBox.button(QtGui.QDialogButtonBox.Help)
     QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
     myMessage = 'Help dialog was not created when help button pressed'
     assert myDialog.helpDialog is not None, myMessage
Пример #25
0
    def Xtest_printMap(self):
        """Test print map, especially on Windows."""

        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='Flood in Jakarta',
            exposure='Essential buildings',
            function='Be affected',
            function_id='Categorised Hazard Building Impact Function')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        set_canvas_crs(GEOCRS, True)
        set_jakarta_extent()

        # Press RUN
        myButton = DOCK.pbnRunStop
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        printButton = DOCK.pbnPrint

        try:
            # noinspection PyCallByClass,PyTypeChecker
            QTest.mouseClick(printButton, QtCore.Qt.LeftButton)
        except OSError:
            LOGGER.debug('OSError')
            # pass
        except Exception, e:
            raise Exception('Exception is not expected, %s' % e)
    def test_create_project_structure_pushButton_creates_project_structure(
            self):
        """testing if using the create_project_pushButton creates the project
        structure
        """

        # create a project
        proj = Project("Test Project")
        proj.save()

        # create a sequence
        seq = Sequence(proj, "Sequence")
        seq.save()

        # create a shot
        shot = Shot(seq, 1)
        shot.save()

        # check if there is no shot folder
        project_path = os.path.join(self.temp_projects_folder,
                                    "Test_Project/Shots/SH001")

        self.assertFalse(os.path.exists(project_path))

        # hit create_structure_pushButton
        dialog = project_manager.MainDialog()

        QTest.mouseClick(dialog.create_project_structure_pushButton,
                         Qt.LeftButton)

        # check if the shot folder has been created
        self.assertTrue(os.path.exists(project_path))
Пример #27
0
    def test_key_not_borked(self):
        rw = RecipesWidget()
        previous = rw.currentRow()

        QTest.keyClick(rw, Qt.Key_Down)

        self.assertEqual(rw.currentRow(), previous + 1)
Пример #28
0
    def test_phase_name_difference_after_modified(self):
        self.main_controller = MainController()
        self.main_controller.calibration_controller.load_calibration('Data/LaB6_p49_40keV_006.poni', update_all=False)
        self.main_controller.calibration_controller.set_calibrant(7)
        self.main_controller.calibration_controller.load_img('Data/LaB6_p49_40keV_006.tif')
        self.main_controller.view.tabWidget.setCurrentIndex(2)
        self.main_controller.view.integration_widget.tabWidget.setCurrentIndex(3)
        self.main_controller.integration_controller.phase_controller.add_phase('Data/jcpds/au_Anderson.jcpds')

        # Erwin starts the software loads Gold and wants to see what is in the jcpds file, however since he does not
        # change anything the names every are the same...

        self.phase_controller = self.main_controller.integration_controller.phase_controller
        self.jcpds_editor_controller = self.phase_controller.jcpds_editor_controller
        self.jcpds_view = self.jcpds_editor_controller.view
        self.jcpds_phase = self.main_controller.phase_data.phases[0]
        self.jcpds_in_spec = self.main_controller.integration_controller.view.spectrum_view.phases[0]

        self.assertEqual('au_Anderson', self.jcpds_phase.name)
        self.assertEqual('au_Anderson', str(self.phase_controller.view.phase_tw.item(0, 2).text()))
        self.phase_controller.view.phase_tw.selectRow(0)
        QTest.mouseClick(self.phase_controller.view.phase_edit_btn, QtCore.Qt.LeftButton)
        QtGui.QApplication.processEvents()
        self.assertEqual('au_Anderson', self.jcpds_phase.name)
        self.assertEqual('au_Anderson', str(self.phase_controller.view.phase_tw.item(0, 2).text()))
Пример #29
0
    def test_postProcessorOutput(self):
        """Check that the post processor does not add spurious report rows."""
        myRunButton = DOCK.pbnRunStop

        # with KAB_NAME aggregation attribute defined in .keyword using
        # kabupaten_jakarta_singlepart.shp
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function')

        # Enable on-the-fly reprojection
        set_canvas_crs(GEOCRS, True)
        set_jakarta_extent()

        assert myResult, myMessage

        # Press RUN
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
        myMessage = 'Spurious 0 filled rows added to post processing report.'
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()
        for line in myResult.split('\n'):
            if 'Entire area' in line:
                myTokens = str(line).split('\t')
                myTokens = myTokens[1:]
                mySum = 0
                for myToken in myTokens:
                    mySum += float(myToken.replace(',', '.'))

                assert mySum != 0, myMessage
    def test_postProcessorOutput(self):
        """Check that the post processor does not add spurious report rows."""
        myRunButton = DOCK.pbnRunStop

        # with KAB_NAME aggregation attribute defined in .keyword using
        # kabupaten_jakarta_singlepart.shp
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function')

        # Enable on-the-fly reprojection
        set_canvas_crs(GEOCRS, True)
        set_jakarta_extent()

        assert myResult, myMessage

        # Press RUN
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
        myMessage = 'Spurious 0 filled rows added to post processing report.'
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()
        for line in myResult.split('\n'):
            if 'Entire area' in line:
                myTokens = str(line).split('\t')
                myTokens = myTokens[1:]
                mySum = 0
                for myToken in myTokens:
                    mySum += float(myToken.replace(',', '.'))

                assert mySum != 0, myMessage
Пример #31
0
    def test_checkAggregationAttributeInKW(self):
        """Aggregation attribute is chosen correctly when present
            in kezwords."""
        myRunButton = DOCK.pbnRunStop
        myAttrKey = defaults('AGGR_ATTR_KEY')

        # with KAB_NAME aggregation attribute defined in .keyword using
        # kabupaten_jakarta_singlepart.shp
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_layer='kabupaten jakarta singlepart',
            aggregation_enabled_flag=True)
        assert myResult, myMessage
        # Press RUN
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
        DOCK.runtimeKeywordsDialog.accept()
        myAttribute = DOCK.aggregator.attributes[myAttrKey]
        myMessage = ('The aggregation should be KAB_NAME. Found: %s' %
                     myAttribute)
        self.assertEqual(myAttribute, 'KAB_NAME', myMessage)
Пример #32
0
    def test_runFloodPopulationImpactFunction_scaling(self):
        """Flood function runs in GUI with 5x5km population data
           Raster on raster based function runs as expected with scaling."""

        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        set_canvas_crs(GEOCRS, True)
        set_jakarta_extent()

        # Press RUN
        myButton = DOCK.pbnRunStop
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page_to_text()

        myMessage = 'Result not as expected: %s' % myResult

        # Check numbers are OK (within expected errors from resampling)
        # These are expected impact number
        assert format_int(10484) in myResult, myMessage
        assert format_int(977) in myResult, myMessage
Пример #33
0
    def test_checkAggregationAttributeNoneAttr(self):
        """Aggregation attribute is chosen correctly when there None in the
            kezwords"""

        myRunButton = DOCK.pbnRunStop
        myFileList = ['kabupaten_jakarta_singlepart_with_None_keyword.shp']
        #add additional layers
        load_layers(myFileList, clear_flag=False, data_directory=TESTDATA)
        myAttrKey = defaults('AGGR_ATTR_KEY')
        # with None aggregation attribute defined in .keyword using
        # kabupaten_jakarta_singlepart_with_None_keyword.shp
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_layer='kabupaten jakarta singlepart with None '
                                'keyword')
        assert myResult, myMessage
        # Press RUN
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
        DOCK.runtimeKeywordsDialog.accept()
        myAttribute = DOCK.aggregator.attributes[myAttrKey]
        myMessage = ('The aggregation should be None. Found: %s' % myAttribute)
        assert myAttribute is None, myMessage
Пример #34
0
    def Xtest_printMap(self):
        """Test print map, especially on Windows."""

        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='Flood in Jakarta',
            exposure='Essential buildings',
            function='Be affected',
            function_id='Categorised Hazard Building Impact Function')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        set_canvas_crs(GEOCRS, True)
        set_jakarta_extent()

        # Press RUN
        myButton = DOCK.pbnRunStop
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        printButton = DOCK.pbnPrint

        try:
            # noinspection PyCallByClass,PyTypeChecker
            QTest.mouseClick(printButton, QtCore.Qt.LeftButton)
        except OSError:
            LOGGER.debug('OSError')
            # pass
        except Exception, e:
            raise Exception('Exception is not expected, %s' % e)
Пример #35
0
    def test_mouse_drag(self):
        """Test setting extents by dragging works.

        This currently fails as QTest does not properly do the mouse
        interactions with the canvas.

        """

        # Click the capture button
        QTest.mouseClick(self.dialog.capture_button, Qt.LeftButton)

        # drag a rect on the canvas
        QTest.mousePress(CANVAS, Qt.LeftButton, pos=QPoint(0, 0), delay=500)
        QTest.mouseRelease(CANVAS,
                           Qt.LeftButton,
                           pos=QPoint(300, 300),
                           delay=-1)

        # on drag the extents selector windows should appear again
        QTest.qWaitForWindowShown(self.dialog)
        # Click ok to dispose of the window again
        ok = self.dialog.button_box.button(QtGui.QDialogButtonBox.Ok)
        QTest.mouseClick(ok, Qt.LeftButton)

        # Check the extent emitted on closing teh dialog is correct
        expected_extent = QgsRectangle(10.0, 10.0, 30.0, 20.0)
        self.assertEqual(self.extent.toString(), expected_extent.toString())
Пример #36
0
    def test_UI_will_not_allow_new_projects_with_no_code(self):
        """testing if the UI will warn the user if no code is supplied
        """
        dialog = project_properties.MainDialog()

        # now edit the project from the UI
        new_name = "Test Project New Name"
        new_code = "test"
        new_fps = 50
        dialog.name_lineEdit.setText(new_name)
        dialog.code_lineEdit.setText(new_code)
        new_client_name = 'Test Client 1'
        dialog.clients_comboBox.lineEdit().setText(new_client_name)
        dialog.fps_spinBox.setValue(new_fps)
        dialog.resolution_comboBox.setCurrentIndex(3)
        preset_name = dialog.resolution_comboBox.currentText()
        resolution_data = conf.resolution_presets[preset_name]
        dialog.active_checkBox.setChecked(False)

        #self.show_dialog(dialog)

        # hit ok
        # this will raise a dialog asking the user to set a proper code value
        QTest.mouseClick(dialog.buttonBox.buttons()[0], Qt.LeftButton)

        self.fail('test can not be implemented')
Пример #37
0
    def test_1(self):
        self.qpart.lines = \
        [ 'func(param,',
          '     "text ( param"))']

        self.qpart.detectSyntax(language = 'Python')

        while self.qpart.isHighlightingInProgress():
            QTest.qWait(20)

        firstBlock = self.qpart.document().firstBlock()
        secondBlock = firstBlock.next()

        bh = BracketHighlighter()

        self._verify(bh.extraSelections(self.qpart, firstBlock, 1),
                     [])

        self._verify(bh.extraSelections(self.qpart, firstBlock, 4),
                     [(4, 5, True), (31, 32, True)])
        self._verify(bh.extraSelections(self.qpart, firstBlock, 5),
                     [(4, 5, True), (31, 32, True)])
        self._verify(bh.extraSelections(self.qpart, secondBlock, 11),
                     [])
        self._verify(bh.extraSelections(self.qpart, secondBlock, 19),
                     [(31, 32, True), (4, 5, True)])
        self._verify(bh.extraSelections(self.qpart, secondBlock, 20),
                     [(31, 32, True), (4, 5, True)])
        self._verify(bh.extraSelections(self.qpart, secondBlock, 21),
                     [(32, 33, False)])
Пример #38
0
    def test_UI_will_create_a_new_Project_instance_if_it_is_not_passed_any(
            self):
        """testing if no Project instance is passed the interface will create
        a new Project instance with the values
        """

        dialog = project_properties.MainDialog()

        # now edit the project from the UI
        new_name = "Test Project New Name"
        new_fps = 50
        dialog.name_lineEdit.setText(new_name)
        new_client_name = 'Test Client 1'
        dialog.clients_comboBox.lineEdit().setText(new_client_name)
        dialog.fps_spinBox.setValue(new_fps)
        dialog.resolution_comboBox.setCurrentIndex(3)
        preset_name = dialog.resolution_comboBox.currentText()
        resolution_data = conf.resolution_presets[preset_name]
        dialog.active_checkBox.setChecked(False)

        # hit ok
        QTest.mouseClick(dialog.buttonBox.buttons()[0], Qt.LeftButton)

        # get the project
        new_project = dialog.project

        # now check the data
        self.assertEqual(new_project.name, new_name)
        self.assertEqual(new_project.client.name, new_client_name)
        self.assertEqual(new_project.fps, new_fps)
        self.assertEqual(new_project.width, resolution_data[0])
        self.assertEqual(new_project.height, resolution_data[1])
        self.assertEqual(new_project.pixel_aspect, resolution_data[2])
        self.assertEqual(new_project.active, False)
Пример #39
0
    def test_createGUI_doc_ui_text(self):
        fun = sys._getframe().f_code.co_name
        print "Run: %s.%s() " % (self.__class__.__name__, fun)
        rank = self.__rnd.randint(1, 6)
        lengths = [self.__rnd.randint(1, 100) for r in range(rank)]
        form = DimensionsDlg()
        self.assertEqual(form.rank, 0)
        self.assertEqual(form.lengths, [])
        self.assertEqual(form.subItems, ["dim"])
        self.assertTrue(isinstance(form.ui, Ui_DimensionsDlg))

        self.assertEqual(form.createGUI(), None)
        form.show()

        #        QTest.keyClicks(form.ui.rankSpinBox, str(rank))
        form.ui.rankSpinBox.setValue(rank)

        self.assertEqual(form.ui.rankSpinBox.value(), rank)
        self.assertEqual(form.ui.dimTableWidget.columnCount(), 1)
        self.assertEqual(form.ui.dimTableWidget.rowCount(), rank)

        for r in range(rank):
            it = form.ui.dimTableWidget.item(r, 0)
            self.assertEqual(it.text(), '')

        cancelWidget = form.ui.buttonBox.button(form.ui.buttonBox.Cancel)
        QTest.mouseClick(cancelWidget, Qt.LeftButton)

        self.assertEqual(form.result(), 0)

        self.assertEqual(form.rank, rank)
        self.assertEqual(form.lengths, [None] * rank)
Пример #40
0
        def continueFunc(dialog):
            page = dialog._pageForItem["Navigator"]
            self.assertEqual(page.lExecuteError.text(),
                             ('You are trying to use etags from the Emacs package, but it is not supported. '
                             'Use Exuberant Ctags.'))

            QTest.keyClick(dialog, Qt.Key_Enter)
Пример #41
0
    def test_on_radPostprocessing_toggled(self):
        """Test hazard radio button toggle behaviour works"""
        myLayer = makePolygonLayer()
        myDefaults = defaults()
        myDialog = KeywordsDialog(PARENT, IFACE, layer=myLayer)
        myButton = myDialog.radPostprocessing
        myButton.setChecked(False)
        # noinspection PyArgumentList
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myMessage = ('Toggling the postprocessing radio did not add a '
                     'category to the keywords list.')
        assert myDialog.get_value_for_key(
            'category') == 'postprocessing', myMessage

        myMessage = ('Toggling the postprocessing radio did not add an '
                     'aggregation attribute to the keywords list.')
        assert myDialog.get_value_for_key(
            myDefaults['AGGR_ATTR_KEY']) == 'KAB_NAME', myMessage

        myMessage = ('Toggling the postprocessing radio did not add a '
                     'female ratio attribute to the keywords list.')

        assert myDialog.get_value_for_key(
            myDefaults['FEM_RATIO_ATTR_KEY']) == myDialog.tr('Use default'), \
            myMessage

        myMessage = ('Toggling the postprocessing radio did not add a '
                     'female ratio default value to the keywords list.')
        assert float(myDialog.get_value_for_key(
            myDefaults['FEM_RATIO_KEY'])) == myDefaults['FEM_RATIO'], myMessage
Пример #42
0
    def testPublishLayersDialog(self):
        # test the content of the GUI
        for idx, ws in enumerate(self.cat.get_workspaces()):
            if ws.name == WORKSPACE:
                wsIdx = idx
            if ws.name == WORKSPACEB:
                wsIdxB = idx
        dialog = PublishLayersDialog(self.cat)
        self.assertEquals(4, dialog.table.columnCount())
        self.assertEquals(8, dialog.table.rowCount())

        # test that cancel return an empty list of layer to publish
        dialog = PublishLayersDialog(self.cat)
        cancelWidget = dialog.buttonBox.button(dialog.buttonBox.Cancel)
        QTest.mouseClick(cancelWidget, Qt.LeftButton)
        self.assertIsNone(dialog.topublish)

        # check that returned layers in the correct workspaces
        # step 1: set first two layer to publish
        dialog.table.item(0,0).setCheckState(Qt.Checked)
        dialog.table.item(1,0).setCheckState(Qt.Checked)
        # step 2: set WS where to publish
        dialog.table.cellWidget(0,1).setCurrentIndex(wsIdx)
        dialog.table.cellWidget(1,1).setCurrentIndex(wsIdxB)
        # step 3: press ok
        okWidget = dialog.buttonBox.button(dialog.buttonBox.Ok)
        QTest.mouseClick(okWidget, Qt.LeftButton)
        # step 4: last check
        self.assertIsNotNone(dialog.topublish)
        self.assertEquals(WORKSPACE, dialog.topublish[0][1].name)
        self.assertEquals(WORKSPACEB, dialog.topublish[1][1].name)
Пример #43
0
 def test_showHelp(self):
     """Test that help button works"""
     myDialog = KeywordsDialog(PARENT, IFACE)
     myButton = myDialog.buttonBox.button(QtGui.QDialogButtonBox.Help)
     QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
     myMessage = 'Help dialog was not created when help button pressed'
     assert myDialog.helpDialog is not None, myMessage
Пример #44
0
    def test_saving_spectrum(self):
        # the widget has to be shown to be able to save the image:
        self.integration_widget.show()

        # Tests if the spectrum save procedures is are working for all fileendings
        def save_spectra_test_for_size_and_delete(self):
            self.integration_spectrum_controller.save_pattern(os.path.join(data_path, 'Test_spec.xy'))
            self.integration_spectrum_controller.save_pattern(os.path.join(data_path, 'Test_spec.chi'))
            self.integration_spectrum_controller.save_pattern(os.path.join(data_path, 'Test_spec.dat'))
            self.integration_spectrum_controller.save_pattern(os.path.join(data_path, 'Test_spec.png'))
            self.integration_spectrum_controller.save_pattern(os.path.join(data_path, 'Test_spec.svg'))

            self.assertTrue(os.path.exists(os.path.join(data_path, 'Test_spec.xy')))
            self.assertTrue(os.path.exists(os.path.join(data_path, 'Test_spec.chi')))
            self.assertTrue(os.path.exists(os.path.join(data_path, 'Test_spec.dat')))
            self.assertTrue(os.path.exists(os.path.join(data_path, 'Test_spec.png')))
            self.assertTrue(os.path.exists(os.path.join(data_path, 'Test_spec.svg')))

            self.assertGreater(os.stat(os.path.join(data_path, 'Test_spec.xy')).st_size, 1)
            self.assertGreater(os.stat(os.path.join(data_path, 'Test_spec.chi')).st_size, 1)
            self.assertGreater(os.stat(os.path.join(data_path, 'Test_spec.dat')).st_size, 1)
            self.assertGreater(os.stat(os.path.join(data_path, 'Test_spec.png')).st_size, 1)
            self.assertGreater(os.stat(os.path.join(data_path, 'Test_spec.svg')).st_size, 1)

            os.remove(os.path.join(data_path, 'Test_spec.xy'))
            os.remove(os.path.join(data_path, 'Test_spec.chi'))
            os.remove(os.path.join(data_path, 'Test_spec.dat'))
            os.remove(os.path.join(data_path, 'Test_spec.png'))
            os.remove(os.path.join(data_path, 'Test_spec.svg'))

        save_spectra_test_for_size_and_delete(self)
        QTest.mouseClick(self.integration_spectrum_controller.widget.spec_q_btn, QtCore.Qt.LeftButton)
        save_spectra_test_for_size_and_delete(self)
        QTest.mouseClick(self.integration_spectrum_controller.widget.spec_d_btn, QtCore.Qt.LeftButton)
        save_spectra_test_for_size_and_delete(self)
Пример #45
0
 def test_showHelp(self):
     """Test that help button works"""
     myDialog = ImpactFunctionsDoc(PARENT)
     myButton = myDialog.myButtonBox.button(QtGui.QDialogButtonBox.Help)
     QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
     myMessage = "Help dialog was not created when help button pressed"
     assert myDialog.helpDialog is not None, myMessage
Пример #46
0
    def test_changing_supersampling_amount_integrating_to_cake_with_mask(self):
        # Edith opens the program, calibrates everything and looks in to the options menu. She sees that there is a
        # miraculous parameter called supersampling. It is currently set to 1 which seems to be normal
        self.assertEqual(self.integration_widget.supersampling_sb.value(), 1)

        # then she sets it to two and she sees that the number of spectrum bin changes and that the spectrum looks
        # smoother

        # values before:
        px1 = self.calibration_model.spectrum_geometry.pixel1
        px2 = self.calibration_model.spectrum_geometry.pixel2

        img_shape = self.img_model.img_data.shape

        self.integration_widget.supersampling_sb.setValue(2)
        self.assertEqual(self.calibration_model.spectrum_geometry.pixel1, 0.5 * px1)
        self.assertEqual(self.calibration_model.spectrum_geometry.pixel2, 0.5 * px2)
        self.assertEqual(self.calibration_model.cake_geometry.pixel1, px1)
        self.assertEqual(self.calibration_model.cake_geometry.pixel2, px2)

        self.assertEqual(self.img_model.img_data.shape[0], 2 * img_shape[0])
        self.assertEqual(self.img_model.img_data.shape[1], 2 * img_shape[1])

        self.mask_model.load_mask(os.path.join(data_path, 'test.mask'))
        QTest.mouseClick(self.integration_widget.img_mask_btn, QtCore.Qt.LeftButton)
        QTest.mouseClick(self.integration_widget.img_mode_btn, QtCore.Qt.LeftButton)
Пример #47
0
    def test_1(self):
        # replace 'foo' with 'UUH' in opened and not opened file
        openedFile = self.createFile('openedFile.txt', 'the text contains foo bar\nand\nfew\nmore lines')
        openedFile.qutepart.cursorPosition = (3, 2)

        notOpenedFilePath = os.path.join(self.TEST_FILE_DIR, 'not_openedFile.txt')
        with open(notOpenedFilePath, 'w') as file_:
            file_.write('this file also contains foo bar')

        self.keyClick(Qt.Key_R, Qt.ShiftModifier | Qt.ControlModifier)
        self.keyClicks('foo')
        self.keyClick(Qt.Key_Tab)
        self.keyClicks('UUHHH')
        self.keyClick(Qt.Key_Enter)
        QTest.qWait(500)  # searching
        self.keyClick(Qt.Key_A, Qt.AltModifier)
        QTest.qWait(500)  # replacing

        with open(notOpenedFilePath) as file_:
            self.assertEqual(file_.read(), 'this file also contains UUHHH bar')

        self.assertEqual(openedFile.qutepart.text, 'the text contains UUHHH bar\nand\nfew\nmore lines')
        self.assertEqual(openedFile.qutepart.cursorPosition, (3, 2))

        self.assertTrue(openedFile.qutepart.document().isModified())
        with open(openedFile.filePath()) as file_:
            self.assertEqual(file_.read(), 'the text contains foo bar\nand\nfew\nmore lines')

        openedFile.saveFile()
        with open(openedFile.filePath()) as file_:
            self.assertEqual(file_.read(), 'the text contains UUHHH bar\nand\nfew\nmore lines\n')
Пример #48
0
 def testGroupDialogWithEmptyName(self):
     dialog = LayerGroupDialog(self.cat)
     dialog.nameBox.setText("")
     okWidget = dialog.buttonBox.button(dialog.buttonBox.Ok)
     QTest.mouseClick(okWidget, Qt.LeftButton)
     self.assertIsNone(dialog.group)
     self.assertEquals("QLineEdit{background: yellow}", dialog.nameBox.styleSheet())
Пример #49
0
    def test_runFloodPopulationImpactFunction_scaling(self):
        """Flood function runs in GUI with 5x5km population data
           Raster on raster based function runs as expected with scaling."""

        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function')
        assert myResult, myMessage

        # Enable on-the-fly reprojection
        set_canvas_crs(GEOCRS, True)
        set_jakarta_extent()

        # Press RUN
        myButton = DOCK.pbnRunStop
        # noinspection PyCallByClass,PyTypeChecker
        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page_to_text()

        myMessage = 'Result not as expected: %s' % myResult

        # Check numbers are OK (within expected errors from resampling)
        # These are expected impact number
        assert format_int(10484) in myResult, myMessage
        assert format_int(977) in myResult, myMessage
Пример #50
0
    def test_mouse_drag(self):
        """Test setting extents by dragging works.

        This currently fails as QTest does not properly do the mouse
        interactions with the canvas.

        """
        # Imported here because it is not available in OSX QGIS bundle
        # pylint: disable=redefined-outer-name
        from PyQt4.QtTest import QTest

        # Click the capture button
        QTest.mouseClick(self.dialog.capture_button, Qt.LeftButton)

        # drag a rect on the canvas
        QTest.mousePress(CANVAS, Qt.LeftButton, pos=QPoint(0, 0), delay=500)
        QTest.mouseRelease(
            CANVAS, Qt.LeftButton,
            pos=QPoint(300, 300),
            delay=-1)

        # on drag the extents selector windows should appear again
        QTest.qWaitForWindowShown(self.dialog)
        # Click ok to dispose of the window again
        ok = self.dialog.button_box.button(QtGui.QDialogButtonBox.Ok)
        QTest.mouseClick(ok, Qt.LeftButton)

        # Check the extent emitted on closing teh dialog is correct
        expected_extent = QgsRectangle(10.0, 10.0, 30.0, 20.0)
        self.assertEqual(self.extent.toString(), expected_extent.toString())
Пример #51
0
    def test_runEarthQuakeGuidelinesFunction(self):
        """GUI runs with Shakemap 2009 and Padang Buildings"""

        # Push OK with the left mouse button

        myButton = DOCK.pbnRunStop
        setCanvasCrs(GEOCRS, True)
        setPadangGeoExtent()
        myMessage = 'Run button was not enabled'
        assert myButton.isEnabled(), myMessage

        #QTest.keyClick(DOCK.cboHazard, QtCore.Qt.Key_Down)
        #QTest.keyClick(DOCK.cboHazard, QtCore.Qt.Key_Enter)
        #
        #QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Down)
        #QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Enter)

        # Hazard layer
        myIndex = DOCK.cboHazard.findText('Padang 2009 scenario')
        assert myIndex != -1, 'Padang 2009 scenario hazard layer not found'
        DOCK.cboHazard.setCurrentIndex(myIndex)

        # Exposure layer
        myIndex = DOCK.cboExposure.findText('Padang_WGS84')
        myMessage = ('Could not find layer Padang_WGS84:\n'
                     '%s' % (combosToString(DOCK)))
        assert myIndex != -1, myMessage
        DOCK.cboExposure.setCurrentIndex(myIndex)

        # Impact function
        myIndex = DOCK.cboFunction.findText('Earthquake Guidelines Function')
        msg = ('Earthquake Guidelines function not '
               'found: ' + combosToString(DOCK))
        assert myIndex != -1, msg
        DOCK.cboFunction.setCurrentIndex(myIndex)

        myDict = getUiState(DOCK)
        myExpectedDict = {'Hazard': 'Padang 2009 scenario',
                          'Exposure': 'Padang_WGS84',
                          'Impact Function': 'Earthquake Guidelines Function',
                          'Run Button Enabled': True}
        myMessage = 'Got:\n %s\nExpected:\n%s\n%s' % (
                        myDict, myExpectedDict, combosToString(DOCK))
        assert myDict == myExpectedDict, myMessage

        QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
        myResult = DOCK.wvResults.page().currentFrame().toPlainText()
        # Expected output:
        #Buildings    Total
        #All:    3160
        #Low damage (10-25%):    0
        #Medium damage (25-50%):    0
        #Pre merge of clip on steroids branch:
        #High damage (50-100%):    3160
        # Post merge of clip on steoids branch:
        #High damage (50-100%):    2993
        myMessage = ('Unexpected result returned for Earthquake guidelines'
               'function. Expected:\n "All" count of 2993, '
               'received: \n %s' % myResult)
        assert '2993' in myResult, myMessage
Пример #52
0
    def test_enter(self):
        R = SigRecorder()
        self.F.fileChanged.connect(R.string)

        #self.F.ui.fileBox.setFocus(Qt.MouseFocusReason)
        QTest.keyClicks(self.F.ui.fileBox, "testing")
        QTest.keyClick(self.F.ui.fileBox, Qt.Key_Enter)

        self.assertEqual('testing', str(self.F.file))
        self.assertEqual(['testing'], R.S)
        R.clear()

        self.assertEqual(1, self.F.ui.fileBox.count())
        self.assertEqual('testing', self.F.ui.fileBox.itemText(0))

        for n in range(7):
            QTest.keyClick(self.F.ui.fileBox, Qt.Key_Backspace)
        QTest.keyClicks(self.F.ui.fileBox, "another")
        QTest.keyClick(self.F.ui.fileBox, Qt.Key_Enter)

        self.assertEqual('another', str(self.F.file))
        self.assertEqual(['another'], R.S)

        self.assertEqual(2, self.F.ui.fileBox.count())
        self.assertEqual('another', self.F.ui.fileBox.itemText(0))
        self.assertEqual('testing', self.F.ui.fileBox.itemText(1))
 def test_monte_carlo(self):
     FORM.on_action_monte_carlo()
     
     monte_carlo = FORM.centralWidget.tab_montecarlo
     
     
     monte_carlo.edit_monte_tasks.setText('2')
     monte_carlo.edit_monte_sigma.setText('0.2')
     
     li_widget = monte_carlo.list_monte_mtr
     my_item = li_widget.item(1)
     li_widget.setItemSelected(my_item, True)
     my_item2 = li_widget.item(2)
     li_widget.setItemSelected(my_item2, True)
     
     
     
     okWidget = monte_carlo.button_monte_compute
     QTest.mouseClick(okWidget, Qt.LeftButton)
     
     assert monte_carlo.groupBox_monte_buttons.title() == '2 materials in memory'
     
     save_widget = monte_carlo.button_monte_save
     QTest.mouseClick(save_widget, Qt.LeftButton)
     
     file_name = '/home/albert/riskflow_test_data/test_mock/MonteCarlo/00/00_ini.ini'
     result = os.path.isfile(file_name)
     assert result == True
Пример #54
0
def crashtest():
    global allWidgets
    try:
        gc.disable()
        actions = [
            createWidget,
            #setParent,
            forgetWidget,
            showWidget,
            processEvents,
            #raiseException,
            #addReference,
        ]

        thread = WorkThread()
        thread.start()

        while True:
            try:
                action = randItem(actions)
                action()
                print('[%d widgets alive, %d zombie]' %
                      (len(allWidgets), len(allWidgets) - len(widgets)))
            except KeyboardInterrupt:
                print("Caught interrupt; send another to exit.")
                try:
                    for i in range(100):
                        QTest.qWait(100)
                except KeyboardInterrupt:
                    thread.terminate()
                    break
            except:
                sys.excepthook(*sys.exc_info())
    finally:
        gc.enable()