def auto_register(): runStartApp() mr.sleep(2) #email = emailScreen() password = "******" easy_device.touch(By.id('id/iv_avatar'), md.DOWN_AND_UP) mr.sleep(1) device.drag((1272, 1002), (249, 1105), 3, 10) mr.sleep(1) easy_device.touch(By.id('id/et_email'), md.DOWN_AND_UP) #device.type(email) mr.sleep(3) device.touch(136, 594, 'DOWN_AND_UP') device.type(password) mr.sleep(1) easy_device.touch(By.id('id/et_confirm_password'), md.DOWN_AND_UP) device.type(password) mr.sleep(2) easy_device.touch(By.id('id/btn_sign'), md.DOWN_AND_UP) mr.sleep(1) image = device.takeSnapshot() mr.sleep(2) image.writeToFile('/Users/apple/auto_test/AutoImage/RegisterN1.png', 'png') result = mr.loadImageFromFile('/Users/apple/auto_test/AutoImage/test1.png', 'png') if image.sameAs(result, 1): print("register user is match right") else: print("the register function have problem!!")
def serverPolicy(): runStartApp() easy_device.touch(By.id('id/iv_avatar'), md.DOWN_AND_UP) mr.sleep(1) device.touch(258, 666, 'DOWN_AND_UP') mr.sleep(1) image = device.takeSnapShot() mr.sleep(2) image.writeToFile('D:/AndroidSdk/AutoImage/TeamServer1.png', 'png') result = mr.loadImageFromFile('D:/AndroidSdk/AutoImage/TeamServer.png', 'png') if image.sameAs(result, 1): print("the team server page match right") else: print("there is a problem here,please check , and the number is:" + "the team server page") easy_device.touch(By.id('id/title_bar_iv_left'), md.DOWN_AND_UP) device.touch(456, 664, 'DOWN_AND_UP') image = device.takeSnapShot() mr.sleep(2) image.writeToFile('D:/AndroidSdk/AutoImage/PrivacyPolicy1.png', 'png') result = mr.loadImageFromFile('D:/AndroidSdk/AutoImage/PrivacyPolicy.png', 'png') if image.sameAs(result, 1): print("the privacy policy page match right") else: print("there is a problem here,please check , and the number is:" + "the privacy policy page")
def send_msg(self,data): print '\n------------ send_msg ------------' if not data.get('msg'): return -1 if self.is_current_group() != 0: return -1 utils.get_encoded_character(deviceid, data['msg'].decode('utf8')) self.restart_qq_monkey() self.easy_device.touch(By.id("id/input"), self.easy_device.DOWN) # self.device.touch(500,1700,'DOWN') sleep(0.5) self.easy_device.touch(By.id("id/input"), self.easy_device.UP) # self.device.touch(500,1700,'UP') # sleep(1) self.touchByMonkeyPixel(270,1590) inputid = self.get_hierarchy_view_by_id('id/input') if inputid: text = self.getTextByMonkeyView(inputid) print "Info : get msg %s from clipboard !" % text if text.strip().split() == data['msg'].strip().split(): if self.touchByMonkeyId('id/fun_btn') != 0: # if self.touchByMonkeyPixel(970,1700) != 0: return -1 print "Info : send msg %s !" % data['msg'] return 0
def Logout(device,edevice): while (not edevice.exists(By.id('id/main_tab_mine_icon'))): device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) edevice.touch(By.id('id/main_tab_mine_icon'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(0.5) edevice.touch(By.id('id/menu_item_logout'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(0.5) print('Has Log out')
def textAssert(idname,text): if easy_device.exists(By.id(idname)) == True: text = easy_device.getText(By.id(idname)) if text.encode('utf-8') == text: print ("Assert pass") else: print ("Assert fail") else: print ("Assert fail")
def addFirstContact(): easy_device.touch(By.id('id/create_contact_button'),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(6) if easy_device.visible(By.id('id/content')): easy_device.touch(By.id('id/left_button'),MonkeyDevice.DOWN_AND_UP) trace( 'select contact information keep local') else: MonkeyRunner.sleep(6)
def addFirstContact(): easy_device.touch(By.id('id/create_contact_button'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(6) if easy_device.visible(By.id('id/content')): easy_device.touch(By.id('id/left_button'), MonkeyDevice.DOWN_AND_UP) trace('select contact information keep local') else: MonkeyRunner.sleep(6)
def logout_vivo(): global device global eDevice global hViewer device.startActivity("com.vivo.game/com.vivo.game.ui.GameTabActivity") time.sleep(3) v = hViewer.findViewById('id/tabs') view = hViewer.getAbsoluteCenterOfView(v.children[3]) device.touch(view.x, view.y, 'DOWN_AND_UP') v = hViewer.findViewById('id/account_nickname') view = hViewer.getAbsoluteCenterOfView(v) device.touch(view.x, view.y, 'DOWN_AND_UP') time.sleep(3) while eDevice.exists(By.id('id/account_nickname')): time.sleep(1) device.touch(view.x, view.y, 'DOWN_AND_UP') print(0) while not eDevice.exists(By.id('id/game_personal_page_account_name')): time.sleep(3) print('????') v = hViewer.findViewById('id/game_personal_page_account_name') view = hViewer.getAbsoluteCenterOfView(v) device.touch(view.x, view.y, 'DOWN_AND_UP') while not eDevice.exists(By.id('id/logout')): time.sleep(3) print(2) v = hViewer.findViewById('id/logout') view = hViewer.getAbsoluteCenterOfView(v) device.touch(view.x, view.y, 'DOWN_AND_UP') while not eDevice.exists(By.id('id/button1')): time.sleep(3) print(3) v = hViewer.findViewById('id/button1') view = hViewer.getAbsoluteCenterOfView(v) v2 = hViewer.findViewById('id/parentPanel') view2 = hViewer.getAbsolutePositionOfView(v2) ptop = int(v.paddingTop) v_h = int(v2.height) v_w = int(v2.width) display_h = int(device.getProperty('display.height')) display_w = int(device.getProperty('display.width')) device.touch((display_w - v_w) / 2 + view.x, (display_h - v_h) / 2 + ptop + view.y, 'DOWN_AND_UP') time.sleep(3) while eDevice.exists(By.id('id/button1')): time.sleep(1) device.touch((display_w - v_w) / 2 + view.x, (display_h - v_h) / 2 + ptop + view.y, 'DOWN_AND_UP')
def main(): # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() easy_device = EasyMonkeyDevice(device) # sets a variable with the package's internal name package = 'org.vhack.dev.vhack' # sets a variable with the name of an Activity in the package activity = 'org.vhack.dev.vhack.SplashActivity' # sets the name of the component to start runComponent = package + '/' + activity # Runs the component device.startActivity(component=runComponent) ips = get_ips(0) time.sleep(3) print 'Start Playing........' easy_device.touch(By.id('id/btnNetwork'), MonkeyDevice.DOWN_AND_UP) time.sleep(1.5) for ip in ips: for i in xrange(15): device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP) device.type(ip.strip()) easy_device.touch(By.id('id/btnScanIP'), MonkeyDevice.DOWN_AND_UP) output = 1 print '[+] Scanning %s' % ip.strip() while output: time.sleep(3) # Takes a screenshot result = device.takeSnapshot() # Writes the screenshot to a file result.writeToFile('./screen.png', 'png') ocr_res = ocr().strip() if ocr_res == 'Attack': output = 0 easy_device.touch(By.id('id/btnTransferIP'), MonkeyDevice.DOWN_AND_UP) print '[#] Attacking Target' time.sleep(2) elif ocr_res == 'Pass': output = 0 print '[-] Pass Target' elif ocr_res == 'Wait': print '[!] Waiting' else: output = 0 print 'Unknown'
def case_login(self): self.device.startActivity( component=self.apk_name_activity ) mr.sleep(3.0) self.easy_device.touch(By.id('id/username'),md.DOWN_AND_UP) text = self.easy_device.getText(By.id('id/username')) self.device.press('KEYCODE_MOVE_END', md.DOWN_AND_UP) for i in range(len(text)): self.device.press('KEYCODE_DEL', md.DOWN) self.device.type(self.data[0]) self.easy_device.touch(By.id('id/password'),md.DOWN_AND_UP) self.device.type(self.data[1]) self.easy_device.touch(By.id('id/login'),md.DOWN_AND_UP) print "case_login"
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 getExistById(self, str_id): try: return self.easy_device.exists(By.id("id/" + str_id)) except Exception, e: msg = "[%s] Failed to get exist by Id: [%s]" %(self.class_name, str(e)) self.m_logger.error(msg) return None
def waitVisible(self, idstr): print('VISIBLE ' + idstr) v = By.id(idstr) while (not self.easy_device.visible(v)): print('wait ' + str(v)) #print('visible'); return v
def touchById(self, str_id, action_type="DOWN_AND_UP"): try: return self.easy_device.touch(By.id("id/" + str_id), self.action_type_dict[action_type]) except Exception, e: msg = "[%s] Failed to touch by Id: [%s]" %(self.class_name, str(e)) self.m_logger.error(msg) return None
def addContactDetail(name,phoneNumber): easy_device.type(By.id('id/0x3'),name) MonkeyRunner.sleep(3) easy_device.type(By.id('id/0x17'),phoneNumber) easy_device.touch(By.id('id/save_menu_item'),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(7) s= easy_device.getText(By.id('id/data')) trace('contact add success,phone number:' + s) phoneInfo= s.replace('-','').replace(' ','').replace('(','').replace(')','') if phoneInfo == phoneNumber: trace('contact information check success') else: trace('contact information add wrong') device.shell('am force-stop com.android.contacts') trace('destroy current contacts application')
def getElementCenterById(self, str_id): try: return self.easy_device.getElementCenter(By.id("id/" + str_id)) except Exception, e: msg = "[%s] Failed to get element center by Id: [%s]" %(self.class_name, str(e)) self.m_logger.error(msg) return None
def getElementCenterById(self, str_id): try: return self.easy_device.getElementCenter(By.id("id/" + str_id)) except Exception, e: msg = "[%s] Failed to get element center by Id: [%s]" % ( self.class_name, str(e)) self.m_logger.error(msg) return None
def addContact(name,phoneNumber): device.startActivity(component = 'com.android.contacts/.activities.PeopleActivity') MonkeyRunner.sleep(3) if easy_device.visible(By.id('id/create_contact_button')): trace('add contact first time') addFirstContact() elif easy_device.visible(By.id('id/menu_add_contact')): trace("Location of add contact menu:" + str(easy_device.locate(By.id('id/menu_add_contact')))) easy_device.touch(By.id('id/menu_add_contact'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(7) else: raise Error('Could not find the "menu_add_contact" button') addContactDetail(name,phoneNumber)
def getExistById(self, str_id): try: return self.easy_device.exists(By.id("id/" + str_id)) except Exception, e: msg = "[%s] Failed to get exist by Id: [%s]" % (self.class_name, str(e)) self.m_logger.error(msg) return None
def main(): apk = sys.argv[1] package = sys.argv[2] instructions_file = sys.argv[3] print(instructions_file) print('Checking adb devices') devices = get_devices() print('Devices found: '+str(devices)) if not len(devices): print('No devices found, setting up emulator') run_emulator() print('Emulator boot completed.. proceding..') device = MonkeyRunner.waitForConnection() easy_device = EasyMonkeyDevice(device) print('Connected\nInstalling package..') device.installPackage(apk) print('Installed!') print('Checking all activities..\nThis may take a while..') f = open(instructions_file, 'r') instructions = json.load(f) for activity in instructions: print(activity) runComponent = package + '/' + activity for button in instructions[activity]: device.startActivity(component=runComponent) time.sleep(1) if easy_device.visible(By.id('id/'+button)): easy_device.touch(By.id('id/'+button), MonkeyDevice.DOWN_AND_UP) time.sleep(1) else: device.press("KEYCODE_BACK", MonkeyDevice.DOWN_AND_UP) time.sleep(1) if easy_device.visible(By.id('id/'+button)): easy_device.touch(By.id('id/'+button), MonkeyDevice.DOWN_AND_UP) result = device.takeSnapshot() result_path = os.path.join(os.path.abspath('monkeyresult/'), package) if not os.path.exists(result_path): os.makedirs(result_path) result.writeToFile( os.path.join(result_path, activity+'.png'), 'png' ) f.close() print('Saved some snapshots to\n'+result_path)
def typeInViewById(self, str_id, str_msg): try: self.easy_device.type(By.id("id/" + str_id), str_msg) return True except Exception, e: msg = "[%s] Failed to type in view [%s]" %(self.class_name, str(e)) self.m_logger.error(msg) return False
def search(self, w): print('SEARCH ' + w) v = self.waitVisible('id/search') sv = By.id('id/search') self.easy_device.touch(sv, MonkeyDevice.DOWN_AND_UP) self.easy_device.type(sv, w) self.easy_device.press('KEYCODE_ENTER', MonkeyDevice.DOWN_AND_UP) self.sleep(3)
def RoomManager_In(device, edevice): if edevice.exists(By.id('id/room_main_terminal_unlock')): print('Has Logined') else: print('Not Login, Start Logining...') edevice.touch(By.id('id/login_role_room_manager_layout'), MonkeyDevice.DOWN_AND_UP) text = (edevice.getText( By.id('id/main_login_account_text'))).encode('utf-8') print(text) while (text != ''): edevice.touch(By.id('id/main_login_icon_clean'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(0.5) text = (edevice.getText( By.id('id/main_login_account_text'))).encode('utf-8') print('text is null') edevice.type(By.id('id/main_login_account_text'), '17816118870') MonkeyRunner.sleep(0.5) device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) edevice.touch(By.id('id/main_login_submit_btn'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) print('Has Logined')
def case_order_select(self, s): mr.sleep(1.0) self.easy_device.touch(By.id("id/toolbar_right"),md.DOWN_AND_UP) mr.sleep(1.0) if s == "order": self.device.touch(400,222,md.DOWN_AND_UP) elif s == "accepted": self.device.touch(400,293,md.DOWN_AND_UP) print "case_order_select"
def touchById(self, str_id, action_type="DOWN_AND_UP"): try: return self.easy_device.touch(By.id("id/" + str_id), self.action_type_dict[action_type]) except Exception, e: msg = "[%s] Failed to touch by Id: [%s]" % (self.class_name, str(e)) self.m_logger.error(msg) return None
def typeInViewById(self, str_id, str_msg): try: self.easy_device.type(By.id("id/" + str_id), str_msg) return True except Exception, e: msg = "[%s] Failed to type in view [%s]" % (self.class_name, str(e)) self.m_logger.error(msg) return False
def addContactDetail(name, phoneNumber): easy_device.type(By.id('id/0x3'), name) MonkeyRunner.sleep(3) easy_device.type(By.id('id/0x17'), phoneNumber) easy_device.touch(By.id('id/save_menu_item'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(7) s = easy_device.getText(By.id('id/data')) trace('contact add success,phone number:' + s) phoneInfo = s.replace('-', '').replace(' ', '').replace('(', '').replace(')', '') if phoneInfo == phoneNumber: trace('contact information check success') else: trace('contact information add wrong') device.shell('am force-stop com.android.contacts') trace('destroy current contacts application')
def case_order_drag(self): mr.sleep(2.0) self.easy_device.touch(By.id("id/order_manage"),md.DOWN_AND_UP) for i in range(3): self.device.drag((190, 770), (190, 130),0.1, 5) mr.sleep(1.0) for i in range(5): self.device.drag((190, 130), (190, 770),0.1, 5) print "case_order_drag"
def press_button(self, id): try: self.easyDevice.touch(By.id('id/' + id), MonkeyDevice.DOWN_AND_UP) self.insert_sleep() except Exception, e: print('Button was not found,saving snapshot of the screen') self.save_snapshot( 'button_not_found' + str(self.err_snapshot_count), 'png') self.err_snapshot_count += 1 raise e
def get_balance(): global device global eDevice global hViewer global LOG server_position = [] server_position.append((420, 600)) #左下角第一个 目前30 server_position.append((950, 600)) #右下角第二个 目前6 server_position.append((420, 420)) #中间左 目前198 server_position.append((950, 420)) #中间右 目前98 server_position.append((420, 230)) #上左 目前588 server_position.append((950, 230)) #上右 目前328 while 1: try: device.drag(server_position[0], server_position[5], 1, 1) time.sleep(1) device.drag(server_position[0], server_position[5], 1, 1) time.sleep(1) device.drag(server_position[0], server_position[5], 1, 1) time.sleep(3) device.touch(server_position[1][0], server_position[1][1], 'DOWN_AND_UP') time.sleep(3) device.touch(640, 510, 'DOWN_AND_UP') #标准充值按钮位置 break except: print('?') time.sleep(3) while 1: if hViewer.getFocusedWindowName( ) == 'com.vivo.sdkplugin/com.vivo.unionsdk.ui.UnionActivity' and eDevice.visible( By.id('id/vivo_payment_order_balance')) and eDevice.visible( By.id('id/vivo_payment_order_price')) and eDevice.visible( By.id('id/vivo_payment_btn_submit')): v = hViewer.findViewById('id/vivo_payment_order_balance') balance_price_result = hViewer.getText(v) print(re.sub("\D", "", balance_price_result)) LOG = LOG + '剩余金额' + str(re.sub("\D", "", balance_price_result)) + '\n' break
def cloudsimOnOff(i): print("-------------cloudsim On or Off-------------") device.wake() easy_device.touch(By.id('id/tb_cloudsim_on_off'),MonkeyDevice.DOWN_AND_UP) if i%2 == 0: MonkeyRunner.sleep(5) else: MonkeyRunner.sleep(60) cloudsimResult=device.takeSnapshot() cloudsimResult.writeToFile(simtakeSnapshotPath+'cloudsimResult'+str(i)+'.png','png')
def testAddContact(device,easy_device): easy_device.touch(By.id("id/addContactButton"),MonkeyDevice.DOWN_AND_UP); MonkeyRunner.sleep(1); print("click successfully!"); easy_device.touch(By.id("id/contactNameEditText"), MonkeyDevice.DOWN_AND_UP); print("try to input some words!"); MonkeyRunner.sleep(1); device.type("monkeyrunner"); print("input successfully!"); easy_device.touch(By.id("id/contactEmailEditText"),MonkeyDevice.DOWN_AND_UP); print("try to input some words!"); MonkeyRunner.sleep(1); device.type("*****@*****.**"); print("input successfully!"); easy_device.touch(By.id("id/contactSaveButton"),MonkeyDevice.DOWN_AND_UP); print("save successfully!"); MonkeyRunner.sleep(1); result =device.takeSnapshot(); result.writeToFile('D:\\workspace\\TestScript\\demo-monkeyrunner\\contact.png');
def auto_teach(i): easy_device = emd(device) device.press('KEYCODE_DPAD_DOWN', 'DOWN_AND_UP') mr.sleep(2) if i == 1: easy_device.touch(By.id('id/tv_standard'), md.DOWN_AND_UP) # (第一次下载APP后打开APP需要这个代码) easy_device.touch(By.id('id/title_bar_iv_left'), md.DOWN_AND_UP) easy_device.touch(By.id('id/tv_myCoin'), md.DOWN_AND_UP) easy_device.touch(By.id('id/tv_sign_in'), md.DOWN_AND_UP) easy_device.touch(By.id(''), md.DOWN_AND_UP) else: easy_device.touch(By.id('id/title_bar_iv_left'), md.DOWN_AND_UP) easy_device.touch(By.id('id/tv_myCoin'), md.DOWN_AND_UP) easy_device.touch(By.id('id/tv_sign_in'), md.DOWN_AND_UP) easy_device.touch(By.id(''), md.DOWN_AND_UP)
def addContact(name, phoneNumber): device.startActivity( component='com.android.contacts/.activities.PeopleActivity') MonkeyRunner.sleep(3) if easy_device.visible(By.id('id/create_contact_button')): trace('add contact first time') addFirstContact() elif easy_device.visible(By.id('id/menu_add_contact')): trace("Location of add contact menu:" + str(easy_device.locate(By.id('id/menu_add_contact')))) easy_device.touch(By.id('id/menu_add_contact'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(7) else: raise Error('Could not find the "menu_add_contact" button') addContactDetail(name, phoneNumber)
def touchByMonkeyId(self,id): # print '------------ touchByMonkeyId %s -------------' % id try: self.screenUsing = 1 self.easy_device.touch(By.id(id), self.easy_device.DOWN_AND_UP) sleep(0.5) self.screenUsing = 0 return 0 except: print 'Error : failed to dump view : %s !' % id return -1
def logoutUser(): print("-------------logoutUser-------------") device.wake() #logout user # device.touch(659,114,"DOWN_AND_UP") easy_device.touch(By.id('id/tv_home_loginOrExit'),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(3) device.wake() device.touch(580,765,"DOWN_AND_UP") endResult=device.takeSnapshot() endResult.writeToFile(takeSnapshotPath+'endResult'+str(cont)+'.png','png')
def select_menu(self, item,id = "id/title"): """select menu option. argv: (str)item -- option display in menu list. return void author: Zhihao.Gu """ self._logger.debug("Select menu option: %s." % item) self._device.press("KEYCODE_MENU", MDAU) MonkeyRunner.sleep(1) self._easy_device.touchtext(By.id(id), item, MDAU) MonkeyRunner.sleep(1)
def select_menu(self, item, id="id/title"): """select menu option. argv: (str)item -- option display in menu list. return void author: Zhihao.Gu """ self._logger.debug("Select menu option: %s." % item) self._device.press("KEYCODE_MENU", MDAU) MonkeyRunner.sleep(1) self._easy_device.touchtext(By.id(id), item, MDAU) MonkeyRunner.sleep(1)
def serverPolicy(): runStartApp() mr.sleep(2) easy_device.touch(By.id('id/iv_avatar'), md.DOWN_AND_UP) mr.sleep(1) device.touch(348, 880, 'DOWN_AND_UP') mr.sleep(5) image = device.takeSnapshot() mr.sleep(2) image.writeToFile('/Users/apple/auto_test/AutoImage/TeamServer1.png', 'png') result = mr.loadImageFromFile( '/Users/apple/auto_test/AutoImage/TeamServer.png', 'png') if image.sameAs(result, 1): print("the team server page match right") else: print( "there is a problem here,please check , and the number is: the team server page" ) mr.sleep(2) easy_device.touch(By.id('id/title_bar_iv_left'), md.DOWN_AND_UP) mr.sleep(1) device.touch(571, 880, 'DOWN_AND_UP') mr.sleep(5) image = device.takeSnapshot() mr.sleep(2) image.writeToFile('/Users/apple/auto_test/AutoImage/PrivacyPolicy1.png', 'png') result = mr.loadImageFromFile( '/Users/apple/auto_test/AutoImage/PrivacyPolicy.png', 'png') if image.sameAs(result, 1): print("the privacy policy page match right") else: print( "there is a problem here,please check , and the number is: the privacy policy page" )
def jisuanji(): # 滑动解锁 jiesuo() # 打开计算器 device.startActivity(component="com.tencent.qrom.calculator/com.tencent.qrom.calculator.Calculator") time.sleep(1) print ("ok") # 将device对象包装成EasyMonkeyDevice类对象 ed = EasyMonkeyDevice(device) print ("okok") # 96*3= ed.touch(By.id("id/digit9"), MonkeyDevice.DOWN_AND_UP) ed.touch(By.id("id/digit6"), MonkeyDevice.DOWN_AND_UP) ed.touch(By.id("id/mul"), MonkeyDevice.DOWN_AND_UP) ed.touch(By.id("id/digit3"), MonkeyDevice.DOWN_AND_UP) ed.touch(By.id("id/equal"), MonkeyDevice.DOWN_AND_UP) print ("ok2") # 通过ID获取mText h = ed.getText(By.id("id/digit9")) print (h)
def case_coupon_consume(self): mr.sleep(1.0) self.easy_device.touch(By.id("id/coupon_consume"), md.DOWN_AND_UP) self.easy_device.touch(By.id("id/rl_manually_consume"), md.DOWN_AND_UP) self.easy_device.touch(By.id("id/coupon_consume_phone"), md.DOWN_AND_UP) self.device.type(self.data[2]) self.easy_device.touch(By.id("id/btn_manually_consume"), md.DOWN_AND_UP) self.easy_device.touch(By.id("id/coupon_name"), md.DOWN_AND_UP) self.easy_device.touch(By.id("id/coupon_use"), md.DOWN_AND_UP) self.easy_device.touch(By.id("id/dialog_positive"),md.DOWN_AND_UP) print "case_coupon_consume"
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 testlogin(): import codecs codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) device = MonkeyRunner.waitForConnection() easyMonkey = EasyMonkeyDevice(device) print ("Test start") # 启动应用Activity device.shell('am start dong.sqlite.order/dong.sqlite.order.MainActivity') MonkeyRunner.sleep(3) # 输入账号 print ("Start typing user name and password") by_name = By.id("id/username") easyMonkey.type(by_name,'zdd') MonkeyRunner.sleep(1) # 输入密码 by_psd = By.id('id/userpwd') easyMonkey.type(by_psd,"my_psd") MonkeyRunner.sleep(1) device.press('KEYCODE_BACK') MonkeyRunner.sleep(1) # 点击登录 by_save = By.id('id/btn_save') easyMonkey.touch(by_save,MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(2) print ("Click the read button") by_read = By.id('id/btn_read') easyMonkey.touch(by_read,MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) device.press('KEYCODE_BACK') print ("Test end")
def safeTouch(easydevice, viewid, touchtype, maxtrycount): if viewid.startswith('id/'): log('viewid starts with "id/", please correct it...') trycount = 0 while True: try: easydevice.touch(By.id('id/' + viewid), MonkeyDevice.DOWN_AND_UP) break except: print "Failed to touch " + viewid + " " + str(trycount) + " times" trycount = trycount + 1 MonkeyRunner.sleep(1.0) if trycount >= maxtrycount: break
def wait_for_exists(self,node_id,step,times): """Waits a specified length of steps× for a UI element or packetage to become visible.""" maxTime = 0 if str(node_id).find("id"): while (not self._easy_device.visible(By.id(node_id))) and maxTime <= times: maxTime = maxTime + 1 self._logger.debug("Wait for skip...") MonkeyRunner.sleep(step) if maxTime > times: self._logger.warning("can't enter the designated page") return False else : self._logger.debug("Enter designated Page Successfully") return True else: pass
def safeType(easydevice, viewid, typevalue, maxtrycount): if viewid.startswith('id/'): log('viewid starts with "id/", please correct it...') trycount = 0 while True: try: easydevice.type(By.id('id/' + viewid), typevalue) break except: print "Failed to type " + viewid + ", value: " + typevalue + ", " + str( trycount) + " times" trycount = trycount + 1 MonkeyRunner.sleep(1.0) if trycount >= maxtrycount: break
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 mr_test_demo_for_easydevice(): print 'test apis for easydevice.' device = get_monkey_device() easy_device = EasyMonkeyDevice(device) # launcher home page # device.press('KEYCODE_HOME') # mr.sleep(1) # easy_device.touch(By.id('id/title'), MonkeyDevice.DOWN_AND_UP) # mr.sleep(1) # device.press('KEYCODE_ENTER') # mr.sleep(5) # film list page # tab_title_text = easy_device.getText(By.id('id/tab_title')) # print tab_title_text.encode('utf8') # touch on card of right area easy_device.touch(By.id('id/subtitle'), MonkeyDevice.DOWN_AND_UP) mr.sleep(1)
#python中获取当前运行的文件的名字 name=sys.argv[0].split("\\") filename=name[len(name)-1] #新建一个log文件 log=open(logpath+filename[0:-3]+"-log"+now+".txt",'w') #连接设备,两个参数分别是等待的时间(这里的时间都是秒为单位),设备的序列号。169.254.105.102:5555 device device=MonkeyRunner.waitForConnection() easy_device = EasyMonkeyDevice(device) #启动activity device.startActivity(component='com.android.calculator2/.Calculator') MonkeyRunner.sleep(3) #通过坐标执行1+2并截图 #device.touch(156,1354,'DOWN_AND_UP') easy_device.touch(By.id('id/digit1'),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) result1=device.takeSnapshot() result1.writeToFile(path+"button-1"+'.png','png') #device.touch(900,1604,'DOWN_AND_UP') easy_device.touch(By.id('id/plus'),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) result2=device.takeSnapshot() result2.writeToFile(path+"button-add"+'.png','png') #device.touch(396,1354,'DOWN_AND_UP') easy_device.touch(By.id('id/digit2'),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1) result3=device.takeSnapshot() result3.writeToFile(path+"button-2"+'.png','png')
hello = vc.findViewById('id/hello') if hello: if hello.getText() == "Hello Donald": print "OK" else: print "FAIL" else: print >> sys.stderr, "'hello' not found" else: print >> sys.stderr, "'Show Dialog' button not found" else: # MonkeyRunner from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By easyDevice = EasyMonkeyDevice(device) showDialogButton = By.id('id/show_dialog_button') if showDialogButton: easyDevice.touch(showDialogButton, MonkeyDevice.DOWN_AND_UP) ViewClient.sleep(3) editText = By.id('id/0x123456') print editText easyDevice.type(editText, 'Donald') ViewClient.sleep(3) ok = By.id('id/button1') if ok: # 09-08 20:16:41.119: D/MonkeyStub(1992): translateCommand: tap 348 268 easyDevice.touch(ok, MonkeyDevice.DOWN_AND_UP) hello = By.id('id/hello') if hello: if easyDevice.getText(hello) == "Hello Donald": print "OK"
def case_order_accept(self): mr.sleep(1.0) self.easy_device.touch(By.id("id/accept"),md.DOWN_AND_UP) #self.easy_device.touch(By.id("id/toolbar_back"), md.DOWN_AND_UP) print "case_order_accept"
def case_order_complete(self): mr.sleep(1.0) self.easy_device.touch(By.id("id/complete"),md.DOWN_AND_UP) print "case_order_complete"
def case_order_failure(self): mr.sleep(1.0) self.easy_device.touch(By.id("id/failure"),md.DOWN_AND_UP) mr.sleep(1.0) self.device.touch(400,222,md.DOWN_AND_UP) print "case_order_failure"
def case_order_reject(self): mr.sleep(1.0) self.easy_device.touch(By.id("id/reject"),md.DOWN_AND_UP) mr.sleep(1.0) self.device.touch(357,494,md.DOWN_AND_UP) print "case_order_reject"
def visible(self, viewId): self.easyDevice.visible(By.id(viewId))
def touchByViewId(self, viewId): self.easyDevice.touch(By.id(viewId), MonkeyDevice.DOWN_AND_UP)
def switch_network(self,type = None): """switch network to specified type. argv: (str)type -- the type of network. author: Leping.Zheng """ self._logger.debug("Switch network to %s." % (type)) if not self.start_app("com.android.settings/com.android.settings.RadioInfo"): self._logger.warning("Cannot launch activity to switch network.") return False if not type in ('2G','3G','LTE','All'): self._device.press("KEYCODE_BACK", MonkeyDevice.DOWN_AND_UP) self._logger.warning("Wrong argument: %s." % (type)) return False if type == '2G': text_type = 'GSM only' elif type == '3G': text_type = 'WCDMA only' elif type == 'LTE': text_type = 'LTE only' elif type == 'All': text_type = 'LTE/GSM/CDMA auto (PRL)' smsc_node = self.get_node('id/smsc') if smsc_node is None: self._logger.warning("Cannot find node 'id/smsc'.") raise TypeError("Cannot get node 'id/smsc'.") if smsc_node.namedProperties.get('isFocused').value == 'true': self._logger.debug("Exist input method.") self._device.press("KEYCODE_BACK", MDAU) MonkeyRunner.sleep(1) self._device.drag((400,700),(400,100),0.1,10) MonkeyRunner.sleep(1) self._device.drag((400,700),(400,100),0.1,10) MonkeyRunner.sleep(1) netmode_node = self.get_node('id/text1') if netmode_node is None: self._device.press("KEYCODE_BACK",MonkeyDevice.DOWN_AND_UP) self._logger.warning("Cannot find node 'id/text1'.") raise TypeError("Cannot get node 'id/text1'.") netmode_text = self._hierarchyviewer.getText(netmode_node) netmodepos = self._hierarchyviewer.getAbsoluteCenterOfView(netmode_node) if text_type not in netmode_text: self._device.touch(netmodepos.x,netmodepos.y,MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(2) self._device.drag((400,400),(400,1000),0.1,10) self._device.drag((400,400),(400,1000),0.1,10) MonkeyRunner.sleep(1) if text_type == 'GSM only' or text_type == 'WCDMA only': pass else: self._device.drag((400,900),(400,400),0.5, 4) MonkeyRunner.sleep(1) self._easy_device.touchtext(By.id("id/text1"),text_type,MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(3) j = 0 if type == 'All': config = GetConfigs("common") support = config.getstr("Default","NETWORK_TYPE","common") if "LTE" in support: type = "LTE" else: type = "3G" while self.get_data_service_state() != type and j < 5: MonkeyRunner.sleep(4) j += 1 if j == 5: self._logger.warning("Cannot get %s service." % (type)) self._device.press("KEYCODE_BACK",MonkeyDevice.DOWN_AND_UP) return False else: max_time = 0 while not self.get_data_connected_status(): MonkeyRunner.sleep(4) max_time += 1 if (max_time) > 10: self._logger.warning("Cannot connect %s data." % (type)) self._device.press("KEYCODE_BACK",MonkeyDevice.DOWN_AND_UP) return False self._logger.debug("Switch network to %s." % (type)) self._device.press("KEYCODE_BACK",MonkeyDevice.DOWN_AND_UP) return True
from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By s = 'OpenSudoku' views = [('cz.romario.opensudoku/cz.romario.opensudoku.gui.FolderListActivity','get_more_puzzles')] #view = 'get_more_puzzles' device = MonkeyRunner.waitForConnection() easy_device = EasyMonkeyDevice(device) for view in views: sourceActivity = view[0] v = view[1] easy_device.startActivity(sourceActivity) MonkeyRunner.sleep(3.0) result1 = device.takeSnapshot() result1.writeToFile('./'+v+'1.png','png') easy_device.touch(By.id('id/'+v),MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(3.0) result = device.takeSnapshot() result.writeToFile('./'+v+'2.png','png')