예제 #1
0
    def test_rename_context_menu_makes_line_editable(self):
        plot_numbers = [0, 1, 2]
        self.view.set_plot_list(plot_numbers)

        # Clicking on the QTableWidget in QTest seems unreliable
        # so we fake the selection instead,
        self.view.get_currently_selected_plot_number = mock.Mock(
            return_value=1)
        self.view.context_menu.actions()[3].trigger()

        name_widget = self.view.table_widget.cellWidget(1, Column.Name)
        self.assertFalse(name_widget.line_edit.isReadOnly())
        self.assertTrue(name_widget.rename_button.isChecked())
예제 #2
0
    def test_creates_run_selector_with_child_view(self, patched_presenter,
                                                  patched_model):
        view = self._make_mock_view()
        parent_view = self._make_mock_parent_view()

        AddRunsPagePresenter(sum_runs_model=mock.Mock(),
                             view=view,
                             parent_view=parent_view)

        patched_model.assert_called_once_with(mock.ANY)
        patched_presenter.assert_called_once_with(mock.ANY,
                                                  patched_model.return_value,
                                                  mock.ANY, mock.ANY, view)
예제 #3
0
    def setUp(self):
        self.load = mock.create_autospec(load_utils.LoadUtils, spec_set=True)
        self.fft = mock.create_autospec(fft_presenter.FFTPresenter,
                                        spec_Set=True)
        self.maxent = mock.create_autospec(maxent_presenter.MaxEntPresenter,
                                           spec_set=True)

        # create widget
        self.widget = transform_widget.TransformWidget(self.load, FFTWidget,
                                                       MaxEntWidget)
        # create the view
        self.view = mock.create_autospec(transform_view.TransformView,
                                         spec_set=False)
        self.view.getView = mock.Mock()
        self.view.getMethods = mock.Mock(return_value=["FFT", "MaxEnt"])
        self.view.hideAll = mock.Mock()
        self.view.showMethod = mock.Mock()
        self.view.selection = mock.create_autospec(
            transform_selection_view.TransformSelectionView, spec_set=True)
        self.view.selection.changeMethodSignal = mock.Mock()
        # set the mocked view to the widget
        self.widget.mockWidget(self.view)
 def test_call_freq_workspace_names(self):
     self.context.get_names_of_frequency_domain_workspaces_to_fit = mock.Mock(
     )
     workspace_list = self.context.get_names_of_workspaces_to_fit(
         runs='19489',
         group_and_pair='fwd, bwd',
         phasequad=True,
         freq="All")
     self.context.get_names_of_frequency_domain_workspaces_to_fit.assert_called_once_with(
         runs='19489',
         group_and_pair='fwd, bwd',
         phasequad=True,
         frequency_type="All")
    def test_creates_summation_settings_with_child_view(self):
        self.view.summation_settings_view.return_value = \
            self.fake_summation_settings_view
        make_summation_settings_presenter = \
            mock.Mock(return_value=self._summation_settings_presenter)

        self.presenter = self._make_presenter_with_child_presenters(
            self._just_use_run_selector_presenter(),
            make_summation_settings_presenter)

        call_args = make_summation_settings_presenter.call_args[0]
        self.assertEqual(self.fake_summation_settings_view, call_args[0])
        self.assertEqual(self.view, call_args[1])
    def test_load_current_run_displays_error_if_incrementing_past_current_run(self):
        # set up current run
        workspace = self.create_fake_workspace()
        self.load_utils_patcher.load_workspace_from_filename = mock.Mock(return_value=(workspace, 1234, "1234.nxs",
                                                                                       False))
        self.view.set_run_edit_text("1234")
        self.presenter.handle_load_current_run()
        self.wait_for_thread(self.presenter._load_thread)

        self.presenter.handle_increment_run()
        self.wait_for_thread(self.presenter._load_thread)

        self.assertEqual(self.view.warning_popup.call_count, 1)
