Example #1
0
 async def _on_validate_clicked(self):
     self.button_validate.setEnabled(False)
     auth_method = self.widget_auth.get_auth_method()
     try:
         if auth_method == DeviceFileType.PASSWORD:
             save_device_with_password_in_config(
                 self.core.config.config_dir, self.loaded_device,
                 self.widget_auth.get_auth())
         elif auth_method == DeviceFileType.SMARTCARD:
             await save_device_with_smartcard_in_config(
                 self.core.config.config_dir, self.loaded_device)
         show_info(self, _("TEXT_AUTH_CHANGE_SUCCESS"))
         if self.dialog:
             self.dialog.accept()
         elif QApplication.activeModalWidget():
             QApplication.activeModalWidget().accept()
         else:
             logger.warning(
                 "Cannot close dialog when changing password info")
     except LocalDeviceCryptoError as exc:
         self.button_validate.setEnabled(True)
         if auth_method == DeviceFileType.SMARTCARD:
             show_error(self, _("TEXT_INVALID_SMARTCARD"), exception=exc)
     except LocalDeviceNotFoundError as exc:
         self.button_validate.setEnabled(True)
         if auth_method == DeviceFileType.PASSWORD:
             show_error(self, _("TEXT_CANNOT_SAVE_DEVICE"), exception=exc)
     except LocalDeviceError as exc:
         self.button_validate.setEnabled(True)
         show_error(self, _("TEXT_CANNOT_SAVE_DEVICE"), exception=exc)
Example #2
0
 def _on_button_clicked(self):
     if self.dialog:
         self.dialog.accept()
     elif QApplication.activeModalWidget():
         QApplication.activeModalWidget().accept()
     else:
         logger.warning("Cannot close dialog when requesting user text input")
Example #3
0
 def _on_show_clicked(self):
     if self.dialog:
         self.dialog.accept()
     elif QApplication.activeModalWidget():
         QApplication.activeModalWidget().accept()
     else:
         logger.warning("Cannot close dialog when displaying info")
Example #4
0
 def _validate_clicked(self):
     if isinstance(self.current_widget, CreateOrgFirstPageWidget):
         if self.current_widget.radio_bootstrap_org.isChecked():
             self.status = ""
             if self.dialog:
                 self.dialog.accept()
             elif QApplication.activeModalWidget():
                 QApplication.activeModalWidget().accept()
             else:
                 logger.warning("Cannot close dialog when org wizard")
         else:
             self.button_validate.setText(_("ACTION_CREATE_ORGANIZATION"))
             self.button_previous.show()
             self._clear_page()
             self.current_widget = CreateOrgSecondPageWidget()
             self.main_layout.addWidget(self.current_widget)
             self.current_widget.line_edit_user_email.textChanged.connect(
                 self._check_infos)
             self.current_widget.line_edit_org_name.textChanged.connect(
                 self._check_infos)
             self.current_widget.check_accept_contract.clicked.connect(
                 self._check_infos)
             self.button_validate.setEnabled(False)
     elif isinstance(self.current_widget, CreateOrgSecondPageWidget):
         self.req_job = self.jobs_ctx.submit_job(
             ThreadSafeQtSignal(self, "req_success"),
             ThreadSafeQtSignal(self, "req_error"),
             _do_api_request,
             email=self.current_widget.line_edit_user_email.text(),
             organization_id=self.current_widget.line_edit_org_name.text(),
         )
         self.button_validate.setEnabled(False)
         self.button_previous.hide()
Example #5
0
 def _on_button_clicked(self, button):
     self.status = button.text()
     if self.dialog:
         self.dialog.accept()
     elif QApplication.activeModalWidget():
         QApplication.activeModalWidget().accept()
     else:
         logger.warning("Cannot close dialog when asking question")
 def on_registration_success(self):
     assert self.registration_job.is_finished()
     assert self.registration_job.status == "ok"
     show_info(self, _("TEXT_INVITE_USER_SUCCESS"))
     self.registration_job = None
     if self.dialog:
         self.dialog.accept()
     elif QApplication.activeModalWidget():
         QApplication.activeModalWidget().accept()
     else:
         logger.warning("Cannot close dialog when inviting user")
Example #7
0
    def _on_req_success(self):
        assert self.req_job
        assert self.req_job.is_finished()
        assert self.req_job.status == "ok"

        _, self.status = self.req_job.ret
        self.req_job = None
        if self.dialog:
            self.dialog.accept()
        elif QApplication.activeModalWidget():
            QApplication.activeModalWidget().accept()
        else:
            logger.warning("Cannot close dialog when org wizard")
Example #8
0
    def test_good_file_multi_table(self):
        fileName = "database.db"
        QTest.qWaitForWindowActive(DatabaseTests.gui)
        QtCore.QTimer.singleShot(
            1000, lambda: inject(QApplication.activeModalWidget(), fileName))
        QtCore.QTimer.singleShot(
            2000, lambda: inject(QApplication.activeModalWidget(), "Beers"))
        QTest.keyPress(DatabaseTests.gui, Qt.Key_I, Qt.ControlModifier)
        QTest.keyRelease(DatabaseTests.gui, Qt.Key_I, Qt.ControlModifier)

        self.assertEqual(core._attributes, ['name', 'manf'])
        self.assertEqual(core._fds, [])
        self.assertEqual(core._cover, [])
        self.assertEqual(DatabaseTests.gui.ui.schemaLine.text(), "name,manf")
