Пример #1
1
    def test_connect_process(self):
        """Test that connect_() works with a process"""
        app1 = Application()
        app1.start(_notepad_exe())

        app_conn = Application()
        app_conn.connect(process=app1.process)
        self.assertEqual(app1.process, app_conn.process)

        app_conn.UntitledNotepad.MenuSelect('File->Exit')
Пример #2
0
class NotepadRegressionTests(unittest.TestCase):
    "Regression unit tests for Notepad"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        self.app.start(_notepad_exe())

        self.dlg = self.app.Window_(title='Untitled - Notepad', class_name='Notepad')
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)
        self.dlg.edit.SetEditText("Here is some text\r\n and some more")

        self.app2 = Application().start(_notepad_exe())


    def tearDown(self):
        "Close the application after tests"

        # close the application
        try:
            self.dlg.Close(0.5)
            if self.app.Notepad["Do&n't Save"].Exists():
                self.app.Notepad["Do&n't Save"].Click()
                self.app.Notepad["Do&n't Save"].WaitNot('visible')
        except Exception: # TimeoutError:
            pass
        finally:
            self.app.kill_()
        self.app2.kill_()

    def testMenuSelectNotepad_bug(self):
        "In notepad - MenuSelect Edit->Paste did not work"

        text = b'Here are some unicode characters \xef\xfc\r\n'
        self.app2.UntitledNotepad.Edit.Wait('enabled')
        time.sleep(0.3)
        self.app2.UntitledNotepad.Edit.SetEditText(text)
        time.sleep(0.3)
        self.assertEquals(self.app2.UntitledNotepad.Edit.TextBlock().encode(locale.getpreferredencoding()), text)

        Timings.after_menu_wait = .7
        self.app2.UntitledNotepad.MenuSelect("Edit->Select All")
        time.sleep(0.3)
        self.app2.UntitledNotepad.MenuSelect("Edit->Copy")
        time.sleep(0.3)
        self.assertEquals(clipboard.GetData().encode(locale.getpreferredencoding()), text)

        self.dlg.SetFocus()
        self.dlg.MenuSelect("Edit->Select All")
        self.dlg.MenuSelect("Edit->Paste")
        self.dlg.MenuSelect("Edit->Paste")
        self.dlg.MenuSelect("Edit->Paste")

        self.app2.UntitledNotepad.MenuSelect("File->Exit")
        self.app2.Window_(title='Notepad', class_name='#32770')["Don't save"].Click()

        self.assertEquals(self.dlg.Edit.TextBlock().encode(locale.getpreferredencoding()), text*3)
Пример #3
0
class RemoteMemoryBlockTests(unittest.TestCase):
    "Unit tests for RemoteMemoryBlock"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.ctrl = self.dlg.TreeView.WrapperObject()

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testGuardSignatureCorruption(self):
        mem = RemoteMemoryBlock(self.ctrl, 16)
        buf = ctypes.create_string_buffer(24)
        
        self.assertRaises(Exception, mem.Write, buf)
        
        mem.size = 24 # test hack
        self.assertRaises(Exception, mem.Write, buf)
Пример #4
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        app = Application()

        import os.path
        path = os.path.split(__file__)[0]

        test_file = os.path.join(path, "test.txt")

        with codecs.open(test_file, mode="rb", encoding='utf-8') as f:
            self.test_data = f.read()
        # remove the BOM if it exists
        self.test_data = self.test_data.replace(repr("\xef\xbb\xbf"), "")
        #self.test_data = self.test_data.encode('utf-8', 'ignore') # XXX: decode raises UnicodeEncodeError even if 'ignore' is used!
        print('self.test_data:')
        print(self.test_data.encode('utf-8', 'ignore'))

        app.start("Notepad.exe " + test_file, timeout=20)

        self.app = app
        self.dlg = app.UntitledNotepad
        self.ctrl = self.dlg.Edit.WrapperObject()

        self.old_pos = self.dlg.Rectangle

        self.dlg.MoveWindow(10, 10, 400, 400)
Пример #5
0
class NonActiveWindowFocusTests(unittest.TestCase):

    """Regression unit tests for setting focus"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Fast()

        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe"))
        self.app2 = Application().start(_notepad_exe())

    def tearDown(self):
        """Close the application after tests"""
        self.app.kill_()
        self.app2.kill_()

    def test_issue_240(self):
        """Check HwndWrapper.set_focus for a desktop without a focused window"""
        ws = self.app.Common_Controls_Sample
        ws.TabControl.Select('CButton (Command Link)')
        dlg1 = ws.wrapper_object()
        dlg2 = self.app2.Notepad.wrapper_object()
        dlg2.click(coords=(2, 2))
        dlg2.minimize()
        # here is the trick: the window is restored but it isn't activated
        dlg2.restore()
        dlg1.set_focus()
        self.assertEqual(ws.GetFocus(), ws.Edit.wrapper_object())
Пример #6
0
class GetDialogPropsFromHandleTest(unittest.TestCase):

    """Unit tests for mouse actions of the HwndWrapper class"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Fast()

        self.app = Application()
        self.app.start(_notepad_exe())

        self.dlg = self.app.UntitledNotepad
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)

    def tearDown(self):
        """Close the application after tests"""
        # close the application
        #self.dlg.type_keys("%{F4}")
        self.dlg.Close(0.5)
        self.app.kill_()


    def test_GetDialogPropsFromHandle(self):
        """Test some small stuff regarding GetDialogPropsFromHandle"""
        props_from_handle = GetDialogPropsFromHandle(self.dlg.handle)
        props_from_dialog = GetDialogPropsFromHandle(self.dlg)
        #unused var: props_from_ctrl = GetDialogPropsFromHandle(self.ctrl)

        self.assertEquals(props_from_handle, props_from_dialog)
Пример #7
0
class ControlStateTests(unittest.TestCase):

    """Unit tests for control states"""

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.Select(4)
        self.ctrl = self.dlg.EditBox.WrapperObject()

    def tearDown(self):
        """Close the application after tests"""
        self.app.kill_()

    def test_VerifyEnabled(self):
        """test for verify_enabled"""
        self.assertRaises(ElementNotEnabled, self.ctrl.verify_enabled)

    def test_VerifyVisible(self):
        """test for verify_visible"""
        self.dlg.TabControl.Select(3)
        self.assertRaises(ElementNotVisible, self.ctrl.verify_visible)
Пример #8
0
    def test_window(self):
        """Test that window_() works correctly"""
        app = Application()

        self.assertRaises(AppNotConnected, app.window_, **{'title' : 'not connected'})

        app.start(_notepad_exe())

        self.assertRaises(ValueError, app.windows_, **{'backend' : 'uia'})

        title = app.window_(title = "Untitled - Notepad")
        title_re = app.window_(title_re = "Untitled[ -]+Notepad")
        classname = app.window_(class_name = "Notepad")
        classname_re = app.window_(class_name_re = "Not..ad")
        handle = app.window_(handle = title.handle)
        bestmatch = app.window_(best_match = "Untiotled Notepad")

        self.assertNotEqual(title.handle, None)
        self.assertNotEqual(title.handle, 0)

        self.assertEqual(title.handle, title_re.handle)
        self.assertEqual(title.handle, classname.handle)
        self.assertEqual(title.handle, classname_re.handle)
        self.assertEqual(title.handle, handle.handle)
        self.assertEqual(title.handle, bestmatch.handle)

        app.UntitledNotepad.MenuSelect("File->Exit")
Пример #9
0
    def testGetitem(self):
        "Test that __getitem__() works correctly"
        app = Application()
        app.start(_notepad_exe())

        try:
            app['blahblah']
        except Exception:
            pass


        #prev_timeout = application.window_find_timeout
        #application.window_find_timeout = .1
        self.assertRaises(
            findbestmatch.MatchError,
            app['blahblah']['not here'].__getitem__, 'handle')

        self.assertEqual(
            app[u'Unt\xeftledNotepad'].handle,
            app.window_(title = "Untitled - Notepad").handle)

        app.UntitledNotepad.MenuSelect("Help->About Notepad")

        self.assertEqual(
            app['AboutNotepad'].handle,
            app.window_(title = "About Notepad").handle)

        app.AboutNotepad.Ok.Click()
        app.UntitledNotepad.MenuSelect("File->Exit")
Пример #10
0
    def test_getattribute(self):
        """Test that __getattribute__() works correctly"""
        app = Application()
        app.start(_notepad_exe())

        self.assertRaises(
            findbestmatch.MatchError,
            app.blahblah.__getattribute__, 'handle')

        self.assertEqual(
            app.UntitledNotepad.handle,
            app.window_(title = "Untitled - Notepad").handle)

        app.UntitledNotepad.MenuSelect("Help->About Notepad")

        # I think it's OK that this no longer raises a matcherror
        # just because the window is not enabled - doesn't mean you
        # should not be able to access it at all!
        #self.assertRaises(findbestmatch.MatchError,
        #    app.Notepad.__getattribute__, 'handle')

        self.assertEqual(
            app.AboutNotepad.handle,
            app.window_(title = "About Notepad").handle)

        app.AboutNotepad.Ok.Click()
        app.UntitledNotepad.MenuSelect("File->Exit")
Пример #11
0
class GetDialogPropsFromHandleTest(unittest.TestCase):
    "Unit tests for mouse actions of the HwndWrapper class"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        if is_x64_Python() or not is_x64_OS():
            self.app.start(r"C:\Windows\System32\notepad.exe")
        else:
            self.app.start(r"C:\Windows\SysWOW64\notepad.exe")

        self.dlg = self.app.UntitledNotepad
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)

    def tearDown(self):
        "Close the application after tests"
        # close the application
        #self.dlg.TypeKeys("%{F4}")
        self.dlg.Close(0.5)
        self.app.kill_()


    def test_GetDialogPropsFromHandle(self):
        "Test some small stuff regarding GetDialogPropsFromHandle"

        props_from_handle = GetDialogPropsFromHandle(self.dlg.handle)

        props_from_dialog = GetDialogPropsFromHandle(self.dlg)

        #unused var: props_from_ctrl = GetDialogPropsFromHandle(self.ctrl)

        self.assertEquals(props_from_handle, props_from_dialog)
Пример #12
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        self.app1 = Application.start("notepad.exe")
        self.app2 = Application.start("notepad.exe")

        self.app1.UntitledNotepad.MoveWindow(RECT(0, 0, 200, 200))
        self.app2.UntitledNotepad.MoveWindow(RECT(0, 200, 200, 400))
Пример #13
0
 def test_cpu_usage(self):
     """Verify that cpu_usage() works correctly"""
     app = Application()
     self.assertRaises(AppNotConnected, app.cpu_usage)
     app.start(_notepad_exe())
     self.assertEquals(0.0 <= app.cpu_usage() <= 100.0, True)
     app.UntitledNotepad.MenuSelect("File->Exit")
     app.UntitledNotepad.WaitNot('exists')
Пример #14
0
 def setUp(self):
     """Start the application set some data and ensure the application
     is in the state we want it."""
     app = Application()
     app.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe"))
     self.app = app
     self.dlg = app.TrayMenu  # top_window_()
     self.dlg.Wait('ready')
Пример #15
0
 def setUp(self):
     """Start the application set some data and ensure the application
     is in the state we want it."""
     backend.activate("native")
     self.tm = _ready_timeout
     app = Application()
     app.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe"), wait_for_idle = False)
     self.app = app
     self.dlg = app.top_window_()
     self.dlg.Wait('ready', timeout=self.tm)
Пример #16
0
 def testStart_bug01(self):
     """On SourceForge forum AppStartError forgot to include %s for application name"""
     app = Application()
     self.assertEqual(app.process, None)
     application.app_start_timeout = 1
     app_name = r"I am not * and Application!/\.exe"
     try:
         app.start(app_name)
     except AppStartError as e:
         self.assertEquals(app_name in str(e), True)
Пример #17
0
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Defaults()

        self.tm = _ready_timeout
        app = Application(backend='win32')
        app.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe"), wait_for_idle = False)
        self.app = app
        self.dlg = app.top_window()
        self.dlg.Wait('ready', timeout=self.tm)
Пример #18
0
class CheckBoxTests(unittest.TestCase):
    "Unit tests for the CheckBox specific methods of the ButtonWrapper class"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.tree = self.dlg.TreeView.WrapperObject()

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testCheckUncheckByClick(self):
        "test for CheckByClick and UncheckByClick"
        self.dlg.TVS_HASLINES.CheckByClick()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_CHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), True)
        
        self.dlg.TVS_HASLINES.CheckByClick() # make sure it doesn't uncheck the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_CHECKED)
        
        self.dlg.TVS_HASLINES.UncheckByClick()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_UNCHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), False)
        
        self.dlg.TVS_HASLINES.UncheckByClick() # make sure it doesn't check the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_UNCHECKED)

    def testCheckUncheckByClickInput(self):
        "test for CheckByClickInput and UncheckByClickInput"
        self.dlg.TVS_HASLINES.CheckByClickInput()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_CHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), True)
        
        self.dlg.TVS_HASLINES.CheckByClickInput() # make sure it doesn't uncheck the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_CHECKED)
        
        self.dlg.TVS_HASLINES.UncheckByClickInput()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_UNCHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), False)
        
        self.dlg.TVS_HASLINES.UncheckByClickInput() # make sure it doesn't check the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_UNCHECKED)

    def testSetCheckIndeterminate(self):
        "test for SetCheckIndeterminate"
        self.dlg.TVS_HASLINES.SetCheckIndeterminate()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(), win32defines.BST_CHECKED)
Пример #19
0
    def test_connect_handle(self):
        """Test that connect_() works with a handle"""
        app1 = Application()
        app1.start(_notepad_exe())
        handle = app1.UntitledNotepad.handle

        app_conn = Application()
        app_conn.connect(handle=handle)
        self.assertEqual(app1.process, app_conn.process)

        app_conn.UntitledNotepad.MenuSelect('File->Exit')
Пример #20
0
 def test_active_window(self):
     """Test that active_() works correctly"""
     app = Application()
     self.assertRaises(AppNotConnected, app.active_)
     self.assertRaises(AppNotConnected, app.is64bit)
     app.start(_notepad_exe())
     app.UntitledNotepad.Wait('ready')
     self.assertEqual(app.active_().handle, app.UntitledNotepad.handle)
     app.UntitledNotepad.MenuSelect("File->Exit")
     app.UntitledNotepad.WaitNot('exists')
     self.assertRaises(RuntimeError, app.active_)
Пример #21
0
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.defaults()

        self.tm = _ready_timeout
        app = Application(backend='win32')
        app.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe"), wait_for_idle=False)
        self.app = app
        self.dlg = app.top_window()
        mouse.move((-500, 200))  # remove the mouse from the screen to avoid side effects
        self.dlg.wait('ready', timeout=self.tm)
Пример #22
0
    def test_start(self):
        """test start() works correctly"""
        app = Application()
        self.assertEqual(app.process, None)
        app.start(_notepad_exe())
        self.assertNotEqual(app.process, None)

        self.assertEqual(app.UntitledNotepad.process_id(), app.process)

        notepadpath = os.path.join(os.environ['systemroot'], self.notepad_subpath)
        self.assertEqual(str(process_module(app.process)).lower(), str(notepadpath).lower())

        app.UntitledNotepad.MenuSelect("File->Exit")
Пример #23
0
    def test_kill_(self):
        """test killing the application"""
        app = Application()
        app.start(_notepad_exe())

        app.UntitledNotepad.Edit.type_keys("hello")

        app.UntitledNotepad.MenuSelect("File->Print...")

        #app.Print.FindPrinter.Click() # Vasily: (Win7 x64) "Find Printer" dialog is from splwow64.exe process
        #app.FindPrinters.Stop.Click()

        app.kill_()

        self.assertRaises(AttributeError, app.UntitledNotepad.Edit)