예제 #7
0
 def setUp(self):
     self.gui.plot_window = None
     self.gui.used_colors = {}
     self.gui.element_lines = {}
     self.has_raise_ValueError_been_called_once = False
     self.gui.detectors = mock.Mock()
     self.gui.detectors.detectors = [mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock()]
     self.gui.lines = mock.Mock()
예제 #8
0
    def setUp(self):
        self.view = mock.Mock(spec=SliceViewerView)
        self.view.dimensions = mock.Mock()
        self.view.norm_opts = mock.Mock()

        self.model = mock.Mock(spec=SliceViewerModel)
        self.model.get_ws = mock.Mock()
        self.model.get_data = mock.Mock()
    def test_that_loading_multiple_files_from_browse_ignores_loads_which_throw(self):
        workspace = self.create_fake_workspace(1)

        files = ["C:/dir1/file1.nxs", "C:/dir2/file2.nxs", "C:/dir2/file3.nxs"]
        self.view.show_file_browser_and_return_selection = mock.Mock(return_value=files)
        load_return_values = [(workspace, 1234 + i, filename, False) for i, filename in enumerate(files)]
        self.load_utils_patcher.side_effect = iter(IteratorWithException(load_return_values, [1]))

        self.presenter.on_browse_button_clicked()
        self.wait_for_thread(self.presenter._load_thread)

        self.assertEqual(self.model.loaded_filenames, ["C:/dir1/file1.nxs", "C:/dir2/file3.nxs"])
        self.assertEqual(self.model.loaded_runs, [[1234], [1236]])
        self.assertEqual(self.view.get_file_edit_text(), "C:/dir1/file1.nxs;C:/dir2/file3.nxs")
예제 #10
0
    def test_passes_correct_config_when_summation_requested(
            self, patched_run_selector):
        # Ensure we know the type that was returned by the constructor
        run_selector_mock = mock.Mock()
        patched_run_selector.return_value = run_selector_mock

        ConfigService["defaultsave.directory"] = "someDir/"
        run_summation = mock.Mock()

        presenter = AddRunsPagePresenter(run_summation, self.view,
                                         self.parent_view)
        presenter._get_filename_manager = mock.Mock(
            return_value=MockedOutAddRunsFilenameManager())

        mocked_run_selector = mock.MagicMock()
        mocked_run_selector.has_any_runs.return_value = True
        run_number_mock = mock.Mock()
        run_number_mock.display_name.return_value = 3
        mocked_run_selector.__iter__.return_value = [run_number_mock]

        run_selector_mock.run_selection.return_value = mocked_run_selector
        self.view.sum.emit()
        run_summation.assert_called_with(mock.ANY, mock.ANY, 'LOQ00003-add')
예제 #11
0
    def test_bad_run_name_gets_file_no_from_file(self):
        # Make sure we don't log before the mock gets injected as it will warn during init
        file_info = SANSFileInformationMock(file_name="0")
        logger_mock = mock.Mock()
        file_info.logger = logger_mock

        filename = "NoDigits"
        # Should get the mock's returned name - overriding classes should call hdf5
        expected = int(file_info._get_run_number_from_file(""))
        # Call init again now we have injected our mock
        file_info.__init__(file_name=filename)

        self.assertEqual(expected, file_info.get_run_number())
        logger_mock.warning.assert_called_once_with(mock.ANY)
 def setUp(self):
     self.parent_presenter = create_run_tab_presenter_mock(
         use_fake_state=False)
     self.view = create_mock_beam_centre_tab()
     self.WorkHandler = mock.MagicMock()
     self.BeamCentreModel = mock.MagicMock()
     self.SANSCentreFinder = mock.MagicMock()
     self.presenter = BeamCentrePresenter(
         self.parent_presenter,
         self.SANSCentreFinder,
         work_handler=self.WorkHandler,
         beam_centre_model=self.BeamCentreModel)
     self.presenter.connect_signals = mock.Mock()
     self.presenter.set_view(self.view)
