示例#1
0
class NonAdminTestCases(ApplicationWarningTestCases):

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        super(NonAdminTestCases, self).setUp()
        self.app = Application().start(self.sample_exe)

    def tearDown(self):
        """Close the application after tests"""
        self.app.kill()
        super(NonAdminTestCases, self).tearDown()

    def test_both_non_admin(self):
        warnings.filterwarnings('always', category=UserWarning, append=True)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            self.app = Application().connect(title="Common Controls Sample", timeout=5)
            assert len(w) == 0

    def test_both_non_admin_click(self):
        self.app = Application().connect(title="Common Controls Sample", timeout=5)
        self.app.CommonControlsSample.TVS_HASBUTTON.check()
        self.assertEqual(self.app.CommonControlsSample.TVS_HASBUTTON.is_checked(), True)
        self.app.CommonControlsSample.OK.click()
        self.app.CommonControlsSample.wait_not('visible')
示例#2
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 = get_dialog_props_from_handle(self.dlg.handle)
        props_from_dialog = get_dialog_props_from_handle(self.dlg)
        #unused var: props_from_ctrl = get_dialog_props_from_handle(self.ctrl)

        self.assertEqual(props_from_handle, props_from_dialog)
示例#3
0
    class AdminTestCases(ApplicationWarningTestCases):

        def setUp(self):
            """Set some data and ensure the application is in the state we want"""
            super(AdminTestCases, self).setUp()
            cmd = 'powershell -Command "Start-Process {} -Verb RunAs"'.format(self.sample_exe)
            self.app = Application().start(cmd, wait_for_idle=False)

        def tearDown(self):
            """Close the application after tests"""
            self.app.kill()
            super(AdminTestCases, self).tearDown()

        def test_non_admin_warning(self):
            warnings.filterwarnings('always', category=UserWarning, append=True)
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always")
                self.app = Application().connect(title="Common Controls Sample", timeout=20)
                assert len(w) >= 1
                assert issubclass(w[-1].category, UserWarning)
                assert "process has no rights" in str(w[-1].message)

        def test_non_admin_click(self):
            self.app = Application().connect(title="Common Controls Sample", timeout=20)
            with self.assertRaises(RuntimeError):
                self.app.CommonControlsSample.OK.click()
            with self.assertRaises(RuntimeError):
                self.app.CommonControlsSample.OK.click_input()
            with self.assertRaises(RuntimeError):
                self.app.CommonControlsSample.TVS_HASBUTTON.check()
示例#4
0
    class SendKeysModifiersTests(unittest.TestCase):
        """Unit tests for the Sendkeys module (modifiers)"""
        def setUp(self):
            """Start the application and ensure it's in the state we want"""
            self.app = Application().start(
                os.path.join(mfc_samples(), u"CtrlTest.exe"))
            self.dlg = self.app.Control_Test_App

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

        def testModifiersForFewChars(self):
            """Make sure that repeated action works"""
            send_keys("%(SC)", pause=.3)
            dlg = self.app.window(title='Using C++ Derived Class')
            dlg.wait('ready')
            dlg.Done.close_click()
            dlg.wait_not('visible')

            send_keys("%(H{LEFT}{UP}{ENTER})", pause=.3)
            dlg = self.app.window(title='Sample Dialog with spin controls')
            dlg.wait('ready')
            dlg.Done.close_click()
            dlg.wait_not('visible')
示例#5
0
class StaticTestCases(unittest.TestCase):
    """Unit tests for the StaticWrapper class"""
    def setUp(self):
        """Start the sample application. Open a tab with ownerdraw button."""
        Timings.defaults()

        self.app = Application().start(
            os.path.join(mfc_samples_folder, u"RebarTest.exe"))
        # open the Help dailog
        self.app.active().type_keys('%h{ENTER}')

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

    def test_NeedsImageProp(self):
        """test a regular static has no the image property"""
        active_window = self.app.active()
        self.assertEqual(active_window.Static2._needs_image_prop, False)
        self.assertEqual('image' in active_window.Static2.get_properties(),
                         False)
        #self.assertNotIn('image', active_window.Static2.get_properties())
        # assertIn and assertNotIn are not supported in Python 2.6

    def test_NeedsImageProp_ownerdraw(self):
        """test whether an image needs to be saved with the properties"""
        active_window = self.app.active()
        self.assertEqual(active_window.Static._needs_image_prop, True)
        self.assertEqual('image' in active_window.Static.get_properties(),
                         True)
示例#6
0
class RemoteMemoryBlockTests(unittest.TestCase):

    """Unit tests for RemoteMemoryBlock"""

    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"CmnCtrl1.exe"))

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

    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)