Пример #24
0
def _toggle_notification_area_icons(show_all=True, debug_img=None):
    """
    A helper function to change 'Show All Icons' settings.
    On a succesful execution the function returns an original
    state of 'Show All Icons' checkbox.

    The helper works only for an "English" version of Windows,
    on non-english versions of Windows the 'Notification Area Icons'
    window should be accessed with a localized title"
    """

    app = Application()
    starter = app.start(r'explorer.exe')
    class_name = 'CabinetWClass'

    def _cabinetwclass_exist():
        "Verify if at least one active 'CabinetWClass' window is created"
        l = findwindows.find_windows(active_only=True, class_name=class_name)
        return (len(l) > 0)

    WaitUntil(30, 0.5, _cabinetwclass_exist)
    handle = findwindows.find_windows(active_only=True,
                                      class_name=class_name)[-1]
    window = WindowSpecification({'handle': handle, })
    explorer = Application().Connect(process=window.ProcessID())
    cur_state = None

    try:
        # Go to "Control Panel -> Notification Area Icons"
        window.AddressBandRoot.ClickInput()
        window.TypeKeys(
                    r'control /name Microsoft.NotificationAreaIcons{ENTER}',
                    with_spaces=True,
                    set_foreground=False)
        explorer.WaitCPUUsageLower(threshold=5, timeout=40)

        # Get the new opened applet
        notif_area = explorer.Window_(title="Notification Area Icons",
                                      class_name=class_name)
        cur_state = notif_area.CheckBox.GetCheckState()

        # toggle the checkbox if it differs and close the applet
        if bool(cur_state) != show_all:
            notif_area.CheckBox.ClickInput()
        notif_area.Ok.ClickInput()
        explorer.WaitCPUUsageLower(threshold=5, timeout=40)

    except Exception as e:
        if debug_img:
            from PIL import ImageGrab
            ImageGrab.grab().save("%s.jpg" % (debug_img), "JPEG")
        l = pywinauto.actionlogger.ActionLogger()
        l.log("RuntimeError in _toggle_notification_area_icons")
        raise e

    finally:
        # close the explorer window
        window.Close()

    return cur_state
Пример #25
0
    def testkill_(self):
        "test killing the application"

        app = Application()
        app.start(_notepad_exe())

        app.UntitledNotepad.Edit.TypeKeys("hello")

        app.UntitledNotepad.MenuSelect("File->Print...")

        #app.Print.FindPrinter.Click() # vvryabov: (Win7 x64) "Find Printers" dialog is from splwow64.exe process
        #app.FindPrinters.Stop.Click() #           so cannot handle it in 32-bit Python

        app.kill_()

        self.assertRaises(AttributeError, app.UntitledNotepad.Edit)
Пример #26
0
    def test_top_window(self):
        """Test that top_window_() works correctly"""
        app = Application()
        self.assertRaises(AppNotConnected, app.top_window_)
        
        app.start(_notepad_exe())

        self.assertEqual(app.UntitledNotepad.handle, app.top_window_().handle)

        app.UntitledNotepad.MenuSelect("Help->About Notepad")

        self.assertEqual(app.AboutNotepad.handle, app.top_window_().handle)

        app.AboutNotepad.Ok.Click()
        app.UntitledNotepad.MenuSelect("File->Exit")
        app.UntitledNotepad.WaitNot('exists')
        self.assertRaises(RuntimeError, app.top_window_)
 def setUp(self):
     """Start the application set some data and ensure the application
     is in the state we want it."""
     actionlogger.enable()
     self.app = Application.start(_notepad_exe())
     self.logger = logging.getLogger('pywinauto')
     self.out = self.logger.parent.handlers[0].stream
     self.logger.parent.handlers[0].stream = open('test_logging.txt', 'w')
Пример #28
0
    def testConnect_path(self):
        "Test that connect_() works with a path"
        app1 = Application()
        app1.start(_notepad_exe())

        app_conn = Application()
        app_conn.connect(path=self.notepad_subpath)
        self.assertEqual(app1.process, app_conn.process)

        app_conn = Application()
        if is_x64_Python() or not is_x64_OS():
            app_conn.connect(path=r"c:\windows\system32\notepad.exe")
        else:
            app_conn.connect(path=r"c:\windows\syswow64\notepad.exe")
        self.assertEqual(app1.process, app_conn.process)

        app_conn.UntitledNotepad.MenuSelect('File->Exit')
Пример #29
0
    def testClickCustomizeButton(self):
        "Test click on the 'show hidden icons' button"

        # Minimize to tray
        self.dlg.minimize()
        _wait_minimized(self.dlg)

        # Make sure that the hidden icons area is enabled
        orig_hid_state = _toggle_notification_area_icons(
            show_all=False,
            debug_img="%s_01" % (self.id())
        )

        # Run one more instance of the sample app
        # hopefully one of the icons moves into the hidden area
        app2 = Application()
        app2.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe"))
        dlg2 = app2.top_window()
        dlg2.wait('visible', timeout=self.tm)
        dlg2.minimize()
        _wait_minimized(dlg2)

        # Test click on "Show Hidden Icons" button
        taskbar.ShowHiddenIconsButton.click_input()
        niow_dlg = taskbar.explorer_app.window(class_name='NotifyIconOverflowWindow')
        niow_dlg.OverflowNotificationAreaToolbar.wait('ready', timeout=self.tm)
        niow_dlg.SysLink.click_input()

        nai = Desktop().window(
            title="Notification Area Icons",
            class_name="CabinetWClass"
        )
        nai.wait('ready')
        origAlwaysShow = nai.CheckBox.get_check_state()
        if not origAlwaysShow:
            nai.CheckBox.click_input()
        nai.OK.click()

        # Restore Notification Area settings
        _toggle_notification_area_icons(show_all=orig_hid_state,
                                        debug_img="%s_02" % (self.id()))

        # close the second sample app
        dlg2.send_message(win32defines.WM_CLOSE)
Пример #30
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        self.app = Application.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))

        self.dlg = self.app.CommonControlsSample #top_window_()
        self.ctrl = self.app.CommonControlsSample.TreeView.WrapperObject()
Пример #31
0
class Windows(Device):
    """Windows client."""
    def __init__(self, handle=None, dpifactor=1, **kwargs):
        super(Windows, self).__init__()
        self.app = None
        self.handle = int(handle) if handle else None
        # windows high dpi scale factor, no exact way to auto detect this value for a window
        # reference: https://msdn.microsoft.com/en-us/library/windows/desktop/mt843498(v=vs.85).aspx
        self._dpifactor = float(dpifactor)
        self._app = Application()
        self._top_window = None
        self._focus_rect = (0, 0, 0, 0)
        self.mouse = mouse
        self.keyboard = keyboard
        self._init_connect(handle, kwargs)

        self.screen = mss()
        self.monitor = self.screen.monitors[0]  # 双屏的时候,self.monitor为整个双屏
        self.main_monitor = self.screen.monitors[
            1]  # 双屏的时候,self.main_monitor为主屏

    @property
    def uuid(self):
        return self.handle

    def _init_connect(self, handle, kwargs):
        if handle:
            self.connect(handle=handle)
        elif kwargs:
            self.connect(**kwargs)

    def connect(self, handle=None, **kwargs):
        """
        Connect to window and set it foreground

        Args:
            **kwargs: optional arguments

        Returns:
            None

        """
        if handle:
            handle = int(handle)
            self.app = self._app.connect(handle=handle)
            self._top_window = self.app.window(handle=handle).wrapper_object()
        else:
            for k in ["process", "timeout"]:
                if k in kwargs:
                    kwargs[k] = int(kwargs[k])
            self.app = self._app.connect(**kwargs)
            self._top_window = self.app.top_window().wrapper_object()
        self.set_foreground()

    def shell(self, cmd):
        """
        Run shell command in subprocess

        Args:
            cmd: command to be run

        Raises:
            subprocess.CalledProcessError: when command returns non-zero exit status

        Returns:
            command output as a byte string

        """
        return subprocess.check_output(cmd, shell=True)

    def snapshot(self, filename=None, quality=10, max_size=None):
        """
        Take a screenshot and save it in ST.LOG_DIR folder

        Args:
            filename: name of the file to give to the screenshot, {time}.jpg by default
            quality: The image quality, integer in range [1, 99]
            max_size: the maximum size of the picture, e.g 1200

        Returns:
            display the screenshot

        """
        if self.handle:
            screen = screenshot(filename, self.handle)
        else:
            screen = screenshot(filename)
            if self.app:
                rect = self.get_rect()
                rect = self._fix_image_rect(rect)
                screen = aircv.crop_image(
                    screen, [rect.left, rect.top, rect.right, rect.bottom])
        if not screen.any():
            if self.app:
                rect = self.get_rect()
                rect = self._fix_image_rect(rect)
                screen = aircv.crop_image(
                    screenshot(filename),
                    [rect.left, rect.top, rect.right, rect.bottom])
        if self._focus_rect != (0, 0, 0, 0):
            height, width = screen.shape[:2]
            rect = (self._focus_rect[0], self._focus_rect[1],
                    width + self._focus_rect[2], height + self._focus_rect[3])
            screen = aircv.crop_image(screen, rect)
        if filename:
            aircv.imwrite(filename, screen, quality, max_size=max_size)
        return screen

    def _fix_image_rect(self, rect):
        """Fix rect in image."""
        # 将rect 转换为左上角为(0,0), 与图片坐标对齐
        rect.left = rect.left - self.monitor["left"]
        rect.right = rect.right - self.monitor["left"]
        rect.top = rect.top - self.monitor["top"]
        rect.bottom = rect.bottom - self.monitor["top"]
        return rect

    def keyevent(self, keyname, **kwargs):
        """
        Perform a key event

        References:
            https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html

        Args:
            keyname: key event
            **kwargs: optional arguments

        Returns:
            None

        """
        self.keyboard.SendKeys(keyname)

    def text(self, text, **kwargs):
        """
        Input text

        Args:
            text: text to input
            **kwargs: optional arguments

        Returns:
            None

        """
        self.keyevent(text)

    def _fix_op_pos(self, pos):
        """Fix operation position."""
        # 如果是全屏的话,就进行双屏修正,否则就正常即可
        if not self.handle:
            pos = list(pos)
            pos[0] = pos[0] + self.monitor["left"]
            pos[1] = pos[1] + self.monitor["top"]

        return pos

    def key_press(self, key):
        """Simulates a key press event.

        Sends a scancode to the computer to report which key has been pressed.
        Some games use DirectInput devices, and respond only to scancodes, not
        virtual key codes. You can simulate DirectInput key presses using this
        method, instead of the keyevent() method, which uses virtual key
        codes.

        :param key: A string indicating which key to be pressed.
                    Available key options are:
                    {'ESCAPE', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    '0', '-', '=', 'BACKSPACE', 'TAB', 'Q', 'W', 'E', 'R', 'T',
                    'Y', 'U', 'I', 'O', 'P', '[', ']', 'ENTER', 'LCTRL', 'A',
                    'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", '`',
                    'LSHIFT', 'BACKSLASH', 'Z', 'X', 'C', 'V', 'B', 'N', 'M',
                    ',', '.', '/', 'RSHIFT', '*', 'LALT', 'SPACE', 'CAPS_LOCK',
                    'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
                    'F10', 'NUM_LOCK', 'SCROLL_LOCK', 'NUMPAD_7', 'NUMPAD_8',
                    'NUMPAD_9', 'NUMPAD_-', 'NUMPAD_4', 'NUMPAD_5', 'NUMPAD_6',
                    'NUMPAD_+', 'NUMPAD_1', 'NUMPAD_2', 'NUMPAD_3', 'NUMPAD_0',
                    'NUMPAD_.', 'F11', 'F12', 'PRINT_SCREEN', 'PAUSE',
                    'NUMPAD_ENTER', 'RCTRL', 'NUMPAD_/', 'RALT', 'HOME', 'UP',
                    'PAGE_UP', 'LEFT', 'RIGHT', 'END', 'DOWN', 'PAGE_DOWN',
                    'INSERT', 'DELETE', 'LWINDOWS', 'RWINDOWS', 'MENU'}.
        """
        key_press(key)

    def key_release(self, key):
        """Simulates a key release event.

        Sends a scancode to the computer to report which key has been released.
        Some games use DirectInput devices, and respond only to scancodes, not
        virtual key codes. You can simulate DirectInput key releases using this
        method. A call to the key_release() method usually follows a call to
        the key_press() method of the same key.

        :param key: A string indicating which key to be released.
        """
        key_release(key)

    def touch(self, pos, **kwargs):
        """
        Perform mouse click action

        References:
            https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html

        Args:
            pos: coordinates where to click
            **kwargs: optional arguments

        Returns:
            None

        """
        duration = kwargs.get("duration", 0.01)
        right_click = kwargs.get("right_click", False)
        button = "right" if right_click else "left"
        steps = kwargs.get("steps", 1)
        offset = kwargs.get("offset", 0)

        start = self._action_pos(win32api.GetCursorPos())
        end = self._action_pos(pos)
        start_x, start_y = self._fix_op_pos(start)
        end_x, end_y = self._fix_op_pos(end)

        interval = float(duration) / steps
        time.sleep(interval)

        for i in range(1, steps):
            x = int(start_x + (end_x - start_x) * i / steps)
            y = int(start_y + (end_y - start_y) * i / steps)
            self.mouse.move(coords=(x, y))
            time.sleep(interval)

        self.mouse.move(coords=(end_x, end_y))

        for i in range(1, offset + 1):
            self.mouse.move(coords=(end_x + i, end_y + i))
            time.sleep(0.01)

        for i in range(offset):
            self.mouse.move(coords=(end_x + offset - i, end_y + offset - i))
            time.sleep(0.01)

        self.mouse.press(button=button, coords=(end_x, end_y))
        time.sleep(duration)
        self.mouse.release(button=button, coords=(end_x, end_y))

    def double_click(self, pos):
        pos = self._fix_op_pos(pos)
        coords = self._action_pos(pos)
        self.mouse.double_click(coords=coords)

    def swipe(self, p1, p2, duration=0.8, steps=5):
        """
        Perform swipe (mouse press and mouse release)

        Args:
            p1: start point
            p2: end point
            duration: time interval to perform the swipe action
            steps: size of the swipe step

        Returns:
            None

        """
        # 设置坐标时相对于整个屏幕的坐标:
        x1, y1 = self._fix_op_pos(p1)
        x2, y2 = self._fix_op_pos(p2)

        from_x, from_y = self._action_pos(p1)
        to_x, to_y = self._action_pos(p2)

        interval = float(duration) / (steps + 1)
        self.mouse.press(coords=(from_x, from_y))
        time.sleep(interval)
        for i in range(1, steps):
            self.mouse.move(coords=(
                int(from_x + (to_x - from_x) * i / steps),
                int(from_y + (to_y - from_y) * i / steps),
            ))
            time.sleep(interval)
        for i in range(10):
            self.mouse.move(coords=(to_x, to_y))
        time.sleep(interval)
        self.mouse.release(coords=(to_x, to_y))

    def mouse_move(self, pos):
        """Simulates a `mousemove` event.

        Known bug:
            Due to a bug in the pywinauto module, users might experience \
            off-by-one errors when it comes to the exact coordinates of \
            the position on screen.

        :param pos: A tuple (x, y), where x and y are x and y coordinates of
                    the screen to move the mouse to, respectively.
        """
        if not isinstance(pos, tuple) or len(pos) != 2:  # pos is not a 2-tuple
            raise ValueError('invalid literal for mouse_move: {}'.format(pos))
        try:
            self.mouse.move(coords=self._action_pos(pos))
        except ValueError:  # in case where x, y are not numbers
            raise ValueError('invalid literal for mouse_move: {}'.format(pos))

    def mouse_down(self, button='left'):
        """Simulates a `mousedown` event.

        :param button: A string indicating which mouse button to be pressed.
                       Available mouse button options are:
                       {'left', 'middle', 'right'}.
        """
        buttons = {'left', 'middle', 'right'}
        if not isinstance(button, str) or button not in buttons:
            raise ValueError(
                'invalid literal for mouse_down(): {}'.format(button))
        else:
            coords = self._action_pos(win32api.GetCursorPos())
            self.mouse.press(button=button, coords=coords)

    def mouse_up(self, button='left'):
        """Simulates a `mouseup` event.

        A call to the mouse_up() method usually follows a call to the
        mouse_down() method of the same mouse button.

        :param button: A string indicating which mouse button to be released.
        """
        buttons = {'left', 'middle', 'right'}
        if not isinstance(button, str) or button not in buttons:
            raise ValueError(
                'invalid literal for mouse_up(): {}'.format(button))
        else:
            coords = self._action_pos(win32api.GetCursorPos())
            self.mouse.release(button=button, coords=coords)

    def start_app(self, path, **kwargs):
        """
        Start the application

        Args:
            path: full path to the application
            kwargs: reference: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.application.html#pywinauto.application.Application.start

        Returns:
            None

        """
        self.app = self._app.start(path, **kwargs)

    def stop_app(self, pid):
        """
        Stop the application

        Args:
            pid: process ID of the application to be stopped

        Returns:
            None

        """
        self._app.connect(process=pid).kill()

    @require_app
    def set_foreground(self):
        """
        Bring the window foreground

        Returns:
            None

        """
        SetForegroundWindow(self._top_window)

    def get_rect(self):
        """
        Get rectangle

        Returns:
            win32structures.RECT

        """
        if self.app and self._top_window:
            return self._top_window.rectangle()
        else:
            return RECT(right=GetSystemMetrics(0), bottom=GetSystemMetrics(1))

    @require_app
    def get_title(self):
        """
        Get the window title

        Returns:
            window title

        """
        return self._top_window.texts()

    @require_app
    def get_pos(self):
        """
        Get the window position coordinates

        Returns:
            coordinates of topleft corner of the window (left, top)

        """
        rect = self.get_rect()
        return (rect.left, rect.top)

    @require_app
    def move(self, pos):
        """
        Move window to given coordinates

        Args:
            pos: coordinates (x, y) where to move the window

        Returns:
            None

        """
        self._top_window.MoveWindow(x=pos[0], y=pos[1])

    @require_app
    def kill(self):
        """
        Kill the application

        Returns:
            None

        """
        self.app.kill()

    def _action_pos(self, pos):
        if self.app:
            pos = self._windowpos_to_screenpos(pos)
        pos = (int(pos[0]), int(pos[1]))
        return pos

    # @property
    # def handle(self):
    #     return self._top_window.handle

    @property
    def focus_rect(self):
        return self._focus_rect

    @focus_rect.setter
    def focus_rect(self, value):
        # set focus rect to get rid of window border
        assert len(
            value) == 4, "focus rect must be in [left, top, right, bottom]"
        self._focus_rect = value

    def get_current_resolution(self):
        rect = self.get_rect()
        w = (rect.right + self._focus_rect[2]) - (rect.left +
                                                  self._focus_rect[0])
        h = (rect.bottom + self._focus_rect[3]) - (rect.top +
                                                   self._focus_rect[1])
        return w, h

    def _windowpos_to_screenpos(self, pos):
        """
        Convert given position relative to window topleft corner to screen coordinates

        Args:
            pos: coordinates (x, y)

        Returns:
            converted position coordinates

        """
        rect = self.get_rect()
        pos = (int(
            (pos[0] + rect.left + self._focus_rect[0]) * self._dpifactor),
               int((pos[1] + rect.top + self._focus_rect[1]) *
                   self._dpifactor))
        return pos

    def get_ip_address(self):
        """
        Return default external ip address of the windows os.

        Returns:
             :py:obj:`str`: ip address
        """
        hostname = socket.getfqdn()
        return socket.gethostbyname_ex(hostname)[2][0]
