예제 #1
0
class WindowWithoutMessageLoopFocusTests(unittest.TestCase):

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

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

        self.app1 = Application().start("cmd.exe", create_new_console=True, wait_for_idle=False)
        self.app2 = Application().start(os.path.join(mfc_samples_folder, "CmnCtrl2.exe"))

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

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

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

    """Regression unit tests for Notepad"""

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

        self.app = Application()
        self.app.start(_notepad_exe())

        self.dlg = self.app.window(title='Untitled - Notepad', class_name='Notepad')
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)
        self.dlg.Edit.set_edit_text("Here is some text\r\n and some more")

        self.app2 = Application().start(_notepad_exe())

    def tearDown(self):
        """Close the application after tests"""
        try:
            self.app.UntitledNotepad.menu_select("File->Exit")
            self.app.Notepad["Do&n't Save"].click()
            self.app.Notepad["Do&n't Save"].wait_not('visible')
        except Exception:  # TimeoutError:
            pass
        finally:
            self.app.kill()
        self.app2.kill()

    def testMenuSelectNotepad_bug(self):
        """In notepad - MenuSelect Edit->Paste did not work"""
        text = b'Here are some unicode characters \xef\xfc\r\n'
        self.app2.UntitledNotepad.Edit.wait('enabled')
        time.sleep(0.3)
        self.app2.UntitledNotepad.Edit.set_edit_text(text)
        time.sleep(0.3)
        self.assertEqual(self.app2.UntitledNotepad.Edit.text_block().encode(locale.getpreferredencoding()), text)

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

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

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

        self.assertEqual(self.dlg.Edit.text_block().encode(locale.getpreferredencoding()), text * 3)
