def do_start(self, str_arg): printLog(self.threadName+"[running command 'start %s']" % str_arg) try: self.md.startActivity(self.__validateString(str_arg)) except: self.resultFlag=False printLog(self.threadName+'[status=%s]' % self.resultFlag)
def do_check(self, str_arg): printLog(self.threadName+"[running command 'check %s']" % str_arg) arg=self.__validateString(str_arg) ret=arg.split(' ', 1) compID=None #check id, just check existing or not try: compID=By.id(ret[0]) #all our checked items, must be visible if not self.ed.visible(compID): self.resultFlag=False printLog(self.threadName+'%s is not visible.' % compID,logging.ERROR) return if len(ret)==2: #get element text, and compare it with the given text value text_on_screen=self.ed.getText(compID).strip() target=ret[1].strip() printLog(self.threadName+'[text on screen: %s]' % text_on_screen) #have GBK problem, need to solve, or text1 is always gbk in chinese machine if not text_on_screen==target.decode('utf-8'): self.resultFlag=False except java.lang.RuntimeException: self.resultFlag=False printLog(self.threadName+'Runtime Exception! %s not found.' % compID, logging.ERROR) except Exception, e: #gbk problem self.resultFlag=False printLog(self.threadName+'Exception in do_check: %s' % e.message, logging.ERROR)
def getLaunchTime(self, fname): ''' Jul 22, scan logcat log file and retrieve activity launch time data, save a list of (activity, launch time) vp ''' if not os.path.isfile(fname): return '' self.callShellCmd('./get_ALT.sh '+fname) ALTList=[] new_fname='logcat.csv' with open(new_fname, 'r') as fd: lines=filter(lambda x: not x.startswith('\n'), fd.readlines()) try: with open(new_fname, mode='w') as f: for line in lines: # printLog('[scanLogcat] current line: %s'% line) # Oct 23: changed method to get activity name and time # use ':' to split columns in get_ALT.sh and '+' to split # activity name and launch time activity, ltime=line.split('(')[0].split('+') activity=activity.split(' ')[2] ltime=self.__convertTime(ltime.rstrip('\n')) ALTList.append((activity, ltime)) f.write(activity+','+ltime+'\n') except Exception, e: printLog('[scanLogcat] Caught exception while writing launch time data to file: %s' % e.message, logging.ERROR)
def getDeviceIdList(self): cmd = r"adb devices|awk -F'\t' '{print $1}'" devices = self.runShellCmd(cmd) deviceIdList = filter(lambda x: not len(x) == 0, devices.splitlines()[1:]) #.split('\t',1)[0] printLog('List of devices attached: \n' + str(deviceIdList)) return deviceIdList
def __compareImage(self, file1, file2): # arg=self.__validateString(str_arg) # file1, file2=arg.split(' ', 1) img1=None img2=None try: img1=Image.open(file1) img2=Image.open(file2) if(img1.size!=img2.size): return False by1=img1.tobytes() by2=img2.tobytes() #format r,g,b,255,r,g,b,255, 3 bytes = 1 point, 255=separator, total 4 bytes l=len(by1)/4 #total points and same points tp=0 sp=0 for j in range(l): i=j*4 tp=tp+1 if by1[i]==by2[i] and by1[i+1]==by2[i+1] and by1[i+2]==by2[i+2]: sp=sp+1 # max to 2% diff allowed if tp*0.98>sp: return False else: return True except Exception, e: printLog(self.threadName+"Exception in __compareImage: %s" % e.message, logging.ERROR) traceback.print_exc() return False
def getLaunchTime(self, fname): ''' Jul 22, scan logcat log file and retrieve activity launch time data, save a list of (activity, launch time) vp ''' if not os.path.isfile(fname): return '' self.callShellCmd('./get_ALT.sh ' + fname) ALTList = [] new_fname = 'logcat.csv' with open(new_fname, 'r') as fd: lines = filter(lambda x: not x.startswith('\n'), fd.readlines()) try: with open(new_fname, mode='w') as f: for line in lines: # printLog('[scanLogcat] current line: %s'% line) # Oct 23: changed method to get activity name and time # use ':' to split columns in get_ALT.sh and '+' to split # activity name and launch time activity, ltime = line.split('(')[0].split('+') activity = activity.split(' ')[2] ltime = self.__convertTime(ltime.rstrip('\n')) ALTList.append((activity, ltime)) f.write(activity + ',' + ltime + '\n') except Exception, e: printLog( '[scanLogcat] Caught exception while writing launch time data to file: %s' % e.message, logging.ERROR)
def do_drag(self, str_arg): # print str_arg (startPoint, endPoint)=self.__getPointXYs(str_arg) printLog(self.threadName+'[do_drag] dragging from (%d,%d) to (%d,%d)...' % \ (startPoint[0],startPoint[1], endPoint[0],endPoint[1])) self.md.drag((startPoint[0],startPoint[1]), (endPoint[0],endPoint[1]),1,10) printLog(self.threadName+'[status=%s]' % self.resultFlag)
def do_installApp(self, str_arg=''): target=BUILD_ROOT_PATH+sep+BUILD_VERSION+sep+APP_NAME+'-'+str(self.buildnum)+sep+BUILD_FILENAME if path.isfile(target): self.installApp(target) return True else: printLog(self.threadName+"CANNOT ACCESS/FIND BUILD FILE at %s" % target, logging.ERROR) return False
def __compressImage(self, file): im=Image.open(file) printLog(self.threadName+'compressing snapshot %s...' % file) ratio = float(SNAPSHOT_WIDTH)/im.size[0] height = int(im.size[1]*ratio) printLog(self.threadName+"new image size: %d*%d" % (SNAPSHOT_WIDTH, height)) os.remove(file) im.resize((SNAPSHOT_WIDTH, height), Image.BILINEAR).save(file)
def pullFile(self, src, tgt='.'): if tgt=='.': tgt='./'+os.path.basename(src) self.callAdbCmd('pull',src+' '+tgt) if os.path.isfile(tgt): return 0 else: printLog("[pullFile] Failed to get file '%s' via adb." % src,logging.ERROR) return 1
def __getpkgNameByApk(self, apkName): ''' Get the package name from .apk file ''' cmd = "aapt dump badging " + apkName + " |grep package:|awk -F ' ' '{print $2}'|awk -F '=' '{print $2}'|tr -d \"'\"" pkgName = self.runShellCmd(cmd) if pkgName is None: printLog('Cannot get package name from apk file.', logging.ERROR) return False
def __getpkgNameByApk(self, apkName): ''' Get the package name from .apk file ''' cmd="aapt dump badging "+apkName+" |grep package:|awk -F ' ' '{print $2}'|awk -F '=' '{print $2}'|tr -d \"'\"" pkgName=self.runShellCmd(cmd) if pkgName is None: printLog('Cannot get package name from apk file.', logging.ERROR) return False
def do_checkCrash(self, str_arg=''): #TODO: customize the App Name App_Name='' self.do_check("id/message Unfortunately, %s has stopped." % App_Name) self.crash=self.resultFlag if self.crash: printLog("********APP CRASHED!!!********", logging.ERROR) # else: #TODO: check if app is still running self.resultFlag = True
def __getChildViewText(self, parentId, childSeq): child_view=self.__getChildView(parentId, childSeq) if child_view: np=child_view.namedProperties # print np return np.get('text:mText').value.encode(sys.getdefaultencoding()) else: printLog(self.threadName+'[__getChildViewText] view not found.', logging.ERROR) self.resultFlag=False return ''
def pullFile(self, src, tgt='.'): if tgt == '.': tgt = './' + os.path.basename(src) self.callAdbCmd('pull', src + ' ' + tgt) if os.path.isfile(tgt): return 0 else: printLog("[pullFile] Failed to get file '%s' via adb." % src, logging.ERROR) return 1
def do_checkCrash(self, str_arg=''): #TODO: customize the App Name App_Name = '' self.do_check("id/message Unfortunately, %s has stopped." % App_Name) self.crash = self.resultFlag if self.crash: printLog("********APP CRASHED!!!********", logging.ERROR) # else: #TODO: check if app is still running self.resultFlag = True
def do_installApp(self, str_arg=''): target = BUILD_ROOT_PATH + sep + BUILD_VERSION + sep + APP_NAME + '-' + str( self.buildnum) + sep + BUILD_FILENAME if path.isfile(target): self.installApp(target) return True else: printLog( self.threadName + "CANNOT ACCESS/FIND BUILD FILE at %s" % target, logging.ERROR) return False
def scanExceptionInFile(path): ''' search for any exception in the file specified in path, and save return the result as a string ''' path=os.path.basename(path) printLog('[scanFile] Scanning file %s for exceptions...' % path, logging.INFO) # self.exception_string=check_output(r'grep -n "Exception" -A 3 log.txt', shell=True) cmdList=["grep", "-n", "ERROR", "-B", "1", "-A", "3", path] exception_string=Popen(cmdList, stdout=PIPE).communicate()[0] # printLog('[scanFile] exceptions found: %s' % exception_string) return exception_string
def __clickChildView(self, parentId, childSeq): child_view=self.__getChildView(parentId, childSeq) if child_view: # 2014/09/25: the returned point Y coordinate does not include the status bar height # using getAbsolutePositionOfView cannot solve this issue # so add 50 to Y point=self.hv.getAbsoluteCenterOfView(child_view) printLog(self.threadName+'[__clickChildView] clicking device at (%d, %d) ...' % (point.x, point.y+50)) self.md.touch(point.x, point.y+50, MonkeyDevice.DOWN_AND_UP) self.resultFlag=True else: printLog(self.threadName+'[__clickChildView] view not found.', logging.ERROR) self.resultFlag=False
def scanExceptionInFile(path): ''' search for any exception in the file specified in path, and save return the result as a string ''' path = os.path.basename(path) printLog('[scanFile] Scanning file %s for exceptions...' % path, logging.INFO) # self.exception_string=check_output(r'grep -n "Exception" -A 3 log.txt', shell=True) cmdList = ["grep", "-n", "ERROR", "-B", "1", "-A", "3", path] exception_string = Popen(cmdList, stdout=PIPE).communicate()[0] # printLog('[scanFile] exceptions found: %s' % exception_string) return exception_string
def getLatestBuildNumber(): """ #TODO: implement the logic and return build number in integer """ fd=file buildnum= 0 try: # read the buildnum.txt and get the currect build number with open(BUILDNUM_FILE_PATH) as fd: content=filter(lambda x: not x.startswith('\n'), fd.readlines()) buildnum=int(content[0].split('-')[1][1:]) except IOError, e: printLog("File %s open error." % BUILDNUM_FILE_PATH, logging.ERROR)
def getLatestBuildNumber(): """ #TODO: implement the logic and return build number in integer """ fd = file buildnum = 0 try: # read the buildnum.txt and get the currect build number with open(BUILDNUM_FILE_PATH) as fd: content = filter(lambda x: not x.startswith('\n'), fd.readlines()) buildnum = int(content[0].split('-')[1][1:]) except IOError, e: printLog("File %s open error." % BUILDNUM_FILE_PATH, logging.ERROR)
def __init__(self, device_id): #interval(seconds) between commands self.INTERVAL=DEFAULT_INTERVAL Android.__init__(self, device_id) self.resultFlag=False self.androidVersion =self.getDeviceAndroidVersion() self.make =self.getDeviceMake() self.model =self.getDeviceModel() self.operator =self.getDeviceOperator() self.idle =True self.threadName='<'+self.model+'_'+ device_id+'> ' # Connect to the current device printLog(self.threadName+'[AndroidDevice] Connecting to device %s...' % device_id, logging.INFO) self.__connect() printLog(self.threadName+'[AndroidDevice] Device %s init completed.' % device_id)
def do_compare(self, str_arg): arg=self.__validateString(str_arg) source, target=arg.split(' ', 1) if os.path.isfile(source): # Mar 27 @swang: if target file doesn't exist, copy source file to setup directory for later test if not os.path.isfile(target): copy(source, target) return # if not self.__compareImage(source, target): if not filecmp.cmp(source, target): printLog(self.threadName+'source file and target file DIFFER!', logging.WARNING) self.resultFlag=False else: self.resultFlag=False raise ValueError('source file not found.')
def start(self): ''' @return: number of failed testcases @rtype: integer ''' self.__reset() self.start_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) ##start multi-threads deadThread=0 for i in range(len(self.devicePool)): try: appTestEngine=AppTestEngine(self.buildnum, self.testPool, self.devicePool[i]) self.testEngineList.append(appTestEngine) appTestEngine.start() except AssertionError, e: printLog('Init test engine %d of %d failed: %s' % (i, len(self.devicePool), e.message), logging.ERROR) deadThread+=1
def removeApp(self, pkgName): printLog("Removing package %s ..." % pkgName) try: if (self.runAdbCmd('uninstall', pkgName).strip() == 'Failure'): printLog('failed to remove %s.' % pkgName) return False else: printLog('%s is removed.' % pkgName) return True except Exception, e: printLog('Exception during remove:' + e, logging.ERROR) return False
def runShellCmd(self, cmd): printLog("[runShellCmd] Running cmd:"+ cmd) try: p=Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out, err=p.communicate() printLog("[runShellCmd] Command returns:\noutput:%s\n" % out) if len(err)>0: printLog("[runShellCmd] error:%s" % err, logging.ERROR) except: printLog("[runShellCmd] Exception when run cmd '%s'." % cmd, logging.ERROR) return None return out
def removeApp(self, pkgName): printLog("Removing package %s ..." % pkgName) try: if (self.runAdbCmd('uninstall',pkgName).strip()=='Failure'): printLog('failed to remove %s.' % pkgName) return False else: printLog('%s is removed.' % pkgName) return True except Exception, e: printLog('Exception during remove:'+ e, logging.ERROR) return False
def runShellCmd(self, cmd): printLog("[runShellCmd] Running cmd:" + cmd) try: p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out, err = p.communicate() printLog("[runShellCmd] Command returns:\noutput:%s\n" % out) if len(err) > 0: printLog("[runShellCmd] error:%s" % err, logging.ERROR) except: printLog("[runShellCmd] Exception when run cmd '%s'." % cmd, logging.ERROR) return None return out
def do_upgradeApp(self, str_arg=''): ''' 1. get the build file 2. do upgrade ''' #TODO: implement target='' if not path.isfile(target): # TODO: get the build file to BUILD_ROOT_PATH pass if path.isfile(target): if self.currentBuildnum< self.buildnum: self.resultFlag=self.upgradeApp(target) else: printLog(self.threadName+"Target build already installed, skip upgrade.") self.resultFlag=False else: printLog(self.threadName+"CANNOT ACCESS/FIND BUILD FILE at %s" % target, logging.ERROR) self.resultFlag=False return self.resultFlag
def start(self): ''' @return: number of failed testcases @rtype: integer ''' self.__reset() self.start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) ##start multi-threads deadThread = 0 for i in range(len(self.devicePool)): try: appTestEngine = AppTestEngine(self.buildnum, self.testPool, self.devicePool[i]) self.testEngineList.append(appTestEngine) appTestEngine.start() except AssertionError, e: printLog( 'Init test engine %d of %d failed: %s' % (i, len(self.devicePool), e.message), logging.ERROR) deadThread += 1
def __init__(self, build_num, test_suite, device_id): TestEngine.__init__(self, build_num, test_suite, device_id) self.currentBuildnum=self.getCurrentBuildNumber() printLog(self.threadName+"[AppTestEngine] current build number is %d, target build number is %s" % (self.currentBuildnum, str(self.buildnum))) if self.currentBuildnum < build_num: # upgrade app to target build if UPGRADE_APP_ON_TEST_START: printLog(self.threadName+"[AppTestEngine] Upgrading device to build %s..." % self.buildnum) assert self.do_upgradeApp() else: printLog(self.threadName+"[AppTestEngine] Upgrade to build %s skipped..." % self.buildnum) else: printLog(self.threadName+"[AppTestEngine] use current installed build %s" % self.currentBuildnum) self.buildnum=self.currentBuildnum
def __init__(self, suite_name=DEFAULT_TEST_SUITE, build_num=0): ''' @param string suite @param string buildnum ''' self.initOK=False ## do input validation self.buildnum=build_num self.suiteName=suite_name self.Pass=0 self.Fail=0 self.Total=0 self.ALTList=[] self.start_time=None self.end_time=None self.exception_string='' ## do environment validation if not path.isfile(self.__class__.__name__+'.py'): print('Please run %s from the directory where is resides.' % (self.__class__.__name__+'.py')) return # if not path.isdir(SETUP_SUBDIR): # print 'Required directory %s does not exist. please check and run again.' % SETUP_SUBDIR # return if not path.isfile(CONFIG_FILE): print("File '%s' is not found in test4u root directory. please make sure you get the full package and start over." % CONFIG_FILE) return if not path.isdir(TC_SUBDIR): print("Directory '%s' is not found in test4u root directory. It is used to store testcase files(*.t4u). Please check and start over." % TC_SUBDIR) return if not path.isdir(TS_SUBDIR): print("Directory '%s' is not found in test4u root directory. It is used to store test suite files(*.ts). Please check and start over." % TC_SUBDIR) return if not path.isdir(SNAPSHOT_SUBDIR): mkdir(SNAPSHOT_SUBDIR) ## remove old log file if path.isfile(TESTER_DEBUG_LOG_FILE): print('Removing old log file...') remove(TESTER_DEBUG_LOG_FILE) # truncate_file(TESTER_DEBUG_LOG_FILE) ## create new log file self.logHandler=createLogger(self.buildnum) ## build device pool self.testServer=TestServer() self.devicePool=self.testServer.getDeviceIdList() if len(self.devicePool)==0: printLog('NO DEVICE FOUND. QUIT.', logging.ERROR) return ## build testcase suite try: self.testPool=TestSuite(self.suiteName) if self.testPool.getTotalCount()==0: printLog('NO TESTCASE IN THE TEST SUITE. QUIT.', logging.ERROR) return except Exception, e: printLog('Failed to create test pool: %s' % e.message, logging.ERROR) return
def callShellCmd(self, cmd): printLog("[callShellCmd] Running cmd:"+ cmd) if call(cmd, shell=True)==0: printLog("[callShellCmd] Command succeed. returns 0") return True else: printLog("[callShellCmd] Failed to execute command '%s'." % cmd, logging.ERROR) return False
def do_longpress(self, str_arg): arg=self.__validateString(str_arg) # if arg.startswith(r'('): # raise ValueError('Bad argument, You may want to use longpress2 with coordinates as auguments.') if arg.startswith(r'('): mode=2 point, sec=arg.split(')') x,y=self.__getPointXY(point+')') else: mode=1 if ' ' in arg: id, sec=arg.split(' ') if len(sec)>0: seconds=int(self.__validateDigit(sec.strip())) else: id=arg seconds=2 # for tmp in range(REPEAT_TIMES_ON_ERROR): try: printLog(self.threadName+"[running 'longpress %s'...]" % str_arg) if mode==1: self.ed.touch(By.id(id), MonkeyDevice.DOWN) # print 'key down' time.sleep(seconds) # print 'sleep' self.ed.touch(By.id(id), MonkeyDevice.UP) # print 'key up' else: self.md.touch(x,y, MonkeyDevice.DOWN) # print 'key down' time.sleep(seconds) # print 'sleeped' self.md.touch(x,y, MonkeyDevice.UP) # print 'key up' return except Exception, e: pass
def callShellCmd(self, cmd): printLog("[callShellCmd] Running cmd:" + cmd) if call(cmd, shell=True) == 0: printLog("[callShellCmd] Command succeed. returns 0") return True else: printLog("[callShellCmd] Failed to execute command '%s'." % cmd, logging.ERROR) return False
def do_upgradeApp(self, str_arg=''): ''' 1. get the build file 2. do upgrade ''' #TODO: implement target = '' if not path.isfile(target): # TODO: get the build file to BUILD_ROOT_PATH pass if path.isfile(target): if self.currentBuildnum < self.buildnum: self.resultFlag = self.upgradeApp(target) else: printLog(self.threadName + "Target build already installed, skip upgrade.") self.resultFlag = False else: printLog( self.threadName + "CANNOT ACCESS/FIND BUILD FILE at %s" % target, logging.ERROR) self.resultFlag = False return self.resultFlag
def __installApp(self, apkPath, removeBeforeInstall): ''' Jan 24, 2013: swang rewrite as a common method to install apk to user part ''' if not os.path.isfile(apkPath): printLog(apkPath + ' is not found.') return False ## need to remove the package first so that policy file could be updated. pkgName=self.__getpkgNameByApk(apkPath) #print pkgName if removeBeforeInstall: if not self.removeApp(pkgName): return False try: printLog("Installing application %s ..." % apkPath) self.installApp(apkPath) printLog('installation is done.') return True except Exception, e: printLog('Exception during install:'+ e, logging.ERROR) return False
def __installApp(self, apkPath, removeBeforeInstall): ''' Jan 24, 2013: swang rewrite as a common method to install apk to user part ''' if not os.path.isfile(apkPath): printLog(apkPath + ' is not found.') return False ## need to remove the package first so that policy file could be updated. pkgName = self.__getpkgNameByApk(apkPath) #print pkgName if removeBeforeInstall: if not self.removeApp(pkgName): return False try: printLog("Installing application %s ..." % apkPath) self.installApp(apkPath) printLog('installation is done.') return True except Exception, e: printLog('Exception during install:' + e, logging.ERROR) return False
def __init__(self, build_num, test_suite, device_id): TestEngine.__init__(self, build_num, test_suite, device_id) self.currentBuildnum = self.getCurrentBuildNumber() printLog( self.threadName + "[AppTestEngine] current build number is %d, target build number is %s" % (self.currentBuildnum, str(self.buildnum))) if self.currentBuildnum < build_num: # upgrade app to target build if UPGRADE_APP_ON_TEST_START: printLog(self.threadName + "[AppTestEngine] Upgrading device to build %s..." % self.buildnum) assert self.do_upgradeApp() else: printLog(self.threadName + "[AppTestEngine] Upgrade to build %s skipped..." % self.buildnum) else: printLog(self.threadName + "[AppTestEngine] use current installed build %s" % self.currentBuildnum) self.buildnum = self.currentBuildnum
def truncate_file(fname, size=0): ''' Open a file for writing, and truncate it to specified size in bytes. ''' if not os.path.isfile(fname): return # with open(fname, "ab") as f: # f.truncate(size) # f.close() initSize=os.path.getsize(fname) printLog('initial size of %s: %d'% (fname, initSize)) with open(fname, mode='w') as f: f.truncate(size) # f.write('[log start]\n') finalSize=os.path.getsize(fname) printLog('final size of %s: %d'% (fname, finalSize)) printLog('truncated size of %s: %d'% (fname, initSize - finalSize))
def do_assert(self, str_arg): arg=self.__validateString(str_arg) if arg not in ('pass','fail'): self.resultFlag=False raise ValueError('Bad parameter.') if(arg=='pass' and self.resultFlag==True): printLog(self.threadName+'[ASSERT PASS]', logging.DEBUG) self.resultFlag=True return if(arg=='fail' and self.resultFlag==False): printLog(self.threadName+'[ASSERT PASS]', logging.DEBUG) self.resultFlag=True return #printLog(self.threadName+'[status=%s]' % self.resultFlag) printLog(self.threadName+'[ASSERT FAIL!]', logging.DEBUG) self.resultFlag=False
def do_checkchild(self, str_arg): printLog(self.threadName+"[running command 'checkchild %s']" % str_arg) arg=self.__validateString(str_arg).strip() try: #to avoid ' ' two spaces case #suppose string like: id/text1 (5,4,2,3,3,3) textfield i=arg.index(' ') ids=arg[0:i] arg=arg[i+1:].strip() if ' ' in arg: i=arg.index(' ') seqs=arg[1:i-1].split(',') arg=arg[i+1:].strip() texts=arg target_text=self.__getChildViewText(ids,seqs) printLog(self.threadName+'[text on screen: %s]' % target_text) self.resultFlag=True if texts!='': if texts==target_text: self.resultFlag=True else: self.resultFlag=False else: seqs=arg[1:-1].split(',') if self.____getChildView(ids, seqs): self.resultFlag=True else: self.resultFlag=False except java.lang.RuntimeException: self.resultFlag=False printLog(self.threadName+'Runtime Exception! id not found.', logging.ERROR) except Exception, e: #gbk problem self.resultFlag=False traceback.print_exc() printLog(self.threadName+'Exception in do_checkchild: %s' % e.message, logging.ERROR)
def do_click(self, str_arg): #todo, wait for x miliseconds arg=self.__validateString(str_arg) for tmp in range(REPEAT_TIMES_ON_ERROR): try: if not '(' in arg: printLog(self.threadName+'[clicking id %s...]' % arg) self.ed.touch(By.id(arg), MonkeyDevice.DOWN_AND_UP) else: point=self.__getPointXY(arg) printLog(self.threadName+'[clicking point %s...]' % arg) self.md.touch(point[0],point[1],MonkeyDevice.DOWN_AND_UP) return except java.net.SocketException,e: printLog(self.threadName+'do_click: the %dth try failed due to SocketException, will retry.' % tmp, logging.ERROR) MonkeyRunner.sleep(1) continue except:
def truncate_file(fname, size=0): ''' Open a file for writing, and truncate it to specified size in bytes. ''' if not os.path.isfile(fname): return # with open(fname, "ab") as f: # f.truncate(size) # f.close() initSize = os.path.getsize(fname) printLog('initial size of %s: %d' % (fname, initSize)) with open(fname, mode='w') as f: f.truncate(size) # f.write('[log start]\n') finalSize = os.path.getsize(fname) printLog('final size of %s: %d' % (fname, finalSize)) printLog('truncated size of %s: %d' % (fname, initSize - finalSize))
def do_clickchild(self, str_arg): printLog(self.threadName+"[running 'clickchild %s']" % str_arg) arg=self.__validateString(str_arg).strip() try: #to avoid ' ' two spaces case #suppose string like: id/button1 (5,2,3,3,3) i=arg.index(' ') ids=arg[0:i] arg=arg[i+1:].strip() seqs=arg[1:-1].split(',') self.__clickChildView(ids,seqs) except: printLog(self.threadName+'do_clickChild: click failed', logging.ERROR) traceback.print_exc() self.resultFlag=False MonkeyRunner.sleep(1) finally: printLog(self.threadName+'[status=%s]' % self.resultFlag)