Пример #32
0
    def test_connect_to_my_account_from_several_ads_from_all_result_page(self):
        print("test_connect_to_my_account_from_several_ads_from_all_result_page")

        i = 1

        # 55
        for x in range(3, 4):
            print("result page : " + str(x))

            url_result_page = "https://www.freelance-info.fr/missions?remote=1&page=" + str(x)

            # Request the content of a page from the url
            html = requests.get(url_result_page)

            time.sleep(3)

            # Parse the content of html_doc
            soup = BeautifulSoup(html.content, 'html.parser')

            if soup.select("#offre") is not None:
                print("offres ok")

                all_offre = soup.select("#offre")

                for offre in all_offre:
                    print("link " + str(i) + " : https://www.freelance-info.fr"
                          + offre.select_one("#titre-mission").find('a').get('href'))

                    app = Application(backend="uia")

                    url_ad = "https://www.freelance-info.fr" + str(offre
                                                                   .select_one("#titre-mission")
                                                                   .find('a')
                                                                   .get('href'))

                    # Ouvrir l'application CCleaner
                    app.start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

                    time.sleep(6)

                    # Open the Freelance-info.fr
                    pywinauto.keyboard.send_keys(url_ad)

                    time.sleep(3)

                    # Press the 'Enter' button
                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(6)

                    pywinauto.mouse.click(button="left", coords=(500, 670))

                    time.sleep(3)

                    pywinauto.keyboard.send_keys("{VK_TAB}")

                    time.sleep(3)

                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(3)

                    pywinauto.mouse.click(button="left", coords=(600, 450))

                    time.sleep(3)

                    # Type the email
                    pywinauto.keyboard.send_keys('')

                    time.sleep(3)

                    pywinauto.keyboard.send_keys("{VK_TAB}")

                    time.sleep(3)

                    # Type the password
                    pywinauto.keyboard.send_keys('')

                    time.sleep(3)

                    pywinauto.keyboard.send_keys("{VK_TAB}")

                    time.sleep(3)

                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(7)

                    pywinauto.mouse.click(button="left", coords=(500, 670))

                    time.sleep(3)

                    pywinauto.keyboard.send_keys("{VK_TAB}")

                    time.sleep(3)

                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(3)

                    pywinauto.mouse.click(button="left", coords=(1170, 85))

                    time.sleep(5)

                    # Close the browser
                    pywinauto.keyboard.send_keys('%{F4}')

                    time.sleep(5)

                    i += 1
            else:
                print("no offres")
Пример #33
0
class SendKeysTests(unittest.TestCase):
    "Unit tests for the Sendkeys module"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        self.app = Application()
        self.app.start(_notepad_exe())

        self.dlg = self.app.UntitledNotepad
        self.ctrl = self.dlg.Edit

    def tearDown(self):
        "Close the application after tests"
        try:
            self.dlg.Close(0.1)
        except Exception:  # TimeoutError:
            pass
        try:
            if self.app.Notepad["Do&n't Save"].Exists():
                self.app.Notepad["Do&n't Save"].Click()
                self.app.Notepad["Do&n't Save"].WaitNot('visible')
        except Exception:  # TimeoutError:
            pass
        finally:
            if self.dlg.Exists(timeout=0.1):
                self.app.kill_()

    def __run_NormalCharacters_with_options(self, **args):
        "Make sure that sending any character in range "

        #unused var: missed = []
        for i in range(32, 127):

            # skip characters that must be escaped
            if chr(i) in (' ', '%', '^', '+', '(', ')', '{', '}', '~'):
                continue

            SendKeys(chr(i), pause=.001, **args)
            received = self.ctrl.TextBlock()[-1]

            self.assertEquals(i, ord(received))

    # Space tests
    def testNormalWithSpaces(self):
        "Make sure that with spaces option works"
        self.__run_NormalCharacters_with_options(with_spaces=True)

    def testNormalWithoutSpaces(self):
        "Make sure that with spaces option works"
        self.__run_NormalCharacters_with_options(with_spaces=False)

    def testSpaceWithSpaces(self):
        "Make sure that with spaces option works"
        SendKeys(" \t \t ", pause=.001, with_spaces=True)
        received = self.ctrl.TextBlock()
        self.assertEquals("   ", received)

    def testSpaceWithoutSpaces(self):
        "Make sure that with spaces option works"
        SendKeys(" \t \t ", pause=.001, with_spaces=False)
        received = self.ctrl.TextBlock()
        self.assertEquals("", received)

    # Tab tests
    def testNormalWithTabs(self):
        "Make sure that with spaces option works"
        self.__run_NormalCharacters_with_options(with_tabs=True)

    def testNormalWithoutTabs(self):
        "Make sure that with spaces option works"
        self.__run_NormalCharacters_with_options(with_tabs=False)

    def testTabWithTabs(self):
        "Make sure that with spaces option works"
        SendKeys("\t \t \t", pause=.1, with_tabs=True)
        received = self.ctrl.TextBlock()
        self.assertEquals("\t\t\t", received)

    def testTabWithoutTabs(self):
        "Make sure that with spaces option works"
        SendKeys("\t a\t b\t", pause=.1, with_tabs=False)
        received = self.ctrl.TextBlock()
        self.assertEquals("ab", received)

    def testTab(self):
        "Make sure that with spaces option works"
        SendKeys("{TAB}  {TAB} ", pause=.3)
        received = self.ctrl.TextBlock()
        self.assertEquals("\t\t", received)

    # Newline tests
    def testNormalWithNewlines(self):
        "Make sure that with spaces option works"
        self.__run_NormalCharacters_with_options(with_newlines=True)

    def testNormalWithoutNewlines(self):
        "Make sure that with_newlines option works"
        self.__run_NormalCharacters_with_options(with_newlines=False)

    def testNewlinesWithNewlines(self):
        "Make sure that with_newlines option works"
        SendKeys("\t \t \t a~\tb\nc", pause=.5, with_newlines=True)
        received = self.ctrl.TextBlock()
        self.assertEquals("a\r\nb\r\nc", received)

    def testNewlinesWithoutNewlines(self):
        "Make sure that with_newlines option works"
        SendKeys("\t \t \t\na", pause=.01, with_newlines=False)
        received = self.ctrl.TextBlock()
        self.assertEquals("a", received)

    #def testANSIExtendedCharacters(self):
    #    "Make sure that sending any character in range "
    #    #self.cmd = Application()
    #    #self.cmd.start("cmd.exe", create_new_console=True, wait_for_idle=False)
    #    ActionLogger().log('Preferred encoding: ' + locale.getpreferredencoding())
    #
    #    #os.system("chcp 850")
    #    matched = 0
    #    extended_chars = b"\x81\x82\x83\xa1\xe1\xff"
    #    for char in extended_chars:

    #        if six.PY3:
    #            c = str(char)
    #        else:
    #            c = char.decode(locale.getpreferredencoding()) #'cp850')
    #        SendKeys(c, pause = .01)
    #        received = self.ctrl.TextBlock()[-1]

    #        if c == received:
    #            matched += 1
    #        else:
    #            print("expected %s, recieved %s"% (
    #                repr(c), repr(received)))

    #    self.assertEquals(matched, len(extended_chars))

    def testCharsThatMustBeEscaped(self):
        "Make sure that escaping characters works"
        SendKeys("{%}{^}{+}{(}{)}{{}{}}{~}")
        received = self.ctrl.TextBlock()
        self.assertEquals("%^+(){}~", received)

    def testIncorrectCases(self):
        "Make sure that incorrect key sequences raise an exception"
        DEBUG = 1
        self.assertRaises(KeySequenceError, SendKeys, "{ENTER")
        self.assertRaises(KeySequenceError, SendKeys, "ENTER)")
        self.assertRaises(RuntimeError, SendKeys, "%{Enterius}")
        self.assertRaises(KeySequenceError, SendKeys, "{PAUSE small}")

        try:
            SendKeys("{ENTER five}")
        except KeySequenceError as exc:
            self.assertEquals("invalid repetition count five", str(exc))

        try:
            SendKeys("ENTER}")
        except KeySequenceError as exc:
            self.assertEquals("`}` should be preceeded by `{`", str(exc))

    def testKeyDescription(self):
        "Test KeyAction._"
        self.assertEquals("<X>", str(KeyAction("X")))
        self.assertEquals("<Y down>", str(KeyAction("Y", up=False)))
        self.assertEquals("<Y up>", str(KeyAction("Y", down=False)))
        #self.assertEquals("<ENTER>", str(VirtualKeyAction(13))) # == "<VK_RETURN>" in Python 2.7 (TODO)
        self.assertEquals("<PAUSE 1.00>", str(PauseAction(1.0)))

    def testRepetition(self):
        "Make sure that repeated action works"
        SendKeys("{TAB 3}{PAUSE 0.5}{F 2}", pause=.3)
        received = self.ctrl.TextBlock()
        self.assertEquals("\t\t\tFF", received)
import time
from pywinauto.application import Application
import pywinauto.keyboard
import pywinauto.mouse

app = Application(backend="uia")

#Ouvrir l'application Google Chrome
app.start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

time.sleep(3)

#Write a URL
url = "pages jaunes contact with email"
pywinauto.keyboard.send_keys(url)

time.sleep(2)

#Press the 'Enter' button
pywinauto.keyboard.send_keys('{ENTER}')

time.sleep(3)

#Scroll down Demande d'informations
pywinauto.keyboard.send_keys('{DOWN 10}')

time.sleep(1)

#Move the mouse to the 'Contacter par mail' button
#Click the 'Contacter par mail' button
pywinauto.mouse.click(button='left', coords=(180, 310))
Пример #35
0
class DialogTestCases(unittest.TestCase):

    """Unit tests for the DialogWrapper class"""

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        self.app = Application()

        if is_x64_Python() or not is_x64_OS():
            self.app.start(r"C:\Windows\System32\calc.exe")
        else:
            self.app.start(r"C:\Windows\SysWOW64\calc.exe")
        self.calc = self.app.CalcFrame

        # write out the XML so that we can read it in later
        self.app.Calculator.WriteToXML("ref_controls.xml")

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()
        #self.calc.TypeKeys("%{F4}")

    def testGetProperties(self):
        "Test getting the properties for the dialog box"
        props = self.calc.GetProperties()

        self.assertEquals(
            "CalcFrame", props['FriendlyClassName'])

        self.assertEquals(self.calc.Texts(), props['Texts'])

        for prop_name in props:
            self.assertEquals(
                getattr(self.calc, prop_name)(), props[prop_name])

    def testRunTests(self):
        "Test running the UI tests on the dialog"
        bugs = self.calc.RunTests()
        from pywinauto.controls.HwndWrapper import HwndWrapper
        self.assertEquals(True, isinstance(bugs[0][0][0], HwndWrapper))

    def testRunTestsWithReference(self):
        "Add a ref control, get the bugs and validate that the hande "
        from pywinauto import controlproperties
        ref_controls = [controlproperties.ControlProps(ctrl) for
                ctrl in XMLHelpers.ReadPropertiesFromFile("ref_controls.xml")]

        bugs = self.calc.RunTests(ref_controls = ref_controls)
        from pywinauto import tests
        tests.print_bugs(bugs)
        from pywinauto.controls.HwndWrapper import HwndWrapper
        self.assertEquals(True, isinstance(bugs[0][0][0], HwndWrapper))

    def testWriteToXML(self):
        "Write the output and validate that it is the same as the test output"
        self.calc.WriteToXML("test_output.xml")

        all_props = [self.calc.GetProperties()]
        all_props.extend([c.GetProperties() for c in self.calc.Children()])

        props = XMLHelpers.ReadPropertiesFromFile("test_output.xml")
        for i, ctrl in enumerate(props):

            for key, ctrl_value in ctrl.items():
                expected_value = all_props[i][key]

                if "Image" in expected_value.__class__.__name__:
                    expected_value = expected_value.tobytes()
                    ctrl_value = ctrl_value.tobytes()

                if isinstance(ctrl_value, (list, tuple)):
                    ctrl_value = list(ctrl_value)
                    expected_value = list(expected_value)

                self.assertEquals(ctrl_value, expected_value)

        import os
        os.unlink("test_output.xml")

    def testClientAreaRect(self):
        """Validate that the client area rect is the right size
        (comparing against the full rectangle)
        Notice that we run an approximate comparison as the actual
        area size depends on Windows OS and a current desktop theme"""
        clientarea = self.calc.ClientAreaRect()
        rectangle = self.calc.Rectangle()
        self.failIf((clientarea.left - rectangle.left) > 10)
        self.failIf((clientarea.top - rectangle.top) > 60)
        self.failIf((rectangle.right - clientarea.right) > 10)
        self.failIf((rectangle.bottom - clientarea.bottom) > 10)

    def testHideFromTaskbar(self):
        "Test that a dialog can be hidden from the Windows taskbar"
        self.assertEquals(self.calc.IsInTaskbar(), True)
        self.calc.HideFromTaskbar()
        self.assertEquals(self.calc.IsInTaskbar(), False)
        self.calc.ShowInTaskbar()
        self.assertEquals(self.calc.IsInTaskbar(), True)
