Esempio n. 1
0
    def test_delete_all(self):
        self.select_all()

        QTest.mouseClick(self.deleteButton, Qt.LeftButton)

        self.assert_elog_files_deleted()
        self.assert_elog_count_consistent()
Esempio n. 2
0
        def continueFunc(dialog):
            page = dialog._pageForItem["Plugins"]
            item = dialog._itemByPath(["Plugins"])
            item.setSelected(True)

            page.update(self._ONE_USERPLUGINS)
            titleCard = \
                page.children()[0].children()[0].children()[0].children()[2]
            enableBtn = titleCard.children()[2].children()[2].buttons()[0]
            cancelButton = dialog.children()[3].children()[2]

            QTest.mouseClick(enableBtn, Qt.LeftButton)
            lenBeforeDelete = len(core.loadedPlugins())
            titleCard._uninstallPlugin()
            self.assertEqual(
                lenBeforeDelete - 1,
                len(core.loadedPlugins()),
                'Plugins should be one fewer after uninstall.')
            self.assertFalse(titleCard._pluginEntry['isLoaded'],
                             'Plugin should not be loaded anymore')
            name = titleCard._pluginEntry['modulename']
            self.assertFalse(
                core.config()["PluginManager"]["Plugins"][name]["Enabled"],
                'Plugin should not be enabled in enki config')
            dirpath = os.path.join(PLUGIN_DIR_PATH, 'testplugin0')
            self.assertFalse(os.path.exists(dirpath),
                             'Plugin directory should not exist')
            QTest.mouseClick(cancelButton, Qt.LeftButton)
Esempio n. 3
0
	def test_tripleSecSpinBox(self):
		'''测试用例 test_tripleSecSpinBox '''	
		print('*** testCase test_tripleSecSpinBox begin ***')
		self.form.setWindowTitle('开始测试用例 test_tripleSecSpinBox ')	
		'''测试修改spinBox部件的最大最小值
			测试它的最小和最大值作为读者的练习。
        '''		
		self.setFormToZero()
		# tripleSecSpinBox在界面中的取值范围为 0 到 11, 将它的最大值设为 12,看是否显示正常。
		self.form.ui.tripleSecSpinBox.setValue(12)
		print('* 当执行self.form.ui.tripleSecSpinBox.setValue(12) 后,ui.tripleSecSpinBox.value() => ' + str( self.form.ui.tripleSecSpinBox.value() ) )				
		self.assertEqual(self.form.ui.tripleSecSpinBox.value(), 11 )	

		# tripleSecSpinBox在界面中的取值范围为 0 到 11, 将它的最小值设为 -1, 看是否显示正常。
		self.form.ui.tripleSecSpinBox.setValue(-1)
		print('* 当执行self.form.ui.tripleSecSpinBox.setValue(-1) 后,ui.tripleSecSpinBox.value() => ' + str( self.form.ui.tripleSecSpinBox.value() ) )				
		self.assertEqual(self.form.ui.tripleSecSpinBox.value(), 0 )	
		
		self.form.ui.tripleSecSpinBox.setValue(2)

        # 用鼠标左键按OK按钮
		okWidget = self.form.ui.okBtn
		QTest.mouseClick(okWidget, Qt.LeftButton)
		self.assertEqual(self.form.getJiggers(), 2)		
		print('*** testCase test_tripleSecSpinBox end ***')