示例#7
0
class UnicodeEditTestCases(unittest.TestCase):
    """Unit tests for the EditWrapper class using Unicode strings"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        _set_timings_fast()

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

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.select("CAnimateCtrl")

        self.ctrl = self.dlg.AnimationFileEdit.wrapper_object()

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

    def testSetEditTextWithUnicode(self):
        "Test setting Unicode text by the SetEditText method of the edit control"
        self.ctrl.select()
        self.ctrl.set_edit_text(579)
        self.assertEqual("\n".join(self.ctrl.texts()[1:]), "579")

        self.ctrl.set_edit_text(333, pos_start=1, pos_end=2)
        self.assertEqual("\n".join(self.ctrl.texts()[1:]), "53339")
示例#8
0
    def test_is64bitprocess(self):
        """Make sure a 64-bit process detection returns correct results"""
        if is_x64_OS():
            # Test a 32-bit app running on x64
            expected_is64bit = False
            if is_x64_Python():
                exe32bit = os.path.join(os.path.dirname(__file__),
                              r"..\..\apps\MFC_samples\RowList.exe")
                app = Application().start(exe32bit, timeout=20)
                pid = app.RowListSampleApplication.process_id()
                res_is64bit = is64bitprocess(pid)
                try:
                    self.assertEqual(expected_is64bit, res_is64bit)
                finally:
                    # make sure to close an additional app we have opened
                    app.kill()

                # setup expected for a 64-bit app on x64
                expected_is64bit = True
        else:
            # setup expected for a 32-bit app on x86
            expected_is64bit = False

        # test native Notepad app
        res_is64bit = is64bitprocess(self.app.UntitledNotepad.process_id())
        self.assertEqual(expected_is64bit, res_is64bit)
class NotePage:
    def __init__(self):
        self.app = Application()
        self.x = []
        self.z = []

    def start_app(self, app):
        self.app.start(app)

    def write_text(self):
        self.app.Notepad.edit.type_keys('ThisIsTest')

    def v_x(self):
        x = self.app.Notepad.edit.window_text()
        return x

    def v_z(self):
        z = self.app.Notepad.edit.window_text()
        return z

    def eq(self):
        self.app.kill()
        if len(self.x) <= len(self.z):
            raise TextNotFound('Текст не найден')

    def kill_app(self):
        self.app.kill()
示例#10
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.wrapper_object()

    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)
示例#11
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.wrapper_object()

    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)
示例#12
0
class UnicodeEditTestCases(unittest.TestCase):

    """Unit tests for the EditWrapper class using Unicode strings"""

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

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

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.select("CAnimateCtrl")

        self.ctrl = self.dlg.AnimationFileEdit.wrapper_object()

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

    def testSetEditTextWithUnicode(self):
        "Test setting Unicode text by the SetEditText method of the edit control"
        self.ctrl.select()
        self.ctrl.set_edit_text(579)
        self.assertEqual("\n".join(self.ctrl.texts()[1:]), "579")

        self.ctrl.set_edit_text(333, pos_start=1, pos_end=2)
        self.assertEqual("\n".join(self.ctrl.texts()[1:]), "53339")
示例#13
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 = get_dialog_props_from_handle(self.dlg.handle)
        props_from_dialog = get_dialog_props_from_handle(self.dlg)
        #unused var: props_from_ctrl = get_dialog_props_from_handle(self.ctrl)

        self.assertEqual(props_from_handle, props_from_dialog)
示例#14
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.get_focus(), ws.Edit.wrapper_object())
示例#15
0
class RemoteMemoryBlockTests(unittest.TestCase):

    """Unit tests for RemoteMemoryBlock"""

    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"CmnCtrl1.exe"))

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

    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)
示例#16
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.get_focus(), ws.Edit.wrapper_object())
示例#17
0
class StaticTestCases(unittest.TestCase):

    """Unit tests for the StaticWrapper class"""

    def setUp(self):
        """Start the sample application. Open a tab with ownerdraw button."""
        Timings.defaults()

        self.app = Application().start(os.path.join(mfc_samples_folder, u"RebarTest.exe"))
        # open the Help dailog
        self.app.active().type_keys('%h{ENTER}')

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

    def test_NeedsImageProp(self):
        """test a regular static has no the image property"""
        active_window = self.app.active()
        self.assertEqual(active_window.Static2._needs_image_prop, False)
        self.assertEqual('image' in active_window.Static2.get_properties(), False)
        #self.assertNotIn('image', active_window.Static2.get_properties())
        # assertIn and assertNotIn are not supported in Python 2.6

    def test_NeedsImageProp_ownerdraw(self):
        """test whether an image needs to be saved with the properties"""
        active_window = self.app.active()
        self.assertEqual(active_window.Static._needs_image_prop, True)
        self.assertEqual('image' in active_window.Static.get_properties(), True)
示例#18
0
class NoteplusPage:

    def __init__(self):
        self.app = Application()
        self.c = []
        self.v = []

    def start_app1(self):
        self.app.start(r'C:\Program Files (x86)\Notepad++\notepad1.exe')

    def write_text1(self):
        self.app.Notepad.Scintilla.type_keys('ThisIsTest')

    def v_c(self):
        c = self.app.Notepad.Scintilla.window_text()
        return c

    def v_v(self):
        v = self.app.Notepad.Scintilla.window_text()
        return v

    def eq1(self):
        self.app.kill(soft=True)
        if len(self.c) <= len(self.v):
            raise TextNotFound('Текст не найден')

    def kill_app1(self):
        self.app.kill(soft=True)
示例#19
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.set_edit_text("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.app.UntitledNotepad.menu_select("File->Exit")
            self.app.Notepad["Do&n't Save"].click()
            self.app.Notepad["Do&n't Save"].wait_not('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.set_edit_text(text)
        time.sleep(0.3)
        self.assertEqual(
            self.app2.UntitledNotepad.Edit.text_block().encode(
                locale.getpreferredencoding()), text)

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

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

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

        self.assertEqual(
            self.dlg.Edit.text_block().encode(locale.getpreferredencoding()),
            text * 3)
    def test_is64bitprocess(self):
        """Make sure a 64-bit process detection returns correct results"""
        if is_x64_OS():
            # Test a 32-bit app running on x64
            expected_is64bit = False
            if is_x64_Python():
                exe32bit = os.path.join(os.path.dirname(__file__),
                                        r"..\..\apps\MFC_samples\RowList.exe")
                app = Application().start(exe32bit, timeout=20)
                pid = app.RowListSampleApplication.process_id()
                res_is64bit = is64bitprocess(pid)
                try:
                    self.assertEqual(expected_is64bit, res_is64bit)
                finally:
                    # make sure to close an additional app we have opened
                    app.kill()

                # setup expected for a 64-bit app on x64
                expected_is64bit = True
        else:
            # setup expected for a 32-bit app on x86
            expected_is64bit = False

        # test native Notepad app
        res_is64bit = is64bitprocess(self.app.UntitledNotepad.process_id())
        self.assertEqual(expected_is64bit, res_is64bit)
示例#21
0
class ButtonOwnerdrawTestCases(unittest.TestCase):

    """Unit tests for the ButtonWrapper(ownerdraw button)"""

    def setUp(self):
        """Start the sample application. Open a tab with ownerdraw button."""
        _set_timings_fast()

        self.app = Application().start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe"))
        # open the needed tab
        self.app.active().TabControl.select(1)

    def tearDown(self):

        """Close the application after tests"""

        self.app.kill()

    def test_NeedsImageProp(self):

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

        active_window = self.app.active()
        self.assertEqual(active_window.Button2._needs_image_prop, True)
        self.assertEqual('image' in active_window.Button2.get_properties(), True)
示例#22
0
def restart_if_app_exist(exepath):
    from pywinauto.application import Application
    try:
        app = Application(backend="win32").connect(path=exepath)
        if app.is_process_running():
            app.kill()
    except Exception:
        None
示例#23
0
class ClipboardTestCases(unittest.TestCase):

    """Unit tests for the clipboard"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.fast()
        EmptyClipboard()
        self.app1 = Application().start("notepad.exe")
        self.app2 = Application().start("notepad.exe")

        self.app1.UntitledNotepad.move_window(RECT(0, 0, 200, 200))
        self.app2.UntitledNotepad.move_window(RECT(0, 200, 200, 400))

    def tearDown(self):
        """Close the application after tests"""
        # close the application
        self.app1.UntitledNotepad.menu_select('File -> Exit')
        if self.app1.Notepad["Do&n't Save"].exists():
            self.app1.Notepad["Do&n't Save"].click()
        self.app1.kill()

        self.app2.UntitledNotepad.menu_select('File -> Exit')
        if self.app2.Notepad["Do&n't Save"].exists():
            self.app2.Notepad["Do&n't Save"].click()
        self.app2.kill()

    def testGetClipBoardFormats(self):
        typetext(self.app1, "here we are")
        copytext(self.app1)

        self.assertEqual(GetClipboardFormats(), [13, 16, 1, 7])

    def testGetFormatName(self):
        typetext(self.app1, "here we are")
        copytext(self.app1)

        self.assertEqual(
            [GetFormatName(f) for f in GetClipboardFormats()],
            ['CF_UNICODETEXT', 'CF_LOCALE', 'CF_TEXT', 'CF_OEMTEXT']
        )

    def testBug1452832(self):
        """Failing test for sourceforge bug 1452832

        Where GetData was not closing the clipboard. FIXED.
        """
        self.app1.UntitledNotepad.menu_select("Edit->Select All Ctrl+A")
        typetext(self.app1, "some text")
        copytext(self.app1)

        # was not closing the clipboard!
        data = GetData()
        self.assertEqual(data, "some text")

        self.assertEqual(gettext(self.app2), "")
        pastetext(self.app2)
        self.assertEqual(gettext(self.app2), "some text")
示例#24
0
class ModbusScope:
    ''' API class for ModbusScope '''

    def __init__(self, path='ModbusScope.exe'):
        ''' Create an API object that can control a single instance of ModbusScope '''
        try:
             self.app = Application(backend="uia").connect(title=u'ModbusScope', class_name = u'ModbusScope')
        except ElementNotFoundError:
            try:
                self.app = Application(backend="uia").start(path)
            except ElementNotFoundError:
                raise RuntimeError("ModbusScope is not running or in PATH")

        self.main_window = self.app['ModbusScope.*']
        self.main_window.set_focus()
        #self.app['ModbusScope.*'].print_control_identifiers()

    def load_project(self, file, path=""):
        ''' Load a project (.mbs) file from the given absolute or relative path '''
        self.main_window.set_focus()
        self.main_window.toolBar.LoadProjectFile.click_input()
        if path is not "":
            self.main_window.SelectMbsFile.BestandsNaamEdit.type_keys(path, with_spaces=True)
            send_keys("{ENTER}")

        self.main_window.SelectMbsFile.BestandsNaamEdit.type_keys(file, with_spaces=True)
        send_keys("{ENTER}")

    def start_logging(self):
        ''' Start logging - Some registers must be added '''
        self.main_window.set_focus()
        self.main_window.toolBar.StartLogging.click_input()

    def stop_logging(self):
        ''' Stop the current logging '''
        self.main_window.set_focus()
        self.main_window.toolBar.StopLogging.click_input()

    def add_register(self, address):
        ''' Add a register at the given address '''
        self.main_window.toolBar.RegisterSettings.click_input()
        self.main_window.RegisterSettings.AddNewRegister.click_input()
        self.main_window.RegisterSettings.print_control_identifiers()

    def about(self):
        ''' Open the About menu '''
        self.main_window.Menu2.menu_select("? -> About")

    def quit(self):
        ''' Open the About menu '''
        self.app.kill()

    def take_screenshot(self, name):
        ''' take screenshot '''
        img = self.main_window.capture_as_image()
        img.save(name)
示例#25
0
 def test_process_is_running(self):
     """Tests process is running and wait for exit function"""
     app = Application()
     app.start(_notepad_exe())
     app.UntitledNotepad.wait("ready")
     self.assertTrue(app.is_process_running())
     self.assertRaises(TimeoutError, lambda: app.wait_for_process_exit(timeout=5, retry_interval=1))
     app.kill()
     app.wait_for_process_exit()
     self.assertFalse(app.is_process_running())