Пример #36
0
    def test_connect_to_my_account_from_several_ads_from_all_result_page(self):
        print("test_connect_to_my_account_from_several_ads_from_all_result_page")

        app = Application(backend="uia")

        i = 1

        # 148
        for x in range(3, 4):
            print("result page : " + str(x))

            url_result_page = "https://www.airjob.fr/recherche/keywords:d%25C3%25A9veloppeur,,l:10,p:" + str(x)

            # Request the content of a page from the url
            html = requests.get(url_result_page)

            time.sleep(3)

            # Parse the content of html_doc
            soup = BeautifulSoup(html.content, 'html.parser')

            if soup.find('div', {'class': 'un-resultat'}) is not None:
                print("offres ok")

                all_offre = soup.find_all('div', {'class': 'un-resultat'})

                for offre in all_offre:
                    print("link " + str(i) + " : https://www.airjob.fr" + str(offre
                                                                              .find('a', {'class': 'resultat-titre'})
                                                                              .get('href')))

                    i += 1

                    url_ad = "https://www.airjob.fr" + str(offre.find('a', {'class': 'resultat-titre'}).get('href'))

                    time.sleep(3)

                    # Ouvrir l'application CCleaner
                    app.start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

                    time.sleep(6)

                    pywinauto.keyboard.send_keys(url_ad)

                    time.sleep(3)

                    # Press the 'Enter' button
                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(6)

                    pywinauto.mouse.click(button="left", coords=(230, 460))

                    time.sleep(3)

                    pywinauto.mouse.click(button="left", coords=(500, 305))

                    time.sleep(3)

                    # Type the email
                    pywinauto.keyboard.send_keys("")

                    time.sleep(3)

                    pywinauto.keyboard.send_keys("{VK_TAB}")

                    time.sleep(3)

                    # Type the password
                    pywinauto.keyboard.send_keys("")

                    time.sleep(3)

                    pywinauto.keyboard.send_keys("{VK_TAB 2}")

                    time.sleep(3)

                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(6)

                    # click on Postuler
                    pywinauto.mouse.click(button="left", coords=(230, 460))

                    time.sleep(4)

                    # click on CV
                    pywinauto.mouse.click(button="left", coords=(900, 180))

                    time.sleep(4)

                    # select the file
                    pywinauto.mouse.click(button="left", coords=(340, 50))
                    time.sleep(3)
                    pywinauto.keyboard.send_keys("C:\\Users\\DELL\\Documents")
                    time.sleep(3)
                    pywinauto.keyboard.send_keys('{ENTER}')
                    time.sleep(3)
                    pywinauto.mouse.click(button="left", coords=(300, 230))
                    time.sleep(3)
                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(4)

                    # select the input for the message
                    pywinauto.mouse.click(button="left", coords=(860, 260))

                    time.sleep(4)

                    # write the message
                    pywinauto.keyboard.send_keys("""
                            """)

                    time.sleep(4)

                    pywinauto.keyboard.send_keys("{VK_TAB}")

                    time.sleep(4)

                    # envoyer ma candidature
                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(7)

                    # revenir tout en haut de la page
                    pywinauto.keyboard.send_keys('{PGUP 7}')

                    time.sleep(4)

                    # type on the url bar 2 times
                    pywinauto.mouse.click(button="left", coords=(820, 50))
                    time.sleep(2)
                    pywinauto.mouse.click(button="left", coords=(820, 50))

                    time.sleep(4)

                    # erase the phrase (#postuler)
                    pywinauto.keyboard.send_keys('{BACKSPACE 9}')

                    time.sleep(4)

                    # refresh the page
                    pywinauto.keyboard.send_keys('{ENTER}')

                    time.sleep(4)

                    # Je me déconnecte
                    pywinauto.mouse.click(button="left", coords=(1200, 230))

                    time.sleep(4)

                    # Close the browser
                    pywinauto.keyboard.send_keys('%{F4}')

                    time.sleep(5)
            else:
                print("no offres")
Пример #37
0
    def handle(self, command, *args, **kwargs):
        """ Execute a given command.
        :param command: string containing the command
        :param args: optional command args
        :param kwargs: optional command kwargs
        """

        if command == "run":
            self.__execute(args)
        elif command == "dictate":
            dictation_recorder = CommandRecorder()
            filename = "dictation.wav"
            log("Listening to dictation...")
            dictation_recorder.record_for_seconds(filename=filename, record_seconds=10)
            log("Dictation ended.")
            transcription = interpret_dication(filename)
            log("Transcription: ", transcription)
            remove(filename)
        elif command == "enter":
            SendKeys('{ENTER}')
        elif command == "home":
            SendKeys('{HOME}')
        elif command == "desktop":
            SendKeys('{LWIN}d')  # does it work?
        elif command == "next_window":
            SendKeys('%{ESC}')
        elif command == "up":
            scroll(coords=GetCursorPos(), wheel_dist=7)
        elif command == "down":
            scroll(coords=GetCursorPos(), wheel_dist=-7)
        elif command == "select_all":
            SendKeys('^a')
        elif command == "copy":
            SendKeys('^c')
        elif command == "paste":
            SendKeys('^v')
        elif command == "save":
            SendKeys('^s')
        elif command == "undo":
            SendKeys('^z')
        elif command == "find":
            SendKeys('^f')
            keyword_recorder = CommandRecorder()
            filename = "keyword.wav"
            log("What to find?")
            keyword_recorder.record_for_seconds(filename=filename, record_seconds=2)
            keyword = interpret_dication(filename)
            log("Szukam ", keyword)
            SendKeys(keyword[1:len(keyword) - 1] + '{ENTER}', with_spaces=True)
            remove(filename)
        elif command == "google":     # WIP
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://www.google.com')
            keyword_recorder = CommandRecorder()
            filename = "keyword.wav"
            log("What to google?")
            keyword_recorder.record_for_seconds(filename=filename, record_seconds=3)
            keyword = interpret_dication(filename)
            log("Googling ", keyword)
            SendKeys(keyword[1:len(keyword)-1] + '{ENTER}', with_spaces=True)
            remove(filename)
        elif command == "youtube":
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://www.youtube.com')
        elif command == "close":
            SendKeys('%{F4}')
        elif command == "end_commander":
            _exit(0)
        elif command == "yoda":
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://youtu.be/bYRYHLUNEs4?t=18')
        elif command == "private_browsing":
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://www.youtube.com/watch?v=x6QZn9xiuOE')
            SendKeys('^+n')
            SendKeys('chicks' + '{ENTER}', with_spaces=True)
            log("Have fun!")
        else:
            raise NotImplementedError('Unknown command!')
Пример #38
0
class MenuWrapperTests(unittest.TestCase):
    "Unit tests for the Menu and the MenuItem classes"

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.defaults()

        self.app = Application()
        self.app.start("Notepad.exe")

        self.dlg = self.app.Notepad

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testInvalidHandle(self):
        "Test that an exception is raised with an invalid menu handle"
        # self.assertRaises(InvalidWindowHandle, HwndWrapper, -1)
        pass

    def testItemCount(self):
        self.assertEqual(5, self.dlg.Menu().ItemCount())

    def testItem(self):
        self.assertEqual(u'&File', self.dlg.Menu().Item(0).Text())
        self.assertEqual(u'&File', self.dlg.Menu().Item(u'File').Text())
        self.assertEqual(u'&File',
                         self.dlg.Menu().Item(u'&File', exact=True).Text())

    def testItems(self):
        self.assertEqual([u'&File', u'&Edit', u'F&ormat', u'&View', u'&Help'],
                         [item.Text() for item in self.dlg.Menu().Items()])

    def testFriendlyClassName(self):
        self.assertEqual('MenuItem',
                         self.dlg.Menu().Item(0).friendly_class_name())

    def testMenuItemNotEnabled(self):
        self.assertRaises(MenuItemNotEnabled, self.dlg.MenuSelect,
                          'Edit->Find Next')
        self.assertRaises(MenuItemNotEnabled,
                          self.dlg.MenuItem('Edit->Find Next').Click)
        self.assertRaises(MenuItemNotEnabled,
                          self.dlg.MenuItem('Edit->Find Next').click_input)

    def testGetProperties(self):
        self.assertEqual(
            {
                u'menu_items': [{
                    u'index': 0,
                    u'state': 0,
                    u'item_type': 0,
                    u'item_id': 64,
                    u'text': u'View &Help'
                }, {
                    u'index': 1,
                    u'state': 3,
                    u'item_type': 2048,
                    u'item_id': 0,
                    u'text': u''
                }, {
                    u'index': 2,
                    u'state': 0,
                    u'item_type': 0,
                    u'item_id': 65,
                    u'text': u'&About Notepad'
                }]
            },
            self.dlg.Menu().GetMenuPath('Help')[0].SubMenu().GetProperties())

    def testGetMenuPath(self):
        # print('id = ' + str(self.dlg.Menu().GetMenuPath('Help->#3')[0].id()))
        self.assertEqual(
            u'&About Notepad',
            self.dlg.Menu().GetMenuPath(' Help -> #2 ')[-1].Text())
        self.assertEqual(u'&About Notepad',
                         self.dlg.Menu().GetMenuPath('Help->$65')[-1].Text())
        self.assertEqual(
            u'&About Notepad',
            self.dlg.Menu().GetMenuPath('&Help->&About Notepad',
                                        exact=True)[-1].Text())
        self.assertRaises(IndexError,
                          self.dlg.Menu().GetMenuPath,
                          '&Help->About what?',
                          exact=True)

    def test__repr__(self):
        print(self.dlg.Menu())
        print(self.dlg.Menu().GetMenuPath('&Help->&About Notepad',
                                          exact=True)[-1])

    def testClick(self):
        self.dlg.Menu().GetMenuPath('&Help->&About Notepad')[-1].Click()
        About = self.app.Window_(title='About Notepad')
        About.Wait('ready')
        About.OK.Click()
        About.WaitNot('visible')

    def testClickInput(self):
        self.dlg.Menu().GetMenuPath('&Help->&About Notepad')[-1].click_input()
        About = self.app.Window_(title='About Notepad')
        About.Wait('ready')
        About.OK.Click()
        About.WaitNot('visible')
Пример #39
0
from pywinauto.application import Application
import time

app = Application()
app.start("Notepad.exe")
Пример #40
0
 def test_connect_process_timeout_failed(self):
     """Test that connect_(process=...) raise error when set timeout"""
     app1 = Application()
     app1.start(_notepad_exe())
     self.assertRaises(ProcessNotFoundError, Application().connect, process=0, timeout=0.5)
     app1.UntitledNotepad.MenuSelect('File->Exit')
Пример #41
0
class ButtonTestCases(unittest.TestCase):

    """Unit tests for the ButtonWrapper class"""

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        self.app = Application()

        if is_x64_Python() or not is_x64_OS():
            self.app.start(r"C:\Windows\System32\calc.exe")
        else:
            self.app.start(r"C:\Windows\SysWOW64\calc.exe")
        self.calc = self.app.Calculator
        self.calc.MenuSelect("View->Scientific")

    def tearDown(self):
        "Close the application after tests"

        self.app.kill_()
        #self.calc.TypeKeys("%{F4}")

    def testGetProperties(self):
        "Test getting the properties for the button control"
        props = self.calc.Degrees.GetProperties()

        self.assertEquals(
            "RadioButton", props['FriendlyClassName'])

        self.assertEquals(
            self.calc.Degrees.Texts(), ['Degrees'])

        self.assertEquals(
            self.calc.Degrees.Texts(), props['Texts'])

        for prop_name in props:
            self.assertEquals(
                getattr(self.calc.Degrees, prop_name)(), props[prop_name])

    def test_NeedsImageProp(self):

        """test whether an image needs to be saved with the properties"""

        self.assertEquals(self.calc.Button5._NeedsImageProp, False)
        self.assertEquals('Image' in self.calc.Button5.GetProperties(), False)
        #self.assertNotIn('Image', self.calc.Button5.GetProperties())
        # assertIn and assertNotIn are not supported in Python 2.6

    def testFriendlyClass(self):
        "Test the FriendlyClassName method"
        self.assertEquals(self.calc.Button9.FriendlyClassName(), "Button")
        self.assertEquals(self.calc.Degree.FriendlyClassName(), "RadioButton")
        #self.assertEquals(self.calc.Hex.FriendlyClassName(), "CheckBox")

        #children = self.calc.Children()
        #no_text_buttons = [
        #    c for c in children
        #        if not c.WindowText() and c.Class() == "Button"]

        #first_group = no_text_buttons[0]

        #self.assertEquals(first_group.FriendlyClassName(), "GroupBox")

    def testCheckUncheck(self):
        "Test unchecking a control"

        self.calc.Grads.Check()
        self.assertEquals(self.calc.Grads.GetCheckState(), 1)
        self.calc.Grads.UnCheck()
        self.assertEquals(self.calc.Grads.GetCheckState(), 0)

    def testGetCheckState_unchecked(self):
        "unchecked"
        self.assertEquals(self.calc.Grads.GetCheckState(), 0)

    def testGetCheckState_checked(self):
        "checked"
        self.calc.Grads.Check()
        self.assertEquals(self.calc.Grads.GetCheckState(), 1)

#    def testGetCheckState_indeterminate(self):
#        "indeterminate"
#        self.calc.Inv.SetCheckIndeterminate()
#        self.assertEquals(self.calc.Inv.GetCheckState(), 0)

    def testClick(self):
        "Test clicking on buttons"
        self.calc.Button15.Click()  # "6"
        self.calc.Button10.Click()  # "5"
        self.calc.Button23.Click()  # "+"
        self.calc.Button4.Click()   # "4"
        self.calc.Button16.Click()  # "3"
        self.calc.Button28.Click()  # "="
        self.assertEquals(self.calc.ChildWindow(class_name='Static', ctrl_index=5).Texts()[0], "108")

    def testIsSelected(self):
        "Test whether the control is selected or not"
        # Todo - I need to find an application where a button can be
        # selected - I don't see one in Calc at least :)
        self.assertEquals(self.calc.Radians.GetCheckState(), 0)

        self.calc.Radians.Click()

        self.assertEquals(self.calc.Radians.GetCheckState(), 1)
