Best Python code snippet using pyatom_python
ldtpd.py
Source:ldtpd.py
1#!/usr/bin/python2import ldtp3import sys4import SimpleXMLRPCServer5import getopt6import logging7import re8import inspect9import wnck10import gobject11import gtk12import time13import fnmatch14import os15import subprocess16import pdb17import dogtail.tree18from fnmatch import translate19logger = logging.getLogger("xmlrpcserver.ldtp")20logger.setLevel(logging.INFO)21class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):22 """Overides the default SimpleXMLRPCRequestHander to support logging. Logs23 client IP and the XML request and response.24 """25 def do_POST(self):26 clientIP, port = self.client_address27 # Log client IP and Port28 logger.info('Client IP: %s - Port: %s' % (clientIP, port))29 try:30 # get arguments31 data = self.rfile.read(int(self.headers["content-length"]))32 # Log client request33 logger.info('Client request: \n%s\n' % data)34 response = self.server._marshaled_dispatch(data, getattr(self, '_dispatch', None))35 # Log server response36 logger.info('Server response: \n%s\n' % response)37 except:38 # This should only happen if the module is buggy39 # internal error, report as HTTP server error40 self.send_response(500)41 self.end_headers()42 else:43 # got a valid XML RPC response44 self.send_response(200)45 self.send_header("Content-type", "text/xml")46 self.send_header("Content-length", str(len(response)))47 self.end_headers()48 self.wfile.write(response)49 # shut down the connection50 self.wfile.flush()51 self.connection.shutdown(1)52#figure out which methods are in LDTPv2 and only use those53#f = open("/root/bin/ldtp_api2.clj", "r")54#ldtp2commands = []55#line = f.readline().strip()56#while line:57# command = line.split("\"")[1]58# ldtp2commands.append(command)59# line = f.readline()60#ldtp2commands.sort()61#f.close62ldtp3commands = ['activatetext',63 'activatewindow',64 'appendtext',65 'appundertest',66 'check',67 'checkrow',68 'click',69 'closewindow',70 'comboselect',71 'comboselectindex',72 'copytext',73 'cuttext',74 'decrease',75 'delaycmdexec',76 'deletetext',77 'deregisterevent',78 'deregisterkbevent',79 'doesmenuitemexist',80 'doesrowexist',81 'doubleclick',82 'doubleclickrow',83 'enterstring',84 'expandtablecell',85 'generatekeyevent',86 'generatemouseevent',87 'getaccesskey',88 'getallitem',89 'getallstates',90 'getapplist',91 'getcellsize',92 'getcellvalue',93 'getcharcount',94 'getchild',95 'getcombovalue',96 'getcpustat',97 'getcursorposition',98 'getlastlog',99 'getmax',100 'getmaxvalue',101 'getmemorystat',102 'getmin',103 'getminincrement',104 'getminvalue',105 'getobjectinfo',106 'getobjectlist',107 'getobjectnameatcoords',108 'getobjectproperty',109 'getobjectsize',110 'getpanelchildcount',111 'getrowcount',112 'getslidervalue',113 'getstatusbartext',114 'gettabcount',115 'gettablerowindex',116 'gettabname',117 'gettextvalue',118 'getvalue',119 'getwindowlist',120 'getwindowsize',121 'grabfocus',122 'guiexist',123 'guitimeout',124 'handletablecell',125 'hasstate',126 'hidelist',127 'imagecapture',128 'increase',129 'inserttext',130 'invokemenu',131 'isalive',132 'ischildindexselected',133 'ischildselected',134 'istextstateenabled',135 'keypress',136 'keyrelease',137 'launchapp',138 'listsubmenus',139 'maximizewindow',140 'menucheck',141 'menuitemenabled',142 'menuuncheck',143 'minimizewindow',144 'mouseleftclick',145 'mousemove',146 'mouserightclick',147 'objectexist',148 'objtimeout',149 'onedown',150 'oneleft',151 'oneright',152 'oneup',153 'onwindowcreate',154 'pastetext',155 'poll_events',156 'press',157 'registerevent',158 'registerkbevent',159 'remap',160 'removecallback',161 'rightclick',162 'scrolldown',163 'scrollleft',164 'scrollright',165 'scrollup',166 'selectall',167 'selecteditemcount',168 'selectindex',169 'selectitem',170 'selectlastrow',171 'selectmenuitem',172 'selectpanel',173 'selectpanelindex',174 'selectpanelname',175 'selectrow',176 'selectrowindex',177 'selectrowpartialmatch',178 'selecttab',179 'selecttabindex',180 'setcellvalue',181 'setcursorposition',182 'setlocale',183 'setmax',184 'setmin',185 'settextvalue',186 'setvalue',187 'showlist',188 'simulatemousemove',189 'singleclickrow',190 'startprocessmonitor',191 'stateenabled',192 'stopprocessmonitor',193 'uncheck',194 'uncheckrow',195 'unhandletablecell',196 'unmaximizewindow',197 'unminimizewindow',198 'unselectall',199 'unselectindex',200 'unselectitem',201 'verifycheck',202 'verifydropdown',203 'verifyhidelist',204 'verifymenucheck',205 'verifymenuuncheck',206 'verifypartialmatch',207 'verifypartialtablecell',208 'verifypushbutton',209 'verifyscrollbarhorizontal',210 'verifyscrollbarvertical',211 'verifyselect',212 'verifysettext',213 'verifysetvalue',214 'verifyshowlist',215 'verifysliderhorizontal',216 'verifyslidervertical',217 'verifytablecell',218 'verifytabname',219 'verifytoggled',220 'verifyuncheck',221 'wait',222 'waittillguiexist',223 'waittillguinotexist',224 'windowuptime']225_ldtp_methods = filter(lambda fn: inspect.isfunction(getattr(ldtp,fn)), dir(ldtp))226_supported_methods = filter(lambda x: x in ldtp3commands, _ldtp_methods)227#_unsupported_methods = filter(lambda x: x not in ldtp3commands, _ldtp_methods)228_additional_methods = ['closewindow', 'maximizewindow', 'getallitem']229for item in _additional_methods: _supported_methods.append(item)230_supported_methods.sort()231#create a class with all ldtp methods as attributes232class AllMethods:233 #states enum from /usr/include/at-spi-1.0/cspi/spi-statetypes.h as part of at-spi-devel234 states = ['INVALID',235 'ACTIVE',236 'ARMED',237 'BUSY',238 'CHECKED',239 'COLLAPSED',240 'DEFUNCT',241 'EDITABLE',242 'ENABLED',243 'EXPANDABLE',244 'EXPANDED',245 'FOCUSABLE',246 'FOCUSED',247 'HORIZONTAL',248 'ICONIFIED',249 'MODAL',250 'MULTI_LINE',251 'MULTISELECTABLE',252 'OPAQUE',253 'PRESSED',254 'RESIZABLE',255 'SELECTABLE',256 'SELECTED',257 'SENSITIVE',258 'SHOWING',259 'SINGLE_LINE',260 'STALE',261 'TRANSIENT',262 'VERTICAL',263 'VISIBLE',264 'MANAGES_DESCENDANTS',265 'INDETERMINATE',266 'TRUNCATED',267 'REQUIRED',268 'INVALID_ENTRY',269 'SUPPORTS_AUTOCOMPLETION',270 'SELECTABLE_TEXT',271 'IS_DEFAULT',272 'VISITED',273 'LAST_DEFINED']274 def _translate_state(self, value):275 if value in self.states:276 return self.states.index(value)277 else:278 return value279 def _translate_number(self, num):280 if num in xrange(len(self.states)):281 return self.states[num]282 else:283 return num284 def _getobjectproperty(self, window, object):285 getobjectlist = getattr(ldtp,"getobjectlist")286 objects = getobjectlist(window)287 for item in objects:288 if re.search(object,str(item)):289 return str(item)290 return object291 def _matches(self, pattern, item):292 return bool(re.match(fnmatch.translate(pattern), item, re.M | re.U | re.L))293 #this replicates the origional algorithm294 def _gettablerowindex(self, window, table, target):295 numrows = ldtp.getrowcount(window, table)296 numcols = len(ldtp.getobjectproperty(window, table, 'children').split())297 for i in range(0,numrows):298 for j in range(0,numcols):299 try:300 value = ldtp.getcellvalue(window, table, i, j)301 if self._matches(target,value):302 ldtp.selectrowindex(window, table, i)303 return i304 except:305 continue306 raise Exception("Item not found in table!")307 #this only searches the first column and is much quicker.308 def _quickgettablerowindex(self, window, table, target):309 numrows = ldtp.getrowcount(window, table)310 for i in range(0,numrows):311 try:312 value = ldtp.getcellvalue(window, table, i, 0)313 if self._matches(target,value):314 ldtp.selectrowindex(window, table, i)315 return i316 except:317 continue318 raise Exception("Item not found in table!")319 def _window_search(self, match, term):320 if re.search(fnmatch.translate(term),321 match,322 re.U | re.M | re.L) \323 or re.search(fnmatch.translate(re.sub("(^frm|^dlg)", "", term)),324 re.sub(" *(\t*)|(\n*)", "", match),325 re.U | re.M | re.L):326 return True327 else:328 return False329 def _closewindow(self, window_name):330 screen = wnck.screen_get_default()331 while gtk.events_pending():332 gtk.main_iteration()333 windows = screen.get_windows()334 success = 0335 for w in windows:336 current_window = w.get_name()337 if self._window_search(current_window,window_name):338 w.close(int(time.time()))339 success = 1340 break341 gobject.idle_add(gtk.main_quit)342 gtk.main()343 return success344 def _maximizewindow(self, window_name):345 screen = wnck.screen_get_default()346 while gtk.events_pending():347 gtk.main_iteration()348 windows = screen.get_windows()349 success = 0350 for w in windows:351 current_window = w.get_name()352 if self._window_search(current_window,window_name):353 w.maximize()354 success = 1355 break356 gobject.idle_add(gtk.main_quit)357 gtk.main()358 return success359 def _launchapp(self, cmd, args=[], delay=0, env=1, lang="C"):360 os.environ['NO_GAIL']='0'361 os.environ['NO_AT_BRIDGE']='0'362 if env:363 os.environ['GTK_MODULES']='gail:atk-bridge'364 os.environ['GNOME_ACCESSIBILITY']='1'365 if lang:366 os.environ['LANG']=lang367 try:368 process=subprocess.Popen([cmd]+args, close_fds=True)369 # Let us wait so that the application launches370 try:371 time.sleep(int(delay))372 except ValueError:373 time.sleep(5)374 except Exception, e:375 raise Exception(str(e))376 os.environ['NO_GAIL']='1'377 os.environ['NO_AT_BRIDGE']='1'378 return process.pid379 def _gettextvalue(self, window_name, object_name, startPosition=None,380 endPosition=None):381 def findFirst(node, search_string):382 try: children = node.children383 except: return None384 for child in children:385 if self._matches(search_string, child.name):386 return child387 else:388 child = findFirst(child,search_string)389 if child:390 return child391 retval = ""392 if ldtp.getobjectproperty(window_name, object_name, "class") == "label":393 f = dogtail.tree.root.application('subscription-manager-gui')394 w = f.childNamed(window_name)395 o = findFirst(w, object_name)396 if o:397 retval = o.text398 else:399 raise Exception("Cannot find object: %s in tree."%(object_name))400 else:401 retval = ldtp.gettextvalue(window_name, object_name, startPosition, endPosition)402 if not ((isinstance(retval, str) or isinstance(retval, unicode))):403 retval = ""404 return retval405 def _getallitem(self, window_name, object_name):406 f = dogtail.tree.root.application("subscription-manager-gui")407 w = f.childNamed(window_name)408 o = w.childNamed(object_name)409 nodes = o.children[0].children410 return [n.name for n in nodes]411 def _dispatch(self, method, params):412 if method in _supported_methods:413 paramslist = list(params)414 if method == "closewindow":415 return self._closewindow(paramslist[0])416 elif method == "getallitem":417 return self._getallitem(*paramslist)418 elif method == "getobjectproperty":419 paramslist[1] = self._getobjectproperty(paramslist[0],paramslist[1])420 params = tuple(paramslist)421 elif method == "gettextvalue":422 return self._gettextvalue(*paramslist)423 elif method == "hasstate":424 paramslist[2]=self._translate_state(paramslist[2])425 params = tuple(paramslist)426 elif method == "launchapp":427 return self._launchapp(*paramslist)428 elif method == "maximizewindow":429 return self._maximizewindow(paramslist[0])430 function = getattr(ldtp,method)431 retval = function(*params)432 if (retval == -1) and (method == "gettablerowindex"):433 paramslist = list(params)434 #use quick method for now435 retval = self._quickgettablerowindex(paramslist[0],436 paramslist[1],437 paramslist[2])438 elif method == "getallstates":439 retval = [self._translate_number(state) for state in retval]440 if retval == None:441 retval = 0442 return retval443 else:444 raise Exception("Function '%s' is not supported."%(method))445 pass446for name in _supported_methods:447 if not item in _additional_methods:448 setattr(AllMethods, name, getattr(ldtp, name))449def usage():450 print "Usage:"451 print "[-p, --port=] Port to listen on"452 print "[-l --logfile=] file to write logging to"453 print "[-h] This help message"454def start_server(port,logfile):455 if logfile:456 hdlr = logging.FileHandler(logfile)457 formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")458 hdlr.setFormatter(formatter)459 logger.addHandler(hdlr)460 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("",int(port)),461 LoggingSimpleXMLRPCRequestHandler)462 else:463 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('',int(port)),464 logRequests=True)465 server.register_introspection_functions()466 server.register_instance(AllMethods())467 try:468 print("Listening on port %s" % port)469 server.serve_forever()470 except KeyboardInterrupt:471 print 'Exiting'472def main():473 try:474 opts, args = getopt.getopt(sys.argv[1:], "hpl:v", ["help", "port=", "logfile="])475 print(opts)476 except getopt.GetoptError, err:477 # print help information and exit:478 print str(err) # will print something like "option -a not recognized"479 usage()480 sys.exit(2)481 port = 4118 #default port482 logfile = None483 for o, a in opts:484 if o in ("-p", "--port"):485 port = a486 elif o in ("-l", "--logfile"):487 logfile = a488 elif o in ("-h", "--help"):489 usage()490 sys.exit()491 else:492 assert False, "unhandled option"493 start_server(port,logfile)494if __name__ == "__main__":...
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__":...
run.py
Source:run.py
1from pysys.constants import *2from pysys.basetest import BaseTest3from pysys.process.monitor import *4from pysys.utils.pycompat import openfile5if PROJECT.testRootDir+'/internal/utilities/extensions' not in sys.path:6 sys.path.append(PROJECT.testRootDir+'/internal/utilities/extensions') # only do this in internal testcases; normally sys.path should not be changed from within a PySys test7from pysysinternalhelpers import *8class PySysTest(BaseTest):9 def execute(self):10 p = self.startProcess(command=sys.executable,11 arguments = [self.input+'/spinner.py'],12 stdout = "%s/test.out" % self.output,13 stderr = "%s/test.err" % self.output,14 state=BACKGROUND)15 16 childtest = runPySys(self, 'pysys', ['run', '-o', self.output+'/myoutdir', '-X', 'pidToMonitor=%d'%p.pid], 17 state=BACKGROUND, workingDir=self.input+'/nestedtests')18 # should be a no-op, just check it doesn't throw19 ProcessMonitorTextFileHandler.setDefaults(ProcessMonitorTextFileHandler.DEFAULT_COLUMNS)20 pm = self.startProcessMonitor(p, interval=0.1, file='monitor-default.tsv')21 pm2 = self.startProcessMonitor(p, interval=0.1, file=self.output+'/monitor-numproc.tsv', numProcessors='10')22 # test all supported stats, and also use of stream rather than filename23 filehandle = openfile(self.output+'/monitor-all.csv', 'w', encoding='utf-8')24 self.addCleanupFunction(lambda: filehandle.close())25 pm_all = self.startProcessMonitor(p, interval=0.1,handlers=[26 ProcessMonitorTextFileHandler(file=filehandle, columns=[27 ProcessMonitorKey.DATE_TIME,28 ProcessMonitorKey.SAMPLE,29 ProcessMonitorKey.CPU_CORE_UTILIZATION,30 ProcessMonitorKey.CPU_TOTAL_UTILIZATION,31 ProcessMonitorKey.MEMORY_RESIDENT_KB,32 ProcessMonitorKey.MEMORY_VIRTUAL_KB,33 ], delimiter=',')34 ])35 pidmonitor = self.startProcessMonitor(p.pid, interval=0.1, file=self.output+'/monitor-pid.tsv')36 assert pm.running(), 'monitor is still running'37 self.waitForGrep('monitor-default.tsv', expr='.', condition='>=5', ignores=['#.*'])38 self.waitForGrep('monitor-numproc.tsv', expr='.', condition='>=5', ignores=['#.*'])39 self.waitForGrep('monitor-pid.tsv', expr='.', condition='>=5', ignores=['#.*'])40 self.waitForGrep('monitor-all.csv', expr='.', condition='>=5', ignores=['#.*'])41 assert pm.running(), 'monitor is still running'42 assert pidmonitor.running(), 'pid monitor is still running'43 self.stopProcessMonitor(pidmonitor)44 self.waitProcess(childtest, timeout=60)45 self.assertTrue(childtest.exitStatus==0, assertMessage='nested pysys test passed')46 self.stopProcessMonitor(pm)47 pm.stop() # should silently do nothing48 self.stopProcessMonitor(pm) # should silently do nothing49 assert p.exitStatus == None, 'spinner process terminated unexpectedly'50 p.stop()51 self.wait(1) # keep process monitor running after it to check it doesn't cause an error52 self.stopProcessMonitor(pm2)53 54 55 def validate(self):56 self.logFileContents('monitor-default.tsv')57 self.logFileContents('monitor-numproc.tsv')58 self.logFileContents('monitor-all.csv')59 self.logFileContents('myoutdir/NestedTest/monitor-legacy.tsv')60 with open(self.output+'/myoutdir/NestedTest/monitor-legacy.tsv') as f:61 header = f.readline()62 f.readline() # ignore first line of results63 line = f.readline().strip() 64 # ensure tab-delimited output has same number of items as header65 line = line.split('\t')66 self.log.info('Sample legacy log line: %s', line)67 self.assertThat('%d == 4', len(line)) 68 self.assertGrep('myoutdir/NestedTest/monitor-legacy.tsv', expr='#.*', contains=False) # no header line69 self.log.info('')70 71 with open(self.output+'/monitor-default.tsv') as f:72 header = f.readline()73 self.assertTrue(header.startswith('#')) 74 f.readline() # ignore first line of results75 line = f.readline().strip() 76 # ensure tab-delimited output has same number of items as header77 line = line.split('\t')78 self.log.info('Sample log line: %s', line)79 self.assertThat('%d == %d', len(line), len(header.split('\t'))) # same number of items in header line as normal lines80 for i in range(len(line)):81 if i > 0: # apart from the first column, every header should be a valid float or int82 try:83 float(line[i])84 except Exception:85 self.addOutcome(FAILED, 'monitor-default.tsv sample line [%d] is not a number: "%s"'%line[i])86 with open(self.output+'/monitor-all.csv') as f:87 header = f.readline()88 self.assertTrue(header.startswith('#')) 89 f.readline() # ignore first line of results90 line = f.readline().strip() 91 # ensure delimited output has same number of items as header92 self.assertGrep('monitor-all.csv', expr='\t', contains=False) # no tabs, since we use commas for this file93 line = line.split(',')94 self.log.info('Sample log line: %s', line)95 self.assertThat('%d == %d', len(line), len(header.split(','))) # same number of items in header line as normal lines96 for i in range(len(line)):97 if i > 0: # apart from the first column, every header should be a valid float or int98 try:99 float(line[i])100 except Exception:101 self.addOutcome(FAILED, 'monitor-all.csv sample line [%d] is not a number: "%s"'%(i, line[i]))102 self.assertGrep('monitor-all.csv', expr='.*[.]', contains=False) # no floats, currently we expect all our stats to be integral103 104 # check files have at least some valid (non -1 ) values105 self.assertGrep('monitor-default.tsv', expr='\t[0-9]+')106 self.assertGrep('monitor-pid.tsv', expr='\t[0-9]+')107 self.assertGrep('myoutdir/NestedTest/monitor-legacy.tsv', expr='\t[0-9]+')108 109 # should be nothing where we couldn't get the data110 self.assertGrep('myoutdir/NestedTest/monitor-legacy.tsv', expr='\t-1', contains=False)...
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!!