Esempio n. 4
0
    def test_delete_one(self):
        self.select_first()

        QTest.mouseClick(self.deleteButton, Qt.LeftButton)

        self.assert_elog_count_equal(TEST_SET_SIZE - 1)
        self.assert_elog_count_consistent()
    def test_send(self):
        port = self.__get_free_port()
        receive_dialog = self.__get_recv_dialog()
        receive_dialog.device.set_server_port(port)
        receive_dialog.ui.btnStart.click()

        send_dialog = self.__get_send_dialog()
        send_dialog.device.set_client_port(port)
        send_dialog.ui.spinBoxNRepeat.setValue(2)
        send_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertEqual(receive_dialog.device.current_index, 2 * self.signal.num_samples)
        self.assertTrue(np.array_equal(receive_dialog.device.data[:receive_dialog.device.current_index // 2],
                                       self.signal.data))

        self.assertEqual(send_dialog.send_indicator.rect().width(), self.signal.num_samples)
        self.assertFalse(send_dialog.ui.btnClear.isEnabled())

        send_dialog.on_clear_clicked()
        self.assertEqual(send_dialog.send_indicator.rect().width(), 0)
        send_dialog.ui.btnStop.click()
        self.assertFalse(send_dialog.ui.btnStop.isEnabled())
        receive_dialog.ui.btnStop.click()
        self.assertFalse(receive_dialog.ui.btnStop.isEnabled())

        self.__close_dialog(receive_dialog)
        self.__close_dialog(send_dialog)
    def test_receive(self):
        port = self.__get_free_port()
        receive_dialog = self.__get_recv_dialog()
        receive_dialog.device.set_server_port(port)
        receive_dialog.ui.btnStart.click()

        data = np.array([complex(1, 2), complex(3, 4), complex(5, 6)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertEqual(receive_dialog.device.current_index, 3)
        self.assertTrue(np.array_equal(receive_dialog.device.data[:3], data))

        receive_dialog.ui.btnStop.click()
        receive_dialog.ui.btnClear.click()

        self.assertEqual(receive_dialog.device.current_index, 0)

        self.__close_dialog(receive_dialog)
Esempio n. 7
0
    def wait_for_settings(self, timeout=10):
        for _ in range(0, timeout * 1000, 100):
            QTest.qWait(100)
            if window.tribler_settings is not None:
                return

        raise TimeoutException("Did not receive settings within 10 seconds")
Esempio n. 8
0
        async def exec_test():
            srv, port, url = await self.mock_nice_blockchain.create_server()
            self.addCleanup(srv.close)

            identities_tab.change_account(self.account, self.password_asker)
            identities_tab.change_community(self.community)
            await asyncio.sleep(1)
            urls = [self.mock_nice_blockchain.get_request(i).url for i in range(0, 7)]
            self.assertTrue('/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ' in urls,
                            msg="Not found in {0}".format(urls))
            self.assertTrue('/wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ' in urls,
                            msg="Not found in {0}".format(urls))
            self.assertTrue('/wot/certified-by/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ' in urls,
                            msg="Not found in {0}".format(urls))


            # requests 1 to 3 are for getting certifiers-of and certified-by
            # on john, + a lookup

            QTest.keyClicks(identities_tab.ui.edit_textsearch, "doe")
            QTest.mouseClick(identities_tab.ui.button_search, Qt.LeftButton)
            await asyncio.sleep(2)
            req = 8

            self.assertEqual(self.mock_nice_blockchain.get_request(req).method, 'GET')
            self.assertEqual(self.mock_nice_blockchain.get_request(req).url,
                             '/blockchain/memberships/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn')
            req += 1

            self.assertEqual(identities_tab.ui.table_identities.model().rowCount(), 1)
            await asyncio.sleep(2)
            self.lp.call_soon(close_dialog)
Esempio n. 9
0
    def test_close_signal(self):
        self.add_signal_to_form("ask.complex")
        sframe = self.form.signal_tab_controller.signal_frames[0]
        sframe.ui.cbModulationType.setCurrentIndex(0)  # ASK
        sframe.ui.spinBoxInfoLen.setValue(295)
        sframe.ui.spinBoxCenterOffset.setValue(-0.1667)
        sframe.refresh()

        # Move with encoding to generator
        gframe = self.form.generator_tab_controller
        gframe.ui.cbViewType.setCurrentIndex(0)
        item = gframe.tree_model.rootItem.children[0].children[0]
        index = gframe.tree_model.createIndex(0, 0, item)
        rect = gframe.ui.treeProtocols.visualRect(index)
        QTest.mousePress(gframe.ui.treeProtocols.viewport(), Qt.LeftButton, pos=rect.center())
        self.assertEqual(gframe.ui.treeProtocols.selectedIndexes()[0], index)
        mimedata = gframe.tree_model.mimeData(gframe.ui.treeProtocols.selectedIndexes())
        gframe.table_model.dropMimeData(mimedata, 1, -1, -1, gframe.table_model.createIndex(0, 0))
        self.assertEqual(gframe.table_model.row_count, self.form.compare_frame_controller.protocol_model.row_count)
        self.form.ui.tabWidget.setCurrentIndex(0)
        self.form.on_selected_tab_changed(0)
        sframe.ui.btnCloseSignal.click()
        self.form.ui.tabWidget.setCurrentIndex(1)
        self.form.on_selected_tab_changed(1)
        self.form.ui.tabWidget.setCurrentIndex(2)
        self.form.on_selected_tab_changed(2)
        self.assertEqual(1, 1)
Esempio n. 10
0
    def test_load_save_markers(self):
        nmarkers = 505
        times = num.arange(nmarkers)
        markers = [gui_util.Marker(tmin=t, tmax=t,
                                   nslc_ids=[('*', '*', '*', '*'), ])
                   for t in times]

        tempfn = self.get_tempfile()
        tempfn_selected = self.get_tempfile()

        self.viewer.add_markers(markers)
        self.viewer.write_selected_markers(
            fn=tempfn_selected)
        self.viewer.write_markers(fn=tempfn)

        self.viewer.read_markers(fn=tempfn_selected)
        self.viewer.read_markers(fn=tempfn)

        for k in 'pnPN':
            QTest.keyPress(self.pile_viewer, k)

        self.viewer.go_to_time(-20., 20)
        self.pile_viewer.update()
        self.viewer.update()
        assert(len(self.viewer.markers) != 0)
        assert(len(self.viewer.markers) == nmarkers * 2)
        len_before = len(self.viewer.markers)
        self.viewer.remove_marker(
            self.viewer.markers[0])
        assert(len(self.viewer.markers) == len_before-1)
        self.viewer.remove_markers(self.viewer.markers)
        assert(len(self.viewer.markers) == 0)
Esempio n. 11
0
    def test_markers(self):
        self.add_one_pick()
        pv = self.pile_viewer
        self.assertEqual(pv.viewer.get_active_event(), None)

        conf = config.config('snuffler')

        # test kinds and phases
        kinds = range(5)
        fkey_map = pyrocko_pile_viewer.fkey_map

        for k in kinds:
            for fkey, fkey_int in fkey_map.items():
                fkey_int += 1
                QTest.keyPress(pv, fkey)
                QTest.keyPress(pv, str(k))

                if fkey_int != 10:
                    want = conf.phase_key_mapping.get(
                        "F%s" % fkey_int, 'Undefined')
                else:
                    want = None
                m = pv.viewer.get_markers()[0]
                self.assertEqual(m.kind, k)
                if want:
                    self.assertEqual(m.get_phasename(), want)
Esempio n. 12
0
    def test_esc_on_widget_closes(self):
        QTest.keyClick(core.mainWindow(), Qt.Key_F, Qt.ControlModifier)
        widget = _findSearchController()._widget
        self.assertFalse(widget.isHidden())

        QTest.keyClick(widget, Qt.Key_Escape)
        self.assertTrue(widget.isHidden())
Esempio n. 13
0
    def test_1(self):
        # replace 'foo' with 'UUH' in opened and not opened file
        openedFile = self.createFile('openedFile.txt', 'the text contains foo bar\nand\nfew\nmore lines')
        openedFile.qutepart.cursorPosition = (3, 2)

        notOpenedFilePath = os.path.join(self.TEST_FILE_DIR, 'not_openedFile.txt')
        with open(notOpenedFilePath, 'w') as file_:
            file_.write('this file also contains foo bar')

        self.keyClick(Qt.Key_R, Qt.ShiftModifier | Qt.ControlModifier)
        self.keyClicks('foo')
        self.keyClick(Qt.Key_Tab)
        self.keyClicks('UUHHH')
        self.keyClick(Qt.Key_Enter)
        QTest.qWait(500)  # searching
        self.keyClick(Qt.Key_A, Qt.AltModifier)
        QTest.qWait(500)  # replacing

        with open(notOpenedFilePath) as file_:
            self.assertEqual(file_.read(), 'this file also contains UUHHH bar')

        self.assertEqual(openedFile.qutepart.text, 'the text contains UUHHH bar\nand\nfew\nmore lines')
        self.assertEqual(openedFile.qutepart.cursorPosition, (3, 2))

        self.assertTrue(openedFile.qutepart.document().isModified())
        with open(openedFile.filePath()) as file_:
            self.assertEqual(file_.read(), 'the text contains foo bar\nand\nfew\nmore lines')

        openedFile.saveFile()
        with open(openedFile.filePath()) as file_:
            self.assertEqual(file_.read(), 'the text contains UUHHH bar\nand\nfew\nmore lines\n')
Esempio n. 14
0
    def test_simulator_graphics_view(self):
        self.__setup_project()
        self.add_all_signals_to_simulator()
        stc = self.form.simulator_tab_controller  # type: SimulatorTabController
        self.assertGreater(len(stc.simulator_config.get_all_items()), 0)

        self.assertEqual(len(stc.simulator_scene.selectedItems()), 0)

        # select first message
        messages = stc.simulator_scene.get_all_message_items()
        pos = stc.ui.gvSimulator.mapFromScene(messages[0].scenePos())

        QTest.mouseClick(stc.ui.gvSimulator.viewport(), Qt.LeftButton, Qt.NoModifier, pos)

        self.assertEqual(len(stc.simulator_scene.selectedItems()), 1)
        self.assertIsInstance(stc.simulator_scene.selectedItems()[0], MessageItem)

        rules = [item for item in stc.simulator_scene.items() if isinstance(item, RuleItem)]
        self.assertEqual(len(rules), 0)
        self.menus_to_ignore = [w for w in QApplication.topLevelWidgets() if isinstance(w, QMenu)]
        timer = QTimer(self.form)
        timer.setInterval(1)
        timer.setSingleShot(True)
        timer.timeout.connect(self.__on_context_menu_simulator_graphics_view_timer_timeout)
        timer.start()

        stc.ui.gvSimulator.contextMenuEvent(QContextMenuEvent(QContextMenuEvent.Mouse, pos))

        rules = [item for item in stc.simulator_scene.items() if isinstance(item, RuleItem)]
        self.assertEqual(len(rules), 1)
Esempio n. 15
0
 def _waitFiles(self):
     for _ in range(20):
         QTest.qWait(5000 / 20)
         if core.project().files() is not None:
             break
     else:
         self.fail("Project not scanned")
Esempio n. 16
0
 def test_edit_channel_rssfeeds(self):
     QTest.mouseClick(window.left_menu_button_my_channel, Qt.LeftButton)
     self.wait_for_variable("edit_channel_page.channel_overview")
     QTest.mouseClick(window.edit_channel_rss_feeds_button, Qt.LeftButton)
     self.screenshot(window, name="edit_channel_rssfeeds_loading")
     self.wait_for_list_populated(window.edit_channel_rss_feeds_list)
     self.screenshot(window, name="edit_channel_rssfeeds")
Esempio n. 17
0
        def continueFunc(dialog):
            page = dialog._pageForItem["Navigator"]
            self.assertEqual(page.lExecuteError.text(),
                             ('You are trying to use etags from the Emacs package, but it is not supported. '
                              'Use Exuberant Ctags.'))

            QTest.keyClick(dialog, Qt.Key_Enter)
Esempio n. 18
0
    def test_market_transactions_page(self):
        QTest.mouseClick(window.token_balance_widget, Qt.LeftButton)
        QTest.mouseClick(window.trade_button, Qt.LeftButton)
        self.wait_for_signal(window.market_page.received_wallets)
        QTest.mouseClick(window.market_transactions_button, Qt.LeftButton)
        self.wait_for_list_populated(window.market_transactions_list)
        self.screenshot(window, name="market_page_transactions")

        # Click on one of the transactions to get more information
        first_widget = window.market_transactions_list.topLevelItem(0)
        rect = window.market_transactions_list.visualItemRect(first_widget)
        QTest.mouseClick(window.market_transactions_list.viewport(), Qt.LeftButton, Qt.NoModifier, rect.center())
        QTest.qWait(100)
        self.screenshot(window, name="market_page_transactions_payments")

        # Pretend we receive a payment
        transaction = first_widget.transaction
        payment = {
            "trader_id": transaction['trader_id'],
            "transaction_number": transaction['transaction_number'],
            "transferred": {
                "amount": transaction['assets']['second']['amount'],
                "type": transaction['assets']['second']['type']
            },
            "payment_id": 'test',
            "address_from": 'a',
            "address_to": 'b',
            "timestamp": transaction['timestamp'] + 10,
            "success": True
        }
        window.core_manager.events_manager.market_payment_received.emit(payment)
        self.screenshot(window, name="market_page_transactions_newpayment")
        window.hide_status_bar()
Esempio n. 19
0
 def test_logWindowSplitter3a(self):
     """Feature 1,2,3. A combination of the above test cases.
     """
     document1 = self.createFile('file1.rst', '.. file1::')
     document2 = self.createFile('file2.rst', '')
     document3 = self.createFile('file3.rst', '.. file3::')
     self._assertHtmlReady(lambda: None)
     self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(document1))
     # Wait for events to process. See qWait comment above.
     QTest.qWait(100)
     # Change splitter setting of document 1.
     newSplitterSize = [125, 124]
     self._widget().splitter.setSizes(newSplitterSize)
     self._widget().splitter.splitterMoved.emit(newSplitterSize[0], 1)
     # Assert log window and preview window are visible and are of almost
     # equal size.
     self.assertNotIn(0, self._widget().splitter.sizes())
     self.assertAlmostEqual(self._widget().splitter.sizes()[0], self._widget().splitter.sizes()[1], delta=10)
     # Switch to an error-free document, assert log window hidden.
     self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(document2))
     # Wait for events to process. See qWait comment above.
     QTest.qWait(100)
     self.assertFalse(self._widget().splitter.sizes()[1])
     # Switch to file3 which will cause build error, check splitter size.
     self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(document3))
     self.assertNotIn(0, self._widget().splitter.sizes())
     self.assertAlmostEqual(self._widget().splitter.sizes()[0], self._widget().splitter.sizes()[1], delta=10)
Esempio n. 20
0
        def exec_test():
            yield from asyncio.sleep(2)
            urls = [mock.get_request(i).url for i in range(0, 7)]
            self.assertTrue(
                "/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ" in urls,
                msg="Not found in {0}".format(urls),
            )
            self.assertTrue(
                "/wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ" in urls, msg="Not found in {0}".format(urls)
            )
            self.assertTrue(
                "/wot/certified-by/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ" in urls,
                msg="Not found in {0}".format(urls),
            )

            # requests 1 to 3 are for getting certifiers-of and certified-by
            # on john, + a lookup

            QTest.keyClicks(identities_tab.edit_textsearch, "doe")
            QTest.mouseClick(identities_tab.button_search, Qt.LeftButton)
            yield from asyncio.sleep(2)
            req = 7

            self.assertEqual(mock.get_request(req).method, "GET")
            self.assertEqual(
                mock.get_request(req).url, "/blockchain/memberships/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn"
            )
            req += 1

            self.assertEqual(identities_tab.table_identities.model().rowCount(), 1)
            yield from asyncio.sleep(2)
            self.lp.call_soon(close_dialog)
Esempio n. 21
0
    def wait_for_variable(self, var, timeout=10, cmp_var=None):
        for _ in range(0, timeout * 1000, 100):
            QTest.qWait(100)
            if self.get_attr_recursive(var) is not cmp_var:
                return

        raise TimeoutException("Variable %s within 10 seconds" % var)
    def test_spectrum(self):
        port = self.__get_free_port()
        spectrum_dialog = self.__get_spectrum_dialog()
        spectrum_dialog.device.set_server_port(port)
        spectrum_dialog.ui.btnStart.click()
        self.assertEqual(len(spectrum_dialog.scene_manager.peak), 0)

        data = np.array([complex(1, 1), complex(2, 2), complex(3, 3)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertGreater(len(spectrum_dialog.scene_manager.peak), 0)

        spectrum_dialog.ui.btnStop.click()

        self.__close_dialog(spectrum_dialog)
Esempio n. 23
0
    def wait_for_home_page_table_populated(self, timeout=10):
        for _ in range(0, timeout * 1000, 100):
            QTest.qWait(100)
            if isinstance(window.home_page_table_view.cellWidget(0, 0), HomeRecommendedItem):
                return

        # List was not populated in time, fail the test
        raise TimeoutException("The list was not populated within 10 seconds")
Esempio n. 24
0
    def test_video_player_page(self):
        self.go_to_and_wait_for_downloads()
        QTest.mouseClick(window.downloads_list.topLevelItem(0).progress_slider, Qt.LeftButton)
        QTest.mouseClick(window.play_download_button, Qt.LeftButton)
        self.screenshot(window, name="video_player_page")

        self.wait_for_signal(window.left_menu_playlist.list_loaded, no_args=True)
        self.screenshot(window, name="video_player_left_menu_loaded")
Esempio n. 25
0
    def tearDownClass(cls):
        '''
        Quit snuffler.
        '''
        if no_gui:  # nosetests runs this even when class is has @skip
            return

        QTest.keyPress(cls.pile_viewer, 'q')
Esempio n. 26
0
    def test_expression_line_edit(self):
        e = ExpressionLineEdit()
        e.setCompleter(QCompleter(self.form.simulator_tab_controller.completer_model, e))
        e.setValidator(RuleExpressionValidator(self.form.simulator_tab_controller.sim_expression_parser))

        self.assertEqual(e.text(), "")
        QTest.keyClick(e, Qt.Key_R, Qt.NoModifier)
        self.assertEqual(e.text(), "r")
Esempio n. 27
0
 def _waitForText(self, text, replName):
     for i in range(50):
         if text in self._browserText(replName):
             break
         else:
             QTest.qWait(100)
     else:
         self.fail("Text doesn't contain '{}'".format(text))
Esempio n. 28
0
 def test_download_start_stop_remove_recheck(self):
     self.go_to_and_wait_for_downloads()
     QTest.mouseClick(window.downloads_list.topLevelItem(0).progress_slider, Qt.LeftButton)
     QTest.mouseClick(window.stop_download_button, Qt.LeftButton)
     QTest.mouseClick(window.start_download_button, Qt.LeftButton)
     QTest.mouseClick(window.remove_download_button, Qt.LeftButton)
     self.screenshot(window, name="remove_download_dialog")
     QTest.mouseClick(window.downloads_page.dialog.buttons[2], Qt.LeftButton)
Esempio n. 29
0
 def _waitCompletion(self, dialog):
     model = dialog._table.model()
     for _ in range(20):
         if model.rowCount() > 1:
             break
         QTest.qWait(1000 / 20)
     else:
         self.fail("No completion")
Esempio n. 30
0
 def test_all_cif_values(self):
     item = self.myapp.ui.cifList_treeWidget.topLevelItem(3)
     self.myapp.ui.cifList_treeWidget.setCurrentItem(item)
     QTest.mouseClick(self.myapp.ui.allEntrysTab, Qt.LeftButton)
     self.assertEqual('Id', self.myapp.ui.allCifTreeWidget.topLevelItem(0).text(0))
     self.assertEqual('250', self.myapp.ui.allCifTreeWidget.topLevelItem(0).text(1))
     self.assertEqual('C107 H142 N14 O26', self.myapp.ui.allCifTreeWidget.topLevelItem(10).text(1))
     self.assertEqual(263, self.myapp.ui.cifList_treeWidget.topLevelItemCount())
Esempio n. 31
0
    def test_simulation_flow(self):
        """
        test a simulation flow with an increasing sequence number

        :return:
        """
        profile = self.get_path_for_filename("testprofile.sim.xml")
        self.form.add_files([profile])
        self.assertEqual(
            len(self.form.simulator_tab_controller.simulator_scene.
                get_all_message_items()), 6)

        port = self.get_free_port()
        self.alice = NetworkSDRInterfacePlugin(raw_mode=True)
        self.alice.client_port = port

        dialog = self.form.simulator_tab_controller.get_simulator_dialog()
        name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME
        dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name)
        dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name)
        QTest.qWait(10)
        simulator = dialog.simulator
        simulator.sniffer.rcv_device.set_server_port(port)

        port = self.get_free_port()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        s.bind(("", port))
        s.listen(1)
        QTest.qWait(10)

        simulator.sender.device.set_client_port(port)
        dialog.ui.btnStartStop.click()
        QTest.qWait(1500)

        conn, addr = s.accept()

        msg = next(msg for msg in dialog.simulator_config.get_all_messages()
                   if msg.source.name == "Alice")
        checksum_label = next(
            lbl for lbl in msg.message_type
            if lbl.is_checksum_label).label  # type: ChecksumLabel

        modulator = dialog.project_manager.modulators[0]  # type: Modulator
        preamble_str = "10101010"
        sync_str = "1001"
        preamble = list(map(int, preamble_str))
        sync = list(map(int, sync_str))
        seq = list(map(int, "00000010"))
        data = list(map(int, "11001101"))

        seq_num = int("".join(map(str, seq)), 2)

        checksum = list(checksum_label.calculate_checksum(seq + data))

        msg1 = preamble + sync + seq + data + checksum

        self.alice.send_raw_data(modulator.modulate(msg1), 1)
        self.alice.send_raw_data(
            np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1)

        bits = self.__demodulate(conn)
        self.assertEqual(len(bits), 1)
        bits = bits[0]
        self.assertTrue(bits.startswith(preamble_str + sync_str))
        bits = bits.replace(preamble_str + sync_str, "")
        self.assertEqual(int(bits, 2), seq_num + 1)

        seq = list(map(int, "{0:08b}".format(seq_num + 2)))
        checksum = list(checksum_label.calculate_checksum(seq + data))
        msg2 = preamble + sync + seq + data + checksum

        self.alice.send_raw_data(modulator.modulate(msg2), 1)
        self.alice.send_raw_data(
            np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1)

        bits = self.__demodulate(conn)
        self.assertEqual(len(bits), 1)
        bits = bits[0]
        self.assertTrue(bits.startswith(preamble_str + sync_str))
        bits = bits.replace(preamble_str + sync_str, "")
        self.assertEqual(int(bits, 2), seq_num + 3)

        seq = list(map(int, "{0:08b}".format(seq_num + 4)))
        checksum = list(checksum_label.calculate_checksum(seq + data))
        msg3 = preamble + sync + seq + data + checksum

        self.alice.send_raw_data(modulator.modulate(msg3), 1)
        self.alice.send_raw_data(
            np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1)

        bits = self.__demodulate(conn)
        self.assertEqual(len(bits), 1)
        bits = bits[0]
        self.assertTrue(bits.startswith(preamble_str + sync_str))
        bits = bits.replace(preamble_str + sync_str, "")
        self.assertEqual(int(bits, 2), seq_num + 5)

        QTest.qWait(50)
        self.assertTrue(simulator.simulation_is_finished())

        time.sleep(1)

        conn.close()
        s.close()

        QTest.qWait(100)
