def test_ignition_point_application_02(qgis_app: QgsApplication,
                                       qgis_locale: QSettings,
                                       qgis_plugin: Dict[str, Any],
                                       qgis_bot: QgisBot, qtbot: QtBot,
                                       qgis_new_project: None,
                                       qgis_canvas: QgsMapCanvas) -> None:
    """
    Tests the Map point tool is destroyed when there is a Right Click

    :param qgis_app: QGIS application fixture
    :type qgis_app: QgsApplication
    :param qgis_locale: QSettings fixture this the current QGIS application locale
    :type qgis_locale: QSettings
    :param qgis_plugin: QGIS loading and unloading fixture for plugins
    :type qgis_plugin: dict of Any
    :param qgis_bot: QGIS UI Test Bot
    :type qgis_bot: QgisBot
    :param qtbot: QT UI Test Bot
    :type qtbot: QtBot
    :param qgis_new_project: Ensures a new project is created for the current test
    :type qgis_new_project: None
    :return: Nothing
    :rtype: None
    """
    assert type(qgis.utils.plugins['gisfire_spread_simulation']
                ).__name__ == 'GisFIRESpreadSimulation'

    plugin: GisFIRESpreadSimulation = qgis_plugin['gisfire_spread_simulation']
    plugin._menu_actions['new_ignition'].trigger()
    assert plugin._pointTool is not None
    qtbot.mouseClick(qgis_canvas.viewport(),
                     qgis.QtCore.Qt.RightButton,
                     pos=QPoint(10, 10))
    assert plugin._pointTool is None
Esempio n. 2
0
def test_wizard_import_config(qtbot: QtBot):
    wiz = ImportWizard(path.joinpath("agilent", "test_ms.b"))
    qtbot.addWidget(wiz)
    wiz.show()
    qtbot.waitExposed(wiz)

    wiz.next()
    wiz.next()

    page = wiz.currentPage()
    assert page.isComplete()
    assert page.getNames() == ("P31", "Eu153", "W182")
    assert page.lineedit_aspect.text() == "2.00"

    page.lineedit_scantime.setText("0")
    assert not page.isComplete()
    assert page.lineedit_aspect.text() == "0.00"

    page.lineedit_speed.setText("0")
    assert not page.isComplete()

    page.lineedit_spotsize.setText("0")
    assert not page.isComplete()
    assert page.lineedit_aspect.text() == ""

    dlg = page.buttonNamesPressed()
    dlg.close()

    page.updateNames({"P31": "31P", "Eu153": "Eu153"})
    assert page.getNames() == ("31P", "Eu153")
Esempio n. 3
0
def test_tool_filter(qtbot: QtBot):
    viewspace = LaserViewSpace()
    qtbot.addWidget(viewspace)
    viewspace.show()
    view = viewspace.activeView()
    widget = view.addLaser(Laser(linear_data(["a", "b", "c"])))
    tool = DriftTool(view.activeWidget())
    view.addTab("Tool", tool)
    qtbot.waitExposed(tool)

    tool.combo_element.setCurrentText("a")
    tool.combo_element.activated.emit(0)

    tool.spinbox_degree.setValue(1)
    tool.apply()

    assert np.all(np.isclose(widget.laser.data["a"], widget.laser.data["a"][0][0]))

    tool.combo_element.setCurrentText("b")
    tool.combo_element.activated.emit(0)

    assert not np.all(np.isclose(widget.laser.data["b"], widget.laser.data["c"][0][0]))

    tool.check_apply_all.setChecked(True)
    tool.apply()

    assert np.all(np.isclose(widget.laser.data["b"], widget.laser.data["c"][0][0]))
Esempio n. 4
0
def controller(qtbot: QtBot, stream: io.StringIO) -> Controller:
    controller = Controller()
    printer = StreamTextPrinter(stream)
    controller._printer = printer
    controller.run_app()
    qtbot.addWidget(controller._gui)
    return controller
