Exemple #1
0
    def test_options_widget(self):
        w = textimport.CSVOptionsWidget()
        schanged = QSignalSpy(w.optionsChanged)
        sedited = QSignalSpy(w.optionsEdited)
        w.setDialect(csv.excel())
        self.assertEqual(len(schanged), 1)
        self.assertEqual(len(sedited), 0)
        w.setSelectedEncoding("iso8859-1")

        self.assertEqual(len(schanged), 2)
        self.assertEqual(len(sedited), 0)

        d = w.dialect()
        self.assertEqual(d.delimiter, csv.excel.delimiter)
        self.assertEqual(d.doublequote, csv.excel.doublequote)
        self.assertEqual(w.encoding(), "iso8859-1")

        d = textimport.Dialect("a", "b", "c", True, True)
        w.setDialect(d)

        cb = w.findChild(QComboBox, "delimiter-combo-box")
        self.assertEqual(cb.currentIndex(),
                         textimport.CSVOptionsWidget.DelimiterOther)
        le = w.findChild(QWidget, "custom-delimiter-edit")
        self.assertEqual(le.text(), "a")

        cb = w.findChild(QWidget, "quote-edit-combo-box")
        self.assertEqual(cb.currentText(), "b")
        d1 = w.dialect()
        self.assertEqual(d.delimiter, d1.delimiter)
        self.assertEqual(d.quotechar, d1.quotechar)
    def wait_for_completion(self, manager):
        spy = QSignalSpy(manager.allDownloaded)
        self.assertTrue(spy.isValid())
        manager.start()

        received = spy.wait(timeout=500)
        self.assertTrue(received)
Exemple #3
0
    def wait_for(self,
                 timeout=None,
                 *,
                 override_waited_for=False,
                 do_skip=False,
                 **kwargs):
        """Wait until a given value is found in the data.

        Keyword arguments to this function get interpreted as attributes of the
        searched data. Every given argument is treated as a pattern which
        the attribute has to match against.

        Args:
            timeout: How long to wait for the message.
            override_waited_for: If set, gets triggered by previous messages
                                 again.
            do_skip: If set, call pytest.skip on a timeout.

        Return:
            The matched line.
        """
        __tracebackhide__ = True

        if timeout is None:
            if do_skip:
                timeout = 2000
            elif 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

        # If there is none, wait for the message
        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                return match
Exemple #4
0
    def testReset(self):
        widget = self._widget
        table = widget._table
        spy = QSignalSpy(widget.load_metadata_sgn)
        spy_count = 0

        cfg = ["efg", "2020-03-03 03:03:03", "efg setup"]
        widget._insertSetupToList(cfg)

        for row in range(2):
            for i in range(2):
                table.itemDoubleClicked.emit(table.item(row, i))
                widget._meta.load_snapshot.assert_called_with(
                    table.item(row, i).text())
                widget._meta.load_snapshot.reset_mock()
                spy_count += 1
                self.assertEqual(spy_count, len(spy))
            table.itemDoubleClicked.emit(table.item(row, 2))
            widget._meta.load_snapshot.assert_not_called()
            self.assertEqual(spy_count, len(spy))

        # test reset
        spy = QSignalSpy(widget.load_metadata_sgn)
        widget._reset_btn.clicked.emit()
        widget._meta.load_snapshot.assert_called_with(widget.DEFAULT)
        self.assertEqual(1, len(spy))
    def test_finished_state(self):
        worker = Worker()
        worker.configure(destination=self.image_net_home,
                         number_of_images=5,
                         images_per_category=10)

        change_spy = QSignalSpy(worker.stateChanged)
        worker.start_download()

        while not worker.complete:
            received = change_spy.wait(500)

        worker = Worker()

        self.assertEqual(worker.download_state, 'finished')
        self.assertTrue(worker.complete)

        worker = Worker()
        expected_path = os.path.abspath(self.image_net_home)

        state_data = json.loads(worker.state_data_json)
        self.assertEqual(state_data['downloadPath'], expected_path)
        self.assertEqual(state_data['numberOfImages'], 5)
        self.assertEqual(state_data['imagesPerCategory'], 10)
        self.assertEqual(state_data['timeLeft'], '0 seconds')
        self.assertEqual(state_data['imagesLoaded'], 5)
        self.assertEqual(state_data['failures'], 0)
        self.assertEqual(state_data['failedUrls'], [])
        self.assertEqual(state_data['progress'], 1.0)
