示例#1
0
    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)
示例#2
0
 def is_checkbox(elem):
     res = False
     if elem.handle is None:
         return False
     hwwrp = HwndWrapper(elem.handle)
     if hwwrp.friendly_class_name() == u'CheckBox':
         if hwwrp.texts() == [u'Show']:
             res = True
     return res
示例#3
0
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.fast()

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

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.select('CButton (Command Link)')
        self.ctrl = HwndWrapper(self.dlg.Command_button_here.handle)
示例#4
0
 def open_focus(target, p_type='explorer'):
     try:
         HwndWrapper(find_window(title=ReportUtilities.base(target))).set_focus()
     except WindowNotFoundError:
         Popen('{process} "{path}"'.format(
             process=p_type,
             path=target)
         )
     except FileNotFoundError:
         print('File: {target} does not exist.'.format(target=target))
示例#5
0
class SendEnterKeyTest(unittest.TestCase):
    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):
        self.dlg.MenuSelect('File -> Exit')
        if self.dlg["Do&n't Save"].Exists():
            self.dlg["Do&n't Save"].Click()
        self.app.kill_()

    def test_sendEnterChar(self):
        self.ctrl.send_chars('Hello{ENTER}World')
        self.assertEquals(['Hello\r\nWorld'], self.dlg.Edit.Texts())
示例#6
0
class SendEnterKeyTest(unittest.TestCase):
    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):
        self.dlg.menu_select('File -> Exit')
        try:
            self.app.Notepad["Do&n't Save"].click()
        except findbestmatch.MatchError:
            self.app.kill()

    def test_sendEnterChar(self):
        self.ctrl.send_chars('Hello{ENTER}World')
        self.assertEqual('Hello\r\nWorld', self.dlg.Edit.window_text())
示例#7
0
    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.set_edit_text("Here is some text\r\n and some more")

        self.app2 = Application().start(_notepad_exe())
示例#8
0
    def test_scroll(self):
        """Test control scrolling"""
        self.dlg.TabControl.select('CNetworkAddressCtrl')
        ctrl = HwndWrapper(self.dlg.TypeListBox.handle)

        # Check exceptions on wrong arguments
        self.assertRaises(ValueError, ctrl.scroll, "bbbb", "line")
        self.assertRaises(ValueError, ctrl.scroll, "left", "aaaa")

        self.assertEqual(ctrl.item_rect(0).top, 0)
        ctrl.scroll('down', 'page', 2)
        self.assertEqual(ctrl.item_rect(0).top < -10, True)