def test_ignition_point_application_05(qgis_app: QgsApplication,
                                       qgis_locale: QSettings,
                                       qgis_plugin: Dict[str, Any],
                                       qgis_bot: QgisBot, qtbot: QtBot,
                                       qgis_new_project: None,
                                       qgis_canvas: QgsMapCanvas) -> None:
    """
    Tests the Ignition Point dialog is shown when there is a Left Click (the appearing dialog is cancelled) so the tests
    checks that the ignition points layer is unchanged

    :param qgis_app: QGIS application fixture
    :type qgis_app: QgsApplication
    :param qgis_locale: QSettings fixture this the current QGIS application locale
    :type qgis_locale: QSettings
    :param qgis_plugin: QGIS loading and unloading fixture for plugins
    :type qgis_plugin: dict of Any
    :param qgis_bot: QGIS UI Test Bot
    :type qgis_bot: QgisBot
    :param qtbot: QT UI Test Bot
    :type qtbot: QtBot
    :param qgis_new_project: Ensures a new project is created for the current test
    :type qgis_new_project: None
    :return: Nothing
    :rtype: None
    """
    assert type(qgis.utils.plugins['gisfire_spread_simulation']
                ).__name__ == 'GisFIRESpreadSimulation'
    plugin: GisFIRESpreadSimulation = qgis_plugin['gisfire_spread_simulation']
    vl_a: QgsVectorLayer = QgsVectorLayer('Point', 'a', 'memory')
    provider: QgsVectorDataProvider = vl_a.dataProvider()
    attributes: List[QgsField] = [
        QgsField('fid', QVariant.Int),
        QgsField('datetime', QVariant.String)
    ]
    provider.addAttributes(attributes)
    vl_a.updateFields()
    crs: QgsCoordinateReferenceSystem = QgsCoordinateReferenceSystem(
        'EPSG:25831')
    vl_a.setCrs(crs, True)
    vl_a.updateExtents()
    plugin._ignition_layer = vl_a
    assert vl_a.featureCount() == 0
    project: QgsProject = QgsProject()
    project_instance: QgsProject = project.instance()
    project_instance.setCrs(crs)

    def on_timer():
        dlg: IgnitionDateTimeDialog = plugin._dlg
        assert dlg.isVisible()
        qtbot.mouseClick(dlg._button_box.button(QDialogButtonBox.Ok),
                         qgis.QtCore.Qt.LeftButton)

    plugin._menu_actions['new_ignition'].trigger()
    assert plugin._pointTool is not None
    QTimer.singleShot(100, on_timer)
    qtbot.mouseClick(qgis_canvas.viewport(),
                     qgis.QtCore.Qt.LeftButton,
                     pos=QPoint(10, 10))

    assert vl_a.featureCount() == 1
Esempio n. 6
0
def test_colocalisation_dialog(qtbot: QtBot):
    data = np.empty((10, 10), dtype=[("a", float), ("b", float), ("c", float)])
    data["a"] = np.repeat(np.linspace(0, 1, 10).reshape(1, -1), 10, axis=0)
    data["b"] = np.repeat(np.linspace(0, 1, 10).reshape(-1, 1), 10, axis=1)
    np.random.seed(9764915)
    data["c"] = np.random.random((10, 10))

    mask = np.ones((10, 10), dtype=bool)
    mask[:2] = False

    dialog = dialogs.ColocalisationDialog(data, mask)
    qtbot.addWidget(dialog)
    dialog.open()

    assert dialog.combo_name1.currentText() == "a"
    assert dialog.combo_name2.currentText() == "b"

    assert dialog.label_r.text() == "0.00"
    assert dialog.label_icq.text() == "0.00"
    assert dialog.label_m1.text() == "0.00"
    assert dialog.label_m2.text() == "0.50"
    assert dialog.label_p.text() == ""

    dialog.combo_name2.setCurrentText("a")

    assert dialog.label_r.text() == "1.00"
    assert dialog.label_icq.text() == "0.50"
    assert dialog.label_m1.text() == "1.00"
    assert dialog.label_m2.text() == "1.00"
    assert dialog.label_p.text() == ""

    dialog.calculatePearsonsProbablity()
    assert dialog.label_p.text() == "1.00"
Esempio n. 7
0
def test_basic_table_view(qtbot: QtBot):
    view = BasicTableView()
    qtbot.addWidget(view)

    x = np.random.random((5, 5))
    model = NumpyArrayTableModel(x)
    view.setModel(model)

    view.setCurrentIndex(view.indexAt(QtCore.QPoint(0, 0)))
    assert view.currentIndex().row() == 0
    view._advance()
    assert view.currentIndex().row() == 1
    view.selectionModel().select(
        view.indexAt(QtCore.QPoint(0, 0)), QtCore.QItemSelectionModel.Select
    )
    view._copy()
    mime_data = QtWidgets.QApplication.clipboard().mimeData()
    assert mime_data.text() == str(x[0, 0]) + "\n" + str(x[1, 0])
    view._cut()  # Same as _copy, _delete
    view._delete()
    assert not np.isnan(x[0, 0])  # Can't delete out of a numpy array
    QtWidgets.QApplication.clipboard().setText("2.0")
    view._paste()
    assert x[0, 0] == 2.0

    view.contextMenuEvent(
        QtGui.QContextMenuEvent(QtGui.QContextMenuEvent.Mouse, QtCore.QPoint(0, 0))
    )