예제 #13
0
    def test_that_rkh_and_nx_can_sas_are_enabled_if_switching_to_non_memory_mode_and_in_2D_reduction_mode(
            self):
        """This tests that nx_can_sas and rkh file type buttons are enabled if switching to file or both mode, when
         reduction dimensionality is 1D, but can sas is not enabled"""

        view = mock.MagicMock()

        view.output_mode_memory_radio_button.isChecked = mock.Mock(
            return_value=False)
        view.reduction_dimensionality_1D.isChecked = mock.Mock(
            return_value=False)
        view.can_sas_checkbox.setEnabled = mock.Mock()
        view.nx_can_sas_checkbox.setEnabled = mock.Mock()
        view.rkh_checkbox.setEnabled = mock.Mock()

        self.presenter.set_view(view)

        self.presenter.on_output_mode_changed()
        self.presenter._view.can_sas_checkbox.setEnabled.assert_not_called()
        self.presenter._view.nx_can_sas_checkbox.setEnabled.assert_called_once_with(
            True)
        self.presenter._view.rkh_checkbox.setEnabled.assert_called_once_with(
            True)
예제 #14
0
    def test_model_is_cleared_correctly(self, load_utils_mock):
        files = [r'EMU00019489.nxs', r'EMU00019490.nxs', r'EMU00019491.nxs']
        load_return_vals = [([1, 2, 3], filename, 19489 + i) for i, filename in enumerate(files)]

        load_utils_mock.load_workspace_from_filename = mock.Mock()
        load_utils_mock.load_workspace_from_filename.side_effect = load_return_vals

        self.model.loadData(files)
        self.model.execute()
        self.assertEqual(len(self.model.loaded_runs), 3)
        self.model.clear_loaded_data()
        self.assertEqual(self.model.loaded_workspaces, [])
        self.assertEqual(self.model.loaded_filenames, [])
        self.assertEqual(self.model.loaded_runs, [])
예제 #15
0
    def test_calls_for_default_save_change(self):
        onValueChangedMock = mock.Mock()

        class FakeConfigObserver(ConfigObserver):
            def onValueChanged(self, name, new, old):
                onValueChangedMock(name, new, old)

        observer = FakeConfigObserver()
        ConfigService.Instance().setString("defaultsave.directory",
                                           "/dev/null")
        onValueChangedMock.assert_any_call("defaultsave.directory", mock.ANY,
                                           mock.ANY)
        onValueChangedMock.assert_any_call("datasearch.directories", mock.ANY,
                                           mock.ANY)
 def setUp(self):
     # patch away getting a real icon as it can hit a race condition when running tests
     # in parallel
     patcher = mock.patch('mantidqt.dialogs.spectraselectordialog.get_icon')
     self._mock_get_icon = patcher.start()
     self._mock_get_icon.return_value = QIcon()
     self.addCleanup(patcher.stop)
     if self._single_spec_ws is None:
         self.__class__._single_spec_ws = WorkspaceFactory.Instance(
         ).create("Workspace2D", NVectors=1, XLength=1, YLength=1)
         self.__class__._multi_spec_ws = WorkspaceFactory.Instance().create(
             "Workspace2D", NVectors=200, XLength=1, YLength=1)
     SpectraSelectionDialog._check_number_of_plots = mock.Mock(
         return_value=True)
    def test_plot_logic_force_new(self, mock_plot):

        workspace_list = [
            'MUSR62260; Group; bottom; Asymmetry; MA',
            'MUSR62261; Group; bottom; Asymmetry; MA'
        ]
        workspace_object_list = [
            self.create_workspace(workspace) for workspace in workspace_list
        ]
        subplot_title = 'MUSR62260 bottom'
        self.model.set_x_lim = mock.Mock()
        self.model.plot(workspace_list, subplot_title, 'Time', False,
                        'Muon Analysis')

        mock_plot.assert_called_once_with(mock.ANY,
                                          wksp_indices=[0],
                                          window_title=subplot_title,
                                          errors=True,
                                          plot_kwargs={
                                              'distribution': True,
                                              'autoscale_on_update': False
                                          })

        self.assertEquals(self.model.plot_figure.clear.call_count, 0)
        self.assertEquals(self.model.set_x_lim.call_count, 1)
        workspace_list = [
            'MUSR62260; Group; top; Asymmetry; MA',
            'MUSR62261; Group; top; Asymmetry; MA'
        ]
        workspace_object_list = [
            self.create_workspace(workspace) for workspace in workspace_list
        ]
        subplot_title = 'MUSR62260 top'

        self.model.plot(workspace_list, subplot_title, 'Time', True,
                        'Muon Analysis')
        self.assertEquals(self.model.plot_figure.clear.call_count, 1)
        self.assertEquals(self.model.set_x_lim.call_count, 2)

        self.assertEquals(mock_plot.call_count, 2)
        mock_plot.assert_any_call(mock.ANY,
                                  wksp_indices=[0],
                                  fig=self.model.plot_figure,
                                  window_title=subplot_title,
                                  plot_kwargs={
                                      'distribution': True,
                                      'autoscale_on_update': False
                                  },
                                  errors=True)