Exemple #6
0
    def _wait_for_new(self, timeout, do_skip, **kwargs):
        """Wait for a log message which doesn't exist yet.

        Called via wait_for.
        """
        __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout)
        message = kwargs.get('message', None)
        if message is not None:
            elided = quteutils.elide(repr(message), 50)
            self._log("\n----> Waiting for {} in the log".format(elided))

        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                if message is not None:
                    self._log("----> found it")
                return match
Exemple #7
0
    def _wait_for_new(self, timeout, do_skip, **kwargs):
        """Wait for a log message which doesn't exist yet.

        Called via wait_for.
        """
        __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout)
        message = kwargs.get('message', None)
        if message is not None:
            elided = quteutils.elide(repr(message), 100)
            self._log("\n----> Waiting for {} in the log".format(elided))

        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                if message is not None:
                    self._log("----> found it")
                return match

        raise quteutils.Unreachable
Exemple #8
0
    def test_normal(self, qtbot, tmpdir, ipc_server, mocker, has_cwd):
        ipc_server.listen()
        spy = QSignalSpy(ipc_server.got_args)
        raw_spy = QSignalSpy(ipc_server.got_raw)
        error_spy = QSignalSpy(ipc_server.got_invalid_data)

        with qtbot.waitSignal(ipc_server.got_args, raising=True, timeout=5000):
            with tmpdir.as_cwd():
                if not has_cwd:
                    m = mocker.patch('qutebrowser.misc.ipc.os')
                    m.getcwd.side_effect = OSError
                sent = ipc.send_to_running_instance('qute-test', ['foo'], None)

        assert sent

        assert not error_spy
        expected_cwd = str(tmpdir) if has_cwd else ''

        assert len(spy) == 1
        assert spy[0] == [['foo'], '', expected_cwd]

        assert len(raw_spy) == 1
        assert len(raw_spy[0]) == 1
        raw_expected = {
            'args': ['foo'],
            'target_arg': None,
            'version': qutebrowser.__version__,
            'protocol_version': ipc.PROTOCOL_VERSION
        }
        if has_cwd:
            raw_expected['cwd'] = str(tmpdir)
        parsed = json.loads(raw_spy[0][0].decode('utf-8'))
        assert parsed == raw_expected
Exemple #9
0
    def wait_for(self, timeout=None, *, override_waited_for=False, **kwargs):
        """Wait until a given value is found in the data.

        Keyword arguments to this function get interpreted as attributes of the
        searched data. Every given argument is treated as a pattern which
        the attribute has to match against.

        Args:
            timeout: How long to wait for the message.
            override_waited_for: If set, gets triggered by previous messages
                                 again.

        Return:
            The matched line.
        """
        __tracebackhide__ = True
        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

        # If there is none, wait for the message
        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                raise WaitForTimeout("Timed out after {}ms waiting for "
                                     "{!r}.".format(timeout, kwargs))

            for args in spy:
                assert len(args) == 1
                line = args[0]

                matches = []

                for key, expected in kwargs.items():
                    value = getattr(line, key)
                    matches.append(self._match_data(value, expected))

                if all(matches):
                    # If we waited for this line, chances are we don't mean the
                    # same thing the next time we use wait_for and it matches
                    # this line again.
                    line.waited_for = True
                    return line
Exemple #10
0
    def wait_for(self, timeout=None, *, override_waited_for=False, **kwargs):
        """Wait until a given value is found in the data.

        Keyword arguments to this function get interpreted as attributes of the
        searched data. Every given argument is treated as a pattern which
        the attribute has to match against.

        Args:
            timeout: How long to wait for the message.
            override_waited_for: If set, gets triggered by previous messages
                                 again.

        Return:
            The matched line.
        """
        __tracebackhide__ = True
        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

        # If there is none, wait for the message
        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                raise WaitForTimeout("Timed out after {}ms waiting for "
                                     "{!r}.".format(timeout, kwargs))

            for args in spy:
                assert len(args) == 1
                line = args[0]

                matches = []

                for key, expected in kwargs.items():
                    value = getattr(line, key)
                    matches.append(self._match_data(value, expected))

                if all(matches):
                    # If we waited for this line, chances are we don't mean the
                    # same thing the next time we use wait_for and it matches
                    # this line again.
                    line.waited_for = True
                    return line