Esempio n. 8
0
def maybe_stop_for_interaction(qtbot: QtBot) -> None:
    """
    Stop the tests to interact with the GUI if 'TEST_INTERACT' environment
    variable is set.
    """
    if os.environ.get("TEST_INTERACT"):
        qtbot.stopForInteraction()
Esempio n. 9
0
def test_main_window_actions_widget(qtbot: QtBot):
    window = MainWindow()
    qtbot.addWidget(window)
    window.viewspace.views[0].addLaser(
        Laser(rand_data("A1"), info={"File Path": "/home/pewpew/real.npz"}))
    window.viewspace.refresh()

    assert window.action_export_all.isEnabled()
    assert window.action_tool_calculator.isEnabled()
    assert window.action_tool_drift.isEnabled()
    assert window.action_tool_filter.isEnabled()
    assert window.action_tool_standards.isEnabled()
    assert window.action_tool_overlay.isEnabled()

    window.actionTransformFlipHorz()
    window.actionTransformFlipVert()
    window.actionTransformRotateLeft()
    window.actionTransformRotateRight()

    window.actionExportAll()
    window.actionToolCalculator()
    window.actionToolDrift()
    window.actionToolFilter()
    window.actionToolStandards()
    window.actionToolOverlay()
Esempio n. 10
0
def test_export_dialog_names(qtbot: QtBot):
    viewspace = LaserViewSpace()
    qtbot.addWidget(viewspace)
    view = viewspace.activeView()

    widget = view.addLaser(
        Laser(
            rand_data(["A", "\\B", "C>_<"]),
            info={
                "Name": "inv@|d",
                "File Path": "/invalid.npz"
            },
        ))
    dlg = ExportDialog(widget)
    dlg.lineedit_directory.setText(str(Path(".")))
    assert dlg.isComplete()
    dlg.lineedit_filename.setText("invalid.csv")
    assert dlg.isComplete()
    dlg.check_export_all.setChecked(True)

    paths = dlg.generatePaths(widget.laser)

    assert paths[0][0].name == "invalid_A.csv"
    assert paths[1][0].name == "invalid__B.csv"
    assert paths[2][0].name == "invalid_C___.csv"
Esempio n. 11
0
def test_main_view(qtbot:QtBot):
    from genial.views.mainview import MainView
    main_view = MainView()
    assert main_view is not None
    qtbot.add_widget(main_view)
    main_view.show()
    assert main_view.isVisible()
Esempio n. 12
0
def test_image_slice_item(qtbot: QtBot):
    window = QtWidgets.QMainWindow()
    qtbot.addWidget(window)

    scene = QtWidgets.QGraphicsScene(0, 0, 100, 100)
    view = QtWidgets.QGraphicsView(scene)
    window.setCentralWidget(view)

    array = np.random.random((10, 10))
    img = ScaledImageItem.fromArray(array, QtCore.QRectF(0, 0, 100, 100))
    item = ImageSliceWidgetItem(img, array)
    scene.addItem(item)

    item.mousePressEvent(
        FakeSceneMouseEvent(QtCore.Qt.LeftButton, QtCore.QPointF(1, 1)))
    item.mouseMoveEvent(
        FakeSceneMouseEvent(QtCore.Qt.LeftButton, QtCore.QPointF(1, 99)))
    item.mouseReleaseEvent(
        FakeSceneMouseEvent(QtCore.Qt.LeftButton, QtCore.QPointF(1, 99)))

    assert item.sliced.size == 10
    assert np.all(item.sliced == array[:, 0])

    item.actionCopyToClipboard()
    item.shape()  # For redraw

    # Draw everything
    window.show()
    qtbot.waitExposed(window)
Esempio n. 13
0
def test_apply_dialog(qtbot: QtBot):
    dialog = dialogs.ApplyDialog()
    qtbot.addWidget(dialog)
    dialog.open()

    for button in dialog.button_box.buttons():
        dialog.buttonClicked(button)
