Best Python code snippet using fMBT_python
controlactions.py
Source:controlactions.py  
1# GUI Application automation and testing library2# Copyright (C) 2006 Mark Mc Mahon3#4# This library is free software; you can redistribute it and/or5# modify it under the terms of the GNU Lesser General Public License6# as published by the Free Software Foundation; either version 2.17# of the License, or (at your option) any later version.8#9# This library is distributed in the hope that it will be useful,10# but WITHOUT ANY WARRANTY; without even the implied warranty of11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.12# See the GNU Lesser General Public License for more details.13#14# You should have received a copy of the GNU Lesser General Public15# License along with this library; if not, write to the16#    Free Software Foundation, Inc.,17#    59 Temple Place,18#    Suite 330,19#    Boston, MA 02111-1307 USA20"""Actions for controls21You can change the following to affect waits after various actions22:delay_after_click: Specify the delay after each click23:delay_after_sendkeys_key: Specify the delay after selecting a menuitem24:delay_after_sendkeys_key: Specify the delay after typing a sendkeys character25"""26__revision__ = "$Revision$"27import time28import ctypes	 # write_debug_text action29import SendKeys  # typekeys action30import win32defines31import win32functions32import win32structures33import handleprops34import findbestmatch35import tests36# we need a slight delay after button click37# In most cases to allow the window to close38delay_after_click = .0839delay_after_menuselect = .0840delay_after_sendkeys_key = .00141class ControlNotEnabled(RuntimeError):42    "Raised when a control is not enabled"43    pass44class ControlNotVisible(RuntimeError):45    "Raised when a control is nto visible"46    pass47#====================================================================48def verify_actionable(ctrl):49    "Verify that the control is visible and enabled"50    verify_enabled(ctrl)51    verify_visible(ctrl)52#====================================================================53def verify_enabled(ctrl):54    "Verify that the control is enabled"55    # check is the parent enabled first56    if not handleprops.friendlyclassname(ctrl) == "Dialog":57        if not ctrl.Parent.IsEnabled():58            raise ControlNotEnabled()59    # then check if the control itself is enabled60    if not ctrl.IsEnabled():61        raise ControlNotEnabled()62#====================================================================63def verify_visible(ctrl):64    "Verify that the control is visible"65    if not ctrl.IsVisible() or not ctrl.Parent.IsVisible():66        raise ControlNotVisible()67_mouse_flags = {68    "left": win32defines.MK_LBUTTON,69    "right": win32defines.MK_RBUTTON,70    "middle": win32defines.MK_MBUTTON,71    "shift": win32defines.MK_SHIFT,72    "control": win32defines.MK_CONTROL,73}74#====================================================================75def calc_flags_and_coords(pressed, coords):76    "Calculate the flags to use and the coordinates"77    flags = 078    for key in pressed.split():79        flags |= _mouse_flags[key.lower()]80    click_point = win32functions.MakeLong(coords[0], coords[1])81    return flags, click_point82#====================================================================83# TODO: Test simulating mouse clicks using SendInput instead of WM_* messages84def _perform_click(85        ctrl,86        button = "left",87        pressed = "",88        coords = (0, 0),89        double = False,90        down = True,91        up = True):92    "Low level method for performing click operations"93    verify_enabled(ctrl)94    msgs  = []95    if not double:96        if button.lower() == "left":97            if down:98                msgs.append(win32defines.WM_LBUTTONDOWN)99            if up:100                msgs.append(win32defines.WM_LBUTTONUP)101        elif button.lower() == "middle":102            if down:103                msgs.append(win32defines.WM_MBUTTONDOWN)104            if up:105                msgs.append(win32defines.WM_MBUTTONUP)106        elif button.lower() == "right":107            if down:108                msgs.append(win32defines.WM_RBUTTONDOWN)109            if up:110                msgs.append(win32defines.WM_RBUTTONUP)111    else:112        if button.lower() == "left":113            msgs = (114                win32defines.WM_LBUTTONDOWN,115                win32defines.WM_LBUTTONUP,116                win32defines.WM_LBUTTONDBLCLK,117                win32defines.WM_LBUTTONUP)118        elif button.lower() == "middle":119            msgs = (120                win32defines.WM_MBUTTONDOWN,121                win32defines.WM_MBUTTONUP,122                win32defines.WM_MBUTTONDBLCLK,123                win32defines.WM_MBUTTONUP)124        elif button.lower() == "right":125            msgs = (126                win32defines.WM_RBUTTONDOWN,127                win32defines.WM_RBUTTONUP,128                win32defines.WM_RBUTTONDBLCLK,129                win32defines.WM_RBUTTONUP)130    flags, click_point = calc_flags_and_coords(pressed, coords)131    for msg in msgs:132        ctrl.PostMessage(msg, flags, click_point)133    #ctrl.PostMessage(msg, 1, click_point)134    time.sleep(delay_after_click)135#====================================================================136def click_action(137    ctrl, button = "left", pressed = "", coords = (0, 0), double = False):138    "Peform a click action"139    _perform_click(ctrl, button, pressed, coords, double)140#====================================================================141def doubleclick_action(142    ctrl, button = "left", pressed = "", coords = (0, 0), double = True):143    "Perform a double click action"144    _perform_click(ctrl, button, pressed, coords, double)145#====================================================================146def rightclick_action(147    ctrl, button = "right", pressed = "", coords = (0, 0), double = True):148    "Perform a right click action"149    _perform_click(ctrl, button, pressed, coords, double)150#====================================================================151def check_button_action(ctrl):152    "Check a checkbox"153    ctrl.SendMessage(win32defines.BM_SETCHECK, win32defines.BST_CHECKED)154#====================================================================155def uncheck_button_action(ctrl):156    "Uncheck a checkbox"157    ctrl.SendMessage(win32defines.BM_SETCHECK, win32defines.BST_UNCHECKED)158#====================================================================159def setcheck_indet_button_action(ctrl):160    "Set the checkbox to indeterminate"161    ctrl.SendMessage(win32defines.BM_SETCHECK, win32defines.BST_INDETERMINATE)162#====================================================================163def press_mouse_action(ctrl, button = "left", pressed = "", coords = (0, 0)):164    "Press the mouse button"165    flags, click_point = calc_flags_and_coords(pressed, coords)166    _perform_click(ctrl, button, pressed, coords, up = False)167#====================================================================168def release_mouse_action(ctrl, button = "left", pressed = "", coords = (0, 0)):169    "Release the mouse button"170    flags, click_point = calc_flags_and_coords(pressed, coords)171    _perform_click(ctrl, button, pressed, coords, down = False)172#====================================================================173def move_mouse_action(ctrl, pressed = "left", coords = (0, 0)):174    "Move the mouse"175    flags, click_point = calc_flags_and_coords(pressed, coords)176    ctrl.PostMessage(win32defines.WM_MOUSEMOVE, flags, click_point)177#====================================================================178def settext_action(ctrl, text, append = False):179    "Set the text of the window"180    if append:181        text = ctrl.Text + text182    text = ctypes.c_wchar_p(unicode(text))183    ctrl.PostMessage(win32defines.WM_SETTEXT, 0, text)184#====================================================================185def typekeys_action(186    ctrl,187    keys,188    pause = delay_after_sendkeys_key,189    with_spaces = False,190    with_tabs = False,191    with_newlines = False,192    turn_off_numlock = True):193    "Type keys to the window using SendKeys"194    verify_enabled(ctrl)195    win32functions.AttachThreadInput(196        win32functions.GetCurrentThreadId(), ctrl.ProcessID, 1)197    win32functions.SetForegroundWindow(ctrl)198    SendKeys.SendKeys(199        keys.encode('mbcs'),200        pause, with_spaces,201        with_tabs,202        with_newlines,203        turn_off_numlock)204    win32functions.AttachThreadInput(205        win32functions.GetCurrentThreadId(), ctrl.ProcessID, 0)206#====================================================================207def combobox_select(ctrl, item):208    """Select the ComboBox item209    item can be either a 0 based index of the item to select210    or it can be the string that you want to select211    """212    verify_enabled(ctrl)213    # Make sure we have an index  so if passed in a214    # string then find which item it is215    if isinstance(item, (int, long)):216        index = item217    else:218        index = ctrl.Texts.index(item) -1219    # change the selected item220    ctrl.SendMessage(win32defines.CB_SETCURSEL, index, 0)221    # Notify the parent that we have changed222    ctrl.NotifyParent(win32defines.CBN_SELCHANGE)223    return ctrl224#====================================================================225def listbox_select(ctrl, item):226    """Select the ListBox item227    item can be either a 0 based index of the item to select228    or it can be the string that you want to select229    """230    verify_enabled(ctrl)231    # Make sure we have an index  so if passed in a232    # string then find which item it is233    if isinstance(item, (int, long)):234        index = item235    else:236        index = ctrl.Texts.index(item)237    # change the selected item238    ctrl.PostMessage(win32defines.LB_SETCURSEL, index, 0)239    # Notify the parent that we have changed240    ctrl.NotifyParent(win32defines.LBN_SELCHANGE)241    return ctrl242#====================================================================243def set_edit_text(ctrl, text, pos_start = 0, pos_end = -1):244    "Set the text of the edit control"245    verify_enabled(ctrl)246    set_edit_selection(ctrl, pos_start, pos_end)247    text = ctypes.c_wchar_p(unicode(text))248    ctrl.SendMessage(win32defines.EM_REPLACESEL, True, text)249#====================================================================250def set_edit_selection(ctrl, start = 0, end = -1):251    "Set the edit selection of the edit control"252    verify_enabled(ctrl)253    # if we have been asked to select a string254    if isinstance(start, basestring):255        string_to_select = start256        #257        start = ctrl.texts[1].index(string_to_select)258        end = start + len(string_to_select)259    ctrl.PostMessage(win32defines.EM_SETSEL, start, end)260#====================================================================261def select_tab_action(ctrl, tab):262    "Select the specified tab on teh tab control"263    verify_enabled(ctrl)264    if isinstance(tab, basestring):265        # find the string in the tab control266        bestText = findbestmatch.find_best_match(tab, ctrl.Texts, ctrl.Texts)267        tab = ctrl.Texts.index(bestText) - 1268    ctrl.SendMessage(win32defines.TCM_SETCURFOCUS, tab)269#====================================================================270def select_menuitem_action(ctrl, path, items = None):271    "Select the menuitem specifed in path"272    verify_enabled(ctrl)273    # if the menu items haven't been passed in then274    # get them from the window275    if not items:276        items = ctrl.MenuItems277    # get the text names from the menu items278    item_texts = [item['Text'] for item in items]279    # get the first part (and remainder)280    parts = path.split("->", 1)281    current_part = parts[0]282    # find the item that best matches the current part283    item = findbestmatch.find_best_match(current_part, item_texts, items)284    # if there are more parts - then get the next level285    if parts[1:]:286        select_menuitem_action(ctrl, "->".join(parts[1:]), item['MenuItems'])287    else:288        # unfortunately this is not always reliable :-(289        #if item['State'] & MF_DISABLED or item['State'] & MF_GRAYED:290        #	raise "TODO - replace with correct exception: " \291        #       "Menu item is not enabled"292        #ctrl.PostMessage(WM_MENURBUTTONUP, win32functions.GetMenu(ctrl))293        #ctrl.PostMessage(WM_COMMAND, 0, item['ID'])294        ctrl.NotifyMenuSelect(item['ID'])295    time.sleep(delay_after_menuselect)296#====================================================================297def write_debug_text(ctrl, text):298    "Write some debug text over the window"299    dc = win32functions.CreateDC(u"DISPLAY", None, None, None )300    if not dc:301        raise ctypes.WinError()302    rect = ctrl.Rectangle303    #ret = win32functions.TextOut(304    #    dc, rect.left, rect.top, unicode(text), len(text))305    ret = win32functions.DrawText(306        dc,307        unicode(text),308        len(text),309        ctypes.byref(rect),310        win32defines.DT_SINGLELINE)311    if not ret:312        raise ctypes.WinError()313#====================================================================314def draw_outline(315    ctrl,316    colour = 'green',317    thickness = 2,318    fill = win32defines.BS_NULL,319    rect = None):320    "Draw an outline around the window"321    colours = {322        "green" : 0x00ff00,323        "blue" : 0xff0000,324        "red" : 0x0000ff,325    }326    # if it's a known colour327    if colour in colours:328        colour = colours[colour]329    if not rect:330        rect = ctrl.Rectangle331    # create the pen(outline)332    hPen = win32functions.CreatePen(win32defines.PS_SOLID, thickness, colour)333    # create the brush (inside)334    brush = win32structures.LOGBRUSH()335    brush.lbStyle = fill336    brush.lbHatch = win32defines.HS_DIAGCROSS337    hBrush = win32functions.CreateBrushIndirect(ctypes.byref(brush))338    # get the Device Context339    dc = win32functions.CreateDC(u"DISPLAY", None, None, None )340    # push our objects into it341    win32functions.SelectObject(dc, hBrush)342    win32functions.SelectObject(dc, hPen)343    win32functions.Rectangle(dc, rect.left, rect.top, rect.right, rect.bottom)344    # Delete the brush and pen we created345    win32functions.DeleteObject(hBrush)346    win32functions.DeleteObject(hPen)347    # delete the Display context that we created348    win32functions.DeleteDC(dc)349def Dialog_RunTests(ctrl, tests_to_run = None):350    "Run the tests on dialog"351    # get all teh controls352    controls = [ctrl]353    controls.extend(ctrl.Children)354    return tests.run_tests(controls, tests_to_run)355# TODO: Make the RemoteMemoryBlock stuff more automatic!356def listview_checkbox_uncheck_action(ctrl, item):357    "Uncheck the ListView item"358    lvitem = win32structures.LVITEMW()359    lvitem.mask = win32defines.LVIF_STATE360    lvitem.state = 0x1000361    lvitem.stateMask = win32defines.LVIS_STATEIMAGEMASK362    from controls.common_controls import RemoteMemoryBlock363    remoteMem = RemoteMemoryBlock(ctrl)364    remoteMem.Write(lvitem)365    ctrl.SendMessage(win32defines.LVM_SETITEMSTATE, item, remoteMem.Address())366    del remoteMem367def listview_checkbox_check_action(ctrl, item):368    "Check the ListView item"369    lvitem = win32structures.LVITEMW()370    lvitem.mask = win32defines.LVIF_STATE371    lvitem.state = 0x2000372    lvitem.stateMask = win32defines.LVIS_STATEIMAGEMASK373    from controls.common_controls import RemoteMemoryBlock374    remoteMem = RemoteMemoryBlock(ctrl)375    remoteMem.Write(lvitem)376    ctrl.SendMessage(win32defines.LVM_SETITEMSTATE, item, remoteMem.Address())377    del remoteMem378def listview_isitemchecked_action(ctrl, item):379    "Return whether the ListView item is checked or not"380    state = ctrl.SendMessage(381        win32defines.LVM_GETITEMSTATE, item, win32defines.LVIS_STATEIMAGEMASK)382    return state & 0x2000383def listbox_setfocusitem_action(ctrl, item):384    "Set the ListBox focus to the item at index"385    # if it is a multiple selection dialog386    if ctrl.HasStyle(win32defines.LBS_EXTENDEDSEL) or \387        ctrl.HasStyle(win32defines.LBS_MULTIPLESEL):388        ctrl.SendMessage(win32defines.LB_SETCARETINDEX, item)389    else:390        ctrl.SendMessage(win32defines.LB_SETCURSEL, item)391def listbox_getcurrentselection_action(ctrl):392    "Retrun the index of current selection in a ListBox"393    return ctrl.SendMessage(win32defines.LB_GETCARETINDEX)394######ANYWIN395#CaptureBitmap396#GetAppId397#GetCaption398#GetChildren399#GetClass400#GetHandle401#GetNativeClass402#GetParent403#IsEnabled404#IsVisible405#TypeKeys406#Click407#DoubleClick408#GetHelpText409#ClearTrap410#Exists411#GenerateDecl412#GetArrayProperty413#GetBitmapCRC414#GetContents415#GetEverything416#GetIDGetIndex417#GetInputLanguage418#GetManyProperties419#GetName420#GetProperty421#GetPropertyList422#GetRect423#GetTag424#InvokeMethods425#IsActive426#IsArrayProperty427#IsDefined428#IsOfClass429#InvokeJava430#MenuSelect431#MoveMouse432#MultiClick433#PopupSelect434#PressKeys435#PressMouse436#ReleaseKeys437#ReleaseMouse438#ScrollIntoView439#SetArrayProperty440#SetInputLanguage441#SetProperty442#SetTrap443#VerifyActive444#VerifyBitmap445#VerifyEnabled446#VerifyEverything447#VerifyText448#VerifyProperties449#WaitBitmap450#Properties451#452#bActive453#AppId454#sCaption455#lwChildren456#Class457#bEnabled458#bExists459#sID460#iIndex461#sName462#wParent463#Rect464#hWnd465#WndTag466#467#468######CONTROL469#GetPriorStatic470#HasFocus471#SetFocus472#VerifyFocus473#474######BUTTON475#Click476#IsIndeterminate477#IsPressed478#479#480#####CHECKBOX481#Check482#GetState483#IsChecked484#SetState485#Toggle486#Uncheck487#VerifyValue488#489#bChecked490#bValue491#492#493#####MENUITEM494#Check495#IsChecked496#Pick497#Uncheck498#VerifyChecked499#500#bChecked501#502#503#####COMBOBOX504#ClearText505#FindItem506#GetContents507#GetItemCount508#GetItemText509#GetSelIndex510#GetSelText511#GetText512#Select513#SetText514#VerifyContents515#VerifyText516#VerifyValue517#518#lsContents519#iItemCount520#iValue521#sValue522#523#####LISTBOX524#BeginDrag525#DoubleSelect526#EndDrag527#ExtendSelect528#FindItem529#GetContents530#GetItemCount531#GetItemText532#GetMultiSelIndex533#GetMultiSelText534#GetSelIndex535#GetSelText536#IsExtendSel537#IsMultiSel538#MultiSelect539#MultiUnselect540#Select541#SelectList542#SelectRange543#VerifyContents544#VerifyValue545#546#lsContents547#bIsExtend548#bIsMulti549#iItemCount550#iValue551#liValue552#lsValue553#sValue554#555#556#####EDIT557#ClearText558#GetContents559#GetFontName560#GetFontSize561#GetMultiSelText562#GetMultiText563#GetPosition564#GetSelRange565#GetSelText566#GetText567#IsBold568#IsItalic569#IsMultiText570#IsRichText571#IsUnderline572#SetMultiText573#SetPosition574#SetSelRange575#SetText576#VerifyPosition577#VerifySelRange578#VerifySelText579#VerifyValue580#581#bIsMulti582#lsValue583#sValue584#585#586#####LISTVIEW587#BeginDrag588#DoubleSelect589#EndDrag590#ExposeItem591#ExtendSelect592#FindItem593#GetColumnCount594#GetColumnName595#GetContents596#GetItemImageState597#GetItemImageIndex598#GetItemRect599#GetItemText600#GetMultiSelIndex601#GetMultiSelText602#GetSelIndex603#GetSelText604#GetView605#method606#(ListView)607#IsExtendSel608#IsMultiSel609#MultiSelect610#MultiUnselect611#PressItem612#ReleaseItem613#Select614#SelectList615#SelectRange616#VerifyContents617#VerifyValue618#619#620#####TREEVIEW621#BeginDrag622#Collapse623#DoubleSelect624#EndDrag625#Expand626#ExposeItem627#ExtendSelect628#FindItem629#GetContents630#GetItemCount631#GetItemImageIndex632#GetItemImageState633#GetItemLevel634#GetItemRect635#GetItemText636#GetSelIndex637#GetSelText638#GetSubItemCount639#GetSubItems640#IsItemEditable641#IsItemExpandable642#IsItemExpanded643#MultiSelect644#MultiUnselect645#PressItem646#ReleaseItem647#Select648#SelectList649#VerifyContents650#VerifyValue651#652#####Static653#GetText654#VerifyValue655_standard_action_funcs = dict(656    Click = click_action,657    RightClick = rightclick_action,658    DoubleClick = doubleclick_action,659    TypeKeys = typekeys_action,660    SetText = settext_action,661    ReleaseMouse = release_mouse_action,662    MoveMouse = move_mouse_action,663    PressMouse = press_mouse_action,664    DebugMessage = write_debug_text,665    DrawOutline = draw_outline,666    )667_class_specific_actions = {668    'ComboBox' : dict(669        Select = combobox_select,670    ),671    'ListBox' : dict(672        Select = listbox_select,673        FocusItem = listbox_getcurrentselection_action,674        SetFocus = listbox_setfocusitem_action,675    ),676    'ListView' : dict(677        Check = listview_checkbox_check_action,678        UnCheck = listview_checkbox_uncheck_action,679        IsChecked = listview_isitemchecked_action,680    ),681    'Edit' : dict(682        Select = set_edit_selection,683        SetText = set_edit_text,684    ),685    'CheckBox' : dict(686        Check = check_button_action,687        UnCheck = uncheck_button_action,688    ),689    'Button' : dict(690        Check = check_button_action,691        UnCheck = uncheck_button_action,692    ),693    "TabControl" : dict(694        Select = select_tab_action,695    ),696    "Dialog" : dict(697        RunTests = Dialog_RunTests,698    ),699}700#=========================================================================701# TODO: Move actions into the appropriate controls module702def add_actions(to_obj):703    "Add the appropriate actions to the control"704    # for each of the standard actions705    for action_name in _standard_action_funcs:706        # add it to the control class707        setattr (708            to_obj.__class__, action_name, _standard_action_funcs[action_name])709    # check if there are actions specific to this type of control710    if _class_specific_actions.has_key(to_obj.FriendlyClassName):711        # apply these actions to the class712        actions = _class_specific_actions[to_obj.FriendlyClassName]713        for action_name, action_func in actions.items():714            setattr (to_obj.__class__, action_name, action_func)715    # If the object has menu items allow MenuSelect716    if to_obj.MenuItems:717        to_obj.__class__.MenuSelect =  select_menuitem_action...ivi_apps.py
Source:ivi_apps.py  
...114               + ', '.join(picture_list)115        self.refreshScreenshot()116        ret = True117        for p in picture_list:118            if not self.waitBitmap(p):119                print "++ %s not found" % p120                ret = False121        return ret122    def findPid(self, process_name):123        cmd = "pgrep -f '%s'" % process_name124        (r, so, se ) = self.shellSOE(cmd)125        pids = []126        if r == 0:127            pids = [string.atoi(n) for n in filter(lambda l: len(l)>0, so.split("\n"))]128        return r, pids129    def verifyAllProcess(self, process_list):130        print "++ check process: " + ', '.join(process_list)131        ret = True132        for p in process_list:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