示例#9
0
class HwndWrapperTests(unittest.TestCase):
    """Unit tests for the HwndWrapper class"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.fast()

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

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.select('CButton (Command Link)')
        self.ctrl = HwndWrapper(self.dlg.Command_button_here.handle)

        #self.dlg = self.app.Calculator
        #self.dlg.menu_select('View->Scientific\tAlt+2')
        #self.ctrl = HwndWrapper(self.dlg.Button2.handle) # Backspace

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

    def test_scroll(self):
        """Test control scrolling"""
        self.dlg.TabControl.select('CNetworkAddressCtrl')
        ctrl = HwndWrapper(self.dlg.TypeListBox.handle)

        # Check exceptions on wrong arguments
        self.assertRaises(ValueError, ctrl.scroll, "bbbb", "line")
        self.assertRaises(ValueError, ctrl.scroll, "left", "aaaa")

        self.assertEqual(ctrl.item_rect(0).top, 0)
        ctrl.scroll('down', 'page', 2)
        self.assertEqual(ctrl.item_rect(0).top < -10, True)

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

    def testFriendlyClassName(self):
        """Test getting the friendly classname of the control"""
        self.assertEqual(self.ctrl.friendly_class_name(), "Button")

    def testClass(self):
        """Test getting the classname of the control"""
        self.assertEqual(self.ctrl.class_name(), "Button")

    def testWindowText(self):
        """Test getting the window Text of the control"""
        self.assertEqual(
            HwndWrapper(self.dlg.Set.handle).window_text(), u'Set')

    def testStyle(self):
        self.dlg.style()
        self.assertEqual(
            self.ctrl.style(), win32defines.WS_CHILD | win32defines.WS_VISIBLE
            | win32defines.WS_TABSTOP | win32defines.BS_COMMANDLINK)

    def testExStyle(self):
        self.assertEqual(
            self.ctrl.exstyle(), win32defines.WS_EX_NOPARENTNOTIFY
            | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING
            | win32defines.WS_EX_RIGHTSCROLLBAR)

        #self.assertEqual(self.dlg.exstyle(),
        #    win32defines.WS_EX_WINDOWEDGE |
        #    win32defines.WS_EX_LEFT |
        #    win32defines.WS_EX_LTRREADING |
        #    win32defines.WS_EX_RIGHTSCROLLBAR |
        #    win32defines.WS_EX_CONTROLPARENT |
        #    win32defines.WS_EX_APPWINDOW)

    def testControlID(self):
        self.assertEqual(self.ctrl.control_id(), 1037)
        self.dlg.control_id()

    def testUserData(self):
        self.ctrl.user_data()
        self.dlg.user_data()

    def testContextHelpID(self):
        self.ctrl.context_help_id()
        self.dlg.context_help_id()

    def testIsVisible(self):
        self.assertEqual(self.ctrl.is_visible(), True)
        self.assertEqual(self.dlg.is_visible(), True)

    def testIsUnicode(self):
        self.assertEqual(self.ctrl.is_unicode(), True)
        self.assertEqual(self.dlg.is_unicode(), True)

    def testIsEnabled(self):
        self.assertEqual(self.ctrl.is_enabled(), True)
        self.assertEqual(self.dlg.is_enabled(), True)
        #self.assertEqual(self.dlg.Note.is_enabled(), False); # Button26 = '%'

    def testRectangle(self):
        """Test getting the rectangle of the dialog"""
        rect = self.dlg.rectangle()

        self.assertNotEqual(rect.top, None)
        self.assertNotEqual(rect.left, None)
        self.assertNotEqual(rect.bottom, None)
        self.assertNotEqual(rect.right, None)

        if abs(rect.height() - 423) > 5:
            self.assertEqual(rect.height(), 423)
        if abs(rect.width() - 506) > 5:
            self.assertEqual(rect.width(), 506)

    def testClientRect(self):
        rect = self.dlg.rectangle()
        cli = self.dlg.client_rect()

        self.assertEqual(cli.left, 0)
        self.assertEqual(cli.top, 0)

        assert (cli.width() < rect.width())
        assert (cli.height() < rect.height())

    def testFont(self):
        self.assertNotEqual(self.dlg.font(), self.ctrl.font())

    def testProcessID(self):
        self.assertEqual(self.ctrl.process_id(), self.dlg.process_id())
        self.assertNotEqual(self.ctrl.process_id(), 0)

    def testHasStyle(self):
        self.assertEqual(self.ctrl.has_style(win32defines.WS_CHILD), True)
        self.assertEqual(self.dlg.has_style(win32defines.WS_CHILD), False)

        self.assertEqual(self.ctrl.has_style(win32defines.WS_SYSMENU), False)
        self.assertEqual(self.dlg.has_style(win32defines.WS_SYSMENU), True)

    def testHasExStyle(self):
        self.assertEqual(
            self.ctrl.has_exstyle(win32defines.WS_EX_NOPARENTNOTIFY), True)
        self.assertEqual(
            self.dlg.has_exstyle(win32defines.WS_EX_NOPARENTNOTIFY), False)

        self.assertEqual(self.ctrl.has_exstyle(win32defines.WS_EX_APPWINDOW),
                         False)
        #self.assertEqual(self.dlg.has_exstyle(win32defines.WS_EX_APPWINDOW), True)

    def testIsDialog(self):
        self.assertEqual(self.ctrl.is_dialog(), False)
        self.assertEqual(self.dlg.is_dialog(), True)

    def testParent(self):
        self.assertEqual(self.ctrl.parent().parent(), self.dlg.handle)

    def testTopLevelParent(self):
        self.assertEqual(self.ctrl.top_level_parent(), self.dlg.handle)
        self.assertEqual(self.dlg.top_level_parent(), self.dlg.handle)

    def testTexts(self):
        self.assertEqual(self.dlg.texts(), ['Common Controls Sample'])
        self.assertEqual(HwndWrapper(self.dlg.Show.handle).texts(), [u'Show'])
        self.assertEqual(
            self.dlg.child_window(class_name='Button', found_index=2).texts(),
            [u'Elevation Icon'])

    def testFoundIndex(self):
        """Test an access to a control by found_index"""

        ctl = self.dlg.child_window(class_name='Button', found_index=3)
        self.assertEqual(ctl.texts(), [u'Show'])
        ctl.draw_outline('blue')  # visualize

        # Test an out-of-range access
        # Notice:
        # A ChildWindow call only creates a WindowSpecification object.
        # The exception is raised later when we try to find the window.
        # For this reason we can't use an assertRaises statement here because
        # the exception is raised before actual call to DrawOutline
        ctl = self.dlg.child_window(class_name='Button', found_index=3333)
        self.assertRaises(ElementNotFoundError, ctl.wrapper_object)

    def testSearchWithPredicateFunc(self):
        """Test an access to a control by filtering with a predicate function"""
        def is_checkbox(elem):
            res = False
            if elem.handle is None:
                return False
            hwwrp = HwndWrapper(elem.handle)
            if hwwrp.friendly_class_name() == u'CheckBox':
                if hwwrp.texts() == [u'Show']:
                    res = True
            return res

        ctl = self.dlg.child_window(predicate_func=is_checkbox)
        self.assertEqual(ctl.texts(), [u'Show'])
        ctl.draw_outline('red')  # visualize

    def testClientRects(self):
        self.assertEqual(self.ctrl.client_rects()[0], self.ctrl.client_rect())
        self.assertEqual(self.dlg.client_rects()[0], self.dlg.client_rect())

    def testFonts(self):
        self.assertEqual(self.ctrl.fonts()[0], self.ctrl.font())
        self.assertEqual(self.dlg.fonts()[0], self.dlg.font())

    def testChildren(self):
        self.assertEqual(self.ctrl.children(), [])
        self.assertNotEqual(self.dlg.children(), [])

    def testIsChild(self):
        self.assertEqual(self.ctrl.is_child(self.dlg.wrapper_object()), True)
        self.assertEqual(self.dlg.is_child(self.ctrl), False)

    def testSendMessage(self):
        vk = self.dlg.send_message(win32defines.WM_GETDLGCODE)
        self.assertEqual(0, vk)

        code = self.dlg.Edit.send_message(win32defines.WM_GETDLGCODE)
        # The expected return code is: "Edit" ? # "Button" = 0x2000 and "Radio" = 0x40
        expected = 0x89  # 0x2000 + 0x40
        self.assertEqual(expected, code)

    def test_send_chars(self):
        testString = "Hello World"

        self.dlg.minimize()
        self.dlg.Edit.send_chars(testString)

        actual = self.dlg.Edit.texts()[0]
        expected = "Hello World"
        self.assertEqual(expected, actual)

    def test_send_chars_invalid(self):
        with self.assertRaises(keyboard.KeySequenceError):
            testString = "Hello{LEFT 2}{DEL 2}"

            self.dlg.minimize()
            self.dlg.Edit.send_chars(testString)

    def test_send_keystrokes_multikey_characters(self):
        testString = "Hawaii#{%}@$"

        self.dlg.minimize()
        self.dlg.Edit.send_keystrokes(testString)

        actual = self.dlg.Edit.texts()[0]
        expected = "Hawaii#%@$"
        self.assertEqual(expected, actual)

    def test_send_keystrokes_enter(self):
        with self.assertRaises(findbestmatch.MatchError):
            testString = "{ENTER}"

            self.dlg.minimize()
            self.dlg.Edit.send_keystrokes(testString)

            self.dlg.restore()

    def test_send_keystrokes_virtual_keys_left_del_back(self):
        testString = "+hello123{LEFT 2}{DEL 2}{BACKSPACE} +world"

        self.dlg.minimize()
        self.dlg.Edit.send_keystrokes(testString)

        actual = self.dlg.Edit.texts()[0]
        expected = "Hello World"
        self.assertEqual(expected, actual)

    def test_send_keystrokes_virtual_keys_shift(self):
        testString = "+hello +world"

        self.dlg.minimize()
        self.dlg.Edit.send_keystrokes(testString)

        actual = self.dlg.Edit.texts()[0]
        expected = "Hello World"
        self.assertEqual(expected, actual)

    def test_send_keystrokes_virtual_keys_ctrl(self):
        testString = "^a^c{RIGHT}^v"

        self.dlg.minimize()
        self.dlg.Edit.send_keystrokes(testString)

        actual = self.dlg.Edit.texts()[0]
        expected = "and the note goes here ...and the note goes here ..."
        self.assertEqual(expected, actual)

    def testSendMessageTimeout(self):
        default_timeout = Timings.sendmessagetimeout_timeout
        Timings.sendmessagetimeout_timeout = 0.1
        vk = self.dlg.send_message_timeout(win32defines.WM_GETDLGCODE)
        self.assertEqual(0, vk)

        code = self.dlg.Show.send_message_timeout(win32defines.WM_GETDLGCODE)
        # The expected return code is: "Button" = 0x2000 # and "Radio" = 0x40
        expected = 0x2000  # + 0x40
        Timings.sendmessagetimeout_timeout = default_timeout
        self.assertEqual(expected, code)

    def testPostMessage(self):
        self.assertNotEqual(0, self.dlg.post_message(win32defines.WM_PAINT))
        self.assertNotEqual(0,
                            self.dlg.Show.post_message(win32defines.WM_PAINT))

#    def testNotifyMenuSelect(self):
#        "Call NotifyMenuSelect to ensure it does not raise"
#        self.ctrl.NotifyMenuSelect(1234)
#        self.dlg.NotifyMenuSelect(1234)

    def testNotifyParent(self):
        """Call notify_parent to ensure it does not raise"""
        self.ctrl.notify_parent(1234)
        #self.dlg.notify_parent(1234)

    def testGetProperties(self):
        """Test getting the properties for the HwndWrapped control"""
        props = self.dlg.get_properties()

        self.assertEqual(self.dlg.friendly_class_name(),
                         props['friendly_class_name'])

        self.assertEqual(self.dlg.texts(), props['texts'])

        for prop_name in props:
            self.assertEqual(getattr(self.dlg, prop_name)(), props[prop_name])

    def test_capture_as_image_multi_monitor(self):
        with mock.patch('win32api.EnumDisplayMonitors') as mon_device:
            mon_device.return_value = (1, 2)
            rect = self.dlg.rectangle()
            expected = (rect.width(), rect.height())
            result = self.dlg.capture_as_image().size
            self.assertEqual(expected, result)

    # def testDrawOutline(self):
    #     """Test the outline was drawn."""
    #     # make sure window is ready
    #     self.dlg.wait('active')
    #     self.dlg.Show.click()
    #
    #     # not sure why, but this extra call makes the test stable
    #     self.dlg.draw_outline()
    #
    #     # outline control
    #     self.dlg.Show.draw_outline()
    #     img1 = self.dlg.Show.capture_as_image()
    #     self.assertEqual(img1.getpixel((0, 0)), (0, 255, 0))  # green
    #
    #     # outline window
    #     self.dlg.draw_outline(colour="red")
    #     img2 = self.dlg.capture_as_image()
    #     self.assertEqual(img2.getpixel((0, 0)), (255, 0, 0))  # red

    def testEquals(self):
        self.assertNotEqual(self.ctrl, self.dlg.handle)
        self.assertEqual(self.ctrl, self.ctrl.handle)
        self.assertEqual(self.ctrl, self.ctrl)


#    def testVerifyActionable(self):

    def testMoveWindow_same(self):
        """Test calling movewindow without any parameters"""
        prevRect = self.dlg.rectangle()
        self.dlg.move_window()
        self.assertEqual(prevRect, self.dlg.rectangle())

    def testMoveWindow(self):
        """Test moving the window"""

        dlgClientRect = self.ctrl.parent().rectangle(
        )  # use the parent as a reference

        prev_rect = self.ctrl.rectangle() - dlgClientRect

        new_rect = win32structures.RECT(prev_rect)
        new_rect.left -= 1
        new_rect.top -= 1
        new_rect.right += 2
        new_rect.bottom += 2

        self.ctrl.move_window(
            new_rect.left,
            new_rect.top,
            new_rect.width(),
            new_rect.height(),
        )
        time.sleep(0.1)

        print('prev_rect = ', prev_rect)
        print('new_rect = ', new_rect)
        print('dlgClientRect = ', dlgClientRect)
        print('self.ctrl.rectangle() = ', self.ctrl.rectangle())
        self.assertEqual(self.ctrl.rectangle(), new_rect + dlgClientRect)

        self.ctrl.move_window(prev_rect)

        self.assertEqual(self.ctrl.rectangle(), prev_rect + dlgClientRect)

    def testMaximize(self):
        self.dlg.maximize()

        self.assertEqual(self.dlg.get_show_state(),
                         win32defines.SW_SHOWMAXIMIZED)
        self.dlg.restore()

    def testMinimize(self):
        self.dlg.minimize()
        self.assertEqual(self.dlg.get_show_state(),
                         win32defines.SW_SHOWMINIMIZED)
        self.dlg.restore()

    def testRestore(self):
        self.dlg.maximize()
        self.dlg.restore()
        self.assertEqual(self.dlg.get_show_state(), win32defines.SW_SHOWNORMAL)

        self.dlg.minimize()
        self.dlg.restore()
        self.assertEqual(self.dlg.get_show_state(), win32defines.SW_SHOWNORMAL)

    def testGetFocus(self):
        self.assertNotEqual(self.dlg.get_focus(), None)
        self.assertEqual(self.dlg.get_focus(), self.ctrl.get_focus())

        self.dlg.Set.set_focus()
        self.assertEqual(self.dlg.get_focus(), self.dlg.Set.handle)

    def test_issue_318(self):
        self.dlg.restore()
        self.dlg.minimize()
        self.dlg.set_focus()
        self.assertTrue(self.dlg.is_normal())
        self.assertTrue(self.dlg.is_active())

        self.dlg.maximize()
        self.dlg.minimize()
        self.dlg.set_focus()
        self.assertTrue(self.dlg.is_maximized())
        self.assertTrue(self.dlg.is_active())
        self.dlg.restore()

    def testSetFocus(self):
        self.assertNotEqual(self.dlg.get_focus(), self.dlg.Set.handle)
        self.dlg.Set.set_focus()
        self.assertEqual(self.dlg.get_focus(), self.dlg.Set.handle)

    def testHasKeyboardFocus(self):
        self.assertFalse(self.dlg.set.has_keyboard_focus())
        self.dlg.set.set_keyboard_focus()
        self.assertTrue(self.dlg.set.has_keyboard_focus())

    def testSetKeyboardFocus(self):
        self.assertNotEqual(self.dlg.get_focus(), self.dlg.set.handle)
        self.dlg.set.set_keyboard_focus()
        self.assertEqual(self.dlg.get_focus(), self.dlg.set.handle)

    def test_pretty_print(self):
        """Test __str__ method for HwndWrapper based controls"""
        if six.PY3:
            assert_regex = self.assertRegex
        else:
            assert_regex = self.assertRegexpMatches

        wrp = self.dlg.wrapper_object()
        assert_regex(
            wrp.__str__(),
            "^hwndwrapper.DialogWrapper - 'Common Controls Sample', Dialog$")
        assert_regex(
            wrp.__repr__(),
            "^<hwndwrapper.DialogWrapper - 'Common Controls Sample', Dialog, [0-9-]+>$"
        )

        wrp = self.ctrl
        assert_regex(
            wrp.__str__(),
            "^win32_controls.ButtonWrapper - 'Command button here', Button$")
        assert_regex(
            wrp.__repr__(),
            "^<win32_controls.ButtonWrapper - 'Command button here', Button, [0-9-]+>$"
        )

        wrp = self.dlg.TabControl.wrapper_object()
        assert_regex(wrp.__str__(),
                     "^common_controls.TabControlWrapper - '', TabControl$")
        assert_regex(
            wrp.__repr__(),
            "^<common_controls.TabControlWrapper - '', TabControl, [0-9-]+>$")

    def test_children_generator(self):
        dlg = self.dlg.wrapper_object()
        children = [child for child in dlg.iter_children()]
        self.assertSequenceEqual(dlg.children(), children)
示例#10
0
class HwndWrapperMouseTests(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().start(
            os.path.join(mfc_samples_folder, u"CmnCtrl3.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.select('CButton (Command Link)')
        self.ctrl = HwndWrapper(self.dlg.NoteEdit.handle)

    def tearDown(self):
        """Close the application after tests"""
        try:
            self.dlg.close(0.5)
        except Exception:  # TimeoutError:
            pass
        finally:
            self.app.kill()

    #def testText(self):
    #    "Test getting the window Text of the dialog"
    #    self.assertEqual(self.dlg.window_text(), "Untitled - Notepad")

    def testClick(self):
        self.ctrl.click(coords=(50, 5))
        self.assertEqual(self.dlg.Edit.selection_indices(), (9, 9))

    def testClickInput(self):
        self.ctrl.click_input(coords=(50, 5))
        self.assertEqual(self.dlg.Edit.selection_indices(), (9, 9))

    def testDoubleClick(self):
        self.ctrl.double_click(coords=(50, 5))
        self.assertEqual(self.dlg.Edit.selection_indices(), (8, 13))

    def testDoubleClickInput(self):
        self.ctrl.double_click_input(coords=(80, 5))
        self.assertEqual(self.dlg.Edit.selection_indices(), (13, 18))

#    def testRightClick(self):
#        pass

    def testRightClickInput(self):
        self.dlg.Edit.type_keys('{HOME}')
        self.dlg.Edit.wait('enabled').right_click_input()
        self.app.PopupMenu.wait('ready').menu().get_menu_path(
            'Select All')[0].click_input()
        self.dlg.Edit.type_keys('{DEL}')
        self.assertEqual(self.dlg.Edit.text_block(), '')

    def testPressMoveRelease(self):
        self.dlg.NoteEdit.press_mouse(coords=(0, 5))
        self.dlg.NoteEdit.move_mouse(coords=(65, 5))
        self.dlg.NoteEdit.release_mouse(coords=(65, 5))
        self.assertEqual(self.dlg.Edit.selection_indices(), (0, 12))

    def testDragMouse(self):
        self.dlg.NoteEdit.drag_mouse(press_coords=(0, 5),
                                     release_coords=(65, 5))
        self.assertEqual(self.dlg.Edit.selection_indices(), (0, 12))

        # continue selection with pressed Shift key
        self.dlg.NoteEdit.drag_mouse(press_coords=(65, 5),
                                     release_coords=(90, 5),
                                     pressed='shift')
        self.assertEqual(self.dlg.Edit.selection_indices(), (0, 17))

    def testDebugMessage(self):
        self.dlg.NoteEdit.debug_message('Test message')
        # TODO: add screenshots comparison

    #def testDrawOutline(self):
    #    # TODO: add screenshots comparison
    #    self.dlg.draw_outline()


#    def testSetWindowText(self):
#        pass
#
#    def testTypeKeys(self):
#        pass

    def testSetTransparency(self):
        self.dlg.set_transparency()
        self.assertRaises(ValueError, self.dlg.set_transparency, 256)
示例#11
0
 def testTexts(self):
     self.assertEqual(self.dlg.texts(), ['Common Controls Sample'])
     self.assertEqual(HwndWrapper(self.dlg.Show.handle).texts(), [u'Show'])
     self.assertEqual(
         self.dlg.child_window(class_name='Button', found_index=2).texts(),
         [u'Elevation Icon'])
示例#12
0
 def testWindowText(self):
     """Test getting the window Text of the control"""
     self.assertEqual(
         HwndWrapper(self.dlg.Set.handle).window_text(), u'Set')
示例#13
0
class HwndWrapperTests(unittest.TestCase):
    """Unit tests for the HwndWrapper class"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Fast()

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

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.Select('CButton (Command Link)')
        self.ctrl = HwndWrapper(self.dlg.Command_button_here.handle)

        #self.dlg = self.app.Calculator
        #self.dlg.MenuSelect('View->Scientific\tAlt+2')
        #self.ctrl = HwndWrapper(self.dlg.Button2.handle) # Backspace

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

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

    def testFriendlyClassName(self):
        "Test getting the friendly classname of the control"
        self.assertEquals(self.ctrl.friendly_class_name(), "Button")

    def testClass(self):
        "Test getting the classname of the control"
        self.assertEquals(self.ctrl.class_name(), "Button")

    def testWindowText(self):
        "Test getting the window Text of the control"
        self.assertEquals(
            HwndWrapper(self.dlg.Set.handle).window_text(), u'Set')

    def testStyle(self):

        self.dlg.Style()

        self.assertEquals(
            self.ctrl.Style(), win32defines.WS_CHILD | win32defines.WS_VISIBLE
            | win32defines.WS_TABSTOP | win32defines.BS_COMMANDLINK)

    def testExStyle(self):
        self.assertEquals(
            self.ctrl.ExStyle(), win32defines.WS_EX_NOPARENTNOTIFY
            | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING
            | win32defines.WS_EX_RIGHTSCROLLBAR)

        #self.assertEquals(self.dlg.ExStyle(),
        #    win32defines.WS_EX_WINDOWEDGE |
        #    win32defines.WS_EX_LEFT |
        #    win32defines.WS_EX_LTRREADING |
        #    win32defines.WS_EX_RIGHTSCROLLBAR |
        #    win32defines.WS_EX_CONTROLPARENT |
        #    win32defines.WS_EX_APPWINDOW)

    def testControlID(self):
        self.assertEquals(self.ctrl.control_id(), 1037)
        self.dlg.control_id()

    def testUserData(self):
        self.ctrl.UserData()
        self.dlg.UserData()

    def testContextHelpID(self):
        self.ctrl.ContextHelpID()
        self.dlg.ContextHelpID()

    def testIsVisible(self):
        self.assertEqual(self.ctrl.is_visible(), True)
        self.assertEqual(self.dlg.is_visible(), True)

    def testIsUnicode(self):
        self.assertEqual(self.ctrl.IsUnicode(), True)
        self.assertEqual(self.dlg.IsUnicode(), True)

    def testIsEnabled(self):
        self.assertEqual(self.ctrl.is_enabled(), True)
        self.assertEqual(self.dlg.is_enabled(), True)
        #self.assertEqual(self.dlg.Note.is_enabled(), False); # Button26 = '%'

    def testRectangle(self):
        "Test getting the rectangle of the dialog"
        rect = self.dlg.rectangle()

        self.assertNotEqual(rect.top, None)
        self.assertNotEqual(rect.left, None)
        self.assertNotEqual(rect.bottom, None)
        self.assertNotEqual(rect.right, None)

        if abs(rect.height() - 423) > 5:
            self.assertEqual(rect.height(), 423)
        if abs(rect.width() - 506) > 5:
            self.assertEqual(rect.width(), 506)

    def testClientRect(self):
        rect = self.dlg.rectangle()
        cli = self.dlg.ClientRect()

        self.assertEqual(cli.left, 0)
        self.assertEqual(cli.top, 0)

        assert (cli.width() < rect.width())
        assert (cli.height() < rect.height())

    def testFont(self):
        self.assertNotEqual(self.dlg.Font(), self.ctrl.Font())

    def testProcessID(self):
        self.assertEqual(self.ctrl.process_id(), self.dlg.process_id())
        self.assertNotEqual(self.ctrl.process_id(), 0)

    def testHasStyle(self):
        self.assertEqual(self.ctrl.HasStyle(win32defines.WS_CHILD), True)
        self.assertEqual(self.dlg.HasStyle(win32defines.WS_CHILD), False)

        self.assertEqual(self.ctrl.HasStyle(win32defines.WS_SYSMENU), False)
        self.assertEqual(self.dlg.HasStyle(win32defines.WS_SYSMENU), True)

    def testHasExStyle(self):
        self.assertEqual(
            self.ctrl.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), True)
        self.assertEqual(
            self.dlg.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), False)

        self.assertEqual(self.ctrl.HasExStyle(win32defines.WS_EX_APPWINDOW),
                         False)
        #self.assertEqual(self.dlg.HasExStyle(win32defines.WS_EX_APPWINDOW), True)

    def testIsDialog(self):
        self.assertEqual(self.ctrl.is_dialog(), False)
        self.assertEqual(self.dlg.is_dialog(), True)

    def testParent(self):
        self.assertEqual(self.ctrl.parent().parent(), self.dlg.handle)

    def testTopLevelParent(self):
        self.assertEqual(self.ctrl.top_level_parent(), self.dlg.handle)
        self.assertEqual(self.dlg.top_level_parent(), self.dlg.handle)

    def testTexts(self):
        self.assertEqual(self.dlg.texts(), ['Common Controls Sample'])
        self.assertEqual(HwndWrapper(self.dlg.Show.handle).texts(), [u'Show'])
        self.assertEqual(
            self.dlg.ChildWindow(class_name='Button', found_index=2).texts(),
            [u'Elevation Icon'])

    def testFoundIndex(self):
        "test an access to a control by found_index"

        ctl = self.dlg.ChildWindow(class_name='Button', found_index=3)
        self.assertEqual(ctl.texts(), [u'Show'])
        ctl.DrawOutline('blue')  # visualize

        # Test an out-of-range access
        # Notice:
        # A ChildWindow call only creates a WindowSpecification object.
        # The exception is raised later when we try to find the window.
        # For this reason we can't use an assertRaises statement here because
        # the exception is raised before actual call to DrawOutline
        ctl = self.dlg.ChildWindow(class_name='Button', found_index=3333)
        self.assertRaises(ElementNotFoundError, ctl.WrapperObject)

    def testSearchWithPredicateFunc(self):
        "test an access to a control by filtering with a predicate function"

        def is_checkbox(elem):
            res = False
            if elem.handle is None:
                return False
            hwwrp = HwndWrapper(elem.handle)
            if hwwrp.friendly_class_name() == u'CheckBox':
                if hwwrp.texts() == [u'Show']:
                    res = True
            return res

        ctl = self.dlg.ChildWindow(predicate_func=is_checkbox)
        self.assertEqual(ctl.texts(), [u'Show'])
        ctl.DrawOutline('red')  # visualize

    def testClientRects(self):
        self.assertEqual(self.ctrl.ClientRects()[0], self.ctrl.ClientRect())
        self.assertEqual(self.dlg.ClientRects()[0], self.dlg.ClientRect())

    def testFonts(self):
        self.assertEqual(self.ctrl.Fonts()[0], self.ctrl.Font())
        self.assertEqual(self.dlg.Fonts()[0], self.dlg.Font())

    def testChildren(self):
        self.assertEqual(self.ctrl.children(), [])
        self.assertNotEqual(self.dlg.children(), [])

    def testIsChild(self):
        self.assertEqual(self.ctrl.is_child(self.dlg.WrapperObject()), True)
        self.assertEqual(self.dlg.is_child(self.ctrl), False)

    def testSendMessage(self):
        vk = self.dlg.SendMessage(win32defines.WM_GETDLGCODE)
        self.assertEqual(0, vk)

        code = self.dlg.Edit.SendMessage(win32defines.WM_GETDLGCODE)
        # The expected return code is: "Edit" ? # "Button" = 0x2000 and "Radio" = 0x40
        expected = 0x89  # 0x2000 + 0x40
        self.assertEqual(expected, code)

    def test_send_chars_simple(self):
        testString = "Hello World"

        self.dlg.Minimize()
        self.dlg.Edit.send_chars(testString)

        actual = self.dlg.Edit.Texts()[0]
        expected = "Hello World"
        self.assertEqual(expected, actual)

    # def test_send_chars_enter(self):
    #     with self.assertRaises(findbestmatch.MatchError):
    #         testString = "{ENTER}"
    #
    #         self.dlg.Minimize()
    #         self.dlg.Edit.send_chars(testString)
    #
    #         actual = self.dlg.Edit.Texts()[0]

    def test_send_chars_virtual_keys_left_del_back(self):
        testString = "Hello123{LEFT 2}{DEL 2}{BACKSPACE} World"

        self.dlg.Minimize()
        self.dlg.Edit.send_chars(testString)

        actual = self.dlg.Edit.Texts()[0]
        expected = "Hello World"
        self.assertEqual(expected, actual)

    def test_send_chars_virtual_keys_shift(self):
        testString = "+hello +world"

        self.dlg.Minimize()
        self.dlg.Edit.send_chars(testString)

        actual = self.dlg.Edit.Texts()[0]
        expected = "Hello World"
        self.assertEqual(expected, actual)

    # def test_send_chars_virtual_keys_ctrl(self):
    #     testString = "^a^c{RIGHT}^v"
    #
    #     self.dlg.Minimize()
    #     self.dlg.Edit.send_chars(testString)
    #
    #     actual = self.dlg.Edit.Texts()[0]
    #     expected = "and the note goes here ...and the note goes here ..."
    #     self.assertEqual(expected, actual)

    def testSendMessageTimeout(self):
        default_timeout = Timings.sendmessagetimeout_timeout
        Timings.sendmessagetimeout_timeout = 0.1
        vk = self.dlg.SendMessageTimeout(win32defines.WM_GETDLGCODE)
        self.assertEqual(0, vk)

        code = self.dlg.Show.SendMessageTimeout(win32defines.WM_GETDLGCODE)
        # The expected return code is: "Button" = 0x2000 # and "Radio" = 0x40
        expected = 0x2000  #+ 0x40
        Timings.sendmessagetimeout_timeout = default_timeout
        self.assertEqual(expected, code)

    def testPostMessage(self):
        self.assertNotEquals(0, self.dlg.PostMessage(win32defines.WM_PAINT))
        self.assertNotEquals(0,
                             self.dlg.Show.PostMessage(win32defines.WM_PAINT))