def test_exposure_widget(qtbot: QtBot):
    CORE.setExposure(15)
    wdg = DefaultCameraExposureWidget(core=CORE)
    qtbot.addWidget(wdg)

    # check that it get's whatever core is set to.
    assert wdg.spinBox.value() == 15
    with qtbot.waitSignal(CORE.events.exposureChanged):
        CORE.setExposure(30)
    assert wdg.spinBox.value() == 30

    with qtbot.wait_signal(CORE.events.exposureChanged):
        wdg.spinBox.setValue(45)
    assert CORE.getExposure() == 45

    # test updating cameraDevice
    CORE.setProperty("Core", "Camera", "")
    assert not wdg.isEnabled()

    with pytest.raises(RuntimeError):
        wdg.setCamera("blarg")

    # set to an invalid camera name
    # should now be disabled.
    wdg.setCamera("blarg", force=True)
    assert not wdg.isEnabled()

    # reset the camera to a working one
    CORE.setProperty("Core", "Camera", "Camera")
    with qtbot.wait_signal(CORE.events.exposureChanged):
        wdg.spinBox.setValue(12)
    assert CORE.getExposure() == 12
Esempio n. 15
0
def test_laser_widget(qtbot: QtBot):
    x = rand_data(["A1", "B2"])
    y = x["A1"].copy()
    viewspace = LaserViewSpace()
    qtbot.addWidget(viewspace)
    viewspace.show()

    view = viewspace.activeView()
    view.addLaser(Laser(x))
    widget = view.activeWidget()

    widget.applyConfig(Config(1.0, 1.0, 1.0))
    assert widget.laser.config.spotsize == 1.0
    widget.applyCalibration({"B2": Calibration(2.0, 2.0)})
    assert widget.laser.calibration["B2"].intercept == 2.0

    widget.updateNames({"A1": "A1", "B2": "2B"})
    assert np.all(viewspace.uniqueElements() == ["2B", "A1"])

    widget.transform(flip="horizontal")
    assert np.all(widget.laser.get("A1") == np.flip(y, axis=1))
    widget.transform(flip="horizontal")
    widget.transform(flip="vertical")
    assert np.all(widget.laser.get("A1") == np.flip(y, axis=0))
    widget.transform(flip="vertical")
    assert np.all(widget.laser.get("A1") == y)
    widget.transform(rotate="right")
    assert np.all(widget.laser.get("A1") == np.rot90(y, k=1, axes=(1, 0)))
    widget.transform(rotate="left")
    assert np.all(widget.laser.get("A1") == y)
Esempio n. 16
0
def test_questions_view(qtbot: QtBot):
    from genial.views.questionsview import QuestionsView
    questions_view = QuestionsView()
    assert questions_view is not None
    qtbot.add_widget(questions_view)
    questions_view.show()
    assert questions_view.isVisible()
Esempio n. 17
0
def test_document_view(qtbot:QtBot):
    from genial.views.documentview import DocumentView
    document_view = DocumentView()
    assert document_view is not None
    qtbot.add_widget(document_view)
    document_view.show()
    assert document_view.isVisible()
Esempio n. 18
0
def test_questions_view(qtbot:QtBot):
    from genial.views.questionsview import QuestionsView
    questions_view = QuestionsView()
    assert questions_view is not None
    qtbot.add_widget(questions_view)
    questions_view.show()
    assert questions_view.isVisible()
Esempio n. 19
0
def test_main_view(qtbot: QtBot):
    from genial.views.mainview import MainView
    main_view = MainView()
    assert main_view is not None
    qtbot.add_widget(main_view)
    main_view.show()
    assert main_view.isVisible()
Esempio n. 20
0
def pytest_configure(config):
    config.addinivalue_line(
        "markers",
        "qt_no_exception_capture: Disables pytest-qt's automatic exception "
        "capture for just one test item.",
    )

    config.addinivalue_line(
        "markers", "qt_log_level_fail: overrides qt_log_level_fail ini option."
    )
    config.addinivalue_line(
        "markers", "qt_log_ignore: overrides qt_log_ignore ini option."
    )
    config.addinivalue_line("markers", "no_qt_log: Turn off Qt logging capture.")

    if config.getoption("qt_log"):
        config.pluginmanager.register(QtLoggingPlugin(config), "_qt_logging")

    qt_api.set_qt_api(config.getini("qt_api"))

    if config.getini("qt_wait_signal_raising"):
        warnings.warn(
            "qt_wait_signal_raising is deprecated, use qt_default_raising instead.",
            DeprecationWarning,
        )

    from .qtbot import QtBot

    QtBot._inject_qtest_methods()