Exemple #11
0
    def testStartStop(self):
        start_spy = QSignalSpy(self.gui.start_sgn)
        stop_spy = QSignalSpy(self.gui.stop_sgn)

        # -------------------------------------------------------------
        # test when the start action button is clicked
        # -------------------------------------------------------------

        start_action = self.gui._tool_bar.actions()[0]
        stop_action = self.gui._tool_bar.actions()[1]

        start_action.trigger()

        # test a ctrl widget own by the ImageToolWindow
        azimuthal_integ_ctrl_widget = self.gui._image_tool._azimuthal_integ_1d_view._ctrl_widget
        geometry_ctrl_widget = self.gui._image_tool._geometry_view._ctrl_widget
        pump_probe_ctrl_widget = self.gui.pump_probe_ctrl_widget
        histogram_ctrl_widget = self.gui.histogram_ctrl_widget
        source_ctrl_widget = self.gui._source_cw

        azimuthal_integ_ctrl_widget.updateMetaData.assert_called_once()
        pump_probe_ctrl_widget.updateMetaData.assert_called_once()
        histogram_ctrl_widget.updateMetaData.assert_called_once()
        source_ctrl_widget.updateMetaData.assert_called_once()

        self.assertEqual(1, len(start_spy))

        pump_probe_ctrl_widget.onStart.assert_called_once()
        histogram_ctrl_widget.onStart.assert_called_once()
        azimuthal_integ_ctrl_widget.onStart.assert_called_once()

        self.assertFalse(start_action.isEnabled())
        self.assertTrue(stop_action.isEnabled())
        self.assertFalse(source_ctrl_widget._con_view.isEnabled())
        self.assertFalse(geometry_ctrl_widget.isEnabled())

        self.assertTrue(self.train_worker.running)
        self.assertTrue(self.pulse_worker.running)

        # -------------------------------------------------------------
        # test when the stop action button is clicked
        # -------------------------------------------------------------

        stop_action.trigger()

        pump_probe_ctrl_widget.onStop.assert_called_once()
        histogram_ctrl_widget.onStop.assert_called_once()
        azimuthal_integ_ctrl_widget.onStop.assert_called_once()

        self.assertEqual(1, len(stop_spy))

        self.assertTrue(start_action.isEnabled())
        self.assertFalse(stop_action.isEnabled())
        self.assertTrue(source_ctrl_widget._con_view.isEnabled())
        self.assertTrue(geometry_ctrl_widget.isEnabled())

        self.assertFalse(self.train_worker.running)
        self.assertFalse(self.pulse_worker.running)
Exemple #12
0
    def wait_for(self, timeout=None, **kwargs):
        """Wait until a given value is found in the data.

        Keyword arguments to this function get interpreted as attributes of the
        searched data. Every given argument is treated as a pattern which
        the attribute has to match against.

        Return:
            The matched line.
        """
        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        # Search existing messages
        for line in self._data:
            matches = []

            for key, expected in kwargs.items():
                value = getattr(line, key)
                matches.append(self._match_data(value, expected))

            if all(matches) and not line.waited_for:
                # If we waited for this line, chances are we don't mean the
                # same thing the next time we use wait_for and it matches
                # this line again.
                line.waited_for = True
                return line

        # If there is none, wait for the message
        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                raise WaitForTimeout("Timed out after {}ms waiting for "
                                     "{!r}.".format(timeout, kwargs))

            for args in spy:
                assert len(args) == 1
                line = args[0]

                matches = []

                for key, expected in kwargs.items():
                    value = getattr(line, key)
                    matches.append(self._match_data(value, expected))

                if all(matches):
                    # If we waited for this line, chances are we don't mean the
                    # same thing the next time we use wait_for and it matches
                    # this line again.
                    line.waited_for = True
                    return line
Exemple #13
0
    def wait_for(self, timeout=None, *, override_waited_for=False,
                 do_skip=False, **kwargs):
        """Wait until a given value is found in the data.

        Keyword arguments to this function get interpreted as attributes of the
        searched data. Every given argument is treated as a pattern which
        the attribute has to match against.

        Args:
            timeout: How long to wait for the message.
            override_waited_for: If set, gets triggered by previous messages
                                 again.
            do_skip: If set, call pytest.skip on a timeout.

        Return:
            The matched line.
        """
        __tracebackhide__ = True

        if timeout is None:
            if do_skip:
                timeout = 2000
            elif 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

        # If there is none, wait for the message
        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                return match