예제 #18
0
 def setUp(self):
     self.parent_presenter = create_run_tab_presenter_mock(
         use_fake_state=False)
     self.parent_presenter._file_information = mock.MagicMock()
     self.parent_presenter._file_information.get_instrument = mock.MagicMock(
         return_value=SANSInstrument.LARMOR)
     self.view = create_mock_beam_centre_tab()
     self.WorkHandler = mock.MagicMock()
     self.BeamCentreModel = mock.MagicMock()
     self.SANSCentreFinder = mock.MagicMock()
     self.presenter = BeamCentrePresenter(self.parent_presenter,
                                          self.WorkHandler,
                                          self.BeamCentreModel,
                                          self.SANSCentreFinder)
     self.presenter.connect_signals = mock.Mock()
예제 #19
0
    def test_calls_for_default_save_change(self):
        onPropertyValueChangedMock = mock.Mock()

        class FakeConfigPropertyObserver(ConfigPropertyObserver):
            def __init__(self, property):
                super(FakeConfigPropertyObserver, self).__init__("defaultsave.directory")

            def onPropertyValueChanged(self, new, old):
                onPropertyValueChangedMock(new, old)

        new_save_directory_value = "/dev/null"
        observer = FakeConfigPropertyObserver("defaultsave.directory")
        self.config.setString("defaultsave.directory", new_save_directory_value)
        self.config.setString("algorithms.retained", "60")
        onPropertyValueChangedMock.assert_called_once_with(new_save_directory_value, mock.ANY)