Esempio n. 21
0
def test_properties_questions_view(qtbot: QtBot):
    from genial.views.propertiesquestiontypeview import PropertiesQuestionTypeView
    properties_questions_view = PropertiesQuestionTypeView()
    assert properties_questions_view is not None
    qtbot.add_widget(properties_questions_view)
    properties_questions_view.show()
    assert properties_questions_view.isVisible()
Esempio n. 22
0
def test_document_view(qtbot: QtBot):
    from genial.views.documentview import DocumentView
    document_view = DocumentView()
    assert document_view is not None
    qtbot.add_widget(document_view)
    document_view.show()
    assert document_view.isVisible()
Esempio n. 23
0
def test_laser_graphics_zoom(qtbot: QtBot):
    graphics = LaserGraphicsView(GraphicsOptions())
    qtbot.addWidget(graphics)

    x = np.random.random((10, 10))
    graphics.drawImage(x, QtCore.QRectF(0, 0, 100, 100), "x")

    qtbot.waitExposed(graphics)

    graphics.zoomStart()

    event = QtGui.QMouseEvent(
        QtCore.QEvent.MouseButtonPress,
        graphics.mapFromScene(QtCore.QPointF(20, 20)),
        QtCore.Qt.LeftButton,
        QtCore.Qt.LeftButton,
        QtCore.Qt.NoModifier,
    )

    graphics.mousePressEvent(event)
    event.setLocalPos(graphics.mapFromScene(QtCore.QPointF(40, 40)))
    graphics.mouseMoveEvent(event)
    graphics.mouseReleaseEvent(event)

    rect = graphics.mapToScene(graphics.viewport().rect()).boundingRect()
    assert 29.5 < rect.center().x() < 30.5
    assert 29.5 < rect.center().y() < 30.5
    assert 19.5 < rect.width() < 20.5 or 19.5 < rect.height() < 20.5
def test_settings_dialog_02(qgis_app: QgsApplication, qgis_locale: QSettings, qgis_plugin: Dict[str, Any],
                            qgis_bot: QgisBot, qtbot: QtBot, qgis_new_project: None):
    """
    Tests the settings dialog is correctly shown and destroyed with an OK action

    :param qgis_app: QGIS application fixture
    :type qgis_app: QgsApplication
    :param qgis_locale: QT settings fixture with a user locale
    :type qgis_locale: QSettings
    :param qgis_plugin: QGIS loading and unloading fixture for plugins
    :type qgis_plugin: dict of Any
    :param qgis_bot: QGIS Bot to automate GUI tests
    :type qgis_bot: QgisBot
    :param qtbot: QT fixture to automate GUI tests
    :type qtbot: QtBot
    :param qgis_new_project: Ensures the project instance is clean
    :type qgis_new_project: None
    """
    # noinspection DuplicatedCode
    assert type(qgis.utils.plugins['gisfire_spread_simulation']).__name__ == 'GisFIRESpreadSimulation'

    dialog: SettingsDialog = SettingsDialog()
    qtbot.addWidget(dialog)
    dialog.show()
    assert dialog.isVisible()
    buttons: QDialogButtonBox = dialog._button_box
    button_ok: QPushButton = buttons.button(qgis.PyQt.QtWidgets.QDialogButtonBox.Ok)
    qtbot.mouseClick(button_ok, qgis.QtCore.Qt.LeftButton)
    assert not dialog.isVisible()
Esempio n. 25
0
def test_colocal_chart(qtbot: QtBot):
    chart = ColocalisationChart("Colocal")
    qtbot.addWidget(chart)

    chart.drawPoints(np.random.random(10), np.random.random(10))
    chart.drawLine(1.0, 0.0)
    chart.drawThresholds(0.25, 0.75)
Esempio n. 26
0
def test_properties_questions_view(qtbot:QtBot):
    from genial.views.propertiesquestiontypeview import PropertiesQuestionTypeView
    properties_questions_view = PropertiesQuestionTypeView()
    assert properties_questions_view is not None
    qtbot.add_widget(properties_questions_view)
    properties_questions_view.show()
    assert properties_questions_view.isVisible()