Example #9
0
    def on_claim_success(self):
        assert self.claim_user_job
        assert self.claim_user_job.is_finished()
        assert self.claim_user_job.status == "ok"

        self.status = self.claim_user_job.ret
        self.claim_user_job = None
        show_info(parent=self,
                  message=_("TEXT_CLAIM_USER_SUCCESS"),
                  button_text=_("ACTION_CONTINUE"))
        if self.dialog:
            self.dialog.accept()
        elif QApplication.activeModalWidget():
            QApplication.activeModalWidget().accept()
        else:
            logger.warning("Cannot close dialog when claiming user")
 def masterPasswordChanged(self, oldPassword, newPassword):
     """
     Public slot to handle the change of the master password.
     
     @param oldPassword current master password (string)
     @param newPassword new master password (string)
     """
     if not self.__loaded:
         self.__load()
     
     progress = E5ProgressDialog(
         self.tr("Re-encoding saved passwords..."),
         None, 0, len(self.__logins), self.tr("%v/%m Passwords"),
         QApplication.activeModalWidget())
     progress.setMinimumDuration(0)
     progress.setWindowTitle(self.tr("Passwords"))
     count = 0
     
     for key in self.__logins:
         progress.setValue(count)
         QCoreApplication.processEvents()
         username, hash = self.__logins[key]
         hash = Utilities.crypto.pwRecode(hash, oldPassword, newPassword)
         self.__logins[key] = (username, hash)
         count += 1
     
     progress.setValue(len(self.__logins))
     QCoreApplication.processEvents()
     self.changed.emit()
Example #11
0
    def on_bootstrap_success(self):
        assert self.bootstrap_job
        assert self.bootstrap_job.is_finished()
        assert self.bootstrap_job.status == "ok"

        self.button_bootstrap.setDisabled(False)
        self.status = self.bootstrap_job.ret
        self.bootstrap_job = None
        self.check_infos()
        show_info(
            parent=self, message=_("TEXT_BOOTSTRAP_ORG_SUCCESS"), button_text=_("ACTION_CONTINUE")
        )
        if self.dialog:
            self.dialog.accept()
        elif QApplication.activeModalWidget():
            QApplication.activeModalWidget().accept()
        else:
            logger.warning("Cannot close dialog when bootstraping")
 def change_password(self):
     if self.line_edit_password.text() != self.line_edit_password_check.text():
         show_error(self, _("TEXT_CHANGE_PASSWORD_PASSWORD_MISMATCH"))
     else:
         key_file = get_key_file(self.core.config.config_dir, self.core.device)
         try:
             change_device_password(
                 key_file, self.line_edit_old_password.text(), self.line_edit_password.text()
             )
             show_info(self, _("TEXT_CHANGE_PASSWORD_SUCCESS"))
             if self.dialog:
                 self.dialog.accept()
             elif QApplication.activeModalWidget():
                 QApplication.activeModalWidget().accept()
             else:
                 logger.warning("Cannot close dialog when changing password info")
         except LocalDeviceCryptoError as exc:
             show_error(self, _("TEXT_CHANGE_PASSWORD_INVALID_PASSWORD"), exception=exc)
    def _on_req_success(self):
        assert self.create_job
        assert self.create_job.is_finished()
        assert self.create_job.status == "ok"

        self.status = self.create_job.ret
        self.create_job = None
        show_info(
            parent=self,
            message=_("TEXT_BOOTSTRAP_ORG_SUCCESS_organization").format(
                organization=self.status[0].organization_id),
            button_text=_("ACTION_CONTINUE"),
        )
        if self.dialog:
            self.dialog.accept()
        elif QApplication.activeModalWidget():
            QApplication.activeModalWidget().accept()
        else:
            logger.warning("Cannot close dialog when org wizard")
Example #14
0
 def test_read_no_delim(self):        
     delim = ""
     fileName = "good_delim.txt"
     QTest.qWaitForWindowActive(ReadFileTests.gui)
     QtCore.QTimer.singleShot(1000, lambda: inject(QApplication.activeModalWidget(), delim))
     QTest.keyPress(ReadFileTests.gui, Qt.Key_F, Qt.ControlModifier | Qt.ShiftModifier)
     QTest.keyRelease(ReadFileTests.gui, Qt.Key_F, Qt.ControlModifier | Qt.ShiftModifier)
     
     self.assertEqual(core._attributes, [])
     self.assertEqual(ReadFileTests.gui.ui.schemaLine.text(), "")