#    def testNotifyMenuSelect(self):
#        "Call NotifyMenuSelect to ensure it does not raise"
#        self.ctrl.NotifyMenuSelect(1234)
#        self.dlg.NotifyMenuSelect(1234)

    def testNotifyParent(self):
        "Call NotifyParent to ensure it does not raise"
        self.ctrl.NotifyParent(1234)
        #self.dlg.NotifyParent(1234)

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

        self.assertEquals(self.dlg.friendly_class_name(),
                          props['friendly_class_name'])

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

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

#    def testCaptureAsImage(self):
#        pass

# def testDrawOutline(self):
#     """Test the outline was drawn."""
#     # make sure window is ready
#     self.dlg.Wait('active')
#     self.dlg.Show.Click()
#
#     # not sure why, but this extra call makes the test stable
#     self.dlg.draw_outline()
#
#     # outline control
#     self.dlg.Show.draw_outline()
#     img1 = self.dlg.Show.capture_as_image()
#     self.assertEqual(img1.getpixel((0, 0)), (0, 255, 0))  # green
#
#     # outline window
#     self.dlg.draw_outline(colour="red")
#     img2 = self.dlg.capture_as_image()
#     self.assertEqual(img2.getpixel((0, 0)), (255, 0, 0))  # red

    def testEquals(self):
        self.assertNotEqual(self.ctrl, self.dlg.handle)
        self.assertEqual(self.ctrl, self.ctrl.handle)
        self.assertEqual(self.ctrl, self.ctrl)