Пример #42
0
class Windows(Device):
    """Windows client."""
    def __init__(self, handle=None, dpifactor=1, **kwargs):
        self.app = None
        self.handle = int(handle) if handle else None
        # windows high dpi scale factor, no exact way to auto detect this value for a window
        # reference: https://msdn.microsoft.com/en-us/library/windows/desktop/mt843498(v=vs.85).aspx
        self._dpifactor = float(dpifactor)
        self._app = Application()
        self._top_window = None
        self._focus_rect = (0, 0, 0, 0)
        self.mouse = mouse
        self.keyboard = keyboard
        self._init_connect(handle, kwargs)

    @property
    def uuid(self):
        return self.handle

    def _init_connect(self, handle, kwargs):
        if handle:
            self.connect(handle=handle)
        elif kwargs:
            self.connect(**kwargs)

    def connect(self, handle=None, **kwargs):
        """
        Connect to window and set it foreground

        Args:
            **kwargs: optional arguments

        Returns:
            None

        """
        if handle:
            handle = int(handle)
            self.app = self._app.connect(handle=handle)
            self._top_window = self.app.window(handle=handle).wrapper_object()
        else:
            self.app = self._app.connect(**kwargs)
            self._top_window = self.app.top_window().wrapper_object()
        self.set_foreground()

    def shell(self, cmd):
        """
        Run shell command in subprocess

        Args:
            cmd: command to be run

        Raises:
            subprocess.CalledProcessError: when command returns non-zero exit status

        Returns:
            command output as a byte string

        """
        return subprocess.check_output(cmd, shell=True)

    def snapshot(self, filename="tmp.png"):
        """
        Take a screenshot and save it to `tmp.png` filename by default

        Args:
            filename: name of file where to store the screenshot

        Returns:
            display the screenshot

        """
        if not filename:
            filename = "tmp.png"
        if self.handle:
            screen = screenshot(filename, self.handle)
        else:
            screen = screenshot(filename)
            if self.app:
                rect = self.get_rect()
                screen = aircv.crop_image(
                    screen, [rect.left, rect.top, rect.right, rect.bottom])
        if not screen.any():
            if self.app:
                rect = self.get_rect()
                screen = aircv.crop_image(
                    screenshot(filename),
                    [rect.left, rect.top, rect.right, rect.bottom])
        if self._focus_rect != (0, 0, 0, 0):
            height, width = screen.shape[:2]
            rect = (self._focus_rect[0], self._focus_rect[1],
                    width + self._focus_rect[2], height + self._focus_rect[3])
            screen = aircv.crop_image(screen, rect)
        if filename:
            aircv.imwrite(filename, screen)
        return screen

    def keyevent(self, keyname, **kwargs):
        """
        Perform a key event

        References:
            https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html

        Args:
            keyname: key event
            **kwargs: optional arguments

        Returns:
            None

        """
        self.keyboard.SendKeys(keyname)

    def text(self, text, **kwargs):
        """
        Input text

        Args:
            text: text to input
            **kwargs: optional arguments

        Returns:
            None

        """
        self.keyevent(text)

    def touch(self, pos, **kwargs):
        """
        Perform mouse click action

        References:
            https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html

        Args:
            pos: coordinates where to click
            **kwargs: optional arguments

        Returns:
            None

        """
        duration = kwargs.get("duration", 0.01)
        right_click = kwargs.get("right_click", False)
        button = "right" if right_click else "left"
        coords = self._action_pos(pos)

        self.mouse.press(button=button, coords=coords)
        time.sleep(duration)
        self.mouse.release(button=button, coords=coords)

    def double_click(self, pos):
        coords = self._action_pos(pos)
        self.mouse.double_click(coords=coords)

    def swipe(self, p1, p2, duration=0.8, steps=5):
        """
        Perform swipe (mouse press and mouse release)
        Args:
            p1: start point
            p2: end point
            duration: time interval to perform the swipe action
            steps: size of the swipe step

        Returns:
            None

        """
        from_x, from_y = self._action_pos(p1)
        to_x, to_y = self._action_pos(p2)

        interval = float(duration) / (steps + 1)
        self.mouse.press(coords=(from_x, from_y))
        time.sleep(interval)
        for i in range(1, steps):
            self.mouse.move(coords=(
                int(from_x + (to_x - from_x) * i / steps),
                int(from_y + (to_y - from_y) * i / steps),
            ))
            time.sleep(interval)
        for i in range(10):
            self.mouse.move(coords=(to_x, to_y))
        time.sleep(interval)
        self.mouse.release(coords=(to_x, to_y))

    def start_app(self, path):
        """
        Start the application

        Args:
            path: full path to the application

        Returns:
            None

        """
        self.app = self._app.start(path)

    def stop_app(self, pid):
        """
        Stop the application

        Args:
            pid: process ID of the application to be stopped

        Returns:
            None

        """
        self._app.connect(process=pid).kill()

    @require_app
    def set_foreground(self):
        """
        Bring the window foreground

        Returns:
            None

        """
        SetForegroundWindow(self._top_window)

    @require_app
    def get_rect(self):
        """
        Get rectangle

        Returns:
            None

        """
        return self._top_window.rectangle()

    @require_app
    def get_title(self):
        """
        Get the window title

        Returns:
            window title

        """
        return self._top_window.texts()

    @require_app
    def get_pos(self):
        """
        Get the window position coordinates

        Returns:
            coordinates of topleft corner of the window (left, top)

        """
        rect = self.get_rect()
        return (rect.left, rect.top)

    @require_app
    def move(self, pos):
        """
        Move window to given coordinates

        Args:
            pos: coordinates (x, y) where to move the window

        Returns:
            None

        """
        self._top_window.MoveWindow(x=pos[0], y=pos[1])

    @require_app
    def kill(self):
        """
        Kill the application

        Returns:
            None

        """
        self.app.kill()

    def _action_pos(self, pos):
        if self.app:
            pos = self._windowpos_to_screenpos(pos)
        pos = (int(pos[0]), int(pos[1]))
        return pos

    # @property
    # def handle(self):
    #     return self._top_window.handle

    @property
    def focus_rect(self):
        return self._focus_rect

    @focus_rect.setter
    def focus_rect(self, value):
        # set focus rect to get rid of window border
        assert len(
            value) == 4, "focus rect must be in [left, top, right, bottom]"
        self._focus_rect = value

    def get_current_resolution(self):
        rect = self.get_rect()
        w = (rect.right + self._focus_rect[2]) - (rect.left +
                                                  self._focus_rect[0])
        h = (rect.bottom + self._focus_rect[3]) - (rect.top +
                                                   self._focus_rect[1])
        return w, h

    def _windowpos_to_screenpos(self, pos):
        """
        Convert given position relative to window topleft corner to screen coordinates

        Args:
            pos: coordinates (x, y)

        Returns:
            converted position coordinates

        """
        rect = self.get_rect()
        pos = (int(
            (pos[0] + rect.left + self._focus_rect[0]) * self._dpifactor),
               int((pos[1] + rect.top + self._focus_rect[1]) *
                   self._dpifactor))
        return pos

    def get_ip_address(self):
        """
        Return default external ip address of the windows os.

        Returns:
             :py:obj:`str`: ip address
        """
        return socket.gethostbyname(socket.gethostname())
Пример #43
0
    def test_connect_to_my_account_from_several_ads_from_one_result_page(self):
        app = Application(backend="uia")

        urls_ad = [
            ""
        ]

        for url_ad in urls_ad:
            print(url_ad)

            time.sleep(3)

            # Ouvrir l'application CCleaner
            app.start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

            time.sleep(6)

            pywinauto.keyboard.send_keys(url_ad)

            time.sleep(3)

            # Press the 'Enter' button
            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(6)

            pywinauto.mouse.click(button="left", coords=(230, 460))

            time.sleep(3)

            pywinauto.mouse.click(button="left", coords=(500, 305))

            time.sleep(3)

            # Type the email
            pywinauto.keyboard.send_keys("")

            time.sleep(3)

            pywinauto.keyboard.send_keys("{VK_TAB}")

            time.sleep(3)

            # Type the password
            pywinauto.keyboard.send_keys("")

            time.sleep(3)

            pywinauto.keyboard.send_keys("{VK_TAB 2}")

            time.sleep(3)

            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(6)

            # click on Postuler
            pywinauto.mouse.click(button="left", coords=(230, 460))

            time.sleep(4)

            # click on CV
            pywinauto.mouse.click(button="left", coords=(900, 180))

            time.sleep(4)

            # select the file
            pywinauto.mouse.click(button="left", coords=(340, 50))
            time.sleep(3)
            pywinauto.keyboard.send_keys("C:\\Users\\DELL\\Documents")
            time.sleep(3)
            pywinauto.keyboard.send_keys('{ENTER}')
            time.sleep(3)
            pywinauto.mouse.click(button="left", coords=(300, 230))
            time.sleep(3)
            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(4)

            # select the input for the message
            pywinauto.mouse.click(button="left", coords=(860, 260))

            time.sleep(4)

            # write the message
            pywinauto.keyboard.send_keys("""
            """)

            time.sleep(4)

            pywinauto.keyboard.send_keys("{VK_TAB}")

            time.sleep(4)

            # envoyer ma candidature
            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(7)

            # type on the url bar 2 times
            pywinauto.mouse.click(button="left", coords=(820, 50))
            time.sleep(2)
            pywinauto.mouse.click(button="left", coords=(820, 50))

            time.sleep(4)

            # erase the phrase (#postuler)
            pywinauto.keyboard.send_keys('{BACKSPACE 9}')

            time.sleep(4)

            # refresh the page
            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(4)

            # Je me déconnecte
            pywinauto.mouse.click(button="left", coords=(1200, 230))

            time.sleep(4)

            # Close the browser
            pywinauto.keyboard.send_keys('%{F4}')

            time.sleep(5)
Пример #44
0
    def test_connect_to_my_account_from_one_ad(self):
        app = Application(backend="uia")

        url_ad = ""

        # Ouvrir l'application CCleaner
        app.start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

        time.sleep(6)

        # Open the Freelance-info.fr
        pywinauto.keyboard.send_keys(url_ad)

        time.sleep(3)

        # Press the 'Enter' button
        pywinauto.keyboard.send_keys('{ENTER}')

        time.sleep(6)

        pywinauto.mouse.click(button="left", coords=(500, 670))

        time.sleep(3)

        pywinauto.keyboard.send_keys("{VK_TAB}")

        time.sleep(3)

        pywinauto.keyboard.send_keys('{ENTER}')

        time.sleep(3)

        pywinauto.mouse.click(button="left", coords=(600, 450))

        time.sleep(3)

        # Type the eamil
        pywinauto.keyboard.send_keys('')

        time.sleep(3)

        pywinauto.keyboard.send_keys("{VK_TAB}")

        time.sleep(3)

        # Type the password
        pywinauto.keyboard.send_keys('')

        time.sleep(3)

        pywinauto.keyboard.send_keys("{VK_TAB}")

        time.sleep(3)

        pywinauto.keyboard.send_keys('{ENTER}')

        time.sleep(7)

        pywinauto.mouse.click(button="left", coords=(500, 670))

        time.sleep(3)

        pywinauto.keyboard.send_keys("{VK_TAB}")

        time.sleep(3)

        pywinauto.keyboard.send_keys('{ENTER}')

        time.sleep(3)

        pywinauto.mouse.click(button="left", coords=(1170, 85))

        time.sleep(5)

        # Close the browser
        pywinauto.keyboard.send_keys('%{F4}')

        time.sleep(5)