示例#26
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.set_edit_text("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.app.UntitledNotepad.menu_select("File->Exit")
            self.app.Notepad["Do&n't Save"].click()
            self.app.Notepad["Do&n't Save"].wait_not('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.set_edit_text(text)
        time.sleep(0.3)
        self.assertEqual(self.app2.UntitledNotepad.Edit.text_block().encode(locale.getpreferredencoding()), text)

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

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

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

        self.assertEqual(self.dlg.Edit.text_block().encode(locale.getpreferredencoding()), text * 3)
示例#27
0
class ClipboardTestCases(unittest.TestCase):
    """Unit tests for the clipboard"""
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.fast()
        EmptyClipboard()
        self.app1 = Application().start("notepad.exe")
        self.app2 = Application().start("notepad.exe")

        self.app1.UntitledNotepad.move_window(RECT(0, 0, 200, 200))
        self.app2.UntitledNotepad.move_window(RECT(0, 200, 200, 400))

    def tearDown(self):
        """Close the application after tests"""
        # close the application
        self.app1.UntitledNotepad.menu_select('File -> Exit')
        if self.app1.Notepad["Do&n't Save"].exists():
            self.app1.Notepad["Do&n't Save"].click()
        self.app1.kill()

        self.app2.UntitledNotepad.menu_select('File -> Exit')
        if self.app2.Notepad["Do&n't Save"].exists():
            self.app2.Notepad["Do&n't Save"].click()
        self.app2.kill()

    def testGetClipBoardFormats(self):
        typetext(self.app1, "here we are")
        copytext(self.app1)

        self.assertEqual(GetClipboardFormats(), [13, 16, 1, 7])

    def testGetFormatName(self):
        typetext(self.app1, "here we are")
        copytext(self.app1)

        self.assertEqual(
            [GetFormatName(f) for f in GetClipboardFormats()],
            ['CF_UNICODETEXT', 'CF_LOCALE', 'CF_TEXT', 'CF_OEMTEXT'])

    def testBug1452832(self):
        """Failing test for sourceforge bug 1452832

        Where GetData was not closing the clipboard. FIXED.
        """
        self.app1.UntitledNotepad.menu_select("Edit->Select All Ctrl+A")
        typetext(self.app1, "some text")
        copytext(self.app1)

        # was not closing the clipboard!
        data = GetData()
        self.assertEqual(data, "some text")

        self.assertEqual(gettext(self.app2), "")
        pastetext(self.app2)
        self.assertEqual(gettext(self.app2), "some text")
示例#28
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.wrapper_object()

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

    def testCheckUncheckByClick(self):
        "test for CheckByClick and UncheckByClick"
        self.dlg.TVS_HASLINES.check_by_click()
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_CHECKED)
        self.assertEqual(self.tree.has_style(win32defines.TVS_HASLINES), True)

        self.dlg.TVS_HASLINES.check_by_click() # make sure it doesn't uncheck the box unexpectedly
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_CHECKED)

        self.dlg.TVS_HASLINES.uncheck_by_click()
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_UNCHECKED)
        self.assertEqual(self.tree.has_style(win32defines.TVS_HASLINES), False)

        self.dlg.TVS_HASLINES.uncheck_by_click() # make sure it doesn't check the box unexpectedly
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_UNCHECKED)

    def testCheckUncheckByClickInput(self):
        "test for CheckByClickInput and UncheckByClickInput"
        self.dlg.TVS_HASLINES.check_by_click_input()
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_CHECKED)
        self.assertEqual(self.tree.has_style(win32defines.TVS_HASLINES), True)

        self.dlg.TVS_HASLINES.check_by_click_input() # make sure it doesn't uncheck the box unexpectedly
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_CHECKED)

        self.dlg.TVS_HASLINES.uncheck_by_click_input()
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_UNCHECKED)
        self.assertEqual(self.tree.has_style(win32defines.TVS_HASLINES), False)

        self.dlg.TVS_HASLINES.uncheck_by_click_input() # make sure it doesn't check the box unexpectedly
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_UNCHECKED)

    def testSetCheckIndeterminate(self):
        "test for SetCheckIndeterminate"
        self.dlg.TVS_HASLINES.set_check_indeterminate()
        self.assertEqual(self.dlg.TVS_HASLINES.get_check_state(), win32defines.BST_CHECKED)
示例#29
0
 def test_wait_cpu_usage_lower_uia(self):
     """Test that wait_cpu_usage_lower() works correctly for UIA"""
     app = Application(backend='uia')
     app.start('notepad.exe')
     try:
         app.wait_cpu_usage_lower(threshold = 1.5, timeout = 30, usage_interval = 2)
     finally:
         app.kill()
     app.cpu_usage = mock.Mock(return_value=10)
     self.assertRaises(
         RuntimeError, app.wait_cpu_usage_lower,
         threshold = 9.0, timeout = 5, usage_interval = 0.5
         )
示例#30
0
class Base:
    def __init__(self,exe_path,backend="uia"):
        try:
            self.app=Application(backend=backend).start(cmd_line=exe_path)
            logger.info("{}程序启动成功".format(exe_path))
        except:
            logger.exception("{}程序启动失败".format(exe_path))
    def kill(self):
        try:
            self.app.kill()
            logger.info("成功关闭程序")
        except:
            logger.exception("关闭程序失败")
示例#31
0
    def test_should_return_not_running_if_failed_to_open_process(
            self, func_open_process):
        """Tests error handling wehn OpenProcess return 0 handle

        Checks is_process_running and wait_for_process_exit works
        even if OpenProcess returns 0 handle without exception
        """
        func_open_process.return_value = pywintypes.HANDLE(0)
        app = Application()
        app.start(_notepad_exe())
        app.wait_for_process_exit(timeout=10, retry_interval=1)
        self.assertFalse(app.is_process_running())
        app.kill()
示例#32
0
def start_test():
    try:
        app = Application().start(
            cmd_line=
            u'"C:\\Program Files\\R\xd8DE Microphones\\RODE Connect\\RODE Connect.exe" '
        )
        jucef = app[u'R\xd8DE Connect']
        jucef.wait('ready')
        automation_test()
        app.kill()
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
示例#33
0
class WeiXin(object):
    def __init__(self):
        # 获取微信客户端连接应用对象
        self.app = Application(backend='uia').connect(
            path="D:\Program Files (x86)\Tencent\WeChat\WeChat.exe")

        # 通过title及ClassName获取窗体对象
        self.weixin_pc_window = self.app.window(
            title=u"微信", class_name="WeChatMainWndForPC")
        self.weixin_pc_window.set_focus()

    def __get_element_postion(self, element):
        """获取元素的中心点位置"""
        # 元素坐标
        element_position = element.rectangle()
        # 算出中心点位置
        center_position = (int(
            (element_position.left + element_position.right) /
            2), int((element_position.top + element_position.bottom) / 2))
        return center_position

    def start(self):
        # 1、获取左侧【聊天】切换元素
        chat_list_element = self.weixin_pc_window.child_window(
            title="聊天", control_type="Button")
        # 2、点击进入到聊天列表
        mouse.click(button='left',
                    coords=self.__get_element_postion(chat_list_element))
        # 3、点击【文件传输助手】进入到聊天页面
        file_helper_element = self.weixin_pc_window.child_window(
            title="文件传输助手", control_type="ListItem")
        mouse.click(button='left',
                    coords=self.__get_element_postion(file_helper_element))
        # 4、获取输入框元素,模拟输入
        edit_element = self.weixin_pc_window.child_window(title=r"输入",
                                                          control_type="Edit")
        sleep(2)
        # 输入内容
        edit_element.type_keys("星安果")
        # 使用键盘模拟回车,即:发送
        send_keys('{ENTER}')

        # 5、释放资源
        self.teardown()

    def teardown(self):
        """释放资源"""
        # 结束进程,释放资源
        self.app.kill()
示例#34
0
    def tearDown(self):
        """Close the application after tests"""
        self.dlg.send_message(win32defines.WM_CLOSE)
        self.dlg.wait_not('ready')

        # cleanup additional unclosed sampleapps
        l = pywinauto.actionlogger.ActionLogger()
        try:
            for i in range(2):
                l.log("Look for unclosed sample apps")
                app = Application()
                app.connect(path="TrayMenu.exe")
                l.log("Forse closing a leftover app: {0}".format(app))
                app.kill()
        except(ProcessNotFoundError):
            l.log("No more leftovers. All good.")
示例#35
0
    def execute(cmd: str = final_exe, args: str = "", wait: int = 0):
        if "--nxdrive-home" not in args:
            args += f' --nxdrive-home="{path}"'
        if "--log-level-file" not in args:
            args += " --log-level-file=DEBUG"
        args = args.strip()

        log.info(f"Starting {cmd!r} with args={args!r}")

        app = Application(backend="uia").start(f"{cmd} {args}")
        try:
            yield app
            if wait > 0:
                sleep(wait)
        finally:
            app.kill()
示例#36
0
class SendKeystrokesAltComboTests(unittest.TestCase):
    """Unit test for Alt- combos sent via send_keystrokes"""
    def setUp(self):
        Timings.defaults()

        self.app = Application().start(
            os.path.join(mfc_samples_folder, u'CtrlTest.exe'))
        self.dlg = self.app.Control_Test_App

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

    def test_send_keystrokes_alt_combo(self):
        self.dlg.send_keystrokes('%(sc)')

        self.assertTrue(self.app['Using C++ Derived Class'].exists())
