Example #1
0
 def testWaitCPUUsageLower(self):
     if is_x64_Python() != is_x64_OS():
         return None
     
     app = Application().Start(r'explorer.exe')
     WaitUntil(30, 0.5, lambda: len(findwindows.find_windows(active_only=True, class_name='CabinetWClass')) > 0)
     handle = findwindows.find_windows(active_only=True, class_name='CabinetWClass')[-1]
     window = WindowSpecification({'handle': handle, })
     explorer = Application().Connect(process=window.ProcessID())
     
     try:
         window.AddressBandRoot.ClickInput(double=True)
         window.Edit.SetEditText(r'Control Panel\Programs\Programs and Features')
         window.TypeKeys(r'{ENTER 2}', set_foreground=False)
         WaitUntil(30, 0.5, lambda: len(findwindows.find_windows(active_only=True, title='Programs and Features', class_name='CabinetWClass')) > 0)
         explorer.WaitCPUUsageLower(threshold=2.5, timeout=40, usage_interval=2)
         installed_programs = window.FolderView.Texts()[1:]
         programs_list = ','.join(installed_programs)
         if ('Microsoft' not in programs_list) and ('Python' not in programs_list):
             HwndWrapper.ImageGrab.grab().save(r'explorer_screenshot.jpg')
         HwndWrapper.ActionLogger().log('\ninstalled_programs:\n')
         for prog in installed_programs:
             HwndWrapper.ActionLogger().log(prog)
         self.assertEqual(('Microsoft' in programs_list) or ('Python' in programs_list), True)
     finally:
         window.Close(2.0)
Example #2
0
    def test__init__(self):
        "Test creating a new spec by hand"

        wspec = WindowSpecification(
            dict(best_match=u"UntitledNotepad", process=self.app.process))

        self.assertEquals(wspec.WindowText(), u"Untitled - Notepad")
    def test__init__(self):
        """Test creating a new spec by hand"""
        wspec = WindowSpecification(
            dict(
                best_match = u"UntitledNotepad",
                process = self.app.process)
            )

        self.assertEquals(
            wspec.window_text(),
            u"Untitled - Notepad")
Example #4
0
    def test__call__(self):
        """Test that __call__() correctly raises an error"""
        self.assertRaises(AttributeError, self.dlgspec)
        self.assertRaises(AttributeError, self.ctrlspec)

        # no best_match!
        wspec = WindowSpecification(
            dict(title=u"blah", process=self.app.process))

        self.assertRaises(AttributeError, wspec)
Example #5
0
    def __init__(self, criteria, actions=None, timeout=None):
        """ Class Initialization.

        Parameters
        ----------
        criteria: dict
            The criteria to use to find the window (please see
            :class:`~pywinauto.application.WindowSpecification`).
        actions: dict
            The set of actions that can be performed along with the keyboard
            actions that are required to achieve that goal.
        timeout: int
            The standard timeout in seconds to use on the basic operations
            such as waiting for focus update or closing the window. The value
            can be overridden in some of the methods.

        """
        from pywinauto.application import WindowSpecification

        self.window_spec = WindowSpecification(criteria)
        self.actions = {} if actions is None else actions
        self.timeout = timeout
    def test_wait_cpu_usage_lower(self):
        """Test that wait_cpu_usage_lower() works correctly"""
        if is_x64_Python() != is_x64_OS():
            return None
        
        app = Application().Start(r'explorer.exe')
        
        def _cabinetwclass_exist():
            "Verify if at least one active 'CabinetWClass' window is created"
            l = findwindows.find_elements(active_only = True, class_name = 'CabinetWClass')
            return (len(l) > 0)

        WaitUntil(40, 0.5, _cabinetwclass_exist)
        handle = findwindows.find_elements(active_only = True, class_name = 'CabinetWClass')[-1].handle
        window = WindowSpecification({'handle': handle, 'backend': 'native', })
        explorer = Application().Connect(process = window.process_id())
        
        try:
            explorer.WaitCPUUsageLower(threshold = 1.5, timeout = 60, usage_interval = 2)
            window.AddressBandRoot.ClickInput()
            window.TypeKeys(r'Control Panel\Programs\Programs and Features', with_spaces=True, set_foreground=True)
            window.TypeKeys(r'{ENTER}', set_foreground = False)
            WaitUntil(40, 0.5, lambda: len(findwindows.find_elements(active_only = True,
                                                                     title = 'Programs and Features',
                                                                     class_name='CabinetWClass')) > 0)
            explorer.WaitCPUUsageLower(threshold = 1.5, timeout = 60, usage_interval = 2)
            installed_programs = window.FolderView.texts()[1:]
            programs_list = ','.join(installed_programs)
            if ('Microsoft' not in programs_list) and ('Python' not in programs_list):
                HwndWrapper.ImageGrab.grab().save(r'explorer_screenshot.jpg')
                HwndWrapper.ActionLogger().log('\ninstalled_programs:\n')
                for prog in installed_programs:
                    HwndWrapper.ActionLogger().log(prog)
            self.assertEqual(('Microsoft' in programs_list) or ('Python' in programs_list), True)
        finally:
            window.Close(2.0)
