Example #1
0
def main():
    app = QApplication(sys.argv)
    snake_game = SnakeGame()
    snake_game.show()
    app.exec_()
    app.deleteLater()
    sys.exit()
Example #2
0
class MenuBarTest(unittest.TestCase):
    def setUp(self) -> None:
        self.app = QApplication([])
        self.main = QMainWindow()
        self.menubar = MenuBar(self.main)

        # Define menu buttons (they are on top ot the menu bar)
        self.file_menu = self.menubar.actions()[0].menu()
        self.help_menu = self.menubar.actions()[1].menu()

        # Define actions for the "File" menu (these actions appear then is putted the cursor in the "File" menu)
        self.new_file_button = self.file_menu.actions()[0]
        self.open_file_button = self.file_menu.actions()[1]

        # Define actions for the "Help" menu (these actions appear then is putted the cursor in the "Help" menu)
        self.about_button = self.help_menu.actions()[0]

    def tearDown(self):
        self.app.deleteLater()

    # These paths aren't exist
    @unittest.mock.patch('src.menu.menu_bar.MenuBar.ABOUT_ICON_PATH',
                         'wrong_about')
    @unittest.mock.patch('src.menu.menu_bar.MenuBar.OPEN_ICON_PATH',
                         'wrong_open')
    @unittest.mock.patch('src.menu.menu_bar.MenuBar.CREATE_ICON_PATH',
                         'wrong_create')
    @unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
    def test_incorrect_default_icons_filenames(self, mock_stdout):
        # The constructor will check paths and will print errors to the console. Important to compare this
        # text in the console and that error message
        menubar = MenuBar(self.main)
        self.assertEqual(
            mock_stdout.getvalue(),
            f"Error: No such file: {MenuBar.CREATE_ICON_PATH}\n"
            f"Error: No such file: {MenuBar.OPEN_ICON_PATH}\n"
            f"Error: No such file: {MenuBar.ABOUT_ICON_PATH}\n")

    # It's necessary to not show the dialog window
    @unittest.mock.patch('PyQt5.QtWidgets.QDialog.show', print)
    def test_pressing_button_create_file(self):
        # The dialog of creating new file doesn't exist at the moment
        with self.assertRaises(AttributeError):
            var = self.main.new_file_dialog

        # Click the button of creating new file
        self.new_file_button.trigger()
        # And now that dialog exists
        self.assertIsNotNone(self.main.new_file_dialog)

    @unittest.mock.patch('PyQt5.QtWidgets.QMessageBox.show', print)
    def test_pressing_button_information(self):
        with self.assertRaises(AttributeError):
            var = self.menubar.info_message

        self.about_button.trigger()
        self.assertIsNotNone(self.menubar.info_message)
        self.assertEqual(self.menubar.info_message.windowTitle(),
                         'О программе')
Example #3
0
def show_image_viewer(image: QImage):
    app = QApplication([])

    viewer = QtImageViewer(image)
    viewer.show()

    exit_code = app.exec()
    app.deleteLater()
    return exit_code