Esempio n. 32
0
    def test_external_program_simulator(self):
        stc = self.form.simulator_tab_controller
        stc.ui.btnAddParticipant.click()
        stc.ui.btnAddParticipant.click()

        stc.simulator_scene.add_counter_action(None, 0)
        action = next(item for item in stc.simulator_scene.items()
                      if isinstance(item, CounterActionItem))
        action.model_item.start = 3
        action.model_item.step = 2
        counter_item_str = "item" + str(
            action.model_item.index()) + ".counter_value"

        stc.ui.gvSimulator.add_empty_message(42)
        stc.ui.gvSimulator.add_empty_message(42)

        stc.ui.cbViewType.setCurrentIndex(0)
        stc.create_simulator_label(0, 10, 20)
        stc.create_simulator_label(1, 10, 20)

        messages = stc.simulator_config.get_all_messages()
        messages[0].source = stc.project_manager.participants[0]
        messages[0].destination = stc.project_manager.participants[1]
        messages[0].destination.simulate = True
        messages[1].source = stc.project_manager.participants[1]
        messages[1].destination = stc.project_manager.participants[0]

        stc.simulator_scene.add_trigger_command_action(None, 200)
        stc.simulator_scene.add_sleep_action(None, 200)

        lbl1 = messages[0].message_type[0]  # type: SimulatorProtocolLabel
        lbl2 = messages[1].message_type[0]  # type: SimulatorProtocolLabel

        lbl1.value_type_index = 3
        lbl1.external_program = get_path_for_data_file(
            "external_program_simulator.py") + " " + counter_item_str
        lbl2.value_type_index = 3
        lbl2.external_program = get_path_for_data_file(
            "external_program_simulator.py") + " " + counter_item_str

        action = next(item for item in stc.simulator_scene.items()
                      if isinstance(item, SleepActionItem))
        action.model_item.sleep_time = 0.001
        stc.simulator_scene.clearSelection()
        action = next(item for item in stc.simulator_scene.items()
                      if isinstance(item, TriggerCommandActionItem))
        action.setSelected(True)
        self.assertEqual(stc.ui.detail_view_widget.currentIndex(), 4)
        fname = tempfile.mktemp()
        self.assertFalse(os.path.isfile(fname))
        external_command = "cmd.exe /C copy NUL {}".format(
            fname) if os.name == "nt" else "touch {}".format(fname)
        stc.ui.lineEditTriggerCommand.setText(external_command)
        self.assertEqual(action.model_item.command, external_command)

        port = self.get_free_port()
        self.alice = NetworkSDRInterfacePlugin(raw_mode=True)
        self.alice.client_port = port

        dialog = stc.get_simulator_dialog()
        name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME
        dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name)
        dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name)
        QTest.qWait(10)
        simulator = dialog.simulator
        simulator.sniffer.rcv_device.set_server_port(port)

        port = self.get_free_port()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        s.bind(("", port))
        s.listen(1)
        QTest.qWait(10)

        simulator.sender.device.set_client_port(port)
        dialog.ui.btnStartStop.click()
        QTest.qWait(1500)

        conn, addr = s.accept()

        modulator = dialog.project_manager.modulators[0]  # type: Modulator

        self.alice.send_raw_data(modulator.modulate("100" + "10101010" * 42),
                                 1)
        self.alice.send_raw_data(
            np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1)

        bits = self.__demodulate(conn)
        self.assertEqual(bits[0], "101010101")

        QTest.qWait(250)
        self.assertTrue(simulator.simulation_is_finished())

        conn.close()
        s.close()

        QTest.qWait(100)

        self.assertTrue(os.path.isfile(fname))
