How to use appundertest method in pyatom

Best Python code snippet using pyatom_python

ldtpd.py-old

Source:ldtpd.py-old Github

copy

Full Screen

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__":...

Full Screen

Full Screen

imageProcessing.py

Source:imageProcessing.py Github

copy

Full Screen

1import re2import uuid3from pytesseract import pytesseract as pt4from PIL import Image5import aut6import logging7import pyautogui8import re9import uuid10import os11logging.basicConfig(filename='ImageProcessing.log', 12level=logging.DEBUG, 13format='%(asctime)s | %(name)s | %(levelname)s | %(message)s')14pt.tesseract_cmd = "C:\\program files\\Tesseract-OCR\\tesseract.exe"15"""16Init -> (optional) Image 17findElement -> Returns the co-ordinates of the given text and instances18findElements -> Returns list of occurences of a given string19"""20class ImageProcessing():21 def __init__(self,windowName=None,imagePath=None,isDebug=True) -> None:22 self.appUnderTest=None23 self.isDebug = isDebug24 if(windowName is not None):25 self.appUnderTest = aut.AUT(windowName)26 self.imagePath = self.appUnderTest.imagePath27 logging.debug("Image Path is set to : "+self.imagePath)28 elif(imagePath is not None):29 self.imagePath = imagePath30 else:31 raise Exception("Either AUT or imagePath is mandatory ")32 def _debugInformation(self):33 if(self.isDebug):34 detectionData = pt.image_to_string(Image.open(self.imagePath))35 id = str(uuid.uuid1())36 logging.info("page Information: "+id+'.txt')37 fp = open(os.path.join('RuntimeInformation',id+'.txt'),'w+')38 fp.write(detectionData)39 fp.close()40 def _getBoxes(self):41 return pt.image_to_boxes(Image.open(self.imagePath), output_type=pt.Output.DICT)42 43 def _getCoOrdinates(self, boxes , object_name , instance):44 overall_string= ''.join(boxes['char'])45 overall_string.replace(' ','')46 current_indx=047 48 while instance>1:49 indx = str.find(overall_string , object_name, current_indx)50 if(indx==-1):51 raise "Object Not Detected"52 else:53 instance=instance-154 current_indx=indx+155 if(instance==1):56 indx = str.find(overall_string,object_name, current_indx)57 if(indx==-1):58 raise Exception("Object Not Detected")59 start=(boxes["left"][indx],boxes["bottom"][indx])60 end = (boxes["right"][indx+object_name.__len__()-1], boxes["top"][indx+object_name.__len__()-1] )61 return start,end 62 63 def _getCoOrdinatesRegx(self , boxes , object_nameRegx , instance):64 overall_string= ''.join(boxes['char'])65 overall_string.replace(' ','')66 rx = re.compile(object_nameRegx)67 result = rx.findall(overall_string)68 if(result==[]):69 raise Exception("Object Not Detected") 70 else:71 return self._getCoOrdinates(boxes , result[instance-1], 1)72 def _getCenterCoOrdinates(self,start,end):73 image = Image.open(self.imagePath)74 width, height = image.size75 s1=(start[0],height-start[1])76 e1=(end[0],height-end[1])77 xDelta=e1[0]-s1[0] 78 yDelta=s1[1]-e1[1]79 xMid=int(xDelta/2)80 yMid=int(yDelta/2)81 return s1[0]+xMid , s1[1]-yMid82 def findElement(self,name,instance,offset=None,isRegex = False):83 logging.info("Finding Object: {0} , instance: {1} , offset: {2} , isRegex: {3}".format(name , str(instance), str(offset), str(isRegex)))84 if(self.appUnderTest is not None):85 self.appUnderTest = aut.AUT(self.appUnderTest.windowName)86 self.imagePath = self.appUnderTest.imagePath87 self._debugInformation()88 bx = self._getBoxes()89 if(isRegex):90 X,Y=self._getCoOrdinatesRegx(bx,name,instance)91 else:92 X,Y=self._getCoOrdinates(bx,name,instance)93 o=self._getCenterCoOrdinates( X , Y )94 if(self.appUnderTest is not None):95 boundingRect = self.appUnderTest.boundingRectangle96 adjusted = (o[0]+boundingRect[0], o[1]+boundingRect[1])97 o=adjusted98 if(offset is not None):99 adju2 = (o[0]+offset[0], o[1],offset[1])100 o=adju2101 return o 102 103 def scrollToFindElement(self, name , instance , offset = None , isRegex = False , scrollDirection = "up", scrollStep=10, limit = 100):104 tryLimit=1105 while True:106 try:107 element = self.findElement(name , instance , offset = offset , isRegex = isRegex)108 return element109 except:110 if(tryLimit>limit):111 logging.error("Scroll limit exceeded and element {0} is not found ".format(name))112 raise Exception("Scroll limit exceeded and element {0} is not found ".format(name))113 logging.info("element not found, scrolling step: "+str(scrollStep) +" in direction "+scrollDirection + " iteration: "+ str(tryLimit))114 if(scrollDirection.lower() == 'up'):115 pyautogui.scroll(scrollStep)116 elif(scrollDirection.lower()=='down'):117 pyautogui.scroll(scrollStep*-1)118 elif(scrollDirection.lower()=='right'):119 pyautogui.hscroll(-1*scrollStep)120 else:121 pyautogui.pyautogui.hscroll(scrollStep)122 tryLimit = tryLimit+1123 124 125 def findElementWithFallback(self, primary_name , primary_instance, seconday_name , secondary_insance , offset = None, isPrimaryRegx = False, isSecondaryRegx=False):126 pass127 def closeApplication(self):128 autBoundaries= self.appUnderTest.boundingRectangle129 pyautogui.doubleClick(autBoundaries[0]+2,autBoundaries[1]+2, interval=1)130 def __del__(self):...