예제 #20
0
    def setUp(self):
        self._model = mock.create_autospec(PeriodicTableModel)
        self.view = PeriodicTableView()
        self.presenter = PeriodicTablePresenter(
            self.view, self._model)
        self.presenter.is_selected = mock.Mock()
        self.mock_elem = mock.create_autospec(PeriodicTableItem)
        self.mock_elem.symbol = mock.Mock()

        self.view.ptable = mock.create_autospec(silxPT)
        self.view.ptable.getSelection = mock.Mock(
            return_value=self.mock_elem)
        self.view.ptable.isElementSelected = mock.Mock(
            return_value=True)

        self.view.on_table_lclicked = mock.Mock()
        self.view.on_table_rclicked = mock.Mock()
        self.view.on_table_changed = mock.Mock()

        self.view.unreg_on_table_lclicked = mock.Mock()
        self.view.unreg_on_table_rclicked = mock.Mock()
        self.view.unreg_on_table_changed = mock.Mock()

        self.presenter.view = self.view
    def test_that_clicking_guess_alpha_triggers_correct_slot_with_correct_row_supplied(
            self):
        # Guess alpha functionality must be implemented by parent widgets. So we just check that the
        # design for implementing this works (via an Observable in the presenter)
        self.presenter.handle_add_pair_button_clicked()
        self.presenter.handle_add_pair_button_clicked()
        self.presenter.guessAlphaNotifier.notify_subscribers = mock.Mock()

        self.view.pairing_table.cellWidget(1, 5).clicked.emit(True)

        self.assertEqual(
            self.presenter.guessAlphaNotifier.notify_subscribers.call_count, 1)
        self.assertEqual(
            self.presenter.guessAlphaNotifier.notify_subscribers.
            call_args_list[0][0][0], ["pair_2", "my_group_0", "my_group_1"])
    def setUp(self):
        # Store an empty widget to parent all the views, and ensure they are deleted correctly
        self.obj = QWidget()

        setup_context_for_tests(self)

        self.data_context.instrument = 'EMU'
        self.view = LoadRunWidgetView(parent=self.obj)
        self.model = LoadRunWidgetModel(self.loaded_data, self.context)
        self.presenter = LoadRunWidgetPresenter(self.view, self.model)

        self.model.load_workspace_from_filename = mock.Mock(return_value=([1, 2, 3], "currentRun.nxs", 1234, False))
        self.view.warning_popup = mock.Mock()
        self.view.disable_load_buttons = mock.Mock()
        self.view.enable_load_buttons = mock.Mock()

        self.presenter.set_current_instrument("EMU")

        fileUtils.get_current_run_filename = mock.Mock(return_value="EMU0001234.nxs")

        patcher = mock.patch('Muon.GUI.Common.load_run_widget.load_run_model.load_utils')
        self.addCleanup(patcher.stop)
        self.load_utils_patcher = patcher.start()
        self.load_utils_patcher.exception_message_for_failed_files.return_value = ''
예제 #23
0
    def test_base_name_not_reset_after_set_by_user(self):
        run_summation = mock.Mock()
        presenter = self._make_presenter(run_summation)
        self._update_selection_model(
            self._make_mock_run_selection_from_paths(['4', '5', '6']))

        user_out_file_name = 'Output'
        self.view.out_file_name.return_value = user_out_file_name
        self.view.outFileChanged.emit()

        self._update_selection_model(
            self._make_mock_run_selection_from_paths(['4', '5']))
        self.view.sum.emit()
        self.assertEqual(user_out_file_name,
                         self._base_file_name_arg(run_summation))
    def test_single_file_from_browse_loaded_into_model_and_view_in_single_file_mode(self):
        workspace = self.create_fake_workspace(1)

        self.mock_browse_button_to_return_files(["C:/dir1/file1.nxs"])
        self.mock_model_to_load_workspaces([workspace], [1234], ["C:/dir1/file1.nxs"])
        self.view.set_file_edit = mock.Mock()

        self.presenter.on_browse_button_clicked()
        self.wait_for_thread(self.presenter._load_thread)

        self.assertEqual(self.model.loaded_filenames, ["C:/dir1/file1.nxs"])
        self.assertEqual(self.model.loaded_workspaces, [workspace])
        self.assertEqual(self.model.loaded_runs, [[1234]])

        self.view.set_file_edit.assert_called_once_with("C:/dir1/file1.nxs", mock.ANY)
예제 #25
0
 def test_update_view_calls_correct_setters_with_correct_values(self):
     presenter = self._generate_presenter()
     new_view_mock = mock.Mock(get_selected_ax_name=lambda: "My Axes: (0, 0)")
     ax = self.fig.get_axes()[0]
     setters = ['set_title', 'set_xlower_limit', 'set_xupper_limit',
                'set_ylower_limit', 'set_yupper_limit', 'set_xlabel',
                'set_ylabel', 'set_xscale', 'set_yscale']
     expected_vals = [self.title.encode('unicode_escape').decode(),
                      ax.get_xlim()[0], ax.get_xlim()[1], ax.get_ylim()[0],
                      ax.get_ylim()[1], self.x_label, self.y_label,
                      self.x_scale, self.y_scale]
     with mock.patch.object(presenter, 'view', new_view_mock):
         presenter.update_view()
         for setter, value in zip(setters, expected_vals):
             getattr(new_view_mock, setter).assert_called_once_with(value)
    def test_single_file_from_user_input_loaded_into_model_and_view_in_single_file_mode(self):
        workspace = self.create_fake_workspace(1)

        self.view.set_file_edit = mock.Mock()
        self.mock_model_to_load_workspaces([workspace], [1234], ["C:/dir1/file1.nxs"])
        self.mock_user_input_text("C:/dir1/file1.nxs")

        self.presenter.handle_file_changed_by_user()
        self.wait_for_thread(self.presenter._load_thread)

        self.assertEqual(self.model.loaded_filenames, ["C:/dir1/file1.nxs"])
        self.assertEqual(self.model.loaded_workspaces, [workspace])
        self.assertEqual(self.model.loaded_runs, [[1234]])

        self.view.set_file_edit.assert_called_once_with("C:/dir1/file1.nxs", mock.ANY)
