def replaced_configure_traits(instance, filename=None, view=None, kind=None, edit=True, context=None, handler=None, id="", scrollable=None, **args): """ Mocked configure_traits to launch then close the GUI. """ ui = instance.edit_traits( view=view, parent=None, kind="live", # other options may block the test context=context, handler=handler, id=id, scrollable=scrollable, **args, ) with reraise_exceptions(): process_cascade_events() # Temporary fix for enthought/traitsui#907 if is_qt(): ui.control.hide() if is_wx(): ui.control.Hide() ui.dispose() process_cascade_events()
def load_tests(loader, tests, pattern): """ Implement load_tests protocol so that when unittest discover is run with this test module, the tests in the demo folder (not a package) are also loaded. See unittest documentation on load_tests """ # Keep all the other loaded tests. suite = unittest.TestSuite() suite.addTests(tests) # Expand the test suite with tests from the examples, assuming # the test for ``group/script.py`` is placed in ``group/tests/`` directory. accepted_files, _ = SEARCHER.get_python_files() test_dirs = set( os.path.join(os.path.dirname(path), "tests") for path in accepted_files) test_dirs = set(path for path in test_dirs if os.path.exists(path)) for dirpath in sorted(test_dirs): # Test files are scripts too and they demonstrate running the # tests. Mock the run side-effect when we load the test cases. with mock.patch.object(unittest.TextTestRunner, "run"): test_suite = unittest.TestLoader().discover(dirpath, pattern=pattern) if is_qt() or is_wx(): suite.addTests(test_suite) return suite
def test_table_editor_select_cells(self): object_list = ObjectListWithSelection( values=[ListItem(value=str(i**2)) for i in range(10)]) object_list.selected_cells = [ (object_list.values[5], "value"), (object_list.values[6], "other value"), (object_list.values[8], "value"), ] with reraise_exceptions(), \ create_ui(object_list, dict(view=select_cells_view)) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): selected = editor.selected elif is_wx(): selected = editor.selected_cells process_cascade_events() self.assertEqual(selected, [ (object_list.values[5], "value"), (object_list.values[6], "other value"), (object_list.values[8], "value"), ])
def right_click_center(editor): """Right click the middle of the widget.""" if is_wx(): import wx control = editor.control event = wx.ListEvent( wx.EVT_LIST_ITEM_RIGHT_CLICK.typeId, control.GetId() ) wx.PostEvent(control, event) elif is_qt(): from pyface.qt import QtCore from pyface.qt.QtTest import QTest view = editor.list_view rect = view.rect() QTest.mouseClick( view.viewport(), QtCore.Qt.MouseButton.RightButton, QtCore.Qt.KeyboardModifier.NoModifier, rect.center(), ) else: raise unittest.SkipTest("Test not implemented for this toolkit")
def test_csv_editor_external_append(self): # Behavior: CSV editor is notified when an element is appended to the # list externally def _wx_get_text_value(ui): txt_ctrl = ui.control.FindWindowByName("text", ui.control) return txt_ctrl.GetValue() def _qt_get_text_value(ui): from pyface import qt txt_ctrl = ui.control.findChild(qt.QtGui.QLineEdit) return txt_ctrl.text() list_of_floats = ListOfFloats(data=[1.0]) csv_view = ListOfFloatsWithCSVEditor(model=list_of_floats) with reraise_exceptions(), create_ui(csv_view) as ui: # add element to list, make sure that editor knows about it list_of_floats.data.append(3.14) # get current value from editor if is_wx(): value_str = _wx_get_text_value(ui) elif is_qt(): value_str = _qt_get_text_value(ui) expected = csv_list_editor._format_list_str([1.0, 3.14]) self.assertEqual(value_str, expected)
def right_click_item(editor, index): """Right clicks on the specified item.""" if is_wx(): import wx control = editor.control event = wx.ListEvent( wx.EVT_LIST_ITEM_RIGHT_CLICK.typeId, control.GetId() ) event.SetIndex(index) wx.PostEvent(control, event) elif is_qt(): from pyface.qt import QtCore from pyface.qt.QtTest import QTest view = editor.list_view q_model_index = view.model().index(index, 0) view.scrollTo(q_model_index) rect = view.visualRect(q_model_index) QTest.mouseClick( view.viewport(), QtCore.Qt.MouseButton.RightButton, QtCore.Qt.KeyboardModifier.NoModifier, rect.center(), ) else: raise unittest.SkipTest("Test not implemented for this toolkit")
def test_list_str_editor_single_selection(self): with reraise_exceptions(), self.setup_gui( ListStrModel(), get_view() ) as editor: if is_qt(): # No initial selection self.assertEqual(editor.selected_index, -1) self.assertEqual(editor.selected, None) elif is_wx(): # First element selected initially self.assertEqual(editor.selected_index, 0) self.assertEqual(editor.selected, "one") set_selected_single(editor, 1) process_cascade_events() self.assertEqual(editor.selected_index, 1) self.assertEqual(editor.selected, "two") set_selected_single(editor, 2) process_cascade_events() self.assertEqual(editor.selected_index, 2) self.assertEqual(editor.selected, "three") clear_selection(editor) process_cascade_events() self.assertEqual(editor.selected_index, -1) self.assertEqual(editor.selected, None)
def close_control(control): """ Close the widget.""" if is_qt(): control.close() elif is_wx(): control.Close() else: raise NotImplementedError("Unexpected toolkit")
def test_list_str_editor_refresh_editor(self): # Smoke test for refresh_editor/refresh_ with reraise_exceptions(), \ self.setup_gui(ListStrModel(), get_view()) as editor: if is_qt(): editor.refresh_editor() elif is_wx(): editor._refresh() process_cascade_events()
def get_custom_ui_tester(): """ Return an instance of UITester that contains extended testing functionality for HTMLEditor. These implementations are used by TraitsUI only, are more ad hoc than they would have been if they were made public. """ if is_qt(): return UITester(registries=[qt_target_registry()]) return UITester()
def get_combobox_text(combobox): """ Return the text given a combobox control. """ if is_wx(): return combobox.GetString(combobox.GetSelection()) elif is_qt(): return combobox.currentText() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def get_list_widget_text(list_widget): """ Return the text of currently selected item in given list widget. """ if is_wx(): selected_item_idx = list_widget.GetSelection() return list_widget.GetString(selected_item_idx) elif is_qt(): return list_widget.currentItem().text() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def test_list_str_editor_single_selection_changed(self): with reraise_exceptions(), self.setup_gui( ListStrModel(), get_view() ) as editor: if is_qt(): # No initial selection self.assertEqual(get_selected_indices(editor), []) elif is_wx(): # First element selected initially self.assertEqual(get_selected_indices(editor), [0]) editor.selected_index = 1 process_cascade_events() self.assertEqual(get_selected_indices(editor), [1]) self.assertEqual(editor.selected, "two") editor.selected = "three" process_cascade_events() self.assertEqual(get_selected_indices(editor), [2]) self.assertEqual(editor.selected_index, 2) # Selected set to invalid value doesn't change anything editor.selected = "four" process_cascade_events() self.assertEqual(get_selected_indices(editor), [2]) self.assertEqual(editor.selected_index, 2) # Selected index changed to editor.selected_index = -1 process_cascade_events() if is_qt(): # -1 clears selection self.assertEqual(get_selected_indices(editor), []) self.assertEqual(editor.selected, None) elif is_wx(): # Visually selects everything but doesn't update `selected` self.assertEqual(editor.selected, "four") self.assertEqual(get_selected_indices(editor), [0, 1, 2])
def get_button_control(control, button_idx): """Get button control from a specified parent control given a button index. Assumes all sizer children (wx) or layout items (qt) are buttons. """ if is_wx(): return control.GetSizer().GetChildren()[button_idx].GetWindow() elif is_qt(): return control.layout().itemAt(button_idx).widget() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def finish_combobox_text_entry(combobox): """ Finish text entry given combobox. """ if is_wx(): import wx event = wx.CommandEvent(wx.EVT_TEXT_ENTER.typeId, combobox.GetId()) wx.PostEvent(combobox, event) elif is_qt(): combobox.lineEdit().editingFinished.emit() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def set_list_widget_selected_index(list_widget, idx): """ Set the choice index given a list widget control and index number. """ if is_wx(): import wx list_widget.SetSelection(idx) event = wx.CommandEvent(wx.EVT_LISTBOX.typeId, list_widget.GetId()) wx.PostEvent(list_widget, event) elif is_qt(): list_widget.setCurrentRow(idx) else: raise unittest.SkipTest("Test not implemented for this toolkit")
def set_selected_single(editor, index): """Selects a specified item in an editor with multi_select=False.""" if is_wx(): editor.control.Select(index) elif is_qt(): from pyface.qt.QtGui import QItemSelectionModel smodel = editor.list_view.selectionModel() mi = editor.model.index(index) smodel.select(mi, QItemSelectionModel.SelectionFlag.ClearAndSelect) else: raise unittest.SkipTest("Test not implemented for this toolkit")
def set_text_in_line_edit(line_edit, text): """ Set text in text widget and complete editing. """ if is_wx(): import wx line_edit.SetValue(text) event = wx.CommandEvent(wx.EVT_TEXT_ENTER.typeId, line_edit.GetId()) wx.PostEvent(line_edit, event) elif is_qt(): line_edit.setText(text) line_edit.editingFinished.emit() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def get_combobox_text(combobox): """ Return the text given a combobox control """ if is_wx(): import wx if isinstance(combobox, wx.Choice): return combobox.GetString(combobox.GetSelection()) else: return combobox.GetValue() elif is_qt(): return combobox.currentText() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def test_radio_enum_editor_pick(self): for cols in range(1, 4): for row_major in [True, False]: enum_edit = EnumModel() tester = UITester() view = get_radio_view(cols=cols) with tester.create_ui(enum_edit, dict(view=view)) as ui: # sanity check self.assertEqual(enum_edit.value, "one") radio_editor = tester.find_by_name(ui, "value") if is_qt(): radio_editor._target.row_major = row_major radio_editor._target.rebuild_editor() item = radio_editor.locate(Index(3)) item.perform(MouseClick()) self.assertEqual(enum_edit.value, "four")
def get_list_items(list_widget): """Return a list of strings from the list widget.""" items = [] if is_wx(): for i in range(list_widget.GetCount()): items.append(list_widget.GetString(i)) elif is_qt(): for i in range(list_widget.count()): items.append(list_widget.item(i).text()) else: raise unittest.SkipTest("Test not implemented for this toolkit") return items
def clear_selection(editor): """Clears existing selection.""" if is_wx(): import wx currently_selected = get_selected_rows(editor) # Deselect all currently selected items for selected_row in currently_selected: editor.control.SetItemState(selected_row, 0, wx.LIST_STATE_SELECTED) elif is_qt(): editor.control.selectionModel().clearSelection() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def click_on_image(image_control): """Click on the image controlled by given image_control.""" if is_wx(): import wx event_down = wx.MouseEvent(wx.EVT_LEFT_DOWN.typeId) wx.PostEvent(image_control, event_down) event_up = wx.MouseEvent(wx.EVT_LEFT_UP.typeId) event_up.SetX(0) event_up.SetY(0) wx.PostEvent(image_control, event_up) elif is_qt(): image_control.click() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def set_selected_single(editor, row): """Selects a specified row in an editor with multi_select=False.""" if is_wx(): editor.control.Select(row) elif is_qt(): from pyface.qt.QtGui import QItemSelectionModel smodel = editor.control.selectionModel() mi = editor.model.index(row, 0) # Add `Rows` flag to select the whole row smodel.select( mi, QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows) else: raise unittest.SkipTest("Test not implemented for this toolkit")
def click_radio_button(widget, button_idx): """ Simulate a radio button click given widget and button number. Assumes all sizer children (wx) or layout items (qt) are buttons.""" if is_wx(): import wx sizer_items = widget.GetSizer().GetChildren() button = sizer_items[button_idx].GetWindow() event = wx.CommandEvent(wx.EVT_RADIOBUTTON.typeId, button.GetId()) event.SetEventObject(button) wx.PostEvent(widget, event) elif is_qt(): widget.layout().itemAt(button_idx).widget().click() else: raise unittest.SkipTest("Test not implemented for this toolkit")
def test_table_editor_select_row_index(self): object_list = ObjectListWithSelection( values=[ListItem(value=str(i**2)) for i in range(10)]) object_list.selected_index = 5 with reraise_exceptions(), \ create_ui(object_list, dict(view=select_row_index_view)) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): selected = editor.selected_indices elif is_wx(): selected = editor.selected_row_index process_cascade_events() self.assertEqual(selected, 5)
def right_click_item(control, index): """ Right clicks on the specified item. """ if is_wx(): import wx event = wx.ListEvent(wx.EVT_LIST_ITEM_RIGHT_CLICK.typeId, control.GetId()) event.SetIndex(index) wx.PostEvent(control, event) elif is_qt(): # Couldn't figure out how to close the context menu programatically raise unittest.SkipTest("Test not implemented for this toolkit") else: raise unittest.SkipTest("Test not implemented for this toolkit")
def click_on_item(editor, item_idx, in_used=False): """ Simulate a click on an item in a specified list. The function deselects all items in both used and unused lists, then selects an item at index item_idx either in the used list (if in_used=True) or in the unused list. Finally the function simulates a click on the selected item. """ unused_list = editor._unused used_list = editor._used if is_wx(): import wx # First deselect all items for i in range(unused_list.GetCount()): unused_list.Deselect(i) for i in range(used_list.GetCount()): used_list.Deselect(i) # Select the item in the correct list list_with_selection = used_list if in_used else unused_list list_with_selection.SetSelection(item_idx) event = wx.CommandEvent( wx.EVT_LISTBOX.typeId, list_with_selection.GetId() ) wx.PostEvent(editor.control, event) elif is_qt(): for i in range(unused_list.count()): status = (not in_used) and (item_idx == i) unused_list.item(i).setSelected(status) for i in range(used_list.count()): status = (in_used) and (item_idx == i) used_list.item(i).setSelected(status) if in_used: used_list.itemClicked.emit(used_list.item(item_idx)) else: unused_list.itemClicked.emit(unused_list.item(item_idx)) else: raise unittest.SkipTest("Test not implemented for this toolkit")
def test_labels_enabled_when(self): # Behaviour: label should enable/disable along with editor dialog = EnableWhenDialog() with reraise_exceptions(), create_ui(dialog) as ui: labelled_editor = ui.get_editors("labelled_item")[0] if is_qt(): unlabelled_editor = ui.get_editors("unlabelled_item")[0] self.assertIsNone(unlabelled_editor.label_control) self.assertTrue(is_control_enabled(labelled_editor.label_control)) dialog.bool_item = False self.assertFalse(is_control_enabled(labelled_editor.label_control)) dialog.bool_item = True
def set_combobox_index(editor, idx): """ Set the choice index of a combobox control given editor and index number. """ if is_wx(): import wx choice = editor.control choice.SetSelection(idx) event = wx.CommandEvent(wx.EVT_CHOICE.typeId, choice.GetId()) event.SetString(choice.GetString(idx)) wx.PostEvent(choice, event) elif is_qt(): # Cannot initiate update programatically because of `activated` # event. At least check that it updates as expected when done # manually editor.update_object(idx) else: raise unittest.SkipTest("Test not implemented for this toolkit")