示例#37
0
class SendKeystrokesAltComboTests(unittest.TestCase):

    """Unit test for Alt- combos sent via send_keystrokes"""

    def setUp(self):
        Timings.defaults()

        self.app = Application().start(os.path.join(mfc_samples_folder, u'CtrlTest.exe'))
        self.dlg = self.app.Control_Test_App

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

    def test_send_keystrokes_alt_combo(self):
        self.dlg.send_keystrokes('%(sc)')

        self.assertTrue(self.app['Using C++ Derived Class'].exists())
示例#38
0
def rsa_stuff():
    app = Application().start(cmd_line=config.RSA_PATH)
    rsa = app.QWidget
    rsa.wait('ready')
    rsa.click_input()

    time.sleep(1)
    pyautogui.typewrite(config.RSA_PIN)
    time.sleep(1)
    pyautogui.press('enter')
    time.sleep(1)
    pyautogui.press('tab')
    pyautogui.press('space')
    token = pyperclip.paste()
    print(f'RSA Token = {token}')
    app.kill()
    return token
示例#39
0
class OutlookRobot:
    def __init__(self, sender: str, addressee: str, subject: str,
                 message: str):
        self.sender = sender
        self.addressee = addressee
        self.subject = subject
        self.message = message

    def launch_outlook(self):
        self.app = Application(backend='uia').start(
            r"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE")
        timings.wait_until(10, 0.5,
                           self.app[f'Inbox — {self.sender} - Outlook'].exists)
        self.dlg = self.app[f'Inbox — {self.sender} - Outlook']

    def send_message(self):
        timings.always_wait_until(10, 0.5,
                                  self.dlg['Nowa wiadomość e-mail'].exists)
        self.dlg['Nowa wiadomość e-mail'].Button.click()

        timings.wait_until(10, 0.5,
                           self.app['Bez tytułu - Wiadomość (HTML) '].exists)
        self.snd_dlg = self.app['Bez tytułu - Wiadomość (HTML) ']

        addressee_input = self.snd_dlg['Edit4']
        addressee_input.set_focus()
        keyboard.send_keys(self.addressee, with_spaces=True)

        subject_input = self.snd_dlg['Edit6']
        subject_input.set_focus()
        keyboard.send_keys(self.subject, with_spaces=True)

        message_input = self.snd_dlg['Edit7']
        message_input.set_focus()
        keyboard.send_keys(self.message, with_spaces=True)

        send_button = self.snd_dlg['Wyślij']
        send_button.click()

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

    def run(self):
        self.launch_outlook()
        self.send_message()
        self.close_outlook()
示例#40
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')
        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.assertEqual(['Hello\r\nWorld'], self.dlg.Edit.Texts())
示例#41
0
class WindowWithoutMessageLoopFocusTests(unittest.TestCase):
    """
    Regression unit tests for setting focus when window does not have
    a message loop.
    """
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.fast()

        self.app1 = Application().start(u"cmd.exe",
                                        create_new_console=True,
                                        wait_for_idle=False)
        self.app2 = Application().start(
            os.path.join(mfc_samples_folder, u"CmnCtrl2.exe"))
        self.app2.wait_cpu_usage_lower(threshold=1.5,
                                       timeout=30,
                                       usage_interval=1)

    def tearDown(self):
        """Close the application after tests"""
        self.app1.kill()
        self.app2.kill()

    def test_issue_270(self):
        """
        Set focus to a window without a message loop, then switch to a window
        with one and type in it.
        """
        self.app1.window().set_focus()
        self.app1.wait_cpu_usage_lower(threshold=1.5,
                                       timeout=30,
                                       usage_interval=1)
        # pywintypes.error:
        #     (87, 'AttachThreadInput', 'The parameter is incorrect.')

        self.app2.window().edit.type_keys("1")
        # cmd.exe into python.exe;  pywintypes.error:
        #     (87, 'AttachThreadInput', 'The parameter is incorrect.')
        # python.exe on its own;  pywintypes.error:
        #     (0, 'SetForegroundWindow', 'No error message is available')
        self.assertTrue(self.app2.window().is_active())
示例#42
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())
示例#43
0
class OwnerDrawnMenuTests(unittest.TestCase):

    """Unit tests for the OWNERDRAW menu items"""

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

        self.app = Application().start(os.path.join(mfc_samples_folder, u"BCDialogMenu.exe"))
        self.dlg = self.app.BCDialogMenu
        self.app.wait_cpu_usage_lower(threshold=1.5, timeout=30, usage_interval=1)
        self.dlg.wait('ready')

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

    def testCorrectText(self):
        menu = self.dlg.menu()
        self.assertEqual(u'&New', menu.get_menu_path('&File->#0')[-1].text()[:4])
        self.assertEqual(u'&Open...', menu.get_menu_path('&File->#1')[-1].text()[:8])
示例#44
0
class ActionLoggerOnStadardLoggerTestCases(unittest.TestCase):

    """Unit tests for the actionlogger based on _StandardLogger"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.fast()
        actionlogger.enable()
        self.app = Application().start(_notepad_exe())
        self.logger = logging.getLogger('pywinauto')
        self.out = self.logger.handlers[0].stream
        self.logger.handlers[0].stream = open('test_logging.txt', 'w')

    def tearDown(self):
        """Close the application after tests"""
        self.logger.handlers[0].stream.close()
        self.logger.handlers[0].stream = self.out
        self.app.kill()

    def __lineCount(self):
        """hack to get line count from current logger stream"""
        self.logger = logging.getLogger('pywinauto')
        self.logger.handlers[0].stream.flush()
        os.fsync(self.logger.handlers[0].stream.fileno())
        with open(self.logger.handlers[0].stream.name, 'r') as f:
            return len(f.readlines())

    def testEnableDisable(self):
        actionlogger.enable()
        prev_line_count = self.__lineCount()
        self.app.UntitledNotepad.type_keys('Test pywinauto logging', with_spaces=True)
        self.assertEqual(self.__lineCount(), prev_line_count + 1)

        actionlogger.disable()
        self.app.UntitledNotepad.menu_select('Help->About Notepad')
        self.assertEqual(self.__lineCount(), prev_line_count + 1)

        actionlogger.enable()
        self.app.window(title='About Notepad').OK.click()
        self.assertEqual(self.__lineCount(), prev_line_count + 2)
示例#45
0
class DragAndDropTests(unittest.TestCase):

    """Unit tests for mouse actions like drag-n-drop"""

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

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

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

    #def testDragMouse(self):
    #    """drag_mouse works! But CmnCtrl1.exe crashes in infinite recursion."""
    #    birds = self.ctrl.get_item(r'\Birds')
    #    dogs = self.ctrl.get_item(r'\Dogs')
    #    self.ctrl.drag_mouse("left", birds.rectangle().mid_point(), dogs.rectangle().mid_point())
    #    dogs = self.ctrl.get_item(r'\Dogs')
    #    self.assertEqual([child.Text() for child in dogs.children()],
    #                      [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane'])

    def testDragMouseInput(self):
        """Test for drag_mouse_input"""
        birds = self.ctrl.get_item(r'\Birds')
        dogs = self.ctrl.get_item(r'\Dogs')
        #birds.select()
        birds.click_input()
        time.sleep(5)  # enough pause to prevent double click detection
        self.ctrl.drag_mouse_input(dst=dogs.client_rect().mid_point(),
                                   src=birds.client_rect().mid_point(),
                                   absolute=False)
        dogs = self.ctrl.get_item(r'\Dogs')
        self.assertEqual([child.text() for child in dogs.children()],
                          [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane'])
示例#46
0
class PopupMenuTestCases(unittest.TestCase):

    """Unit tests for the PopupMenuWrapper 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("notepad.exe")
        self.app.Notepad.Edit.right_click()
        self.popup = self.app.PopupMenu.wrapper_object()

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

    def testGetProperties(self):
        "Test getting the properties for the PopupMenu"
        props = self.popup.get_properties()

        self.assertEqual(
            "PopupMenu", props['friendly_class_name'])

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

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

    def testIsDialog(self):
        "Ensure that is_dialog works correctly"
        self.assertEqual(True, self.popup.is_dialog())

    def test_menu_handle(self):
        "Ensure that the menu handle is returned"
        handle = self.popup._menu_handle()
        self.assertNotEqual(0, handle)
