Best Python code snippet using pyatom_python
ldtpd.py-old
Source:ldtpd.py-old
1#!/usr/bin/python2import ldtp3import sys4import SimpleXMLRPCServer5import getopt6import logging7import re8import inspect9import wnck10import gobject11import gtk12import time13import fnmatch14import os15import subprocess16import pdb17from fnmatch import translate18logger = logging.getLogger("xmlrpcserver.ldtp")19logger.setLevel(logging.INFO)20class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):21 """Overides the default SimpleXMLRPCRequestHander to support logging. Logs22 client IP and the XML request and response.23 """24 def do_POST(self):25 clientIP, port = self.client_address26 # Log client IP and Port27 logger.info('Client IP: %s - Port: %s' % (clientIP, port))28 try:29 # get arguments30 data = self.rfile.read(int(self.headers["content-length"]))31 # Log client request32 logger.info('Client request: \n%s\n' % data)33 response = self.server._marshaled_dispatch(data, getattr(self, '_dispatch', None))34 # Log server response35 logger.info('Server response: \n%s\n' % response)36 except:37 # This should only happen if the module is buggy38 # internal error, report as HTTP server error39 self.send_response(500)40 self.end_headers()41 else:42 # got a valid XML RPC response43 self.send_response(200)44 self.send_header("Content-type", "text/xml")45 self.send_header("Content-length", str(len(response)))46 self.end_headers()47 self.wfile.write(response)48 # shut down the connection49 self.wfile.flush()50 self.connection.shutdown(1)51#figure out which methods are in LDTPv2 and only use those52#f = open("/root/bin/ldtp_api2.clj", "r")53#ldtp2commands = []54#line = f.readline().strip()55#while line:56# command = line.split("\"")[1]57# ldtp2commands.append(command)58# line = f.readline()59#ldtp2commands.sort()60#f.close61ldtp3commands = ['activatetext',62 'activatewindow',63 'appendtext',64 'appundertest',65 'check',66 'checkrow',67 'click',68 'closewindow',69 'comboselect',70 'comboselectindex',71 'copytext',72 'cuttext',73 'decrease',74 'delaycmdexec',75 'deletetext',76 'deregisterevent',77 'deregisterkbevent',78 'doesmenuitemexist',79 'doesrowexist',80 'doubleclick',81 'doubleclickrow',82 'enterstring',83 'expandtablecell',84 'generatekeyevent',85 'generatemouseevent',86 'getaccesskey',87 'getallitem',88 'getallstates',89 'getapplist',90 'getcellsize',91 'getcellvalue',92 'getcharcount',93 'getchild',94 'getcombovalue',95 'getcpustat',96 'getcursorposition',97 'getlastlog',98 'getmax',99 'getmaxvalue',100 'getmemorystat',101 'getmin',102 'getminincrement',103 'getminvalue',104 'getobjectinfo',105 'getobjectlist',106 'getobjectnameatcoords',107 'getobjectproperty',108 'getobjectsize',109 'getpanelchildcount',110 'getrowcount',111 'getslidervalue',112 'getstatusbartext',113 'gettabcount',114 'gettablerowindex',115 'gettabname',116 'gettextvalue',117 'getvalue',118 'getwindowlist',119 'getwindowsize',120 'grabfocus',121 'guiexist',122 'guitimeout',123 'handletablecell',124 'hasstate',125 'hidelist',126 'imagecapture',127 'increase',128 'inserttext',129 'invokemenu',130 'isalive',131 'ischildindexselected',132 'ischildselected',133 'istextstateenabled',134 'keypress',135 'keyrelease',136 'launchapp',137 'listsubmenus',138 'maximizewindow',139 'menucheck',140 'menuitemenabled',141 'menuuncheck',142 'minimizewindow',143 'mouseleftclick',144 'mousemove',145 'mouserightclick',146 'objectexist',147 'objtimeout',148 'onedown',149 'oneleft',150 'oneright',151 'oneup',152 'onwindowcreate',153 'pastetext',154 'poll_events',155 'press',156 'registerevent',157 'registerkbevent',158 'remap',159 'removecallback',160 'rightclick',161 'scrolldown',162 'scrollleft',163 'scrollright',164 'scrollup',165 'selectall',166 'selecteditemcount',167 'selectindex',168 'selectitem',169 'selectlastrow',170 'selectmenuitem',171 'selectpanel',172 'selectpanelindex',173 'selectpanelname',174 'selectrow',175 'selectrowindex',176 'selectrowpartialmatch',177 'selecttab',178 'selecttabindex',179 'setcellvalue',180 'setcursorposition',181 'setlocale',182 'setmax',183 'setmin',184 'settextvalue',185 'setvalue',186 'showlist',187 'simulatemousemove',188 'singleclickrow',189 'startprocessmonitor',190 'stateenabled',191 'stopprocessmonitor',192 'uncheck',193 'uncheckrow',194 'unhandletablecell',195 'unmaximizewindow',196 'unminimizewindow',197 'unselectall',198 'unselectindex',199 'unselectitem',200 'verifycheck',201 'verifydropdown',202 'verifyhidelist',203 'verifymenucheck',204 'verifymenuuncheck',205 'verifypartialmatch',206 'verifypartialtablecell',207 'verifypushbutton',208 'verifyscrollbarhorizontal',209 'verifyscrollbarvertical',210 'verifyselect',211 'verifysettext',212 'verifysetvalue',213 'verifyshowlist',214 'verifysliderhorizontal',215 'verifyslidervertical',216 'verifytablecell',217 'verifytabname',218 'verifytoggled',219 'verifyuncheck',220 'wait',221 'waittillguiexist',222 'waittillguinotexist',223 'windowuptime']224_ldtp_methods = filter(lambda fn: inspect.isfunction(getattr(ldtp,fn)), dir(ldtp))225_supported_methods = filter(lambda x: x in ldtp3commands, _ldtp_methods)226#_unsupported_methods = filter(lambda x: x not in ldtp3commands, _ldtp_methods)227_additional_methods = ['closewindow', 'maximizewindow']228for item in _additional_methods: _supported_methods.append(item)229_supported_methods.sort()230#create a class with all ldtp methods as attributes231class AllMethods:232 #states enum from /usr/include/at-spi-1.0/cspi/spi-statetypes.h as part of at-spi-devel233 states = ['INVALID',234 'ACTIVE',235 'ARMED',236 'BUSY',237 'CHECKED',238 'COLLAPSED',239 'DEFUNCT',240 'EDITABLE',241 'ENABLED',242 'EXPANDABLE',243 'EXPANDED',244 'FOCUSABLE',245 'FOCUSED',246 'HORIZONTAL',247 'ICONIFIED',248 'MODAL',249 'MULTI_LINE',250 'MULTISELECTABLE',251 'OPAQUE',252 'PRESSED',253 'RESIZABLE',254 'SELECTABLE',255 'SELECTED',256 'SENSITIVE',257 'SHOWING',258 'SINGLE_LINE',259 'STALE',260 'TRANSIENT',261 'VERTICAL',262 'VISIBLE',263 'MANAGES_DESCENDANTS',264 'INDETERMINATE',265 'TRUNCATED',266 'REQUIRED',267 'INVALID_ENTRY',268 'SUPPORTS_AUTOCOMPLETION',269 'SELECTABLE_TEXT',270 'IS_DEFAULT',271 'VISITED',272 'LAST_DEFINED']273 def _translate_state(self, value):274 if value in self.states:275 return self.states.index(value)276 else:277 return value278 def _translate_number(self, num):279 if num in xrange(len(self.states)):280 return self.states[num]281 else:282 return num283 def _getobjectproperty(self, window, object):284 getobjectlist = getattr(ldtp,"getobjectlist")285 objects = getobjectlist(window)286 for item in objects:287 if re.search(object,str(item)):288 return str(item)289 return object290 def _matches(self, pattern, item):291 return bool(re.match(fnmatch.translate(pattern), item, re.M | re.U | re.L))292 #this replicates the origional algorithm293 def _gettablerowindex(self, window, table, target):294 numrows = ldtp.getrowcount(window, table)295 numcols = len(ldtp.getobjectproperty(window, table, 'children').split())296 for i in range(0,numrows):297 for j in range(0,numcols):298 try:299 value = ldtp.getcellvalue(window, table, i, j)300 if self._matches(target,value):301 ldtp.selectrowindex(window, table, i)302 return i303 except:304 continue305 raise Exception("Item not found in table!")306 #this only searches the first column and is much quicker.307 def _quickgettablerowindex(self, window, table, target):308 numrows = ldtp.getrowcount(window, table)309 for i in range(0,numrows):310 try:311 value = ldtp.getcellvalue(window, table, i, 0)312 if self._matches(target,value):313 ldtp.selectrowindex(window, table, i)314 return i315 except:316 continue317 raise Exception("Item not found in table!")318 def _window_search(self, match, term):319 if re.search(fnmatch.translate(term),320 match,321 re.U | re.M | re.L) \322 or re.search(fnmatch.translate(re.sub("(^frm|^dlg)", "", term)),323 re.sub(" *(\t*)|(\n*)", "", match),324 re.U | re.M | re.L):325 return True326 else:327 return False328 def _closewindow(self, window_name):329 screen = wnck.screen_get_default()330 while gtk.events_pending():331 gtk.main_iteration()332 windows = screen.get_windows()333 success = 0334 for w in windows:335 current_window = w.get_name()336 if self._window_search(current_window,window_name):337 w.close(int(time.time()))338 success = 1339 break340 gobject.idle_add(gtk.main_quit)341 gtk.main()342 return success343 def _maximizewindow(self, window_name):344 screen = wnck.screen_get_default()345 while gtk.events_pending():346 gtk.main_iteration()347 windows = screen.get_windows()348 success = 0349 for w in windows:350 current_window = w.get_name()351 if self._window_search(current_window,window_name):352 w.maximize()353 success = 1354 break355 gobject.idle_add(gtk.main_quit)356 gtk.main()357 return success358 def _launchapp(self, cmd, args=[], delay=0, env=1, lang="C"):359 os.environ['NO_GAIL']='0'360 os.environ['NO_AT_BRIDGE']='0'361 if env:362 os.environ['GTK_MODULES']='gail:atk-bridge'363 os.environ['GNOME_ACCESSIBILITY']='1'364 if lang:365 os.environ['LANG']=lang366 try:367 process=subprocess.Popen([cmd]+args, close_fds=True)368 # Let us wait so that the application launches369 try:370 time.sleep(int(delay))371 except ValueError:372 time.sleep(5)373 except Exception, e:374 raise Exception(str(e))375 os.environ['NO_GAIL']='1'376 os.environ['NO_AT_BRIDGE']='1'377 return process.pid378 #def _gettextvalue(self, window_name, object_name, startPosition=None,379 # endPosition=None):380 # TODO: implement this with getlabel if object is label381 def _dispatch(self, method, params):382 if method in _supported_methods:383 paramslist = list(params)384 if method == "hasstate":385 paramslist[2]=self._translate_state(paramslist[2])386 params = tuple(paramslist)387 elif method == "closewindow":388 return self._closewindow(paramslist[0])389 elif method == "maximizewindow":390 return self._maximizewindow(paramslist[0])391 elif method == "getobjectproperty":392 paramslist[1] = self._getobjectproperty(paramslist[0],paramslist[1])393 params = tuple(paramslist)394 elif method == "launchapp":395 return self._launchapp(*paramslist)396 function = getattr(ldtp,method)397 retval = function(*params)398 if (method == "gettextvalue") and not (isinstance(retval, str) or399 isinstance(retval, unicode)):400 retval = ""401 elif (retval == -1) and (method == "gettablerowindex"):402 paramslist = list(params)403 #use quick method for now404 retval = self._quickgettablerowindex(paramslist[0],405 paramslist[1],406 paramslist[2])407 elif method == "getallstates":408 retval = [self._translate_number(state) for state in retval]409 if retval == None:410 retval = 0411 return retval412 pass413for name in _supported_methods:414 if not item in _additional_methods:415 setattr(AllMethods, name, getattr(ldtp, name))416def usage():417 print "Usage:"418 print "[-p, --port=] Port to listen on"419 print "[-l --logfile=] file to write logging to"420 print "[-h] This help message"421def start_server(port,logfile):422 if logfile:423 hdlr = logging.FileHandler(logfile)424 formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")425 hdlr.setFormatter(formatter)426 logger.addHandler(hdlr)427 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("",int(port)),428 LoggingSimpleXMLRPCRequestHandler)429 else:430 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('',int(port)),431 logRequests=True)432 server.register_introspection_functions()433 server.register_instance(AllMethods())434 try:435 print("Listening on port %s" % port)436 server.serve_forever()437 except KeyboardInterrupt:438 print 'Exiting'439def main():440 try:441 opts, args = getopt.getopt(sys.argv[1:], "hpl:v", ["help", "port=", "logfile="])442 print(opts)443 except getopt.GetoptError, err:444 # print help information and exit:445 print str(err) # will print something like "option -a not recognized"446 usage()447 sys.exit(2)448 port = 4118 #default port449 logfile = None450 for o, a in opts:451 if o in ("-p", "--port"):452 port = a453 elif o in ("-l", "--logfile"):454 logfile = a455 elif o in ("-h", "--help"):456 usage()457 sys.exit()458 else:459 assert False, "unhandled option"460 start_server(port,logfile)461if __name__ == "__main__":...
text.py
Source:text.py
1#!/usr/bin/env python2#3# Linux Desktop Testing Project http://www.gnomebangalore.org/ldtp4#5# Description:6# This set of test scripts will test the LDTP framework for correct7# functioning of its APIs. This is a Regression Suite.8#9# Author:10# Prashanth Mohan <prashmohan@gmail.com>11#12#13# This test script is free software; you can redistribute it and/or14# modify it under the terms of the GNU Library General Public15# License as published by the Free Software Foundation; either16# version 2 of the License, or (at your option) any later version.17#18# This library is distributed in the hope that it will be useful,19# but WITHOUT ANY WARRANTY; without even the implied warranty of20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU21# Library General Public License for more details.22#23# You should have received a copy of the GNU Library General Public24# License along with this library; if not, write to the25# Free Software Foundation, Inc., 59 Temple Place - Suite 330,26# Boston, MA 02111-1307, USA.27#28from regression import *29import random, os30try:31 check_open('gedit')32except:33 raise34data_object = LdtpDataFileParser (datafilename)35text = data_object.gettagvalue ('text')36insert_text = data_object.gettagvalue ('inserttext')37insert_pos = data_object.gettagvalue ('insertpos')38cut_start = data_object.gettagvalue ('cutstart')39cut_stop = data_object.gettagvalue ('cutstop')40delete_start = data_object.gettagvalue ('deletestart')41delete_stop = data_object.gettagvalue ('deletestop')42if text == []:43 text = 'This is the default text for the LDTP Regression Suite'44else:45 text = text[0]46if insert_text == []:47 insert_text = text48else:49 insert_text = insert_text[0]50if insert_pos == []:51 insert_pos = 052else:53 insert_pos = int(insert_pos[0])54if cut_start == []:55 cut_start = 056else:57 cut_start = int(cut_start[0])58 59try:60 check_open('gedit')61except:62 raise63log ('settextvalue','teststart')64try:65 if settextvalue ('*gedit','txt0',text) == 0:66 raise LdtpExecutionError (str (traceback.format_exc ()))67 if verifysettext ('*gedit','txt0',text) == 0:68 raise LdtpExecutionError (str (traceback.format_exc ()))69except:70 testfail ('settextvalue')71 raise LdtpExecutionError (str (traceback.format_exc ()))72testpass ('settextvalue')73log ('gettextvalue','teststart')74try:75 present_text = gettextvalue ('*gedit','txt0')76 if present_text != text:77 raise LdtpExecutionError (str (traceback.format_exc ()))78except:79 testfail ('gettextvalue')80 raise LdtpExecutionError (str (traceback.format_exc ()))81testpass ('gettextvalue')82log ('verifysettext','teststart')83try:84 present_text = gettextvalue ('*gedit','txt0')85 if verifysettext ('*gedit','txt0',present_text) != 1:86 log ('Text present but says not present','cause')87 raise LdtpExecutionError (str (traceback.format_exc ()))88 if verifysettext ('*gedit','txt0',present_text+'123') != 0:89 log ('Text not present but says present','cause')90 raise LdtpExecutionError (str (traceback.format_exc ()))91 if verifysettext ('*gedit','txt0',present_text[:-1]) != 0:92 log ('Text not present but says present','cause')93 raise LdtpExecutionError (str (traceback.format_exc ()))94 # http://bugzilla.gnome.org/show_bug.cgi?id=351227 95# if verifysettext ('*gedit','txt0','') != 0 and present_text != '':96# log ('Text not present but says present','cause')97# raise LdtpExecutionError (str (traceback.format_exc ()))98except:99 testfail ('verifysettext')100 raise LdtpExecutionError (str (traceback.format_exc ()))101testpass('verifysettext')102 103log ('stateenabled','teststart')104try:105 if istextstateenabled ('*gedit','txt0') == 0:106 log ('State Disabled','info')107 raise LdtpExecutionError (str (traceback.format_exc ()))108 else:109 log ('State Enabled','info')110except:111 testfail ('stateenbled')112 raise LdtpExecutionError (str (traceback.format_exc ()))113testpass ('stateenbled')114log ('appendtext','teststart')115try:116 present_text = gettextvalue ('*gedit','txt0')117 if appendtext ('*gedit','txt0',text) == 0:118 raise LdtpExecutionError (str (traceback.format_exc ()))119 if gettextvalue ('*gedit','txt0') != present_text+text:120 raise LdtpExecutionError (str (traceback.format_exc ()))121except:122 testfail ('appendtext')123 raise LdtpExecutionError (str (traceback.format_exc ()))124testpass ('appendtext')125log ('getcharactercount','teststart')126try:127 present_text = gettextvalue ('*gedit','txt0')128 if getcharcount ('*gedit','txt0') != len(present_text):129 raise LdtpExecutionError (str (traceback.format_exc ()))130except:131 testfail ('getcharactercount')132 raise LdtpExecutionError (str (traceback.format_exc ()))133testpass ('getcharactercount')134log ('getcursorposition','teststart')135try:136 if getcharcount ('*gedit','txt0') != getcursorposition ('*gedit','txt0'):137 raise LdtpExecutionError (str (traceback.format_exc ()))138except:139 testfail ('getcursorposition')140 raise LdtpExecutionError (str (traceback.format_exc ()))141testpass ('getcursorposition')142if len (present_text) < insert_pos:143 new_text = present_text+insert_text144else:145 new_text = present_text[:insert_pos]+insert_text+present_text[insert_pos:]146log ('inserttext','teststart')147try:148 if inserttext ('*gedit', 'txt0', insert_pos, insert_text) == 0:149 raise LdtpExecutionError (str (traceback.format_exc ()))150 if gettextvalue ('*gedit','txt0') != new_text:151 raise LdtpExecutionError (str (traceback.format_exc ()))152except:153 testfail ('inserttext')154 raise LdtpExecutionError (str (traceback.format_exc ()))155testpass ('inserttext')156 157log ('cuttext','teststart')158try:159 if cut_stop == []:160 cut_stop = getcharactercount ('*gedit','txt0')161 else:162 cut_stop = int(cut_stop[0])163 present_text = gettextvalue ('*gedit','txt0')164 length = getcharcount ('*gedit','txt0')165 if cut_stop < cut_start or cut_start > length or cut_stop > length:166 log ('Input not proper','cause')167 raise LdtpExecutionError (str (traceback.format_exc ()))168 new_text = present_text[:cut_start]+present_text[cut_stop:]169 cut_text = present_text[cut_start:cut_stop]170 if cuttext ('*gedit','txt0',cut_start, cut_stop) == 0:171 raise LdtpExecutionError (str (traceback.format_exc ()))172 if gettextvalue ('*gedit','txt0') != new_text:173 raise LdtpExecutionError (str (traceback.format_exc ()))174except:175 testfail ('cuttext')176 raise LdtpExecutionError (str (traceback.format_exc ()))177testpass ('cuttext')178log ('pastetext','teststart')179try:180 present_text = gettextvalue ('*gedit','txt0')181 new_text = present_text[:cut_start]+cut_text+present_text[cut_start:]182 if pastetext ('*gedit','txt0',cut_start) == 0:183 raise LdtpExecutionError (str (traceback.format_exc ()))184 if gettextvalue ('*gedit','txt0') != new_text:185 raise LdtpExecutionError (str (traceback.format_exc ()))186except:187 testfail ('pastetext')188 raise LdtpExecutionError (str (traceback.format_exc ()))189testpass ('pastetext')190log ('copytext','teststart')191try:192 length = getcharcount ('*gedit','txt0')193 if cut_stop < cut_start or cut_start > length:194 log ('Input not proper','cause')195 raise LdtpExecutionError (str (traceback.format_exc ()))196 if cut_stop > length:197 cut_stop = length-1198 199 present_text = gettextvalue ('*gedit','txt0')200 copy_text = present_text[cut_start:cut_stop]201 202 if copytext ('*gedit','txt0',cut_start, cut_stop) == 0:203 raise LdtpExecutionError (str (traceback.format_exc ()))204 if gettextvalue ('*gedit','txt0') != present_text:205 raise LdtpExecutionError (str (traceback.format_exc ()))206except:207 testfail ('copytext')208 raise LdtpExecutionError (str (traceback.format_exc ()))209testpass ('copytext')210log ('pastetext','teststart')211try:212 present_text = gettextvalue ('*gedit','txt0')213 new_text = present_text[:cut_start]+copy_text+present_text[cut_start:]214 if pastetext ('*gedit','txt0',cut_start) == 0:215 raise LdtpExecutionError (str (traceback.format_exc ()))216 if gettextvalue ('*gedit','txt0') != new_text:217 raise LdtpExecutionError (str (traceback.format_exc ()))218except:219 testfail ('pastetext')220 raise LdtpExecutionError (str (traceback.format_exc ()))221testpass ('pastetext')222log ('deletetext','teststart')223try:224 length = getcharcount ('*gedit','txt0')225 present_text = gettextvalue ('*gedit','txt0')226 if delete_start == []:227 delete_start = 0228 else:229 delete_start = int (delete_start[0])230 if delete_stop == []:231 if delete_start+1 <= length:232 log ('Not enough text on screen','cause')233 raise LdtpExecutionError (str (traceback.format_exc ()))234 delete_stop = delete_start + 1235 else:236 delete_stop = int (delete_stop[0])237 238 if delete_stop < delete_start or delete_start > length or delete_stop > length:239 log ('Input not proper','cause')240 raise LdtpExecutionError (str (traceback.format_exc ()))241 242 new_text = present_text[:delete_start]+present_text[delete_stop:]243 if deletetext ('*gedit','txt0',delete_start, delete_stop) == 0:244 raise LdtpExecutionError (str (traceback.format_exc ()))245 if gettextvalue ('*gedit','txt0') != new_text:246 raise LdtpExecutionError (str (traceback.format_exc ()))247except:248 testfail ('deletetext')249 raise LdtpExecutionError (str (traceback.format_exc ()))250testpass ('deletetext')251log ('cursorposition','teststart') #tests for getcursorposition and setcursorposition252try:253 length = getcharcount ('*gedit','txt0')254 setcursorposition ('*gedit','txt0',0)255 if getcursorposition ('*gedit','txt0') != 0:256 log ('Unable to Set Cursor position to 0','cause')257 raise LdtpExecutionError (str (traceback.format_exc ()))258 if length == 0:259 val = 0260 else:261 val = length - 1262 setcursorposition ('*gedit','txt0',val)263 if getcursorposition ('*gedit','txt0') != val:264 log ('Unable to Set Cursor position to end of sentence','cause')265 raise LdtpExecutionError (str (traceback.format_exc ()))266 val = length/2267 setcursorposition ('*gedit','txt0',val)268 if getcursorposition ('*gedit','txt0') != val:269 log ('Unable to Set Cursor position to middle of sentence','cause')270 raise LdtpExecutionError (str (traceback.format_exc ()))271except:272 testfail ('cursorposition')273 raise LdtpExecutionError (str (traceback.format_exc ()))274testpass ('cursorposition')275log ('verifypartialmatch','teststart')276try:277 present_text = gettextvalue ('*gedit','txt0')278 length = len (present_text)279 middle = random.randint (0,length-1)280 if verifypartialmatch ('*gedit','txt0',281 present_text[middle:random.randint (middle, length-1)]) != 1:282 log ('Does not do correct matching','cause')283 raise LdtpExecutionError (str (traceback.format_exc ()))284 if verifypartialmatch ('*gedit','txt0',text+'123') != 0:285 log ('Does not check for overflow','cause')286 raise LdtpExecutionError (str (traceback.format_exc ()))287 if verifypartialmatch ('*gedit','txt0','123'+text) != 0:288 log ('Does not check for overflow','cause')289 raise LdtpExecutionError (str (traceback.format_exc ()))290except:291 testfail ('cursorposition')292 raise LdtpExecutionError (str (traceback.format_exc ()))293testpass ('cursorposition')294log ('selecttextbyname','teststart')295try:296 selecttextbyname ('*gedit','txt0')297 ## FIXME :: Find a way to verify this!!!298 setcursorposition ('*gedit','txt0',0)299except:300 testfail ('selecttextbyname')301 raise LdtpExecutionError (str (traceback.format_exc ()))302testpass ('selecttextbyname')303 304## FIXME :: Add test for text properties -- gettextproperty and comparetextproperty305# try:306# close_gedit()307# except:...
ldtpd.py
Source:ldtpd.py
1#!/usr/bin/python2import ldtp3import sys4import SimpleXMLRPCServer5import getopt6import logging7import re8import inspect9import wnck10import gobject11import gtk12import time13import fnmatch14from fnmatch import translate15logger = logging.getLogger("xmlrpcserver.ldtp")16logger.setLevel(logging.INFO)17class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):18 """Overides the default SimpleXMLRPCRequestHander to support logging. Logs19 client IP and the XML request and response.20 """21 def do_POST(self):22 clientIP, port = self.client_address23 # Log client IP and Port24 logger.info('Client IP: %s - Port: %s' % (clientIP, port))25 try:26 # get arguments27 data = self.rfile.read(int(self.headers["content-length"]))28 # Log client request29 logger.info('Client request: \n%s\n' % data)30 response = self.server._marshaled_dispatch(data, getattr(self, '_dispatch', None))31 # Log server response32 logger.info('Server response: \n%s\n' % response)33 except:34 # This should only happen if the module is buggy35 # internal error, report as HTTP server error36 self.send_response(500)37 self.end_headers()38 else:39 # got a valid XML RPC response40 self.send_response(200)41 self.send_header("Content-type", "text/xml")42 self.send_header("Content-length", str(len(response)))43 self.end_headers()44 self.wfile.write(response)45 # shut down the connection46 self.wfile.flush()47 self.connection.shutdown(1)48#figure out which methods are in LDTPv2 and only use those49#f = open("/root/bin/ldtp_api2.clj", "r")50#ldtp2commands = []51#line = f.readline().strip()52#while line:53# command = line.split("\"")[1]54# ldtp2commands.append(command)55# line = f.readline()56#ldtp2commands.sort()57#f.close58ldtp2commands = ['activatetext', 'activatewindow', 'appendtext', 'check', 'checkrow', 'click', 'closewindow', 'comboselect', 'comboselectindex', 'copytext', 'cuttext', 'decrease', 'deletetext', 'doesmenuitemexist', 'doesrowexist', 'doubleclick', 'doubleclickrow', 'enterstring', 'expandtablecell', 'generatekeyevent', 'generatemouseevent', 'getallitem', 'getallstates', 'getapplist', 'getcellvalue', 'getcharcount', 'getchild', 'getcursorposition', 'getmax', 'getmaxvalue', 'getminincrement', 'getminvalue', 'getobjectinfo', 'getobjectlist', 'getobjectproperty', 'getobjectsize', 'getrowcount', 'getslidervalue', 'getstatusbartext', 'gettabcount', 'gettablerowindex', 'gettabname', 'gettextvalue', 'getvalue', 'getwindowlist', 'getwindowsize', 'grabfocus', 'guiexist', 'hasstate', 'hidelist', 'imagecapture', 'increase', 'invokemenu', 'isalive', 'ischildindexselected', 'ischildselected', 'istextstateenabled', 'keypress', 'keyrelease', 'launchapp', 'listsubmenus', 'maximizewindow', 'menucheck', 'menuitemenabled', 'menuuncheck', 'minimizewindow', 'mouseleftclick', 'mousemove', 'mouserightclick', 'objectexist', 'onedown', 'oneleft', 'oneright', 'oneup', 'onwindowcreate', 'pastetext', 'poll_events', 'press', 'registerevent', 'remap', 'removecallback', 'removeevent', 'scrolldown', 'scrollleft', 'scrollright', 'scrollup', 'selectall', 'selecteditemcount', 'selectindex', 'selectitem', 'selectlastrow', 'selectmenuitem', 'selectrow', 'selectrowindex', 'selectrowpartialmatch', 'selecttab', 'selecttabindex', 'setcellvalue', 'setcursorposition', 'setlocale', 'setmax', 'setmin', 'settextvalue', 'setvalue', 'showlist', 'simulatemousemove', 'singleclickrow', 'stateenabled', 'uncheck', 'uncheckrow', 'unmaximizewindow', 'unminimizewindow', 'unselectall', 'unselectindex', 'unselectitem', 'verifycheck', 'verifydropdown', 'verifyhidelist', 'verifymenucheck', 'verifymenuuncheck', 'verifypartialmatch', 'verifypartialtablecell', 'verifyscrollbarhorizontal', 'verifyscrollbarvertical', 'verifyselect', 'verifysettext', 'verifysetvalue', 'verifyshowlist', 'verifysliderhorizontal', 'verifyslidervertical', 'verifytablecell', 'verifytabname', 'verifytoggled', 'verifyuncheck', 'wait', 'waittillguiexist', 'waittillguinotexist', 'windowuptime']59_ldtp_methods = filter(lambda fn: inspect.isfunction(getattr(ldtp,fn)), dir(ldtp))60_supported_methods = filter(lambda x: x in ldtp2commands, _ldtp_methods)61_additional_methods = ['closewindow', 'maximizewindow']62for item in _additional_methods: _supported_methods.append(item)63_supported_methods.sort()64#create a class with all ldtp methods as attributes65class AllMethods:66 #states class variable67 #states enum from /usr/include/at-spi-1.0/cspi/spi-statetypes.h as part of at-spi-devel68 #hint: state = $line_number - 8069 states = ['INVALID',70 'ACTIVE',71 'ARMED',72 'BUSY',73 'CHECKED',74 'COLLAPSED',75 'DEFUNCT',76 'EDITABLE',77 'ENABLED',78 'EXPANDABLE',79 'EXPANDED',80 'FOCUSABLE',81 'FOCUSED',82 'HORIZONTAL',83 'ICONIFIED',84 'MODAL',85 'MULTI_LINE',86 'MULTISELECTABLE',87 'OPAQUE',88 'PRESSED',89 'RESIZABLE',90 'SELECTABLE',91 'SELECTED',92 'SENSITIVE',93 'SHOWING',94 'SINGLE_LINE',95 'STALE',96 'TRANSIENT',97 'VERTICAL',98 'VISIBLE',99 'MANAGES_DESCENDANTS',100 'INDETERMINATE',101 'TRUNCATED',102 'REQUIRED',103 'INVALID_ENTRY',104 'SUPPORTS_AUTOCOMPLETION',105 'SELECTABLE_TEXT',106 'IS_DEFAULT',107 'VISITED',108 'LAST_DEFINED']109 def _translate_state(self,value):110 if value in self.states:111 return self.states.index(value)112 else:113 return value114 def _translate_number(self,num):115 if num in xrange(len(self.states)):116 return self.states[num]117 else:118 return num119 def _getobjectproperty(self, window, object):120 getobjectlist = getattr(ldtp,"getobjectlist")121 objects = getobjectlist(window)122 for item in objects:123 if re.search(object,str(item)):124 return str(item)125 return object126 def _matches(self, pattern, item):127 return bool(re.match(fnmatch.translate(pattern), item, re.M | re.U | re.L))128 #this replicates the origional algorithm129 def _gettablerowindex(self, window, table, target):130 numrows = ldtp.getrowcount(window, table)131 numcols = len(ldtp.getobjectproperty(window, table, 'children').split())132 for i in range(0,numrows):133 for j in range(0,numcols):134 try:135 value = ldtp.getcellvalue(window, table, i, j)136 if self._matches(target,value):137 ldtp.selectrowindex(window, table, i)138 return i139 except:140 continue141 raise Exception("Item not found in table!")142 #this only searches the first column and is much quicker.143 def _quickgettablerowindex(self, window, table, target):144 numrows = ldtp.getrowcount(window, table)145 for i in range(0,numrows):146 try:147 value = ldtp.getcellvalue(window, table, i, 0)148 if self._matches(target,value):149 ldtp.selectrowindex(window, table, i)150 return i151 except:152 continue153 raise Exception("Item not found in table!")154 def _window_search(self,match,term):155 if re.search(fnmatch.translate(term),156 match,157 re.U | re.M | re.L) \158 or re.search(fnmatch.translate(re.sub("(^frm|^dlg)", "", term)),159 re.sub(" *(\t*)|(\n*)", "", match),160 re.U | re.M | re.L):161 return True162 else:163 return False164 def _closewindow(self,window_name):165 screen = wnck.screen_get_default()166 while gtk.events_pending():167 gtk.main_iteration()168 windows = screen.get_windows()169 success = 0170 for w in windows:171 current_window = w.get_name()172 if self._window_search(current_window,window_name):173 w.close(int(time.time()))174 success = 1175 break176 gobject.idle_add(gtk.main_quit)177 gtk.main()178 return success179 def _maximizewindow(self,window_name):180 screen = wnck.screen_get_default()181 while gtk.events_pending():182 gtk.main_iteration()183 windows = screen.get_windows()184 success = 0185 for w in windows:186 current_window = w.get_name()187 if self._window_search(current_window,window_name):188 w.maximize()189 success = 1190 break191 gobject.idle_add(gtk.main_quit)192 gtk.main()193 return success194 def _dispatch(self,method,params):195 if method in _supported_methods:196 paramslist = list(params)197 if method == "hasstate":198 paramslist[2]=self._translate_state(paramslist[2])199 params = tuple(paramslist)200 elif method == "closewindow":201 return self._closewindow(paramslist[0])202 elif method == "maximizewindow":203 return self._maximizewindow(paramslist[0])204 elif method == "getobjectproperty":205 paramslist[1] = self._getobjectproperty(paramslist[0],paramslist[1])206 params = tuple(paramslist)207 function = getattr(ldtp,method)208 retval = function(*params)209 if (method == "gettextvalue") and not (isinstance(retval, str) or210 isinstance(retval, unicode)):211 retval = ""212 elif (retval == -1) and (method == "gettablerowindex"):213 paramslist = list(params)214 #use quick method for now215 retval = self._quickgettablerowindex(paramslist[0],216 paramslist[1],217 paramslist[2])218 elif method == "getallstates":219 retval = [self._translate_number(state) for state in retval]220 if retval == None:221 retval = 0222 return retval223 pass224for name in _supported_methods:225 if not item in _additional_methods:226 setattr(AllMethods, name, getattr(ldtp, name))227def usage():228 print "Usage:"229 print "[-p, --port=] Port to listen on"230 print "[-l --logfile=] file to write logging to"231 print "[-h] This help message"232def start_server(port,logfile):233 if logfile:234 hdlr = logging.FileHandler(logfile)235 formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")236 hdlr.setFormatter(formatter)237 logger.addHandler(hdlr)238 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("",int(port)),239 LoggingSimpleXMLRPCRequestHandler)240 else:241 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('',int(port)),242 logRequests=True)243 server.register_introspection_functions()244 server.register_instance(AllMethods())245 try:246 print("Listening on port %s" % port)247 server.serve_forever()248 except KeyboardInterrupt:249 print 'Exiting'250def main():251 try:252 opts, args = getopt.getopt(sys.argv[1:], "hpl:v", ["help", "port=", "logfile="])253 print(opts)254 except getopt.GetoptError, err:255 # print help information and exit:256 print str(err) # will print something like "option -a not recognized"257 usage()258 sys.exit(2)259 port = 4118 #default port260 logfile = None261 for o, a in opts:262 if o in ("-p", "--port"):263 port = a264 elif o in ("-l", "--logfile"):265 logfile = a266 elif o in ("-h", "--help"):267 usage()268 sys.exit()269 else:270 assert False, "unhandled option"271 start_server(port,logfile)272if __name__ == "__main__":...
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!!