Esempio n. 27
0
def pytest_configure(config):
    config.addinivalue_line(
        "markers",
        "qt_no_exception_capture: Disables pytest-qt's automatic exception "
        "capture for just one test item.",
    )

    config.addinivalue_line(
        "markers",
        "qt_log_level_fail: overrides qt_log_level_fail ini option.")
    config.addinivalue_line(
        "markers", "qt_log_ignore: overrides qt_log_ignore ini option.")
    config.addinivalue_line("markers",
                            "no_qt_log: Turn off Qt logging capture.")

    if config.getoption("qt_log") and config.getoption("capture") != "no":
        config.pluginmanager.register(QtLoggingPlugin(config), "_qt_logging")

    qt_api.set_qt_api(config.getini("qt_api"))

    if config.getini("qt_wait_signal_raising"):
        warnings.warn(
            "qt_wait_signal_raising is deprecated, use qt_default_raising instead.",
            DeprecationWarning,
        )

    from .qtbot import QtBot

    QtBot._inject_qtest_methods()
Esempio n. 28
0
def test_calibration_dialog(qtbot: QtBot):
    cals = {
        "A": Calibration.from_points([[0, 2], [1, 4]], unit="ppb"),
        "B": Calibration(),
    }

    dialog = dialogs.CalibrationDialog(cals, "B")
    qtbot.addWidget(dialog)
    dialog.open()

    assert dialog.combo_element.currentText() == "B"
    assert dialog.points.model.array.size == 0
    assert not dialog.button_plot.isEnabled()
    assert not dialog.points.button_remove.isEnabled()

    dialog.lineedit_gradient.setText("1")
    dialog.lineedit_intercept.setText("2")
    dialog.lineedit_unit.setText("ppm")

    dialog.combo_element.setCurrentIndex(0)
    assert dialog.combo_element.currentText() == "A"
    assert dialog.points.model.array.size == 6
    assert dialog.button_plot.isEnabled()

    # Points enabled on remove / add
    dialog.points.removeCalibrationLevel()
    assert not dialog.button_plot.isEnabled()
    dialog.points.addCalibrationLevel()
    assert not dialog.button_plot.isEnabled()
    dialog.points.model.setData(dialog.points.model.index(0, 1), 1.0)
    dialog.points.model.setData(dialog.points.model.index(1, 1), 6.0)
    assert dialog.button_plot.isEnabled()
    assert np.isclose(dialog.calibrations["A"].gradient, 4.0)

    # Points weightings
    assert dialog.calibrations["A"].weighting == "Equal"
    assert np.all(dialog.calibrations["A"].weights == 1.0)

    dialog.points.combo_weighting.setCurrentText("y")
    assert dialog.calibrations["A"].weighting == "y"
    assert np.all(
        dialog.calibrations["A"].weights == dialog.calibrations["A"].y)

    # Restored on change
    assert dialog.calibrations["B"].gradient == 1.0
    assert dialog.calibrations["B"].intercept == 2.0
    assert dialog.calibrations["B"].unit == "ppm"

    # Just run code as can't test clipboard
    dialog.copyToClipboard()
    dialog.copyAllToClipboard()

    dialog.combo_element.setCurrentIndex(0)
    dialog.showCurve()

    dialog.apply()
    dialog.check_all.setChecked(True)
    dialog.apply()
Esempio n. 29
0
def window(model: Model, qtbot: QtBot, mocker: MockFixture):
    """the window."""
    message_box = 'usc_lr_timer.app.QtWidgets.QMessageBox.{}'
    mocker.patch(message_box.format('question'),
                 return_value=QtWidgets.QMessageBox.Yes)
    mocker.patch(message_box.format('information'))
    window = MainWindow(model)
    qtbot.add_widget(window)
    return window
Esempio n. 30
0
def test_tool_calculator_formula(qtbot: QtBot):
    textedit = CalculatorFormula("", ["a", "b"])
    qtbot.addWidget(textedit)

    assert not textedit.hasAcceptableInput()
    textedit.setPlainText("a + 1")
    assert textedit.hasAcceptableInput()
    textedit.setPlainText("a + c")
    assert not textedit.hasAcceptableInput()