Example #15
0
    def test_no_file(self):
        QTest.qWaitForWindowActive(DatabaseTests.gui)
        QtCore.QTimer.singleShot(
            2000, lambda: QTest.keyPress(QApplication.activeModalWidget(), Qt.
                                         Key_Escape))
        QTest.keyPress(DatabaseTests.gui, Qt.Key_I, Qt.ControlModifier)
        QTest.keyRelease(DatabaseTests.gui, Qt.Key_I, Qt.ControlModifier)

        self.assertEqual(core._attributes, [])
        self.assertEqual(core._fds, [])
        self.assertEqual(core._cover, [])
        self.assertEqual(DatabaseTests.gui.ui.schemaLine.text(), "")
 def addWindow(self, window, target):
     parent = QApplication.activeModalWidget()
     if not parent:
         parent = self
     dialog = QDialog(parent)
     dialog.setWindowTitle(_('Wizard'))
     dialog.setModal(True)
     layout = QHBoxLayout(dialog)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addWidget(window)
     window.setParent(dialog)
     # self.connect( window, SIGNAL('closed()'), dialog.accept )
     # self.connect( window, oialog.accept )
     window.show()
     dialog.exec_()
Example #17
0
class WebUI(object):
    def __init__(self, url='https://google.com'):
        w = 1280
        h = 960

        self.url = url
        self.app = QApplication([])
        self.app.setApplicationName('test')
        self.app.setWindowIcon(QIcon('../icon.svg'))
        self.view = QWebEngineView(self.app.activeModalWidget())
        self.view.window().resize(w, h)

    def run_gui(self):
        self.view.load(QUrl(self.url))

        change_setting = self.view.page().settings().setAttribute
        settings = QWebEngineSettings
        change_setting(settings.LocalStorageEnabled, True)
        change_setting(settings.PluginsEnabled, True)
        change_setting(settings.DnsPrefetchEnabled, True)

        self.view.show()
        sys.exit(self.app.exec_())
Example #18
0
 def switch_to_tab(self, idx):
     if not QApplication.activeModalWidget():
         self.tab_center.setCurrentIndex(idx)
Example #19
0
    async def _on_next_clicked(self):
        if isinstance(self.current_widget, CreateOrgUserInfoWidget):
            backend_addr = None
            org_id = None
            device_label = None
            human_handle = None

            if self.start_addr:
                backend_addr = self.start_addr
            else:
                try:
                    org_id = OrganizationID(
                        self.current_widget.line_edit_org_name.text())
                except ValueError as exc:
                    show_error(self,
                               _("TEXT_ORG_WIZARD_INVALID_ORGANIZATION_ID"),
                               exception=exc)
                    return
                try:
                    backend_addr = BackendOrganizationBootstrapAddr.build(
                        backend_addr=self.current_widget.backend_addr
                        if self.current_widget.radio_use_custom.isChecked()
                        else self.config.preferred_org_creation_backend_addr,
                        organization_id=org_id,
                    )
                except ValueError as exc:
                    show_error(self,
                               _("TEXT_ORG_WIZARD_INVALID_BACKEND_ADDR"),
                               exception=exc)
                    return
            try:
                user_name = validators.trim_user_name(
                    self.current_widget.line_edit_user_full_name.text())

                human_handle = HumanHandle(
                    self.current_widget.line_edit_user_email.text(), user_name)
            except ValueError as exc:
                show_error(self,
                           _("TEXT_ORG_WIZARD_INVALID_HUMAN_HANDLE"),
                           exception=exc)
                return
            # No try/except given `self.current_widget.line_edit_device` has already been validated against `DeviceLabel`
            try:
                device_label = DeviceLabel(
                    self.current_widget.line_edit_device.text())
            except ValueError as exc:
                show_error(self,
                           _("TEXT_ORG_WIZARD_INVALID_DEVICE_LABEL"),
                           exception=exc)
                return

            # TODO: call `await _do_create_org` directly since the context is now async
            self.create_job = self.jobs_ctx.submit_job(
                self.req_success,
                self.req_error,
                _do_create_org,
                config=self.config,
                human_handle=human_handle,
                device_label=device_label,
                backend_addr=backend_addr,
            )
            self.dialog.button_close.setVisible(False)
            self.button_validate.setEnabled(False)
        else:
            auth_method = self.current_widget.get_auth_method()
            try:
                if auth_method == DeviceFileType.PASSWORD:
                    save_device_with_password_in_config(
                        self.config.config_dir, self.new_device,
                        self.current_widget.get_auth())
                elif auth_method == DeviceFileType.SMARTCARD:
                    await save_device_with_smartcard_in_config(
                        self.config.config_dir, self.new_device)
                self.status = (self.new_device, auth_method,
                               self.current_widget.get_auth())

                if self.dialog:
                    self.dialog.accept()
                elif QApplication.activeModalWidget():
                    QApplication.activeModalWidget().accept()
                else:
                    logger.warning("Cannot close dialog when org wizard")
            except LocalDeviceCryptoError as exc:
                if auth_method == DeviceFileType.SMARTCARD:
                    show_error(self,
                               _("TEXT_INVALID_SMARTCARD"),
                               exception=exc)
            except LocalDeviceNotFoundError as exc:
                if auth_method == DeviceFileType.PASSWORD:
                    show_error(self,
                               _("TEXT_CANNOT_SAVE_DEVICE"),
                               exception=exc)
            except LocalDeviceError as exc:
                show_error(self, _("TEXT_CANNOT_SAVE_DEVICE"), exception=exc)