示例#47
0
class DragAndDropTests(unittest.TestCase):

    """Unit tests for mouse actions like drag-n-drop"""

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

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

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

    #def testDragMouse(self):
    #    """drag_mouse works! But CmnCtrl1.exe crashes in infinite recursion."""
    #    birds = self.ctrl.get_item(r'\Birds')
    #    dogs = self.ctrl.get_item(r'\Dogs')
    #    self.ctrl.drag_mouse("left", birds.rectangle().mid_point(), dogs.rectangle().mid_point())
    #    dogs = self.ctrl.get_item(r'\Dogs')
    #    self.assertEqual([child.Text() for child in dogs.children()],
    #                      [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane'])

    def testDragMouseInput(self):
        """Test for drag_mouse_input"""
        birds = self.ctrl.get_item(r'\Birds')
        dogs = self.ctrl.get_item(r'\Dogs')
        #birds.select()
        birds.click_input()
        time.sleep(5)  # enough pause to prevent double click detection
        self.ctrl.drag_mouse_input(dst=dogs.client_rect().mid_point(),
                                   src=birds.client_rect().mid_point(),
                                   absolute=False)
        dogs = self.ctrl.get_item(r'\Dogs')
        self.assertEqual([child.text() for child in dogs.children()],
                          [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane'])
示例#48
0
class WindowWithoutMessageLoopFocusTests(unittest.TestCase):

    """
    Regression unit tests for setting focus when window does not have
    a message loop.
    """

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

        self.app1 = Application().start(u"cmd.exe",
                                        create_new_console=True,
                                        wait_for_idle=False)
        self.app2 = Application().start(os.path.join(
            mfc_samples_folder, u"CmnCtrl2.exe"))
        self.app2.wait_cpu_usage_lower(threshold=1.5, timeout=30, usage_interval=1)

    def tearDown(self):
        """Close the application after tests"""
        self.app1.kill()
        self.app2.kill()

    def test_issue_270(self):
        """
        Set focus to a window without a message loop, then switch to a window
        with one and type in it.
        """
        self.app1.window().set_focus()
        self.app1.wait_cpu_usage_lower(threshold=1.5, timeout=30, usage_interval=1)
        # pywintypes.error:
        #     (87, 'AttachThreadInput', 'The parameter is incorrect.')

        self.app2.window().edit.type_keys("1")
        # cmd.exe into python.exe;  pywintypes.error:
        #     (87, 'AttachThreadInput', 'The parameter is incorrect.')
        # python.exe on its own;  pywintypes.error:
        #     (0, 'SetForegroundWindow', 'No error message is available')
        self.assertTrue(self.app2.window().is_active())
示例#49
0
class FindWindowsTestCases(unittest.TestCase):

    """Unit tests for findwindows.py module"""

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

        # start the application
        self.app = Application(backend='win32')
        self.app = self.app.start(mfc_app_1)

        self.dlg = self.app.CommonControlsSample

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

    def test_find_window(self):
        """Test if function find_window() works as expected including raising the exceptions"""
        ctrl = self.dlg.OK.wrapper_object()
        handle = find_window(process=self.app.process, best_match='OK', top_level_only=False)

        self.assertEqual(handle, ctrl.handle)

        self.assertRaises(WindowNotFoundError, find_window, process=self.app.process, class_name='OK')

        self.assertRaises(WindowAmbiguousError, find_window,
                          process=self.app.process, class_name='Button', top_level_only=False)

    def test_find_windows(self):
        """Test if function find_windows() works as expected including raising the exceptions"""
        ctrl_hwnds = [elem.handle for elem in self.dlg.children() if elem.class_name() == 'Edit']
        handles = find_windows(process=self.app.process, class_name='Edit', top_level_only=False)

        self.assertEqual(set(handles), set(ctrl_hwnds))

        self.assertRaises(WindowNotFoundError, find_windows,
                          process=self.app.process, class_name='FakeClassName', found_index=1)
示例#50
0
class CalendarWrapperTests(unittest.TestCase):

    """Unit tests for the CalendarWrapperTests class"""
    NO_HOLIDAYS_IN_MONTH = 0

    CALENDARBK_WIDTH_COEFF = 9
    CALENDARBK_HEIGHT_OFFSET = 112
    TITLEBK_WIDTH_COEFF = 2
    TITLEBK_HEIGHT_COEFF = 26.67

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        self.app = Application().start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.select(4)
        self.calendar = self.app.Common_Controls_Sample.CalendarWrapper

        rect = self.app['Common Controls Sample']['Calendar'].rectangle()
        self.width = rect.width()
        self.height = rect.height()

    def tearDown(self):
        """Close the application after tests"""
        # close the application
        self.app.kill()

    def test_can_get_current_date_from_calendar(self):
        date = self.calendar.get_current_date()
        self.assert_actual_time_is_equal_to_expect_date_time(date, datetime.date.today())

    def test_runtime_error_when_try_to_get_current_date_from_calendar_if_calendar_state_is_multiselect(self):
        self._set_calendar_state_into_multiselect()
        self.assertRaises(RuntimeError, self.calendar.get_current_date)

    def test_can_set_current_date_in_calendar(self):
        self.calendar.set_current_date(2016, 4, 3, 13)
        self.assert_actual_time_is_equal_to_expect_date_time(
            self.calendar.get_current_date(),
            datetime.date(2016, 4, 13))

    def test_should_throw_runtime_error_when_try_to_set_invalid_date(self):
        self.assertRaises(RuntimeError, self.calendar.set_current_date, -2016, -4, -3, -13)

    def test_can_get_calendar_border(self):
        width = self.calendar.get_border()
        self.assertEqual(width, 4)

    def test_can_set_calendar_border(self):
        self.calendar.set_border(6)
        self.assertEqual(self.calendar.get_border(), 6)

    def test_can_get_calendars_count(self):
        count = self.calendar.count()
        self.assertEqual(count, 1)

    def test_can_get_calendars_view(self):
        view = self.calendar.get_view()
        self.assertEqual(view, 0)

    def test_should_throw_runtime_error_when_try_to_set_invalid_view(self):
        self.assertRaises(RuntimeError, self.calendar.set_view, -1)

    def test_can_set_calendars_view_into_month(self):
        self.calendar.set_view(win32defines.MCMV_MONTH)
        self.assertEqual(self.calendar.get_view(), win32defines.MCMV_MONTH)

    def test_can_set_calendars_view_into_years(self):
        self.calendar.set_view(win32defines.MCMV_YEAR)
        self.assertEqual(self.calendar.get_view(), win32defines.MCMV_YEAR)

    def test_can_set_calendars_view_into_decade(self):
        self.calendar.set_view(win32defines.MCMV_DECADE)
        self.assertEqual(self.calendar.get_view(), win32defines.MCMV_DECADE)

    def test_can_set_calendars_view_into_century(self):
        self.calendar.set_view(win32defines.MCMV_CENTURY)
        self.assertEqual(self.calendar.get_view(), win32defines.MCMV_CENTURY)

    def test_can_set_day_state(self):
        month_states = [self.NO_HOLIDAYS_IN_MONTH, self.NO_HOLIDAYS_IN_MONTH, self.NO_HOLIDAYS_IN_MONTH]
        self._set_calendar_state_to_display_day_states()

        res = self.calendar.set_day_states(month_states)

        self.assertNotEqual(0, res)

    def test_cant_set_day_state_passing_one_month_state(self):
        month_states = [self.NO_HOLIDAYS_IN_MONTH]
        self._set_calendar_state_to_display_day_states()
        self.assertRaises(RuntimeError, self.calendar.set_day_states, month_states)

    def test_can_minimize_rectangle(self):
        expected_rect = self._get_expected_minimized_rectangle()
        rect = self.calendar.calc_min_rectangle(expected_rect.left + 100, expected_rect.top + 100,
                                                expected_rect.right + 100, expected_rect.bottom + 100)
        self.assertEqual(expected_rect, rect)

    def test_can_minimize_rectangle_handle_less_than_zero_values(self):
        expected_rect = self._get_expected_minimized_rectangle()
        rect = self.calendar.calc_min_rectangle(-1, -1, -1, -1)
        self.assertEqual(expected_rect, rect)

    def test_can_determine_calendar_is_hit(self):
        x = int(self.width / self.CALENDARBK_WIDTH_COEFF)
        y = int(self.height - self.CALENDARBK_HEIGHT_OFFSET)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDAR, res)

    def test_can_determine_calendar_background_is_hit(self):
        x = int(self.width / self.CALENDARBK_WIDTH_COEFF)
        y = int(self.height - self.CALENDARBK_HEIGHT_OFFSET)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDARBK, res)

    def test_can_determine_date_is_hit(self):
        x = int(self.width / 1.13)
        y = int(self.height / 1.62)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDARDATE, res)

    def test_can_determine_next_month_date_is_hit(self):
        x = int(self.width / 1.14)
        y = int(self.height / 1.23)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDARDATENEXT, res)

    def test_can_determine_prev_month_date_is_hit(self):
        x = int(self.width / 16)
        y = int(self.height / 2.67)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDARDATEPREV, res)

    def test_can_determine_nothing_is_hit(self):
        res = self.calendar.hit_test(0, 0)
        self.assertEqual(win32defines.MCHT_NOWHERE, res)

    def test_can_determine_top_left_title_corner_is_hit(self):
        x = int(self.width / 16)
        y = int(self.height / 16)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_TITLEBTNPREV, res)

    def test_can_determine_title_is_hit(self):
        x = int(self.width / self.TITLEBK_WIDTH_COEFF)
        y = int(self.height / self.TITLEBK_HEIGHT_COEFF)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_TITLE, res)

    def test_can_determine_title_background_is_hit(self):
        x = int(self.width / self.TITLEBK_WIDTH_COEFF)
        y = int(self.height / self.TITLEBK_HEIGHT_COEFF)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_TITLEBK, res)

    def test_can_determine_top_right_title_corner_is_hit(self):
        x = int(self.width / 1.07)
        y = int(self.height / 8)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_TITLEBTNNEXT, res)

    # TODO: test_can_determine_today_link_is_hit fails in CI with strange res = 1048576.
    # There is no such value for MCHT_* defines.
    # def test_can_determine_today_link_is_hit(self):
    #     x = int(self.width / 1.25)
    #     y = int(self.height / 1.14)
    #
    #     res = self.calendar.test_hit(x, y)
    #
    #     self.assertEqual(win32defines.MCHT_TODAYLINK, res)

    def test_can_determine_day_abbreviation_is_hit(self):
        x = int(self.width / 5.33)
        y = int(self.height / 4)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDARDAY, res)

    def test_can_determine_week_number_is_hit(self):
        self._set_calendar_state_to_display_week_numbers()
        x = int(self.width / 13.5)
        y = int(self.height / 1.7)

        res = self.calendar.hit_test(x, y)

        self.assertEqual(win32defines.MCHT_CALENDARWEEKNUM, res)

    def test_should_throw_runtime_error_when_try_to_set_invalid_type_of_calendar(self):
        self.assertRaises(ValueError, self.calendar.set_id, 'Aloha!')

    def test_should_get_valid_type_of_calendar(self):
        self.assertEqual(self.calendar.get_id(), 0)

    def test_should_throw_runtime_error_when_try_to_set_invalid_type_of_place_for_color(self):
        self.assertRaises(ValueError, self.calendar.set_color, 'Aloha!', 0, 0, 0)

    # TODO create tests for get_color in future
    #def test_return_zero_when_color_not_set_early(self):
    #    self.assertEqual(self.calendar.get_color('text'), 0)

    #def test_should_get_valid_calendar_color(self):
    #    self.calendar.set_color('text', 5, 5, 5)
    #    self.assertEqual(self.calendar.get_color('text'), 328965)

    def test_return_error_about_color(self):
        self.assertRaises(RuntimeError, self.calendar.set_color, 'background', -1, -1, -1)

    def test_return_error_when_color_hire_then_255(self):
        self.assertRaises(RuntimeError, self.calendar.set_color, 'background', 600, 600, 600)

    def test_can_get_today(self):
        """Test getting the control's today field"""
        date = self.calendar.get_today()
        self.assert_actual_time_is_equal_to_expect_date_time(date, datetime.date.today())

    def test_can_set_today(self):
        """Test setting up the control's today field"""
        self.calendar.set_today(2016, 5, 1)
        self.assert_actual_time_is_equal_to_expect_date_time(self.calendar.get_today(),
                                                             datetime.date(2016, 5, 1))

    def test_can_set_and_get_first_day_of_week(self):
        """Test can set and get first day of the week"""
        self.calendar.set_first_weekday(4)
        self.assertEqual((True, 4), self.calendar.get_first_weekday())

    def test_can_get_default_scroll_rate(self):
        actual_rate = 1

        self.assertEqual(actual_rate, self.calendar.get_month_delta())

    def test_can_set_scroll_rate(self):
        actual_rate = 4
        self.calendar.set_month_delta(actual_rate)

        self.assertEqual(actual_rate, self.calendar.get_month_delta())

    def test_should_throw_value_error_when_try_to_set_incorrect_scroll_rate(self):
        self.assertRaises(ValueError, self.calendar.set_month_delta, -1)

    def test_can_get_month_range_when_calendars_view_into_month(self):
        self.calendar.set_current_date(2017, 5, 2, 2)
        exp_range = 1
        start_month = datetime.date(2017, 5, 1)
        end_month = datetime.date(2017, 5, 31)

        self._check_month_range(exp_range, start_month, end_month)

    def test_can_get_month_range_when_calendars_view_into_years(self):
        self.calendar.set_current_date(2017, 5, 2, 2)
        self.calendar.set_view(win32defines.MCMV_YEAR)

        exp_range = 12
        start_month = datetime.date(2017, 1, 1)
        end_month = datetime.date(2017, 12, 31)

        self._check_month_range(exp_range, start_month, end_month)

    def test_can_get_month_range_with_include_preceding_and_trailing_months(self):
        self.calendar.set_current_date(2017, 5, 2, 2)

        res = self.calendar.get_month_range(win32defines.GMR_DAYSTATE)
        range_months, system_time = res[:2]

        exp_range = 3
        start_month = datetime.date(2017, 4, 24)
        end_month = datetime.date(2017, 6, 4)

        self.assertEqual(range_months, exp_range)
        self.assertEqual(system_time[0].wYear, start_month.year)
        self.assertEqual(system_time[0].wMonth, start_month.month)
        self.assertEqual(system_time[1].wYear, end_month.year)
        self.assertEqual(system_time[1].wMonth, end_month.month)

    def test_should_throw_value_error_when_try_to_get_month_range_and_scope_of_range_is_incorrect(self):
        self.assertRaises(ValueError, self.calendar.get_month_range, -1)

    def _check_month_range(self, exp_range, start_month, end_month):
        res = self.calendar.get_month_range(win32defines.GMR_VISIBLE)
        range_months, system_time = res[:2]

        self.assertEqual(range_months, exp_range)
        self.assert_actual_time_is_equal_to_expect_date_time(system_time[0], start_month)
        self.assert_actual_time_is_equal_to_expect_date_time(system_time[1], end_month)

    def assert_actual_time_is_equal_to_expect_date_time(self, actual_date, expect_date):
        self.assertEqual(actual_date.wYear, expect_date.year)
        self.assertEqual(actual_date.wMonth, expect_date.month)
        self.assertEqual(actual_date.wDay, expect_date.day)

    def _get_expected_minimized_rectangle(self):
        expected_rect = win32structures.RECT()
        expected_rect.left = 0
        expected_rect.top = 0
        expected_rect.right = self.width
        expected_rect.bottom = self.height
        return expected_rect

    def _set_calendar_state_to_display_day_states(self):
        self.app['Common Controls Sample']['MCS_DAYSTATE'].click()

    def _set_calendar_state_to_display_week_numbers(self):
        self.app['Common Controls Sample']['MCS_WEEKNUMBERS'].click()

    def _set_calendar_state_into_multiselect(self):
        self.app['Common Controls Sample']['MCS_MULTISELECT'].click()
    class UIAElementInfoTests(unittest.TestCase):

        """Unit tests for the UIElementInfo class"""

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

            self.app = Application(backend="uia")
            self.app = self.app.start(wpf_app_1)

            self.dlg = self.app.WPFSampleApplication
            self.handle = self.dlg.handle
            self.ctrl = UIAElementInfo(self.handle)

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

        def testProcessId(self):
            """Test process_id equals"""
            self.assertEqual(self.ctrl.process_id, processid(self.handle))

        def testName(self):
            """Test application name equals"""
            self.assertEqual(self.ctrl.name, "WPF Sample Application")

        def testHandle(self):
            """Test application handle equals"""
            self.assertEqual(self.ctrl.handle, self.handle)

        def testEnabled(self):
            """Test whether the element is enabled"""
            self.assertEqual(self.ctrl.enabled, True)

        def testVisible(self):
            """Test whether the element is visible"""
            self.assertEqual(self.ctrl.visible, True)

        def testChildren(self):
            """Test whether a list of only immediate children of the element is equal"""
            self.assertEqual(len(self.ctrl.children()), 5)

        def test_children_generator(self):
            """Test whether children generator iterates over correct elements"""
            children = [child for child in self.ctrl.iter_children()]
            self.assertSequenceEqual(self.ctrl.children(), children)

        def test_default_depth_descendants(self):
            """Test whether a list of descendants with default depth of the element is equal"""
            self.assertEqual(len(self.ctrl.descendants(depth=None)), len(self.ctrl.descendants()))

        def test_depth_level_one_descendants(self):
            """Test whether a list of descendants with depth=1 of the element is equal to children set"""
            self.assertEqual(len(self.ctrl.descendants(depth=1)), len(self.ctrl.children()))

        def test_depth_level_three_descendants(self):
            """Test whether a list of descendants with depth=3 of the element is equal"""
            descendants = self.ctrl.children()

            level_two_children = []
            for element in descendants:
                level_two_children.extend(element.children())
            descendants.extend(level_two_children)

            level_three_children = []
            for element in level_two_children:
                level_three_children.extend(element.children())
            descendants.extend(level_three_children)

            self.assertEqual(len(self.ctrl.descendants(depth=3)), len(descendants))

        def test_invalid_depth_descendants(self):
            """Test whether a list of descendants with invalid depth raises exception"""
            self.assertRaises(Exception, self.ctrl.descendants, depth='qwerty')

        def test_descendants_generator(self):
            """Test whether descendant generator iterates over correct elements"""
            descendants = [desc for desc in self.ctrl.iter_descendants(depth=3)]
            self.assertSequenceEqual(self.ctrl.descendants(depth=3), descendants)