Esempio n. 33
0
 def setUp(self):
     """Create the GUI"""
     self.app = QtWidgets.QApplication(sys.argv)
     self.main_window = MainWindow()
     self.main_window.show()
     QTest.qWaitForWindowExposed(self.main_window)
Esempio n. 34
0
 def clickButton(self, button_objs):
     self.assertEqual(len(button_objs), 1)
     QTest.mouseMove(button_objs[0])
     QTest.mouseClick(button_objs[0], Qt.LeftButton, delay=100)
     Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)
Esempio n. 35
0
mw = None  # clear out that mainwindow
settings.clear()
recentlist = [
    '/the/path/to/glory/recent_1', '/the/path/to/glory2/recent_2',
    '/the/path/to/glory3/recent_3'
]
_write_flist(settings, recentlist, 'mainwindow/recent_files')
# Enable the following to see "Re-open" dialog - click cancel
openlist = [
    '/somewhere/over/the/rainbow/open_1', '/somewhere/over/the/rainbow/open_2'
]
_write_flist(settings, openlist, 'mainwindow/open_files')
#CLICK CANCEL TO MESSAGE
mw = mainwindow.MainWindow(settings)
mw.close()
# open file list should be empty because cancel clicked
xlist = _read_flist(settings, 'mainwindow/open_files')
assert len(xlist) == 0
# recent file list should go in and come out the same
xlist = _read_flist(settings, 'mainwindow/recent_files')
assert len(xlist) == len(recentlist)
for path in xlist:
    assert path in recentlist
# log may not be empty owing to dictionary path msgs
#assert empty_log()

app.quit()
# idle a bit after quit to let garbage be collected
from PyQt5.QtTest import QTest
QTest.qWait(200)
Esempio n. 36
0
 def go_to_and_wait_for_downloads(self):
     QTest.mouseClick(window.left_menu_button_downloads, Qt.LeftButton)
     QTest.mouseClick(window.downloads_all_button, Qt.LeftButton)
     self.wait_for_variable("downloads_page.downloads")
Esempio n. 37
0
 def run(self):
     self.parent.song = QSound(self.song_name)
     self.parent.song.play()
     self.parent.label_tiempo.show()
     QTest.qWait(1000)
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("19")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("19")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("17")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("16")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("15")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("14")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("13")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("12")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("11")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("10")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("9")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("8")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("7")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("6")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("5")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("4")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("2")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("2")
     QTest.qWait(1000)
     self.parent.label_tiempo.setText("1")
     QTest.qWait(1000)
     self.parent.song.stop()
     self.parent.label_tiempo.hide()
     self.parent.label_chat.setText(self.label_chat.text() + "\n" +
                                    "> Preparate para la siguiente ronda")
Esempio n. 38
0
def test_main():
    addObatRacikApp = QtWidgets.QApplication(sys.argv)
    wt = main.AppWindow()
    QTest.keyClicks(wt.ui.fieldNamaResep, "Pramanix")
    QTest.keyClicks(wt.findChild(QtWidgets.QLineEdit, "field_namaObat1"),
                    "Paracetamol")
    QTest.keyClicks(wt.findChild(QtWidgets.QLineEdit, "field_jumlah1"), "500")
    assert main.get_dialog_data(wt, wt.count) == {
        'nama': 'Pramanix',
        'data': [('Paracetamol', '500', 'Gram')]
    }
    QTest.mouseClick(wt.ui.addItemsButton, QtCore.Qt.LeftButton)
    assert wt.count == 2
    assert main.get_dialog_data(wt, wt.count) == {
        'nama': 'Pramanix',
        'data': [('Paracetamol', '500', 'Gram'), ('', '', 'Gram')]
    }
    QTest.keyClicks(wt.findChild(QtWidgets.QLineEdit, "field_namaObat2"),
                    "Ibuprofen")
    QTest.keyClicks(wt.findChild(QtWidgets.QLineEdit, "field_jumlah2"), "100")
    assert main.get_dialog_data(wt, wt.count) == {
        'nama': 'Pramanix',
        'data': [('Paracetamol', '500', 'Gram'), ('Ibuprofen', '100', 'Gram')]
    }
    QTest.keyClicks(wt.ui.fieldNamaResep, "\b\b\b\b\b\b\b")
    QTest.keyClicks(wt.ui.fieldNamaResep, "aramex")
    assert main.get_dialog_data(wt, wt.count) == {
        'nama': 'Paramex',
        'data': [('Paracetamol', '500', 'Gram'), ('Ibuprofen', '100', 'Gram')]
    }
Esempio n. 39
0
 def wait_before_new_file(self):
     QApplication.instance().processEvents()
     QTest.qWait(self.WAIT_TIMEOUT_BEFORE_NEW)
Esempio n. 40
0
    def start(self):
        self.startcronotipy = True  #for while

        if self.cronotipy_ui.menu_Loop_On_Off.isChecked():  #for loop
            self.isOnOff_loop = True

        get_titles = [
            self.listwd.item(item).text()
            for item in range(self.listwd.count())
        ]
        title_message = {}

        for title in get_titles:
            title_message[title] = self.findChild(QLineEdit, title).text()
            #timeinseconds = cronotipy.time2seconds(self, self.title_and_time[title])
            #print(timeinseconds)

        seconds_title = {}
        cnt = 0
        cnt_finish = 0
        while self.startcronotipy:  #start counts
            cnt += 1
            try:  #try for when to delete the title at the time of counting
                for i, title in enumerate(get_titles):
                    time = cronotipy.time2seconds(
                        self,
                        self.title_and_time[title])  #calc time in seconds

                    if cnt == 1:  #get dictionary just in first iteration
                        seconds_title[time] = title

                    self.findChild(QProgressBar, get_titles[i]).setMaximum(
                        time)  #set max value of progbar
                    self.findChild(QProgressBar,
                                   get_titles[i]).setTextVisible(True)
                    self.findChild(QProgressBar, get_titles[i]).setValue(
                        cnt)  #change value of progbar
            except KeyError:
                #QUANDO DELETAMOS UM TITULO ENQUANTO A CONTAGEM TA ROLANDO DA ESSE KEYERROR
                #ESSE TRY RESOLVE ISSO, MAS PRECISO TIRAR ESSE TITULO DO DICIONARIO PARA NAO APARECER NOTIFICAÇÃO
                pass

            if cnt in seconds_title.keys():  #when cnt pass through time
                if self.isOnOff_Notify:
                    Notify.Notification.new(seconds_title[cnt],
                                            title_message[seconds_title[cnt]],
                                            path_logo).show()

                if self.isOnOff_Sound:
                    subprocess.run('play {} &'.format(path_sound_notify),
                                   shell=True)

                cnt_finish += 1

            elif cnt_finish == len(
                    seconds_title):  #when the last notify finish
                self.startcronotipy = False

                if self.isOnOff_Notify:
                    Notify.Notification.new('Done!',
                                            'All notifications are over.',
                                            path_logo).show()

            QTest.qWait(1000)
        #loop
        if self.isOnOff_loop:
            self.startcronotipy = True
            cronotipy.start(self)
Esempio n. 41
0
 def test_gui_default_run(self):
     """Test the GUI in its default state"""
     assert self.form.send_button.text() == "Отправить"
     assert self.window.windowTitle() == "Messanger Client"
     QTest.mouseClick(self.form.send_button, Qt.LeftButton)
Esempio n. 42
0
        def continueFunc(dialog):
            page = dialog._pageForItem["Editor/Font"]

            page.lFont.setFont(font)

            QTest.keyClick(dialog, Qt.Key_Enter)