Example #7
0
    def test_wait_cpu_usage_lower(self):
        """Test that wait_cpu_usage_lower() works correctly"""
        if is_x64_Python() != is_x64_OS():
            return None

        Application().Start(r'explorer.exe')

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

        WaitUntil(40, 0.5, _cabinetwclass_exist)
        handle = findwindows.find_elements(
            active_only=True, class_name='CabinetWClass')[-1].handle
        window = WindowSpecification({
            'handle': handle,
            'backend': 'win32',
        })
        explorer = Application().Connect(process=window.process_id())

        try:
            explorer.WaitCPUUsageLower(threshold=1.5,
                                       timeout=60,
                                       usage_interval=2)
            window.AddressBandRoot.ClickInput()
            window.TypeKeys(r'Control Panel\Programs\Programs and Features',
                            with_spaces=True,
                            set_foreground=True)
            window.TypeKeys(r'{ENTER}', set_foreground=False)
            WaitUntil(
                40, 0.5, lambda: len(
                    findwindows.find_elements(active_only=True,
                                              title='Programs and Features',
                                              class_name='CabinetWClass')) > 0)
            explorer.WaitCPUUsageLower(threshold=1.5,
                                       timeout=60,
                                       usage_interval=2)
            installed_programs = window.FolderView.texts()[1:]
            programs_list = ','.join(installed_programs)
            if ('Microsoft' not in programs_list) and ('Python'
                                                       not in programs_list):
                hwndwrapper.ImageGrab.grab().save(r'explorer_screenshot.jpg')
                hwndwrapper.ActionLogger().log('\ninstalled_programs:\n')
                for prog in installed_programs:
                    hwndwrapper.ActionLogger().log(prog)
            self.assertEqual(('Microsoft' in programs_list)
                             or ('Python' in programs_list), True)
        finally:
            window.Close(2.0)