Пример #45
0
class CheckBoxTests(unittest.TestCase):
    """Unit tests for the CheckBox specific methods of the ButtonWrapper class"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        _set_timings_fast()

        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.tree = self.dlg.TreeView.WrapperObject()

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testCheckUncheckByClick(self):
        "test for CheckByClick and UncheckByClick"
        self.dlg.TVS_HASLINES.CheckByClick()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_CHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), True)

        self.dlg.TVS_HASLINES.CheckByClick(
        )  # make sure it doesn't uncheck the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_CHECKED)

        self.dlg.TVS_HASLINES.UncheckByClick()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_UNCHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), False)

        self.dlg.TVS_HASLINES.UncheckByClick(
        )  # make sure it doesn't check the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_UNCHECKED)

    def testCheckUncheckByClickInput(self):
        "test for CheckByClickInput and UncheckByClickInput"
        self.dlg.TVS_HASLINES.CheckByClickInput()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_CHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), True)

        self.dlg.TVS_HASLINES.CheckByClickInput(
        )  # make sure it doesn't uncheck the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_CHECKED)

        self.dlg.TVS_HASLINES.UncheckByClickInput()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_UNCHECKED)
        self.assertEquals(self.tree.HasStyle(win32defines.TVS_HASLINES), False)

        self.dlg.TVS_HASLINES.UncheckByClickInput(
        )  # make sure it doesn't check the box unexpectedly
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_UNCHECKED)

    def testSetCheckIndeterminate(self):
        "test for SetCheckIndeterminate"
        self.dlg.TVS_HASLINES.SetCheckIndeterminate()
        self.assertEquals(self.dlg.TVS_HASLINES.GetCheckState(),
                          win32defines.BST_CHECKED)
Пример #46
0
def _toggle_notification_area_icons(show_all=True, debug_img=None):
    """
    A helper function to change 'Show All Icons' settings.
    On a succesful execution the function returns an original
    state of 'Show All Icons' checkbox.

    The helper works only for an "English" version of Windows,
    on non-english versions of Windows the 'Notification Area Icons'
    window should be accessed with a localized title"
    """

    app = Application()
    starter = app.start(r'explorer.exe')
    class_name = 'CabinetWClass'

    def _cabinetwclass_exist():
        "Verify if at least one active 'CabinetWClass' window is created"
        l = findwindows.find_elements(active_only=True, class_name=class_name)
        return (len(l) > 0)

    WaitUntil(_ready_timeout, _retry_interval, _cabinetwclass_exist)
    handle = findwindows.find_elements(active_only=True,
                                       class_name=class_name)[-1].handle
    window = WindowSpecification({
        'handle': handle,
        'backend': 'native',
    })
    explorer = Application().Connect(process=window.process_id())
    cur_state = None

    try:
        # Go to "Control Panel -> Notification Area Icons"
        window.Wait("ready", timeout=_ready_timeout)
        window.AddressBandRoot.click_input()
        window.type_keys(r'control /name Microsoft.NotificationAreaIcons',
                         with_spaces=True,
                         set_foreground=True)
        # Send 'ENTER' separately, this is to make sure
        # the window focus hasn't accidentally been lost
        window.type_keys('{ENTER}', with_spaces=True, set_foreground=True)
        explorer.WaitCPUUsageLower(threshold=5, timeout=_ready_timeout)

        # Get the new opened applet
        notif_area = explorer.Window_(title="Notification Area Icons",
                                      class_name=class_name)
        notif_area.Wait("ready", timeout=_ready_timeout)
        cur_state = notif_area.CheckBox.GetCheckState()

        # toggle the checkbox if it differs and close the applet
        if bool(cur_state) != show_all:
            notif_area.CheckBox.click_input()
        notif_area.Ok.click_input()
        explorer.WaitCPUUsageLower(threshold=5, timeout=_ready_timeout)

    except Exception as e:
        if debug_img:
            from PIL import ImageGrab
            ImageGrab.grab().save("%s.jpg" % (debug_img), "JPEG")
        l = pywinauto.actionlogger.ActionLogger()
        l.log("RuntimeError in _toggle_notification_area_icons")
        raise e

    finally:
        # close the explorer window
        window.Close()

    return cur_state
Пример #47
0
    def test_connect_to_my_account_from_several_ads(self):
        app = Application(backend="uia")

        urls_ad = [
            "https://www.freelance-info.fr/mission/ingenieur-citrix-ivanti-1563088",
            "https://www.freelance-info.fr/mission/developpeur-python-1563083",
            "https://www.freelance-info.fr/mission/chef-de-projet-securite-it-maroc-1563078",
            "https://www.freelance-info.fr/mission/developpeur-front-end-liferay-j-ee-h-f-1563065",
            "https://www.freelance-info.fr/mission/lsa-pega-1563058",
            "https://www.freelance-info.fr/mission/developpeur-net-core-azure-1563047"
        ]

        for url_ad in urls_ad:
            # Ouvrir l'application CCleaner
            app.start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

            time.sleep(6)

            # Open the Freelance-info.fr
            pywinauto.keyboard.send_keys(url_ad)

            time.sleep(3)

            # Press the 'Enter' button
            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(6)

            pywinauto.mouse.click(button="left", coords=(500, 670))

            time.sleep(3)

            pywinauto.keyboard.send_keys("{VK_TAB}")

            time.sleep(3)

            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(3)

            pywinauto.mouse.click(button="left", coords=(600, 450))

            time.sleep(3)

            # Type the email
            pywinauto.keyboard.send_keys('')

            time.sleep(3)

            pywinauto.keyboard.send_keys("{VK_TAB}")

            time.sleep(3)

            # Type the password
            pywinauto.keyboard.send_keys('')

            time.sleep(3)

            pywinauto.keyboard.send_keys("{VK_TAB}")

            time.sleep(3)

            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(7)

            pywinauto.mouse.click(button="left", coords=(500, 670))

            time.sleep(3)

            pywinauto.keyboard.send_keys("{VK_TAB}")

            time.sleep(3)

            pywinauto.keyboard.send_keys('{ENTER}')

            time.sleep(3)

            pywinauto.mouse.click(button="left", coords=(1170, 85))

            time.sleep(5)

            # Close the browser
            pywinauto.keyboard.send_keys('%{F4}')

            time.sleep(5)
Пример #48
0
class SendKeysTests(unittest.TestCase):
    """Unit tests for the Sendkeys module"""
    def setUp(self):
        """Start the application set some data and ensure the application is in the state we want it."""
        if sys.platform == 'win32':
            self.app = Application()
            self.app.start(_notepad_exe())
            self.dlg = self.app.UntitledNotepad
            self.ctrl = self.dlg.Edit
        else:
            self.app = subprocess.Popen("exec " + _test_app(), shell=True)
            time.sleep(0.1)
            mouse.click(coords=(300, 300))
            time.sleep(0.1)

    def tearDown(self):
        """Close the application after tests"""
        if sys.platform == 'win32':
            try:
                self.dlg.Close(0.1)
            except Exception:  # TimeoutError:
                pass
            try:
                if self.app.Notepad["Do&n't Save"].Exists():
                    self.app.Notepad["Do&n't Save"].Click()
                    self.app.Notepad["Do&n't Save"].WaitNot('visible')
            except Exception:  # TimeoutError:
                pass
            finally:
                if self.dlg.Exists(timeout=0.1):
                    self.app.kill_()
        else:
            # call Popen.kill() on Linux since Application.kill_() is not implemented yet
            self.app.kill()

    def receive_text(self):
        """Receive data from text field"""
        received = ' '
        if sys.platform == 'win32':
            received = self.ctrl.TextBlock()
        else:
            time.sleep(0.2)
            SendKeys('^a')
            time.sleep(0.2)
            SendKeys('^c')
            SendKeys('{RIGHT}')
            received = clipboard.get_data()
        return received

    def __run_NormalCharacters_with_options(self, **args):
        """Make sure that sending any character in range """
        #unused var: missed = []
        for i in range(32, 127):

            # skip characters that must be escaped
            if chr(i) in '~!@#$%^&*()_+{}|:"<>? ':
                continue

            SendKeys(chr(i), pause=.001, **args)
            received = self.receive_text()[-1]

            self.assertEqual(i, ord(received))

    # Space tests
    def testNormalWithSpaces(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_spaces=True)

    def testNormalWithoutSpaces(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_spaces=False)

    def testSpaceWithSpaces(self):
        """Make sure that with spaces option works"""
        SendKeys(" \t \t ", pause=.001, with_spaces=True)
        received = self.receive_text()
        self.assertEqual("   ", received)

    def testSpaceWithoutSpaces(self):
        """Make sure that with spaces option works"""
        SendKeys(" \t \t ", pause=.001, with_spaces=False)
        received = self.receive_text()
        self.assertEqual("", received)

    # Tab tests
    def testNormalWithTabs(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_tabs=True)

    def testNormalWithoutTabs(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_tabs=False)

    def testTabWithTabs(self):
        """Make sure that with spaces option works"""
        SendKeys("\t \t \t", pause=.1, with_tabs=True)
        received = self.receive_text()
        self.assertEqual("\t\t\t", received)

    def testTabWithoutTabs(self):
        """Make sure that with spaces option works"""
        SendKeys("\t a\t b\t", pause=.1, with_tabs=False)
        received = self.receive_text()
        self.assertEqual("ab", received)

    def testTab(self):
        """Make sure that with spaces option works"""
        SendKeys("{TAB}  {TAB} ", pause=.3)
        received = self.receive_text()
        self.assertEqual("\t\t", received)

    # Newline tests
    def testNormalWithNewlines(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_newlines=True)

    def testNormalWithoutNewlines(self):
        """Make sure that with_newlines option works"""
        self.__run_NormalCharacters_with_options(with_newlines=False)

    def testNewlinesWithNewlines(self):
        """Make sure that with_newlines option works"""
        SendKeys("\t \t \t a~\tb\nc", pause=.5, with_newlines=True)
        received = self.receive_text()
        if sys.platform == 'win32':
            self.assertEqual("a\r\nb\r\nc", received)
        else:
            self.assertEqual("a\nb\nc", received)

    def testNewlinesWithoutNewlines(self):
        """"Make sure that with_newlines option works"""
        SendKeys("\t \t \t\na", pause=.01, with_newlines=False)
        received = self.receive_text()
        self.assertEqual("a", received)

    #def testANSIExtendedCharacters(self):
    #    "Make sure that sending any character in range "
    #    #self.cmd = Application()
    #    #self.cmd.start("cmd.exe", create_new_console=True, wait_for_idle=False)
    #    ActionLogger().log('Preferred encoding: ' + locale.getpreferredencoding())
    #
    #    #os.system("chcp 850")
    #    matched = 0
    #    extended_chars = b"\x81\x82\x83\xa1\xe1\xff"
    #    for char in extended_chars:

    #        if six.PY3:
    #            c = str(char)
    #        else:
    #            c = char.decode(locale.getpreferredencoding()) #'cp850')
    #        SendKeys(c, pause = .01)
    #        received = self.receive_text()[-1]

    #        if c == received:
    #            matched += 1
    #        else:
    #            print("expected %s, recieved %s"% (
    #                repr(c), repr(received)))

    #    self.assertEqual(matched, len(extended_chars))

    def testCharsThatMustBeEscaped(self):
        """Make sure that escaping characters works"""
        SendKeys("{%}{^}{+}{(}{)}{{}{}}{~}")
        received = self.receive_text()
        self.assertEqual("%^+(){}~", received)

    def testIncorrectCases(self):
        """Make sure that incorrect key sequences raise an exception"""
        self.assertRaises(KeySequenceError, SendKeys, "{ENTER")
        self.assertRaises(KeySequenceError, SendKeys, "ENTER)")
        self.assertRaises(RuntimeError, SendKeys, "%{Enterius}")
        self.assertRaises(KeySequenceError, SendKeys, "{PAUSE small}")

        try:
            SendKeys("{ENTER five}")
        except KeySequenceError as exc:
            self.assertEqual("invalid repetition count five", str(exc))

        try:
            SendKeys("ENTER}")
        except KeySequenceError as exc:
            self.assertEqual("`}` should be preceeded by `{`", str(exc))

    def testKeyDescription(self):
        """Test KeyAction._"""
        self.assertEqual("<X>", str(KeyAction("X")))
        self.assertEqual("<Y down>", str(KeyAction("Y", up=False)))
        self.assertEqual("<Y up>", str(KeyAction("Y", down=False)))
        #self.assertEqual("<ENTER>", str(VirtualKeyAction(13))) # == "<VK_RETURN>" in Python 2.7 (TODO)
        if sys.platform == 'win32':
            self.assertEqual("<PAUSE 1.00>", str(PauseAction(1.0)))

    def testRepetition(self):
        """Make sure that repeated action works"""
        SendKeys("{TAB 3}{PAUSE 0.5}{F 3}", pause=.3)
        received = self.receive_text()
        self.assertEqual("\t\t\tFFF", received)

    def testShiftModifier(self):
        """Make sure that Shift modifier works"""
        SendKeys("+(a)")
        received = self.receive_text()
        self.assertEqual("A", received)

    if sys.platform != 'win32':

        def testAltModifier(self):
            """Make sure that alt modifier works"""
            clipboard.set_data('abc')
            # check alt via opening edit menu and paste text from clipboard
            time.sleep(0.3)
            SendKeys('%(e)')
            time.sleep(0.3)
            SendKeys('{ENTER}')
            received = self.receive_text()
            self.assertEqual('abc', received)