Esempio n. 43
0
    def test_sniff(self):
        # add a signal so we can use it
        self.add_signal_to_form("esaver.complex")
        logger.debug("Added signalfile")
        QApplication.instance().processEvents()

        self.__add_first_signal_to_generator()
        generator_frame = self.form.generator_tab_controller
        self.assertEqual(generator_frame.table_model.rowCount(), 3)

        QApplication.instance().processEvents()
        sniff_dialog = self.__get_sniff_dialog()
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.setChecked(
            False)
        self.assertEqual(sniff_dialog.device.name,
                         NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)
        sniff_dialog.sniff_settings_widget.ui.comboBox_sniff_viewtype.setCurrentIndex(
            0)

        port = self.__get_free_port()

        sniff_dialog.device.set_server_port(port)
        generator_frame.network_sdr_plugin.client_port = port
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()

        QTest.qWait(self.SEND_RECV_TIMEOUT)
        received_msgs = sniff_dialog.ui.txtEd_sniff_Preview.toPlainText(
        ).split("\n")
        orig_msgs = generator_frame.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.click()
        self.assertTrue(
            sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.click()
        self.assertFalse(
            sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))

        target_file = os.path.join(QDir.tempPath(), "sniff_file.txt")
        self.assertFalse(os.path.isfile(target_file))

        sniff_dialog.ui.btnClear.click()
        QApplication.instance().processEvents()
        sniff_dialog.sniff_settings_widget.ui.lineEdit_sniff_OutputFile.setText(
            target_file)
        sniff_dialog.sniff_settings_widget.ui.lineEdit_sniff_OutputFile.editingFinished.emit(
        )
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        self.assertFalse(sniff_dialog.ui.btnAccept.isEnabled())

        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(
                    orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        os.remove(target_file)

        sniff_dialog.ui.btnStop.click()
        self.assertFalse(sniff_dialog.ui.btnStop.isEnabled())

        self.__close_dialog(sniff_dialog)
Esempio n. 44
0
    def test_insert_sine_plugin(self):
        insert_sine_plugin = self.sframe.ui.gvSignal.insert_sine_plugin
        num_samples = 10000
        dialog = insert_sine_plugin.get_insert_sine_dialog(
            original_data=self.signal.data,
            position=2000,
            sample_rate=self.signal.sample_rate,
            num_samples=num_samples)

        graphics_view = dialog.graphicsViewSineWave  # type: ZoomableGraphicView

        while not dialog.doubleSpinBoxAmplitude.isEnabled():
            app.processEvents()
            QTest.qWait(10)

        self.assertEqual(int(graphics_view.sceneRect().width()),
                         self.signal.num_samples + num_samples)
        self.assertEqual(insert_sine_plugin.insert_indicator.rect().width(),
                         num_samples)
        self.assertEqual(insert_sine_plugin.insert_indicator.rect().x(), 2000)

        dialog.doubleSpinBoxAmplitude.setValue(0.1)
        dialog.doubleSpinBoxAmplitude.editingFinished.emit()
        self.assertEqual(insert_sine_plugin.amplitude, 0.1)

        while not dialog.doubleSpinBoxAmplitude.isEnabled():
            app.processEvents()
            QTest.qWait(10)

        dialog.doubleSpinBoxFrequency.setValue(1e6)
        dialog.doubleSpinBoxFrequency.editingFinished.emit()
        self.assertEqual(insert_sine_plugin.frequency, 1e6)

        while not dialog.doubleSpinBoxAmplitude.isEnabled():
            app.processEvents()
            QTest.qWait(10)

        dialog.doubleSpinBoxPhase.setValue(100)
        dialog.doubleSpinBoxPhase.editingFinished.emit()
        self.assertEqual(insert_sine_plugin.phase, 100)

        while not dialog.doubleSpinBoxAmplitude.isEnabled():
            app.processEvents()
            QTest.qWait(10)

        dialog.doubleSpinBoxSampleRate.setValue(2e6)
        dialog.doubleSpinBoxSampleRate.editingFinished.emit()
        self.assertEqual(insert_sine_plugin.sample_rate, 2e6)

        while not dialog.doubleSpinBoxAmplitude.isEnabled():
            app.processEvents()
            QTest.qWait(10)

        dialog.doubleSpinBoxNSamples.setValue(0.5e6)
        dialog.doubleSpinBoxNSamples.editingFinished.emit()
        self.assertEqual(insert_sine_plugin.num_samples, 0.5e6)

        while not dialog.doubleSpinBoxAmplitude.isEnabled():
            app.processEvents()
            QTest.qWait(10)

        sep = Formatter.local_decimal_seperator()
        self.assertEqual(dialog.lineEditTime.text(), "250" + sep + "000m")
Esempio n. 45
0
 def __close_dialog(self, dialog):
     dialog.close()
     dialog.setParent(None)
     dialog.deleteLater()
     QApplication.instance().processEvents()
     QTest.qWait(self.CLOSE_TIMEOUT)
Esempio n. 46
0
    def _4Run(self):  #run the suite
        QTest.mouseClick(self.D.pushButton_R_run, Qt.LeftButton)

        self.res_d['run_pick_d'] = self.D.run_pick_d
Esempio n. 47
0
    def _5Analy(self):  #analyze results
        QTest.mouseClick(self.D.pushButton_A_plotRiskCurves, Qt.LeftButton)
        QTest.mouseClick(self.D.pushButton_A_plotBox, Qt.LeftButton)

        self.res_d['fig_d'] = self.D.fig_d
Esempio n. 48
0
    def test_jump(self):
        self.qpart.text = '\n' * 5
        QTest.keyClick(self.qpart, Qt.Key_B, Qt.ControlModifier)
        for i in range(2):
            QTest.keyClick(self.qpart, Qt.Key_Down)
        QTest.keyClick(self.qpart, Qt.Key_B, Qt.ControlModifier)
        for i in range(2):
            QTest.keyClick(self.qpart, Qt.Key_Down)
        QTest.keyClick(self.qpart, Qt.Key_B, Qt.ControlModifier)
        self.assertEqual(self._markedBlocks(), [0, 2, 4])

        self.qpart.cursorPosition = (0, 0)

        QTest.keyClick(self.qpart, Qt.Key_PageDown, Qt.AltModifier)
        self.assertEqual(self.qpart.cursorPosition[0], 2)
        QTest.keyClick(self.qpart, Qt.Key_PageDown, Qt.AltModifier)
        self.assertEqual(self.qpart.cursorPosition[0], 4)
        QTest.keyClick(self.qpart, Qt.Key_PageDown, Qt.AltModifier)
        self.assertEqual(self.qpart.cursorPosition[0], 4)

        QTest.keyClick(self.qpart, Qt.Key_PageUp, Qt.AltModifier)
        self.assertEqual(self.qpart.cursorPosition[0], 2)
        QTest.keyClick(self.qpart, Qt.Key_PageUp, Qt.AltModifier)
        self.assertEqual(self.qpart.cursorPosition[0], 0)
        QTest.keyClick(self.qpart, Qt.Key_PageUp, Qt.AltModifier)
        self.assertEqual(self.qpart.cursorPosition[0], 0)
Esempio n. 49
0
    def history(self,
                code,
                period,
                unit=None,
                start=None,
                end=None,
                path=None,
                merge=True,
                warning=True,
                prev_next='0'):
        """
        Download historical market data of given code and save it as csv to given path

        :param code: str
            unique code of stock or sector
        :param period: str
            one of tick, min, day, week, month and year
        :param unit: int
            1, 3, 5, 10, 30 etc.. (cf. 1 bar = unit * period)
        :param start: str
            string of start day in format 'YYYYMMDD'
        :param end: str
            string of end day in format 'YYYYMMDD'. if None, until now by default.
        :param path: str
            path to save downloaded data
        :param merge: bool
            whether to merge data with existing file or to overwrite it
        :param warning: bool
            turn on/off the warning message if any
        :param prev_next: str
            this param is given by the response from the server. default is '0'
        """
        # Wait for default request limit, 3600 ms
        QTest.qWait(history.REQUEST_LIMIT_TIME)

        ctype = history.get_code_type(code)  # ctype = 'stock' | 'sector'
        tr_code = history.get_tr_code(period, ctype)
        """
            Setting args just for once.
        """
        if prev_next == '0':
            # In case path is '' or None
            if not path:
                path = getcwd()

            # To share variables with Slot
            kwargs = effective_args(locals(), remove=['ctype', 'tr_code'])
            self.share.remove_single(name())
            self.share.update_single(name(), 'error', False)
            self.share.update_single(name(), 'restart', False)
            self.share.update_single(name(), 'complete', False)
            self.share.update_single(name(), 'impossible', False)

            # To check format of input dates
            if 'start' in kwargs:
                if not history.is_date(start):
                    raise ValueError(
                        f"Given 'start' {start} is not a valid date.")
            if 'end' in kwargs:
                if not history.is_date(end):
                    raise ValueError(f"Given 'end' {end} is not a valid date.")
            """
                Check 'start' and 'end' points to save downloading time. 
            """
            if merge:
                try:
                    file = join(path, code + '.csv')
                    col = history.get_datetime_column(period)
                    df = read_csv(file,
                                  index_col=[col],
                                  parse_dates=[col],
                                  encoding=config.ENCODING)

                    if period in ['tick', 'min']:
                        # Last tick for stock is 15:30 and for sector is 18:00
                        h, m = (15, 30) if ctype is history.STOCK else (
                            18, 00)  # else for sector
                        last_day = date(df.index[-1])
                        last_tick_of_day = Timestamp(df.index[-1]).replace(
                            hour=h, minute=m)
                        download_completed = last_tick_of_day <= df.index[-1]

                        # To push 'start' date further as much as possible. If None, set newly.
                        if 'start' not in kwargs or date(
                                kwargs['start']) <= last_day:
                            if download_completed:
                                # Start from the day after last day
                                kwargs['start'] = str(
                                    (last_day + DateOffset(1)).date()).replace(
                                        '-', '')
                            else:
                                # Start from the last day
                                kwargs['start'] = str(last_day).replace(
                                    '-', '')

                        # If downloading is not needed, just return
                        if 'end' in kwargs:
                            if download_completed:
                                if date(kwargs['end']) <= last_day:
                                    self.share.update_single(
                                        name(), 'complete', True)
                                    return

                    else:  # if period in ['day', 'week', 'month', 'year']
                        last_day = date(df.index[-1])
                        # To push 'start' date further as much as possible. If None, set newly.
                        if 'start' not in kwargs or date(
                                kwargs['start']) <= last_day:
                            # Start from the last day
                            kwargs['start'] = str(last_day).replace('-', '')

                        # If downloading is not needed, just return
                        if 'end' in kwargs:
                            if date(kwargs['end']) < last_day:
                                self.share.update_single(
                                    name(), 'complete', True)
                                return

                    # Once read, use later in Server.history_to_csv() to increase efficiency
                    self.share.update_single(name(), 'file', df)

                # If any exception, just skip
                except Exception as err:
                    pass
            """
                Update and print arguments. 
            """
            # Done arg setting
            self.share.update_args(name(), kwargs)

            # Print args
            f = lambda key: f"'{kwargs[key]}'" if key in kwargs else None
            print(
                f"{{code={f('code')}, start={f('start')}, end={f('end')}, period={f('period')}}}"
            )
        """
            Start downloading.
        """
        # Check requesting status
        if 'histories' in self.share.single:
            self.share.single['histories']['nrq'] += 1
            if history.SPEEDING:
                if self.share.get_single('histories',
                                         'nrq') >= history.REQUEST_LIMIT_TRY:
                    # Set back to default configuration
                    if self.share.get_single('histories', 'cnt') == 0:
                        self.share.update_single(name(), 'impossible', True)
                    self.share.update_single(name(), 'restart', True)
                    self.api.unloop()
                    return

        # Finally request data to server
        for key, val in history.inputs(tr_code, code, unit, end):
            self.api.set_input_value(key, val)
        scr_no = self.scr.alloc(tr_code, code)

        # If comm_rq_data returns non-zero error code, restart downloading
        if self.api.comm_rq_data(name(), tr_code, prev_next, scr_no) != 0:
            self.share.update_single(name(), 'impossible', True)
            self.share.update_single(name(), 'restart', True)
            self.api.unloop()
            return

        # Wait response from the server
        self.api.loop()
Esempio n. 50
0
 def changeParamValueText(self,
                          w,
                          path,
                          value_name,
                          new_text,
                          old_path=None):
     param_widget = self.getParamWidget(w, path, value_name, old_path)
     self.assertNotEqual(param_widget, None)
     pos = param_widget.valueTestPosition()
     widget = param_widget.valueTestWidget()
     QTest.mouseMove(widget, pos)
     Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)
     QTest.mouseClick(widget, Qt.LeftButton, pos=pos)
     QTest.mouseDClick(widget, Qt.LeftButton, pos=pos)
     # The default editing widget on a QTreeWidgetItem is a QLineEdit.
     # But it doesn't seem to show up until the item has focus.
     # This is pretty brittle but seems to work OK for now.
     line_edit = Testing.findQObjectsByType(widget,
                                            "PyQt5.QtWidgets.QLineEdit")
     for obj in line_edit:
         if obj.objectName() == "":
             widget = obj
             break
     Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)
     QTest.keyClick(widget, Qt.Key_Backspace)
     QTest.keyClicks(widget, new_text)
     QTest.keyClick(widget, Qt.Key_Return)
     Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)
Esempio n. 51
0
    def test_generator_label(self):
        labels = self.cframe.proto_analyzer.protocol_labels
        self.assertEqual(len(labels), 2)

        # Open Protocol in Generator
        self.form.ui.tabWidget.setCurrentIndex(2)
        item = self.gframe.tree_model.rootItem.children[0].children[0]
        index = self.gframe.tree_model.createIndex(0, 0, item)
        rect = self.gframe.ui.treeProtocols.visualRect(index)
        self.assertEqual(len(self.gframe.ui.treeProtocols.selectedIndexes()),
                         0)
        QTest.mousePress(self.gframe.ui.treeProtocols.viewport(),
                         Qt.LeftButton,
                         pos=rect.center())
        self.assertEqual(self.gframe.ui.treeProtocols.selectedIndexes()[0],
                         index)
        mimedata = self.gframe.tree_model.mimeData(
            self.gframe.ui.treeProtocols.selectedIndexes())
        self.gframe.table_model.dropMimeData(
            mimedata, 1, -1, -1, self.gframe.table_model.createIndex(0, 0))
        self.assertEqual(self.gframe.table_model.row_count, 3)

        # Check Label in Generator
        labels = self.gframe.table_model.protocol.protocol_labels
        self.assertEqual(len(labels), 2)

        # Fuzz Label
        lbl = copy.deepcopy(
            self.gframe.table_model.protocol.messages[0].message_type[1])
        self.gframe.table_model.protocol.messages[0].message_type[1] = lbl
        lbl.fuzz_values.append("1")
        lbl.add_fuzz_value()
        lbl.add_fuzz_value()
        lbl.add_fuzz_value()
        lbl.add_fuzz_value()
        lbl.fuzz_me = Qt.Checked
        self.assertEqual(len(lbl.fuzz_values), 5)
        self.gframe.refresh_label_list()
        self.gframe.refresh_table()
        self.gframe.ui.btnFuzz.setEnabled(True)
        self.gframe.ui.btnFuzz.click()
        self.assertTrue(lbl.active_fuzzing)
        self.assertIn(
            lbl, self.gframe.table_model.protocol.messages[0].message_type)
        self.assertEqual(self.gframe.table_model.row_count, 4 + 3)

        # Check if Background for fuzzed labels is drawn correctly
        self.__check_background_is_drawn(lbl, 43, 43)

        # Delete a line
        old_row_count = self.gframe.table_model.row_count
        self.gframe.ui.tableMessages.selectRow(2)
        QTest.keyClick(self.gframe.ui.tableMessages, Qt.Key_Delete)
        self.assertEqual(self.gframe.table_model.row_count, old_row_count - 1)

        self.__check_background_is_drawn(lbl, 43, 43)

        # Remove everything
        for i in range(old_row_count):
            self.gframe.ui.tableMessages.selectRow(0)
            QTest.keyClick(self.gframe.ui.tableMessages, Qt.Key_Delete)

        self.assertEqual(self.gframe.table_model.row_count, 0)