Example #8
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(_ready_timeout, _retry_interval, _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.Wait("ready", timeout=_ready_timeout)
        window.AddressBandRoot.ClickInput()
        window.TypeKeys(
                    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.TypeKeys(
                    '{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.ClickInput()
        notif_area.Ok.ClickInput()
        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
Example #9
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"
    """

    Application().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)

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

    try:
        # Go to "Control Panel -> Notification Area Icons"
        cmd_str = r'control /name Microsoft.NotificationAreaIcons'
        for _ in range(3):
            window.wait("ready", timeout=_ready_timeout)
            window.AddressBandRoot.click_input()
            explorer.wait_cpu_usage_lower(threshold=2, timeout=_ready_timeout)
            window.type_keys(cmd_str, with_spaces=True, set_foreground=True)
            # verfiy the text in the address combobox after type_keys finished
            cmbx_spec = window.AddressBandRoot.ComboBoxEx
            if cmbx_spec.exists(timeout=_ready_timeout, retry_interval=_retry_interval):
                texts = cmbx_spec.texts()
                if texts and texts[0] == cmd_str:
                    break
            # Send ESCs to remove the invalid text
            window.type_keys("{ESC}" * 3)

        # 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.wait_cpu_usage_lower(threshold=5, timeout=_ready_timeout)

        # Get the new opened applet
        notif_area = Desktop().window(title="Notification Area Icons",
                                      class_name=class_name)
        notif_area.wait("ready", timeout=_ready_timeout)
        cur_state = notif_area.CheckBox.get_check_state()

        # 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.wait_cpu_usage_lower(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
Example #10
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
Example #11
0
class WindowAssistant(object):
    """ Window assistant class.

    The WindowAssistant encloses the logic to find and simulate user
    interaction with an application window or dialog.

    """
    def __init__(self, criteria, actions=None, timeout=None):
        """ Class Initialization.

        Parameters
        ----------
        criteria: dict
            The criteria to use to find the window (please see
            :class:`~pywinauto.application.WindowSpecification`).
        actions: dict
            The set of actions that can be performed along with the keyboard
            actions that are required to achieve that goal.
        timeout: int
            The standard timeout in seconds to use on the basic operations
            such as waiting for focus update or closing the window. The value
            can be overridden in some of the methods.

        """
        from pywinauto.application import WindowSpecification

        self.window_spec = WindowSpecification(criteria)
        self.actions = {} if actions is None else actions
        self.timeout = timeout

    @property
    def window(self):
        """ Return the pywinauto wrapper object corresponding to the window
        handle.

        """
        return self.window_spec.WrapperObject()

    @property
    def title(self):
        """ Return the title of the window.
        """
        return self.window.WindowText()

    def invoke_action(self, action):
        """ Execute the action in the specified window.

        Parameters
        ----------
        action : str
            The action to simulate out of the self.actions dictionary

        """
        self.set_focus()
        self.type_key_sequence(self.actions[action])

    def set_focus(self, timeout=None):
        """ Focus the window.

        Parameters
        ----------
        timeout : int
            override the default timeout interval.

        """
        timeout = self.timeout if timeout is None else timeout
        self.window_spec.Wait('exists', timeout=timeout)
        self.window.SetFocus()
        self.window_spec.Wait('ready', timeout=timeout)

    def type_key_sequence(self, key_sequence, with_spaces=False):
        """ Send the key sequence in the Window.

        Parameters
        ----------
        key_sequence : str
            The key sequence (see SendKeys for more information).
        with_spaces :
            Add a space between each key

        .. note: The method does not change the current window focus.

        """
        self.window.TypeKeys(key_sequence, with_spaces=with_spaces)

    def click(self, button='left', position=(None, None)):
        """ Simulate a mouse click in the window.

        Parameter
        ---------
        button : str
            The 'left', 'right' or 'middle' mouse button to click.
        position : tuple
            The coordinates relative to top left corner of the window where
            the mouse click will take place.

        """
        self.set_focus()
        self.window.ClickInput(button=button, double=False, coords=position)

    def doubleclick(
            self,
            button='left',
            position=(None, None),
    ):
        """ Simulate a mouse double-click in the window area

        Parameter
        ---------
        button : str
            The 'left', 'right' or 'middle' mouse button to click.
        position : tuple
            The coordinates relative to top left corner of the window where
            the mouse click will take place.

        """
        self.set_focus()
        self.window.ClickInput(button=button, double=True, coords=position)

    def exists(self, timeout=None):
        """ Return true if the window exists.

        Parameter
        ---------
        timeout : int
            override the default timeout interval.

        """
        timeout = self.timeout if timeout is None else timeout
        return self.window_spec.Exists(timeout)

    def does_not_exist(self, timeout=None):
        """ Return true if the window does not exist.

        Parameter
        ---------
        timeout : int
            override the default timeout interval.

        """
        timeout = self.timeout if timeout is None else timeout
        try:
            self.window_spec.WaitNot('exists', timeout=timeout)
        except RuntimeError:
            return False
        return True

    def close(self, timeout=None):
        """ Closed the window.

        Parameter
        ---------
        timeout : int
            override the default timeout interval.

        """
        timeout = self.timeout if timeout is None else timeout
        self.window.Close()
        self.does_not_exist(timeout)
Example #12
0
def print_control_identifiers(self, depth=None, filename=None):
    WindowSpecification.print_control_identifiers(self,
                                                  depth=None,
                                                  filename=None)