예제 #3
0
    def test_getattribute(self):
        """Test that __getattribute__() works correctly"""
        Timings.window_find_timeout = 5
        app = Application()
        app.start(_notepad_exe())

        self.assertRaises(
            findbestmatch.MatchError,
            app.blahblah.__getattribute__, '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.__getattribute__, 'handle')

        self.assertEqual(
            app.AboutNotepad.handle,
            app.window(title = "About Notepad").handle)

        app.AboutNotepad.Ok.Click()
        app.UntitledNotepad.MenuSelect("File->Exit")
예제 #4
0
def OnMouseEvent(event):
    global last_event_time
    # if this is the first action - remember the start time of the script
    if not last_event_time:
        last_event_time = event.Time
    app = Application()

    # wrap the window that is coming from the event
    if event.Window:
        wrapped = app.window(handle = event.Window)
    else:
        wrapped = None

    # if there was no previous message
    global last_message
    if last_message is None:
        last_message = event.MessageName
        return True


    # get the button pressed
    button = ""
    if "right" in event.MessageName and "right" in last_message:
        button = "Right"
    elif "left" in event.MessageName and "left" in last_message:
        button = "Left"

    toplevel = ""
    if wrapped and not wrapped.IsDialog():
        toplevel = '.Window_(title = "%s", class_name = "%s")' %(
            wrapped.TopLevelParent().window_text(), wrapped.TopLevelParent().class_name())

    if "up" in event.MessageName and "down" in last_message:
        print "time.sleep(%d)"% (event.Time - last_event_time)
        print 'app%s.Window_(title = "%s", class_name = "%s").%sClickInput()'%(
            toplevel,
            wrapped.WindowText(),
            wrapped.Class(),
            button)

    last_event_time = event.Time
    last_message = event.MessageName


  # called when mouse events are received
  #print 'MessageName:',event.MessageName
#  print 'Message:',event.Message
#  print 'Time:',event.Time
  #print 'Window:',event.Window
#  print 'WindowName:',event.WindowName
#  print 'Position:',event.Position
#  print 'Wheel:',event.Wheel
#  print 'Injected:',event.Injected
#  print '---'

  # return True to pass the event to other handlers
    return True
예제 #5
0
class ActionLoggerOnStadardLoggerTestCases(unittest.TestCase):

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

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

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

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

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

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

        actionlogger.enable()
        self.app.window(title='About Notepad').OK.click()
        self.assertEqual(self.__lineCount(), prev_line_count + 2)
예제 #6
0
class WindowWithoutMessageLoopFocusTests(unittest.TestCase):

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

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

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

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

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

        self.app2.window().edit.type_keys("1")
        # cmd.exe into python.exe;  pywintypes.error:
        #     (87, 'AttachThreadInput', 'The parameter is incorrect.')
        # python.exe on its own;  pywintypes.error:
        #     (0, 'SetForegroundWindow', 'No error message is available')
        self.assertTrue(self.app2.window().is_active())
예제 #7
0
class ActionloggerTestCases(unittest.TestCase):
    """Unit tests for the actionlogger"""
    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 tearDown(self):
        """Close the application after tests"""
        self.logger.parent.handlers[0].stream = self.out
        self.app.kill_()

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

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

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

        actionlogger.enable()
        self.app.window(title='About Notepad').OK.Click()
        self.assertEquals(self.__lineCount(), prev_line_count + 2)
예제 #8
0
 def process_the_file(self):
     if os.path.exists(self.path_models + "spec.csv"):
         os.remove(self.path_models + "spec.csv")
     os.chdir(self.path)
     app = Application(backend="win32").start("wkinet.exe")
     app.window().menu().get_menu_path("Файл")[0].sub_menu().get_menu_path(
         "Открыть")[0].click()
     dlg = app.top_window()
     dlg.Edit.set_edit_text("spec.kin")
     dlg["Открыть"].click_input()
     app.top_window().set_focus()
     sleep(0.5)
     send_keys("{F5}")
     sleep(4)
     app.top_window().menu_select("Окна->Решение 1")
     sleep(0.5)
     app.top_window().menu_select("Файл->Экспорт")
     app.top_window().set_focus()
     dlg = app.top_window()
     dlg.Edit.set_edit_text("spec.csv")
     dlg["Сохранить"].click_input()
     sleep(2)
     app.kill()
예제 #9
0
 def workField_Open_EditArgument(self):
     """
     紧固件强度校核--紧固件参数输入
     打开编辑参数弹框,并返回窗口实例
     :return:
     """
     from tool import Check_winControl
     workField = self.workField.Button2
     Check_winControl(None, workField).window_handle_WhetherOpen(
         "#32770", "Edit4")  # 编辑参数是否打开
     hwnd = win32gui.FindWindow("#32770", None)  # 获取窗体的句柄
     app = Application().connect(handle=hwnd, timeout=20)
     dlg_spec = app.window(handle=hwnd)  # 切换到选择文件弹窗窗口
     return dlg_spec
예제 #10
0
def test_Input_Goods():
    Application(backend="uia").start(r"H:\POSsystem\qxsaas.exe")
    app=Application(backend="uia").connect(path=r"H:\POSsystem\qxsaas.exe")
    Dialog=app.window(title='云POS')
    Dialog.type_keys("~")
    #键盘操作
    input_pykeyword=PyKeyboard()
    with open(r'C:\Users\drigon\Desktop\winpos自动化\winpos脚本\task2.0\dict.txt','r') as List:
        for list_number in List:
            input_pykeyword.type_string(list_number)
            Dialog.type_keys("~")
            time.sleep(random.uniform(0.1,0.5))
            Dialog.type_keys("~")
        List.close()
예제 #11
0
파일: tool.py 프로젝트: hejian5621/Aerobook
 def handle_popUp_exist(self, identification):
     """
     通过窗口的类名获取句柄,通句柄判断窗口是否存在
     :return:
     """
     import win32gui
     hwnd = win32gui.FindWindow(self.title, None)  # 通过弹窗的类名获取弹窗的句柄
     app = Application().connect(handle=hwnd, timeout=20)
     dlg_spec = app.window(handle=hwnd)  # 切换到选择文件弹窗窗口
     if dlg_spec[identification].exists():
         retur = True
     else:
         retur = False
     return retur
예제 #12
0
class WeiXin(object):
    def __init__(self):
        # 获取微信客户端连接应用对象
        self.app = Application(backend='uia').connect(
            path="D:\Program Files (x86)\Tencent\WeChat\WeChat.exe")

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

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

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

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

    def teardown(self):
        """释放资源"""
        # 结束进程,释放资源
        self.app.kill()
예제 #13
0
def OnKeyboardEvent(event):
    global last_event_time

    # if this is the first action - remember the start time of the script
    if not last_event_time:
        last_event_time = event.Time

    #print dir(event)

    app = Application()

    if event.Window:
        wrapped = app.window(handle = event.Window)
    else:
        pass

    global last_message
    if last_message is None:
        last_message = event.MessageName
        return True

    if "down" in event.MessageName:
        print "time.sleep(%d)"% (event.Time - last_event_time)
        print 'app.Window_(title = "%s", class_name = "%s").Typekeys("%s")'%(
            wrapped.window_text(),
            wrapped.class_name(),
            `event.Key`)

    last_event_time = event.Time
    print 'MessageName:',event.MessageName


#  print 'Message:',event.Message
#  print 'Time:',event.Time
#  print 'Window:',event.Window
#  print 'WindowName:',event.WindowName
    win = event.WindowName
#  print 'Ascii:', event.Ascii, chr(event.Ascii)
#  print 'Key:', event.Key
#  print 'KeyID:', event.KeyID
#  print 'ScanCode:', event.ScanCode
#  print 'Extended:', event.Extended
#  print 'Injected:', event.Injected
#  print 'Alt', event.Alt
#  print 'Transition', event.Transition
#  print '---'

  # return True to pass the event to other handlers
    return True
예제 #14
0
class Application:
    def __init__(self, target):
        #конструктор для инициализации тестируемого приложения target - путь к нему
        self.application = WinApplication(backend="win32").start(target)
        #вызвали конструктор импортируемого класса с параметром для вызова и старт с путем к исполяемому файлу
        self.main_window = self.application.window(title="Free Address Book")
        #сохранили метод с вызовом окна
        self.main_window.wait("visible")
        #ожидание видимости окна
        self.groups = GroupHelper(self)
        #сохраняем ссылку для используемого помощника c сылкой на текущий объект в качестве параметра

    def destroy(self):
        #останавливает тестируемое приложение(фикстуру разрушает)
        self.main_window.close()
예제 #15
0
 def designVariableSection_LayUp(self):
     """
     设计变量--一维单元设计变量(截面尺寸)--铺层比定义
     :return:
     """
     try:
         wnd = win32gui.FindWindow(None, "铺层比定义")  # 通过弹窗的类名获取弹窗的句柄
         if wnd == 0:  # 如果句柄是0,就说明没有找到窗口,就抛出异常
             raise MyException("没有找到弹窗“1D截面参数定义”")
     except Exception:
         pass
     else:
         app = Application().connect(handle=wnd)
         self.dlg_spec = app.window(handle=wnd)  # 切换到选择文件弹窗窗口
         self.dlg_spec.Button3.click_input()
예제 #16
0
파일: reload_2.py 프로젝트: shj0180/test01
def start_moni():
    app_adress = r'C:\175撮合\sh\sh_moni.exe'
    aim_dir = os.path.dirname(app_adress)
    os.chdir(aim_dir)
    os.popen(app_adress.split('\\')[-1])

    time.sleep(1)
    app = Application().connect(path=app_adress)
    time.sleep(1)
    qd = app.window(class_name='WindowsForms10.Window.8.app.0.2bf8098_r11_ad1',
                    title='上海模拟撮合').child_window(
                        title="启动",
                        auto_id="start_cl",
                        control_type="System.Windows.Forms.Button")
    # qd.print_control_identifiers()
    qd.click()
예제 #17
0
def main(argv):
    orbit_testing.WaitForOrbit()
    application = Application(backend='uia').connect(title_re='orbitprofiler')
    orbit_testing.ConnectToGamelet(application)
    orbit_testing.SelectProcess(application, 'hello_')
    orbit_testing.FocusOnCaptureWindow(application)
    orbit_testing.Capture(application, 5)

    main_wnd = application.window(title_re='orbitprofiler', found_index=0)
    main_wnd.child_window(title="Bottom-Up").click_input()
    logging.info('Switched to Bottom-Up tab')

    # Now that the "Bottom-Up" tab is selected,
    # main_wnd.TreeView is the QTreeView of the bottom-up view.
    # main_wnd.TreeView.children(control_type='TreeItem') returns
    # every cell in the bottom-up view, in order by row and then column.
    # It can take a few seconds.
    logging.info('Listing items of the bottom-up view...')
    tree_items = main_wnd.TreeView.children(control_type='TreeItem')
    BOTTOM_UP_ROW_CELL_COUNT = 5
    row_count_before_expansion = len(tree_items) / BOTTOM_UP_ROW_CELL_COUNT

    if row_count_before_expansion < 10:
        raise RuntimeError('Less than 10 rows in the bottom-up view')

    if tree_items[0].window_text() != 'ioctl':
        raise RuntimeError('First item of the bottom-up view is not "ioctl"')
    logging.info('Verified that first item is "ioctl"')

    tree_items[0].double_click_input()
    logging.info('Expanded the first item')

    logging.info('Re-listing items of the bottom-up view...')
    tree_items = main_wnd.TreeView.children(control_type='TreeItem')
    row_count_after_expansion = len(tree_items) / BOTTOM_UP_ROW_CELL_COUNT
    if row_count_after_expansion <= row_count_before_expansion:
        raise RuntimeError('First item of the bottom-up view has no children')

    if not tree_items[BOTTOM_UP_ROW_CELL_COUNT].window_text().startswith(
            'drm'):
        raise RuntimeError('First child of the first item ("ioctl") '
                           'of the bottom-up view doesn\'t start with "drm"')
    logging.info(
        'Verified that first child of the first item starts with "drm"')

    main_wnd.CloseButton.click_input()
    logging.info('Closed Orbit.')
예제 #18
0
 def fin():
     print('\nSome resource fin')
     time.sleep(5)
     # так как фикстура запускает перезапуск процесса (возможно, стоит над этим подумать и как-то изменить), нужен слип, чтобы процесс запустился
     app1 = Application(backend="uia").connect(title="SecurOS Enterprise")
     time.sleep(1)
     app1.window().Edit2.click_input()
     time.sleep(1)
     app1.window().Edit2.type_keys("securos")
     time.sleep(1)
     app1.window().Авторизоваться.click()
예제 #19
0
    def run(self):
        app = Application(backend='win32')
        if not self.login_app_connectable():
            sys.exit()

        app.connect(title='Open API Login')
        dlg = app.window(title='Open API Login')

        # dlg.Edit1.get_focus()
        # dlg.Edit1.type_keys(self.login_id)
        dlg.Edit2.get_focus()
        dlg.Edit2.type_keys(self.login_password)
        # dlg.Edit3.get_focus()
        # dlg.Edit3.type_keys(self.certificate_password)

        dlg.Button1.click_input()
        self.event_loop.exit()
예제 #20
0
class Monitool:

    def __init__(self):
        self.syst_name = 'ECD'
        self.client = '800'
        self.user = '******'
        self.pw = 'Welcome123'
        self.transactions = []
        print('Hello World')

    def pause(self, seconds):
        time.sleep(seconds)

    def open_sap_logon(self):
        try:
            print("Checking if App is already opened.")
            self.app = Application().Connect(path=r"C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplogon.exe")
            self.dlg = self.app.Dialog
        except:
            print("Opening App.")
            self.app = Application().Start(cmd_line=u'"C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplogon.exe"')
            self.dlg = self.app.Dialog

    def connect_sap_system(self):
        print("Opening system instance.")
        self.dlg.Button7.click()  # list view
        syst_list = self.dlg.listView
        self.pause(2)

        try:
            syst_list.type_keys("{HOME}")
            syst_list.GetItem(self.syst_name).Click()
            self.dlg['Log&On'].Click()
        except ValueError:
            print("Please add system in SAP logon")
            self.app.Kill_()

        print("Login user.")
        sap_frontend_session = self.app.window(class_name='SAP_FRONTEND_SESSION')
        sap_frontend_session.type_keys(self.user + "{TAB}" + self.pw)
        sap_frontend_session.type_keys("{TAB 21}")
        sap_frontend_session.type_keys("^a{BKSP}" + self.client)
        sap_frontend_session.type_keys("{ENTER}")

    def set_system(self, system):
        self.syst_name = system
예제 #21
0
def BuildAionApp(testAppName):
    if not(os.path.isdir(testAppDirectory + "\\" + testAppName)):
        print ("Failed to find test application directory")
        print ("Exit code 3: The system cannot find the path specified.")
        return (3)
    if not(os.path.exists(testAppDirectory + "\\" + testAppName + "\\" + testAppName + ".app" )):
        print ("Failed to find test application directory")
        print ("Exit code 2: The system cannot find the file specified.")
        return (2)
    goToTestExample = "cd  " + testAppDirectory + "\\" + testAppName + " && "
    deleteOldLogsAndTestFiles = "rmdir " + testAppName + ".bin /s /q  &  del " + testAppName + ".log & dir > " + testAppName + ".log && "
    respawnApp = "respawn associate.app >> " + testAppName + ".log  2>&1"
    print("In the next step I will run respawn in command line")
    cmdTestRoutineWin = goToTestExample + deleteOldLogsAndTestFiles + respawnApp
    print(cmdTestRoutineWin)

    try:
        subprocess.call(cmdTestRoutineWin, shell=True, timeout=3)
    except Exception:
        print("Fail to start your test application")
        print("Because of Error when attempting to start test application this test run will be aborted ... ")
        #   sys.exit(8)

    # Check for specific Dialog box window that in this case indicate missing test file
    try:
        appCheckPoint = Application().Connect(title='Aion Build Utility')
    except Exception:
        print("Everything seems to be fine with respawn")

    try:
        appCheckPoint
        if appCheckPoint.window(title='Aion Build Utility').Exists():
            print("Aion Build Utility Error")
            # If detected dialog exists it should be closed othewise it polute client desktop afte test exits
            appCheckPoint['Dialog']['Button'].click()
    except NameError:
        print("Everything is fine with running respawn command")
    except Exception:
        print("Something else went wrong")
    print("file open checkpoint")
    print(testAppDirectory + "\\" + testAppName + ".log")
    file = open(testAppDirectory + "\\" + testAppName + "\\" + testAppName + ".log", 'r')
    print(file.read())

    print("Finished building test application")
    print (testAppName)
예제 #22
0
def test_delete_dumps():
    m = dt.datetime.now()
    app = Application(backend="uia").start(path).connect(title=title)
    file_name, file_name1, file_name2, file_name3 = set_file_name_with_datetime(
        m)
    dlg = app.window(title=title)
    dlg2 = dlg.child_window(auto_id="1011")
    #как именно выделять чек-бокс, не разобрался. Просто кликаю, ставит\снимает.
    dlg2.click()
    copyfile(dump_to_copy, path_to_copy)
    time.sleep(5)
    dlg.Пуск.click()
    time.sleep(390)
    app = Application(backend="uia").connect(path=path)
    close_final_dialogs(app, dlg)
    #внутри удаления идет проверка на существование файла, возможно стоит ее вытащить сюда, но не факт.
    delete_issinfo(file_name, file_name1, file_name2, file_name3)
예제 #23
0
def telegram_test ():
    shell = win32com.client.Dispatch("WScript.Shell") #нажатие клавиш с клавиатуры

    username = getpass.getuser()
    print(username)
    path_telegram = (r"C:\\Users\\" + username + r"\\AppData\\Roaming\\Telegram Desktop\\Telegram.exe")
    print (path_telegram)
    start = Application(backend="uia").start(path_telegram) #надо получать пользователя и подменять его
    
    PROCNAME = "Telegram.exe"
    for proc in psutil.process_iter():
        if proc.name() == PROCNAME:
            print(proc)
            app = Application(backend="uia").connect(process = proc.pid)

    dlg = app.window(title="Telegram")
    print("GO")
    
    time.sleep(5)
    
    shell.SendKeys("Saved messages")
    time.sleep(1)
    shell.SendKeys('{ENTER}')
    time.sleep(1)
    shell.SendKeys("first message - hahaha")
    time.sleep(1)
    shell.SendKeys('{ENTER}')
    time.sleep(1)

    os.system('explorer.exe C:\test\files')
    time.sleep(1)
    shell.SendKeys('%{TAB}')
    time.sleep(1)
    shell.SendKeys('^a',0)
    time.sleep(1)
    shell.SendKeys('^c',0)
    time.sleep(1)
    shell.Sendkeys('%{F4}')
    time.sleep(1)

    shell.SendKeys('%{TAB}')
    
    time.sleep(1)
    shell.SendKeys('^v',0)
    time.sleep(2)
    shell.SendKeys('{Enter}')
예제 #24
0
def OnKeyboardEvent(event):
    global last_event_time

    # if this is the first action - remember the start time of the script
    if not last_event_time:
        last_event_time = event.Time

    #print dir(event)

    app = Application()

    if event.Window:
        wrapped = app.window(handle=event.Window)
    else:
        pass

    global last_message
    if last_message is None:
        last_message = event.MessageName
        return True

    if "down" in event.MessageName:
        print "time.sleep(%d)" % (event.Time - last_event_time)
        print 'app.Window_(title = "%s", class_name = "%s").Typekeys("%s")' % (
            wrapped.window_text(), wrapped.class_name(), ` event.Key `)

    last_event_time = event.Time
    print 'MessageName:', event.MessageName

    #  print 'Message:',event.Message
    #  print 'Time:',event.Time
    #  print 'Window:',event.Window
    #  print 'WindowName:',event.WindowName
    win = event.WindowName
    #  print 'Ascii:', event.Ascii, chr(event.Ascii)
    #  print 'Key:', event.Key
    #  print 'KeyID:', event.KeyID
    #  print 'ScanCode:', event.ScanCode
    #  print 'Extended:', event.Extended
    #  print 'Injected:', event.Injected
    #  print 'Alt', event.Alt
    #  print 'Transition', event.Transition
    #  print '---'

    # return True to pass the event to other handlers
    return True
예제 #25
0
def get_expressions(bit_map):
    eps = []
    app = Application().start(
        os.path.join('implementation', 'Logic Functions Minimization.exe'))
    a = app.window()
    size, bits = bit_map.shape
    i_bits = np.log2(size)
    for i in range(bits):
        if (np.all(bit_map[:, i] == 0) == False):
            min = np.where(bit_map[:, i] == 1)[0].tolist()
            ep = get_expression(min, i_bits, a)
            eps.append(ep)
        else:
            ep = 'the %d line is all 0' % i
            eps.append(ep)
    a['Quit'].Click()
    return eps
예제 #26
0
def test_Save_Pay():
    #需要与其他def函数使用同种连接方式
    Application(backend="uia").start(r"H:\POSsystem\qxsaas.exe")
    app=Application(backend="uia").connect(path=r"H:\POSsystem\qxsaas.exe")
    #判断窗体是否形成句柄
    Dialog=app.window(title='云POS')
    Flag=1
    while Flag:
        try:
            #储值卡支付快捷键"X"
            win32api.keybd_event(35,0,0,0)
            win32api.keybd_event(35,0,win32con.KEYEVENTF_KEYUP,0)
            time.sleep(2)
            Dialog.child_window(title="储值卡收款", control_type="Text").wait('exists',timeout=3,retry_interval=3)
            Pay=Dialog.child_window(title="储值卡收款", control_type="Text")
            #储值卡账号输入
            Pay.type_keys("10000")
            Pay.type_keys("~")
            time.sleep(2)
            Pay.type_keys("~")
            #储值卡支付密码弹出窗体
            Save_Dialog=Dialog.child_window(title="等待顾客输入密码或扫手机动态码", control_type="Text")
            Save_Dialog.wait('ready',timeout=3,retry_interval=3)
            Save_Dialog.type_keys("~")
            #储值卡密码输入
            Save_Dialog.type_keys("123456")
        except:
            print("储值卡支付界面疑似出现延迟!!!")
            Save_Dialog.type_keys("{ESC}")
            Pay.type_keys("{ESC}")
            log_object=open('D:\error.log','a')
            log_object.writelines(time.asctime(time.localtime(time.time())))
            log_object.writelines("储值卡收款界面疑似出现延迟!!!"+'\n')
            log_object.close()
            try:
                #如果出现大批量促销商品,会触发该保护策略
                Pop_box=Dialog.child_window(title="正在计算促销,还不能结算"+'\n')
                Pop_box.wait('exists',timeout=3)
            except:
                continue
            else:
                Pop_box.type_keys("~")
                time.sleep(1)
        else:
            Save_Dialog.type_keys("~")
            Flag=0
예제 #27
0
파일: tool.py 프로젝트: hejian5621/Aerobook
 def console(self):
     """
     弹窗置顶操作
     :return:
     """
     print("\033[0;31m开始%r弹窗置顶操作" % self.window_name, __file__,
           sys._getframe().f_lineno)
     # 首先判断控件是否是最大化
     main_window = Application().connect(title_re=self.window_name,
                                         timeout=10)
     Aerobook_main = main_window.window(title_re=self.window_name)
     WindowState = Aerobook_main.is_maximized()  # 判断窗口是否是最大化
     if WindowState:  # 如果是
         print("弹窗已经是最大化")
     else:  # 如果不是最大化
         Aerobook_main.maximize()  # 窗口最大化
         print("进行弹窗最大化操作")
     WindowTop(self.window_name).EnumWindows()  # 窗口置顶显示
예제 #28
0
def copy_and_past():
    """It is required to have a notepad window already open.
    When passing in the file name, just pass in 'TextName' and don't pass in '- Notepad or .txt'
    """
    document_name = input("What is the name of your file?: ")
    app = Application().connect(
        title=f'{document_name} - Notepad', class_name="Notepad"
    )  # Connect is used to set what application is running.
    # Basically connecting the program to the application
    app.top_window().set_focus()
    rect = app.window(title=f'{document_name} - Notepad',
                      found_index=0)  # Get the program by named
    rect.move_window(x=0, y=0)  # Moves the window to top left of screen
    pyautogui.moveTo(100, 200)  # moves the mous to 100, 200
    click()  # clicks the mouse on the open app
    pyautogui.hotkey('ctrl', 'a', interval=0.10)  # select all
    pyautogui.hotkey('ctrl', 'c', interval=0.1)  # copy all that was selected
    print(pyperclip.paste())  # print out what was copied
def test_34_YUAN():
    m = dt.datetime.now()
    end_time = m.strftime("%Y%m%dT%H%M%S%Z")
    cam_id = "34"
    out_file_name = "34_YUAN.asf"
    app = Application(backend="uia").start(r'"' + path_to_backupexe + '" --out "' + output_folder + out_file_name + '" --cam "' + cam_id + '" --from "' + begin_time + '" --to "' + end_time + '" --archive-path "' + path_to_archive + '" --video-codec MPEG4 --audio-codec PCM --span cd --video-quality 0 --fps-divider 1 --raw-video').connect(title=title)
    dlg = app.window(title=title)
    dlg1 = dlg.child_window(auto_id="2")
    dlg1.wait('visible', timeout=150)
    dlg.child_window(auto_id="2").click()

    hasher = hashlib.md5()
    with open(''+output_folder + out_file_name+'', 'rb') as afile:
        buf = afile.read()
        hasher.update(buf)
    print(hasher.hexdigest())
    assert hasher.hexdigest() == hash5_YUAN
    os.remove(''+output_folder + out_file_name+'')
예제 #30
0
def test_Member_Savecent_Pay():
    #需要与其他def函数使用同种连接方式
    Application(backend="uia").start(r"H:\POSsystem\qxsaas.exe")
    app=Application(backend="uia").connect(path=r"H:\POSsystem\qxsaas.exe")
    #判断窗体是否形成句柄
    Dialog=app.window(title='云POS')
    Flag=1
    while Flag:
        try:
            #会员积分支付快捷键"X"
            win32api.keybd_event(88,0,0,0)
            win32api.keybd_event(88,0,win32con.KEYEVENTF_KEYUP,0)
            Dialog.child_window(title="积分收款", control_type="Text").wait('exists',timeout=3,retry_interval=3)
            Pay=Dialog.child_window(title="积分收款", control_type="Text")
            Pay.type_keys("~")
            Dialog.child_window(title="等待顾客输入密码或扫手机动态码").wait('exists',timeout=3,retry_interval=2)
        except:
            print("会员积分支付界面疑似出现延迟!!!")
            log_object=open('D:\error.log','a')
            log_object.writelines(time.asctime(time.localtime(time.time())))
            log_object.writelines("会员积分收款界面疑似出现延迟!!!"+'\n')
            log_object.close()
            #操作alt+f4关闭积分支付界面,由于积分界面有两个所以推出两次
            win32api.keybd_event(18,0,0,0)
            win32api.keybd_event(115,0,0,0)
            win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0)
            win32api.keybd_event(115,0,win32con.KEYEVENTF_KEYUP,0)
            win32api.keybd_event(18,0,0,0)
            win32api.keybd_event(115,0,0,0)
            win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0)
            win32api.keybd_event(115,0,win32con.KEYEVENTF_KEYUP,0)
            try:
                Pop_box=Dialog.child_window(title="正在计算促销,还不能结算"+'\n')
                Pop_box.wait('exists',timeout=3)
            except:
                continue
            else:
                Pop_box.type_keys("~")
                time.sleep(1)
        else:
            Save_Pay=Dialog.child_window(title="等待顾客输入密码或扫手机动态码")
            Save_Pay.type_keys("123456")
            Save_Pay.type_keys("~")
            Flag=0
