Пример #1
0
def _test_TextTagPanel_keyboard_close():
    sim   = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    panel = tt.TextTagPanel(frame, style=tt.TTP_KEYBOARD_NAV)
    sizer.Add(panel, flag=wx.EXPAND)
    frame.SetSizer(sizer)
    frame.Layout()

    result = [None]

    def handler(ev):
        result[0] = ev.tag

    panel.Bind(tt.EVT_TTP_TAG_REMOVED, handler)

    tags = ['tag1', 'tag2', 'tag3']

    panel.SetOptions(tags)
    for t in tags:
        panel.AddTag(t)
    realYield()

    # Give a tag focus
    simclick(sim, panel.tags[0], stype=2)

    # Hit the delete key
    simkey(sim, panel.tags[0], wx.WXK_DELETE)
    assert result[0] == tags[0]

    # Give another tag focus
    simclick(sim, panel.tags[0], stype=2)
    # Hit the backspace key
    simkey(sim, panel.tags[0], wx.WXK_BACK)
    assert result[0] == tags[1]
def _test_notebook_events(side, ornt):
    sim      = wx.UIActionSimulator()
    frame    = wx.GetApp().GetTopWindow()
    sizer    = wx.BoxSizer(wx.VERTICAL)
    notebook = nb.Notebook(frame, style=side | ornt)
    page1    = wx.Panel(notebook)
    page2    = wx.Panel(notebook)
    page3    = wx.Panel(notebook)

    notebook.AddPage(page1, 'page1')
    notebook.AddPage(page2, 'page2')
    notebook.AddPage(page3, 'page3')

    clicked = [None]

    def onbtn(ev):
        clicked[0] = ev.index

    notebook.Bind(nb.EVT_PAGE_CHANGE, onbtn)

    sizer.Add(notebook, flag=wx.EXPAND, proportion=1)
    frame.SetSizer(sizer)
    frame.Layout()
    realYield()

    btn1, btn2, btn3 = notebook.buttons

    notebook.SetSelection(2)

    simclick(sim, btn1)
    assert clicked[0] == 0
    simclick(sim, btn2)
    assert clicked[0] == 1
    simclick(sim, btn3)
    assert clicked[0] == 2
Пример #3
0
def PressKey(window, key):

    window.SetFocus()

    uias = wx.UIActionSimulator()

    uias.Char(key)
Пример #4
0
    def __init__(self, compid, C_component_out, ConnectionAddr):
        CBasicWaiter.__init__(self, compid, C_component_out, None,
                              ConnectionAddr)
        self.User_Simulator = wx.UIActionSimulator()

        self.header_len = 36
        self.event_len = 10
Пример #5
0
def windows_accessibility_fix(browser):
	robot = wx.UIActionSimulator()
	browser.SetFocus()
	position = browser.GetPosition()
	position = browser.ClientToScreen(position)
	robot.MouseMove(position)
	robot.MouseClick()
Пример #6
0
def _test_NumberDialog_create():

    sim   = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()

    testcases = [
        ({'real' : False, 'initial' :    999}, 'ok',        999),
        ({'real' : False, 'initial' :   -999}, 'ok',       -999),
        ({'real' : True,  'initial' : 0.3443}, 'ok',     0.3443),
        ({'real' : True,  'initial' :  -0.48}, 'ok',      -0.48),
        ({'real' : True,  'initial' : 0.3443}, 'cancel',   None),
    ]

    for kwargs, target, expected in testcases:
        dlg = numdlg.NumberDialog(
            frame,
            title='NumberDialog test',
            message='Enter a number',
            **kwargs)

        if target == 'ok': target = dlg.okButton
        else:              target = dlg.cancelButton

        dlg.Show()
        realYield()

        simclick(sim, target)
        assert dlg.GetValue() == expected