示例#52
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)
示例#53
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)
示例#54
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):
        if sys.platform == 'win32':
            self.app.kill_()
        else:
            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)
        SendKeys('^a')
        SendKeys('^c')
        if sys.platform == 'win32':
            win32clipboard.OpenClipboard()
            data = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()
        else:
            data = clipboard.get_data()
        return data

    def test_position(self):
        left, top = self.__get_pos(50)
        print(left, top)
        mouse.click(coords=(left, top))
        data = self.__get_text()
        self.assertTrue(str(int(top)) in data)
        self.assertTrue(str(int(left)) in data)

    def test_click(self):
        mouse.click(coords=(self.__get_pos(50)))
        data = self.__get_text()
        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)
示例#55
0
class HandlepropsTestCases(unittest.TestCase):

    """Unit tests for the handleprops module"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.defaults()
        self.app = Application().start("notepad")
        self.dlghandle = self.app.UntitledNotepad.handle
        self.edit_handle = self.app.UntitledNotepad.Edit.handle

    def tearDown(self):
        """Close the application after tests"""
        # close the application
        #self.dlg.SendMessage(win32defines.WM_CLOSE)
        #self.app.UntitledNotepad.menu_select("File->Exit")
        self.app.kill()

    def test_text(self):
        """Make sure the text method returns correct result"""
        self.assertEqual("Untitled - Notepad", text(self.dlghandle))
        self.assertEqual("", text(self.edit_handle))
        self.assertEqual(None, text(sys.maxsize))
        self.assertEqual(None, text(None))


    def test_classname(self):
        """Make sure the classname method returns correct result"""
        self.assertEqual("Notepad", classname(self.dlghandle))
        self.assertEqual("Edit", classname(self.edit_handle))
        self.assertEqual("", classname(sys.maxsize))
        self.assertEqual(None, classname(None))

    def test_parent(self):
        """Make sure the parent method returns correct result"""
        self.assertEqual(0, parent(self.dlghandle))
        self.assertEqual(self.dlghandle, parent(self.edit_handle))

    def test_style(self):
        """Make sure the style method returns correct result"""
        self.assertEqual(0x14cf0000, style(self.dlghandle))
        # will be 0x50300104 if wordwrap is on and 0x50200104 if off
        self.assertTrue(
            (0x50200104, 0x50300104).__contains__,
            style(self.edit_handle),)

    def test_exstyle(self):
        """Make sure the exstyle method returns correct result"""
        self.assertEqual(0x110, exstyle(self.dlghandle))
        self.assertEqual(0x200, exstyle(self.edit_handle))

    def test_controlid(self):
        """Make sure the controlid method returns correct result"""
        #self.assertEqual(0, controlid(self.dlghandle))
        self.assertEqual(15, controlid(self.edit_handle))

    def test_userdata(self):
        """Make sure the userdata method returns correct result"""
        self.assertEqual(0, userdata(self.dlghandle))
        self.assertEqual(0, userdata(self.edit_handle))

    def test_contexthelpid(self):
        """Make sure the contexthelpid method returns correct result"""
        self.assertEqual(0, contexthelpid(self.dlghandle))
        self.assertEqual(0, contexthelpid(self.edit_handle))

    def test_iswindow(self):
        """Make sure the iswindow method returns correct result"""
        self.assertEqual(True, iswindow(self.dlghandle))
        self.assertEqual(True, iswindow(self.edit_handle))

        self.assertEqual(False, iswindow(1))
        self.assertEqual(False, iswindow(sys.maxsize))
        self.assertEqual(False, iswindow(None))

    def test_isvisible(self):
        """Make sure the isvisible method returns correct result"""
        self.assertEqual(True, isvisible(self.dlghandle))
        self.assertEqual(True, isvisible(self.edit_handle))
        self.assertEqual(False, isvisible(sys.maxsize))
        self.assertEqual(False, isvisible(None))
        # need to check something invisible
        #self.assertEqual(False, isvisible(self.edit_handle))

    def test_isunicode(self):
        """Make sure the isunicode method returns correct result"""
        self.assertEqual(True, isunicode(self.dlghandle))
        self.assertEqual(True, isunicode(self.edit_handle))
        self.assertEqual(False, isunicode(sys.maxsize))
        self.assertEqual(False, isunicode(None))

        # need to check something not unicode
        #self.assertEqual(False, isunicode(self.edit_handle))

    def test_isenabled(self):
        """Make sure the isenabled method returns correct result"""
        self.assertEqual(False, isenabled(sys.maxsize))
        self.assertEqual(False, isenabled(None))
        self.assertEqual(True, isenabled(self.dlghandle))
        self.assertEqual(True, isenabled(self.edit_handle))

        self.app.UntitledNotepad.menu_select("Help->About Notepad")
        self.app.AboutNotepad.wait('ready')
        self.assertEqual(False, isenabled(self.dlghandle))
        self.app.AboutNotepad.OK.close_click()

        self.app.UntitledNotepad.menu_select("Edit->Replace")
        self.assertEqual(
            False,
            isenabled(
                self.app.Replace.child_window(
                    title_re = "Replace.*",
                    class_name = "Button",
                    enabled_only = False).handle))
        self.app.Replace.Cancel.click()

    def test_clientrect(self):
        """Make sure clientrect() function works"""
        self.assertEqual(0, clientrect(self.dlghandle).left)
        self.assertEqual(0, clientrect(self.edit_handle).left)

        self.assertEqual(0, clientrect(self.dlghandle).top)
        self.assertEqual(0, clientrect(self.edit_handle).top)

        self.assertEqual(True,
            rectangle(self.dlghandle).right > clientrect(self.dlghandle).right)
        self.assertEqual(True,
            rectangle(self.edit_handle).right > clientrect(self.edit_handle).right)

        self.assertEqual(True,
            rectangle(self.dlghandle).bottom > clientrect(self.dlghandle).bottom)
        self.assertEqual(True,
            rectangle(self.edit_handle).bottom > clientrect(self.edit_handle).bottom)

    def test_rectangle(self):
        """Make sure rectangle() function works"""
        dlgrect = rectangle(self.dlghandle)
        self.assertEqual(True, dlgrect.left < dlgrect.right)
        self.assertEqual(True, dlgrect.top < dlgrect.bottom)

        editrect = rectangle(self.edit_handle)
        self.assertEqual(True, editrect.left < editrect.right)
        self.assertEqual(True, editrect.top < editrect.bottom)

    def test_font(self):
        """Make sure font() function works"""
        dlgfont = font(self.dlghandle)
        self.assertEqual(True, isinstance(dlgfont.lfFaceName, six.string_types))

        editfont = font(self.edit_handle)
        self.assertEqual(True, isinstance(editfont.lfFaceName, six.string_types))

        # handle.props font should return DEFAULT font for an invalid handle
        # Check only for a returned type as the default font can vary
        expected = win32structures.LOGFONTW()
        self.assertEqual(type(expected), type(font(sys.maxsize)))
        self.assertEqual(type(expected), type(font(None)))

    def test_processid(self):
        """Make sure processid() function works"""
        self.assertEqual(self.app.process, processid(self.dlghandle))
        self.assertEqual(self.app.process, processid(self.edit_handle))

    def test_children(self):
        """Make sure the children method returns correct result"""
        self.assertEqual(2,  len(children(self.dlghandle)))
        self.assertEqual([], children(self.edit_handle))

    def test_has_style(self):
        """Make sure the has_style method returns correct result"""
        self.assertEqual(True, has_style(self.dlghandle, 0xf0000))
        self.assertEqual(True, has_style(self.edit_handle, 0x4))

        self.assertEqual(False, has_style(self.dlghandle, 4))
        self.assertEqual(False, has_style(self.edit_handle, 1))


    def test_has_exstyle(self):
        """Make sure the has_exstyle method returns correct result"""
        self.assertEqual(True, has_exstyle(self.dlghandle, 0x10))
        self.assertEqual(True, has_exstyle(self.edit_handle, 0x200))

        self.assertEqual(False, has_exstyle(self.dlghandle, 4))
        self.assertEqual(False, has_exstyle(self.edit_handle, 0x10))

    def test_is_toplevel_window(self):
        """Make sure is_toplevel_window() function works"""
        self.assertEqual(True, is_toplevel_window(self.dlghandle))
        self.assertEqual(False, is_toplevel_window(self.edit_handle))

        self.app.UntitledNotepad.menu_select("Edit->Replace")
        self.assertEqual(True, is_toplevel_window(self.app.Replace.handle))
        self.assertEqual(False, is_toplevel_window(self.app.Replace.Cancel.handle))
        self.app.Replace.Cancel.click()

    def test_is64bitprocess(self):
        """Make sure a 64-bit process detection returns correct results"""
        if is_x64_OS():
            # Test a 32-bit app running on x64
            expected_is64bit = False
            if is_x64_Python():
                exe32bit = os.path.join(os.path.dirname(__file__),
                              r"..\..\apps\MFC_samples\RowList.exe")
                app = Application().start(exe32bit, timeout=20)
                pid = app.RowListSampleApplication.process_id()
                res_is64bit = is64bitprocess(pid)
                try:
                    self.assertEqual(expected_is64bit, res_is64bit)
                finally:
                    # make sure to close an additional app we have opened
                    app.kill()

                # setup expected for a 64-bit app on x64
                expected_is64bit = True
        else:
            # setup expected for a 32-bit app on x86
            expected_is64bit = False

        # test native Notepad app
        res_is64bit = is64bitprocess(self.app.UntitledNotepad.process_id())
        self.assertEqual(expected_is64bit, res_is64bit)

    def test_is64bitbinary(self):
        exe32bit = os.path.join(os.path.dirname(__file__),
            r"..\..\apps\MFC_samples\RowList.exe")
        dll32bit = os.path.join(os.path.dirname(__file__),
            r"..\..\apps\MFC_samples\mfc100u.dll")
        self.assertEqual(is64bitbinary(exe32bit), False)
        self.assertEqual(is64bitbinary(dll32bit), None)

        warnings.filterwarnings('always', category=RuntimeWarning, append=True)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            is64bitbinary(dll32bit)
            assert len(w) >= 1
            assert issubclass(w[-1].category, RuntimeWarning)
            assert "Cannot get binary type for file" in str(w[-1].message)


    def test_dumpwindow(self):
        """Make sure dumpwindow() function works"""
        dlgdump = dumpwindow(self.dlghandle)

        for key, item in dlgdump.items():
            self.assertEqual(item, globals()[key](self.dlghandle))

        editdump = dumpwindow(self.edit_handle)

        for key, item in editdump.items():
            self.assertEqual(item, globals()[key](self.edit_handle))
示例#56
0
class ButtonTestCases(unittest.TestCase):

    """Unit tests for 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 = self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.app.Common_Controls_Sample.TabControl.select("CDateTimeCtrl")

        self.ctrl = self.app.Common_Controls_Sample

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

    def testGetProperties(self):
        """Test getting the properties for the button control"""
        props = self.ctrl.Button2.get_properties()

        self.assertEqual(
            "Button", props['friendly_class_name'])

        self.assertEqual(
            self.ctrl.Button2.texts(), props['texts'])

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

    def test_NeedsImageProp(self):
        """Test whether an image needs to be saved with the properties"""
        self.assertEqual(self.ctrl.OKButton._needs_image_prop, True)
        self.assertEqual('image' in self.ctrl.OKButton.get_properties(), True)

    def testFriendlyClass(self):
        """Test the friendly_class_name method"""
        self.assertEqual(self.ctrl.Button2.friendly_class_name(), "Button")
        self.assertEqual(self.ctrl.RadioButton2.friendly_class_name(), "RadioButton")

    def testCheckUncheck(self):
        """Test unchecking a control"""
        self.ctrl.RadioButton2.check()
        self.assertEqual(self.ctrl.RadioButton2.get_check_state(), 1)
        self.ctrl.RadioButton2.uncheck()
        self.assertEqual(self.ctrl.RadioButton2.get_check_state(), 0)

    def testGetCheckState_unchecked(self):
        """Test whether the control is unchecked"""
        self.assertEqual(self.ctrl.RadioButton.get_check_state(), 0)

    def testGetCheckState_checked(self):
        """Test whether the control is checked"""
        self.ctrl.RadioButton2.check()
        self.assertEqual(self.ctrl.RadioButton2.get_check_state(), 1)