예제 #31
0
def test_Only_List():
    i=10
    Application(backend="uia").start(r"H:\POSsystem\qxsaas.exe")
    app=Application(backend="uia").connect(path=r"H:\POSsystem\qxsaas.exe")
    Dialog=app.window(title='云POS')
    #键盘操作
    input_pykeyword=PyKeyboard()
    while i!=0:
        i=i-1
        with open(r'C:\Users\drigon\Desktop\winpos自动化\winpos脚本\task2.0\TestData\dict.txt','r') as List:
            for list_number in List:
                input_pykeyword.type_string(list_number)
                Dialog.type_keys("~")
                time.sleep(random.uniform(0.1,0.5))
                Dialog.type_keys("~")
            List.close()
        time.sleep(random.uniform(1,2))
        win32api.keybd_event(65,0,0,0)
        win32api.keybd_event(65,0,win32con.KEYEVENTF_KEYUP,0)
예제 #32
0
class Paint:
	__paint_process = None
	_paint = None

	def __init__(self):
		self.__paint_process = Popen(["mspaint"])
		self._paint = Application(backend="uia").connect(process=self.__paint_process.pid)
		self._paint = self._paint.window()

	def __del__(self):
		self.__paint_process.terminate()

	def __call__(self, *args, **kwargs):
		return self._paint

	def ribbon(self):
		return Ribbon(self())

	def size_changing_dialog(self):
		return SizeChangingDialog(self())