Exemple #14
0
 def test_monitor_times(self):
     app = QtWidgets.QApplication(sys.argv)
     status = DogStatus()
     status_spy = QSignalSpy(status.pooping.status_changed)
     time_spy = QSignalSpy(status.pooping.time_changed)
     status.start()
     self.assertEqual(len(time_spy), 0)
     status_emitted = status_spy.wait(1)
     self.assertTrue(status_emitted)
     self.assertEqual(len(time_spy), 1)
 def setUp(self):
     self.dataNavigatorModel = DataNavigatorModel()
     self.dataNavigatorView = DataNavigatorView(
         dataModel=self.dataNavigatorModel)
     self.spyViewItemClicked = QSignalSpy(self.dataNavigatorView.clicked)
     #        self.spyModelItemChanged = QSignalSpy(self.dataNavigatorModel.itemChanged[QStandardItem*])
     self.spyModelDataChanged = QSignalSpy(
         self.dataNavigatorModel.dataChanged)
     self.spyModelRowsInserted = QSignalSpy(
         self.dataNavigatorModel.rowsInserted)
Exemple #16
0
 def test_case3(self):
     try:
         for i in range(9):
             QTest.mouseClick(gv.window.toggleButton, Qt.LeftButton)
             QTest.qWait(100)
         spy = QSignalSpy(gv.window.notify)
         t = spy.wait(timeout=10000)
         print(f"Spy signal: {t}")
     except Exception as e:
         self.fail(e)
Exemple #17
0
    def test_changedFontFamily(self):
        signalspy = QSignalSpy(self.ui.fontComboBox.currentIndexChanged)
        self.ui.fontComboBox.setCurrentIndex(2)

        # current connections for a signal
        self.assertEqual(
            self.ui.fontComboBox.receivers(
                self.ui.fontComboBox.currentIndexChanged), 1)

        self.assertEqual(len(signalspy), 1)
        self.assertTrue(signalspy.isValid())

        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.bloodTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.renalTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.liverTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.thyroidTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.electrolyteTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.lipidTextEdit.fontFamily())

        self.ui.fontComboBox.setCurrentIndex(3)

        self.assertTrue(signalspy.isValid())
        self.assertEqual(len(signalspy), 2)

        self.assertEqual(
            self.ui.fontComboBox.receivers(
                self.ui.fontComboBox.currentIndexChanged), 1)

        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.bloodTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.renalTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.liverTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.thyroidTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.electrolyteTextEdit.fontFamily())
        self.assertEqual(self.ui.fontComboBox.currentText(),
                         self.ui.lipidTextEdit.fontFamily())

        for signal in signalspy:
            print(
                "That was argument's value during setCurrentIndex (for font family change) execution: ",
                signal[0], "\n")
            print("So the font family changed to ",
                  self.ui.fontComboBox.itemText(signal[0]), "\n")
    def test_wait_until_download_complete(self):
        worker = Worker()
        worker.configure(destination=self.image_net_home,
                         number_of_images=10,
                         images_per_category=5)

        change_spy = QSignalSpy(worker.stateChanged)
        worker.start_download()

        while not worker.complete:
            received = change_spy.wait(500)

        self.assertEqual(worker.download_state, 'finished')
        self.assertTrue(worker.complete)
Exemple #19
0
    def receive_message(self, sniffer):
        if len(sniffer.messages) > 0:
            return sniffer.messages.pop(0)

        spy = QSignalSpy(sniffer.message_sniffed)
        if spy.wait(self.project_manager.simulator_timeout_ms):
            try:
                return sniffer.messages.pop(0)
            except IndexError:
                self.log_message("Could not receive message")
                return None
        else:
            self.log_message("Receive timeout")
            return None