#    def testVerifyActionable(self):

    def testMoveWindow_same(self):
        "Test calling movewindow without any parameters"
        prevRect = self.dlg.rectangle()
        self.dlg.MoveWindow()
        self.assertEquals(prevRect, self.dlg.rectangle())

    def testMoveWindow(self):
        "Test moving the window"

        dlgClientRect = self.ctrl.parent().rectangle(
        )  # use the parent as a reference

        prev_rect = self.ctrl.rectangle() - dlgClientRect

        new_rect = win32structures.RECT(prev_rect)
        new_rect.left -= 1
        new_rect.top -= 1
        new_rect.right += 2
        new_rect.bottom += 2

        self.ctrl.MoveWindow(
            new_rect.left,
            new_rect.top,
            new_rect.width(),
            new_rect.height(),
        )
        time.sleep(0.1)

        print('prev_rect = ', prev_rect)
        print('new_rect = ', new_rect)
        print('dlgClientRect = ', dlgClientRect)
        print('self.ctrl.rectangle() = ', self.ctrl.rectangle())
        self.assertEquals(self.ctrl.rectangle(), new_rect + dlgClientRect)

        self.ctrl.MoveWindow(prev_rect)

        self.assertEquals(self.ctrl.rectangle(), prev_rect + dlgClientRect)

    def testMaximize(self):
        self.dlg.Maximize()

        self.assertEquals(self.dlg.GetShowState(),
                          win32defines.SW_SHOWMAXIMIZED)
        self.dlg.Restore()

    def testMinimize(self):
        self.dlg.Minimize()
        self.assertEquals(self.dlg.GetShowState(),
                          win32defines.SW_SHOWMINIMIZED)
        self.dlg.Restore()

    def testRestore(self):
        self.dlg.Maximize()
        self.dlg.Restore()
        self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL)

        self.dlg.Minimize()
        self.dlg.Restore()
        self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL)

    def testGetFocus(self):
        self.assertNotEqual(self.dlg.GetFocus(), None)
        self.assertEqual(self.dlg.GetFocus(), self.ctrl.GetFocus())

        self.dlg.Set.set_focus()
        self.assertEqual(self.dlg.GetFocus(), self.dlg.Set.handle)

    def testSetFocus(self):
        self.assertNotEqual(self.dlg.GetFocus(), self.dlg.Set.handle)
        self.dlg.Set.set_focus()
        self.assertEqual(self.dlg.GetFocus(), self.dlg.Set.handle)

    def testHasKeyboardFocus(self):
        self.assertFalse(self.dlg.set.has_keyboard_focus())
        self.dlg.set.set_keyboard_focus()
        self.assertTrue(self.dlg.set.has_keyboard_focus())

    def testSetKeyboardFocus(self):
        self.assertNotEqual(self.dlg.get_focus(), self.dlg.set.handle)
        self.dlg.set.set_keyboard_focus()
        self.assertEqual(self.dlg.get_focus(), self.dlg.set.handle)
示例#14
0
else:
    app = application.Application().connect(title_re=".*Mozilla Firefox")
    mozilla = app.window(title_re=".*Mozilla Firefox")

# ie doesn't define it's menus as Menu's but actually as a toolbar!
print("No Menu's in FireFox:", mozilla.menu_items())

# File -> Save As
mozilla.type_keys("%FA")
#ie.Toolbar3.press_button("File")
app.SaveAs.Edit.set_edit_text(outputfilename)

app.SaveAs.Save.close_click()

try:
    # if asked to overwrite say yes
    if app.SaveAs.Yes.Exists():
        app.SaveAs.Yes.close_click()
except WindowAmbiguousError as e:
    for w in e.windows:
        w = HwndWrapper(w)
        print(w.window_text(), w.class_name())

print("saved:", outputfilename)

# File close tab or close
#(Firefox makes it easy for us having the same shortcut for both!
mozilla.type_keys("%FC")