def test_settings_dialog_03(qgis_app: QgsApplication, qgis_locale: QSettings, qgis_plugin: Dict[str, Any],
                            qgis_bot: QgisBot, qtbot: QtBot, qgis_new_project: None):
    """
    Tests the settings dialog loads correctly the different layers of the project depending on its type and its
    selection

    :param qgis_app: QGIS application fixture
    :type qgis_app: QgsApplication
    :param qgis_locale: QT settings fixture with a user locale
    :type qgis_locale: QSettings
    :param qgis_plugin: QGIS loading and unloading fixture for plugins
    :type qgis_plugin: dict of Any
    :param qgis_bot: QGIS Bot to automate GUI tests
    :type qgis_bot: QgisBot
    :param qtbot: QT fixture to automate GUI tests
    :type qtbot: QtBot
    :param qgis_new_project: Ensures the project instance is clean
    :type qgis_new_project: None
    """
    assert type(qgis.utils.plugins['gisfire_spread_simulation']).__name__ == 'GisFIRESpreadSimulation'
    project: QgsProject = QgsProject()
    project_instance: QgsProject = project.instance()
    # Create possible vector layers to choose from
    vl_a = QgsVectorLayer('Point', 'a', 'memory')
    vl_b = QgsVectorLayer('Point', 'b', 'memory')
    vl_c = QgsVectorLayer('Point', 'c', 'memory')
    project_instance.addMapLayer(vl_a)
    project_instance.addMapLayer(vl_b)
    project_instance.addMapLayer(vl_c)
    vl_d = QgsVectorLayer('Polygon', 'd', 'memory')
    vl_e = QgsVectorLayer('Polygon', 'e', 'memory')
    vl_f = QgsVectorLayer('Polygon', 'f', 'memory')
    vl_g = QgsVectorLayer('Polygon', 'g', 'memory')
    project_instance.addMapLayer(vl_d)
    project_instance.addMapLayer(vl_e)
    project_instance.addMapLayer(vl_f)
    project_instance.addMapLayer(vl_g)

    dialog: SettingsDialog = SettingsDialog(layers=project_instance.mapLayers())
    assert dialog._combobox_ignition_layer.count() == 3
    assert dialog._combobox_perimeter_layer.count() == 4
    assert dialog._combobox_land_cover_layer.count() == 4
    qtbot.addWidget(dialog)
    dialog.show()
    assert dialog.isVisible()
    # Select the different layers in the combobox
    qtbot.keyClicks(dialog._combobox_ignition_layer, 'c')
    qtbot.keyClicks(dialog._combobox_perimeter_layer, 'd')
    qtbot.keyClicks(dialog._combobox_land_cover_layer, 'g')
    buttons: QDialogButtonBox = dialog._button_box
    button_ok: QPushButton = buttons.button(qgis.PyQt.QtWidgets.QDialogButtonBox.Ok)
    qtbot.mouseClick(button_ok, qgis.QtCore.Qt.LeftButton)
    assert not dialog.isVisible()
    # Get the values
    assert dialog.ignition_layer == vl_c
    assert dialog.perimeter_layer == vl_d
    assert dialog.land_cover_layer == vl_g
Esempio n. 32
0
def test_figure_registration(app: Mockautodidaqt, qtbot: QtBot):
    panel = Panel(FauxParent(), "test", app)
    qtbot.add_widget(panel)

    fig = panel.register_figure("plot")

    assert len(panel.canvases) == 1
    assert len(panel.figures) == 1
    assert isinstance(fig, Figure)
Esempio n. 33
0
def test_selection_dialog(qtbot: QtBot):
    x = np.random.random((10, 10))
    graphics = LaserGraphicsView(GraphicsOptions())
    graphics.drawImage(x, QtCore.QRectF(0, 0, 10, 10), "x")

    dialog = dialogs.SelectionDialog(graphics)
    qtbot.addWidget(dialog)
    dialog.open()

    # Test enabling of options
    assert dialog.lineedit_manual.isEnabled()
    assert not dialog.spinbox_method.isEnabled()
    assert not dialog.spinbox_comparison.isEnabled()

    dialog.combo_method.setCurrentText("K-means")
    dialog.refresh()
    assert not dialog.lineedit_manual.isEnabled()
    assert dialog.spinbox_method.isEnabled()
    assert dialog.spinbox_comparison.isEnabled()
    assert dialog.spinbox_method.value() == 3
    assert dialog.spinbox_comparison.value() == 1

    dialog.combo_method.setCurrentText("Mean")
    dialog.check_limit_selection.setChecked(True)
    dialog.refresh()
    assert not dialog.spinbox_method.isEnabled()
    assert not dialog.spinbox_comparison.isEnabled()

    # Test correct states and masks emmited
    with qtbot.wait_signal(dialog.maskSelected) as emitted:
        dialog.apply()
    assert np.all(emitted.args[0] == (x > x.mean()))
    assert emitted.args[1] == ["intersect"]

    dialog.check_limit_selection.setChecked(False)
    dialog.combo_method.setCurrentText("Manual")
    dialog.lineedit_manual.setText("0.9")
    dialog.refresh()

    with qtbot.wait_signal(dialog.maskSelected) as emitted:
        dialog.apply()
    assert np.all(emitted.args[0] == (x > 0.9))
    assert emitted.args[1] == [""]

    dialog.graphics.selection = emitted.args[0]

    # Test limit threshold
    dialog.combo_method.setCurrentText("Mean")
    dialog.check_limit_threshold.setChecked(True)
    graphics.mask = x > 0.9
    dialog.refresh()

    with qtbot.wait_signal(dialog.maskSelected) as emitted:
        dialog.apply()
    assert np.all(emitted.args[0] == (x > np.mean(x[x > 0.9])))
    assert emitted.args[1] == [""]