Full Screen

Full Screen

steps.py

Source:steps.py Github

copy

Full Screen

1'''2Created on Oct 7, 20103@author: camerondawson4'''5from features.models import CompanyModel, ProductModel6from features.tcm_request_helper import verify_status, add_params7from lettuce import step, world8from lettuce.terrain import before, after9import cgi10import httplib11import mock_scenario_data12def save_db_state():13 '''14 This will dump the database to a file. That file will then be used at the beginning15 of each scenario to reset to a known state of the database16 '''17 conn = httplib.HTTPConnection(world.hostname, world.port, timeout=120)18 conn.request("GET", world.path_savedb)19 conn.getresponse()20def restore_db_state():21 '''22 This will re-create the database from the dump created in save_db_state(). This will23 be run at the beginning end of each scenario to reset the database to the known state.24 '''25 conn = httplib.HTTPConnection(world.hostname, world.port, timeout=120)26 conn.request("GET", world.path_restoredb)27 response = conn.getresponse()28 verify_status(200, response, "Restored the database")29def setup_connection():30 world.conn = httplib.HTTPConnection(world.hostname, world.port)31@before.all32def setup_before_all():33 if (world.save_db):34 save_db_state()35 # usually, the test will replace the countryId based on looking it up36 world.seed_company = {"name": "Massive Dynamic",37 "phone": "555-867-5309",38 "address": "650 Castro St.",39 "city": "Mountain View",40 "zip": "94043",41 "url": "http//www.fringepedia.net",42 "country name": "United States"43 }44 # usually the test setup will replace the companyId with the one looked up based on creating45 # the seed company above.46 world.seed_product = {"company name": "Massive Dynamic",47 "name": "Cortexiphan",48 "description": "I can see your universe from here"49 }50 # keep track of the api(uri) calls made51 world.apis_called = {}52@before.each_scenario53def setup_before_scenario(scenario):54 # make sure the auth cookie is cleared55 world.auth_cookie = None56 # @todo: DON'T NEED?????57 # dict of names of objects used in scenarios to remember from one step to the next keyed by type such as "user"58 world.names = {}59 # the id of the last referenced item of this tcm_type60 world.latest_of_type = {}61 if (world.restore_db):62 restore_db_state()63 if (world.use_mock):64 scenarioData = mock_scenario_data.get_scenario_data(scenario.name).strip()65 headers = {'content-Type':'text/plain',66 "Content-Length": "%d" % len(scenarioData) }67 setup_connection()68 world.conn.request("POST",69 add_params(world.path_mockdata,70 {"scenario" : scenario.name}),71 "", headers)72 world.conn.send(scenarioData)73 world.conn.getresponse()74@before.each_step75def setup_step_connection(step):76 setup_connection()77 world.current_sentence = step.sentence78@after.all79def teardown_after_all(total):80 if (world.restore_db_after_all):81 restore_db_state()82 write_apis_called_file()83def write_apis_called_file():84 f = open(world.apis_called_file, 'w')85 world.apis_called86 tablerows = ""87 # we can't sort a dict, so we need to sort the keys, then fetch the value for it88 keys = world.apis_called.keys()89 keys.sort()90 for key in keys:91 # each value is a set of the methods called (to keep them unique) so we join them by spaces92 tablerow = "<tr><td>%s</td><td>%s</td></tr>" % (key, ' '.join(world.apis_called[key]))93 tablerows += tablerow94 output = '''95 <html xmlns="http://www.w3.org/1999/xhtml">96 <head>97 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />98 <title>%(appUnderTest)s Results</title>99 </head>100 <body>101 <h1>%(appUnderTest)s APIs Called</h1>102 <table border=1>103 <tr><th>API</th><th>Methods</th></tr>104 %(tablerows)s105 </table>106 </body>107 </html>108 ''' % {'tablerows': tablerows,109 'appUnderTest': cgi.escape(world.applicationUnderTest)110 }111 f.write(output)112@step(u'create the seed company and product with these names')113def create_seed_company_and_product(step):114 names = step.hashes[0]115 # create the seed company116 company = world.seed_company.copy()117 # use the value passed in, in case it's different than the default118 company["name"] = names["company name"]119 world.names["company"] = company["name"]120 #TODO: not able to search for the country name yet121 company["countryId"] = 123122 if company.has_key("country name"):123 del company["country name"]124 companyModel = CompanyModel()125 companyModel.create(company)126 # create the seed product127 # persist the last one we make. Sometimes we will only make one.128 product = world.seed_product.copy()129 product["name"] = names["product name"]130 world.names["product"] = product["name"]131 # get the company id from the passed company name132 company_id = CompanyModel().get_resid(product["company name"])[0]133 product["companyId"] = company_id134 if product.has_key("company name"):135 del product["company name"]136 productModel = ProductModel()...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pyatom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful