def crashtest(): global allWidgets try: gc.disable() actions = [ createWidget, #setParent, forgetWidget, showWidget, processEvents, #raiseException, #addReference, ] thread = WorkThread() thread.start() while True: try: action = randItem(actions) action() print('[%d widgets alive, %d zombie]' % (len(allWidgets), len(allWidgets) - len(widgets))) except KeyboardInterrupt: print("Caught interrupt; send another to exit.") try: for i in range(100): QTest.qWait(100) except KeyboardInterrupt: thread.terminate() break except: sys.excepthook(*sys.exc_info()) finally: gc.enable()
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")
def test_1(self): self.qpart.lines = \ [ 'func(param,', ' "text ( param"))'] self.qpart.detectSyntax(language = 'Python') while self.qpart.isHighlightingInProgress(): QTest.qWait(20) firstBlock = self.qpart.document().firstBlock() secondBlock = firstBlock.next() bh = BracketHighlighter() self._verify(bh.extraSelections(self.qpart, firstBlock, 1), []) self._verify(bh.extraSelections(self.qpart, firstBlock, 4), [(4, 5, True), (31, 32, True)]) self._verify(bh.extraSelections(self.qpart, firstBlock, 5), [(4, 5, True), (31, 32, True)]) self._verify(bh.extraSelections(self.qpart, secondBlock, 11), []) self._verify(bh.extraSelections(self.qpart, secondBlock, 19), [(31, 32, True), (4, 5, True)]) self._verify(bh.extraSelections(self.qpart, secondBlock, 20), [(31, 32, True), (4, 5, True)]) self._verify(bh.extraSelections(self.qpart, secondBlock, 21), [(32, 33, False)])
def test_login_success(self): self.form.dialog.loginedit.setText('user1') self.form.dialog.passwordedit.setText('123') QTest.mouseClick(self.form.dialog.loginbutton, QtCore.Qt.LeftButton) QTest.qWait(1000) assert not self.form.dialog.isVisible() assert self.form.api_thread.is_authenticated()
def test_drag_drop_file(self): """ Test dropping multiple files on the tab widget. :return: http://stackoverflow.com/questions/11500844/qtest-its-possible-to-test-dragdrop http://wiki.qt.io/Drag_and_Drop_of_files """ # pre_cnt = self.form.documents_tabWidget.count() # D&D events take MIME data and for files need URLs mime_files = QMimeData() files = [QUrl().fromLocalFile(os.path.join(self.data_dir, 'lorem.txt')), QUrl().fromLocalFile(os.path.join(self.data_dir, 'utf8_test.txt'))] mime_files.setUrls(files) # Drag the files action = Qt.MoveAction target = self.form.documents_tabWidget.rect().center() drag_drop = QDropEvent(target, action, mime_files, Qt.LeftButton, Qt.NoModifier) drag_drop.acceptProposedAction() # Drop the files self.form.documents_tabWidget.dropEvent(drag_drop) QTest.qWait(200) # Give the GUI time to load the data # Check the new tabs post_cnt = self.form.documents_tabWidget.count() self.assertEqual(post_cnt, pre_cnt + len(files)) self.assertEqual(self.form.documents_tabWidget.widget(1).filename, 'lorem.txt') self.assertEqual(self.form.documents_tabWidget.widget(2).filename, 'utf8_test.txt')
def tearDown(self): ''' Clean up after the test ''' # Close the form self.form.close() QTest.qWait(100) self.form = None
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')
def crashtest(): global allWidgets try: gc.disable() actions = [ createWidget, #setParent, forgetWidget, showWidget, processEvents, #raiseException, #addReference, ] thread = WorkThread() thread.start() while True: try: action = randItem(actions) action() print('[%d widgets alive, %d zombie]' % (len(allWidgets), len(allWidgets) - len(widgets))) except KeyboardInterrupt: print("Caught interrupt; send another to exit.") try: for i in range(100): QTest.qWait(100) except KeyboardInterrupt: thread.terminate() break except: sys.excepthook(*sys.exc_info()) finally: gc.enable()
def test_carbon(self): file_path = os.path.join(FILE_BASE, 'carbon_biophysical.json') model_ui = modelui.ModelUI(file_path, True) # since we need to test both carbon biophysical and valuation, we need # to check the checkbox to actually trigger the calculation of # sequestration so that the valuation component can be run. checkbox = model_ui.allElements['calc_sequestration'] checkbox.setValue(True) #QTest.mouseClick(checkbox, Qt.MouseButton(1)) QTest.qWait(500) # so that validation can finish for enabled elements. files_to_check = [ 'Output/tot_C_cur.tif', 'Output/tot_C_fut.tif', 'Output/sequest.tif', 'Intermediate/bio_hwp_cur.tif', 'Intermediate/bio_hwp_fut.tif', 'Intermediate/c_hwp_cur.tif', 'Intermediate/c_hwp_fut.tif', 'Intermediate/vol_hwp_cur.tif', 'Intermediate/vol_hwp_fut.tif' ] self.click_through_model(model_ui, files_to_check) # Now that we've run the carbon biophysical model and checked that all # required files exist, do the same steps with carbon valuation. file_path = os.path.join(FILE_BASE, 'carbon_valuation.json') valuation_ui = modelui.ModelUI(file_path, True) # The sequestration file field needs to be set to contain the URI of the # sequestration raster output from the biophysical model. sequest_element = valuation_ui.allElements['sequest_uri'] sequest_element.setValue( os.path.join(self.workspace, 'Output', 'sequest.tif')) # only one output file to check! files_to_check = ['Output/value_seq.tif'] self.click_through_model(valuation_ui, files_to_check)
def test_login_fail(self): self.form.dialog.loginedit.setText('user1') self.form.dialog.passwordedit.setText('999999') QTest.mouseClick(self.form.dialog.loginbutton, QtCore.Qt.LeftButton) QTest.qWait(1000) assert self.form.dialog.isVisible() assert self.form.dialog.errorlabel.isVisible()
def test_tray_icon_menu_pause_action(self): pause_action = self.form.tray_icon.contextMenu().actions()[1] self.play_mix() assert pause_action.isEnabled() pause_action.trigger() QTest.qWait(100) assert not pause_action.isEnabled() assert self.form.mediaObject.state() == Phonon.PausedState
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))
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")
def _sleepAndCheck(self, sleep, doc1_modified, doc1_removed, doc2_modified, doc2_removed): QTest.qWait(sleep * 1000) self.assertEqual(self._doc1._externallyModified, doc1_modified) self.assertEqual(self._doc1._externallyRemoved, doc1_removed) self.assertEqual(self._doc2._externallyModified, doc2_modified) self.assertEqual(self._doc2._externallyRemoved, doc2_removed)
def test_tags_change(self): self.form.api_thread.request_mixes() QTest.qWait(100) # wait for mixes assert 'Hot' in self.form.browserWidget.mixes self.form.browserWidget.update_mixes('sex') QTest.qWait(2000) assert self.form.browserWidget.current_tag == 'sex' assert 'sex' in self.form.browserWidget.mixes self.form.browserWidget.update_mixes('Hot')
def test_skip_track(self): assert isinstance(self.form.skipAction, QtGui.QAction) assert not self.form.skipAction.isEnabled() self.play_mix() assert self.form.skipAction.isEnabled() track = self.form.current_track self.form.skipAction.trigger() QTest.qWait(2000) assert track != self.form.current_track assert self.form.mediaObject.state() == Phonon.PlayingState
def process_example_data(self): # Add the job to the list self.ex.ui.pushButtonGo.click() # Click the start button to run the job self.ex.ui.pushButtonStart.click() # Wait for process to finish while self.ex.workthread is not None: QTest.qWait(250)
def process_example_data(self): # Add the job to the list self.ex.ui.pushButtonGo.click() # Click the start button to run the job self.ex.ui.pushButtonStart.click() # Wait for process to finish while self.ex.workthread is not None: QTest.qWait(250)
def test_check_code(self): """ Can quality issues in code be flagged for review by the user? :return: """ srcpath = os.path.join(self.data_dir, 'unlinted.py') self.form.open_filepath(srcpath) tab = self.form.ui.documents_tabWidget.currentWidget() self.form.ui.actionCheck_Code.trigger() QTest.qWait(200) next_marker = tab.editor.markerFindNext(0,-1) self.assertGreater(next_marker, -1)
def waitUntilPassed(self, timeout, func): """Try to execute a function until it doesn't fail""" for _ in range(20): QTest.qWait(timeout / 20.) try: func() except: continue else: break else: func()
def test_dev_null(self): core.workspace().openFile(self.EXISTING_FILE) NEW_PATH = "/dev/null" _startEditCurrentFilePath() self.keyClicks(NEW_PATH) self.keyClick(Qt.Key_Return) QTest.qWait(100) # Test fails without a sleep. Threads inside Qt??? self.assertFalse(os.path.isfile(self.EXISTING_FILE)) self.assertIsNone(core.workspace().currentDocument())
def test_dev_null(self): core.workspace().openFile(self.EXISTING_FILE) NEW_PATH = '/dev/null' _startEditCurrentFilePath() self.keyClicks(NEW_PATH) self.keyClick(Qt.Key_Return) QTest.qWait(100) # Test fails without a sleep. Threads inside Qt??? self.assertFalse(os.path.isfile(self.EXISTING_FILE)) self.assertIsNone(core.workspace().currentDocument())
def test_annotate(self): self.win.log_list.select_revid(self.tree.branch.get_rev_id(2)) QTest.qWait(50) doc = self.win.guidebar_panel.edit.document() data = self.win.guidebar_panel.bar.entries['annotate'].data expected = [x[1] for x in DIFF if len(x[1]) > 0] self.assertEqual(len(data), len(expected)) for (block_no, num), lines in zip(data, expected): self.assertEqual(num, len(lines)) for i in range(num): text = str(doc.findBlockByNumber(block_no + i).text()) self.assertEqual(text, lines[i])
def setUp(self): TestGuideBarBase.setUp(self) self.tree.commit(message='2') self.win = AnnotateWindow(None, None, None, None, None, loader=self.load, loader_args=[]) self.addCleanup(self.win.close) self.win.show() QTest.qWait(50) self.waitUntil(lambda: self.win.throbber.isVisible() == False, 500)
def test_success(self): core.workspace().openFile(self.EXISTING_FILE) NEW_PATH = self.TEST_FILE_DIR + "/newname" _startEditCurrentFilePath() self.keyClicks(NEW_PATH) self.keyClick(Qt.Key_Return) QTest.qWait(100) # Test fails without a sleep. Threads inside Qt??? self.assertTrue(os.path.isfile(NEW_PATH)) with open(NEW_PATH) as f: text = f.read() self.assertEqual(text, self.EXISTING_FILE_TEXT)
def test_value_changed(self): # verify that when the value of the textfield is changed, the # value_changed communicator is triggered. mock_func = mock.MagicMock(name='function') self.widget.value_changed.register(mock_func) # verify the mock function has not yet been called. self.assertEqual(mock_func.called, False) # change the value, verify that mock_func has been called. self.widget.set_text('some new value') QTest.qWait(50) # wait for the Qt event loop to detect changed text self.assertEqual(self.widget.text(), 'some new value') self.assertEqual(mock_func.called, True)
def test_success(self): core.workspace().openFile(self.EXISTING_FILE) NEW_PATH = self.TEST_FILE_DIR + '/newname' _startEditCurrentFilePath() self.keyClicks(NEW_PATH) self.keyClick(Qt.Key_Return) QTest.qWait(100) # Test fails without a sleep. Threads inside Qt??? self.assertTrue(os.path.isfile(NEW_PATH)) with open(NEW_PATH) as f: text = f.read() self.assertEqual(text, self.EXISTING_FILE_TEXT)
def test_halt_running_script(self): """ Can a long running script be cleanly halted? :return: """ srcpath = os.path.join(self.data_dir, 'run_forever.py') self.form.open_filepath(srcpath) cmd = self.form.ui.runScript_command.text() self.assertIn('run_forever.py', cmd) self.form.ui.actionRun_Current_Script.trigger() self.assertGreater(self.form.runscript_process.state(), 0) QTest.qWait(200) self.form.terminate_current_script() self.assertEqual(self.form.runscript_process.state(), 0)
def click_through_model(self, model_ui, files_to_check): """Click through a standard modelui interface. model_ui - an instance of natcap.invest.iui.modelui.ModelUI files_to_check - a list of strings. Each string must be a URI relative to the workspace. All files at these URIs are required to exist. An AssertionError will be thrown if a file does not exist. Returns nothing.""" workspace_element = locate_workspace_element(model_ui) workspace_element.setValue(self.workspace) QTest.qWait(100) # Wait for the test workspace to validate # Assert that the test workspace didn't get a validation error. self.assertEqual(workspace_element.has_error(), False) # Assert that there are no default data validation errors. validation_errors = model_ui.errors_exist() self.assertEqual( validation_errors, [], 'Validation errors ' 'exist for %s inputs. Errors: %s' % (len(validation_errors), validation_errors)) # Click the 'Run' button and see what happens now. QTest.mouseClick(model_ui.runButton, Qt.MouseButton(1)) # Now that the run button has been pressed, we need to check the state # of the operation dialog to see if it has finished completing. This # check is done at half-secong intervals. while not model_ui.operationDialog.backButton.isEnabled(): QTest.qWait(500) # Once the test has finished, click the back button on the dialog to # return toe the UI. QTest.mouseClick(model_ui.operationDialog.backButton, Qt.MouseButton(1)) missing_files = [] for filepath in files_to_check: full_filepath = os.path.join(self.workspace, filepath) if not os.path.exists(full_filepath): missing_files.append(filepath) self.assertEqual( missing_files, [], 'Some expected files were not ' 'found: %s' % missing_files)
def test_setMessage(self): parent = FakeParent() sb = StatusBar(parent) sb.setMessage('Just a message') self.assertEqual(sb._statusLabel.text(), 'Just a message') sb.setMessage('Just a message', pixmap=self.greenPixmap) self.assertEqual(sb._pixmapLabel.pixmap().cacheKey(), self.greenPixmap.cacheKey()) sb.setMessage('Just another message', duration=1, pixmap=self.redPixmap) self.assertEqual(sb._statusLabel.text(), 'Just another message') self.assertEqual(sb._pixmapLabel.pixmap().cacheKey(), self.redPixmap.cacheKey()) QTest.qWait(2000) self.assertEqual(sb._statusLabel.text(), 'Just a message')
def retryUntilPassed(self, timeoutMs, function): """ Try to execute a function until it doesn't generate any exception but not more than for timeoutSec Raise exception, if timeout passed """ for _ in range(20): QTest.qWait(timeoutMs / 20.) try: function() except: continue else: return else: function()
def retryUntilPassed(self, timeoutMs, function): """ Try to execute a function until it doesn't generate any exception but not more than for timeoutSec Raise exception, if timeout passed """ for _ in range(20): QTest.qWait(timeoutMs / 20.) try: function() except: continue else: return else: function()
def test_value_changed(self): mock_func = mock.MagicMock(name='function') self.widget.value_changed.register(mock_func) # verify that when the value is set (but not changed), the function is # not called. self.assertEqual(mock_func.called, False) self.widget.setCurrentIndex(self.widget.currentIndex()) self.assertEqual(mock_func.called, False) # when the value is changed, verify that the communicator is called new_index = 1 self.assertNotEqual(self.widget.currentIndex(), new_index) self.widget.setCurrentIndex(new_index) QTest.qWait(50) # wait for the qt event loop to catch on self.assertEqual(mock_func.called, True)
def waitFor(predicate, timeout): """Process events until predicate is true or timeout seconds passed This seems to not handle the destruction of widget correctly, use waitForLoop in such cases. """ if predicate(): return True timer = Qt.QElapsedTimer() timer.start() while not timer.hasExpired(timeout): QTest.qWait(min(100, timeout - timer.elapsed())) if predicate(): return True return predicate()
def test_sync13a(self): """ Make sure sync stops if the Preview dock is hidden. See https://github.com/hlamer/enki/issues/352. """ # First, open the preview dock. self._doBasicTest('rst') # Speed up the test by reducing the cursor movemovement timer's timeout. This can only be done when the preview dock is open. Record `ps`, since this won't be available when the Preview dock is hidden below. ps = self._dock().previewSync ps._cursorMovementTimer.setInterval(0) # Now, switch to a non-previewable file. self.createFile('foo.unpreviewable_extension', 'Junk') # Move the cursor. Make sure sync doesn't run. qp = core.workspace().currentDocument().qutepart # One way to tell: the background sync won't run, meaning the future won't change. I tried with ``mock.patch('enki.plugins.preview.preview_sync.PreviewSync.syncTextToPreview`) as syncTextToPreview:``, but ``syncTextToPreview.assert_not_called()`` always passed. f = ps._runLatest.future qp.cursorPosition = (100, 100) # Wait for Qt to process messages, such as the timer. QTest.qWait(0) self.assertEquals(f, ps._runLatest.future)
def testInfoIcon(self): iw = QWidget() layout = QHBoxLayout() layout.setMargin(100) ii = InfoIcon('hover popup text', iw) layout.addWidget(ii) iw.setLayout(layout) iw.setWindowModality(Qt.ApplicationModal) iw.show() QTest.mouseMove(iw, iw.pos()) self.assertEqual(QToolTip.text(), 'Name is not unique') QTest.mouseMove(ii) # why is this necessary? QTest.qWait(250) QTest.mouseMove(ii) QTest.qWait(2000) self.assertEqual(QToolTip.text(), 'hover popup text')
def testInfoIcon(self): iw = QWidget() layout = QHBoxLayout() layout.setMargin(100) ii = InfoIcon('hover popup text', iw) layout.addWidget(ii) iw.setLayout(layout) iw.setWindowModality(Qt.ApplicationModal) iw.show() QTest.mouseMove(iw, iw.pos()) self.assertEqual(QToolTip.text(), '') QTest.mouseMove(ii) # why is this necessary? QTest.qWait(250) QTest.mouseMove(ii) QTest.qWait(2000) self.assertEqual(QToolTip.text(), 'hover popup text')
def test_1(self): """ File is checked after opened """ doc = self.createFile('test.py', 'asdf\n\n') QTest.qWait(500) self.assertEqual(doc.qutepart.lintMarks, {0: ('e', "Undefined variable 'asdf'")}) self.assertEqual(core.mainWindow().statusBar().currentMessage(), "Undefined variable 'asdf'") doc.qutepart.cursorPosition = ((1, 0)) self.assertEqual(core.mainWindow().statusBar().currentMessage(), "") doc.qutepart.cursorPosition = ((0, 1)) self.assertEqual(core.mainWindow().statusBar().currentMessage(), "Undefined variable 'asdf'") doc.qutepart.text = 'def main()\n return 7' self.assertEqual(doc.qutepart.lintMarks, {}) self.assertEqual(core.mainWindow().statusBar().currentMessage(), "") doc.saveFile() QTest.qWait(500) self.assertEqual(doc.qutepart.lintMarks, {0: ('e', 'invalid syntax')})
def test_12(self): for _ in self.singleThreadOnly: with AsyncController(_) as ac: q1a = Queue() q1b = Queue() def f1(): q1b.put(None) q1a.get() em1 = Emitter() future1 = ac.start(em1.g, f1) q1b.get() self.assertEquals(future1.state, Future.STATE_RUNNING) future2 = ac.start(None, lambda: None) QTest.qWait(100) self.assertEquals(future2.state, Future.STATE_WAITING) with WaitForSignal(em1.bing, 1000): future2.cancel() q1a.put(None) self.assertEquals(future1.state, Future.STATE_FINISHED) QTest.qWait(100) self.assertEquals(future2.state, Future.STATE_CANCELED)
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')
def test_13(self): for _ in self.singleThreadOnly: with AsyncController(_) as ac: q1a = Queue() q1b = Queue() def f1(): q1b.put(None) q1a.get() # Cancel future3 while it's running in the other thread. em1 = Emitter('em1 should never be called by {}'.format(_), self.assertEquals) em1.bing.connect(self.fail) future1 = ac.start(em1.g, f1) q1b.get() self.assertEquals(future1.state, Future.STATE_RUNNING) future1.cancel(True) q1a.put(None) # If the result is discarded, it should never emit a signal or # invoke its callback, even if the task is already running. Wait # to make sure neither happened. QTest.qWait(100) # In addition, the signal from a finished task that is discarded # should not invoke the callback, even after the task has # finihsed and the sigal emitted. em2 = Emitter('em2 should never be called be {}'.format(_), self.assertEquals) em2.bing.connect(self.fail) future2 = ac.start(em2.g, lambda: None) # Don't use qWait here, since it will process messages, which # causes em2.g to be invoked. time.sleep(0.1) self.assertEquals(future2.state, Future.STATE_FINISHED) future2.cancel(True) # Test per-task priority. # Wait, in case a pending signal will invoke em2.g. QTest.qWait(100)
def test_non_ascii(self): curve = models.CurveDB.create([1,3,4]) curve.save() import pyinstruments.curvefinder from PyQt4.QtTest import QTest print 'before import' QTest.qWait(1000) from pyinstruments.curvefinder import LIST_CURVE_WIDGET, CURVE_DISPLAY_WIDGET print 'after import' QTest.qWait(1000) LIST_CURVE_WIDGET.select_by_id(curve.id) comment_widget = CURVE_DISPLAY_WIDGET.left_panel.alter_curve_widget.\ curve_comment_widget.comment_box save_button = CURVE_DISPLAY_WIDGET.left_panel.alter_curve_widget.save_button QTest.qWait(1000) QTest.keyClicks(comment_widget, 'yoyoé') QTest.mouseClick(save_button, 1) curve = models.CurveDB.objects.get(id=curve.id)
def inSaveFileDialog(saveDialog): QTest.qWait(4000) self.keyClick('Esc')
def processEvents(): p('process events') QTest.qWait(25)
def testExistingUseCase(self): ''' Test whether an existing Use case can be shown and exported to SVG properly. Also tests moving objects up and down (Z-order). ''' # Copy the test_base database to a new location. BASE_DB = 'test_base.db' NEW_DB = 'test_new.db' if os.path.exists(NEW_DB): os.remove(NEW_DB) shutil.copy(BASE_DB, NEW_DB) # Open the database self.form.onNew(NEW_DB) # Open all the Use Cases. session = model.SessionFactory() for details in session.query(model.View).all(): self.form.centralwidget.openView(details) QTest.qWait(100) # Ensure the 'Overview' view is on top. overview = session.query(model.View).filter(model.View.Name=='Overview').one() self.form.centralwidget.openView(overview) editor = self.form.centralwidget.ui.tabGraphicViews.currentWidget() scene = editor.scene # Move the 'Archtool' block to the back. editor.last_rmouse_click = QtCore.QPoint(255, 116) self.postGuiFunc(editor.onChangeItemOrder, editor.MOVE_TOP) QTest.qWait(100) rep = session.query(model.Anchor).filter(model.Anchor.Id==10).one() self.assertEqual(rep.Order, 7) editor.last_rmouse_click = QtCore.QPoint(255, 116) self.postGuiFunc(editor.onChangeItemOrder, editor.MOVE_DOWN) QTest.qWait(100) session.refresh(rep) self.assertEqual(rep.Order, 6) editor.last_rmouse_click = QtCore.QPoint(255, 116) self.postGuiFunc(editor.onChangeItemOrder, editor.MOVE_UP) QTest.qWait(100) session.refresh(rep) self.assertEqual(rep.Order, 7) editor.last_rmouse_click = QtCore.QPoint(255, 116) self.postGuiFunc(editor.onChangeItemOrder, editor.MOVE_BOTTOM) QTest.qWait(100) session.refresh(rep) self.assertEqual(rep.Order, 0) # Pause to show the result if False: while True: QTest.qWait(100)
def testUseCaseDrawing(self): ''' Test creating and editing a 2D drawing. ''' # Create a Use Case cw = self.form.centralwidget cw.ui.treeUseCases.addHandler() it = cw.ui.treeUseCases.topLevelItem(0) # Open the 2D editor. cw.ui.treeUseCases.itemDoubleClicked.emit(it, 0) editor = cw.ui.tabGraphicViews.currentWidget() # Add two new Architecture Blocks editor.last_rmouse_click = QtCore.QPoint(100, 100) self.APP.postEvent(self.form, AddBlockEvent(editor)) self.answer('Block 1') QTest.qWait(200) editor.last_rmouse_click = QtCore.QPoint(300, 100) self.APP.postEvent(self.form, AddBlockEvent(editor)) self.answer('Block 2') QTest.qWait(200) self.assertEqual(cw.ui.treeBlocks.topLevelItemCount(), 2) # Make a private session for use within the testing thread. session = model.SessionFactory() self.assertEqual(session.query(model.ArchitectureBlock).count(), 2) # Connect the two blocks scene = editor.scene for b in scene.anchors.values(): b.setSelected(True) # TODO: Test if the option to connect blocks is shown in the context menu. self.postGuiFunc(editor.onConnect) QTest.qWait(100) self.assertEqual(session.query(model.BlockConnection).count(), 1) self.assertEqual(session.query(model.ConnectionRepresentation).count(), 1) # Add an Action to the connection and to a block. self.postGuiFunc(scene.clearSelection) editor.last_rmouse_click = QtCore.QPoint(168, 235) self.postGuiFunc(editor.onNewAction) self.answer('Actie 1') QTest.qWait(100) self.assertEqual(session.query(model.FunctionPoint).count(), 1) # Add an Action to the connection editor.last_rmouse_click = QtCore.QPoint(224, 196) self.postGuiFunc(editor.onNewAction) self.answer('Actie 2') QTest.qWait(100) self.assertEqual(session.query(model.FunctionPoint).count(), 2) # Add an Annotation self.postGuiFunc(scene.clearSelection) editor.last_rmouse_click = QtCore.QPoint(100, 300) self.postGuiFunc(editor.onAddAnnotation) QTest.qWait(100) self.assertEqual(session.query(model.Annotation).count(), 1) # Create a second 'Block 2' and connect it # Hack the scene so that the last block is dropped block = session.query(model.ArchitectureBlock).all()[-1] scene.drop2Details = lambda x: block ev = QtGui.QDropEvent(QtCore.QPoint(300, 300), Qt.DropActions(), QtCore.QMimeData(), Qt.MouseButtons(1), Qt.KeyboardModifiers()) self.postGuiFunc(editor.dropEvent, ev) while True: QTest.qWait(100) break # Select the first and third block. scene.clearSelection() for b in [scene.anchors[i] for i in [1, 7]]: b.setSelected(True) self.postGuiFunc(editor.onConnect) QTest.qWait(100) # Check there is just one BlockConnection with two ConnectionRepresentation self.assertEqual(session.query(model.BlockConnection).count(), 1) self.assertEqual(session.query(model.ConnectionRepresentation).count(), 2) # Export to SVG if os.path.exists('test.db.new item.svg'): os.remove('test.db.new item.svg') self.postGuiFunc(editor.exportSvg) self.answer('') # Close the pop-up QTest.qWait(100) self.assertTrue(os.path.exists('test.db.new item.svg')) # Pause to show the result while True: QTest.qWait(200) break pass # For breakpoint # Delete the actions scene.clearSelection() for a in scene.fpviews.values(): a.setSelected(True) self.postGuiFunc(editor.onDelete) QTest.qWait(100) self.assertEqual(session.query(model.FpRepresentation).count(), 0) # Delete the Annotation self.postGuiFunc(scene.clearSelection) editor.last_rmouse_click = QtCore.QPoint(120, 253) self.postGuiFunc(editor.onDeleteItem) QTest.qWait(100) self.assertEqual(session.query(model.Annotation).count(), 0) # Delete the blocks scene.clearSelection() for a in scene.items(): if isinstance(a, BlockItem): a.setSelected(True) self.postGuiFunc(editor.onDelete) QTest.qWait(100) self.assertEqual(session.query(model.BlockRepresentation).count(), 0) # All the connections must have been deleted as well. self.assertEqual(session.query(model.ConnectionRepresentation).count(), 0) self.assertEqual(len([i for i in scene.items() if isinstance(i, Connection)]), 0)
def clickStopButton(after=5000): QTest.qWait(after) dlg = getWABDialog() QTest.mouseClick(dlg.buttonCreateOrStopApp, Qt.LeftButton)
def inSaveFileDialog(saveDialog): QTest.qWait(4000) self.keyClick('Esc')
def inDialogFunc(dialog): cmdPath = (self.TEST_FILE_DIR + '/the').replace('\\', '\\\\').replace(' ', '\\ ') self.keyClicks('o ' + cmdPath) QTest.qWait(200) self.assertTrue(dialog._edit.text().endswith('file.txt')) self.keyClick(Qt.Key_Enter)
def inDialogFunc(dialog): self.keyClicks(text) QTest.qWait(150) self.keyClick(Qt.Key_Enter)
def proceed(self): # This updates the status dialog box, and tells the user what to do next. # It will also tell the user what is happening. # If the row counter is past the number of design matrix rows, save everything and quit if self.row_counter >= len(self.main_dict['design matrix']): # Get the measurement from the edit line self.readout = float(self.ui.readoutEdit.text()) self.ui.readoutEdit.clear() self.update_history_table(self.readout, self.temp, self.press, self.humid) # update the history table self.save_data() # save the current readout and environmentals into the dictionary self.quicksave() # save the latest info into the temp file self.get_readout = False self.status_signal3.emit('Finished with measurements. Generating input file.') self.ui.continueButton.setEnabled(0) # Disable continue button while file is being written QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.waiting = False # put variables to 0 so no if statements will run self.set = 0 runs = sorted(self.data_dict.keys()) pretty(self.main_dict) input_file = generate_input_file(self.input_file_path, self.main_dict, self.data_dict[runs[self.run-1]], 1, len(self.data_dict.keys())) # START OF NEW MASS CODE # Populate the massInfo dictionary based on the main_dict self.massInfo = populate_massInfo(self.main_dict, self.massInfo, False) # pretty(self.massInfo) # print 'END OF MASS INFO' # pretty(self.data_dict) # output = masscode_v1.MassCode(self.massInfo, self.data_dict) output = masscode_v2.MassCode(self.massInfo, self.data_dict) output_file = input_file[:].replace('.ntxt', '.nout') # Create the json file json_file_path = generate_json_file(self.input_file_path, self.main_dict, self.data_dict, output) print json_file_path # END OF NEW MASS CODE # Run input file command = '"%s" "%s" "%s"\n' % (str(masscode_path), str(input_file), str(output_file)) print command t = Thread(target=call, args=(command,)) t.start() QApplication.restoreOverrideCursor() QTest.qWait(2000) self.window.close() try: row = self.main_dict['design matrix'][self.row_counter] # becomes a row of the design matrix e.g. 1 -1 0 0 set1 = [a + 1 for a, b in enumerate(row) if b == 1] # set1 is all the weights with a 1 in the design matrix set2 = [a + 1 for a, b in enumerate(row) if b == -1] # set2 is all the weights with a -1 in the design matrix except IndexError: pretty(self.data_dict) if self.get_readout: # Get the measurement from the edit line self.readout = float(self.ui.readoutEdit.text()) self.ui.readoutEdit.clear() self.update_history_table(self.readout, self.temp, self.press, self.humid) # update the history table self.save_data() # save the current readout and environmentals into the dictionary self.quicksave() # save the latest info into the temp file self.get_readout = False self.ui.readoutEdit.setEnabled(0) if self.waiting: # if a weight was just loaded, isMeasure will be True. self.ui.continueButton.setEnabled(0) # disable the continue button self.stab_timer.start(1000) # start the timer for the stabilization time countdown while not self.ui.readoutEdit.isEnabled(): QTest.qWait(1000) self.ui.continueButton.setEnabled(1) if self.step == 4: # at step 4, it enters the B2A2 phase self.AB = 2 elif self.step == 8: # at the end of B2A2, shift back into A1B1 mode and move to next row self.AB = 1 self.row_counter += 1 self.step = 0 # Increment the progress bar self.ui.progressBar.setValue(self.row_counter) self.waiting = False self.get_readout = True self.step += 1 elif self.set == 1: weights = [] # These are the weights that will be put on # Look at which weights need to be put on and display the weight names for weightNum in set1: weights.append(str(weightNum) + ' - ' + str(self.ui.reminderTable.item(weightNum-1, 0).text())) self.status_signal3.emit('Put on weight(s): %s \nPress Continue to begin stabilization time.' % weights) self.waiting = True if self.AB == 1: self.set = 2 self.step += 1 elif self.set == 2: weights = [] # same as above # same as above for weightNum in set2: weights.append(str(weightNum) + ' - ' + str(self.ui.reminderTable.item(weightNum-1, 0).text())) self.status_signal3.emit('Put on weight(s): %s \nPress Continue to begin stabilization time.' % weights) self.waiting = True if self.AB == 2: self.set = 1 self.step += 1
def test_skip_track(self): self.api_thread.tracks_api._get_play_token() self.api_thread.skip_track(12345) QTest.qWait(500) assert self.next_track_after_skip assert isinstance(self.next_track_after_skip, Track)
def start_download(self): if self.checkBox_from_file.isChecked() and self.lineEdit_path2file.text() == "" \ or not self.checkBox_from_file.isChecked() and self.lineEdit_keywords.text() == "": print("Keywords is empty!") self.lineEdit_keywords.setFocus() return if self.lineEdit_output.text() == "": print("Output directory is empty!") self.lineEdit_output.setFocus() return self.state = "run" self.pushButton_start.setEnabled(False) self.pushButton_cancel.setEnabled(True) config, keywords_list = self.gen_config_from_ui() self.elapsed_timer.restart() self.update_timer.start() self.reset_ui() num_keywords = len(keywords_list) self.progressBar_total.setMaximum(num_keywords) self.progressBar_total.setFormat("%p%, %v/%m") self.progressBar_total.setValue(0) for index in range(num_keywords): if self.state != "run": break keywords = keywords_list[index].strip() if keywords == "": continue config.keywords = keywords str_paras = config.to_command_paras() print(str_paras) self.progressBar_current.setMaximum(config.max_number) self.progressBar_current.setValue(0) self.progressBar_current.setFormat(keywords + ", %p%, %v/%m") thread_download = Thread(target=image_downloader.main, args=[shlex.split(str_paras)]) thread_download.start() while thread_download.is_alive(): QTest.qWait(1000) if self.isHidden(): os._exit(0) self.progressBar_total.setValue(index + 1) if self.state == "run": self.state = "stop" self.pushButton_cancel.setEnabled(False) self.pushButton_start.setEnabled(True) self.update_timer.stop() print("stopped") pass
def test_Requirements(self): ''' Test adding and editing some requirements. ''' cw = self.form.centralwidget self.assertIsInstance(cw, run.ArchitectureView) # Get the window that is shown inside the current TAB window cw.ui.tabWidget.setCurrentWidget(cw.ui.treeRequirements) QTest.qWait(100) # Add a new requirement cw.ui.treeRequirements.addHandler() QTest.qWait(100) self.assertEqual(cw.ui.treeRequirements.topLevelItemCount(), 1) # Check a database record has been created. r = self.form.session.query(model.Requirement).all() self.assertEqual(len(r), 1) # Check the values in the details editor self.assertEqual(cw.details_viewer.edits[0].currentText(), 'Functional') self.assertEqual(cw.details_viewer.edits[1].text(), 'new item') self.assertEqual(cw.details_viewer.edits[2].toPlainText(), '') self.assertEqual(cw.details_viewer.edits[3].currentText(), 'Must') # Change the name and check the name in the database can be edited. name = 'Requirement 1' cw.details_viewer.edits[1].setText(name) cw.details_viewer.edits[1].textEdited.emit(name) QTest.qWait(100) self.assertEqual(r[0].Name, name) # Commit the change and check the list is updated # Normally, the database is committed when the user selects something. self.form.session.commit() it = cw.ui.treeRequirements.topLevelItem(0) self.assertEqual(it.text(0), name) # Create a new requirement, as child from the first one. # Select the first requirement. it.setSelected(True) # Create the new item cw.ui.treeRequirements.addHandler() QTest.qWait(100) # Check the database and GUI structures self.assertEqual(cw.ui.treeRequirements.topLevelItemCount(), 1) r = self.form.session.query(model.Requirement).all() self.assertEqual(len(r), 2) self.assertEqual(r[1].Parent, r[0].Id) self.assertEqual(it.childCount(), 1) self.assertEqual(it.child(0).childCount(), 0) # Ensure the new item is editable name2 = 'Requirement 2' cw.details_viewer.edits[1].setText(name2) cw.details_viewer.edits[1].textEdited.emit(name2) QTest.qWait(100) self.assertEqual(r[1].Name, name2) self.assertEqual(r[0].Name, name) # Add a status change. self.assertEqual(len(r[1].StateChanges), 0) self.postGuiFunc(StateChangeEditor.add, cw.details_viewer, r[1], self.form.session) self.answer('') QTest.qWait(100) self.assertEqual(len(r[1].StateChanges), 1)