Exemple #20
0
    def receive_message(self, sniffer):
        if len(sniffer.messages) > 0:
            return sniffer.messages.pop(0)

        spy = QSignalSpy(sniffer.message_sniffed)
        if spy.wait(self.project_manager.simulator_timeout_ms):
            try:
                return sniffer.messages.pop(0)
            except IndexError:
                self.log_message("Could not receive message")
                return None
        else:
            self.log_message("Receive timeout")
            return None
    def _assert_signal_emitted(self, signal):
        app_state = AppState()
        manager = DownloadManager(app_state)

        conf = DownloadConfiguration(number_of_images=5,
                                     images_per_category=10,
                                     download_destination=self.image_net_home)
        app_state.set_configuration(conf)
        signal = getattr(manager, signal)
        spy = QSignalSpy(signal)
        manager.start()
        received = spy.wait(timeout=500)
        self.assertTrue(received)

        self.stop_the_thread(manager)
 def testSetRowName1(self):
     self.model.initializeDataRows(COUNTER_OPTS_2, COUNTER_NAMES_2)
     spy = QSignalSpy(self.model.dataChanged)
     ROW_NAME_1 = "ISetThis"
     ROW_NAME_2 = "ThisToo"
     ROW_NAME_3 = "CantDoThis"
     self.model.setRowName(0, ROW_NAME_1)
     dataChangedData = spy[0][0]
     with self.assertRaises(IndexError):
         spy[1]
     self.assertEqual(dataChangedData.row(), 0)
     self.assertEqual(dataChangedData.column(), 0)
     self.assertEqual(dataChangedData.data(), ROW_NAME_1)
     logger.debug("Contents of QSignalSpy %s %s %s" %
                  (spy[0][0].row(), spy[0][0].column(), spy[0][0].data()))
     self.model.setRowName(1, ROW_NAME_2)
     dataChangedData = spy[1][0]
     with self.assertRaises(IndexError):
         spy[2]
     self.assertEqual(dataChangedData.row(), 1)
     self.assertEqual(dataChangedData.column(), 0)
     self.assertEqual(dataChangedData.data(), ROW_NAME_2)
     self.model.setRowName(2, ROW_NAME_2)
     with self.assertRaises(IndexError):
         self.model.setRowName(3, ROW_NAME_2)
     with self.assertRaises(IndexError):
         self.model.setRowName(4, ROW_NAME_2)
     self.assertEqual(len(spy), 3)
    def testImageCtrlWidget(self):
        widget = self.image_tool._image_ctrl_widget
        proc = self.pulse_worker._image_proc
        assembler = self.pulse_worker._assembler

        spy = QSignalSpy(self.image_tool._mediator.reset_image_level_sgn)
        widget.auto_level_btn.clicked.emit()
        self.assertEqual(1, len(spy))

        # test default
        proc.update()
        self.assertEqual((-1e5, 1e5), proc._threshold_mask)

        assembler.update()
        self.assertEqual(False, assembler._mask_tile)

        # test set new value
        widget.threshold_mask_le.setText("1, 10")
        proc.update()
        self.assertEqual((1, 10), proc._threshold_mask)

        widget.mask_tile_cb.setChecked(True)
        assembler.update()
        self.assertEqual(True, assembler._mask_tile)

        # test loading meta data
        mediator = widget._mediator
        mediator.onImageThresholdMaskChange((-100, 10000))
        mediator.onImageMaskTileEdgeChange(False)
        widget.loadMetaData()
        self.assertEqual("-100, 10000", widget.threshold_mask_le.text())
        self.assertEqual(False, widget.mask_tile_cb.isChecked())
Exemple #24
0
 def testScanSelected(self):
     selectedScan = 5
     specFile = os.path.join(self.dataPath, FLUORESCENCE_FILE)
     spyLoaded = QSignalSpy(self.scanBrowser.scanLoaded)
     specData = SpecDataFile(specFile)
     self.scanBrowser.loadScans(specData.scans)
     self.assertEqual(len(spyLoaded), 1)
     self.assertEqual(len(self.spySelected), 0)
     self.scanBrowser.setCurrentScan(selectedScan)
     self.assertEqual(len(spyLoaded), 1)
     self.assertEqual(len(self.spySelected), 1)
     self.assertEqual(self.scanBrowser.getCurrentScan(), '6')
     self.scanBrowser.filterByScanTypes(specData.scans, SCAN_TYPES[2])
     self.assertEqual(len(spyLoaded), 2)
     self.assertEqual(len(self.spySelected), 1)
     # Doesn't register a selection change since row has not changed
     self.scanBrowser.setCurrentScan(selectedScan)
     self.assertEqual(len(spyLoaded), 2)
     self.assertEqual(len(self.spySelected), 1)
     self.assertEqual(self.scanBrowser.getCurrentScan(), '12')
     # Register a selection change since row changed
     self.scanBrowser.setCurrentScan(selectedScan + 1)
     self.assertEqual(len(spyLoaded), 2)
     self.assertEqual(len(self.spySelected), 2)
     self.assertEqual(self.scanBrowser.getCurrentScan(), '13')