Пример #49
0
class Win32HooksTests(unittest.TestCase):
    """Unit tests for the Win32Hook class"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        self.logger = pywinauto.actionlogger.ActionLogger()
        self.hook = Hook()
        self.hook.handler = self._on_hook_event
        self.wait_time = 0.4
        self.short_wait_time = self.wait_time / 4.0
        self.timer = None
        self.keybd_events = []
        self.mouse_events = []
        self.app = None

        # prevent capturing keyboard keys when launching a test manually
        time.sleep(self.short_wait_time)

    def tearDown(self):
        """Close all hooks after tests"""
        self.keybd_events = []
        self.mouse_events = []
        if self.timer:
            self.timer.cancel()
        self.hook.stop()
        if self.app:
            self.app.kill_()

    def _get_safe_point_to_click(self):
        """Run notepad.exe to have a safe area for mouse clicks"""

        mfc_samples_folder = os.path.join(os.path.dirname(__file__),
                                          r"..\..\apps\MFC_samples")
        if is_x64_Python():
            mfc_samples_folder = os.path.join(mfc_samples_folder, 'x64')
        sample_exe = os.path.join(mfc_samples_folder, "CmnCtrl1.exe")
        self.app = Application()
        self.app.start(sample_exe)
        self.app.CommonControlsSample.wait("ready")
        return self.app.CommonControlsSample.rectangle().mid_point()

    def _sleep_and_unhook(self):
        """A helper to remove all hooks after a pause"""
        time.sleep(self.short_wait_time)
        self.hook.stop()

    def trace(self, msg, *args):
        """Log the specified message"""
        self.logger.log(msg.format(*args))

    def _on_hook_event(self, args):
        """Callback for keyboard events"""
        if isinstance(args, KeyboardEvent):
            self.trace(
                "Win32HooksTests::_on_hook_event got KeyboardEvent: key={0} type={1}",
                args.current_key, args.event_type)
            self.keybd_events.append(args)
        elif isinstance(args, MouseEvent):
            self.trace(
                "Win32HooksTests::_on_hook_event got MouseEvent: key={0} type={1}",
                args.current_key, args.event_type)
            self.mouse_events.append(args)

    def _type_keys_and_unhook(self, key_strokes):
        """A timer callback to type key strokes and unhook"""
        SendKeys(key_strokes)

        # Give a time to process the keys by the hook
        self._sleep_and_unhook()

    def test_keyboard_hook_unicode_sequence(self):
        """Test capturing a sequence of unicode keystrokes by a keyboard hook"""
        keys = u'uk'
        self.timer = Timer(self.wait_time, self._type_keys_and_unhook, [keys])
        self.timer.start()
        self.hook.hook(keyboard=True, mouse=False)
        # Continue here only when the hook will be removed by the timer
        _delete_keys_from_terminal(keys)
        self.assertEqual(len(self.keybd_events), 4)
        self.assertEqual(self.keybd_events[0].current_key, u'u')
        self.assertEqual(self.keybd_events[0].event_type, 'key down')
        self.assertEqual(len(self.keybd_events[0].pressed_key), 0)
        self.assertEqual(self.keybd_events[1].current_key, u'u')
        self.assertEqual(self.keybd_events[1].event_type, 'key up')
        self.assertEqual(len(self.keybd_events[1].pressed_key), 0)
        self.assertEqual(self.keybd_events[2].current_key, u'k')
        self.assertEqual(self.keybd_events[2].event_type, 'key down')
        self.assertEqual(len(self.keybd_events[2].pressed_key), 0)
        self.assertEqual(self.keybd_events[3].current_key, u'k')
        self.assertEqual(self.keybd_events[3].event_type, 'key up')
        self.assertEqual(len(self.keybd_events[3].pressed_key), 0)

    def test_keyboard_hook_parallel_pressed_keys(self):
        """Test capturing parallel pressed keys by a keyboard hook"""
        keys = u'+a'
        self.timer = Timer(self.wait_time, self._type_keys_and_unhook, [keys])
        self.timer.start()
        self.hook.hook(keyboard=True, mouse=False)
        # Continue here only when the hook will be removed by the timer
        _delete_keys_from_terminal(keys)
        self.assertEqual(len(self.keybd_events), 4)
        self.assertEqual(self.keybd_events[0].current_key, u'Lshift')
        self.assertEqual(self.keybd_events[0].event_type, 'key down')
        self.assertEqual(len(self.keybd_events[0].pressed_key), 0)
        self.assertEqual(self.keybd_events[1].current_key, u'A')
        self.assertEqual(self.keybd_events[1].event_type, 'key down')
        self.assertEqual(len(self.keybd_events[1].pressed_key), 0)
        self.assertEqual(self.keybd_events[2].current_key, u'A')
        self.assertEqual(self.keybd_events[2].event_type, 'key up')
        self.assertEqual(len(self.keybd_events[2].pressed_key), 0)
        self.assertEqual(self.keybd_events[3].current_key, u'Lshift')
        self.assertEqual(self.keybd_events[3].event_type, 'key up')
        self.assertEqual(len(self.keybd_events[3].pressed_key), 0)

    def _mouse_click_and_unhook(self, coords):
        """A timer callback to perform a mouse click and unhook"""
        click(coords=coords)

        # Give a time to process the mouse clicks by the hook
        self._sleep_and_unhook()

    def test_mouse_hook(self):
        """Test capturing a sequence of mouse clicks by hook"""

        # Get a safe point to click
        pt = self._get_safe_point_to_click()
        coords = [(pt.x, pt.y)]

        # Set a timer to perform a click and hook the mouse
        self.timer = Timer(self.wait_time, self._mouse_click_and_unhook,
                           coords)
        self.timer.start()
        self.hook.hook(keyboard=False, mouse=True)
        # Continue here only when the hook will be removed by the timer
        self.assertEqual(len(self.mouse_events), 2)
        self.assertEqual(self.mouse_events[0].current_key, u'LButton')
        self.assertEqual(self.mouse_events[0].event_type, 'key down')
        self.assertEqual(self.mouse_events[0].mouse_x, pt.x)
        self.assertEqual(self.mouse_events[0].mouse_y, pt.y)
        self.assertEqual(self.mouse_events[1].current_key, u'LButton')
        self.assertEqual(self.mouse_events[1].event_type, 'key up')
        self.assertEqual(self.mouse_events[1].mouse_x, pt.x)
        self.assertEqual(self.mouse_events[1].mouse_y, pt.y)
Пример #50
0
from pywinauto.application import Application

from pywinauto import mouse

# app = Application(backend="uia").start(cmd_line=u'"C:\\Program Files (x86)\\Microsoft\\Skype for Desktop\\Skype.exe" ')

# skp = app.window(title_re='Skype.*') # actual search is NOT happening here
#skp.wait('ready', timeout=20) # wait up to 20 sec. (actual search is done, return early if found)

app = Application(backend="uia")
app.start(
    cmd_line=
    u'"C:\\Program Files (x86)\\Microsoft\\Skype for Desktop\\Skype.exe" ')
skp = app.window(title_re='Skype.*')  # actual search is NOT happening here
actionable_skp = skp.wait('visible')
# app.SkypeUsername.draw_outline()
# dlg =app.SkypeUsername
# contacts =dlg.Listbox  # My contacts seem to be under the header "Listbox" when I use point_control identifiers, so I assigned it to contacts for easy reference.

# search = skp["搜尋使用者、群組及訊息"]
# skp.Properties.button.click()
# skp.print_control_identifiers()
# search.click() # actual search of the sub-element is done here (inside of call to .click())
# app = Application(backend="uia").start(cmd_line=u'"C:\\Program Files (x86)\\Microsoft\\Skype for Desktop\\Skype.exe" ')
# app = Application().start(cmd_line=u'"C:\\Program Files (x86)\\Microsoft\\Skype for Desktop\\Skype.exe" ')
# skype_dig = app.window(title='Skype')
# skype_dig.Properties.print_control_identifiers()
# skype_dig.print_control_identifiers()
# skype_dig["[42.66432.4.-53]"].click()

# app.Kill_()
Пример #51
0
class MouseTests(unittest.TestCase):
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        if sys.platform == 'win32':
            Timings.defaults()
            self.app = Application()
            self.app.start(_test_app())
            self.dlg = self.app.mousebuttons
        else:
            self.display = Display()
            self.app = subprocess.Popen("exec " + _test_app(), shell=True)
            time.sleep(1)

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

    def __get_pos(self, shift):
        if sys.platform == 'win32':
            rect = self.dlg.rectangle()
            center = rect.mid_point()
            return center.x + shift, center.y + shift
        else:
            root = self.display.screen().root
            left_pos = root.get_geometry().width / 2
            top_pos = root.get_geometry().height / 2
            return left_pos - shift, top_pos - shift

    def __get_text(self):
        data = ''
        time.sleep(1)
        send_keys('^a^c', pause=0.2)
        if sys.platform == 'win32':
            win32clipboard.OpenClipboard()
            data = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()
        else:
            data = clipboard.get_data()
        return data

    def test_left_click(self):
        left, top = self.__get_pos(50)
        mouse.click(coords=(left, top))
        print(left, top)
        data = self.__get_text()
        print(data)
        self.assertTrue(str(int(top)) in data)
        self.assertTrue(str(int(left)) in data)
        self.assertTrue("LeftButton" in data)
        self.assertTrue("Mouse Press" in data)
        self.assertTrue("Mouse Release" in data)

    def test_double_click(self):
        mouse.double_click(coords=(self.__get_pos(50)))
        data = self.__get_text()
        self.assertTrue("Mouse DoubleClick" in data)

    def test_press_release(self):
        left, top = self.__get_pos(50)
        left1, top1 = self.__get_pos(20)
        mouse.press(coords=(left, top))
        mouse.release(coords=(left1, top1))
        data = self.__get_text()
        self.assertEqual(str(top) in data, str(top1) in data)
        self.assertEqual(str(left) in data, str(left1) in data)

    def test_right_click(self):
        mouse.right_click((self.__get_pos(50)))
        data = self.__get_text()
        self.assertTrue("Mouse Press" in data)
        self.assertTrue("Mouse Release" in data)
        self.assertTrue("RightButton" in data)

    def test_vertical_scroll_up(self):
        mouse.click(coords=(self.__get_pos(50)))
        mouse.scroll(self.__get_pos(50), 1)
        data = self.__get_text()
        self.assertTrue("UP" in data)

    def test_vertical_scroll_down(self):
        mouse.click(coords=(self.__get_pos(50)))
        mouse.scroll(self.__get_pos(50), -1)
        data = self.__get_text()
        self.assertTrue("DOWN" in data)

    def test_wheel_click(self):
        mouse.wheel_click((self.__get_pos(50)))
        data = self.__get_text()
        self.assertTrue("Mouse Press" in data)
        self.assertTrue("Mouse Release" in data)
        self.assertTrue("MiddleButton" in data)

    if sys.platform != 'win32':

        def test_swapped_buttons(self):
            current_map = self.display.get_pointer_mapping()
            swapped_map = copy.copy(current_map)
            swapped_map[0], swapped_map[2] = swapped_map[2], swapped_map[0]
            self.display.set_pointer_mapping(swapped_map)
            try:
                mouse.right_click((self.__get_pos(50)))
                data = self.__get_text()
                self.assertTrue("RightButton" in data)
            finally:
                self.display.set_pointer_mapping(current_map)
Пример #52
0
    def test_click_on_button_email_without_opencv_4(self):
        app = Application(backend="uia")

        contacts = [
            # siderurgie
            {
                # Auvergne-Rhône-Alpes
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Auvergne-Rh%C3%B4ne-Alpes&proximite=0&quoiQuiInterprete=siderurgie&contexte=X670jNNGAb2aMzRhUJQWzw%3D%3D&idOu=R84&page=',
                'number_of_page': '21',
                'y': '580'
            },
            {
                # Bourgogne-Franche-Comté
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Bourgogne-Franche-Comt%C3%A9&proximite=0&quoiQuiInterprete=siderurgie&contexte=PT14eXDaujFwxxowNQVTFA%3D%3D&idOu=R27&page=',
                'number_of_page': '9',
                'y': '580'
            },
            {
                # Bretagne
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Bretagne&idOu=R53&proximite=0&quoiQuiInterprete=siderurgie&contexte=mVLjbCNFGx3Ul%2BpcBNwbLA%3D%3D&page=',
                'number_of_page': '5',
                'y': '580'
            },
            {
                # Centre-Val-de-Loire
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Centre-Val-de-Loire&proximite=0&quoiQuiInterprete=siderurgie&contexte=m82au55EdkOKvZky7L0fQA%3D%3D&idOu=R24&page=',
                'number_of_page': '4',
                'y': '580'
            },
            {
                # Corse
                'contact':
                'https://www.pagesjaunes.fr/recherche/region/corse/siderurgie?quoiqui=siderurgie&ou=Corse&univers=pagesjaunes&idOu=&acOuSollicitee=1&nbPropositionOuTop=5&nbPropositionOuHisto=0&ouSaisi=Corse&acQuiQuoiSollicitee=0&nbPropositionQuiQuoiTop=0&nbPropositionQuiQuoiHisto=0&nbPropositionQuiQuoiGeo=0&quiQuoiSaisi=siderurgie&page=',
                'number_of_page': '1',
                'y': '580'
            },
            {
                # Grand-Est
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Grand-Est&proximite=0&quoiQuiInterprete=siderurgie&contexte=6X1jsfCLIss2yckhG3qjCw%3D%3D&idOu=R44&page=',
                'number_of_page': '14',
                'y': '580'
            },
            {
                # Hauts-de-France
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Hauts-de-France&proximite=0&quoiQuiInterprete=siderurgie&contexte=TI95WWBOqeN4MI9rrYkCaA%3D%3D&idOu=R32&page=',
                'number_of_page': '14',
                'y': '580'
            },
            {
                # Ile-de-France
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Ile-de-France&idOu=R11&proximite=0&quoiQuiInterprete=siderurgie&contexte=eJK8nXK7%2BLBq512knKytkQ%3D%3D&page=',
                'number_of_page': '13',
                'y': '580'
            },
            {
                # Normandie
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Normandie&idOu=R28&proximite=0&quoiQuiInterprete=siderurgie&contexte=7i/faE0vDhmMqitTNeRdsg%3D%3D&page=',
                'number_of_page': '6',
                'y': '580'
            },
            {
                # Nouvelle-Aquitaine
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Nouvelle-Aquitaine&proximite=0&quoiQuiInterprete=siderurgie&contexte=4cg8qOrYUfub0c6bCPcFqw%3D%3D&idOu=R75&page=',
                'number_of_page': '12',
                'y': '580'
            },
            {
                # Occitanie
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Occitanie&idOu=R76&proximite=0&quoiQuiInterprete=siderurgie&contexte=xuzZtNY/M7GibtQ5xMK1qQ%3D%3D&page=',
                'number_of_page': '11',
                'y': '580'
            },
            {
                # Pays%20de%20la%20Loire
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Pays%20de%20la%20Loire&proximite=0&quoiQuiInterprete=siderurgie&contexte=aWcblFLD8vcnzqOqQuFY1g%3D%3D&idOu=R52&page=',
                'number_of_page': '8',
                'y': '580'
            },
            {
                # Provence-Alpes-Côte-d%27Azur
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Provence-Alpes-C%C3%B4te-d%27Azur&proximite=0&quoiQuiInterprete=siderurgie&contexte=X7DCUb5%2BK%2BgLhvqI1ExajA%3D%3D&idOu=R93&page=',
                'number_of_page': '8',
                'y': '580'
            },
            {
                # Guadeloupe
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=Guadeloupe&proximite=0&quoiQuiInterprete=siderurgie&contexte=8rBcxFjt8SXVIR8LN2YnZ3eKL16bkxx3e0d5jKAkSaA%3D&idOu=D971&page=',
                'number_of_page': '2',
                'y': '580'
            },
            {
                # Martinique
                'contact':
                'https://www.pagesjaunes.fr/recherche/departement/martinique-972/siderurgie?quoiqui=siderurgie&ou=Martinique+%28972%29&univers=pagesjaunes&idOu=D972&ouSaisi=Martinique&ouNbCar=10&acOuSollicitee=1&rangOu=2&sourceOu=TOP&typeOu=Departement&nbPropositionOuTop=5&nbPropositionOuHisto=0&acQuiQuoiSollicitee=0&nbPropositionQuiQuoiTop=0&nbPropositionQuiQuoiHisto=0&nbPropositionQuiQuoiGeo=0&quiQuoiSaisi=siderurgie&page=',
                'number_of_page': '1',
                'y': '580'
            },
            {
                # Guyane
                'contact':
                'https://www.pagesjaunes.fr/recherche/departement/guyane-973/siderurgie?quoiqui=siderurgie&ou=Guyane+%28973%29&univers=pagesjaunes&idOu=D973&ouSaisi=Guyane&ouNbCar=6&acOuSollicitee=1&rangOu=2&sourceOu=TOP&typeOu=Departement&nbPropositionOuTop=5&nbPropositionOuHisto=0&acQuiQuoiSollicitee=0&nbPropositionQuiQuoiTop=0&nbPropositionQuiQuoiHisto=0&nbPropositionQuiQuoiGeo=0&quiQuoiSaisi=siderurgie&page=',
                'number_of_page': '1',
                'y': '580'
            },
            {
                # La%20Réunion%20%28974%29
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=siderurgie&ou=La%20R%C3%A9union%20%28974%29&idOu=D974&proximite=0&quoiQuiInterprete=siderurgie&contexte=PrfBkU3EisxgP7IY1H%2BLsQxISMRndNFsTX8Pg%2Byl0iE%3D&page=',
                'number_of_page': '2'
            },
            {
                # Mayotte
                'contact':
                'https://www.pagesjaunes.fr/recherche/departement/mayotte-976/siderurgie?quoiqui=siderurgie&ou=Mayotte+%28976%29&univers=pagesjaunes&idOu=D976&ouSaisi=Mayotte&ouNbCar=7&acOuSollicitee=1&rangOu=2&sourceOu=TOP&typeOu=Departement&nbPropositionOuTop=5&nbPropositionOuHisto=0&acQuiQuoiSollicitee=0&nbPropositionQuiQuoiTop=0&nbPropositionQuiQuoiHisto=0&nbPropositionQuiQuoiGeo=0&quiQuoiSaisi=siderurgie&page=',
                'number_of_page': '1',
                'y': '580'
            },
            # achat or
            {
                # Auvergne-Rhône-Alpes
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Auvergne-Rh%C3%B4ne-Alpes&idOu=R84&proximite=0&quoiQuiInterprete=achat%20or&contexte=fTKLUOf1OYREdQhkmplVdQ%3D%3D&page=',
                'number_of_page': '8',
                'y': '560'
            },
            {
                # Bourgogne-Franche-Comté
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Bourgogne-Franche-Comt%C3%A9&idOu=R27&proximite=0&quoiQuiInterprete=achat%20or&contexte=H/dBBw%2BSq0qEv5VDHuPwvA%3D%3D&page=',
                'number_of_page': '3',
                'y': '560'
            },
            {
                # Bretagne
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Bretagne&idOu=R53&proximite=0&quoiQuiInterprete=achat%20or&contexte=N7VOEakOWYk4AvMbZX4rSQ%3D%3D&page=',
                'number_of_page': '3',
                'y': '560'
            },
            {
                # Centre-Val-de-Loire
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Centre-Val-de-Loire&proximite=0&quoiQuiInterprete=achat%20or&contexte=8nd4dT9dfMRkU4OkQWzieg%3D%3D&idOu=R24&page=',
                'number_of_page': '4',
                'y': '560'
            },
            {
                # Corse
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Corse&idOu=R94&proximite=0&quoiQuiInterprete=achat%20or&contexte=XGmYCgCx3RM3Kz7RzrZsBA%3D%3D&page=',
                'number_of_page': '4',
                'y': '560'
            },
            {
                # Grand-Est
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Grand-Est&proximite=0&quoiQuiInterprete=achat%20or&contexte=pEuB5H3TH6hxsFyxa4h50A%3D%3D&idOu=R44&page=',
                'number_of_page': '5',
                'y': '560'
            },
            {
                # Hauts-de-France
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Hauts-de-France&idOu=R32&proximite=0&quoiQuiInterprete=achat%20or&contexte=LnTHcMriHJQbbenO3wb9oA%3D%3D&page=',
                'number_of_page': '5',
                'y': '560'
            },
            {
                # Ile-de-France
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Ile-de-France&idOu=R11&proximite=0&quoiQuiInterprete=achat%20or&contexte=M2Hsy261NCjEa%2B0ILFz7Gg%3D%3D&page=',
                'number_of_page': '10',
                'y': '560'
            },
            {
                # Normandie
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Normandie&idOu=R28&proximite=0&quoiQuiInterprete=achat%20or&contexte=fp%2BfjxxH5jnwFLRrgtHqRg%3D%3D&page=',
                'number_of_page': '3',
                'y': '560'
            },
            {
                # Nouvelle-Aquitaine
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Nouvelle-Aquitaine&idOu=R75&proximite=0&quoiQuiInterprete=achat%20or&contexte=Qkrxiw/ZCb62tUa6IJPpDA%3D%3D&page=',
                'number_of_page': '9',
                'y': '560'
            },
            {
                # Occitanie
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Occitanie&idOu=R76&proximite=0&quoiQuiInterprete=achat%20or&contexte=tEdSPboj15xgSYPZHYeV5A%3D%3D&page=',
                'number_of_page': '9',
                'y': '560'
            },
            {
                # Pays%20de%20la%20Loire
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Pays%20de%20la%20Loire&proximite=0&quoiQuiInterprete=achat%20or&contexte=57tiCDeURWn8/5U5yFtaaA%3D%3D&idOu=R52&page=',
                'number_of_page': '4',
                'y': '560'
            },
            {
                # Provence-Alpes-Côte-d%27Azur
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Provence-Alpes-C%C3%B4te-d%27Azur&idOu=R93&proximite=0&quoiQuiInterprete=achat%20or&contexte=0pFDpjwvyqlzf88XtJ/uvw%3D%3D&page=',
                'number_of_page': '10'
            },
            {
                # Guadeloupe
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Guadeloupe%20%28971%29&idOu=D971&proximite=0&quoiQuiInterprete=achat%20or&contexte=q2ZP8zvBNHds6bGgkXGQtg%3D%3D&page=',
                'number_of_page': '5',
                'y': '560'
            },
            {
                # Martinique
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Martinique%20%28972%29&idOu=D972&proximite=0&quoiQuiInterprete=achat%20or&contexte=QYMAchgMrwtv1rieKfg0/g%3D%3D&page=',
                'number_of_page': '3',
                'y': '560'
            },
            {
                # Guyane
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=Guyane%20%28973%29&idOu=D973&proximite=0&quoiQuiInterprete=achat%20or&contexte=Q5laNK8vzizaZGaPg/BWsw%3D%3D&page=',
                'number_of_page': '2',
                'y': '560'
            },
            {
                # La%20Réunion%20%28974%29
                'contact':
                'https://www.pagesjaunes.fr/annuaire/chercherlespros?quoiqui=achat%20or&ou=La%20R%C3%A9union%20%28974%29&idOu=D974&proximite=0&quoiQuiInterprete=achat%20or&contexte=HnWcSpZ6Kq/oerlH1nox1w%3D%3D&page=',
                'number_of_page': '7',
                'y': '560'
            },
            {
                # Mayotte
                'contact':
                'https://www.pagesjaunes.fr/recherche/departement/mayotte-976/achat-or?quoiqui=achat+or&ou=Mayotte+%28976%29&univers=pagesjaunes&idOu=D976&ouSaisi=Mayotte&ouNbCar=7&acOuSollicitee=1&rangOu=2&sourceOu=HISTORIQUE&typeOu=Departement&nbPropositionOuTop=4&nbPropositionOuHisto=1&acQuiQuoiSollicitee=0&nbPropositionQuiQuoiTop=0&nbPropositionQuiQuoiHisto=0&nbPropositionQuiQuoiGeo=0&quiQuoiSaisi=achat+or&page=',
                'number_of_page': '1',
                'y': '560'
            }
        ]

        for contact in contacts:
            for x in range(1, int(contact.get('number_of_page')) + 1):
                url_page = ''

                url = contact.get('contact') + str(x)

                html = requests.get(url)

                time.sleep(5)

                print('url result : ' + url)

                # Parse the content of html_doc
                soup = BeautifulSoup(html.content, 'html.parser')

                if soup.find("section", {"id": "listResults"}) is not None:

                    all_article = soup.select_one("#listResults").find_all(
                        'li')

                    for article in all_article:
                        if article.find("li",
                                        {"class": "SEL-email"}) is not None:
                            if article.find(
                                    "h3",
                                {"class": "company-name noTrad"}) is not None:
                                if article.find("h3", {
                                        "class": "company-name noTrad"
                                }).select("a")[0].get('href') == "#":
                                    json_bloc = json.loads(
                                        article.get('data-pjtoggleclasshisto'))

                                    bloc_id = json_bloc["idbloc"]["id_bloc"]

                                    no_sequence = json_bloc["idbloc"][
                                        "no_sequence"]

                                    json_code_rubrique = json.loads(
                                        article.select("div")[0].get(
                                            'data-pjinfosaccengage-rmk-connexefd-'
                                            + bloc_id.lower()))

                                    code_rubrique = json_code_rubrique[
                                        "kAN9ProToUserInfo"]

                                    url_page += 'https://www.pagesjaunes.fr/pros/detail?bloc_id=' + bloc_id + \
                                              '&no_sequence=' + no_sequence + '&code_rubrique=' + code_rubrique

                                else:
                                    url_page += 'https://www.pagesjaunes.fr' + \
                                                article.find(
                                                  "h3", {"class": "company-name noTrad"}).select("a")[0].get('href')

                                print(url_page)

                                # Ouvrir l'application Google Chrome
                                app.start(
                                    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
                                )

                                time.sleep(7)

                                pywinauto.keyboard.send_keys(url_page)

                                time.sleep(3)

                                # Press the 'Enter' button
                                pywinauto.keyboard.send_keys('{ENTER}')

                                time.sleep(7)

                                # Scroll down Demande d'informations
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')

                                time.sleep(4)

                                # Move the mouse to the 'Contacter par mail' button
                                # Click the 'Contacter par mail' button
                                pywinauto.mouse.click(
                                    button='left',
                                    coords=(300, int(contact.get('y'))))

                                time.sleep(4)

                                # Move the mouse to the 'Nom' textbox
                                # Click on the 'Nom'
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 250))

                                time.sleep(4)

                                # Write my name in the 'Nom' textbox
                                my_name = ""
                                pywinauto.keyboard.send_keys(my_name)

                                time.sleep(4)

                                # Move the mouse to the 'Email' textbox
                                # Click on the 'Email' textbox
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 340))

                                time.sleep(4)

                                # Write my name in the 'Email' textbox
                                my_email = ""
                                pywinauto.keyboard.send_keys(my_email)

                                time.sleep(4)

                                # Move the mouse to the 'Objet du message' textbox
                                # Click on the 'Objet du message' textbox
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 500))

                                time.sleep(4)

                                # Write my name in the 'Objet du message' textbox
                                my_subject = ""
                                pywinauto.keyboard.send_keys(my_subject)

                                time.sleep(4)

                                # Move the mouse to the 'Message' textbox
                                # Click on the 'Objet du message' textbox
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 600))

                                time.sleep(4)

                                # Write my name in the 'Message' textbox
                                my_message = ("")
                                pywinauto.keyboard.send_keys(my_message)

                                time.sleep(4)

                                # Tab
                                pywinauto.keyboard.send_keys('{VK_TAB 2}')

                                time.sleep(4)

                                # Click on the 'Recevoir une copie du message' button
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 370))

                                time.sleep(4)

                                # Click on the 'Envoyer' button
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 440))

                                time.sleep(4)

                                # Close an active window with Alt+F4
                                pywinauto.keyboard.send_keys('%{F4}')
Пример #53
0
class ListBoxTestCases(unittest.TestCase):

    """Unit tests for the ListBoxWrapper class"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        _set_timings_fast()

        self.app = Application()

        app_path = os.path.join(MFC_tutorial_folder, "MFC_Tutorial9.exe")
        self.app.start(app_path)

        self.dlg = self.app.MFC_Tutorial9
        self.dlg.Wait('ready', timeout=20)
        self.dlg.TypeYourTextEdit.type_keys('qqq')
        self.dlg.Add.Click()

        self.dlg.TypeYourTextEdit.Select()
        self.dlg.TypeYourTextEdit.type_keys('123')
        self.dlg.Add.Click()

        self.dlg.TypeYourTextEdit.Select()
        self.dlg.TypeYourTextEdit.type_keys('third item', with_spaces=True)
        self.dlg.Add.Click()

        self.ctrl = self.dlg.ListBox.WrapperObject()

    def tearDown(self):
        "Close the application after tests"

        #self.dlg.Cancel.Click()

        # close the application
        self.app.kill_()

    def testGetProperties(self):
        "Test getting the properties for the list box control"
        props = self.ctrl.GetProperties()

        self.assertEquals(
            "ListBox", props['friendly_class_name'])

        self.assertEquals(
            self.ctrl.texts(), props['texts'])

        for prop_name in props:
            self.assertEquals(
                getattr(self.ctrl, prop_name)(), props[prop_name])

    def testItemCount(self):
        "test that the count of items is correct"
        self.assertEquals(self.ctrl.ItemCount(), 3)

    def testItemData(self):
        "For the moment - just test that it does not raise"
        self.ctrl.ItemData(1)
        self.ctrl.ItemData(self.ctrl.ItemCount() - 1)

    def testSelectedIndices(self):
        "test that the selected indices are correct"
        self.assertEquals(self.ctrl.SelectedIndices(), (-1,))
        self.ctrl.Select(2)
        self.assertEquals(self.ctrl.SelectedIndices(), (2, ))

        self.assertTrue(isinstance(self.ctrl.SelectedIndices(), tuple))

    def testSelect(self):
        "Test selecting an item"
        self.ctrl.Select(1)
        self.assertEquals(self.ctrl.SelectedIndices(), (1, ))

        # get the text of the 2nd item (3rd item in list
        # because of empty window_text)
        item_to_select = self.ctrl.texts()[2]

        self.ctrl.Select(item_to_select)
        self.assertEquals(self.ctrl.SelectedIndices(), (1, ))

    def testGetSetItemFocus(self):
        "Test setting and getting the focus of a particular item"
        self.ctrl.SetItemFocus(0)
        self.assertEquals(self.ctrl.GetItemFocus(), 0)

        self.ctrl.SetItemFocus(2)
        self.assertEquals(self.ctrl.GetItemFocus(), 2)