예제 #33
0
    def menu_LetsGoTopopover(self):
        """
        确定被测弹窗是否存在,如果存在返回弹窗实体
        :return:
        """

        while self.CircleInitial <= self.cycleIndex:
            try:
                hwnd = win32gui.FindWindow(None, self.window_title)
                if hwnd == 0:
                    raise MyException("窗口没有关闭")  # 实例化一个异常,实例化的时候需要传参数
            except Exception as obj:  # 如果没有找到弹窗继续循环找
                time.sleep(0.1)
            else:
                app = Application().connect(handle=hwnd)
                self.popupWin = app.window(handle=hwnd)
                break
            self.CircleInitial = self.CircleInitial + 1
            if self.CircleInitial == (self.cycleIndex + 1):
                raise MyException("没有找到”%r“弹窗" % self.window_title)
        return self.popupWin
예제 #34
0
def test_Entity_Pay():
    #需要与其他def函数使用同种连接方式
    Application(backend="uia").start(r"H:\POSsystem\qxsaas.exe")
    app=Application(backend="uia").connect(path=r"H:\POSsystem\qxsaas.exe")
    #判断窗体是否形成句柄
    Dialog=app.window(title='云POS')
    #将文件路径使用Path函数增添到某个变量中
    p=Path(r'C:\Users\drigon\Desktop\winpos自动化\winpos脚本\task2.0\TestData\entity_coupons.txt')
    #使用Path方式打开优惠券字典表
    with p.open() as f:
        #将p目录下的文件按行全部读取到ss中形成列表
        ss=f.readlines()
        #将列表中字符串按个取出
        for line in ss:
            try:
                #实体券支付快捷键"Z"
                win32api.keybd_event(90,0,0,0)
                win32api.keybd_event(90,0,win32con.KEYEVENTF_KEYUP,0)
                #优惠券收款窗体等待
                Dialog.child_window(title="优惠券收款", control_type="Text").wait('exists',timeout=3,retry_interval=3)
                Pay=Dialog.child_window(title="优惠券收款", control_type="Text")
                #输入优惠券号
                Pay.type_keys(line)
                #进行优惠券支付操作
                Pay.type_keys("~")
                time.sleep(2)
                Pay.type_keys("~")
            except:
                print("实体券支付界面出现异常!!!")
                log_object=open('D:\error.log','a')
                log_object.writelines(time.asctime(time.localtime(time.time())))
                log_object.writelines("现金收款界面疑似出现延迟!!!"+'\n')
                log_object.close()
            else:
                #由于每次都读取字典表中第一行,所以删除读取到优惠券字典表中的第一行数据即可
                ss=ss[:0]+ss[1:]
                p.write_text(''.join(ss))
                #关闭优惠券字典表
                f.close()
            break