Exemple #25
0
 def testPlayAllowedCard(self):
     spy = QSignalSpy(self._hand_panel.cardPlayed)
     self._hand_panel.setCards(self._cards)
     card = random.choice(self._cards)
     self._hand_panel.setAllowedCards((card, ))
     self._click_card_helper(card)
     self.assertEqual(spy[0][0], card)
    def testSmartStringLineEdit(self):
        widget = SmartStringLineEdit("abc")
        spy = QSignalSpy(widget.value_changed_sgn)

        # set an empty string
        widget.clear()
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual(0, len(spy))

        # set a space
        widget.clear()
        QTest.keyClicks(widget, ' ')
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual(0, len(spy))

        # a string started with a space is allowed
        widget.clear()
        QTest.keyClicks(widget, ' Any')
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual(1, len(spy))

        # a Karabo device ID
        widget.clear()
        QTest.keyClicks(widget, 'SA3_XTD10_MONO/MDL/PHOTON_ENERGY')
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual(2, len(spy))

        # a string started with number and contains special characters and white spaces
        widget.clear()
        QTest.keyClicks(widget, '123 *$ Any')
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual(3, len(spy))
    def testSmartSliceLineEdit(self):
        # test initialization with invalid content
        with self.assertRaises(ValueError):
            SmartSliceLineEdit("")

        # test initialization
        widget = SmartIdLineEdit("0:10:1")
        self.assertEqual("0:10:1", widget._cached)
        spy = QSignalSpy(widget.value_changed_sgn)
        self.assertEqual(0, len(spy))

        # set an invalid value
        widget.clear()
        QTest.keyClicks(widget, "0:10:2:2")
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual("0:10:2:2", widget.text())
        self.assertEqual("0:10:1", widget._cached)
        self.assertEqual(0, len(spy))

        # set a valid value again
        widget.clear()
        QTest.keyClicks(widget, "0:10")
        QTest.keyPress(widget, Qt.Key_Enter)
        self.assertEqual("0:10", widget.text())
        self.assertEqual("0:10", widget._cached)
        self.assertEqual(1, len(spy))
Exemple #28
0
 def testPlayNullCard(self):
     spy = QSignalSpy(self._hand_panel.cardPlayed)
     self._hand_panel.setCards([None, None, None])
     card, rect = random.choice(self._hand_panel.cards())
     self.assertIsNone(card)
     point = (rect.topLeft() + QPointF(1, 1)).toPoint()
     QTest.mouseClick(self._hand_panel, Qt.LeftButton, Qt.NoModifier, point)
     self.assertFalse(spy, card)