Example #20
0
class TestClass:
    # TODO: refactoring, make parts of tests reusable
    # TODO: remove old tests which are not working/covered by new ones
    def setup_method(self):
        base = ".\\resources\\test_data"
        data_source = base + "\\source"
        tempdir = base + "\\temp_dir"
        try:
            rmtree(tempdir)
        except FileNotFoundError:
            pass

        copytree(data_source, tempdir)  # Throws file not found exception

        self.app = QApplication([])
        self.ui = ExampleApp(".\\resources\\CloneSpyResult.txt")
        self.menu = self.ui.menuBar()
        self.ui.show()
        QTest.qWaitForWindowExposed(self.ui)

    def teardown_method(self):
        rmtree(".\\resources\\test_data\\temp_dir")

    # todo check if this test should be left/removed/fixed
    @pytest.mark.parametrize("key, row, expected_action",
                             [(Qt.Key_D, 0, "Delete"),
                              (Qt.Key_H, -1, "Hardlink"), (Qt.Key_U, 0, None)])
    def test_if_key_presses_registered_as_action(self, row_chosen, qtbot, key,
                                                 row, expected_action):
        # GIVEN main window displayed and a row selected - handled by fixture
        # WHEN action key pressed
        # self.mark_rows_with_actions(row, key)
        QTest.keyPress(self.ui, key, Qt.NoModifier, 100)
        QTest.keyRelease(self.ui, key)
        # THEN Action column value changed to action
        data = list()
        for i in range(7):
            index = self.ui.model.createIndex(row, i)
            data.append(index.data(Qt.DisplayRole))
        assert data[Column.Action.index] == expected_action
        assert data[Column.Processed.index] is False

    @pytest.fixture()
    def main_window_displayed(self, qtbot):
        qtbot.addWidget(self.ui)

    @pytest.fixture()
    def row_chosen(self, main_window_displayed, row):
        if row == -1:
            row = self.ui.model.rowCount(0) - 1
        self.ui.tableView.selectRow(row)

    # todo check if this test should be left/removed/fixed
    @pytest.mark.parametrize("key, row, expected_action, expected_processed",
                             [(Qt.Key_D, 0, "Delete", True),
                              (Qt.Key_H, -1, "Hardlink", True),
                              (Qt.Key_U, 5, None, False)])
    def test_processing_changes_table_values(self, row_chosen, qtbot, key, row,
                                             expected_action,
                                             expected_processed):
        # todo reuse same logic among tests
        # GIVEN actions assigned to some files
        QTest.keyPress(self.ui, key, Qt.NoModifier, 100)
        QTest.keyRelease(self.ui, key)
        data = list()
        for i in range(7):
            index = self.ui.model.createIndex(row, i)
            data.append(index.data(Qt.DisplayRole))
        assert data[Column.Action.index] == expected_action
        assert data[Column.Processed.index] is False
        # WHEN click Execute Action button
        QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)
        # THEN Processed set == True where Action is not empty
        data.clear()
        for i in range(7):
            index = self.ui.model.createIndex(row, i)
            data.append(index.data(Qt.DisplayRole))
        assert data[Column.Processed.index] == expected_processed

    # todo add groups of more than 2 members to test data
    # todo add tests for groups mentioned above
    # todo check if this test should be left/removed/fixed
    @pytest.mark.parametrize("group_to_mark, keys",
                             [(1, [Qt.Key_D]), (-1, [Qt.Key_D]),
                              (1, [Qt.Key_D, Qt.Key_H]),
                              (2, [Qt.Key_D, Qt.Key_H, Qt.Key_D])])
    def test_group_validations_popup_message_shown(self, main_window_displayed,
                                                   group_to_mark, keys, qtbot):
        # GIVEN actions assigned to all members of some range
        if group_to_mark == -1:  # if group is -1 then take last group in the table
            last_index_row = self.ui.model.rowCount(0) - 1
            last_group_value_index = self.ui.model.createIndex(
                last_index_row, Column.Group.index)
            group_to_mark = last_group_value_index.data(Qt.DisplayRole)

        indexes_of_group = self.ui.model.find_indexes_of_value(
            Column.Group.index, group_to_mark)
        if len(keys) == 1:
            for index in indexes_of_group:
                self.ui.tableView.selectRow(index.row())
                QTest.keyPress(self.ui, keys[0], Qt.NoModifier, 0)
                QTest.keyRelease(self.ui, keys[0])
                data = list()
                for i in range(7):
                    index = self.ui.model.createIndex(index.row(), i)
                    data.append(index.data(Qt.DisplayRole))
                # group = data[Column.Group.index]
                # assert data[Column.Action.index] == expected_action todo activate
                assert data[Column.Processed.index] is False
        else:
            for index, key in zip(indexes_of_group, keys):
                self.ui.tableView.selectRow(index.row())
                QTest.keyPress(self.ui, key, Qt.NoModifier, 0)
                QTest.keyRelease(self.ui, key)
                data = list()
                for i in range(7):
                    index = self.ui.model.createIndex(index.row(), i)
                    data.append(index.data(Qt.DisplayRole))
                # group = data[Column.Group.index]
                # assert data[Column.Action.index] == expected_action todo activate
                assert data[Column.Processed.index] is False

        # WHEN click Execute Action button
        QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)

        # THEN popup shown with ranges which will be fully removed
        # QTimer.singleShot(1000, handle_popup_waiting)
        assert self.ui.files_exterminated_question_window.isActiveWindow()
        assert self.ui.files_exterminated_question_window.isVisible()
        assert str(
            group_to_mark) in self.ui.files_exterminated_question_window.text(
            )  # todo test proper format
        # WHEN clicked Cancel
        buttons = self.ui.files_exterminated_question_window.buttons()
        no_button = None
        yes_button = None
        for button in buttons:
            if 'No' in button.text():
                no_button = button
            elif 'Yes' in button.text():
                yes_button = button
        QTest.mouseClick(no_button, Qt.LeftButton)
        # THEN actions not executed and files not touched
        assert not self.ui.files_exterminated_question_window.isActiveWindow()
        assert not self.ui.files_exterminated_question_window.isVisible()
        # todo assert files exist
        # todo add validation of popup text
        # WHEN click Execute Action button again
        QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)
        # THEN popup shown with ranges which will be fully removed
        assert self.ui.files_exterminated_question_window.isActiveWindow()
        assert self.ui.files_exterminated_question_window.isVisible()
        # WHEN clicked Yes
        QTest.mouseClick(yes_button, Qt.LeftButton)
        # THEN actions applied to duplicates, files removed
        assert not self.ui.files_exterminated_question_window.isActiveWindow()
        assert not self.ui.files_exterminated_question_window.isVisible()
        # todo assert files not exist
        assert 1

    def mark_rows_with_keys(self, rows, keys):
        actions = self.convert_keys_to_actions(keys)
        for row, key, action in zip(rows, keys, actions):
            if row == -1:
                row = self.ui.model.rowCount(0) - 1
            self.ui.tableView.selectRow(row)
            QTest.keyPress(self.ui, key, Qt.NoModifier, 100)
            QTest.keyRelease(self.ui, key)
            data = list()
            for i in range(7):
                index = self.ui.model.createIndex(row, i)
                data.append(index.data(Qt.DisplayRole))
            # group = data[Column.Group.index]
            assert data[Column.Action.index] == action.value
            assert data[Column.Processed.index] is False

    def convert_keys_to_actions(self, keys):
        actions = list()
        for key in keys:
            if key == Qt.Key_D:
                actions.append(Action.delete)
            elif key == Qt.Key_H:
                actions.append(Action.hardlink)
            elif key == Qt.Key_S:
                actions.append(Action.source)
            elif key == Qt.Key_N:
                actions.append(Action.none)
        return actions

    def handle_question_window(self, accept, group):
        w = self.app.activeModalWidget()
        assert w.isVisible()
        window_text = w.text()
        assert str(group) in window_text

        no_button, yes_button = self.find_buttons()
        if accept:
            yes_button.click()
        else:
            no_button.click()

        assert not w.isVisible()

    def find_buttons(self):
        buttons = self.ui.files_exterminated_question_window.buttons()
        no_button = None
        yes_button = None
        for button in buttons:
            if 'No' in button.text():
                no_button = button
            elif 'Yes' in button.text():
                yes_button = button
        return no_button, yes_button

    def get_actions_in_group(self, group_number):
        group_indexes = self.ui.model.find_indexes_of_value(
            Column.Group.index, group_number)
        actions = self.get_actions_from_group_indexes(group_indexes)
        actions_objects = list()
        for action in actions:
            actions_objects.append(Action(action))
        return actions_objects

    def get_actions_from_group_indexes(self, group_indexes):
        actions = list()
        for group_index in group_indexes:
            action_index = self.ui.model.createIndex(group_index.row(),
                                                     Column.Action.index)
            action = action_index.data(Qt.DisplayRole)
            actions.append(action)
        return actions

    def get_errors_for_group(self, group_number):
        indexes_of_group = self.ui.model.find_indexes_of_value(
            Column.Group.index, group_number)
        rows_of_group = (index.row() for index in indexes_of_group)
        errors = self.ui.current_errors.copy()
        errors_of_group = list()
        for error in errors:
            if error.row_causing_the_error in rows_of_group:
                errors_of_group.append(error)
        return errors_of_group

    def mark_group_with_keys(self, group, keys):
        indexes_of_group = self.ui.model.find_indexes_of_value(
            Column.Group.index, group)
        rows = (index.row() for index in indexes_of_group)
        self.mark_rows_with_keys(rows, keys)

    # todo fix this test or functionality
    @pytest.mark.parametrize(
        "rows, keys, groups_in_prompt",
        [
            # TC04
            ([0, 1, 2], [Qt.Key_D, Qt.Key_D, Qt.Key_D], "1"),
            ([13, 14], [Qt.Key_D, Qt.Key_D], "5")
        ])
    def test_groups_extermination_popup_message_shown(self,
                                                      main_window_displayed,
                                                      rows, keys,
                                                      groups_in_prompt, qtbot):
        # GIVEN actions assigned to all members of some group
        self.mark_rows_with_keys(rows, keys)

        # WHEN click Execute Action button
        QTimer.singleShot(
            1000, lambda: self.handle_question_window(False, groups_in_prompt))
        QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)

        # THEN popup shown with ranges which will be fully removed
        # WHEN clicked Cancel
        # THEN actions not executed and files not touched
        paths = list()
        indexes = self.ui.model.find_indexes_of_value(Column.Group.index,
                                                      int(groups_in_prompt))
        for index in indexes:
            file_index = self.ui.model.createIndex(index.row(),
                                                   Column.Path.index)
            path = file_index.data(Qt.EditRole)
            paths.append(path)
            assert os.path.isfile(path)

        # WHEN click Execute Action button again
        QTimer.singleShot(
            1000, lambda: self.handle_question_window(True, groups_in_prompt))
        QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)

        # THEN popup shown with ranges which will be fully removed

        # WHEN clicked Yes
        # THEN actions applied to duplicates, files removed
        for path in paths:
            assert not os.path.isfile(path)
            assert len(winshell.ShellRecycleBin().versions(str(path))) > 0

    @pytest.mark.parametrize(
        "keys_to_assign, group_number",
        [
            # TC00
            ([], 1),
            # TC01
            ([Qt.Key_D, Qt.Key_D], 1),
            # TC02
            ([Qt.Key_D], 3)
        ])
    def test_positive_no_errors_assigned(self, main_window_displayed, qtbot,
                                         keys_to_assign, group_number):
        # GIVEN list of duplicates displayed
        # WHEN actions assigned to the group
        if len(keys_to_assign) > 0:
            indexes_of_group = self.ui.model.find_indexes_of_value(
                Column.Group.index, group_number)
            rows = (index.row() for index in indexes_of_group)
            self.mark_rows_with_keys(rows, keys_to_assign)

        # THEN there's no errors raised for the group
        errors = self.get_errors_for_group(group_number)
        assert len(errors) == 0

    @pytest.mark.parametrize(
        "keys_to_assign, group_number, action_expected_from_autocompletion",
        [
            # TC01-2
            ([Qt.Key_H], 2, Action.source),
            ([Qt.Key_H, Qt.Key_D, Qt.Key_D, Qt.Key_D], 3, Action.source),
            # TC01-3
            ([Qt.Key_S], 2, Action.hardlink),
            ([Qt.Key_N, Qt.Key_D, Qt.Key_D, Qt.Key_S, Qt.Key_D
              ], 3, Action.hardlink)
        ])
    def test_auto_completion_of_actions(self, main_window_displayed, qtbot,
                                        keys_to_assign, group_number,
                                        action_expected_from_autocompletion):
        # GIVEN duplicates displayed
        # WHEN actions assigned to rows
        indexes_of_group = self.ui.model.find_indexes_of_value(
            Column.Group.index, group_number)
        rows = (index.row() for index in indexes_of_group)
        self.mark_rows_with_keys(rows, keys_to_assign)

        # THEN there's no errors raised for the group
        errors = self.get_errors_for_group(group_number)
        assert len(errors) == 0
        # AND autocompletion added actions to the group
        actions = self.get_actions_in_group(group_number)
        assert action_expected_from_autocompletion in actions

    @pytest.mark.parametrize(
        "keys_to_assign, group_number, error_type_expected, error_rownumber_expected",
        [
            # TC03
            ([Qt.Key_H, Qt.Key_D, Qt.Key_H
              ], 3, ValidationErrorType.source_for_hardlink_absence, 5),
            # TC06
            ([Qt.Key_S, Qt.Key_D, Qt.Key_D
              ], 3, ValidationErrorType.hardlink_absence, 5),
            # TC05-1
            ([Qt.Key_H, Qt.Key_D, Qt.Key_D, Qt.Key_D, Qt.Key_D
              ], 3, ValidationErrorType.source_for_hardlink_absence, 5),
            # TC05-2
            ([Qt.Key_D, Qt.Key_D, Qt.Key_S, Qt.Key_D, Qt.Key_D
              ], 3, ValidationErrorType.hardlink_absence, 7),
            # TC07
            ([Qt.Key_S, Qt.Key_D, Qt.Key_S
              ], 3, ValidationErrorType.more_than_one_source_in_group, 5)
        ])
    def test_source_and_hardlink_errors_validation(self, main_window_displayed,
                                                   qtbot, keys_to_assign,
                                                   group_number,
                                                   error_type_expected,
                                                   error_rownumber_expected):
        # GIVEN duplicates displayed
        # WHEN actions assigned to rows
        self.mark_group_with_keys(group_number, keys_to_assign)
        # THEN new error generated and assigned to the row
        errors = self.get_errors_for_group(group_number)

        assert error_type_expected in (err.error_type for err in errors)
        assert error_rownumber_expected in (err.row_causing_the_error
                                            for err in errors)

    @pytest.mark.parametrize(
        "keys_to_assign_1, group_number_1, error_row_1, keys_to_assign_2, group_number_2, error_row_2",
        [([Qt.Key_H, Qt.Key_D, Qt.Key_D], 1, 0, [Qt.Key_D, Qt.Key_D, Qt.Key_S
                                                 ], 3, 7),
         ([Qt.Key_H, Qt.Key_H, Qt.Key_D], 1, 0, [Qt.Key_D, Qt.Key_D, Qt.Key_S
                                                 ], 3, 7)])
    def test_errors_controls_behavior(self, main_window_displayed, qtbot,
                                      keys_to_assign_1, group_number_1,
                                      error_row_1, keys_to_assign_2,
                                      group_number_2, error_row_2):
        # GIVEN duplicates displayed
        # WHEN actions assigned to rows
        self.mark_group_with_keys(group_number_1, keys_to_assign_1)
        # THEN error counter changed
        assert self.ui.label_errors_count.text() == "Errors found: 1"
        # AND label color changed
        assert self.ui.label_errors_count.styleSheet() == "color: red"
        # AND row has red color
        error_row_1_index = self.ui.model.createIndex(error_row_1, 0)
        color1 = error_row_1_index.data(Qt.ForegroundRole)
        assert color1 == QtGui.QColor("red")
        # self.ui.model.data()
        # error_row_1

        # WHEN another actions assigned to another rows
        self.mark_group_with_keys(group_number_2, keys_to_assign_2)
        # THEN error counter changed
        assert self.ui.label_errors_count.text() == "Errors found: 2"
        # AND row has red color
        error_row_2_index = self.ui.model.createIndex(error_row_1, 0)
        color2 = error_row_2_index.data(Qt.ForegroundRole)
        assert color2 == QtGui.QColor("red")

        # AND navigation buttons can be used to go to next and previous errors
        next_error = self.ui.btn_next_error
        prev_error = self.ui.btn_previous_error
        QTest.mouseClick(prev_error, Qt.LeftButton)
        assert self.ui.tableView.currentIndex().row() == error_row_1
        QTest.mouseClick(prev_error, Qt.LeftButton)
        assert self.ui.tableView.currentIndex().row() == error_row_2
        QTest.mouseClick(next_error, Qt.LeftButton)
        assert self.ui.tableView.currentIndex().row() == error_row_1
        QTest.mouseClick(next_error, Qt.LeftButton)
        assert self.ui.tableView.currentIndex().row() == error_row_2

    @pytest.mark.parametrize("row_to_select, action", [(1, Action.delete),
                                                       (6, Action.hardlink)])
    def test_mark_siblings_actions(self, main_window_displayed, qtbot,
                                   row_to_select, action):
        # GIVEN some row selected
        self.ui.tableView.selectRow(row_to_select)
        row_path_index = self.ui.model.createIndex(row_to_select,
                                                   Column.Path.index)
        # row_action_index = self.ui.model.createIndex(row_to_select, Column.Action.index)
        # row_action = row_action_index.data(Qt.DisplayRole)
        row_path = row_path_index.data(Qt.EditRole)
        row_path_parent = row_path.parent

        # WHEN some mark action triggered
        if action == Action.delete:
            trigger = self.ui.actionDelete_sibling_duplicates
        elif action == Action.hardlink:
            trigger = self.ui.actionHardlink_sibling_duplicates
        # elif action == Action.source:
        # action = self.ui.actionSource_sibling_duplicates
        # todo add Source mark action to gui and main method
        trigger.trigger()

        # THEN all rows from the same folder marked selected action
        #   get all the rows
        rowcount = self.ui.model.rowCount(0)
        # columncount = self.ui.model.columnCount()
        for rownum in range(rowcount):
            path_index = self.ui.model.createIndex(rownum, Column.Path.index)
            action_index = self.ui.model.createIndex(rownum,
                                                     Column.Action.index)
            action_to_check = action_index.data(Qt.EditRole)
            path_to_check = path_index.data(Qt.EditRole)
            path_to_check_parent = path_to_check.parent
            #   check that rows with the same folder have chosen action
            if path_to_check_parent == row_path_parent:
                assert action_to_check == action
            #   check that rows with another folder don't have chosen action
            else:
                assert action_to_check != action

    @pytest.mark.parametrize("row, key", [(0, Qt.Key_D), (-1, Qt.Key_D)])
    def test_files_are_deleted(self, main_window_displayed, row, key, qtbot):
        # GIVEN main window displayed
        # WHEN action assigned to files
        self.mark_rows_with_keys([row], [key])
        # QTest.keyPress(self.ui, key, Qt.NoModifier, 100)
        # QTest.keyRelease(self.ui, key)
        data = list()
        for i in range(7):
            index = self.ui.model.createIndex(row, i)
            data.append(index.data(Qt.DisplayRole))
        assert data[Column.Processed.index] is False
        # AND click Execute Action button
        # Watch for the app.worker.finished signal, then start the worker.
        with qtbot.waitSignal(self.ui.files_processor_worker.finished,
                              timeout=10000) as blocker:
            # blocker.connect(self.ui.files_processor_worker.failed)  # Can add other signals to blocker
            QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)
            # app.worker.start()
            # Test will block at this point until signal is emitted or
            # 10 seconds has elapsed
        # QTest.mouseClick(self.ui.pushButton_2, Qt.LeftButton)
        # qtbot.waitSignal(self.ui.files_processor_worker.finished, 10000)
        # THEN files are moved to recycle bin
        data.clear()
        for i in range(7):
            index = self.ui.model.createIndex(row, i)
            data.append(index.data(Qt.DisplayRole))
        print(self.ui.model._data)
        assert data[Column.Processed.index] is True
        file_exists = pathlib.Path(data[Column.Path.index]).is_file()
        assert not file_exists