Esempio n. 34
0
def test_dataclass_bindings(qtbot: QtBot):
    data = Data()
    gated = Data()
    ui = {}

    with CollectUI(ui):
        g = group(
            "Dataclass Binding",
            layout_dataclass(Data, prefix="data"),
            layout_dataclass(Data, prefix="gated", submit="Submit"),
        )

        bind_dataclass(data, prefix="data", ui=ui)
        bind_dataclass(gated, prefix="gated", ui=ui)

    qtbot.add_widget(g)

    # check keys are generated appropriately
    assert set(ui.keys()).issuperset({("data", k)
                                      for k in ["x", "y", "z", "choice"]})

    # this only gives one way binding
    assert data == Data()

    # directly plug into the observables
    ui[("data", "x")].on_next(5)
    assert data == Data(x=5)

    ui[("data", "choice")].on_next(AorB.B)
    assert data == Data(x=5, choice=AorB.B)

    # check that the gated option does not update until submitted
    ui[("gated", "x")].on_next(5)
    assert gated == Data()

    ui[("gated", "y")].on_next(-1)
    assert gated == Data()

    qtbot.mouseClick(ui[("gated", "submit!")], QtCore.Qt.LeftButton)
    assert gated == Data(x=5, y=-1)

    # check field types
    with pytest.raises(TypeError) as exc:
        ui[("data", "z")].on_next(10)

    assert "unexpected type 'int'" in str(exc.value)

    expected_classes = [
        DoubleSpinBox,
        SpinBox,
        LineEdit,
        ComboBox,
    ]

    for partial_id, cls in zip(["x", "y", "z", "choice"], expected_classes):
        assert isinstance(ui[("data", partial_id)], cls)
Esempio n. 35
0
def show_and_close_window(qtbot: QtBot, template: QDialog):
    """
    Function for displaying and then closing a window/widget. This appears to be necessary in order to make sure
    some interactions with the UI are recognised. Otherwise the UI can behave as though no clicks/button presses/etc
    actually took place which then causes tests to fail even though they ought to pass in theory.
    :param qtbot: The qtbot testing tool.
    :param template: The window/widget to be opened.
    """
    template.show()
    qtbot.waitForWindowShown(template)
Esempio n. 36
0
def qtbot(qapp, request):
    """
    Fixture used to create a QtBot instance for using during testing.

    Make sure to call addWidget for each top-level widget you create to ensure
    that they are properly closed after the test ends.
    """
    result = QtBot()
    no_capture = _is_exception_capture_disabled(request.node)
    if no_capture:
        yield result  # pragma: no cover
    else:
        with capture_exceptions() as exceptions:
            yield result
        if exceptions:
            pytest.fail(format_captured_exceptions(exceptions), pytrace=False)

    result._close()
Esempio n. 37
0
def pytest_configure(config):
    config.addinivalue_line(
        'markers',
        "qt_no_exception_capture: Disables pytest-qt's automatic exception "
        'capture for just one test item.')

    config.addinivalue_line(
        'markers',
        'qt_log_level_fail: overrides qt_log_level_fail ini option.')
    config.addinivalue_line(
        'markers',
        'qt_log_ignore: overrides qt_log_ignore ini option.')

    if config.getoption('qt_log'):
        config.pluginmanager.register(QtLoggingPlugin(config), '_qt_logging')

    qt_api.set_qt_api(config.getini('qt_api'))

    from .qtbot import QtBot
    QtBot._inject_qtest_methods()