Esempio n. 52
0
    def test_performance(self):
        self.form = MainController()
        self.cfc = self.form.compare_frame_controller
        self.stc = self.form.simulator_tab_controller
        self.gtc = self.form.generator_tab_controller

        self.form.add_signalfile(get_path_for_data_file("esaver.complex"))
        self.sframe = self.form.signal_tab_controller.signal_frames[0]
        self.sim_frame = self.form.simulator_tab_controller
        self.form.ui.tabWidget.setCurrentIndex(3)
        self.cfc.proto_analyzer.auto_assign_labels()

        self.network_sdr_plugin_sender = NetworkSDRInterfacePlugin(
            raw_mode=True)

        part_a = Participant("Device A", shortname="A", color_index=0)
        part_b = Participant("Device B", shortname="B", color_index=1)
        part_b.simulate = True

        self.form.project_manager.participants.append(part_a)
        self.form.project_manager.participants.append(part_b)
        self.form.project_manager.project_updated.emit()

        sniffer = ProtocolSniffer(100,
                                  0.01,
                                  0.1,
                                  5,
                                  1,
                                  NetworkSDRInterfacePlugin.NETWORK_SDR_NAME,
                                  BackendHandler(),
                                  network_raw_mode=True)
        sender = EndlessSender(BackendHandler(),
                               NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)

        simulator = Simulator(self.stc.simulator_config,
                              self.gtc.modulators,
                              self.stc.sim_expression_parser,
                              self.form.project_manager,
                              sniffer=sniffer,
                              sender=sender)

        pause = 100000
        msg_a = SimulatorMessage(
            part_b, [1, 0] * 16 + [1, 1, 0, 0] * 8 + [0, 0, 1, 1] * 8 +
            [1, 0, 1, 1, 1, 0, 0, 1, 1, 1] * 4,
            pause=pause,
            message_type=MessageType("empty_message_type"),
            source=part_a)

        msg_b = SimulatorMessage(
            part_a, [1, 0] * 16 + [1, 1, 0, 0] * 8 + [1, 1, 0, 0] * 8 +
            [1, 0, 1, 1, 1, 0, 0, 1, 1, 1] * 4,
            pause=pause,
            message_type=MessageType("empty_message_type"),
            source=part_b)

        self.stc.simulator_config.add_items([msg_a, msg_b], 0, None)
        self.stc.simulator_config.update_active_participants()

        port = self.get_free_port()
        sniffer = simulator.sniffer
        sniffer.rcv_device.set_server_port(port)

        self.network_sdr_plugin_sender.client_port = port

        sender = simulator.sender
        port = self.get_free_port()
        sender.device.set_client_port(port)
        sender.device._VirtualDevice__dev.name = "simulator_sender"

        current_index = Value("L")
        elapsed = Value("f")
        target_num_samples = 113600 - pause
        receive_process = Process(target=receive,
                                  args=(port, current_index,
                                        target_num_samples, elapsed))
        receive_process.daemon = True
        receive_process.start()

        # Ensure receiver is running
        time.sleep(2)

        # spy = QSignalSpy(self.network_sdr_plugin_receiver.rcv_index_changed)
        simulator.start()

        modulator = Modulator("test_modulator")
        modulator.samples_per_bit = 100
        modulator.carrier_freq_hz = 55e3

        # yappi.start()

        self.network_sdr_plugin_sender.send_raw_data(
            modulator.modulate(msg_a.encoded_bits), 1)
        QTest.qWait(10)
        # send some zeros to simulate the end of a message
        self.network_sdr_plugin_sender.send_raw_data(
            np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1)
        QTest.qWait(100)
        receive_process.join(10)

        logger.info("PROCESS TIME: {0:.2f}ms".format(elapsed.value))

        self.assertEqual(current_index.value, target_num_samples)
        self.assertLess(elapsed.value, 200)
Esempio n. 53
0
        def continueFunc(dialog):
            page = dialog._pageForItem["Navigator"]

            page.leCtagsPath.setText('new ctags path')

            QTest.keyClick(dialog, Qt.Key_Enter)
Esempio n. 54
0
    def close_msg_boxes(self):

        message_boxes = QApplication.topLevelWidgets()
        for msg in message_boxes:
            if msg.inherits("QMessageBox"):
                QTest.keyClick(msg, Qt.Key_Enter)
Esempio n. 55
0
 def test_big_step_forward_btn_increments_five_frames(self):
     # Big step forward takes  the user foraward 5 frames
     self.assertEqual(self.gui.FrameView.DrawScene.current_frame, 0)
     QTest.mouseClick(self.gui.BigStepForwardButton, Qt.LeftButton)
     self.assertEqual(self.gui.FrameView.DrawScene.current_frame, 5)
Esempio n. 56
0
        def continueFunc(dialog):
            page = dialog._pageForItem["Navigator"]

            page.cbSortTagsAlphabetically.setChecked(True)
            QTest.keyClick(dialog, Qt.Key_Enter)
Esempio n. 57
0
 def tearDownClass(cls):
     if window:
         window.core_manager.stop()
     QTest.qWait(2000)
Esempio n. 58
0
 def test_big_step_backward_btn_increments_five_frames(self):
     # Big step backward takes the user back 5 frames
     self.gui.FrameView.DrawScene.get_frame(5)
     self.assertEqual(self.gui.FrameView.DrawScene.current_frame, 5)
     QTest.mouseClick(self.gui.BigStepBackwardButton, Qt.LeftButton)
     self.assertEqual(self.gui.FrameView.DrawScene.current_frame, 0)
Esempio n. 59
0
from TriblerGUI.widgets.channel_torrent_list_item import ChannelTorrentListItem
from TriblerGUI.widgets.home_recommended_item import HomeRecommendedItem

api_port = get_random_port()
core_manager.START_FAKE_API = True

import TriblerGUI
TriblerGUI.defs.DEFAULT_API_PORT = api_port

from TriblerGUI.widgets.loading_list_item import LoadingListItem
from TriblerGUI.tribler_window import TriblerWindow

if os.environ.get("TEST_GUI") == "yes":
    app = QApplication(sys.argv)
    window = TriblerWindow(api_port=api_port)
    QTest.qWaitForWindowExposed(window)
else:
    window = None


def start_fake_core(port):
    from twisted.internet import reactor
    from twisted.web.server import Site

    from FakeTriblerAPI.endpoints.root_endpoint import RootEndpoint
    from FakeTriblerAPI.endpoints.video_root_endpoint import VideoRootEndpoint
    from FakeTriblerAPI.tribler_data import TriblerData
    import FakeTriblerAPI.tribler_utils as tribler_utils

    def generate_tribler_data():
        tribler_utils.tribler_data = TriblerData()
Esempio n. 60
0
 def test_step_backward_btn_increments_one_frame(self):
     # Step backward takes the user back one frame
     self.gui.FrameView.DrawScene.get_frame(5)
     self.assertEqual(self.gui.FrameView.DrawScene.current_frame, 5)
     QTest.mouseClick(self.gui.StepBackwardButton, Qt.LeftButton)
     self.assertEqual(self.gui.FrameView.DrawScene.current_frame, 4)