Example #4
0
class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.main = QMainWindow()
        self.new_map = NewFileDialog(self.main)

    def tearDown(self):
        self.app.deleteLater()

    @unittest.mock.patch("src.menu.new_file.NewFileDialog.ICONS_IMAGES_DIR",
                         'incorrect')
    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_incorrect_path_icon(self, io_string):
        NewFileDialog(QMainWindow())
        self.assertEqual(io_string.getvalue(),
                         'Error: No such file: incorrect\\mainIcon.png\n')

    @unittest.mock.patch("src.menu.new_file.NewFileDialog.FILENAME_UI",
                         'incorrect')
    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_incorrect_io_file(self, io_string):
        # When you create an instance, FileNotFoundError will be raised and sys.exit will be called
        with self.assertRaises(SystemExit):
            NewFileDialog(QMainWindow())

    def test_default_flags(self):
        self.assertFalse(self.new_map.incorrect_map_filename)
        self.assertFalse(self.new_map.incorrect_troops_directory)

    def test_setting_modality(self):
        self.assertTrue(self.new_map.isModal())

    @unittest.mock.patch("PyQt5.QtWidgets.QDialog.sender")
    def test_remove_widget(self, sender):
        sender.return_value = self.new_map.mapsDirectoryLine
        self.new_map.incorrect_map_filename = True
        with self.assertRaises(AttributeError):
            self.new_map.correct_wrong_path()

        sender.return_value = self.new_map.troopsDirectoryLine
        self.new_map.incorrect_troops_directory = True
        with self.assertRaises(AttributeError):
            self.new_map.correct_wrong_path()

    @unittest.mock.patch("PyQt5.QtWidgets.QDialog.sender")
    def test_correct_wrong_map_file(self, sender):
        sender.return_value = self.new_map.mapsDirectoryLine
        self.new_map.incorrect_map_filename = True

        self.new_map.error_maps_lbl = QLabel("test")
        self.new_map.VLayout.addWidget(self.new_map.error_maps_lbl)
        self.assertIsNotNone(self.new_map.error_maps_lbl)
        self.new_map.correct_wrong_path()

        self.assertFalse(self.new_map.incorrect_map_filename)
        self.assertIsNone(self.new_map.error_maps_lbl)
Example #5
0
def main(argv=None):
    if not argv:
        argv = sys.argv

    app = QApplication(argv)
    window = MainWindow()
    window.show()
    result = app.exec_()
    app.deleteLater()
    return result
Example #6
0
def main():

    app = QApplication(sys.argv)
    ex = Run_gui()
    #sys.exit(app.exec_())

    # avoid message 'Segmentation fault (core dumped)' with app.deleteLater()
    app.exec()
    app.deleteLater()
    sys.exit()
