def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() import os.path path = os.path.split(__file__)[0] test_file = os.path.join(path, "test.txt") with codecs.open(test_file, mode="rb", encoding='utf-8') as f: self.test_data = f.read() # remove the BOM if it exists self.test_data = self.test_data.replace(repr("\xef\xbb\xbf"), "") #self.test_data = self.test_data.encode('utf-8', 'ignore') # XXX: decode raises UnicodeEncodeError even if 'ignore' is used! print('self.test_data:') print(self.test_data.encode('utf-8', 'ignore')) app.start_("Notepad.exe " + test_file, timeout=20) self.app = app self.dlg = app.UntitledNotepad self.ctrl = self.dlg.Edit.WrapperObject() self.old_pos = self.dlg.Rectangle self.dlg.MoveWindow(10, 10, 400, 400)
class GetDialogPropsFromHandleTest(unittest.TestCase): "Unit tests for mouse actions of the HwndWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() 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.TypeKeys("%{F4}") def test_GetDialogPropsFromHandle(self): "Test some small stuff regarding GetDialogPropsFromHandle" props_from_handle = GetDialogPropsFromHandle(self.dlg.handle) props_from_dialog = GetDialogPropsFromHandle(self.dlg) props_from_ctrl = GetDialogPropsFromHandle(self.ctrl) self.assertEquals(props_from_handle, props_from_dialog)
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() import os.path path = os.path.split(__file__)[0] test_file = os.path.join(path, "test.txt") self.test_data = open(test_file, "rb").read() # remove the BOM if it exists self.test_data = self.test_data.replace("\xef\xbb\xbf", "") self.test_data = self.test_data.decode('utf-8') app.start_("Notepad.exe " + test_file) self.app = app self.dlg = app.UntitledNotepad self.ctrl = self.dlg.Edit.WrapperObject() self.old_pos = self.dlg.Rectangle self.dlg.MoveWindow(10, 10, 400, 400)
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" self.texts = [u'', u'New', u'Open', u'Save', u'Cut', u'Copy', u'Paste', u'Print', u'About', u'Help'] # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) #app.start_(os.path.join(controlspy_folder, "Tooltip.exe")) self.app = app self.dlg = app.Common_Controls_Sample self.dlg.TabControl.Select(u'CToolBarCtrl') ''' tips = app.windows_( visible_only = False, enabled_only = False, top_level_only = False, class_name = "tooltips_class32") ''' self.ctrl = self.dlg.Toolbar.GetToolTipsControl() #WrapHandle(tips[1])
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "RowList.exe"), timeout=20) self.texts = [u"Color", u"Red", u"Green", u"Blue", u"Hue", u"Sat", u"Lum", u"Type"] self.item_rects = [ RECT(0, 0, 150, 19), RECT(150, 0, 200, 19), RECT(200, 0, 250, 19), RECT(250, 0, 300, 19), RECT(300, 0, 400, 19), RECT(400, 0, 450, 19), RECT(450, 0, 500, 19), RECT(500, 0, 650, 19), ] self.app = app self.dlg = app.RowListSampleApplication # top_window_() self.ctrl = app.RowListSampleApplication.Header.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, u"RowList.exe")) self.texts = [ (u"Yellow", u"255", u"255", u"0", u"40", u"240", u"120", u"Neutral"), (u"Red", u"255", u"0", u"0", u"0", u"240", u"120", u"Warm"), (u"Green", u"0", u"255", u"0", u"80", u"240", u"120", u"Cool"), (u"Magenta", u"255", u"0", u"255", u"200", u"240", u"120", u"Warm"), (u"Cyan", u"0", u"255", u"255", u"120", u"240", u"120", u"Cool"), (u"Blue", u"0", u"0", u"255", u"160", u"240", u"120", u"Cool"), (u"Gray", u"192", u"192", u"192", u"160", u"0", u"181", u"Neutral"), ] self.app = app self.dlg = app.RowListSampleApplication # top_window_() self.ctrl = app.RowListSampleApplication.ListView.WrapperObject() self.dlg.Toolbar.Button(0).Click() # switch to icon view self.dlg.Toolbar.Button(6).Click() # switch off states
class GetDialogPropsFromHandleTest(unittest.TestCase): "Unit tests for mouse actions of the HwndWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() if is_x64_Python() or not is_x64_OS(): self.app.start_(r"C:\Windows\System32\notepad.exe") else: self.app.start_(r"C:\Windows\SysWOW64\notepad.exe") self.dlg = self.app.UntitledNotepad self.ctrl = HwndWrapper(self.dlg.Edit.handle) def tearDown(self): "Close the application after tests" # close the application #self.dlg.TypeKeys("%{F4}") self.dlg.Close(0.5) self.app.kill_() def test_GetDialogPropsFromHandle(self): "Test some small stuff regarding GetDialogPropsFromHandle" props_from_handle = GetDialogPropsFromHandle(self.dlg.handle) props_from_dialog = GetDialogPropsFromHandle(self.dlg) #unused var: props_from_ctrl = GetDialogPropsFromHandle(self.ctrl) self.assertEquals(props_from_handle, props_from_dialog)
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Tree View.exe")) self.root_text = "The Planets" self.texts = [ ("Mercury", '57,910,000', '4,880', '3.30e23'), ("Venus", '108,200,000', '12,103.6', '4.869e24'), ("Earth", '149,600,000', '12,756.3', '5.9736e24'), ("Mars", '227,940,000', '6,794', '6.4219e23'), ("Jupiter", '778,330,000', '142,984', '1.900e27'), ("Saturn", '1,429,400,000', '120,536', '5.68e26'), ("Uranus", '2,870,990,000', '51,118', '8.683e25'), ("Neptune", '4,504,000,000', '49,532', '1.0247e26'), ("Pluto", '5,913,520,000', '2,274', '1.27e22'), ] self.app = app self.dlg = app.MicrosoftControlSpy #top_window_() self.ctrl = app.MicrosoftControlSpy.TreeView.WrapperObject()
class RemoteMemoryBlockTests(unittest.TestCase): "Unit tests for RemoteMemoryBlock" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe")) self.dlg = self.app.Common_Controls_Sample self.ctrl = self.dlg.TreeView.WrapperObject() def tearDown(self): "Close the application after tests" self.app.kill_() def testGuardSignatureCorruption(self): mem = RemoteMemoryBlock(self.ctrl, 16) buf = ctypes.create_string_buffer(24) self.assertRaises(Exception, mem.Write, buf) mem.size = 24 # test hack self.assertRaises(Exception, mem.Write, buf)
def testGetattr(self): "Test that __getattr__() works correctly" app = Application() app.start_(_notepad_exe()) #prev_timeout = application.window_find_timeout #application.window_find_timeout = .1 self.assertRaises( findbestmatch.MatchError, app.blahblah.__getattr__, 'handle') self.assertEqual( app.UntitledNotepad.handle, app.window_(title = "Untitled - Notepad").handle) app.UntitledNotepad.MenuSelect("Help->About Notepad") # I think it's OK that this no longer raises a matcherror # just because the window is not enabled - doesn't mean you # should not be able to access it at all! #self.assertRaises(findbestmatch.MatchError, # app.Notepad.__getattr__, 'handle') self.assertEqual( app.AboutNotepad.handle, app.window_(title = "About Notepad").handle) app.AboutNotepad.Ok.Click() app.UntitledNotepad.MenuSelect("File->Exit")
class NotepadRegressionTests(unittest.TestCase): "Regression unit tests for Notepad" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_(_notepad_exe()) self.dlg = self.app.Window_(title='Untitled - Notepad', class_name='Notepad') self.ctrl = HwndWrapper(self.dlg.Edit.handle) self.dlg.edit.SetEditText("Here is some text\r\n and some more") self.app2 = Application.start(_notepad_exe()) def tearDown(self): "Close the application after tests" # close the application try: self.dlg.Close(0.5) if self.app.Notepad["Do&n't Save"].Exists(): self.app.Notepad["Do&n't Save"].Click() self.app.Notepad["Do&n't Save"].WaitNot('visible') except Exception: # timings.TimeoutError: pass finally: self.app.kill_() self.app2.kill_() def testMenuSelectNotepad_bug(self): "In notepad - MenuSelect Edit->Paste did not work" text = b'Here are some unicode characters \xef\xfc\r\n' self.app2.UntitledNotepad.Edit.Wait('enabled') time.sleep(0.3) self.app2.UntitledNotepad.Edit.SetEditText(text) time.sleep(0.3) self.assertEquals(self.app2.UntitledNotepad.Edit.TextBlock().encode(locale.getpreferredencoding()), text) Timings.after_menu_wait = .7 self.app2.UntitledNotepad.MenuSelect("Edit->Select All") time.sleep(0.3) self.app2.UntitledNotepad.MenuSelect("Edit->Copy") time.sleep(0.3) self.assertEquals(clipboard.GetData().encode(locale.getpreferredencoding()), text) self.dlg.SetFocus() self.dlg.MenuSelect("Edit->Select All") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") self.app2.UntitledNotepad.MenuSelect("File->Exit") self.app2.Window_(title='Notepad', class_name='#32770')["Don't save"].Click() self.assertEquals(self.dlg.Edit.TextBlock().encode(locale.getpreferredencoding()), text*3)
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(controlspy_folder + "Tab.exe") self.texts = [ "Pluto", "Neptune", "Uranus", "Saturn", "Jupiter", "Mars", "Earth", "Venus", "Mercury", "Sun"] self.rects = [ RECT(2,2,80,21), RECT(80,2,174,21), RECT(174,2,261,21), RECT(2,21,91,40), RECT(91,21,180,40), RECT(180,21,261,40), RECT(2,40,64,59), RECT(64,40,131,59), RECT(131,40,206,59), RECT(206,40,261,59), ] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.TabControl.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Tab.exe")) self.texts = [ "Pluto", "Neptune", "Uranus", "Saturn", "Jupiter", "Mars", "Earth", "Venus", "Mercury", "Sun"] self.rects = [ RECT(2,2,63,21), RECT(63,2,141,21), RECT(141,2,212,21), RECT(212,2,280,21), RECT(280,2,348,21), RECT(2,21,68,40), RECT(68,21,135,40), RECT(135,21,207,40), RECT(207,21,287,40), RECT(287,21,348,40), ] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.TabControl.WrapperObject()
def testClickCustomizeButton(self): "Test click on the 'show hidden icons' button" # Minimize to tray self.dlg.Minimize() self.dlg.WaitNot("active") # Make sure that the hidden icons area is enabled orig_hid_state = _toggle_notification_area_icons(show_all=False, debug_img="%s_01.jpg" % (self.id())) # Run one more instance of the sample app # hopefully one of the icons moves into the hidden area app2 = Application() app2.start_(os.path.join(mfc_samples_folder, u"TrayMenu.exe")) dlg2 = app2.TrayMenu dlg2.Wait("visible") dlg2.Minimize() dlg2.WaitNot("active") # Test click on "Show Hidden Icons" button taskbar.ShowHiddenIconsButton.ClickInput() niow_dlg = taskbar.explorer_app.Window_(class_name="NotifyIconOverflowWindow") niow_dlg.OverflowNotificationAreaToolbar.Wait("ready", timeout=30) niow_dlg.SysLink.ClickInput() nai = taskbar.explorer_app.Window_(title="Notification Area Icons", class_name="CabinetWClass") origAlwaysShow = nai.CheckBox.GetCheckState() if not origAlwaysShow: nai.CheckBox.ClickInput() nai.OK.Click() # Restore Notification Area settings _toggle_notification_area_icons(show_all=orig_hid_state, debug_img="%s_02.jpg" % (self.id())) # close the second sample app dlg2.SendMessage(win32defines.WM_CLOSE)
def testGetitem(self): "Test that __getitem__() works correctly" app = Application() app.start_(_notepad_exe()) try: app['blahblah'] except Exception: pass #prev_timeout = application.window_find_timeout #application.window_find_timeout = .1 self.assertRaises( findbestmatch.MatchError, app['blahblah']['not here'].__getitem__, 'handle') self.assertEqual( app[u'Unt\xeftledNotepad'].handle, app.window_(title = "Untitled - Notepad").handle) app.UntitledNotepad.MenuSelect("Help->About Notepad") self.assertEqual( app['AboutNotepad'].handle, app.window_(title = "About Notepad").handle) app.AboutNotepad.Ok.Click() app.UntitledNotepad.MenuSelect("File->Exit")
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" self.screen_w = win32api.GetSystemMetrics(0) # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) self.texts = [ u"CTreeCtrl", u"CAnimateCtrl", u"CToolBarCtrl", u"CDateTimeCtrl", u"CMonthCalCtrl"] self.rects = [ RECT(2, 2, 58, 20), RECT(58, 2, 130, 20), RECT(130, 2, 201, 20), RECT(201, 2, 281, 20), RECT(281, 2, 360, 20) ] self.app = app self.dlg = app.CommonControlsSample self.ctrl = app.CommonControlsSample.TabControl.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" app = Application() app.start_(os.path.join(mfc_samples_folder, u"TrayMenu.exe")) self.app = app self.dlg = app.TrayMenu # top_window_() self.dlg.Wait("ready")
def testConnect_process(self): "Test that connect_() works with a process" app1 = Application() app1.start_(_notepad_exe()) app_conn = Application() app_conn.connect_(process = app1.process) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def testActiveWindow(self): "Test that active_() works correctly" app = Application() self.assertRaises(AppNotConnected, app.active_) self.assertRaises(AppNotConnected, app.is64bit) app.start_(_notepad_exe()) app.UntitledNotepad.Wait('ready') self.assertEqual(app.active_().handle, app.UntitledNotepad.handle) app.UntitledNotepad.MenuSelect("File->Exit") app.UntitledNotepad.WaitNot('exists') self.assertRaises(RuntimeError, app.active_)
def testStart_bug01(self): "On SourceForge forum AppStartError forgot to include %s for application name" app = Application() self.assertEqual(app.process, None) application.app_start_timeout = 1 app_name = r"I am not * and Application!/\.exe" try: app.start_(app_name) except AppStartError as e: self.assertEquals(app_name in str(e), True)
def testConnect_handle(self): "Test that connect_() works with a handle" app1 = Application() app1.start_(_notepad_exe()) handle = app1.UntitledNotepad.handle app_conn = Application() app_conn.connect_(handle = handle) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(controlspy_folder + "rebar.exe") self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.Rebar.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Up-Down.exe")) self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.UpDown2.WrapperObject()
def teststart_(self): "test start_() works correctly" app = Application() self.assertEqual(app.process, None) app.start_(_notepad_exe()) self.assertNotEqual(app.process, None) self.assertEqual(app.UntitledNotepad.ProcessID(), app.process) notepadpath = os.path.join(os.environ['systemroot'], self.notepad_subpath) self.assertEqual(str(process_module(app.process)).lower(), str(notepadpath).lower()) app.UntitledNotepad.MenuSelect("File->Exit")
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Status bar.exe")) self.texts = ["Long text", "", "Status Bar"] self.part_rects = [RECT(0, 2, 65, 22), RECT(67, 2, 90, 22), RECT(92, 2, 261, 22)] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.StatusBar.WrapperObject()
def testConnect_windowspec(self): "Test that connect_() works with a windowspec" app1 = Application() app1.start_(_notepad_exe()) #unused var: handle = app1.UntitledNotepad.handle app_conn = Application() try: app_conn.connect_(title = "Untitled - Notepad") except findwindows.WindowAmbiguousError: wins = findwindows.find_windows(title = "Untitled - Notepad") app_conn.connect_(handle = wins[0]) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Header.exe")) self.texts = [u'Distance', u'Diameter', u'Mass'] self.item_rects = [ RECT(0, 0, 90, 26), RECT(90, 0, 180, 26), RECT(180, 0, 260, 26)] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.Header.WrapperObject()
def testConnect_path(self): "Test that connect_() works with a path" app1 = Application() app1.start_(_notepad_exe()) app_conn = Application() app_conn.connect_(path = self.notepad_subpath) self.assertEqual(app1.process, app_conn.process) app_conn = Application() if is_x64_Python() or not is_x64_OS(): app_conn.connect_(path = r"c:\windows\system32\notepad.exe") else: app_conn.connect_(path = r"c:\windows\syswow64\notepad.exe") self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def testTopWindow(self): "Test that top_window_() works correctly" app = Application() self.assertRaises(AppNotConnected, app.top_window_) app.start_(_notepad_exe()) self.assertEqual(app.UntitledNotepad.handle, app.top_window_().handle) app.UntitledNotepad.MenuSelect("Help->About Notepad") self.assertEqual(app.AboutNotepad.handle, app.top_window_().handle) app.AboutNotepad.Ok.Click() app.UntitledNotepad.MenuSelect("File->Exit") app.UntitledNotepad.WaitNot('exists') self.assertRaises(RuntimeError, app.top_window_)
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Header.exe")) self.texts = [u'Distance', u'Diameter', u'Mass'] self.item_rects = [ RECT(0, 0, 90, 21), RECT(90, 0, 180, 21), RECT(180, 0, 260, 21) ] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.Header.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(controlspy_folder, "Status bar.exe")) self.texts = ["Long text", "", "Status Bar"] self.part_rects = [ RECT(0, 2, 65, 20), RECT(67, 2, 90, 20), RECT(92, 2, 357, 20) ] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.StatusBar.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it. The app title can be tricky. If no document is opened the title is just: "RebarTest" However if an document is created/opened in the child frame the title is appended with a document name: "RebarTest - RebarTest1" A findbestmatch proc does well here with guessing the title even though the app is started with a short title "RebarTest". """ # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "RebarTest.exe")) self.app = app self.dlg = app.RebarTest_RebarTest self.ctrl = app.RebarTest_RebarTest.Rebar.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" self.texts = ['Tooltip Tool 0', 'Tooltip Tool 1', 'Tooltip Tool 2'] # start the application from pywinauto.application import Application app = Application() app.start_(controlspy_folder + "Tooltip.exe") self.app = app self.dlg = app.MicrosoftControlSpy tips = app.windows_(visible_only=False, enabled_only=False, top_level_only=False, class_name="tooltips_class32") self.ctrl = WrapHandle(tips[1])
def testWindows(self): "Test that windows_() works correctly" app = Application() self.assertRaises(AppNotConnected, app.windows_, **{'title': 'not connected'}) app.start_('notepad.exe') notepad_handle = app.UntitledNotepad.handle self.assertEquals(app.windows_(visible_only=True), [notepad_handle]) app.UntitledNotepad.MenuSelect("Help->About Notepad") aboutnotepad_handle = app.AboutNotepad.handle self.assertEquals(app.windows_(visible_only=True, enabled_only=False), [aboutnotepad_handle, notepad_handle]) app.AboutNotepad.OK.Click() app.UntitledNotepad.MenuSelect("File->Exit")
def setUp(self): """Start the application set some data and ensure the application is in the state we want it. The app title can be tricky. If no document is opened the title is just: "RebarTest" However if an document is created/opened in the child frame the title is appended with a document name: "RebarTest - RebarTest1" A findbestmatch proc does well here with guessing the title even though the app is started with a short title "RebarTest". """ # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "RebarTest.exe")) self.app = app self.dlg = app.RebarTest_RebarTest self.dlg.Wait('ready', 20) self.ctrl = app.RebarTest_RebarTest.Rebar.WrapperObject()
class DragAndDropTests(unittest.TestCase): "Unit tests for mouse actions like drag-n-drop" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe")) self.dlg = self.app.Common_Controls_Sample self.ctrl = self.dlg.TreeView.WrapperObject() def tearDown(self): "Close the application after tests" self.app.kill_() ''' def testDragMouse(self): "DragMouse works! But CmnCtrl1.exe crashes in infinite recursion." birds = self.ctrl.GetItem(r'\Birds') dogs = self.ctrl.GetItem(r'\Dogs') self.ctrl.DragMouse("left", birds.Rectangle().mid_point(), dogs.Rectangle().mid_point()) dogs = self.ctrl.GetItem(r'\Dogs') self.assertEquals([child.Text() for child in dogs.Children()], [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane']) ''' def testDragMouseInput(self): "test for DragMouseInput" birds = self.ctrl.GetItem(r'\Birds') dogs = self.ctrl.GetItem(r'\Dogs') birds.ClickInput() time.sleep(5) # enough pause to prevent double click detection self.ctrl.DragMouseInput("left", birds.Rectangle().mid_point(), dogs.Rectangle().mid_point()) dogs = self.ctrl.GetItem(r'\Dogs') self.assertEquals( [child.Text() for child in dogs.Children()], [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane'])
class MenuWrapperTests(unittest.TestCase): "Unit tests for the TreeViewWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_("Notepad.exe") self.dlg = self.app.Notepad def tearDown(self): "Close the application after tests" # close the application #self.dlg.TypeKeys("%{F4}") self.app.kill_() def testInvalidHandle(self): "Test that an exception is raised with an invalid menu handle" #self.assertRaises(InvalidWindowHandle, HwndWrapper, -1) pass def testItemCount(self): self.assertEquals(5, self.dlg.Menu().ItemCount()) def testItem(self): pass def testItems(self): pass def testGetProperties(self): pass def testGetMenuPath(self): pass def test__repr__(self): pass
class PopupMenuTestCases(unittest.TestCase): "Unit tests for the DialogWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() self.app.start_("notepad.exe") self.app.Notepad.Edit.RightClick() self.popup = self.app.PopupMenu.WrapperObject() def tearDown(self): "Close the application after tests" self.popup.TypeKeys("{ESC}") self.app.Notepad.TypeKeys("%{F4}") def testGetProperties(self): "Test getting the properties for the PopupMenu" props = self.popup.GetProperties() self.assertEquals( "PopupMenu", props['FriendlyClassName']) self.assertEquals(self.popup.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.popup, prop_name)(), props[prop_name]) def testIsDialog(self): "Ensure that IsDialog works correctly" self.assertEquals(True, self.popup.IsDialog()) def test_menu_handle(self): "Ensure that the menu handle is returned" handle = self.popup._menu_handle() self.assertNotEquals(0, handle)
def testClickCustomizeButton(self): "Test click on the 'show hidden icons' button" # Minimize to tray self.dlg.Minimize() self.dlg.WaitNot('active') # Make sure that the hidden icons area is enabled orig_hid_state = _toggle_notification_area_icons( show_all=False, debug_img="%s_01.jpg" % (self.id())) # Run one more instance of the sample app # hopefully one of the icons moves into the hidden area app2 = Application() app2.start_(os.path.join(mfc_samples_folder, u"TrayMenu.exe")) dlg2 = app2.TrayMenu dlg2.Wait('visible') dlg2.Minimize() dlg2.WaitNot('active') # Test click on "Show Hidden Icons" button taskbar.ShowHiddenIconsButton.ClickInput() niow_dlg = taskbar.explorer_app.Window_( class_name='NotifyIconOverflowWindow') niow_dlg.OverflowNotificationAreaToolbar.Wait('ready', timeout=30) niow_dlg.SysLink.ClickInput() nai = taskbar.explorer_app.Window_(title="Notification Area Icons", class_name="CabinetWClass") origAlwaysShow = nai.CheckBox.GetCheckState() if not origAlwaysShow: nai.CheckBox.ClickInput() nai.OK.Click() # Restore Notification Area settings _toggle_notification_area_icons(show_all=orig_hid_state, debug_img="%s_02.jpg" % (self.id())) # close the second sample app dlg2.SendMessage(win32defines.WM_CLOSE)
def testClickHiddenIcon(self): """ Test minimizing a sample app into the hidden area of the tray and restoring the app back """ if is_x64_Python() != is_x64_OS(): # We don't run this test for mixed cases: # a 32-bit Python process can't interact with # a 64-bit explorer process (taskbar) and vice versa return # Make sure that the hidden icons area is enabled orig_hid_state = _toggle_notification_area_icons( show_all=False, debug_img="%s_01.jpg" % (self.id())) self.dlg.Minimize() self.dlg.WaitNot('active') # Run one more instance of the sample app # hopefully one of the icons moves into the hidden area app2 = Application() app2.start_(os.path.join(mfc_samples_folder, u"TrayMenu.exe")) dlg2 = app2.TrayMenu dlg2.Wait('visible') dlg2.Minimize() dlg2.WaitNot('active') # Click in the hidden area taskbar.explorer_app.WaitCPUUsageLower(threshold=5, timeout=40) taskbar.ClickHiddenSystemTrayIcon('MFCTrayDemo', double=True) self.dlg.Wait('visible', timeout=30) # Restore Notification Area settings _toggle_notification_area_icons(show_all=orig_hid_state, debug_img="%s_02.jpg" % (self.id())) dlg2.SendMessage(win32defines.WM_CLOSE)
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) self.app = app self.dlg = app.CommonControlsSample # select a tab with toolbar controls self.dlg.SysTabControl.Select(u"CToolBarCtrl") # see identifiers available at that tab #self.dlg.PrintControlIdentifiers() # The sample app has two toolbars. The first toolbar can be # addressed as Toolbar, Toolbar0 and Toolbar1. # The second control goes as Toolbar2 self.ctrl = app.CommonControlsSample.ToolbarNew.WrapperObject() self.ctrl2 = app.CommonControlsSample.ToolbarErase.WrapperObject()
def testWindow(self): "Test that window_() works correctly" app = Application() app.start_(_notepad_exe()) title = app.window_(title="Untitled - Notepad") title_re = app.window_(title_re="Untitled[ -]+Notepad") classname = app.window_(class_name="Notepad") classname_re = app.window_(class_name_re="Not..ad") handle = app.window_(handle=title.handle) bestmatch = app.window_(best_match="Untiotled Notepad") self.assertNotEqual(title.handle, None) self.assertNotEqual(title.handle, 0) self.assertEqual(title.handle, title_re.handle) self.assertEqual(title.handle, classname.handle) self.assertEqual(title.handle, classname_re.handle) self.assertEqual(title.handle, handle.handle) self.assertEqual(title.handle, bestmatch.handle) app.UntitledNotepad.MenuSelect("File->Exit")
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, "RowList.exe"), timeout=20) self.texts = [u'Color', u'Red', u'Green', u'Blue', u'Hue', u'Sat', u'Lum', u'Type'] self.item_rects = [ RECT ( 0, 0, 150, 19), RECT (150, 0, 200, 19), RECT (200, 0, 250, 19), RECT (250, 0, 300, 19), RECT (300, 0, 400, 19), RECT (400, 0, 450, 19), RECT (450, 0, 500, 19), RECT (500, 0, 650, 19)] self.app = app self.dlg = app.RowListSampleApplication #top_window_() self.ctrl = app.RowListSampleApplication.Header.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(controlspy_folder + "List View.exe") self.texts = [ ("Mercury", '57,910,000', '4,880', '3.30e23'), ("Venus", '108,200,000', '12,103.6', '4.869e24'), ("Earth", '149,600,000', '12,756.3', '5.9736e24'), ("Mars", '227,940,000', '6,794', '6.4219e23'), ("Jupiter", '778,330,000', '142,984', '1.900e27'), ("Saturn", '1,429,400,000', '120,536', '5.68e26'), ("Uranus", '2,870,990,000', '51,118', '8.683e25'), ("Neptune", '4,504,000,000', '49,532', '1.0247e26'), ("Pluto", '5,913,520,000', '2,274', '1.27e22'), ] self.app = app self.dlg = app.MicrosoftControlSpy #top_window_() self.ctrl = app.MicrosoftControlSpy.ListView.WrapperObject()
def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application app = Application() app.start_(os.path.join(mfc_samples_folder, u"RowList.exe")) self.texts = [ (u"Yellow", u"255", u"255", u"0", u"40", u"240", u"120", u"Neutral"), (u"Red", u"255", u"0", u"0", u"0", u"240", u"120", u"Warm"), (u"Green", u"0", u"255", u"0", u"80", u"240", u"120", u"Cool"), (u"Magenta", u"255", u"0", u"255", u"200", u"240", u"120", u"Warm"), (u"Cyan", u"0", u"255", u"255", u"120", u"240", u"120", u"Cool"), (u"Blue", u"0", u"0", u"255", u"160", u"240", u"120", u"Cool"), (u"Gray", u"192", u"192", u"192", u"160", u"0", u"181", u"Neutral") ] self.app = app self.dlg = app.RowListSampleApplication #top_window_() self.ctrl = app.RowListSampleApplication.ListView.WrapperObject() self.dlg.Toolbar.Button(0).Click() # switch to icon view self.dlg.Toolbar.Button(6).Click() # switch off states
class banques: """Classe principale permettant de regrouper les fonctions d'automatisation""" def __init__(self): "Constructeur de l'objet principale du module pywinauto: l'applicaton a automatiser" self.app = Application() #Etape 0 (cf blog www.python4d.com) try: #Connection de l'objet app avec le process lié à la fenêtre principale Google Chrome self.app.connect_(title_re=".* - Google Chrome", class_name=r"Chrome_WidgetWin_1") except: #lancer un nouveau process Chrome et s'y connecter #Etape 1(cf blog www.python4d.com) self.app.start_( r"C:\Users\damien\AppData\Local\Google\Chrome\Application\chrome.exe", timeout=2) sleep(5) self.app["Chrome_WidgetWin_1"].Maximize() #Mettre le curseur souris à un endroit qui ne perturbe pas le focus des fenêtres du browser SetCursorPos(0, 0) sleep(1) #fenêtre de l'application tout entière Chrome self.ChromeWin = self.app["Chrome_WidgetWin_1"] #fenêtre (textbox) de l'URL self.ChromeUrl = self.app["Chrome_WidgetWin_1"]["Chrome_OmniboxView"] #Etape n°2 (cf blog www.python4d.com) self.newtab() def newtab(self): "Méthode qui lance un CTRL-T sur l'application Chrome: création d'un nouvel onglet" sleep(2) self.ChromeWin.TypeKeys(r"^T") #Mettre le curseur souris à un endroit qui ne perturbe pas le focus des fenêtres du browser SetCursorPos(0, 0) sleep(1) def matchtemplate(self, img1, img2): "Méthode de comparaison entre deux images [cv2.matchTemplate (OpenCV)]" imgVignette = cv2.imread(img2) imgEcran = cv2.imread(img1) result = cv2.matchTemplate(imgEcran, imgVignette, 5) (_, _, _, maxLoc) = cv2.minMaxLoc(result, mask=None) return maxLoc def ingdirect(self, compte="12345{TAB}01011901{ENTER}", mdp="012345"): "Methode automatisant les entrées claviers et souris pour le site INGDIRECT" dirbase = r".//ingdirect//" adrbanque = r"https://secure.ingdirect.fr/public/displayLogin.jsf" #Etape n°3 (cf blog www.python4d.com) self.ChromeUrl.TypeKeys("^a" + adrbanque + "{ENTER}"), sleep(4) #Etape n°4 (cf blog www.python4d.com) self.ChromeWin.TypeKeys(compte), sleep(5) #Etape n°5 (cf blog www.python4d.com) WinBoursoramaImage = self.ChromeWin.CaptureAsImage() WinBoursoramaImage.save(dirbase + "WebImage.png") coordy = [ 0, ] * 10 coordx = [ 0, ] * 10 x, y = self.matchtemplate(dirbase + "WebImage.png", dirbase + "VALIDER.png") #Etape n°6/9 (cf blog www.python4d.com) for i in range(0, 10): small = str(i) + '.png' coordx[i], coordy[i] = self.matchtemplate(dirbase + "WebImage.png", dirbase + small) premiere_absisse = x #absisse du premier code correspond à l'absisse de la forme "VALIDER". #Etape n°7/9 (cf blog www.python4d.com) for i in range(3): codex, codey = self.matchtemplate(dirbase + "WebImage.png", dirbase + "code.png") code = int( round(abs(premiere_absisse - codex) / 32.0) ) #on considère que chaque emplacement de code est séparé par 32 points (! dépend de la résolution !) self.ChromeWin.ClickInput(coords=(coordx[int(mdp[code])] + 10, coordy[int(mdp[code])] + 10), double=False) WinBoursoramaImage = self.ChromeWin.CaptureAsImage() WinBoursoramaImage.save(dirbase + "WebImage.png") #Etape n°8 (cf blog www.python4d.com) self.ChromeWin.ClickInput(coords=(x + 10, y + 10), double=False)
class HwndWrapperTests(unittest.TestCase): "Unit tests for the TreeViewWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_("calc.exe") self.dlg = self.app.Calculator self.ctrl = HwndWrapper(self.dlg.Backspace.handle) def tearDown(self): "Close the application after tests" # close the application self.dlg.TypeKeys("%{F4}") def testInvalidHandle(self): "Test that an exception is raised with an invalid window handle" self.assertRaises(InvalidWindowHandle, HwndWrapper, -1) #def testText(self): # "Test getting the window Text of the dialog" # self.assertEquals(self.dlg.WindowText(), "Untitled - Notepad") def testFriendlyClassName(self): "Test getting the friendly classname of the dialog" self.assertEquals(self.ctrl.FriendlyClassName(), "Button") def testClass(self): "Test getting the classname of the dialog" self.assertEquals(self.ctrl.Class(), "Button") def testWindowText(self): "Test getting the window Text of the dialog" self.assertEquals(self.ctrl.WindowText(), "Backspace") def testStyle(self): self.dlg.Style() self.assertEquals( self.ctrl.Style(), win32defines.WS_CHILD | win32defines.WS_VISIBLE | win32defines.BS_PUSHBUTTON | win32defines.BS_TEXT) def testExStyle(self): self.assertEquals( self.ctrl.ExStyle(), win32defines.WS_EX_NOPARENTNOTIFY | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING | win32defines.WS_EX_RIGHTSCROLLBAR) self.assertEquals( self.dlg.ExStyle(), win32defines.WS_EX_WINDOWEDGE | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING | win32defines.WS_EX_RIGHTSCROLLBAR | win32defines.WS_EX_CONTROLPARENT | win32defines.WS_EX_APPWINDOW) def testControlID(self): self.assertEquals(self.ctrl.ControlID(), 83) self.dlg.ControlID() def testUserData(self): self.ctrl.UserData() self.dlg.UserData() def testContextHelpID(self): self.ctrl.ContextHelpID() self.dlg.ContextHelpID() def testIsVisible(self): self.assertEqual(self.ctrl.IsVisible(), True) self.assertEqual(self.dlg.IsVisible(), True) def testIsUnicode(self): self.assertEqual(self.ctrl.IsUnicode(), True) self.assertEqual(self.dlg.IsUnicode(), True) def testIsEnabled(self): self.assertEqual(self.ctrl.IsEnabled(), True) self.assertEqual(self.dlg.IsEnabled(), True) self.assertEqual( self.dlg.ChildWindow(title='Ave', enabled_only=False).IsEnabled(), False) def testCloseClick_bug(self): self.dlg.Sta.Click() Timings.closeclick_dialog_close_wait = .5 try: self.app.StatisticsBox.CAD.CloseClick() except timings.TimeoutError: pass self.app.StatisticsBox.TypeKeys("%{F4}") #self.assertEquals(self.app.StatisticsBox.Exists(), False) 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) self.assertEqual(rect.height(), 309) self.assertEqual(rect.width(), 480) def testClientRect(self): rect = self.dlg.Rectangle() cli = self.dlg.ClientRect() self.assertEqual(cli.left, 0) self.assertEqual(cli.top, 0) assert (cli.width() < rect.width()) assert (cli.height() < rect.height()) def testFont(self): self.assertNotEqual(self.dlg.Font(), self.ctrl.Font()) def ProcessID(self): self.assertEqual(self.ctrl.ProcessID(), self.dlg.ProcessID) self.assertNotEqual(self.ctrl.ProcessID(), 0) def testHasStyle(self): self.assertEqual(self.ctrl.HasStyle(win32defines.WS_CHILD), True) self.assertEqual(self.dlg.HasStyle(win32defines.WS_CHILD), False) self.assertEqual(self.ctrl.HasStyle(win32defines.WS_SYSMENU), False) self.assertEqual(self.dlg.HasStyle(win32defines.WS_SYSMENU), True) def testHasExStyle(self): self.assertEqual( self.ctrl.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), True) self.assertEqual( self.dlg.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), False) self.assertEqual(self.ctrl.HasExStyle(win32defines.WS_EX_APPWINDOW), False) self.assertEqual(self.dlg.HasExStyle(win32defines.WS_EX_APPWINDOW), True) def testIsDialog(self): self.assertEqual(self.ctrl.IsDialog(), False) self.assertEqual(self.dlg.IsDialog(), True) def testMenuItems(self): self.assertEqual(self.ctrl.MenuItems(), []) self.assertEqual(self.dlg.MenuItems()[1]['Text'], '&View') def testParent(self): self.assertEqual(self.ctrl.Parent(), self.dlg.handle) def testTopLevelParent(self): self.assertEqual(self.ctrl.TopLevelParent(), self.dlg.handle) self.assertEqual(self.dlg.TopLevelParent(), self.dlg.handle) def testTexts(self): self.assertEqual(self.dlg.Texts(), [u'Calculator']) self.assertEqual(self.ctrl.Texts(), [u'Backspace']) self.assertEqual(self.dlg.Edit.Texts(), ['0. ', "0. "]) def testClientRects(self): self.assertEqual(self.ctrl.ClientRects()[0], self.ctrl.ClientRect()) self.assertEqual(self.dlg.ClientRects()[0], self.dlg.ClientRect()) def testFonts(self): self.assertEqual(self.ctrl.Fonts()[0], self.ctrl.Font()) self.assertEqual(self.dlg.Fonts()[0], self.dlg.Font()) def testChildren(self): self.assertEqual(self.ctrl.Children(), []) self.assertNotEqual(self.dlg.Children(), []) def testIsChild(self): self.assertEqual(self.ctrl.IsChild(self.dlg.WrapperObject()), True) self.assertEqual(self.dlg.IsChild(self.ctrl), False) def testSendMessage(self): vk = self.dlg.SendMessage(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) code = self.dlg.Inv.SendMessage(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) def testSendMessageTimeout(self): vk = self.dlg.SendMessageTimeout(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) code = self.dlg.Inv.SendMessageTimeout(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) def testPostMessage(self): self.assertNotEquals(0, self.dlg.PostMessage(win32defines.WM_PAINT)) self.assertNotEquals(0, self.dlg.Inv.PostMessage(win32defines.WM_PAINT)) # def testNotifyMenuSelect(self): # "Call NotifyMenuSelect to ensure it does not raise" # self.ctrl.NotifyMenuSelect(1234) # self.dlg.NotifyMenuSelect(1234) def testNotifyParent(self): "Call NotifyParent to ensure it does not raise" self.ctrl.NotifyParent(1234) #self.dlg.NotifyParent(1234) def testGetProperties(self): "Test getting the properties for the HwndWrapped control" props = self.dlg.GetProperties() self.assertEquals(self.dlg.FriendlyClassName(), props['FriendlyClassName']) self.assertEquals(self.dlg.Texts(), props['Texts']) for prop_name in props: self.assertEquals(getattr(self.dlg, prop_name)(), props[prop_name]) # def testCaptureAsImage(self): # pass def 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): # self.assertRaises() # def testVerifyEnabled(self): # self.assertRaises() # def testVerifyVisible(self): # self.assertRaises() def testMoveWindow_same(self): "Test calling movewindow without any parameters" prevRect = self.dlg.Rectangle() self.dlg.MoveWindow() self.assertEquals(prevRect, self.dlg.Rectangle()) def testMoveWindow(self): "Test moving the window" dlgClientRect = self.dlg.ClientAreaRect() prev_rect = self.ctrl.Rectangle() - dlgClientRect new_rect = win32structures.RECT(prev_rect) new_rect.left -= 1 new_rect.top -= 1 new_rect.right += 2 new_rect.bottom += 2 self.ctrl.MoveWindow( new_rect.left, new_rect.top, new_rect.width(), new_rect.height(), ) self.assertEquals(self.ctrl.Rectangle(), new_rect + dlgClientRect) self.ctrl.MoveWindow(prev_rect) self.assertEquals(self.ctrl.Rectangle(), prev_rect + dlgClientRect) def testMaximize(self): self.dlg.Maximize() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWMAXIMIZED) self.dlg.Restore() def testMinimize(self): self.dlg.Minimize() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWMINIMIZED) self.dlg.Restore() def testRestore(self): self.dlg.Maximize() self.dlg.Restore() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL) self.dlg.Minimize() self.dlg.Restore() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL) def testGetFocus(self): self.assertNotEqual(self.dlg.GetFocus(), None) self.assertEqual(self.dlg.GetFocus(), self.ctrl.GetFocus()) self.dlg.Hyp.SetFocus() self.assertEqual(self.dlg.GetFocus(), self.dlg.Hyp.handle) def testSetFocus(self): self.assertNotEqual(self.dlg.GetFocus(), self.dlg.Hyp.handle) self.dlg.Hyp.SetFocus() self.assertEqual(self.dlg.GetFocus(), self.dlg.Hyp.handle) def testMenuSelect(self): "Test selecting a menut item" if not self.dlg.MenuItem("View -> Digit grouping").IsChecked(): self.dlg.MenuSelect("View -> Digit grouping") self.dlg.TypeKeys("1234567") self.dlg.MenuSelect("Edit->Copy") self.dlg.CE.Click() self.assertEquals(self.dlg.Edit.Texts()[1], "0. ") self.dlg.MenuSelect("Edit->Paste") self.assertEquals(self.dlg.Edit.Texts()[1], "1,234,567. ") def testClose(self): "Test the Close() method of windows" # open the statistics dialog try: self.dlg.Sta.CloseClick() except timings.TimeoutError: pass # make sure it is open and visible self.assertTrue(self.app.StatisticsBox.IsVisible(), True) # close it self.app.StatisticsBox.Close() # make sure that it is not visible self.assertRaises(AttributeError, self.app.StatisticsBox) # make sure the main calculator dialog is still open self.assertEquals(self.dlg.IsVisible(), True)
class HwndWrapperMouseTests(unittest.TestCase): "Unit tests for mouse actions of the HwndWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_("notepad.exe") # Get the old font self.app.UntitledNotepad.MenuSelect("Format->Font") self.old_font = self.app.Font.FontComboBox.SelectedIndex() self.old_font_style = self.app.Font.FontStyleCombo.SelectedIndex() # ensure we have the correct settings for this test self.app.Font.FontStyleCombo.Select(0) self.app.Font.FontComboBox.Select("Lucida Console") self.app.Font.OK.Click() self.dlg = self.app.UntitledNotepad self.ctrl = HwndWrapper(self.dlg.Edit.handle) self.dlg.edit.SetEditText("Here is some text\r\n and some more") def tearDown(self): "Close the application after tests" # Set the old font again self.app.UntitledNotepad.MenuSelect("Format->Font") self.app.Font.FontComboBox.Select(self.old_font) self.app.Font.FontStyleCombo.Select(self.old_font_style) self.app.Font.OK.Click() # close the application self.dlg.TypeKeys("%{F4}") if self.app.Notepad.No.Exists(): self.app.Notepad.No.Click() #def testText(self): # "Test getting the window Text of the dialog" # self.assertEquals(self.dlg.WindowText(), "Untitled - Notepad") def testClick(self): self.ctrl.Click(coords=(50, 10)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (5, 5)) def testClickInput(self): self.ctrl.ClickInput(coords=(50, 10)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (5, 5)) def testDoubleClick(self): self.ctrl.DoubleClick(coords=(60, 30)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (24, 29)) def testDoubleClickInput(self): self.ctrl.DoubleClickInput(coords=(60, 30)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (24, 29)) def testMenuSelectNotepad_bug(self): "In notepad - MenuSelect Edit->Paste did not work" text = u'Here are some unicode characters \xef\xfc\r\n' app2 = Application.start("notepad") app2.UntitledNotepad.Edit.SetEditText(text) app2.UntitledNotepad.MenuSelect("Edit->Select All") app2.UntitledNotepad.MenuSelect("Edit->Copy") self.dlg.MenuSelect("Edit->Select All") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") app2.UntitledNotepad.MenuSelect("File->Exit") app2.Notepad.No.Click() self.assertEquals(self.dlg.Edit.TextBlock(), text * 3)
class HwndWrapperTests(unittest.TestCase): "Unit tests for the TreeViewWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() if is_x64_Python() or not is_x64_OS(): self.app.start_(r"C:\Windows\System32\calc.exe") else: self.app.start_(r"C:\Windows\SysWOW64\calc.exe") self.dlg = self.app.Calculator self.dlg.MenuSelect('View->Scientific\tAlt+2') self.ctrl = HwndWrapper(self.dlg.Button2.handle) # Backspace def tearDown(self): "Close the application after tests" # close the application #self.dlg.TypeKeys("%{F4}") #self.dlg.Close() self.app.kill_() def testInvalidHandle(self): "Test that an exception is raised with an invalid window handle" self.assertRaises(InvalidWindowHandle, HwndWrapper, -1) #def testText(self): # "Test getting the window Text of the dialog" # self.assertEquals(self.dlg.WindowText(), "Untitled - Notepad") def testFriendlyClassName(self): "Test getting the friendly classname of the dialog" self.assertEquals(self.ctrl.FriendlyClassName(), "Button") def testClass(self): "Test getting the classname of the dialog" self.assertEquals(self.ctrl.Class(), "Button") def testWindowText(self): "Test getting the window Text of the dialog" self.assertEquals(self.ctrl.WindowText(), '\uf013') #"Backspace") def testStyle(self): self.dlg.Style() self.assertEquals( self.ctrl.Style(), win32defines.WS_CHILD | win32defines.WS_VISIBLE | win32defines.BS_PUSHBUTTON | win32defines.BS_TEXT) def testExStyle(self): self.assertEquals( self.ctrl.ExStyle(), win32defines.WS_EX_NOPARENTNOTIFY | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING | win32defines.WS_EX_RIGHTSCROLLBAR) """self.assertEquals(self.dlg.ExStyle(), win32defines.WS_EX_WINDOWEDGE | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING | win32defines.WS_EX_RIGHTSCROLLBAR | win32defines.WS_EX_CONTROLPARENT | win32defines.WS_EX_APPWINDOW)""" def testControlID(self): self.assertEquals(self.ctrl.ControlID(), 83) self.dlg.ControlID() def testUserData(self): self.ctrl.UserData() self.dlg.UserData() def testContextHelpID(self): self.ctrl.ContextHelpID() self.dlg.ContextHelpID() def testIsVisible(self): self.assertEqual(self.ctrl.IsVisible(), True) self.assertEqual(self.dlg.IsVisible(), True) def testIsUnicode(self): self.assertEqual(self.ctrl.IsUnicode(), True) self.assertEqual(self.dlg.IsUnicode(), True) def testIsEnabled(self): self.assertEqual(self.ctrl.IsEnabled(), True) self.assertEqual(self.dlg.IsEnabled(), True) self.assertEqual( self.dlg.ChildWindow(title='%', enabled_only=False).IsEnabled(), False) def testCloseClick_bug(self): self.dlg.MenuSelect('Help->About Calculator') self.app.AboutCalculator.CloseButton.CloseClick() Timings.closeclick_dialog_close_wait = .5 try: self.app.AboutCalculator.CloseClick() except timings.TimeoutError: pass self.app.AboutCalculator.Close() #self.assertEquals(self.app.StatisticsBox.Exists(), False) 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) self.assertEqual(rect.height(), 310) self.assertEqual(rect.width(), 413) def testClientRect(self): rect = self.dlg.Rectangle() cli = self.dlg.ClientRect() self.assertEqual(cli.left, 0) self.assertEqual(cli.top, 0) assert (cli.width() < rect.width()) assert (cli.height() < rect.height()) def testFont(self): self.assertNotEqual(self.dlg.Font(), self.ctrl.Font()) def ProcessID(self): self.assertEqual(self.ctrl.ProcessID(), self.dlg.ProcessID) self.assertNotEqual(self.ctrl.ProcessID(), 0) def testHasStyle(self): self.assertEqual(self.ctrl.HasStyle(win32defines.WS_CHILD), True) self.assertEqual(self.dlg.HasStyle(win32defines.WS_CHILD), False) self.assertEqual(self.ctrl.HasStyle(win32defines.WS_SYSMENU), False) self.assertEqual(self.dlg.HasStyle(win32defines.WS_SYSMENU), True) def testHasExStyle(self): self.assertEqual( self.ctrl.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), True) self.assertEqual( self.dlg.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), False) self.assertEqual(self.ctrl.HasExStyle(win32defines.WS_EX_APPWINDOW), False) #self.assertEqual(self.dlg.HasExStyle(win32defines.WS_EX_APPWINDOW), True) def testIsDialog(self): self.assertEqual(self.ctrl.IsDialog(), False) self.assertEqual(self.dlg.IsDialog(), True) def testMenuItems(self): self.assertEqual(self.ctrl.MenuItems(), []) self.assertEqual(self.dlg.MenuItems()[1]['Text'], '&Edit') def testParent(self): self.assertEqual(self.ctrl.Parent().Parent().Parent(), self.dlg.handle) def testTopLevelParent(self): self.assertEqual(self.ctrl.TopLevelParent(), self.dlg.handle) self.assertEqual(self.dlg.TopLevelParent(), self.dlg.handle) def testTexts(self): self.assertEqual(self.dlg.Texts(), ['Calculator']) self.assertEqual(self.ctrl.Texts(), ['\uf013']) #u'Backspace']) self.assertEqual( self.dlg.ChildWindow(class_name='Static', ctrl_index=5).Texts(), ['0']) def testClientRects(self): self.assertEqual(self.ctrl.ClientRects()[0], self.ctrl.ClientRect()) self.assertEqual(self.dlg.ClientRects()[0], self.dlg.ClientRect()) def testFonts(self): self.assertEqual(self.ctrl.Fonts()[0], self.ctrl.Font()) self.assertEqual(self.dlg.Fonts()[0], self.dlg.Font()) def testChildren(self): self.assertEqual(self.ctrl.Children(), []) self.assertNotEqual(self.dlg.Children(), []) def testIsChild(self): self.assertEqual(self.ctrl.IsChild(self.dlg.WrapperObject()), True) self.assertEqual(self.dlg.IsChild(self.ctrl), False) def testSendMessage(self): vk = self.dlg.SendMessage(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) code = self.dlg.Inv.SendMessage(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) def testSendMessageTimeout(self): vk = self.dlg.SendMessageTimeout(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) code = self.dlg.Inv.SendMessageTimeout(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) def testPostMessage(self): self.assertNotEquals(0, self.dlg.PostMessage(win32defines.WM_PAINT)) self.assertNotEquals(0, self.dlg.Inv.PostMessage(win32defines.WM_PAINT)) # def testNotifyMenuSelect(self): # "Call NotifyMenuSelect to ensure it does not raise" # self.ctrl.NotifyMenuSelect(1234) # self.dlg.NotifyMenuSelect(1234) def testNotifyParent(self): "Call NotifyParent to ensure it does not raise" self.ctrl.NotifyParent(1234) #self.dlg.NotifyParent(1234) def testGetProperties(self): "Test getting the properties for the HwndWrapped control" props = self.dlg.GetProperties() self.assertEquals(self.dlg.FriendlyClassName(), props['FriendlyClassName']) self.assertEquals(self.dlg.Texts(), props['Texts']) for prop_name in props: self.assertEquals(getattr(self.dlg, prop_name)(), props[prop_name]) # def testCaptureAsImage(self): # pass def 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): # self.assertRaises() # def testVerifyEnabled(self): # self.assertRaises() # def testVerifyVisible(self): # self.assertRaises() def testMoveWindow_same(self): "Test calling movewindow without any parameters" prevRect = self.dlg.Rectangle() self.dlg.MoveWindow() self.assertEquals(prevRect, self.dlg.Rectangle()) def testMoveWindow(self): "Test moving the window" dlgClientRect = self.dlg.Rectangle() #.ClientAreaRect() prev_rect = self.ctrl.Rectangle() - dlgClientRect new_rect = win32structures.RECT(prev_rect) new_rect.left -= 1 new_rect.top -= 1 new_rect.right += 2 new_rect.bottom += 2 self.ctrl.MoveWindow( new_rect.left, new_rect.top, new_rect.width(), new_rect.height(), ) time.sleep(0.1) print('prev_rect = ', prev_rect) print('new_rect = ', new_rect) print('dlgClientRect = ', dlgClientRect) print('self.ctrl.Rectangle() = ', self.ctrl.Rectangle()) self.assertEquals(self.ctrl.Rectangle(), new_rect + dlgClientRect) self.ctrl.MoveWindow(prev_rect) self.assertEquals(self.ctrl.Rectangle(), prev_rect + dlgClientRect) def testMaximize(self): self.dlg.Maximize() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWMAXIMIZED) self.dlg.Restore() def testMinimize(self): self.dlg.Minimize() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWMINIMIZED) self.dlg.Restore() def testRestore(self): self.dlg.Maximize() self.dlg.Restore() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL) self.dlg.Minimize() self.dlg.Restore() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL) def testGetFocus(self): self.assertNotEqual(self.dlg.GetFocus(), None) self.assertEqual(self.dlg.GetFocus(), self.ctrl.GetFocus()) self.dlg.Radians.SetFocus() self.assertEqual(self.dlg.GetFocus(), self.dlg.Radians.handle) def testSetFocus(self): self.assertNotEqual(self.dlg.GetFocus(), self.dlg.Radians.handle) self.dlg.Radians.SetFocus() self.assertEqual(self.dlg.GetFocus(), self.dlg.Radians.handle) def testMenuSelect(self): "Test selecting a menu item" if not self.dlg.MenuItem("View -> Digit grouping").IsChecked(): self.dlg.MenuSelect("View -> Digit grouping") self.dlg.TypeKeys("1234567") self.dlg.MenuSelect("Edit->Copy\tCtrl+C") self.dlg.CE.Click() self.assertEquals( self.dlg.ChildWindow(class_name='Static', ctrl_index=5).Texts()[0], "0") self.dlg.MenuSelect("Edit->Paste\tCtrl+V") self.assertEquals( self.dlg.ChildWindow(class_name='Static', ctrl_index=5).Texts()[0], "1Â 234Â 567") def testClose(self): "Test the Close() method of windows" # open about dialog self.dlg.MenuSelect('Help->About Calculator') # make sure it is open and visible self.assertTrue( self.app.Window_(title='About Calculator').IsVisible(), True) # close it self.app.Window_(title='About Calculator', class_name='#32770').Close(1) # make sure that it is not visible try: #self.assertRaises(WindowNotFoundError, self.app.Window_(title='About Calculator', class_name='#32770').WrapperObject()) # vvryabov: TimeoutError is caught by assertRaises, so the second raise is not caught correctly self.app.Window_(title='About Calculator', class_name='#32770').WrapperObject() except WindowNotFoundError: print('WindowNotFoundError exception is raised as expected. OK.') # make sure the main calculator dialog is still open self.assertEquals(self.dlg.IsVisible(), True)
class DialogTestCases(unittest.TestCase): "Unit tests for the DialogWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() self.app.start_("calc.exe") self.calc = self.app.SciCalc # write out the XML so that we can read it in later self.app.Calculator.WriteToXML("ref_controls.xml") def tearDown(self): "Close the application after tests" self.calc.TypeKeys("%{F4}") def testGetProperties(self): "Test getting the properties for the dialog box" props = self.calc.GetProperties() self.assertEquals("SciCalc", props['FriendlyClassName']) self.assertEquals(self.calc.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.calc, prop_name)(), props[prop_name]) def testRunTests(self): "Test running the UI tests on the dialog" bugs = self.calc.RunTests() from pywinauto.controls.HwndWrapper import HwndWrapper self.assertEquals(True, isinstance(bugs[0][0][0], HwndWrapper)) def testRunTestsWithReference(self): "Add a ref control, get the bugs and validate that the hande " from pywinauto import controlproperties ref_controls = [ controlproperties.ControlProps(ctrl) for ctrl in XMLHelpers.ReadPropertiesFromFile("ref_controls.xml") ] bugs = self.calc.RunTests(ref_controls=ref_controls) from pywinauto import tests tests.print_bugs(bugs) from pywinauto.controls.HwndWrapper import HwndWrapper self.assertEquals(True, isinstance(bugs[0][0][0], HwndWrapper)) def testWriteToXML(self): "Write the output and validate that it is the same as the test output" self.calc.WriteToXML("test_output.xml") all_props = [self.calc.GetProperties()] all_props.extend([c.GetProperties() for c in self.calc.Children()]) props = XMLHelpers.ReadPropertiesFromFile("test_output.xml") for i, ctrl in enumerate(props): for key, ctrl_value in ctrl.items(): expected_value = all_props[i][key] if "Image" in expected_value.__class__.__name__: expected_value = expected_value.tostring() ctrl_value = ctrl_value.tostring() if isinstance(ctrl_value, (list, tuple)): ctrl_value = list(ctrl_value) expected_value = list(expected_value) self.assertEquals(ctrl_value, expected_value) import os os.unlink("test_output.xml") def testClientAreaRect(self): """Validate that the client area rect is the right size (comparing against the full rectangle)""" clientarea = self.calc.ClientAreaRect() self.assertEquals(self.calc.Rectangle().left + 3, clientarea.left) self.assertEquals(self.calc.Rectangle().top + 41, clientarea.top) self.assertEquals(self.calc.Rectangle().right - 3, clientarea.right) self.assertEquals(self.calc.Rectangle().bottom - 3, clientarea.bottom)
class MenuWrapperTests(unittest.TestCase): "Unit tests for the Menu and the MenuItem classes" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_("Notepad.exe") self.dlg = self.app.Notepad def tearDown(self): "Close the application after tests" self.app.kill_() def testInvalidHandle(self): "Test that an exception is raised with an invalid menu handle" #self.assertRaises(InvalidWindowHandle, HwndWrapper, -1) pass def testItemCount(self): self.assertEquals(5, self.dlg.Menu().ItemCount()) def testItem(self): self.assertEquals(u'&File', self.dlg.Menu().Item(0).Text()) def testItems(self): self.assertEquals([u'&File', u'&Edit', u'F&ormat', u'&View', u'&Help'], [item.Text() for item in self.dlg.Menu().Items()]) def testFriendlyClassName(self): self.assertEquals('MenuItem', self.dlg.Menu().Item(0).FriendlyClassName()) def testMenuItemNotEnabled(self): self.assertRaises(MenuItemNotEnabled, self.dlg.MenuSelect, 'Edit->Find Next') self.assertRaises(MenuItemNotEnabled, self.dlg.MenuItem('Edit->Find Next').Click) self.assertRaises(MenuItemNotEnabled, self.dlg.MenuItem('Edit->Find Next').ClickInput) def testGetProperties(self): self.assertEquals( { u'MenuItems': [{ u'Index': 0, u'State': 0, u'Type': 0, u'ID': 64, u'Text': u'View &Help' }, { u'Index': 1, u'State': 3, u'Type': 2048, u'ID': 0, u'Text': u'' }, { u'Index': 2, u'State': 0, u'Type': 0, u'ID': 65, u'Text': u'&About Notepad' }] }, self.dlg.Menu().GetMenuPath('Help')[0].SubMenu().GetProperties()) def testGetMenuPath(self): #print('ID = ' + str(self.dlg.Menu().GetMenuPath('Help->#3')[0].ID())) self.assertEquals(u'&About Notepad', self.dlg.Menu().GetMenuPath('Help->#2')[-1].Text()) self.assertEquals(u'&About Notepad', self.dlg.Menu().GetMenuPath('Help->$65')[-1].Text()) self.assertEquals( u'&About Notepad', self.dlg.Menu().GetMenuPath('&Help->&About Notepad', exact=True)[-1].Text()) self.assertRaises(IndexError, self.dlg.Menu().GetMenuPath, '&Help->About what?', exact=True) def test__repr__(self): print(self.dlg.Menu()) print(self.dlg.Menu().GetMenuPath('&Help->&About Notepad', exact=True)[-1]) def testClick(self): self.dlg.Menu().GetMenuPath('&Help->&About Notepad')[-1].Click() About = self.app.Window_(title='About Notepad') About.Wait('ready') About.OK.Click() About.WaitNot('visible') def testClickInput(self): self.dlg.Menu().GetMenuPath('&Help->&About Notepad')[-1].ClickInput() About = self.app.Window_(title='About Notepad') About.Wait('ready') About.OK.Click() About.WaitNot('visible')
class NotepadRegressionTests(unittest.TestCase): "Regression unit tests for Notepad" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() self.app.start_(_notepad_exe()) self.dlg = self.app.Window_(title='Untitled - Notepad', class_name='Notepad') self.ctrl = HwndWrapper(self.dlg.Edit.handle) self.dlg.edit.SetEditText("Here is some text\r\n and some more") self.app2 = Application.start(_notepad_exe()) def tearDown(self): "Close the application after tests" # close the application try: self.dlg.Close(0.5) if self.app.Notepad["Do&n't Save"].Exists(): self.app.Notepad["Do&n't Save"].Click() self.app.Notepad["Do&n't Save"].WaitNot('visible') except Exception: # timings.TimeoutError: pass finally: self.app.kill_() self.app2.kill_() def testMenuSelectNotepad_bug(self): "In notepad - MenuSelect Edit->Paste did not work" text = b'Here are some unicode characters \xef\xfc\r\n' self.app2.UntitledNotepad.Edit.Wait('enabled') time.sleep(0.3) self.app2.UntitledNotepad.Edit.SetEditText(text) time.sleep(0.3) self.assertEquals( self.app2.UntitledNotepad.Edit.TextBlock().encode( locale.getpreferredencoding()), text) Timings.after_menu_wait = .7 self.app2.UntitledNotepad.MenuSelect("Edit->Select All") time.sleep(0.3) self.app2.UntitledNotepad.MenuSelect("Edit->Copy") time.sleep(0.3) self.assertEquals( clipboard.GetData().encode(locale.getpreferredencoding()), text) self.dlg.SetFocus() self.dlg.MenuSelect("Edit->Select All") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") self.app2.UntitledNotepad.MenuSelect("File->Exit") self.app2.Window_(title='Notepad', class_name='#32770')["Don't save"].Click() self.assertEquals( self.dlg.Edit.TextBlock().encode(locale.getpreferredencoding()), text * 3)
class ListBoxTestCases(unittest.TestCase): "Unit tests for the TreeViewWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() self.app.start_(r"c:\Program Files\Windows NT\Accessories\wordpad.exe") self.app.DocumentWordPad.MenuSelect("Insert->Date and time...") #pdb.set_trace() self.dlg = self.app.DateAndTime self.ctrl = self.dlg.ListBox.WrapperObject() def tearDown(self): "Close the application after tests" self.dlg.Cancel.Click() # close the application self.app.DocumentWordPad.MenuSelect("File->Exit") def testGetProperties(self): "Test getting the properties for the listbox control" props = self.ctrl.GetProperties() self.assertEquals("ListBox", props['FriendlyClassName']) self.assertEquals(self.ctrl.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemCount(self): "test that the count of items is correct" self.assertEquals(self.ctrl.ItemCount(), 14) def testItemData(self): "For the moment - just test that it does not raise" self.ctrl.ItemData(1) self.ctrl.ItemData(self.ctrl.ItemCount() - 1) def testSelectedIndices(self): "test that the selected indices are correct" self.assertEquals(self.ctrl.SelectedIndices(), (0, )) self.ctrl.Select(2) self.assertEquals(self.ctrl.SelectedIndices(), (2, )) self.assertTrue(type(self.ctrl.SelectedIndices()) == tuple) def testSelect(self): "Test selecting an item" self.ctrl.Select(5) self.assertEquals(self.ctrl.SelectedIndices(), (5, )) # get the text of the 2nd item (3rd item in list # because of empty WindowText) item_to_select = self.ctrl.Texts()[2] self.ctrl.Select(item_to_select) self.assertEquals(self.ctrl.SelectedIndices(), (1, )) def testGetSetItemFocus(self): "Test setting and getting the focus of a particular item" self.ctrl.SetItemFocus(0) self.assertEquals(self.ctrl.GetItemFocus(), 0) self.ctrl.SetItemFocus(5) self.assertEquals(self.ctrl.GetItemFocus(), 5)
class HwndWrapperTests(unittest.TestCase): "Unit tests for the TreeViewWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() if is_x64_Python() or not is_x64_OS(): self.app.start_(r"C:\Windows\System32\calc.exe") else: self.app.start_(r"C:\Windows\SysWOW64\calc.exe") self.dlg = self.app.Calculator self.dlg.MenuSelect('View->Scientific\tAlt+2') self.ctrl = HwndWrapper(self.dlg.Button2.handle) # Backspace def tearDown(self): "Close the application after tests" # close the application #self.dlg.TypeKeys("%{F4}") #self.dlg.Close() self.app.kill_() def testInvalidHandle(self): "Test that an exception is raised with an invalid window handle" self.assertRaises(InvalidWindowHandle, HwndWrapper, -1) #def testText(self): # "Test getting the window Text of the dialog" # self.assertEquals(self.dlg.WindowText(), "Untitled - Notepad") def testFriendlyClassName(self): "Test getting the friendly classname of the dialog" self.assertEquals(self.ctrl.FriendlyClassName(), "Button") def testClass(self): "Test getting the classname of the dialog" self.assertEquals(self.ctrl.Class(), "Button") def testWindowText(self): "Test getting the window Text of the dialog" self.assertEquals( HwndWrapper(self.dlg.Degrees.handle).WindowText(), u'Degrees') def testStyle(self): self.dlg.Style() self.assertEquals(self.ctrl.Style(), win32defines.WS_CHILD | win32defines.WS_VISIBLE | win32defines.BS_PUSHBUTTON | win32defines.BS_TEXT) def testExStyle(self): self.assertEquals(self.ctrl.ExStyle(), win32defines.WS_EX_NOPARENTNOTIFY | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING | win32defines.WS_EX_RIGHTSCROLLBAR) """self.assertEquals(self.dlg.ExStyle(), win32defines.WS_EX_WINDOWEDGE | win32defines.WS_EX_LEFT | win32defines.WS_EX_LTRREADING | win32defines.WS_EX_RIGHTSCROLLBAR | win32defines.WS_EX_CONTROLPARENT | win32defines.WS_EX_APPWINDOW)""" def testControlID(self): self.assertEquals(self.ctrl.ControlID(), 83) self.dlg.ControlID() def testUserData(self): self.ctrl.UserData() self.dlg.UserData() def testContextHelpID(self): self.ctrl.ContextHelpID() self.dlg.ContextHelpID() def testIsVisible(self): self.assertEqual(self.ctrl.IsVisible(), True) self.assertEqual(self.dlg.IsVisible(), True) def testIsUnicode(self): self.assertEqual(self.ctrl.IsUnicode(), True) self.assertEqual(self.dlg.IsUnicode(), True) def testIsEnabled(self): self.assertEqual(self.ctrl.IsEnabled(), True) self.assertEqual(self.dlg.IsEnabled(), True) self.assertEqual(self.dlg.Button26.IsEnabled(), False); # Button26 = '%' def testCloseClick_bug(self): self.dlg.MenuSelect('Help->About Calculator') self.app.AboutCalculator.Wait("visible", 10) self.app.AboutCalculator.CloseButton.CloseClick() Timings.closeclick_dialog_close_wait = .7 try: self.app.AboutCalculator.CloseClick() except TimeoutError: pass self.app.AboutCalculator.Close() #self.assertEquals(self.app.StatisticsBox.Exists(), False) def testCloseAltF4(self): self.dlg.MenuSelect('Help->About Calculator') AboutCalculator = self.app.Window_(title='About Calculator', active_only=True, class_name='#32770') AboutWrapper = AboutCalculator.Wait("enabled") AboutCalculator.CloseAltF4() AboutCalculator.WaitNot('visible') self.assertNotEqual(AboutWrapper.IsVisible(), True) 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() - 323) > 2: if rect.height() != 310: self.assertEqual(rect.height(), 323) if abs(rect.width() - 423) > 2: if rect.width() != 413: self.assertEqual(rect.width(), 423) def testClientRect(self): rect = self.dlg.Rectangle() cli = self.dlg.ClientRect() self.assertEqual(cli.left , 0) self.assertEqual(cli.top , 0) assert(cli.width() < rect.width()) assert(cli.height() < rect.height()) def testFont(self): self.assertNotEqual(self.dlg.Font(), self.ctrl.Font()) def ProcessID(self): self.assertEqual(self.ctrl.ProcessID(), self.dlg.ProcessID) self.assertNotEqual(self.ctrl.ProcessID(), 0) def testHasStyle(self): self.assertEqual(self.ctrl.HasStyle(win32defines.WS_CHILD), True) self.assertEqual(self.dlg.HasStyle(win32defines.WS_CHILD), False) self.assertEqual(self.ctrl.HasStyle(win32defines.WS_SYSMENU), False) self.assertEqual(self.dlg.HasStyle(win32defines.WS_SYSMENU), True) def testHasExStyle(self): self.assertEqual(self.ctrl.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), True) self.assertEqual(self.dlg.HasExStyle(win32defines.WS_EX_NOPARENTNOTIFY), False) self.assertEqual(self.ctrl.HasExStyle(win32defines.WS_EX_APPWINDOW), False) #self.assertEqual(self.dlg.HasExStyle(win32defines.WS_EX_APPWINDOW), True) def testIsDialog(self): self.assertEqual(self.ctrl.IsDialog(), False) self.assertEqual(self.dlg.IsDialog(), True) def testMenuItems(self): self.assertEqual(self.ctrl.MenuItems(), []) self.assertEqual(self.dlg.MenuItems()[1]['Text'], '&Edit') def testParent(self): self.assertEqual(self.ctrl.Parent().Parent().Parent(), self.dlg.handle) def testTopLevelParent(self): self.assertEqual(self.ctrl.TopLevelParent(), self.dlg.handle) self.assertEqual(self.dlg.TopLevelParent(), self.dlg.handle) def testTexts(self): self.assertEqual(self.dlg.Texts(), ['Calculator']) self.assertEqual(HwndWrapper(self.dlg.Degrees.handle).Texts(), [u'Degrees']) self.assertEqual(self.dlg.ChildWindow(class_name='Static', ctrl_index=5).Texts(), ['0']) def testFoundIndex(self): "test an access to a control by found_index" # The edit box with '0' can be accessed directly by control_index = 5 # or by a search combination: class_name='Static', found_index=3 ctl = self.dlg.ChildWindow(ctrl_index=5) self.assertEqual(ctl.Texts(), [u'0']) ctl = self.dlg.ChildWindow(class_name='Static', found_index=3) self.assertEqual(ctl.Texts(), [u'0']) ctl.DrawOutline('blue') # visualize # Test an out-of-range access # Notice: # A ChildWindow call only creates a WindowSpecification object. # The exception is raised later when we try to find the window. # For this reason we can't use an assertRaises statement here because # the exception is raised before actual call to DrawOutline ctl = self.dlg.ChildWindow(class_name='Static', found_index=3333) self.assertRaises(WindowNotFoundError, ctl.WrapperObject) def testSearchWithPredicateFunc(self): "test an access to a control by filtering with a predicate function" def is_radians(h): res = False hwwrp = HwndWrapper(h) if hwwrp.FriendlyClassName() == u'RadioButton': if hwwrp.Texts() == [u'Radians']: res = True return res ctl = self.dlg.ChildWindow(predicate_func=is_radians) self.assertEqual(ctl.Texts(), [u'Radians']) ctl.DrawOutline('red') # visualize def testClientRects(self): self.assertEqual(self.ctrl.ClientRects()[0], self.ctrl.ClientRect()) self.assertEqual(self.dlg.ClientRects()[0], self.dlg.ClientRect()) def testFonts(self): self.assertEqual(self.ctrl.Fonts()[0], self.ctrl.Font()) self.assertEqual(self.dlg.Fonts()[0], self.dlg.Font()) def testChildren(self): self.assertEqual(self.ctrl.Children(), []) self.assertNotEqual(self.dlg.Children(), []) def testIsChild(self): self.assertEqual(self.ctrl.IsChild(self.dlg.WrapperObject()), True) self.assertEqual(self.dlg.IsChild(self.ctrl), False) def testSendMessage(self): vk = self.dlg.SendMessage(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) code = self.dlg.Degrees.SendMessage(win32defines.WM_GETDLGCODE) # The expected return code is: "Button" = 0x2000 and "Radio" = 0x40 expected = 0x2000 + 0x40 self.assertEqual(expected, code) def testSendMessageTimeout(self): vk = self.dlg.SendMessageTimeout(win32defines.WM_GETDLGCODE) self.assertEqual(0, vk) code = self.dlg.Degrees.SendMessageTimeout(win32defines.WM_GETDLGCODE) # The expected return code is: "Button" = 0x2000 and "Radio" = 0x40 expected = 0x2000 + 0x40 self.assertEqual(expected, code) def testPostMessage(self): self.assertNotEquals(0, self.dlg.PostMessage(win32defines.WM_PAINT)) self.assertNotEquals(0, self.dlg.Degrees.PostMessage(win32defines.WM_PAINT)) # def testNotifyMenuSelect(self): # "Call NotifyMenuSelect to ensure it does not raise" # self.ctrl.NotifyMenuSelect(1234) # self.dlg.NotifyMenuSelect(1234) def testNotifyParent(self): "Call NotifyParent to ensure it does not raise" self.ctrl.NotifyParent(1234) #self.dlg.NotifyParent(1234) def testGetProperties(self): "Test getting the properties for the HwndWrapped control" props = self.dlg.GetProperties() self.assertEquals( self.dlg.FriendlyClassName(), props['FriendlyClassName']) self.assertEquals( self.dlg.Texts(), props['Texts']) for prop_name in props: self.assertEquals(getattr(self.dlg, prop_name)(), props[prop_name]) # def testCaptureAsImage(self): # pass def 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): # self.assertRaises() # def testVerifyEnabled(self): # self.assertRaises() # def testVerifyVisible(self): # self.assertRaises() def testMoveWindow_same(self): "Test calling movewindow without any parameters" prevRect = self.dlg.Rectangle() self.dlg.MoveWindow() self.assertEquals(prevRect, self.dlg.Rectangle()) def testMoveWindow(self): "Test moving the window" dlgClientRect = self.ctrl.Parent().Rectangle() # use the parent as a reference prev_rect = self.ctrl.Rectangle() - dlgClientRect new_rect = win32structures.RECT(prev_rect) new_rect.left -= 1 new_rect.top -= 1 new_rect.right += 2 new_rect.bottom += 2 self.ctrl.MoveWindow( new_rect.left, new_rect.top, new_rect.width(), new_rect.height(), ) time.sleep(0.1) print('prev_rect = ', prev_rect) print('new_rect = ', new_rect) print('dlgClientRect = ', dlgClientRect) print('self.ctrl.Rectangle() = ', self.ctrl.Rectangle()) self.assertEquals( self.ctrl.Rectangle(), new_rect + dlgClientRect) self.ctrl.MoveWindow(prev_rect) self.assertEquals( self.ctrl.Rectangle(), prev_rect + dlgClientRect) def testMaximize(self): self.dlg.Maximize() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWMAXIMIZED) self.dlg.Restore() def testMinimize(self): self.dlg.Minimize() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWMINIMIZED) self.dlg.Restore() def testRestore(self): self.dlg.Maximize() self.dlg.Restore() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL) self.dlg.Minimize() self.dlg.Restore() self.assertEquals(self.dlg.GetShowState(), win32defines.SW_SHOWNORMAL) def testGetFocus(self): self.assertNotEqual(self.dlg.GetFocus(), None) self.assertEqual(self.dlg.GetFocus(), self.ctrl.GetFocus()) self.dlg.Radians.SetFocus() self.assertEqual(self.dlg.GetFocus(), self.dlg.Radians.handle) def testSetFocus(self): self.assertNotEqual(self.dlg.GetFocus(), self.dlg.Radians.handle) self.dlg.Radians.SetFocus() self.assertEqual(self.dlg.GetFocus(), self.dlg.Radians.handle) def testMenuSelect(self): "Test selecting a menu item" if not self.dlg.MenuItem("View -> Digit grouping").IsChecked(): self.dlg.MenuSelect("View -> Digit grouping") self.dlg.TypeKeys("1234567") self.dlg.MenuSelect("Edit->Copy\tCtrl+C") self.dlg.Button8.Click() # 'Button8' is a class name of the 'CE' button self.assertEquals(self.dlg.ChildWindow(class_name='Static', ctrl_index=5).Texts()[0], "0") # get a pasted text self.dlg.MenuSelect("Edit->Paste\tCtrl+V") cur_str = self.dlg.ChildWindow(class_name='Static', ctrl_index=5).Texts()[0] # use a regular expression to match the typed string # because on machines with different locales # the digit groups can have different spacers. For example: # "1,234,567" or "1 234 567" and so on. exp_pattern = u"1.234.567" res = re.match(exp_pattern, cur_str) self.assertNotEqual(res, None) def testClose(self): "Test the Close() method of windows" # open about dialog self.dlg.MenuSelect('Help->About Calculator') # make sure it is open and visible self.app.AboutCalculator.Wait("visible", 20) self.assertTrue(self.app.Window_(title='About Calculator').IsVisible(), True) # close it self.app.Window_(title='About Calculator', class_name='#32770').Close(1) # make sure that it is not visible try: #self.assertRaises(WindowNotFoundError, self.app.Window_(title='About Calculator', class_name='#32770').WrapperObject()) # vvryabov: TimeoutError is caught by assertRaises, so the second raise is not caught correctly self.app.Window_(title='About Calculator', class_name='#32770').WrapperObject() except WindowNotFoundError: print('WindowNotFoundError exception is raised as expected. OK.') # make sure the main calculator dialog is still open self.assertEquals(self.dlg.IsVisible(), True)
class ButtonTestCases(unittest.TestCase): "Unit tests for the ComboBoxWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() if is_x64_Python() or not is_x64_OS(): self.app.start_(r"C:\Windows\System32\calc.exe") else: self.app.start_(r"C:\Windows\SysWOW64\calc.exe") self.calc = self.app.Calculator self.calc.MenuSelect("View->Scientific") def tearDown(self): "Close the application after tests" self.app.kill_() #self.calc.TypeKeys("%{F4}") def testGetProperties(self): "Test getting the properties for the button control" props = self.calc.Degrees.GetProperties() self.assertEquals("RadioButton", props['FriendlyClassName']) self.assertEquals(self.calc.Degrees.Texts(), ['Degrees']) self.assertEquals(self.calc.Degrees.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.calc.Degrees, prop_name)(), props[prop_name]) def test_set_if_needs_image(self): "test whether an image needs to be saved with the properties" self.assertEquals(self.calc.Button5._NeedsImageProp, False) def testFriendlyClass(self): "Test the FriendlyClassName method" self.assertEquals(self.calc.Button9.FriendlyClassName(), "Button") self.assertEquals(self.calc.Degree.FriendlyClassName(), "RadioButton") #self.assertEquals(self.calc.Hex.FriendlyClassName(), "CheckBox") #children = self.calc.Children() #no_text_buttons = [ # c for c in children # if not c.WindowText() and c.Class() == "Button"] #first_group = no_text_buttons[0] #self.assertEquals(first_group.FriendlyClassName(), "GroupBox") def testCheckUncheck(self): "Test unchecking a control" self.calc.Grads.Check() self.assertEquals(self.calc.Grads.GetCheckState(), 1) self.calc.Grads.UnCheck() self.assertEquals(self.calc.Grads.GetCheckState(), 0) def testGetCheckState_unchecked(self): "unchecked" self.assertEquals(self.calc.Grads.GetCheckState(), 0) def testGetCheckState_checked(self): "checked" self.calc.Grads.Check() self.assertEquals(self.calc.Grads.GetCheckState(), 1) # def testGetCheckState_indeterminate(self): # "indeterminate" # self.calc.Inv.SetCheckIndeterminate() # self.assertEquals(self.calc.Inv.GetCheckState(), 0) def testClick(self): "Test clicking on buttons" self.calc.Button15.Click() # "6" self.calc.Button10.Click() # "5" self.calc.Button23.Click() # "+" self.calc.Button4.Click() # "4" self.calc.Button16.Click() # "3" self.calc.Button28.Click() # "=" self.assertEquals( self.calc.ChildWindow(class_name='Static', ctrl_index=5).Texts()[0], "108") def testIsSelected(self): "Test whether the control is selected or not" # Todo - I need to find an application where a button can be # selected - I don't see one in Calc at least :) self.assertEquals(self.calc.Radians.GetCheckState(), 0) self.calc.Radians.Click() self.assertEquals(self.calc.Radians.GetCheckState(), 1)
class ComboBoxTestCases(unittest.TestCase): "Unit tests for the ComboBoxWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() self.app.start_("Notepad.exe") self.app.UntitledNotepad.MenuSelect("Format->Font") self.ctrl = self.app.Font.ComboBox2.WrapperObject() def tearDown(self): "Close the application after tests" self.app.Font.Cancel.CloseClick() # close the application self.app.UntitledNotepad.MenuSelect("File->Exit") if self.app.Notepad.No.Exists(): self.app.Notepad.No.Click() def testGetProperties(self): "Test getting the properties for the combobox control" props = self.ctrl.GetProperties() self.assertEquals("ComboBox", props['FriendlyClassName']) self.assertEquals(self.ctrl.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemCount(self): "Test that ItemCount returns the correct number of items" self.assertEquals(self.ctrl.ItemCount(), 4) def testDroppedRect(self): "Test that the dropped rect is correct" rect = self.ctrl.DroppedRect() #import pdb;pdb.set_trace() self.assertEquals(rect.left, 0) self.assertEquals(rect.top, 0) self.assertEquals(rect.right, self.ctrl.ClientRect().right) self.assertEquals(rect.bottom, self.ctrl.Rectangle().height() - 3) def testSelectedIndex(self): "That the control returns the correct index for the selected item" self.ctrl.Select(2) self.assertEquals(self.ctrl.SelectedIndex(), 2) self.assertEquals(self.ctrl.Texts()[3], self.app.Font.Edit2.Texts()[1]) def testSelect_negative(self): "Test that the Select method correctly handles negative indices" self.ctrl.Select(-1) self.assertEquals(self.ctrl.SelectedIndex(), 3) def testSelect_toohigh(self): "Test that the Select correctly raises if the item is too high" self.assertRaises(IndexError, self.ctrl.Select, 211) def testSelect_string(self): "Test that we can select based on a string" self.ctrl.Select(0) self.assertEquals(self.ctrl.SelectedIndex(), 0) self.ctrl.Select("Italic") self.assertEquals(self.ctrl.SelectedIndex(), 1) # now do it with a typo self.assertRaises(ValueError, self.ctrl.Select, "Bold Italc") def testSelect_simpleCombo(self): "Test selection for a simple combo" self.app.Font.ScriptComboBox.Select(0) self.assertEquals(self.app.Font.ScriptComboBox.SelectedIndex(), 0) self.app.Font.ScriptComboBox.Select(2) self.assertEquals(self.app.Font.ScriptComboBox.SelectedIndex(), 2) def testItemData(self): "Test that it doesn't raise" self.ctrl.ItemData(0) self.ctrl.ItemData(1) self.ctrl.ItemData("Italic") self.ctrl.ItemData(self.ctrl.ItemCount() - 1)
class ListBoxTestCases(unittest.TestCase): "Unit tests for the TreeViewWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() app_path = os.path.join(MFC_tutorial_folder, "MFC_Tutorial9.exe") self.app.start_(app_path) self.dlg = self.app.MFC_Tutorial9 self.dlg.TypeYourTextEdit.TypeKeys('qqq') self.dlg.Add.Click() self.dlg.TypeYourTextEdit.Select() self.dlg.TypeYourTextEdit.TypeKeys('123') self.dlg.Add.Click() self.dlg.TypeYourTextEdit.Select() self.dlg.TypeYourTextEdit.TypeKeys('third item', with_spaces=True) self.dlg.Add.Click() self.ctrl = self.dlg.ListBox.WrapperObject() def tearDown(self): "Close the application after tests" #self.dlg.Cancel.Click() # close the application self.app.kill_() def testGetProperties(self): "Test getting the properties for the listbox control" props = self.ctrl.GetProperties() self.assertEquals("ListBox", props['FriendlyClassName']) self.assertEquals(self.ctrl.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemCount(self): "test that the count of items is correct" self.assertEquals(self.ctrl.ItemCount(), 3) def testItemData(self): "For the moment - just test that it does not raise" self.ctrl.ItemData(1) self.ctrl.ItemData(self.ctrl.ItemCount() - 1) def testSelectedIndices(self): "test that the selected indices are correct" self.assertEquals(self.ctrl.SelectedIndices(), (-1, )) self.ctrl.Select(2) self.assertEquals(self.ctrl.SelectedIndices(), (2, )) self.assertTrue(type(self.ctrl.SelectedIndices()) == tuple) def testSelect(self): "Test selecting an item" self.ctrl.Select(1) self.assertEquals(self.ctrl.SelectedIndices(), (1, )) # get the text of the 2nd item (3rd item in list # because of empty WindowText) item_to_select = self.ctrl.Texts()[2] self.ctrl.Select(item_to_select) self.assertEquals(self.ctrl.SelectedIndices(), (1, )) def testGetSetItemFocus(self): "Test setting and getting the focus of a particular item" self.ctrl.SetItemFocus(0) self.assertEquals(self.ctrl.GetItemFocus(), 0) self.ctrl.SetItemFocus(2) self.assertEquals(self.ctrl.GetItemFocus(), 2)
class HwndWrapperMouseTests(unittest.TestCase): "Unit tests for mouse actions of the HwndWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application self.app = Application() if is_x64_Python() or not is_x64_OS(): self.app.start_(r"C:\Windows\System32\notepad.exe") else: self.app.start_(r"C:\Windows\SysWOW64\notepad.exe") # Get the old font self.app.UntitledNotepad.MenuSelect("Format->Font") self.old_font = self.app.Font.FontComboBox.SelectedIndex() self.old_font_style = self.app.Font.FontStyleCombo.SelectedIndex() # ensure we have the correct settings for this test self.app.Font.FontStyleCombo.Select(0) self.app.Font.FontComboBox.Select("Lucida Console") self.app.Font.OK.Click() self.dlg = self.app.Window_(title='Untitled - Notepad', class_name='Notepad') self.ctrl = HwndWrapper(self.dlg.Edit.handle) self.dlg.edit.SetEditText("Here is some text\r\n and some more") def tearDown(self): "Close the application after tests" # Set the old font again self.app.UntitledNotepad.MenuSelect("Format->Font") self.app.Font.FontComboBox.Select(self.old_font) self.app.Font.FontStyleCombo.Select(self.old_font_style) self.app.Font.OK.Click() self.app.Font.WaitNot('visible') # close the application try: self.dlg.Close(0.5) if self.app.Notepad["Do&n't Save"].Exists(): self.app.Notepad["Do&n't Save"].Click() self.app.Notepad["Do&n't Save"].WaitNot('visible') except: # timings.TimeoutError: pass finally: self.app.kill_() #def testText(self): # "Test getting the window Text of the dialog" # self.assertEquals(self.dlg.WindowText(), "Untitled - Notepad") def testClick(self): self.ctrl.Click(coords=(50, 10)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (6, 6)) def testClickInput(self): self.ctrl.ClickInput(coords=(50, 10)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (6, 6)) def testDoubleClick(self): self.ctrl.DoubleClick(coords=(60, 30)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (24, 29)) def testDoubleClickInput(self): self.ctrl.DoubleClickInput(coords=(60, 30)) self.assertEquals(self.dlg.Edit.SelectionIndices(), (24, 29)) def testMenuSelectNotepad_bug(self): "In notepad - MenuSelect Edit->Paste did not work" text = b'Here are some unicode characters \xef\xfc\r\n' app2 = Application.start("notepad") app2.UntitledNotepad.Edit.SetEditText(text) app2.UntitledNotepad.MenuSelect("Edit->Select All") app2.UntitledNotepad.MenuSelect("Edit->Copy") self.dlg.MenuSelect("Edit->Select All") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") self.dlg.MenuSelect("Edit->Paste") app2.UntitledNotepad.MenuSelect("File->Exit") app2.Window_(title='Notepad', class_name='#32770')["Don't save"].Click() self.assertEquals( self.dlg.Edit.TextBlock().encode(locale.getpreferredencoding()), text * 3)
class ComboBoxTestCases(unittest.TestCase): "Unit tests for the ComboBoxWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() self.app.start_(os.path.join(mfc_samples_folder, u"CmnCtrl2.exe")) self.app.Common_Controls_Sample.TabControl.Select("CSpinButtonCtrl") self.ctrl = self.app.Common_Controls_Sample.AlignmentComboBox.WrapperObject( ) def tearDown(self): "Close the application after tests" self.app.kill_() def testGetProperties(self): "Test getting the properties for the combobox control" props = self.ctrl.GetProperties() self.assertEquals("ComboBox", props['FriendlyClassName']) self.assertEquals(self.ctrl.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemCount(self): "Test that ItemCount returns the correct number of items" self.assertEquals(self.ctrl.ItemCount(), 3) def testDroppedRect(self): "Test that the dropped rect is correct" rect = self.ctrl.DroppedRect() #import pdb;pdb.set_trace() self.assertEquals(rect.left, 0) self.assertEquals(rect.top, 0) self.assertEquals(rect.right, self.ctrl.ClientRect().right) self.assertEquals(rect.bottom, self.ctrl.Rectangle().height() + 48) def testSelectedIndex(self): "That the control returns the correct index for the selected item" self.ctrl.Select(1) self.assertEquals(self.ctrl.SelectedIndex(), 1) #self.assertEquals(self.ctrl.Texts()[3], self.app.Font.Edit2.Texts()[1]) def testSelect_negative(self): "Test that the Select method correctly handles negative indices" self.ctrl.Select(-1) self.assertEquals(self.ctrl.SelectedIndex(), 2) def testSelect_toohigh(self): "Test that the Select correctly raises if the item is too high" self.assertRaises(IndexError, self.ctrl.Select, 211) def testSelect_string(self): "Test that we can select based on a string" self.ctrl.Select(0) self.assertEquals(self.ctrl.SelectedIndex(), 0) self.ctrl.Select("Left (UDS_ALIGNLEFT)") self.assertEquals(self.ctrl.SelectedIndex(), 1) # now do it with a typo self.assertRaises(ValueError, self.ctrl.Select, "Right (UDS_ALIGNRIGT)") def testSelect_simpleCombo(self): "Test selection for a simple combo" self.app.Common_Controls_Sample.OrientationComboBox.Select(0) self.assertEquals( self.app.Common_Controls_Sample.OrientationComboBox.SelectedIndex( ), 0) self.app.Common_Controls_Sample.OrientationComboBox.Select(1) self.assertEquals( self.app.Common_Controls_Sample.OrientationComboBox.SelectedIndex( ), 1) def testItemData(self): "Test that it doesn't raise" self.ctrl.ItemData(0) self.ctrl.ItemData(1) self.ctrl.ItemData("Right (UDS_ALIGNRIGHT)") self.ctrl.ItemData(self.ctrl.ItemCount() - 1)
class ButtonTestCases(unittest.TestCase): "Unit tests for the ComboBoxWrapper class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" # start the application from pywinauto.application import Application self.app = Application() self.app.start_("calc.exe") self.calc = self.app.SciCalc self.calc.MenuSelect("View->Scientific") def tearDown(self): "Close the application after tests" self.calc.TypeKeys("%{F4}") def testGetProperties(self): "Test getting the properties for the button control" props = self.calc._6.GetProperties() self.assertEquals("Button", props['FriendlyClassName']) self.assertEquals(self.calc._6.Texts(), ['6']) self.assertEquals(self.calc._6.Texts(), props['Texts']) for prop_name in props: self.assertEquals( getattr(self.calc._6, prop_name)(), props[prop_name]) def test_set_if_needs_image(self): "test whether an image needs to be saved with the properties" self.assertEquals(self.calc._8._NeedsImageProp, False) def testFriendlyClass(self): "Test the FriendlyClassName method" self.assertEquals(self.calc._8.FriendlyClassName(), "Button") self.assertEquals(self.calc.Dec.FriendlyClassName(), "RadioButton") self.assertEquals(self.calc.Hyp.FriendlyClassName(), "CheckBox") children = self.calc.Children() no_text_buttons = [ c for c in children if not c.WindowText() and c.Class() == "Button" ] first_group = no_text_buttons[0] self.assertEquals(first_group.FriendlyClassName(), "GroupBox") def testCheckUncheck(self): "Test unchecking a control" self.calc.Inv.Check() self.assertEquals(self.calc.Inv.GetCheckState(), 1) self.calc.Inv.UnCheck() self.assertEquals(self.calc.Inv.GetCheckState(), 0) def testGetCheckState_unchecked(self): "unchecked" self.assertEquals(self.calc.Inv.GetCheckState(), 0) def testGetCheckState_checked(self): "checked" self.calc.Inv.Check() self.assertEquals(self.calc.Inv.GetCheckState(), 1) # def testGetCheckState_indeterminate(self): # "indeterminate" # self.calc.Inv.SetCheckIndeterminate() # self.assertEquals(self.calc.Inv.GetCheckState(), 0) def testClick(self): "Test clicking on buttons" self.calc._6.Click() self.calc._5.Click() self.calc['+'].Click() self.calc._4.Click() self.calc._3.Click() self.calc['='].Click() self.assertEquals(self.calc.Edit.Texts()[1], "108. ") def testIsSelected(self): "Test whether the control is selected or not" # Todo - I need to find an application where a button can be # selected - I don't see one in Calc at least :) self.assertEquals(self.calc.Hex.GetCheckState(), 0) self.calc.Hex.Click() self.assertEquals(self.calc.Hex.GetCheckState(), 1)