Пример #7
0
    def test_unit_int_txt_ctrl(self):

        ctrl = UnitIntegerCtrl(self.panel, value=123456789, unit='m')
        self.add_control(ctrl,
                         label=ctrl.__class__.__name__,
                         flags=wx.EXPAND | wx.ALL)

        self.assertEqual(ctrl.GetValue(), 123456789)
        self.assertEqual(ctrl.get_value_str(), u"123.456789 Mm")

        test.gui_loop(0.1)

        # Create simulator and focus the field
        sim = wx.UIActionSimulator()
        # Focusing the field will select all the number in it, but not the unit (Mm)
        ctrl.SetFocus()
        test.gui_loop(0.1)

        # Set the value to 1 Mm (period should not register)
        for c in "0.001\r":
            sim.Char(ord(c))
            test.gui_loop(0.02)

        self.assertEqual(ctrl.GetValue(), 1000000)
        self.assertEqual(ctrl.get_value_str(), u"1 Mm")

        ctrl.SetSelection(0, 20)

        for c in "44m\r":
            sim.Char(ord(c))
            test.gui_loop(0.02)

        self.assertEqual(ctrl.GetValue(), 44)
        self.assertEqual(ctrl.get_value_str(), u"44 m")
Пример #8
0
    def test_float_txt_ctrl(self):

        ctrl = FloatTextCtrl(self.panel, value=123456789)
        self.add_control(ctrl,
                         label=ctrl.__class__.__name__,
                         flags=wx.EXPAND | wx.ALL)

        test.gui_loop(0.1)
        self.assertEqual(123456789, ctrl.GetValue())

        # Create simulator and focus field
        sim = wx.UIActionSimulator()
        # Focusing the field will select all the text in it
        ctrl.SetFocus()

        # Type '1' followed by an [Enter]
        test.gui_loop(0.1)
        sim.Char(ord('1'))

        self.assertEqual(123456789, ctrl.GetValue())
        sim.Char(ord('\r'))

        # The value should now be 1.0
        test.gui_loop(0.1)
        self.assertEqual(1.0, ctrl.GetValue())
Пример #9
0
    def test_uiactionMouseMotion(self):
        p = MouseEventsPanel(self.frame, wx.EVT_MOTION)
        self.assertTrue(p.Size.Get() > (20, 20))

        uia = wx.UIActionSimulator()
        uia.MouseMove(p.ClientToScreen((1, 1)))
        self.myYield()
        uia.MouseMove(p.ClientToScreen((5, 5)))
        self.myYield()
        uia.MouseMove(
            p.ClientToScreen((10, 10)).x,
            p.ClientToScreen((10, 10)).y)
        self.myYield()
        self.myYield()

        if sys.platform == 'darwin':
            # The events do seem to be happening, but I just can't seem to
            # capture them the same way as in the other tests, so bail out
            # before the asserts to avoid false negatives.
            return

        self.assertEqual(len(p.events), 3)
        self.assertTrue(self.cmp(p.events[0], wx.wxEVT_MOTION, (1, 1)))
        self.assertTrue(self.cmp(p.events[1], wx.wxEVT_MOTION, (5, 5)))
        self.assertTrue(self.cmp(p.events[2], wx.wxEVT_MOTION, (10, 10)))
Пример #10
0
def _test_Event():
    falseicon = wx.Bitmap(op.join(datadir, 'false.png'), wx.BITMAP_TYPE_PNG)
    trueicon = wx.Bitmap(op.join(datadir, 'true.png'), wx.BITMAP_TYPE_PNG)

    sim = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()
    panel = wx.Panel(frame)
    rad = bmpradio.BitmapRadioBox(panel)
    szr = wx.BoxSizer(wx.HORIZONTAL)
    szr.Add(rad, flag=wx.EXPAND)
    panel.SetSizer(szr)

    result = [None]

    def handler(ev):
        result[0] = (ev.index, ev.clientData)

    rad.Bind(bmpradio.EVT_BITMAP_RADIO_EVENT, handler)

    rad.Set([trueicon, falseicon], ['true', 'false'])

    panel.Layout()
    panel.Fit()
    wx.Yield()

    btns = []
    for c in rad.GetChildren():
        if isinstance(c, bmptoggle.BitmapToggleButton):
            btns.append(c)

    simclick(sim, btns[0])
    assert result[0] == (0, 'true')
    simclick(sim, btns[1])
    assert result[0] == (1, 'false')
def _test_popup_no_propagate_enter():

    sim = wx.UIActionSimulator()
    parent = wx.GetApp().GetTopWindow()
    atc = autott.AutoTextCtrl(parent,
                              modal=False,
                              style=autott.ATC_NO_PROPAGATE_ENTER)

    called = [False]

    def atcEnter(ev):
        called[0] = True

    addall(parent, [atc])

    atc.Bind(autott.EVT_ATC_TEXT_ENTER, atcEnter)
    atc.AutoComplete(['aaa', 'aab', 'aba', 'bcc'])

    simtext(sim, atc, 'ab', enter=False)

    simkey(sim, atc.popup.textCtrl, wx.WXK_DOWN)
    simkey(sim, atc.popup.listBox, wx.WXK_RETURN)

    assert atc.GetValue() == 'aba'
    assert not called[0]
Пример #12
0
def _test_TextTagPanel_case_sensitive():
    sim   = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    panel = tt.TextTagPanel(frame, style=(tt.TTP_CASE_SENSITIVE |
                                          tt.TTP_NO_DUPLICATES  |
                                          tt.TTP_ALLOW_NEW_TAGS))

    sizer.Add(panel, flag=wx.EXPAND)
    frame.SetSizer(sizer)
    frame.Layout()

    tags = ['Tag1', 'Tag2', 'Tag3', 'tag3']
    panel.SetOptions(tags)
    assert panel.GetOptions() == tags

    realYield()
    for i in range(len(tags)):
        simtext(sim, panel.newTagCtrl.textCtrl, tags[i])
        assert panel.GetTags() == tags[:i + 1]
        assert panel.HasTag(tags[i])

    panel.RemoveTag(tags[3])
    assert panel.GetTags() == tags[:3]

    panel.SetTagColour(tags[2], ( 50,  50,  50))
    panel.SetTagColour(tags[3], (100, 100, 100))

    assert panel.GetTagColour(tags[2]) == ( 50,  50,  50)
    assert panel.GetTagColour(tags[3]) == (100, 100, 100)
Пример #13
0
def _test_TextTagPanel_close_event():

    sim   = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    panel = tt.TextTagPanel(frame, style=0)
    sizer.Add(panel, flag=wx.EXPAND)
    frame.SetSizer(sizer)
    frame.Layout()

    result = [None]

    def handler(ev):
        result[0] = ev.tag

    panel.Bind(tt.EVT_TTP_TAG_REMOVED, handler)

    panel.AddTag('MyTag1')
    panel.AddTag('MyTag2')
    wx.Yield()

    simclick(sim, panel.tags[1].closeButton, stype=2)
    assert result[0]       == 'MyTag2'
    assert panel.GetTags() == ['MyTag1']

    simclick(sim, panel.tags[0].closeButton, stype=2)
    assert result[0]       == 'MyTag1'
    assert panel.GetTags() == []
Пример #14
0
    def test_uiactionMouseDD(self):
        p = MouseEventsPanel(self.frame,
                             [wx.EVT_MOTION, wx.EVT_LEFT_DOWN, wx.EVT_LEFT_UP])

        x1, y1 = p.ClientToScreen((10, 10))
        x2 = x1 + 20
        y2 = y1 + 20

        uia = wx.UIActionSimulator()
        uia.MouseDragDrop(x1, y1, x2, y2)
        self.myYield()
        self.myYield()

        if sys.platform == 'darwin':
            # The events do seem to be happening, but I just can't seem to
            # capture them the same way as in the other tests, so bail out
            # before the asserts to avoid false negatives.
            return

        #print p.events
        self.assertEqual(len(p.events), 4)
        self.assertTrue(self.cmp(p.events[0], wx.wxEVT_MOTION, (10, 10)))
        self.assertTrue(self.cmp(p.events[1], wx.wxEVT_LEFT_DOWN, (10, 10)))
        self.assertTrue(self.cmp(p.events[2], wx.wxEVT_MOTION, (30, 30)))
        self.assertTrue(self.cmp(p.events[3], wx.wxEVT_LEFT_UP, (30, 30)))
Пример #15
0
def actions(main_window: asn1editor.wxPython.MainWindow):
    def get_children(window: wx.Window):
        my_children = window.GetChildren()
        if my_children is not None:
            their_children = []
            for my_child in my_children:
                their_children += get_children(my_child)
            return list(my_children) + their_children
        else:
            return []

    sleep(1)

    key_codes = [
        wx.WXK_TAB, wx.WXK_DOWN, wx.WXK_UP, wx.WXK_LEFT, wx.WXK_RIGHT,
        wx.WXK_SPACE
    ] + [c for c in range(ord('1'), ord('9'))]

    ui_sim = wx.UIActionSimulator()

    for _ in range(1000):
        main_window.SetFocus()
        key_code = random.choice(key_codes)
        ui_sim.KeyDown(key_code)
        ui_sim.KeyUp(key_code)
    try:
        main_window.save_data_to_file('test.json')
    except asn1tools.ConstraintsError:
        pass

    main_window.Close(True)
    wx.GetApp().ExitMainLoop()
Пример #16
0
def _test_FlirtFileDialog(panel, overlayList, displayCtx):

    sim = wx.UIActionSimulator()

    contents = ['func.nii.gz', 'struct.nii.gz', 'func2struct.mat']

    with MockFileDialog() as mdlg, mockdir(contents):

        dlg = applyflirtxfm.FlirtFileDialog(panel, 'func.nii')
        simclick(sim, dlg.cancel)

        dlg = applyflirtxfm.FlirtFileDialog(panel, 'func.nii')

        dlg.affType.SetSelection(0)
        dlg._FlirtFileDialog__onAffType(None)

        mdlg.GetPath_retval = 'struct.nii.gz'
        dlg._FlirtFileDialog__onRefFileButton(None)

        mdlg.GetPath_retval = 'func2struct.mat'
        dlg._FlirtFileDialog__onMatFileButton(None)

        simclick(sim, dlg.ok)
        assert dlg.GetAffineType() == 'flirt'
        assert dlg.GetMatFile() == op.abspath('func2struct.mat')
        assert dlg.GetRefFile() == op.abspath('struct.nii.gz')
def _test_MaskDialog(frame, overlayList, displayCtx):

    sim = wx.UIActionSimulator()

    dlg = amds.MaskDialog(frame, ['a', 'b', 'c'])
    wx.CallLater(500, simclick, sim, dlg.okButton)
    dlg.ShowModal()
    dlg.Destroy()


    dlg = amds.MaskDialog(frame, ['a', 'b', 'c'])
    wx.CallLater(500, simclick, sim, dlg.cancelButton)
    dlg.ShowModal()
    dlg.Destroy()

    dlg = amds.MaskDialog(frame, ['a', 'b', 'c'])

    # wxgtk2 does not like simulated clicks
    # on wx.Choice objects, so we can't test
    # that
    wx.CallLater(500,  simclick, sim, dlg.checkbox)
    wx.CallLater(1000, simclick, sim, dlg.okButton)

    dlg.ShowModal()
    dlg.GetChoice()
    assert dlg.GetCheckBox()
    dlg.Destroy()
Пример #18
0
    def test_window(self):
        # Note: UIActionSimulator.Text() doesn't seem to work on wxPython 4.0.7,
        # but it works again on wxPython 4.1. It worked on wxPython 4.0.1.
        wx_ver = tuple(int(v) for v in wx.__version__.split("."))
        if wx_ver < (4, 1, 0):
            logging.warning(
                "Test case is known to fail on wxPython 4.0.7 due to buggy UIActionSimulator.Text"
            )

        bugreporter = OdemisBugreporter()
        # Special verison of .run(), which simulates inputs
        bugreporter._compress_files_f = bugreporter._executor.submit(
            bugreporter.compress_files)
        app = wx.App()
        gui = BugreporterFrame(bugreporter)
        bugreporter.gui = gui
        # Create simulator and focus field
        sim = wx.UIActionSimulator()
        self.gui_loop(0.1)

        # Fill up the form
        gui.name_ctrl.SetFocus()
        # TODO: how to simulate typing non ascii-characters? .Char() + modifiers?
        # sim.Text(b"Tstingteam member")
        gui.name_ctrl.SetValue(u"TÉstingteam member")
        self.gui_loop(0.1)

        gui.email_ctrl.SetFocus()
        gui.email_ctrl.SetValue(TEST_SUPPORT_TEAM_EMAIL)
        # sim.Text(TEST_SUPPORT_TEAM_EMAIL) # "@" doesn't work
        self.gui_loop(0.1)

        gui.summary_ctrl.SetFocus()
        sim.Text(b"Bugreporter test")
        self.gui_loop(0.1)

        gui.description_ctrl.SetFocus()
        sim.Text(b"This is a test")
        self.gui_loop(0.1)

        # Simulates a "click" on the button by pressing Enter
        gui.report_btn.SetFocus()
        sim.Char(ord("\r"))
        self.gui_loop(0.1)

        try:
            # If sent successfully, the window should close after a few seconds
            self.gui_loop(2)
            bugreporter._compress_files_f.result()
            self.gui_loop(2)
            self.assertFalse(
                gui
            )  # wxPython widgets which are destroyed are considered "False"
            bugreporter._executor.shutdown(
            )  # wait for the background tasks to complete
        finally:
            # app.MainLoop()  # DEBUG: For leaving the window afterwards
            if gui:
                gui.Destroy()