예제 #35
0
 def AuthorizedOperation(self, app_window):
     """
     进行授权操作
     :return:
     """
     # 点击请求授权按钮
     son_window = app_window.child_window(
         title="本地授权",
         auto_id="groupBox_local",
         control_type="System.Windows.Forms.GroupBox")
     son_window.window(title="请求授权").wait("exists",
                                          timeout=10,
                                          retry_interval=0.1).click_input()
     succeed_window = Application().connect(title_re=r'成功', timeout=10)
     succeed1_window = succeed_window.window(title_re=r'成功')
     # succeed1_window.print_control_identifiers()
     succeed1_window.child_window(title="确定").wait(
         "exists", timeout=10, retry_interval=0.1).click_input()  # 点击确定按钮
     # 切回到Aerobook平台启动器窗口并点击运行按钮
     app_window.window(title=r'运行').wait("exists",
                                         timeout=10,
                                         retry_interval=0.1).click_input()
예제 #36
0
 def select_workingCondition(self,title_name):
     """
     在工作栏中选择工况
     :return:
     """
     hwnd = win32gui.FindWindow(None, title_name)
     app = Application().connect(handle=hwnd,timeout=20)  # 连接校核工况弹窗
     dlg_spec = app.window(handle=hwnd)
     # dlg_spec.print_control_identifiers()
     txt=dlg_spec.ComboBox.window_text()  # 检查是否已经有工况组合
     if txt:  # 如果txt不为空,说明有工况组合数据
         dlg1_spec=dlg_spec.RadioButton2
         Check_winControl(None,dlg1_spec).Verify_CheckBox_Status()  # 点击工况组合选中工况组合
         Check_winControl(title_name,"确认").popUp_Whether_close()
     else:  # 如果txt为空,说明没有工况组合数据,就增加数据
         dlg1_spec = dlg_spec.RadioButton3
         Check_winControl(None,dlg1_spec).Verify_CheckBox_Status()  # 点击工况组合选中工况组合
         dlg2_spec = dlg_spec.Edit2
         Check_winControl(None, dlg2_spec).Verify_inputBox("all")
         dlg3_spec = dlg_spec.新建工况组合Button
         Check_winControl(None, dlg3_spec).Verify_CheckBox_Status()  # 点击工况组合选中工况组合
         Check_winControl(title_name, "确认").popUp_Whether_close()