Пример #54
0
class NotepadRegressionTests(unittest.TestCase):
    """Regression unit tests for Notepad"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Fast()

        self.app = Application()
        self.app.start(_notepad_exe())

        self.dlg = self.app.Window_(title='Untitled - Notepad',
                                    class_name='Notepad')
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)
        self.dlg.Edit.SetEditText("Here is some text\r\n and some more")

        self.app2 = Application().start(_notepad_exe())

    def tearDown(self):
        """Close the application after tests"""
        try:
            self.dlg.Close(0.5)
            if self.app.Notepad["Do&n't Save"].Exists():
                self.app.Notepad["Do&n't Save"].Click()
                self.app.Notepad["Do&n't Save"].WaitNot('visible')
        except Exception:  # TimeoutError:
            pass
        finally:
            self.app.kill_()
        self.app2.kill_()

    def testMenuSelectNotepad_bug(self):
        """In notepad - MenuSelect Edit->Paste did not work"""
        text = b'Here are some unicode characters \xef\xfc\r\n'
        self.app2.UntitledNotepad.Edit.Wait('enabled')
        time.sleep(0.3)
        self.app2.UntitledNotepad.Edit.SetEditText(text)
        time.sleep(0.3)
        self.assertEquals(
            self.app2.UntitledNotepad.Edit.TextBlock().encode(
                locale.getpreferredencoding()), text)

        Timings.after_menu_wait = .7
        self.app2.UntitledNotepad.MenuSelect("Edit->Select All")
        time.sleep(0.3)
        self.app2.UntitledNotepad.MenuSelect("Edit->Copy")
        time.sleep(0.3)
        self.assertEquals(
            clipboard.GetData().encode(locale.getpreferredencoding()), text)

        self.dlg.set_focus()
        self.dlg.MenuSelect("Edit->Select All")
        self.dlg.MenuSelect("Edit->Paste")
        self.dlg.MenuSelect("Edit->Paste")
        self.dlg.MenuSelect("Edit->Paste")

        self.app2.UntitledNotepad.MenuSelect("File->Exit")
        self.app2.Window_(title='Notepad',
                          class_name='#32770')["Don't save"].Click()

        self.assertEquals(
            self.dlg.Edit.TextBlock().encode(locale.getpreferredencoding()),
            text * 3)
Пример #55
0
def start_application(application_path):
    app = Application(backend="uia")
    app.start(application_path)

    return app
Пример #56
0
class ComboBoxTestCases(unittest.TestCase):

    """Unit tests for the ComboBoxWrapper class"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        _set_timings_fast()

        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl2.exe"))
        self.app.Common_Controls_Sample.TabControl.Select("CSpinButtonCtrl")

        self.ctrl = self.app.Common_Controls_Sample.AlignmentComboBox.WrapperObject()

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testGetProperties(self):
        "Test getting the properties for the combobox control"
        props = self.ctrl.GetProperties()

        self.assertEquals(
            "ComboBox", props['friendly_class_name'])

        self.assertEquals(
            self.ctrl.texts(), props['texts'])

        for prop_name in props:
            self.assertEquals(
                getattr(self.ctrl, prop_name)(), props[prop_name])

    def testItemCount(self):
        "Test that ItemCount returns the correct number of items"
        self.assertEquals(self.ctrl.ItemCount(), 3)

    def testDroppedRect(self):
        "Test that the dropped rect is correct"
        rect = self.ctrl.DroppedRect()
        #import pdb;pdb.set_trace()
        self.assertEquals(rect.left, 0)
        self.assertEquals(rect.top, 0)
        self.assertEquals(rect.right, self.ctrl.ClientRect().right)
        self.assertEquals(rect.bottom, self.ctrl.rectangle().height() + 48)

    def testSelectedIndex(self):
        "That the control returns the correct index for the selected item"
        self.ctrl.Select(1)
        self.assertEquals(self.ctrl.SelectedIndex(), 1)
        #self.assertEquals(self.ctrl.texts()[3], self.app.Font.Edit2.texts()[1])

    def testSelect_negative(self):
        "Test that the Select method correctly handles negative indices"
        self.ctrl.Select(-1)
        self.assertEquals(self.ctrl.SelectedIndex(), 2)

    def testSelect_toohigh(self):
        "Test that the Select correctly raises if the item is too high"
        self.assertRaises(IndexError, self.ctrl.Select, 211)

    def testSelect_string(self):
        "Test that we can select based on a string"
        self.ctrl.Select(0)
        self.assertEquals(self.ctrl.SelectedIndex(), 0)
        self.ctrl.Select("Left (UDS_ALIGNLEFT)")
        self.assertEquals(self.ctrl.SelectedIndex(), 1)
        self.assertEquals(self.ctrl.SelectedText(), "Left (UDS_ALIGNLEFT)")

        # now do it with a typo
        self.assertRaises(ValueError, self.ctrl.Select, "Right (UDS_ALIGNRIGT)")

    def testSelect_simpleCombo(self):
        "Test selection for a simple combo"
        self.app.Common_Controls_Sample.OrientationComboBox.Select(0)
        self.assertEquals(self.app.Common_Controls_Sample.OrientationComboBox.SelectedIndex(), 0)
        self.app.Common_Controls_Sample.OrientationComboBox.Select(1)
        self.assertEquals(self.app.Common_Controls_Sample.OrientationComboBox.SelectedIndex(), 1)

    def testItemData(self):
        "Test that it doesn't raise"
        self.ctrl.ItemData(0)
        self.ctrl.ItemData(1)
        self.ctrl.ItemData("Right (UDS_ALIGNRIGHT)")
        self.ctrl.ItemData(self.ctrl.ItemCount() - 1)
Пример #57
0
    def test_click_on_button_email_without_opencv_3(self):
        app = Application(backend="uia")

        contacts = [{
            'contact': '',
            'number_of_page': ''
        }, {
            'contact': '',
            'number_of_page': ''
        }, {
            'contact': '',
            'number_of_page': ''
        }]

        for contact in contacts:
            for x in range(1, int(contact.get('number_of_page')) + 1):
                url_page = ''

                url = contact.get('contact') + str(x)

                html = requests.get(url)

                time.sleep(5)

                print('url : ' + str(x))

                # Parse the content of html_doc
                soup = BeautifulSoup(html.content, 'html.parser')

                if soup.find("section", {"id": "listResults"}) is not None:
                    all_article = soup.select("#listResults")[0].find_all(
                        'article')

                    for article in all_article:
                        if article.find("a", {"title": "E-Mail"}) is not None:
                            if article.find(
                                    "h2",
                                {"class": "company-name noTrad"}) is not None:
                                if article.find("h2", {
                                        "class": "company-name noTrad"
                                }).select("a")[0].get('href') == "#":
                                    json_bloc = json.loads(
                                        article.get('data-pjtoggleclasshisto'))
                                    bloc_id = json_bloc["idbloc"]["id_bloc"]
                                    no_sequence = json_bloc["idbloc"][
                                        "no_sequence"]

                                    json_code_rubrique = json.loads(
                                        article.select("div")[0].get(
                                            'data-pjinfosaccengage-rmk-connexefd-'
                                            + bloc_id.lower()))
                                    code_rubrique = json_code_rubrique[
                                        "kAN9ProToUserInfo"]

                                    url_page += 'https://www.pagesjaunes.fr/pros/detail?bloc_id=' + bloc_id + \
                                              '&no_sequence=' + no_sequence + '&code_rubrique=' + code_rubrique

                                else:
                                    url_page += 'https://www.pagesjaunes.fr' + \
                                                article.find(
                                                  "h2", {"class": "company-name noTrad"}).select("a")[0].get('href')

                                # Ouvrir l'application Google Chrome
                                app.start(
                                    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
                                )

                                time.sleep(7)

                                print(url_page)

                                pywinauto.keyboard.send_keys(url_page)

                                time.sleep(3)

                                # Press the 'Enter' button
                                pywinauto.keyboard.send_keys('{ENTER}')

                                time.sleep(7)

                                # Scroll down Demande d'informations
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')
                                time.sleep(1)
                                pywinauto.keyboard.send_keys('{DOWN}')

                                time.sleep(4)

                                # Move the mouse to the 'Contacter par mail' button
                                # Click the 'Contacter par mail' button
                                # pywinauto.mouse.click(button='left', coords=(300, 460))
                                # pywinauto.mouse.click(button='left', coords=(300, 510))
                                pywinauto.mouse.click(button='left',
                                                      coords=(300, 610))
                                # pywinauto.mouse.click(button='left', coords=(300, 600))
                                # pywinauto.mouse.click(button='left', coords=(300, 555))
                                # pywinauto.mouse.click(button='left', coords=(300, 590))

                                time.sleep(4)

                                # Move the mouse to the 'Nom' textbox
                                # Click on the 'Nom'
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 250))

                                time.sleep(4)

                                # Write my name in the 'Nom' textbox
                                myName = ""
                                pywinauto.keyboard.send_keys(myName)

                                time.sleep(4)

                                # Move the mouse to the 'Email' textbox
                                # Click on the 'Email' textbox
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 340))

                                time.sleep(4)

                                # Write my name in the 'Email' textbox
                                myEmail = ""
                                pywinauto.keyboard.send_keys(myEmail)

                                time.sleep(4)

                                # Move the mouse to the 'Objet du message' textbox
                                # Click on the 'Objet du message' textbox
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 500))

                                time.sleep(4)

                                # Write my name in the 'Objet du message' textbox
                                mySubject = ""
                                pywinauto.keyboard.send_keys(mySubject)

                                time.sleep(4)

                                # Move the mouse to the 'Message' textbox
                                # Click on the 'Objet du message' textbox
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 600))

                                time.sleep(4)

                                # Write my name in the 'Message' textbox
                                myMessage = ("")
                                pywinauto.keyboard.send_keys(myMessage)

                                time.sleep(4)

                                # Tab
                                pywinauto.keyboard.send_keys('{VK_TAB 2}')

                                time.sleep(4)

                                # Click on the 'Recevoir une copie du message' button
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 370))

                                time.sleep(4)

                                # Click on the 'Envoyer' button
                                pywinauto.mouse.click(button='left',
                                                      coords=(600, 440))

                                time.sleep(4)

                                # Close an active window with Alt+F4
                                pywinauto.keyboard.send_keys('%{F4}')