Пример #19
0
    def Run(self):
        buzzard_script = os.path.join(self.buzzard_path, 'buzzard.py')

        if self._pcbnew_frame is None:
            self._pcbnew_frame = [x for x in wx.GetTopLevelWindows() if 'pcbnew' in x.GetTitle().lower() and not 'python' in x.GetTitle().lower()][0]

        def run_buzzard(str):
            import re

            str = str + ' -o ki -stdout'
            args = [a.strip('"') for a in re.findall('".+?"|\S+', str)]
            if sys.platform.startswith('win'):
                args = [re.sub('([<>])', r'^\1', a) for a in args] # escape '<' or '>' with a caret, '^<'

            # Execute Buzzard
            process = None
            if sys.platform.startswith('linux') or sys.platform == 'darwin':
                process = subprocess.Popen(['python3', buzzard_script] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            else:
                env_without_kicad = os.environ.copy()
                path_without_kicad = env_without_kicad["PATH"].split(';')
                path_without_kicad = [x for x in path_without_kicad if 'KiCad' not in x]
                path_without_kicad = ';'.join(path_without_kicad)
                env_without_kicad["PATH"] = path_without_kicad
                process = subprocess.Popen(['python', buzzard_script] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=env_without_kicad) # Use PATH instead of C:\\Python38\\python.exe
            stdout, stderr = process.communicate()
            if stderr:
                wx.MessageBox(stderr, 'Error', wx.OK | wx.ICON_ERROR)

            # check for errors
            error_line = [s for s in stderr.decode('utf8').split('\n') if 'error' in s]
            if len(error_line) > 0:
                wx.MessageBox(error_line[0], 'Error', wx.OK | wx.ICON_ERROR)

            else:
                # Copy footprint into clipboard
                if sys.platform.startswith('linux'):
                    clip_args = ['xclip', '-sel', 'clip', '-noutf8']
                elif sys.platform == 'darwin':
                    clip_args = ['pbcopy']
                else:
                    clip_args = ['clip.exe']

                process = subprocess.Popen(clip_args, stdin=subprocess.PIPE)
                process.communicate(stdout)

                dlg.EndModal(wx.ID_OK)

        dlg = Dialog(self._pcbnew_frame, self.config, self.buzzard_path, run_buzzard)
        try:
            if dlg.ShowModal() == wx.ID_OK:
                # Set focus to main window and execute a Paste operation
                self._pcbnew_frame.Raise()
                wx.Yield()
                keyinput = wx.UIActionSimulator()
                keyinput.Char(ord("V"), wx.MOD_CONTROL)
        finally:
            self.config.Flush()
            dlg.Destroy()
Пример #20
0
def _test_fillSelection(ortho, overlayList, displayCtx):
    sim = wx.UIActionSimulator()
    img = Image(op.join(datadir, '3d'))
    overlayList.append(img)
    realYield()
    ortho.profile = 'edit'
    realYield(20)

    profile = ortho.getCurrentProfile()
    profile.mode = 'sel'
    profile.drawMode = False
    profile.selectionSize = 1
    profile.fillValue = 999

    xcanvas = ortho.getXCanvas()
    opts = ortho.displayCtx.getOpts(img)

    realYield(20)

    pxs = np.random.randint(0, img.shape[1], 10)
    pys = np.random.randint(0, img.shape[2], 10)

    for i in range(10):
        px, py = pxs[i] + 0.5, pys[i] + 0.5
        pos = opts.transformCoords((8, px, py), 'voxel', 'display')

        px, py = pos[1], pos[2]

        bounds = xcanvas.opts.displayBounds

        xoff = bounds.xlo - opts.bounds.ylo
        yoff = bounds.ylo - opts.bounds.zlo

        px = (px - xoff) / bounds.xlen
        py = (py - yoff) / bounds.ylen

        simclick(sim, xcanvas, pos=(px, 1 - py))
        realYield(10)

    sel = np.array(profile.editor(img).getSelection().getSelection())

    profile.fillSelection()
    realYield(20)

    w, h = xcanvas.GetClientSize().Get()

    voxels = np.zeros((10, 3), dtype=np.int32)
    voxels[:, 0] = 8
    voxels[:, 1] = pxs
    voxels[:, 2] = pys

    xs, ys, zs = voxels.T

    exp = np.zeros(img.shape)
    exp[xs, ys, zs] = 1

    assert np.all(sel == exp)
    assert np.all(img[:][xs, ys, zs] == 999)
Пример #21
0
    def Run(self):
        if self._pcbnew_frame is None:
            try:
                self._pcbnew_frame = [x for x in wx.GetTopLevelWindows() if ('pcbnew' in x.GetTitle().lower() and not 'python' in x.GetTitle().lower()) or ('pcb editor' in x.GetTitle().lower())]
                if len(self._pcbnew_frame) == 1:
                    self._pcbnew_frame = self._pcbnew_frame[0]
                else:
                    self._pcbnew_frame = None
            except:
                pass

        def run_buzzard(dlg, p_buzzard): 

            if len(dlg.polys) == 0:
                dlg.EndModal(wx.ID_CANCEL)
                return

            if '5.1' in self.kicad_build_version or '5.0' in self.kicad_build_version:
                # Handle KiCad 5.1
                filepath = self.filepath

                with open(filepath, 'w+') as f:
                    f.write(p_buzzard.create_v5_footprint())

                print(os.path.dirname(filepath))

                board = pcbnew.GetBoard()
                footprint = pcbnew.FootprintLoad(os.path.dirname(filepath), 'label')

                footprint.SetPosition(pcbnew.wxPoint(0, 0))
                board.Add(footprint)
                pcbnew.Refresh()

                # Zoom doesn't seem to work.
                #b = footprint.GetBoundingBox()
                #pcbnew.WindowZoom(b.GetX(), b.GetY(), b.GetWidth(), b.GetHeight())

            elif '5.99' in self.kicad_build_version or '6.0' in self.kicad_build_version:
                footprint_string = p_buzzard.create_v6_footprint()


                if wx.TheClipboard.Open():
                    wx.TheClipboard.SetData(wx.TextDataObject(footprint_string))
                    wx.TheClipboard.Close()
                    
            dlg.EndModal(wx.ID_OK)

        dlg = Dialog(self._pcbnew_frame, self.config, Buzzard(), run_buzzard)
        try:
            if dlg.ShowModal() == wx.ID_OK:
                
                if '5.99' in self.kicad_build_version:
                    if self._pcbnew_frame is not None:
                        # Set focus to main window and attempt to execute a Paste operation
                        self._pcbnew_frame.Raise()
                        wx.Yield()
                        keyinput = wx.UIActionSimulator()
                        keyinput.Char(ord("V"), wx.MOD_CONTROL)    
Пример #22
0
	def focus(self):
		focus = self.WebPanel.browser
		focus.SetFocus()
		if platform.system() == 'Windows':
			robot = wx.UIActionSimulator()  
			position = focus.GetPosition() 
			position = focus.ClientToScreen(position) 
			robot.MouseMove(position) 
			robot.MouseClick()    
Пример #23
0
    def test_uiactionKeyboardChar(self):
        uia = wx.UIActionSimulator()
        for c in "This is a test":
            mod = wx.MOD_NONE
            if c.isupper():
                mod = wx.MOD_SHIFT
            uia.Char(ord(c), mod)
            self.waitFor(WAIT)
        self.waitFor(WAIT * 2)

        self.assertEqual(self.tc.GetValue(), "This is a test")
Пример #24
0
def test_embed():

    gc.collect()
    idle.idleReset()

    app = wx.App()
    frame = [wx.Frame(None)]
    panel = wx.Panel(frame[0])
    btn = wx.Button(panel)
    btn.SetLabel('Click to open FSLeyes')
    fsizer = wx.BoxSizer(wx.VERTICAL)
    frame[0].SetSizer(fsizer)
    fsizer.Add(panel, flag=wx.EXPAND)

    psizer = wx.BoxSizer(wx.VERTICAL)
    panel.SetSizer(psizer)
    psizer.Add(btn, flag=wx.EXPAND)

    sim = wx.UIActionSimulator()
    ncalls = [0]

    def finish():
        frame[0].Close()
        app.ExitMainLoop()

    def embedded(overlayList, displayCtx, fframe):

        print('Embedded call', ncalls[0])

        img = fslimage.Image(op.join(datadir, '3d'))
        fframe.addOrthoPanel()
        overlayList.append(img)
        fframe.Show()
        ncalls[0] += 1

        wx.CallLater(1500, fframe.Close)
        fframe = None
        if ncalls[0] < 4:
            wx.CallLater(2500, simclick, sim, btn)
        else:
            print('Done - closing')
            wx.CallLater(1500, finish)

    def open_fsleyes(ev):
        fslmain.embed(frame[0], callback=embedded, menu=False, save=False)

    btn.Bind(wx.EVT_BUTTON, open_fsleyes)

    wx.CallLater(1000, simclick, sim, btn)

    frame[0].Show()
    app.MainLoop()

    assert ncalls[0] == 4
Пример #25
0
def runTest(frame, nb, log):
    try:
        uisim = wx.UIActionSimulator()
        win = TestPanel(nb, log)
        return win
    except NotImplementedError:
        from wx.lib.msgpanel import MessagePanel
        win = MessagePanel(
            nb, "This build of wxWidgets does not include the \n"
            "wx.UIActionSimulator implementation.", "Sorry", wx.ICON_WARNING)
        return win
Пример #26
0
    def test_uiactionMouseLeftClick(self):
        p = MouseEventsPanel(self.frame, [wx.EVT_LEFT_DOWN, wx.EVT_LEFT_UP])
        self.myYield()
        
        uia = wx.UIActionSimulator()
        uia.MouseMove(p.ClientToScreen((10,10)));  self.waitFor(WAIT)
        uia.MouseClick();                          self.waitFor(WAIT)
        self.waitFor(WAIT)

        self.assertTrue(len(p.events) == 2)
        self.assertTrue(self.cmp(p.events[0], wx.wxEVT_LEFT_DOWN, (10,10)))
        self.assertTrue(self.cmp(p.events[1], wx.wxEVT_LEFT_UP, (10,10)))
Пример #27
0
def _test_SliderSpinPanel_show_edit_limits():

    sim = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    panel = floatslider.SliderSpinPanel(frame,
                                        style=floatslider.SSP_SHOW_LIMITS
                                        | floatslider.SSP_EDIT_LIMITS)
    sizer.Add(panel, flag=wx.EXPAND)
    frame.SetSizer(sizer)
    frame.Layout()

    panel.SetRange(0, 100)

    result = [None]

    def handler(ev):
        result[0] = (ev.min, ev.max)

    panel.Bind(floatslider.EVT_SSP_LIMIT, handler)

    numberdlg = mock.MagicMock()
    numberdlg.ShowModal.return_value = wx.ID_OK
    numberdlg.GetValue.return_value = 9

    minbtn = panel._SliderSpinPanel__minButton
    maxbtn = panel._SliderSpinPanel__maxButton

    # limbutton, value, expectedrange, shouldTriggerEvent
    testcases = [
        (minbtn, 50, (50, 100), True),
        (minbtn, 150, (50, 100), False),
        (minbtn, -100, (-100, 100), True),
        (maxbtn, 50, (-100, 50), True),
        (maxbtn, -200, (-100, 50), False),
        (maxbtn, 500, (-100, 500), True),
    ]

    with mock.patch('fsleyes_widgets.numberdialog.NumberDialog',
                    return_value=numberdlg):

        for btn, val, expected, shouldEv in testcases:

            result[0] = None

            numberdlg.GetValue.return_value = val

            realYield()
            simclick(sim, btn)
            assert tuple(panel.GetRange()) == expected

            if shouldEv: assert result[0] == expected
            else: assert result[0] is None
Пример #28
0
def _test_RangeSliderSpinPanel_onlimit():

    sim = wx.UIActionSimulator()
    frame = wx.GetApp().GetTopWindow()
    panel = rangeslider.RangeSliderSpinPanel(frame,
                                             style=rangeslider.RSSP_SHOW_LIMITS
                                             | rangeslider.RSSP_EDIT_LIMITS)
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    sizer.Add(panel, flag=wx.EXPAND, proportion=1)
    frame.SetSizer(sizer)
    frame.Layout()

    panel.SetLimits(0, 100)
    panel.SetRange(0, 100)

    called = [False]

    def handler(ev):
        called[0] = True

    panel.Bind(rangeslider.EVT_RANGE_LIMIT, handler)

    numberdlg = mock.MagicMock()
    numberdlg.ShowModal.return_value = wx.ID_OK
    numberdlg.GetValue.return_value = 9

    minbtn = panel.minButton
    maxbtn = panel.maxButton

    # limbutton, value, expectedrange, shouldTriggerEvent
    testcases = [
        (minbtn, 50, (50, 100), True),
        (minbtn, 150, (50, 100), False),
        (minbtn, -100, (-100, 100), True),
        (maxbtn, 50, (-100, 50), True),
        (maxbtn, -200, (-100, 50), False),
        (maxbtn, 500, (-100, 500), True),
    ]

    with mock.patch('fsleyes_widgets.rangeslider.numberdialog.NumberDialog',
                    return_value=numberdlg):

        for btn, val, expected, shouldEv in testcases:

            called[0] = None

            numberdlg.GetValue.return_value = val

            simclick(sim, btn)
            assert tuple(panel.GetLimits()) == expected

            if shouldEv: assert called[0]
            else: assert not called[0]
Пример #29
0
def _test_FloatSpinCtrl_text():
    frame = wx.GetApp().GetTopWindow()
    spin  = floatspin.FloatSpinCtrl(frame)
    sim   = wx.UIActionSimulator()

    spin.SetRange(0, 100)

    result = [0]

    def handler(ev):
        result[0] = ev.value

    enter = [False]

    def enterHandler(ev):
        enter[0] = True

    spin.Bind(floatspin.EVT_FLOATSPIN, handler)
    spin.Bind(wx.EVT_TEXT_ENTER,       enterHandler)

    # input, expected
    testcases = [
        (   '',          0),
        (   '1',         1),
        (   '5',         5),
        ('Baba',         5),
        (   '0',         0),
        (  '20',        20),
        ('-423',         0),
        (  '99',        99),
        ('1055',       100),
        (  '25',        25),
        (  '25.42',  25.42),
    ]

    realYield()

    for text, expected in testcases:

        oldValue  = spin.GetValue()
        result[0] = None
        enter[0]  = False
        simtext(sim, spin.textCtrl, text)
        assert spin.GetValue() == expected

        try:
            float(text)
            assert enter[0]
        except:
            assert not enter[0]

        if oldValue == expected: assert result[0] is None
        else:                    assert result[0] == expected
Пример #30
0
 def test_uiactionKeyboardKeyDownUp(self):
     uia = wx.UIActionSimulator()
     for c in "This is a test":
         if c.isupper():
             uia.KeyDown(wx.WXK_SHIFT);  self.waitFor(WAIT)
         uia.KeyDown(ord(c));            self.waitFor(WAIT)
         uia.KeyUp(ord(c));              self.waitFor(WAIT)
         if c.isupper():
             uia.KeyUp(wx.WXK_SHIFT);    self.waitFor(WAIT)
     self.waitFor(WAIT*2)
             
     self.assertEqual(self.tc.GetValue(), "This is a test")