예제 #37
0
def checkAvailabilityOfReexec():
    # INVOKE PROGRAM
    try:
         # Generate respawn dialog box and if successfull then report success in "exception" block
            # When AionBRE is correcly installed, respawn.exe is accessible from system path.
            # Set of Timeout is mandatory otherwise script will not process rest of the code. NOTE: Timeout not available in Python 2.7
            respawnCheckpoint = subprocess.call("reexec.exe", shell=True, timeout=1)
    except Exception:
        print("Found reexec.exe ... ")
        # CLEAN-UP
        # Reexec execution will automatically create dialog box. We need to close this no longer needed dialog box.
    try:
        # Check if connection to respawn.exe generated dialog box is possible
        appCheckPoint = Application().Connect(title='Run Aion Application')
        # Verified that reexec.exe generated dialog box exists and now that test is done I need to remove it (clean up).
        if appCheckPoint.window(title='Run Aion Application').Exists():
            appCheckPoint['Dialog']['Cancel'].click()
        print("Run Aion Application is available and functional")
    # ERROR PROCESSING
    except Exception:
        # Something went wrong. Report problem (most likely repawn is not installed or not in system path)
        print("reexec.exe (Run Aion Application) is not available on targeted system.")
        print("Return code 197: The operating system is not presently configured to run reexec application.")
        exit(197)