예제 #27
0
    def test_destroy_all(self):
        num = 0
        self.add_manager(num)

        other_mock_fig = mock.Mock()
        other_mock_manager = MockFigureManager(num + 1)
        other_mock_manager.canvas.figure = other_mock_fig
        GlobalFigureManager.set_active(other_mock_manager)

        self.assertEqual(2, len(GlobalFigureManager._activeQue))
        self.assertEqual(2, len(GlobalFigureManager.figs))

        GlobalFigureManager.destroy_all()
        self.assertEqual(0, len(GlobalFigureManager._activeQue))
        self.assertEqual(0, len(GlobalFigureManager.figs))
예제 #28
0
    def test_simul_fit_by_selector_updates_fit_specifier_correctly_when_simul_fit_type_changes(
            self):
        self.view.simul_fit_checkbox.setChecked(True)
        self.view.simul_fit_by_combo.setCurrentIndex(
            SIMUL_FIT_BY_COMBO_MAP["Run"])
        self.presenter._get_selected_groups_and_pairs = mock.Mock(
            return_value=["fwd", "bwd"])

        # now switch to group/pair
        self.view.simul_fit_by_combo.setCurrentIndex(
            SIMUL_FIT_BY_COMBO_MAP["Group/Pair"])

        self.assertEqual(str(self.view.simul_fit_by_specifier.itemText(0)),
                         "fwd")
        self.assertEqual(str(self.view.simul_fit_by_specifier.itemText(1)),
                         "bwd")
예제 #29
0
    def test_passes_correct_config_when_summation_requested(self):
        ConfigService["defaultsave.directory"] = "someDir/"
        run_summation = mock.Mock()

        self.presenter = self._make_presenter(
            run_summation,
            self._capture_on_change_callback(self.run_selector_presenter),
            self._just_use_summation_settings_presenter())

        fake_run_selection = self._make_mock_run_selection_from_paths(['3'])
        self.run_selector_presenter.run_selection.return_value = fake_run_selection
        self._on_model_updated(fake_run_selection)
        self.view.sum.emit()
        run_summation.assert_called_with(fake_run_selection,
                                         self._summation_settings,
                                         'LOQ00003-add')
예제 #30
0
    def test_that_uncheck_on_removed_blocks_signals_and_calls_right_function(self):
        rem_lines = ['line Total', 'line Prompt', 'line 3']
        calls = [mock.call(True), mock.call(False)]
        self.gui.uncheck_detectors_if_no_line_plotted = mock.Mock()
        tmp_detectors = copy.deepcopy(self.gui.detectors.detectors)
        for detector in self.gui.detectors.detectors:
            detector.isChecked.return_value = False

        self.gui.uncheck_on_removed(rem_lines)

        self.gui.lines.total.blockSignals.assert_has_calls(calls)
        self.gui.lines.prompt.blockSignals.assert_has_calls(calls)
        self.gui.lines.delayed.blockSignals.assert_has_calls([])
        self.assertEqual(1, self.gui.uncheck_detectors_if_no_line_plotted.call_count)

        self.gui.detectors.detectors = tmp_detectors