#    def testGetCheckState_indeterminate(self):
#        "indeterminate"
#        self.calc.Inv.set_check_indeterminate()
#        self.assertEqual(self.calc.Inv.get_check_state(), 0)

    def testClick(self):
        """Test clicking on buttons"""
        self.ctrl.RadioButton2.click()  # DTS_SHORTDATEFORMAT
        self.ctrl.RadioButton.click()  # DTS_TIMEFORMAT
        self.ctrl.RadioButton3.click()  # DTS_LONGDATEFORMAT
        self.assertEqual(self.ctrl.RadioButton3.get_check_state(), 1)

    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.assertEqual(self.ctrl.RadioButton.get_check_state(), 0)

        self.ctrl.RadioButton.click()

        self.assertEqual(self.ctrl.RadioButton.get_check_state(), 1)
示例#57
0
class DialogTestCases(unittest.TestCase):

    """Unit tests for the DialogWrapper 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 = self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.cmn_ctrl = self.app.Common_Controls_Sample

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

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

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

        self.assertEqual(
            "Dialog", props['friendly_class_name'])

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

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

    def testRunTests(self):
        """Test running the UI tests on the dialog"""
        bugs = self.cmn_ctrl.run_tests()
        from pywinauto.controls.hwndwrapper import HwndWrapper
        self.assertEqual(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 xml_helpers.ReadPropertiesFromFile("ref_controls.xml")]

        bugs = self.cmn_ctrl.run_tests(ref_controls = ref_controls)
        from pywinauto import tests
        tests.print_bugs(bugs)
        from pywinauto.controls.hwndwrapper import HwndWrapper
        self.assertEqual(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.cmn_ctrl.write_to_xml("test_output.xml")

        all_props = [self.cmn_ctrl.get_properties()]
        all_props.extend([c.get_properties() for c in self.cmn_ctrl.children()])

        props = xml_helpers.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)

                if ctrl_value == 'None':
                    ctrl_value = None

                self.assertEqual(ctrl_value, expected_value)

        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.cmn_ctrl.client_area_rect()
        rectangle = self.cmn_ctrl.rectangle()
        self.assertFalse((clientarea.left - rectangle.left) > 10)
        self.assertFalse((clientarea.top - rectangle.top) > 60)
        self.assertFalse((rectangle.right - clientarea.right) > 10)
        self.assertFalse((rectangle.bottom - clientarea.bottom) > 10)

    def testHideFromTaskbar(self):
        """Test that a dialog can be hidden from the Windows taskbar"""
        self.assertEqual(self.cmn_ctrl.is_in_taskbar(), True)
        self.cmn_ctrl.hide_from_taskbar()
        self.assertEqual(self.cmn_ctrl.is_in_taskbar(), False)
        self.cmn_ctrl.show_in_taskbar()
        self.assertEqual(self.cmn_ctrl.is_in_taskbar(), True)
示例#58
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.wrapper_object()

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

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

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

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

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

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

    def testSelectedIndices(self):
        "test that the selected indices are correct"
        self.assertEqual(self.ctrl.selected_indices(), (-1,))
        self.ctrl.select(2)
        self.assertEqual(self.ctrl.selected_indices(), (2, ))

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

    def testSelect(self):
        "Test selecting an item"
        self.ctrl.select(1)
        self.assertEqual(self.ctrl.selected_indices(), (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.assertEqual(self.ctrl.selected_indices(), (1, ))

    def testGetSetItemFocus(self):
        "Test setting and getting the focus of a particular item"
        self.ctrl.set_item_focus(0)
        self.assertEqual(self.ctrl.get_item_focus(), 0)

        self.ctrl.set_item_focus(2)
        self.assertEqual(self.ctrl.get_item_focus(), 2)
示例#59
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.wrapper_object()

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

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

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

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

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

    def testDroppedRect(self):
        "Test that the dropped rect is correct"
        rect = self.ctrl.dropped_rect()
        #import pdb;pdb.set_trace()
        self.assertEqual(rect.left, 0)
        self.assertEqual(rect.top, 0)
        self.assertEqual(rect.right, self.ctrl.client_rect().right)
        self.assertEqual(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.assertEqual(self.ctrl.selected_index(), 1)
        #self.assertEqual(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.assertEqual(self.ctrl.selected_index(), 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.assertEqual(self.ctrl.selected_index(), 0)
        self.ctrl.select("Left (UDS_ALIGNLEFT)")
        self.assertEqual(self.ctrl.selected_index(), 1)
        self.assertEqual(self.ctrl.selected_text(), "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.assertEqual(self.app.Common_Controls_Sample.OrientationComboBox.selected_index(), 0)
        self.app.Common_Controls_Sample.OrientationComboBox.select(1)
        self.assertEqual(self.app.Common_Controls_Sample.OrientationComboBox.selected_index(), 1)

    def testItemData(self):
        "Test that it doesn't raise"
        self.ctrl.item_data(0)
        self.ctrl.item_data(1)
        self.ctrl.item_data("Right (UDS_ALIGNRIGHT)")
        self.ctrl.item_data(self.ctrl.item_count() - 1)