Exemple #29
0
def test_cookies_changed_not_emitted(config_stub, fake_save_manager,
                                     monkeypatch, qapp):
    """Test that changed is not emitted when nothing changes."""
    config_stub.data = CONFIG_COOKIES_ENABLED
    monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub)
    jar = cookies.CookieJar()
    changed_spy = QSignalSpy(jar.changed)
    assert not changed_spy
    def test_start_pause_and_resume(self):
        app_state = AppState()

        manager = DownloadManager(app_state)

        conf = DownloadConfiguration(number_of_images=5,
                                     images_per_category=1,
                                     download_destination=self.image_net_home)

        app_state.set_configuration(conf)

        paused_spy = QSignalSpy(manager.downloadPaused)
        resumed_spy = QSignalSpy(manager.downloadResumed)
        finished_spy = QSignalSpy(manager.allDownloaded)

        manager.start()
        manager.pause_download()
        received = paused_spy.wait(timeout=500)
        self.assertTrue(received)

        time.sleep(0.5)

        manager.resume_download()

        received = finished_spy.wait(timeout=500)
        self.assertTrue(received)

        self._assert_expected_directories_exist()
        self._assert_files_are_correct()

        self.stop_the_thread(manager)
    def testCommonStartStopReset(self):
        win = self._win
        com_ctrl_widget = win._com_ctrl
        ctrl_widget = win._ctrl_widget
        client = win._client

        self.assertFalse(com_ctrl_widget.stop_btn.isEnabled())

        self.assertIsNone(client._endpoint)
        with patch.object(win._client, "start") as client_start:
            with patch.object(win._plot_timer, "start") as timer_start:
                spy = QSignalSpy(win.started_sgn)
                QTest.mouseClick(com_ctrl_widget.start_btn, Qt.LeftButton)

                self.assertEqual(
                    f"tcp://{com_ctrl_widget._hostname_le.text()}:"
                    f"{com_ctrl_widget._port_le.text()}", client._endpoint)

                self.assertEqual(1, len(spy))
                self.assertTrue(com_ctrl_widget.stop_btn.isEnabled())
                self.assertFalse(com_ctrl_widget.start_btn.isEnabled())
                self.assertFalse(com_ctrl_widget.load_dark_run_btn.isEnabled())

                self.assertFalse(ctrl_widget.dummy_widget.isEnabled())

                client_start.assert_called_once()
                timer_start.assert_called_once()

        with patch.object(win._client, "stop") as client_stop:
            with patch.object(win._plot_timer, "stop") as timer_stop:
                spy = QSignalSpy(win.stopped_sgn)
                QTest.mouseClick(com_ctrl_widget.stop_btn, Qt.LeftButton)
                self.assertEqual(1, len(spy))
                self.assertFalse(com_ctrl_widget.stop_btn.isEnabled())
                self.assertTrue(com_ctrl_widget.start_btn.isEnabled())
                self.assertTrue(com_ctrl_widget.load_dark_run_btn.isEnabled())

                self.assertTrue(ctrl_widget.dummy_widget.isEnabled())

                client_stop.assert_called_once()
                timer_stop.assert_called_once()

        spy = QSignalSpy(win.reset_sgn)
        QTest.mouseClick(com_ctrl_widget.reset_btn, Qt.LeftButton)
        self.assertEqual(1, len(spy))
Exemple #32
0
def test_multiline(qtbot, ipc_server, connected_socket):
    spy = QSignalSpy(ipc_server.got_args)
    error_spy = QSignalSpy(ipc_server.got_invalid_data)

    data = ('{{"args": ["one"], "target_arg": "tab",'
            ' "protocol_version": {version}}}\n'
            '{{"args": ["two"], "target_arg": null,'
            ' "protocol_version": {version}}}\n'.format(
                version=ipc.PROTOCOL_VERSION))

    with qtbot.waitSignals([ipc_server.got_args, ipc_server.got_args],
                           raising=True):
        connected_socket.write(data.encode('utf-8'))

    assert not error_spy
    assert len(spy) == 2
    assert spy[0] == [['one'], 'tab', '']
    assert spy[1] == [['two'], '', '']
Exemple #33
0
def test_set_cookies_never_accept(config_stub):
    """Test setCookiesFromUrl when cookies are not accepted."""
    config_stub.data = CONFIG_NEVER_COOKIES
    ram_jar = cookies.RAMCookieJar()
    changed_signal_spy = QSignalSpy(ram_jar.changed)

    url = QUrl('http://example.com/')
    assert not ram_jar.setCookiesFromUrl(url, 'test')
    assert not changed_signal_spy
    assert not ram_jar.cookiesForUrl(url)
def test_item_updated_triggers_data_changed(simple_app_image):
    model = AppImageTreeModel()
    interface = create_interface(simple_app_image)
    model.appInterface = interface
    spy = QSignalSpy(model.dataChanged)

    index = model.index(0, 0, model.index(0, 0))
    interface.itemUpdated.emit('devices/jealous')

    assert len(spy) == 1
    assert spy[0] == [index, index, []]
Exemple #35
0
def test_item_updated_triggers_data_changed(simple_data):
    model = WatchlistModel()
    interface = create_interface(simple_data)
    model.appInterface = interface
    spy = QSignalSpy(model.dataChanged)

    index = model.index(2, 0, QModelIndex())
    interface.itemUpdated.emit('garage')

    assert len(spy) == 1
    assert spy[0] == [index, index, []]