Example #7
0
class TestSetupNetworkWidget(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.testNetworkWidget = SetupNetworkWidget()

    def tearDown(self):
        self.testNetworkWidget.deleteLater()
        self.app.deleteLater()
        self.app.quit()

    def test_can_always_go_back(self):
        self.assertTrue(self.testNetworkWidget.canGoBack())
Example #8
0
class TestFirstStartSummaryWidget(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.testSummaryWidget = FirstStartSummaryWidget()

    def tearDown(self):
        self.testSummaryWidget.deleteLater()
        self.app.deleteLater()
        self.app.quit()

    def test_can_always_go_back(self):
        self.assertTrue(self.testSummaryWidget.canGoBack())

    def test_can_never_proceed(self):
        self.assertFalse(self.testSummaryWidget.canProceed())
Example #9
0
class MainWindowTest(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.main_window = MainWindow()
        self.desktop = QDesktopWidget().availableGeometry()

    def tearDown(self):
        self.app.deleteLater()

    def test_width_height(self):
        self.assertEqual(self.main_window.width(), self.desktop.width() - 100)
        self.assertEqual(self.main_window.height(),
                         self.desktop.height() - 100)

    def test_minimum_width_height(self):
        self.assertEqual(self.main_window.minimumWidth(), 800)
        self.assertEqual(self.main_window.minimumHeight(), 600)

    def test_center_point(self):
        x = self.main_window.geometry().center().x()
        y = self.main_window.geometry().center().y()

        x_desktop = self.desktop.center().x()
        y_desktop = self.desktop.center().y()

        # The main window's center point is set like the half of width or height of desktop
        # Therefore, variation between them must be less 1
        self.assertTrue(abs(x - x_desktop) <= 1)
        self.assertTrue(abs(y - y_desktop) <= 1)

    def test_setting_menubar(self):
        # Test that menubar was set. If it's new QMainWindow, then its menu bar must be None
        self.assertIsNotNone(self.main_window.menuWidget())
        self.assertIsNone(QMainWindow().menuWidget())

    def test_setting_title_parameters(self):
        self.assertEqual(self.main_window.windowTitle(), 'Troops review')
        # Check default icon path is a file
        self.assertTrue(isfile(self.main_window.ICON_PATH))

    # It's necessary to not print an error to the console
    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_setting_central_widget(self, string_io):
        # The central widget isn't set at the moment
        self.assertIsNone(self.main_window.centralWidget())
        self.main_window.setup_central_widget('first', 'second')
        # But now it's set
        self.assertIsNotNone(self.main_window.centralWidget())
Example #10
0
    def test_syncFiles_sends_retrieve_files_message_with_callback(
            self, mockGetInstance):
        fakeHub = MagicMock()
        mockGetInstance.return_value = fakeHub

        from view.mainpanel import MainPanel
        app = QApplication([])
        testMainPanelWidget = MainPanel()

        testMainPanelWidget.syncFileList()

        testMainPanelWidget.deleteLater()
        app.deleteLater()
        app.quit()

        self.assertEqual(
            fakeHub.sendNetworkMessage.call_args[0][0].header.messageType,
            MessageTypes.SYNC_FILES)
        self.assertIsNotNone(fakeHub.sendNetworkMessage.call_args[0][1])
Example #11
0
class TestDialogs(TestCase):
    def setUp(self):
        super(TestDialogs, self).setUp()
        self.app = QApplication(sys.argv)

    def tearDown(self):
        super(TestDialogs, self).tearDown()
        self.app.exit(0)
        self.app.deleteLater()

    def test_dialogs(self):
        window = QMainWindow()
        PaymentsDialog(window)
        EnvironmentsDialog(window)
        NodeNameDialog(window)
        dialog = ChangeTaskDialog(window)
        dialog.can_be_closed = False
        dialog.close()
        dialog.can_be_closed = True
        dialog.close()
        window.close()
Example #12
0
def main():
    parser = argparse.ArgumentParser(
        description="Minimal BibTeX reference manager and PDF viewer.")
    parser.add_argument(
        '-c', '--config',
        help="Config file.")
    parser.add_argument(
        '-b', '--bibfile',
        help="BibTeX file to use for the library.")
    parser.add_argument(
        '-p', '--pdfdir',
        help="Path to directory containing PDF documents.")
    args = parser.parse_args()

    app = QApplication([])
    main_window = mainwindow.MainWindow(bibfile=args.bibfile,
                                        pdfdir=args.pdfdir)
    main_window.show()
    app.exec_()
    app.deleteLater()
    sys.exit(0)
Example #13
0
def run():
    if getattr(sys, 'frozen', False):
        print("Running in a bundle")
        # running in a bundle
        sys.path.append(os.path.join(sys._MEIPASS, 'src'))
        imgDir = os.path.join(sys._MEIPASS, 'img')
        # if linux export qt plugins path
        if sys.platform == 'linux':
            os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = os.path.join(
                sys._MEIPASS, 'PyQt5', 'Qt', 'plugins')
    else:
        # running live
        print("Running live")
        sys.path.append(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src'))
        imgDir = os.path.abspath(
            os.path.join(
                os.path.join(
                    os.path.join(os.path.join(__file__, os.pardir), os.pardir),
                    os.pardir), 'img'))

    # Create App and main window
    from PyQt5.QtWidgets import QApplication
    try:
        from .mainwindow import MainWindow
    except ImportError:
        from mainwindow import MainWindow
    app = QApplication(sys.argv)
    ex = MainWindow(app, APP_VERSION, imgDir)

    # Execute App
    app.exec_()
    try:
        app.deleteLater()
    except Exception as e:
        print(e)

    sys.exit()
Example #14
0
File: app.py Project: yhnu/mmgui
class App(Context):
    def __init__(self,
                 headless: bool = False,
                 icon_file=None,
                 splash_file=None,
                 splash_text=None,
                 configs_file=None,
                 log_file=None):
        self._headless = headless
        self._configs_file = configs_file
        self._icon_file = icon_file
        self._splash_file = splash_file
        self._splash_text = splash_text
        self._log_file = log_file
        self._settings: QSettings = None
        self._qt_application = None
        self._events_callback = {"create": [], "destroy": []}

    def on(self, event: str, callback: Callable[[Context], None]) -> NoReturn:
        if event not in self._events_callback:
            raise Exception("unsupported event %s" % event)
        self._events_callback[event].append(callback)

    def _notify_callback(self, event: str) -> NoReturn:
        if event not in self._events_callback:
            raise Exception("unsupported event %s" % event)
        for callback in self._events_callback[event]:
            callback(self)

    def on_create(self) -> NoReturn:
        self._notify_callback("create")

    def on_destroy(self) -> NoReturn:
        self._notify_callback("destroy")

    def run(self) -> int:
        setup_stdio()
        setup_console()
        run_as_job()

        argv = sys.argv[:]
        if self._headless:
            self._qt_application = QCoreApplication(argv)  # Non-GUI
            signal.signal(signal.SIGINT,
                          lambda *a: self._qt_application.quit())
        else:
            self._qt_application = QApplication(argv)

        # icon
        if self._icon_file:
            self._window_icon = QtGui.QIcon(self._icon_file)
            self._qt_application.setWindowIcon(self._window_icon)

        # splash
        if self._splash_file:
            pixmap = QtGui.QPixmap(self._splash_file)
            self._splash = QSplashScreen(pixmap)
            if self._splash_text:
                self._set_splash_text(self._splash_text, "#ffffff")
            self._splash.show()

        # asyncqt
        asyncqt_ui_thread_loop.start_loop()

        # configs
        if self._configs_file:
            self._settings = QSettings(self._configs_file, QSettings.IniFormat)
            self._settings.sync()

        # log
        if self._log_file:
            logfp = open(self._log_file, 'w')
            STDERR_STREAMS.add(logfp)
            STDOUT_STREAMS.add(logfp)

        self._qt_application.aboutToQuit.connect(self._on_quit)
        self.on_create()  # -> create and show the WebView window
        exit_code = self._qt_application.exec_()
        self._qt_application.deleteLater()
        return exit_code
        #sys.exit(exit_code)

    def _set_splash_text(self, text, color):
        self._splash.showMessage(text,
                                 alignment=QtCore.Qt.AlignHCenter
                                 | QtCore.Qt.AlignBottom,
                                 color=QtGui.QColor(color))

    def set_main_window(self, window):
        if window:
            self._splash.finish(window)
            window.setWindowIcon(self._window_icon)

    def get_config(self, key, def_val=None):
        if self._settings:
            return self._settings.value(key, def_val)
        return def_val

    def _on_quit(self):
        self.on_destroy()

    def exit(self) -> NoReturn:
        self._qt_application.quit()

    def get_application_dir_path(self):
        return self._qt_application.applicationDirPath()
Example #15
0
class TestDropboxAccountForm(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.testAccountForm = DropboxAccountForm()

    def tearDown(self):
        self.app.deleteLater()
        self.app.quit()

    def test_setAccountData_sets_data(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.Dropbox,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": {
                    "apiToken": "testAPIToken"
                },
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        componentAccountData = self.testAccountForm.getAccountData()

        self.assertEqual(testAccountData.accountType,
                         componentAccountData.accountType)
        self.assertEqual(testAccountData.identifier,
                         componentAccountData.identifier)
        self.assertEqual(testAccountData.cryptoKey,
                         componentAccountData.cryptoKey)
        self.assertEqual(testAccountData.data, componentAccountData.data)
        self.assertEqual(testAccountData.id, componentAccountData.id)

    def test_reset_clears_account_specific_data_and_only_that(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.Dropbox,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": {
                    "apiToken": "testAPIToken"
                },
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)
        self.testAccountForm.reset()

        componentAccountData = self.testAccountForm.getAccountData()

        self.assertEqual(componentAccountData.accountType,
                         testAccountData.accountType)
        self.assertEqual(componentAccountData.identifier, "")
        self.assertEqual(componentAccountData.cryptoKey, "")
        self.assertEqual(componentAccountData.data, {"apiToken": ""})
        self.assertEqual(componentAccountData.id, testAccountData.id)

    def test_isFormValid_returns_true_on_valid_account_data(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.Dropbox,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": {
                    "apiToken": "testAPIToken"
                },
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertTrue(self.testAccountForm.isFormValid())

    def test_isFormValid_returns_false_on_missing_identifier(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.Dropbox,
                "identifier": "",
                "cryptoKey": "sixteen byte key",
                "data": {
                    "apiToken": "testAPIToken"
                },
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertFalse(self.testAccountForm.isFormValid())

    def test_isFormValid_returns_false_on_missing_cryptoKey(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.Dropbox,
                "identifier": "testAccount",
                "cryptoKey": "",
                "data": {
                    "apiToken": "testAPIToken"
                },
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertFalse(self.testAccountForm.isFormValid())

    def test_isFormValid_returns_false_on_missing_apiToken(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.Dropbox,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": {
                    "apiToken": ""
                },
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertFalse(self.testAccountForm.isFormValid())
Example #16
0
    else:
        # running live
        sys.path.append(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src'))
        imgDir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                              'img')

    from PyQt5.QtWidgets import QApplication
    from mainApp import App

    # Create App
    app = QApplication(sys.argv)

    # --------------

    # Create QMainWindow Widget
    ex = App(imgDir, app, args)

    # -- Launch RPC watchdog
    ex.mainWindow.rpc_watchdogThread.start()

    # Execute App
    app.exec_()
    try:
        app.deleteLater()
    except Exception as e:
        print(e)

    sys.exit()
Example #17
0
class TestDriveAccountForm(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.testAccountForm = DriveAccountForm()

    def tearDown(self):
        self.app.deleteLater()
        self.app.quit()

    def test_setAccountData_sets_data(self):
        testAccountSpecificData = {
            "type": "service_account",
            "project_id": "testID",
            "private_key_id": "testPrivKeyID",
            "private_key": "testPrivKey",
            "client_email": "testEmail",
            "client_id": "testClientID",
            "auth_uri": "testAuthUri",
            "token_uri": "testTokenUri",
            "auth_provider_x509_cert_url": "testCertProviderUri",
            "client_x509_cert_url": "testCertUri"
        }

        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.GoogleDrive,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": testAccountSpecificData,
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        componentAccountData = self.testAccountForm.getAccountData()

        self.assertEqual(testAccountData.accountType,
                         componentAccountData.accountType)
        self.assertEqual(testAccountData.identifier,
                         componentAccountData.identifier)
        self.assertEqual(testAccountData.cryptoKey,
                         componentAccountData.cryptoKey)
        self.assertEqual(testAccountData.data, componentAccountData.data)
        self.assertEqual(testAccountData.id, componentAccountData.id)

    def test_reset_clears_account_specific_data_and_only_that(self):
        testAccountSpecificData = {
            "type": "service_account",
            "project_id": "testID",
            "private_key_id": "testPrivKeyID",
            "private_key": "testPrivKey",
            "client_email": "testEmail",
            "client_id": "testClientID",
            "auth_uri": "testAuthUri",
            "token_uri": "testTokenUri",
            "auth_provider_x509_cert_url": "testCertProviderUri",
            "client_x509_cert_url": "testCertUri"
        }

        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.GoogleDrive,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": testAccountSpecificData,
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)
        self.testAccountForm.reset()

        componentAccountData = self.testAccountForm.getAccountData()
        self.assertEqual(componentAccountData.accountType,
                         testAccountData.accountType)
        self.assertEqual(componentAccountData.identifier, "")
        self.assertEqual(componentAccountData.cryptoKey, "")
        self.assertEqual(componentAccountData.data, {})
        self.assertEqual(componentAccountData.id, testAccountData.id)

    def test_isFormValid_returns_true_on_valid_account_data(self):
        testAccountSpecificData = {
            "type": "service_account",
            "project_id": "testID",
            "private_key_id": "testPrivKeyID",
            "private_key": "testPrivKey",
            "client_email": "testEmail",
            "client_id": "testClientID",
            "auth_uri": "testAuthUri",
            "token_uri": "testTokenUri",
            "auth_provider_x509_cert_url": "testCertProviderUri",
            "client_x509_cert_url": "testCertUri"
        }

        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.GoogleDrive,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": testAccountSpecificData,
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertTrue(self.testAccountForm.isFormValid())

    def test_isFormValid_returns_false_on_missing_identifier(self):
        testAccountSpecificData = {
            "type": "service_account",
            "project_id": "testID",
            "private_key_id": "testPrivKeyID",
            "private_key": "testPrivKey",
            "client_email": "testEmail",
            "client_id": "testClientID",
            "auth_uri": "testAuthUri",
            "token_uri": "testTokenUri",
            "auth_provider_x509_cert_url": "testCertProviderUri",
            "client_x509_cert_url": "testCertUri"
        }

        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.GoogleDrive,
                "identifier": "",
                "cryptoKey": "sixteen byte key",
                "data": testAccountSpecificData,
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertFalse(self.testAccountForm.isFormValid())

    def test_isFormValid_returns_false_on_missing_cryptoKey(self):
        testAccountSpecificData = {
            "type": "service_account",
            "project_id": "testID",
            "private_key_id": "testPrivKeyID",
            "private_key": "testPrivKey",
            "client_email": "testEmail",
            "client_id": "testClientID",
            "auth_uri": "testAuthUri",
            "token_uri": "testTokenUri",
            "auth_provider_x509_cert_url": "testCertProviderUri",
            "client_x509_cert_url": "testCertUri"
        }

        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.GoogleDrive,
                "identifier": "testAccount",
                "cryptoKey": "",
                "data": testAccountSpecificData,
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertFalse(self.testAccountForm.isFormValid())

    def test_isFormValid_returns_false_on_missing_drive_credentials(self):
        testAccountData = AccountData(
            **{
                "accountType": AccountTypes.GoogleDrive,
                "identifier": "testAccount",
                "cryptoKey": "sixteen byte key",
                "data": {},
                "id": 1
            })
        self.testAccountForm.setAccountData(testAccountData)

        self.assertFalse(self.testAccountForm.isFormValid())
Example #18
0
class TestSetupAccountsWrapperWidget(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.fakeAccountsWidget = FakeAccountsWidget()

    def tearDown(self):
        self.app.deleteLater()
        self.app.quit()

    @patch("view.firststart.accounts.SetupAccountsWidget")
    @patch.object(ServiceHub, "getInstance")
    def test_initData_starts_network_service_and_retrieves_accountList(
            self, mockGetInstance, fakeAccountsWidget):
        fakeAccountsWidget.return_value = self.fakeAccountsWidget
        fakeHub = MagicMock()
        mockGetInstance.return_value = fakeHub

        component = SetupAccountsWrapperWidget()
        component.initData()

        self.assertTrue(fakeHub.startNetworkService.called)
        self.assertEqual(fakeHub.startNetworkService.call_count, 1)

        self.assertTrue(fakeHub.connectToServer.called)
        self.assertEqual(fakeHub.connectToServer.call_count, 1)

        self.assertTrue(fakeHub.sendNetworkMessage.called)
        self.assertEqual(fakeHub.sendNetworkMessage.call_count, 1)

        self.assertTrue(fakeHub.networkStatusChannel.connect.called)
        self.assertEqual(fakeHub.networkStatusChannel.connect.call_count, 1)

        networkMessageToBeSent = fakeHub.sendNetworkMessage.call_args[0][0]
        callBackFunction = fakeHub.sendNetworkMessage.call_args[0][1]

        self.assertEqual(networkMessageToBeSent.header.messageType,
                         MessageTypes.GET_ACCOUNT_LIST)
        self.assertIsNotNone(networkMessageToBeSent.header.uuid)
        self.assertIsNotNone(callBackFunction)

        component.deleteLater()

    @patch("view.firststart.accounts.SetupAccountsWidget")
    @patch.object(ServiceHub, "getInstance")
    def test_cannot_proceed_on_empty_account_list(self, mockGetInstance,
                                                  fakeAccountsWidget):
        fakeAccountsWidget.return_value = self.fakeAccountsWidget
        fakeHub = MagicMock()
        mockGetInstance.return_value = fakeHub

        # testSetupAccountsWidget.return_value = SetupAccountsWidget()

        component = SetupAccountsWrapperWidget()
        component.initData()

        fakeAccountResponse = {"accounts": []}
        callBackFunction = fakeHub.sendNetworkMessage.call_args[0][1]

        callBackFunction(fakeAccountResponse)

        self.assertFalse(component.canProceed())
        self.assertTrue(component.isInited())

    @patch("view.firststart.accounts.SetupAccountsWidget")
    @patch.object(ServiceHub, "getInstance")
    def test_can_proceed_if_server_returns_non_empty_account_list(
            self, mockGetInstance, fakeAccountsWidget):

        fakeAccountsWidget.return_value = self.fakeAccountsWidget
        fakeHub = MagicMock()
        mockGetInstance.return_value = fakeHub

        component = SetupAccountsWrapperWidget()
        component.initData()

        fakeAccountData = {
            "accountType": AccountTypes.Dropbox,
            "identifier": "fakeAccount",
            "cryptoKey": "sixteen byte key",
            "data": {
                "apiToken": "fakeAPIToken"
            },
            "id": 1
        }
        fakeAccountResponse = {"accounts": [fakeAccountData]}
        callBackFunction = fakeHub.sendNetworkMessage.call_args[0][1]

        callBackFunction(fakeAccountResponse)

        self.assertTrue(component.canProceed())

    def test_can_go_back_always_true(self):
        component = SetupAccountsWrapperWidget()
        self.assertTrue(component.canGoBack())

    @patch("view.firststart.accounts.SetupAccountsWidget")
    @patch.object(ServiceHub, "getInstance")
    def test_callBack_sets_retrieved_account_list_into_underlying_accountListComponent(
            self, mockGetInstance, fakeAccountsWidget):
        testAccountData = AccountData(AccountTypes.Dropbox, "fakeAccount",
                                      "sixteen byte key",
                                      {"apiToken": "fakeAPIToken"}, 1)
        self.fakeAccountsWidget.accounts = [testAccountData]
        fakeAccountsWidget.return_value = self.fakeAccountsWidget
        fakeHub = MagicMock()
        mockGetInstance.return_value = fakeHub

        component = SetupAccountsWrapperWidget()
        accountData = component.getFormData()

        self.assertEqual(len(accountData), 1)

        self.assertEqual(testAccountData.accountType,
                         accountData[0].accountType)
        self.assertEqual(testAccountData.identifier, accountData[0].identifier)
        self.assertEqual(testAccountData.cryptoKey, accountData[0].cryptoKey)
        self.assertEqual(testAccountData.data, accountData[0].data)
        self.assertEqual(testAccountData.id, accountData[0].id)

    @patch("view.firststart.accounts.SetupAccountsWidget")
    @patch.object(ServiceHub, "getInstance")
    def test_invalidate_removes_all_accounts_and_shows_loading_icon_and_resets_network_service(
            self, mockGetInstance, fakeAccountsWidget):
        testAccountData = AccountData(AccountTypes.Dropbox, "fakeAccount",
                                      "sixteen byte key",
                                      {"apiToken": "fakeAPIToken"}, 1)
        self.fakeAccountsWidget.accounts = [testAccountData]
        fakeAccountsWidget.return_value = self.fakeAccountsWidget
        fakeHub = MagicMock()
        fakeHub.isNetworkServiceRunning.return_value = True
        mockGetInstance.return_value = fakeHub

        component = SetupAccountsWrapperWidget()

        self.assertEqual(len(component.getFormData()),
                         len(self.fakeAccountsWidget.accounts))

        component.invalidate()

        self.assertEqual(self.fakeAccountsWidget.accounts, [])
        self.assertTrue(fakeHub.isNetworkServiceRunning.called)
        self.assertTrue(fakeHub.shutdownNetwork.called)
        self.assertTrue(fakeHub.initNetworkService.called)
Example #19
0
    def setGraphWidget(self, gwid):

        self.gwid = gwid

    def setSignalWidget(self, swid):

        self.swid = swid

    def setGraph(self, graph):

        self.graph = graph
        self.cmbEdges.clear()

        if self.graph is not None:
            for src, dst in self.graph.edges():
                self.cmbEdges.addItem(src + ' → ' + dst)

        self.setEnabled(self.graph is not None)
        self.btnBack.setEnabled(False)
        self.lblStateNr.setText('State: ' + str(self.graph.stateCount() - 1))


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = RunWindow()
    app.exec_()
    app.deleteLater()
    sys.exit()