예제 #38
0
class MenuWrapperTests(unittest.TestCase):
    "Unit tests for the Menu and the MenuItem classes"

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

        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.assertEqual(5, self.dlg.menu().item_count())

    def testItem(self):
        self.assertEqual(u'&File', self.dlg.menu().item(0).text())
        self.assertEqual(u'&File', self.dlg.menu().item(u'File').text())
        self.assertEqual(u'&File', self.dlg.menu().item(u'&File', exact=True).text())

    def testItems(self):
        self.assertEqual([u'&File', u'&Edit', u'F&ormat', u'&View', u'&Help'],
                          [item.text() for item in self.dlg.menu().items()])

    def testFriendlyClassName(self):
        self.assertEqual('MenuItem', self.dlg.menu().item(0).friendly_class_name())

    def testMenuItemNotEnabled(self):
        self.assertRaises(MenuItemNotEnabled, self.dlg.menu_select, 'Edit->Find Next')
        self.assertRaises(MenuItemNotEnabled, self.dlg.menu_item('Edit->Find Next').click)
        self.assertRaises(MenuItemNotEnabled, self.dlg.menu_item('Edit->Find Next').click_input)

    def testGetProperties(self):
        self.assertEqual(
            {u'menu_items':
                [{u'index': 0, u'state': 0, u'item_type': 0, u'item_id': 64, u'text': u'View &Help'},
                 {u'index': 1, u'state': 3, u'item_type': 2048, u'item_id': 0, u'text': u''},
                 {u'index': 2, u'state': 0, u'item_type': 0, u'item_id': 65, u'text': u'&About Notepad'}]},
            self.dlg.menu().get_menu_path('Help')[0].sub_menu().get_properties())

    def testGetMenuPath(self):
        # print('id = ' + str(self.dlg.menu().get_menu_path('Help->#3')[0].id()))
        self.assertEqual(u'&About Notepad', self.dlg.menu().get_menu_path(' Help -> #2 ')[-1].text())
        self.assertEqual(u'&About Notepad', self.dlg.menu().get_menu_path('Help->$65')[-1].text())
        self.assertEqual(u'&About Notepad',
                          self.dlg.menu().get_menu_path('&Help->&About Notepad', exact=True)[-1].text())
        self.assertRaises(IndexError, self.dlg.menu().get_menu_path, '&Help->About what?', exact=True)

    def test__repr__(self):
        print(self.dlg.menu())
        print(self.dlg.menu().get_menu_path('&Help->&About Notepad', exact=True)[-1])

    def testClick(self):
        self.dlg.menu().get_menu_path('&Help->&About Notepad')[-1].click()
        About = self.app.window(title='About Notepad')
        About.wait('ready')
        About.OK.click()
        About.wait_not('visible')

    def testClickInput(self):
        self.dlg.menu().get_menu_path('&Help->&About Notepad')[-1].click_input()
        About = self.app.window(title='About Notepad')
        About.wait('ready')
        About.OK.click()
        About.wait_not('visible')
예제 #39
0
class HwndWrapperMenuTests(unittest.TestCase):

    """Unit tests for menu actions of the HwndWrapper class"""

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

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

        self.dlg = self.app.RowListSampleApplication
        self.ctrl = self.app.RowListSampleApplication.ListView.wrapper_object()

    def tearDown(self):
        """Close the application after tests"""
        self.dlg.send_message(win32defines.WM_CLOSE)

    def testMenuItems(self):
        """Test getting menu items"""
        self.assertEqual(self.ctrl.menu_items(), [])
        self.assertEqual(self.dlg.menu_items()[1]['text'], '&View')

    def testMenuSelect(self):
        """Test selecting a menu item"""

        if self.dlg.menu_item("View -> Toolbar").is_checked():
            self.dlg.menu_select("View -> Toolbar")
        self.assertEqual(self.dlg.menu_item("View -> Toolbar").is_checked(), False)

        self.dlg.menu_select("View -> Toolbar")
        self.assertEqual(self.dlg.menu_item("View -> Toolbar").is_checked(), True)

    def testClose(self):
        """Test the Close() method of windows"""
        # open about dialog
        self.dlg.menu_select('Help->About RowList...')

        # make sure it is open and visible
        self.app.AboutRowList.wait("visible", 20)
        self.assertTrue(self.app.window(title='About RowList').is_visible(), True)

        # close it
        self.app.window(title='About RowList', class_name='#32770').close(1)

        # make sure that it is not visible
        try:
            #self.assertRaises(ElementNotFoundError,
            #                  self.app.window(title='About RowList', class_name='#32770').wrapper_object())
            # vvryabov: TimeoutError is caught by assertRaises, so the second raise is not caught correctly
            self.app.window(title='About RowList', class_name='#32770').wrapper_object()
        except ElementNotFoundError:
            print('ElementNotFoundError exception is raised as expected. OK.')

        # make sure the main RowList dialog is still open
        self.assertEqual(self.dlg.is_visible(), True)

    def testCloseClick_bug(self):
        self.dlg.menu_select('Help->About RowList...')
        self.app.AboutRowList.wait("visible", 10)

        self.assertEqual(self.app.AboutRowList.exists(), True)
        self.app.AboutRowList.CloseButton.close_click()
        self.assertEqual(self.app.AboutRowList.exists(), False)

        #Timings.closeclick_dialog_close_wait = .7
        #try:
        #    self.app.AboutRowList.CloseButton.close_click()
        #except TimeoutError:
        #    pass
        #self.app.AboutRowList.close()

    def testCloseAltF4(self):
        self.dlg.menu_select('Help->About RowList...')
        AboutRowList = self.app.window(title='About RowList', active_only=True, class_name='#32770')
        AboutWrapper = AboutRowList.wait("enabled")
        AboutRowList.close_alt_f4()
        AboutRowList.wait_not('visible')
        self.assertNotEqual(AboutWrapper.is_visible(), True)
예제 #40
0
print(__doc__)

import time
from pprint import pprint

from pywinauto.application import Application

# start the application and wait for the Agent Dialog to be ready
app = Application().start(r"c:\program files\agent\agent.exe")

while not app.Windows_():
    time.sleep(.5)

# if the trial nag dialog pops up
if app.window(title = "Forte Agent Trial").Exists():
    #app.ForteAgentTrial.IdLikeToContinueUsingAgentfor7moredays.click()
    app.ForteAgentTrial.IdliketouseFreeAgent.check()
    app.ForteAgentTrial.OK.click()

if app.window(title = "Free Agent Registration").Exists():
    app.FreeAgentRegistration.ImreallybusyRemindmein30.click()
    app.FreeAgentRegistration.OK.close_click()

if app.window(title = "What's New Reminder").Exists():
    app.WhatsNewReminder.ImreallybusyRemindmein90.click()
    app.WhatsNewReminder.OK.close_click()



# wait until the app is ready
예제 #41
0
    #appAion = Application().start(r"C:\TEMP\examples\Associate\associate.bin\_associate.exe")
    appAion = Application().start(r"reexec C:\TEMP\examples\Associate\associate.app")
    #Delay timer for applications that may be slower to initialize their GUI
    while not appAion.Windows_():
        time.sleep(.5)
except Exception:
    print ("Generic exception: Application failed to start")
except:
    print ("something else went wrong")
    sys.exit()
#appAion.print_control_identifiers()
print("Second round")


#Check for specific Dialog box window that in this case indicate missing test file
if appAion.window(title = "Aion Init").Exists():
    print ("Aion script that you are referencing does not exist.")
    print(appAion['Dialog'].Texts())
    print(appAion['Dialog']['Static'].GetProperties())
    print(appAion['Dialog']['Static'].Texts())
    print(appAion['Dialog']['Button'].Texts())
    print(appAion['Dialog'].capture_as_image().save("screen_capture_InitError.png", "PNG"))
    appAion['Dialog']['Button'].click()
    print("Because test app is not available we should exit the test")
    sys.exit()




dlg = appAion['Dialog']
dlg.print_control_identifiers()
예제 #42
0
    anotherMenuDlg.capture_as_image().save("2ndMenuDlg_%d.png" % lang)

    anotherMenuDlg.OK.click()

    optionsdlg.OK.click()


# get the languages as an integer
langs = [int(arg) for arg in sys.argv[1:]]

for lang in langs:
    # start the application
    app = Application().start(t['apppath'][lang])

    # we have to wait for the Licence Dialog to open
    time.sleep(2)

    # close the Buy licence dialog box
    licence_dlg = app[t['Buy Licence'][lang]]
    licence_dlg[t['Close'][lang]].click()

    # find the WinRar main dialog
    rar_dlg = app.window(title_re = ".* - WinRAR.*")

    # dump and capture some dialogs
    get_winrar_dlgs(rar_dlg, app,  lang)

    # exit WinRar
    time.sleep(.5)
    rar_dlg.menu_select(t['File->Exit'][lang])