def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app = Application() self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe")) self.app2 = Application().start(_notepad_exe())
def setTiming(self, speed): if speed.lower() == 'slow': Timings.Slow() elif speed.lower() == 'fast': Timings.Fast() else: Timings.Defaults()
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() actionlogger.enable() self.app = Application().start(_notepad_exe()) self.logger = logging.getLogger('pywinauto') self.out = self.logger.parent.handlers[0].stream self.logger.parent.handlers[0].stream = open('test_logging.txt', 'w')
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app = Application() self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe")) self.dlg = self.app.Common_Controls_Sample self.ctrl = self.dlg.TreeView.WrapperObject()
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app = Application() self.app.start(_notepad_exe()) self.dlg = self.app.UntitledNotepad self.ctrl = HwndWrapper(self.dlg.Edit.handle)
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app = Application().start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe")) self.dlg = self.app.Common_Controls_Sample self.dlg.TabControl.Select('CButton (Command Link)') self.ctrl = HwndWrapper(self.dlg.Command_button_here.handle)
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app1 = Application().start(u"cmd.exe", create_new_console=True, wait_for_idle=False) self.app2 = Application().start( os.path.join(mfc_samples_folder, u"CmnCtrl2.exe"))
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() EmptyClipboard() self.app1 = Application().start("notepad.exe") self.app2 = Application().start("notepad.exe") self.app1.UntitledNotepad.MoveWindow(RECT(0, 0, 200, 200)) self.app2.UntitledNotepad.MoveWindow(RECT(0, 200, 200, 400))
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app1 = Application().start(u"cmd.exe", create_new_console=True, wait_for_idle=False) self.app2 = Application().start(os.path.join( mfc_samples_folder, u"CmnCtrl2.exe")) self.app2.wait_cpu_usage_lower(threshold=1.5, timeout=30, usage_interval=1)
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app = Application() self.app.start(_notepad_exe()) self.dlg = self.app.Window_(title='Untitled - Notepad', class_name='Notepad') self.ctrl = HwndWrapper(self.dlg.Edit.handle) self.dlg.Edit.SetEditText("Here is some text\r\n and some more") self.app2 = Application().start(_notepad_exe())
def matchXl_dict(self,year): self.book = xlrd.open_workbook(self.from_this_dir('C:\\MYP\\Python\\custom.xlsx'), formatting_info=False) self.sheet = self.book.sheet_by_name('Sheet1') xlval = self.sheet.col_values( 0,0,4) Timings.Defaults() app = Application() try: app.connect_(title_re = ".*Skip Logic.*") except: app.start_('C:\MYP\Swami-KT\MYP_09_00_00_93\QATools\start.bat') time.sleep(5) app.connect_(title_re = ".*Skip Logic.*") Timings.Fast()
def save_spectra(self): acquisition_mode = self.acquisition_mode.get() safe_acquisition = not self.fast_acquisition.get() overwrite = self.overwrite.get() if self.fast_acquisition.get(): Timings.Fast() Timings.window_find_timeout = 2 if acquisition_mode == ACQUISITION_MODE_MANUAL: self.results_text.set("Manual save") if acquisition_mode == ACQUISITION_MODE_LIVE: self.results_text.set("Live save") app = Application(backend="win32").connect( path=self.program_path.get()) logger.info("Application connected") top_window = app.window(title_re=".*ElementsView.*") if safe_acquisition: top_window.wait("exists enabled visible ready") for spectrum_id in range(1, self.number_spectra.get() + 1): logger.info("Spectrum id: {:d}".format(spectrum_id)) if safe_acquisition: top_window.wait("exists enabled visible ready") if acquisition_mode == ACQUISITION_MODE_MANUAL: top_window.Button2.click() time.sleep(self.delay_spectrum_s.get()) if safe_acquisition: top_window.wait("exists enabled visible ready") top_window.menu_select("File -> Save") if safe_acquisition: app.Comment.wait("exists enabled visible ready") app.CommentEdit.Edit.SetEditText("auto script") app.Comment.OK.click() save_as_window = app['Save As'] if safe_acquisition: save_as_window.wait("exists enabled visible ready") file_name = "%s_%i.elv" % (self.basename.get(), spectrum_id) save_as_window.Edit.SetEditText(file_name) save_as_window.Save.click() if overwrite: try: window_confirm = app['Confirm Save As'] if safe_acquisition: window_confirm.wait("exists enabled visible ready") if self.overwrite.get(): window_confirm.Yes.click() else: window_confirm.No.click() save_as_window.Cancel.click() self.results_text.set("Cancel save file already exist") return except Exception as message: logger.error(message) logger.info("Done") self.results_text.set("Done")
import os import os.path import unittest import time import pprint import pdb import warnings import sys sys.path.append(".") from pywinauto import application from pywinauto.application import * from pywinauto import findwindows from pywinauto.timings import Timings Timings.Fast() #application.set_timing(1, .01, 1, .01, .05, 0, 0, .1, 0, .01) # page setup dialog takes a long time to load # so make sure that we wait for it. Timings.window_find_timeout = 10 class ApplicationTestCases(unittest.TestCase): "Unit tests for the application.Application class" def setUp(self): """Start the application set some data and ensure the application is in the state we want it.""" self.prev_warn = warnings.showwarning def no_warnings(*args, **kwargs): pass
def _set_timings_fast(): """Set Timings.Fast() and some slower settings for reliability""" Timings.Fast() Timings.window_find_timeout = 3 Timings.closeclick_dialog_close_wait = 2.
def RunNotepad(): "Run notepad and do some small stuff with it" print "Run with option 'language' e.g. notepad_fast.py language to use" print "application data. This should work on any language Windows/Notepad" print print "Trying fast timing settings - it's possible these won't work" print "if pywinauto tries to access a window that is not accessible yet" # use fast timings - but allow to wait for windows a long time Timings.Fast() Timings.window_find_timeout = 10 start = time.time() run_with_appdata = False if len(sys.argv) > 1 and sys.argv[1].lower() == 'language': run_with_appdata = True scriptdir = os.path.split(os.path.abspath(__file__))[0] if run_with_appdata: print "\nRunning this script so it will load application data and run" print "against any lanuguage version of Notepad/Windows" # make sure that the app data gets read from the same folder as # the script app = application.Application( os.path.join(scriptdir, "Notepad_fast.pkl")) else: app = application.Application() ## for distribution we don't want to connect to anybodies application ## because we may mess up something they are working on! #try: # app.connect_(path = ur"c:\windows\system32\notepad.exe") #except application.ProcessNotFoundError: # app.start_(ur"c:\windows\system32\notepad.exe") app.start_(ur"notepad.exe") app.Notepad.MenuSelect("File->PageSetup") # ----- Page Setup Dialog ---- # Select the 4th combobox item app.PageSetupDlg.SizeComboBox.Select(4) # Select the 'Letter' combobox item or the Letter try: app.PageSetupDlg.SizeComboBox.Select("Letter") except ValueError: app.PageSetupDlg.SizeComboBox.Select('Letter (8.5" x 11")') app.PageSetupDlg.SizeComboBox.Select(2) # run some tests on the Dialog. List of available tests: # "AllControls", # "AsianHotkey", # "ComboBoxDroppedHeight", # "CompareToRefFont", # "LeadTrailSpaces", # "MiscValues", # "Missalignment", # "MissingExtraString", # "Overlapping", # "RepeatedHotkey", # "Translation", # "Truncation", bugs = app.PageSetupDlg.RunTests('RepeatedHotkey Truncation') # if there are any bugs they will be printed to the console # and the controls will be highlighted tests.print_bugs(bugs) # ----- Next Page Setup Dialog ---- app.PageSetupDlg.Printer.Click() # do some radio button clicks # Open the Connect to printer dialog so we can # try out checking/unchecking a checkbox app.PageSetupDlg.Network.Click() # ----- Connect To Printer Dialog ---- # Select a checkbox app.ConnectToPrinter.ExpandByDefault.Check() app.ConnectToPrinter.ExpandByDefault.UnCheck() # try doing the same by using click app.ConnectToPrinter.ExpandByDefault.Click() app.ConnectToPrinter.ExpandByDefault.Click() # close the dialog app.ConnectToPrinter.Cancel.CloseClick() # ----- 2nd Page Setup Dialog again ---- app.PageSetupDlg.Properties.Click() doc_props = app.window_(title_re=".*Properties$") doc_props.Wait('exists', timeout=40) # # # ----- Document Properties Dialog ---- # # some tab control selections # # Two ways of selecting tabs with indices... # doc_props.TabCtrl.Select(0) # doc_props.TabCtrl.Select(1) # try: # doc_props.TabCtrl.Select(2) # except IndexError: # # not all users have 3 tabs in this dialog # pass # # # or with text... # #doc_props.TabCtrl.Select("PaperQuality") # doc_props.TabCtrl.Select(1) # # try: # #doc_props.TabCtrl.Select("JobRetention") # doc_props.TabCtrl.Select("3") # except MatchError: # # some people do not have the "Job Retention" tab # pass # # doc_props.TabCtrl.Select("Finishing") # #doc_props.TabCtrl.Select(0) # # # do some radio button clicks # doc_props.RotatedLandscape.Click() # doc_props.BackToFront.Click() # doc_props.FlipOnShortEdge.Click() # # doc_props.Portrait.Click() # doc_props._None.Click() # #doc_props.FrontToBack.Click() # # # open the Advanced options dialog in two steps # advbutton = doc_props.Advanced # advbutton.Click() # # # close the 4 windows # # # ----- Advanced Options Dialog ---- # app.window_(title_re = ".* Advanced Options").Ok.Click() # ----- Document Properties Dialog again ---- doc_props.Cancel.CloseClick() # for some reason my current printer driver # window does not close cleanly :( if doc_props.Cancel.Exists(): doc_props.OK.CloseClick() # ----- 2nd Page Setup Dialog again ---- app.PageSetupDlg.OK.CloseClick() # ----- Page Setup Dialog ---- app.PageSetupDlg.Ok.CloseClick() # type some text - note that extended characters ARE allowed app.Notepad.Edit.SetEditText(u"I am typing s\xe4me text to Notepad\r\n\r\n" "And then I am going to quit") app.Notepad.Edit.RightClick() app.Popup.MenuItem("Right To Left Reading Order").Click() #app.PopupMenu.MenuSelect("Paste", app.Notepad.ctrl_()) #app.Notepad.Edit.RightClick() #app.PopupMenu.MenuSelect( # "Right To Left Reading Order", app.Notepad.ctrl_()) #app.PopupMenu.MenuSelect( # "Show unicode control characters", app.Notepad.ctrl_()) #time.sleep(1) #app.Notepad.Edit.RightClick() #app.PopupMenu.MenuSelect("Right To Left Reading Order", app.Notepad.ctrl_()) #time.sleep(1) #app.Notepad.Edit.RightClick() #app.PopupMenu.MenuSelect( # "Insert Unicode control character -> IAFS", app.Notepad.ctrl_()) #time.sleep(1) #app.Notepad.Edit.TypeKeys("{ESC}") # the following shows that Sendtext does not accept # accented characters - but does allow 'control' characters app.Notepad.Edit.TypeKeys( u"{END}{ENTER}SendText d\xf6\xe9s " u"s\xfcpp\xf4rt \xe0cce\xf1ted characters!!!", with_spaces=True) # Try and save app.Notepad.MenuSelect("File->SaveAs") app.SaveAs.EncodingComboBox.Select("UTF-8") app.SaveAs.FileNameEdit.SetEditText("Example-utf8.txt") app.SaveAs.Save.CloseClick() # my machine has a weird problem - when connected to the network # the SaveAs Dialog appears - but doing anything with it can # cause a LONG delay - the easiest thing is to just wait # until the dialog is no longer active # - Dialog might just be gone - because click worked # - dialog might be waiting to disappear # so can't wait for next dialog or for it to be disabled # - dialog might be waiting to display message box so can't wait # for it to be gone or for the main dialog to be enabled. # while the dialog exists wait upto 30 seconds (and yes it can # take that long on my computer sometimes :-( ) app.SaveAsDialog2.Cancel.WaitNot('enabled') # If file exists - it asks you if you want to overwrite try: app.SaveAs.Yes.Wait('exists').CloseClick() except pywinauto.MatchError: pass # exit notepad app.Notepad.MenuSelect("File->Exit") if not run_with_appdata: app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl")) print "That took %.3f to run" % (time.time() - start)
def RunTestTool(self, year, quarter, sleeptime): Timings.Defaults() app = Application() try: app.connect_(title_re = ".*a.*") sys.stderr.write ( 'connected to window '+'\n') except: import sys, string, os app.start_('C:\\MYP\\Python\\start.bat') time.sleep(5) app.connect_(title_re = ".*a.*") sys.stderr.write ( 'connected to window '+'\n') app.connect_(title_re = ".*a.*") app.top_window_().Restore() Timings.Fast() window = app.window_(process=18000) window.SetFocus() time.sleep(5) app.top_window_().Click() time.sleep(5) #window.TypeKeys("{TAB 2}") window.TypeKeys("{RIGHT 2}") window.TypeKeys("{TAB 4}") sys.stderr.write ( 'tabbing completed'+'\n') dict = app.top_window_()._ctrl_identifiers() print dict for k,v in dict.items(): #print v for v1 in v: if (v1==u'a'): print k.handle #k.Click() app.top_window_().YearComboxBox.Select(year) #app.top_window_().ComboBox7.Select("a") app.top_window_()['a'].Click() sys.stderr.write ( 'Setting Options and Clicked'+'\n') print app.top_window_().PopulationComboBox1.ItemTexts() measures= [] measures = app.top_window_().PopulationComboBox1.ItemTexts() print measures mmap= { 'a':['b'], } #from collections import OrderedDict #mmap1={} #mmap1=OrderedDict((mmap[key], True) for key in mmap) measures=mmap.keys() measures.sort() s='' s1='' dictErrors ={} i=0 previousError='' previousSkip='' for measure in measures: i=i+1 #if(i==6): #break print 'using ' print measure indicators=[] indicators=mmap[measure] if not measure == '': # Change the not operator if you want to run it for all cases in one go. app.top_window_().PopulationComboBox1.Select(measure) #indicators= app.top_window_().IndicatorComboBox3.ItemTexts() for indicator in indicators: if indicator == '': continue app.top_window_().IndicatorComboBox3.Select(indicator) app.top_window_()['Create and Run TestsButton'].Click() #app.top_window_()['Create and Run TestsButton'].Click() #time.sleep(12) while(True): time.sleep(1) times_Run = app.top_window_()['Testing:Edit'].Texts()[0].strip(" ").split()[0] if(times_Run=='00100'): s1=app.top_window_()['Skip Logic ErrorsEdit2'].Texts()[0].strip(" ") s = app.top_window_()['Measure Engine ErrorsEdit2'].Texts()[0].strip(" ") print s print s1 break #print dictErrors sleeptime = 30 errors='' time.sleep(sleeptime) sys.stderr.write ( 'Slept for '+str(sleeptime)+'\n') #print s+s1 #s1 = app.top_window_()['Skip Logic ErrorsEdit2'].Texts()[0] #s = app.top_window_()['Measure Engine ErrorsEdit2'].Texts()[0] print errors print dictErrors if(errors != '' ): raise AssertionError(errors) app.start_('C:\\MYP\\Python\\stop.bat') print 'reached3' #MayNotWork app.kill() app.start_('C:\\MYP\\Python\\stop.bat') sys.stderr.write ( 'All done')