Example #21
0
 def set_file(self, fileName):
     QTest.qWaitForWindowActive(CoverEqualityTests.gui)
     QtCore.QTimer.singleShot(2000, lambda: inject(QApplication.activeModalWidget(), fileName))
     QTest.keyPress(CoverEqualityTests.gui, Qt.Key_O, Qt.ControlModifier)
     QTest.keyRelease(CoverEqualityTests.gui, Qt.Key_O, Qt.ControlModifier)
Example #22
0
 def test_bad_fix_cover(self):
     QTest.mouseClick(CoverEqualityTests.gui.ui.clearCoverBtn, Qt.LeftButton)
     QtCore.QTimer.singleShot(1000, lambda: self.assertTrue(len(QApplication.activeModalWidget().buttons())==3))
     QtCore.QTimer.singleShot(2000, lambda: QTest.mouseClick(QApplication.activeModalWidget().buttons()[0], Qt.LeftButton))
     QTest.mouseClick(CoverEqualityTests.gui.ui.testCoverBtn, Qt.LeftButton)
     return True
Example #23
0
    def msgbox(cls,
               typename,
               text,
               button0,
               button1=None,
               button2=None,
               title=None,
               form=None) -> Any:
        """Return a messageBox."""
        from pineboolib import application

        if application.PROJECT._splash:
            application.PROJECT._splash.hide()

        if not isinstance(text, str):
            logger.warning("MessageBox help!", stack_info=True)
            # temp = text
            text = button1
            button1 = title
            title = button0
            button0 = button2
            button2 = None

        if form:
            logger.warning(
                "MessageBox: Se intentó usar form, y no está implementado.")
        icon = QMessageBox.NoIcon
        if not title:
            title = "Pineboo"
        if typename == "question":
            icon = QMessageBox.Question
            if not title:
                title = "Question"
        elif typename == "information":
            icon = QMessageBox.Information
            if not title:
                title = "Information"
        elif typename == "warning":
            icon = QMessageBox.Warning
            if not title:
                title = "Warning"
        elif typename == "critical":
            icon = QMessageBox.Critical
            if not title:
                title = "Critical"
        # title = unicode(title,"UTF-8")
        # text = unicode(text,"UTF-8")
        msg = QMessageBox(icon, title, text)
        parent = QApplication.activeModalWidget(
        ) or application.PROJECT.main_window
        msg.setParent(parent)

        msg.setWindowModality(QtCore.Qt.ApplicationModal)
        msg.setEnabled(True)
        if button0:
            msg.addButton(button0)
        if button1:
            msg.addButton(button1)
        if button2:
            msg.addButton(button2)

        # size = msg.sizeHint()
        # screen_rect = QDesktopWidget().screenGeometry(parent)
        # screen_num = QDesktopWidget().screenNumber(parent)
        # geo = QDesktopWidget().availableGeometry(screen_num)
        # print("*", geo, geo.x(), geo.y())
        # msg.move(QPoint(geo.x() + ( geo.width() / 2 ) + 100, geo.y() + ( geo.height() / 2 )))

        return msg.exec_()
Example #24
0
 def set_file(self, delim, fileName):
     QTest.qWaitForWindowActive(ReadFileTests.gui)
     QtCore.QTimer.singleShot(1000, lambda: inject(QApplication.activeModalWidget(), delim))
     QtCore.QTimer.singleShot(2000, lambda: inject(QApplication.activeModalWidget(), fileName))
     QTest.keyPress(ReadFileTests.gui, Qt.Key_F, Qt.ControlModifier | Qt.ShiftModifier)
     QTest.keyRelease(ReadFileTests.gui, Qt.Key_F, Qt.ControlModifier | Qt.ShiftModifier)