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)
class MonkeyWrapImpl(): def waitForConnection(self): self.device = MonkeyRunner.waitForConnection() self.initEasyDevice() def startActivity(self, runComponent): self.device.startActivity(component=runComponent) def initEasyDevice(self): self.easyDevice = EasyMonkeyDevice(self.device) def touchByViewId(self, viewId): self.easyDevice.touch(By.id(viewId), MonkeyDevice.DOWN_AND_UP) def visible(self, viewId): self.easyDevice.visible(By.id(viewId)) def touch_down(self, x, y): self.device.touch(x, y, MonkeyDevice.DOWN) def touch_up(self, x, y): self.device.touch(x, y, MonkeyDevice.UP) def touch_down_and_up(self, x, y): self.device.touch(x, y, MonkeyDevice.DOWN_AND_UP) def press_menu_down_and_up(self): self.device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP) def press_power_down_and_up(self): self.device.press('KEYCODE_POWER', MonkeyDevice.DOWN_AND_UP) def drag(self, sx, sy, ex, ey, duration, steps): self.device.drag((sx, sy), (ex, ey), duration, steps) def wakeup(self): self.device.wake() def sleep(self, sec): MonkeyRunner.sleep(sec) def takeAndSaveSnapshot(self, savaPath, type): img = self.device.takeSnapshot() img.writeToFile(savaPath, type) def screenWidth(self): # w = self.device.getProperty('width') # print('width=' + w) # return w; return 720 def screenHeight(self): # h = self.device.getProperty('height') # return h; return 1280 def __init__(self): '''
class DeviceHandler(): package = 'com.rehivetech.beeeon.debug' main_activity = 'com.rehivetech.beeeon.gui.activity.LoginActivity' apk_path = '../../../artifacts/app-debug.apk' def __init__(self, insert_sleeps=True): print("Waiting for device") self.device = MonkeyRunner.waitForConnection() self.easyDevice = EasyMonkeyDevice(self.device) self.insert_sleeps = insert_sleeps self.device.press('KEYCODE_HOME', MonkeyDevice.DOWN_AND_UP) kill_command = 'am force-stop %s' % DeviceHandler.package self.device.shell(kill_command) self.insert_sleep(time=3) self.err_snapshot_count = 0 apk_path = self.device.shell('pm path ' + DeviceHandler.package) if apk_path.startswith('package:'): print "BeeeOn already installed,but I am gonna reinstall it to test the newest version" self.device.installPackage(DeviceHandler.apk_path) else: print "BeeeOn not installed, installing APKs..." self.device.installPackage(DeviceHandler.apk_path) # sets the name of the component to start runComponent = DeviceHandler.package + '/' + DeviceHandler.main_activity print("Starting activity " + runComponent) # Runs the component self.device.startActivity(component=runComponent) self.insert_sleep() def insert_sleep(self, time=3): if self.insert_sleep: MonkeyRunner.sleep(time) 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
class MonkeyWrapImpl(): def waitForConnection(self): self.device = MonkeyRunner.waitForConnection() self.initEasyDevice() def startActivity(self,runComponent): self.device.startActivity(component=runComponent) def initEasyDevice(self): self.easyDevice = EasyMonkeyDevice(self.device); def touchByViewId(self,viewId): self.easyDevice.touch(By.id(viewId),MonkeyDevice.DOWN_AND_UP) def visible(self,viewId): self.easyDevice.visible(By.id(viewId)) def touch_down(self,x,y): self.device.touch(x,y,MonkeyDevice.DOWN) def touch_up(self,x,y): self.device.touch(x,y,MonkeyDevice.UP) def touch_down_and_up(self,x,y): self.device.touch(x,y,MonkeyDevice.DOWN_AND_UP) def press_menu_down_and_up(self): self.device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP) def press_power_down_and_up(self): self.device.press('KEYCODE_POWER', MonkeyDevice.DOWN_AND_UP) def drag(self,sx,sy,ex,ey,duration,steps): self.device.drag((sx,sy),(ex,ey),duration,steps); def wakeup(self): self.device.wake() def sleep(self,sec): MonkeyRunner.sleep(sec); def takeAndSaveSnapshot(self,savaPath,type): img = self.device.takeSnapshot() img.writeToFile(savaPath,type) def screenWidth(self): # w = self.device.getProperty('width') # print('width=' + w) # return w; return 720; def screenHeight(self): # h = self.device.getProperty('height') # return h; return 1280; def __init__(self): '''
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)
class MyMonkeyRunner: idSearchStr = 'id/top_view_search' idMainBarStr = 'id/main_bar' def getDevice(self): self.dev = MonkeyRunner.waitForConnection() return self.dev def getEasyDevice(self, dev): self.eDevice = EasyMonkeyDevice(dev) return self.eDevice def getHierarchyViewer(self): self.hDevice = self.dev.getHierarchyViewer() return self.hDevice def touchByID(self, id): self.eDevice.touch(By.id(id), MonkeyDevice.DOWN_AND_UP)
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)
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 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'
class MonkeyLib: def __init__(self, apk, package, mainActivity, runActivity, bundle): # Connects to the current device, returning a MonkeyDevice object self.device = MonkeyRunner.waitForConnection() self.easy_device = EasyMonkeyDevice(self.device) self.apk = apk self.package = package self.bundle = bundle self.main = self.component(package, mainActivity) self.run = self.component(package, runActivity) def component(self, package, activity): return package + '/' + activity # I N S T A L L / U N I N S T A L L def install(self): # Installs the Android package. Notice that this method returns a boolean, so you can test to see if the installation worked. print('INSTALL APP ' + self.apk) self.device.installPackage(self.apk) def remove(self): print('REMOVE APP ' + self.package) self.device.removePackage(self.package) # S Y N C 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 sleep(self, s): MonkeyRunner.sleep(s) # A C T I V I T Y def mainActivity(self): print('MAIN') self.device.startActivity(component=self.main) self.sleep(3) def activity(self): print('ACTIVITY ' + str(self.run)) self.device.startActivity(component=self.run) self.sleep(3) def activity2(self, action, extras): print('ACTIVITY ' + str(self.run) + ' extras:' + str(extras)) extras.update(self.bundle) self.device.startActivity(component=self.run, action=action, extras=extras) self.sleep(3) def kill(self): print('KILL') self.device.shell('am force-stop ' + self.package) # S E A R C H 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) # K E Y B O A R D E V E N T S def pressKey(self, k): print('PRESS ' + k) self.device.press(k, MonkeyDevice.DOWN_AND_UP) def back(self): print('BACK') pressKey('KEYCODE_BACK') # T O U C H E V E N T S def touch(self, id): print('TOUCH ' + id) bid = By.id(id) self.easy_device.touch(bid, MonkeyDevice.DOWN_AND_UP) def touchView(self, vn): print('TOUCH ' + str(vn)) p = self.device.getHierarchyViewer().getAbsoluteCenterOfView(vn) self.device.touch(p.x, p.y, MonkeyDevice.DOWN_AND_UP) def touchout(self): print('TOUCHOUT') self.device.touch(10, 100, MonkeyDevice.DOWN_AND_UP) def drag(self): print('DRAG') self.device.drag((600, 400), (300, 200), 2, 10) #self.sleep(3) # T R A V E R S A L def traverseFrom(self, start, process): process(start) if start.children != None: for node in start.children: self.traverseFrom(node, process) def rtraverseFrom(self, start, process): process(start) if start.children != None: for node in reversed(start.children): self.rtraverseFrom(node, process) def ytraverse(self, node): yield node if node.children != None: for child in node.children: for node2 in self.ytraverse(child): yield node2 def ytraverseFrom(self, start, process): for node in self.ytraverse(start): if process(node): break def yrtraverse(self, node): yield node if node.children != None: for child in reversed(node.children): for node2 in self.yrtraverse(child): yield node2 def yrtraverseFrom(self, start, process): for node in self.yrtraverse(start): if process(node): break # V I E W S def findViewById(self, id): return self.device.getHierarchyViewer().findViewById(id) #def findViewById2(self,id): # By.id(id).findView(self.device.getHierarchyViewer()) def getViewIds(self): return self.device.getViewIdList() # I M A G I N G def snapshot(self): # Takes a screenshot: a MonkeyImage return self.device.takeSnapshot() def toFile(self, shot, fname): # Writes the screenshot to a file shot.writeToFile('shot-' + fname + '.png', 'png')
# init param wait_app_launch = 3 wait_button_time = 1 wait_cmd_time = 2 test_vt_time = 20 MonkeyRunner.sleep(wait_cmd_time) # launch VT working app print 'Launch Engineering Working Menu' os.popen( 'adb shell "am start -a android.intent.action.MAIN -n com.mediatek.engineermode/.videotelephone.WorkingMode"' ) MonkeyRunner.sleep(wait_app_launch) easy_device.touch(By.id("id/working_mode_media_loopback"), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(wait_button_time) easy_device.touch(By.id("id/media_loopback_stack"), MonkeyDevice.DOWN_AND_UP) #MonkeyRunner.sleep(wait_button_time); # MonkeyRunner.sleep(wait_app_launch); # print 'launch VT Activity' # os.popen('adb shell "am start -a com.android.vt.VTLoopbackActivity.LAUNCH -n com.android.phone/.VTLoopbackActivity"') # Launch VT Lookback Activity # os.popen('adb shell "am start -a com.android.vt.VTLoopbackActivity.LAUNCH -n com.android.phone/.VTLoopbackActivity"') # #os.popen('adb shell "am start -a com.android.vt.VTLoopbackActivity.MAIN -n com.android.phone/.VTLoopbackActivity"') # #os.popen('adb shell "am start -a android.intent.action.MAIN -n com.android.phone/.VTLoopbackActivity"') # # am start -a android.intent.action.MAIN -n com.android.phone/.VTLoopbackActivity
class MonkeyDaemon(object): def __init__(self, qq): print '-------- MonkeyDaemon __init__ ---------' self.qq = qq # self.emulator = { # 'width':1080, # 'height':1920, # 'qqStart':[150,1650], # 'qqName':[75,150], # 'msgs':[200,1700], # 'contacts':[500,1700], # 'groups':[700,500], # 'myGroups':[300,300], # 'info':[1000,150], # 'heartbeat':[430,150], # 'paste':[270,1590], # 'leave':[150,150], # 'self_msg':'930', # } self.emulator = { 'width':480, 'height':800, 'qqStart':[50,750], 'qqName':[40,75], 'msgs':[80,750], 'contacts':[240,750], 'groups':[300,230], 'myGroups':[100,150], 'info':[450,75], 'heartbeat':[200,75], 'paste':[150,725], 'leave':[60,70], 'input':[200,760], 'send':[430,760], 'self_msg':'404', } self.path_dict = { 'is_grouplist':{ 'is_main' : ['contacts','groups'], 'is_grouplist': 'leave', # 重新进入grouplist 'is_group': 'leave', 'is_info' : 'leave', }, 'is_group':{ 'is_main': 'is_grouplist', 'is_grouplist':'enter_group', 'is_group': None, 'is_info': 'leave', }, 'is_info':{ 'is_main': 'is_grouplist', 'is_grouplist':'enter_group', 'is_group': 'info', 'is_info': None, }, 'is_main':{ 'is_home_screen': 'qqStart', 'is_main': None, 'is_grouplist': 'leave', 'is_group': 'leave', 'is_info': 'leave', }, } # add a api to get pure group list, on-going self.screenUsing = 0 self.groupListUpdating = 0 self.heartbeat = 0 # {drag, index, groupId, groupName, UILocation, msgs, storedMsgs} self.groupList = {} # already in this group self.currentGroup = { 'groupId': '', 'groupName': '', 'UILocation': '', 'msgs': [], 'storedMsgs': [] } self.monkey_set_up() if self.restart_qq_monkey() != 0: sys.exit(-1) if self.get_qqName_monkey() != 0: sys.exit(-1) if self.get_grouplist() != 0: self.get_pure_group_list_monkey() if self.groupList != {}: self.write_grouplist() self.register_monkey() def monkey_set_up(self): print '------------ monkey_set_up -------------' self.device = MonkeyRunner.waitForConnection(5, self.qq['deviceid']) self.easy_device = EasyMonkeyDevice(self.device) sleep(0.5) if not self.device or not self.easy_device: print "Error : monkey_set_up failed !" sys.exit(-1) return 0 ### basic check steps ### # decorator to check qq status def check_qq_status(func): def new_func(self): print '------------ check qq status ------------' ret = self.is_home_screen() if ret == 0: return func(self) else: print "Error : QQ status is not correct !" return -1 return new_func def is_screen_lock(self): try: if 'Keyguard' not in self.get_focus_window_name(): return 0 else: self.screenUsing = 1 self.device.drag((240, 550),(450, 550),0.2,1) self.screenUsing = 0 except: print "Error : failed to get focus window name Keyguard !" return -1 def is_home_screen(self): try: if 'Launcher' in self.get_focus_window_name(): return 0 except: print "Error : failed to get focus window name Launcher !" return 1 def is_main(self): try: if 'SplashActivity' in self.get_focus_window_name(): return 0 except: print "Error : failed to get focus window name SplashActivity !" return 1 def is_group(self): try: if 'ChatActivity' in self.get_focus_window_name(): return 0 except: print "Error : failed to get focus window name ChatActivity !" return 1 def is_info(self): try: if 'ChatSettingForTroop' in self.get_focus_window_name(): return 0 except: print "Error : failed to get focus window name ChatSettingForTroop !" return 1 def is_grouplist(self): try: if 'TroopActivity' in self.get_focus_window_name(): return 0 except: print "Error : failed to get focus window name TroopActivity !" return 1 def is_current_group(self): # 暂时没有用到,以后单口的时候可能会用到。 # print '------------ is_current_group ------------' print "Info : current group : %s !" % self.currentGroup['groupId'] groupId = '' if self.is_group() == 0: groupId = self.get_group_id() if self.currentGroup['groupId'] == groupId: return 0 else: print "Info : I am not in current group %s, but %s !" % \ (self.currentGroup['groupId'], groupId) return -1 else: return 1 ### basic check steps ### ### basic monkey operations ### def get_hierarchy_view_by_id(self,id): try: hViewer = self.device.getHierarchyViewer() view = hViewer.findViewById(id) return view except: return None def get_focus_window_name(self): try: hViewer = self.device.getHierarchyViewer() window_name = hViewer.focusedWindowName return window_name except: return '' def get_current_view(self): window_name = self.get_focus_window_name() if 'ChatActivity' in window_name: ### NoneType' object is not iterable return 'is_group' elif 'TroopActivity' in window_name: return 'is_grouplist' elif 'SplashActivity' in window_name: return 'is_main' elif 'ChatSettingForTroop' in window_name: return 'is_info' elif 'Launcher' in window_name: return 'is_home_screen' else: return '' def goto_window(self,dest): print "------------ goto_window %s" % dest current_view = self.get_current_view() while( current_view != dest ): action = self.path_dict[dest][current_view] if callable(action): action() elif 'is_' in action: pass # action = self.path_dict[dest][current_view] elif type(action) is list: for i in action: self.touchByMonkeyPixel(self.emulator[i]) else: self.touchByMonkeyPixel(self.emulator[action]) sleep(1) current_view = self.get_current_view() return 0 # decorator to wait screen def touch_wait_screen(func): def new_func(self, *args): if self.screenUsing == 1: print "Info : self.screenUsing == 1 !" # sleep(1) return func(self, *args) return new_func def drag_to_page_down(self): try: # self.device.shell("input keyevent KEYCODE_PAGE_DOWN") # self.device.press('KEYCODE_PAGE_DOWN','DOWN_AND_UP','') self.device.drag((480/2, 710),(480/2, 130),0.2,1) except: print "Error : failed to drag_to_page_down !" return -1 def drag_to_page_up(self): try: # self.device.shell("input keyevent KEYCODE_PAGE_UP") # self.device.press('KEYCODE_PAGE_UP','DOWN_AND_UP','') self.device.drag((480/2, 130),(480/2, 710),0.2,1) except: print "Error : failed to drag_to_page_up !" return -1 def touch_to_enter_home_screen(self): self.device.press('KEYCODE_HOME','DOWN_AND_UP','') while(self.is_home_screen() != 0): self.device.press('KEYCODE_HOME','DOWN_AND_UP','') # @touch_wait_screen def touch_to_leave(self): try: self.touchByMonkeyPixel(self.emulator['leave']) return 0 except: print "Error : failed to touch_to_leave !" return 1 def touch_to_enter_main(self): # 先回到chatlist或contacts return self.goto_window('is_main') # @touch_wait_screen def touch_to_enter_group(self): return self.goto_window('is_group') # @touch_wait_screen def touch_to_enter_info(self): return self.goto_window('is_info') # @touch_wait_screen # 换另外一个group,要重新进入grouplist def touch_to_enter_grouplist(self): return self.goto_window('is_grouplist') # @touch_wait_screen def touch_to_enter_msgs(self): if self.touch_to_enter_main() == 0: if self.touchByMonkeyPixel(self.emulator['msgs']) == 0: return self.touchByMonkeyPixel(self.emulator['msgs']) # @touch_wait_screen def touch_to_enter_contacts(self): # 不把touch_to_enter_main()判断放在里边,是为了单独处理QQ restart闪退情况。 if self.touchByMonkeyPixel(self.emulator['contacts']) == 0: return self.touchByMonkeyPixel(self.emulator['contacts']) else: print "Error : failed to touch_to_enter_contacts !" return -1 # @touch_wait_screen def touchByMonkeyPixel(self,point): # print '------------ touchByMonkeyPixel %s %s -------------' % (x,y) try: self.screenUsing = 1 self.device.touch(point[0],point[1],'DOWN_AND_UP') sleep(0.5) self.screenUsing = 0 return 0 except: # sleep(1) return -1 # @touch_wait_screen 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 getTextByMonkeyView(self,view): # print '------------ getTextByMonkeyView %s -------------' % view try: return view.namedProperties.get('text:mText').value.encode('utf8') except: # images print 'Error : failed to find text for view : %s !' % view return '' def getDescByMonkeyView(self,view): # print '------------ getDescByMonkeyView %s -------------' % view try: return view.namedProperties.get('accessibility:getContentDescription()').value.encode('utf8') except: # images print 'Error : failed to find desc for view : %s !' % view return '' ### basic monkey operations ### def restart_qq_monkey(self): print '------------ restart_qq_monkey -------------' while(self.is_home_screen()==0): # self.touch_to_enter_home_screen() self.touchByMonkeyPixel(self.emulator['qqStart']) sleep(3) # 一开始启动,QQ闪退的情况 if self.is_main() == 0: self.touch_to_enter_contacts() # 点击联系人,QQ闪退的情况 sleep(2) print "Info : qq has been restarted correctly !" return 0 # @check_qq_status def get_qqName_monkey(self): print '------------ get_qqName_monkey ------------' self.touch_to_enter_msgs() # self.device.drag((300, 150),(1000, 150),0.2,1) self.touchByMonkeyPixel(self.emulator['qqName']) nickname = self.get_hierarchy_view_by_id('id/nickname') self.qq['qqName'] = self.getTextByMonkeyView(nickname) self.device.drag((410, 70),(150, 70),0.2,1) if self.qq['qqName']: print "Info : qq name is %s !" % self.qq['qqName'] return 0 return -1 def get_grouplist(self): if not os.path.isfile(self.qq['grouplistfile']): return 1 f = open(self.qq['grouplistfile'],'r') self.groupList = json.loads(f.read()) f.close() return 0 def write_grouplist(self): if not os.path.isfile(self.qq['grouplistfile']): os.system('touch %s' % self.qq['grouplistfile']) f = open(self.qq['grouplistfile'],'w') f.write(json.dumps(self.groupList).encode('utf8')) f.close() return 0 def get_pure_group_list_monkey(self): print '------------ get_pure_group_list_monkey ------------' self.groupListUpdating = 1 if self.touch_to_enter_grouplist() != 0: return 1 for drag in range(0,10): print "Info : drag for %s time !" % drag if drag != 0: try: # self.device.drag((1080/2, 1700),(1080/2, 400),0.2,1) # self.device.drag((480/2, 750),(480/2, 190),0.2,1) self.drag_to_page_down() except: print "Error : failed for the %s drag !" % drag qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view') if qb_troop_list_view == None: continue _groupList = [] _groupList = qb_troop_list_view.children if _groupList == []: print "Error : failed to parse view qb_troop_list_view !" continue if drag == 0: # first one is the search box del _groupList[0] index = 0 for group in _groupList: index += 1 view = self.get_current_view() if view == 'is_group' or view == 'is_info': self.touch_to_enter_grouplist() # 我创建的群(16) 这样的一行 notGroup = self.getTextByMonkeyView(group.children[0]) if notGroup: # print "Info : this is not a group %s !" % notGroup continue groupNameView = group.children[1].children[2].children[1] item = { 'groupName': self.getTextByMonkeyView(groupNameView), 'drag':drag, # 363 is qb_troop_list_view.top, 156是整个一条group的高度。 # 78 / 182 'UILocation': group.top + 78/2 + 182, 'index':index, 'msgs': [], 'storedMsgs': [] } # 点击进入到群组会话中,去获取groupId # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。 # if item['UILocation'] < 370 or item['UILocation'] > 1760: if item['UILocation'] < 200 or item['UILocation'] > 760: print "Info : skip this group in case we touch screen incorrectly !" continue groupId = '' if self.touchByMonkeyPixel([self.emulator['width']/2,item['UILocation']]) == 0: if self.is_group() == 0: for i in range(0,3): groupId = self.get_group_id() if groupId == '': continue else: break if groupId == '': print "Error : failed to get the group id for group %s !" % \ item['groupName'] continue else: if groupId in self.groupList.keys(): print "Info : this group %s %s has already exist !" % \ (item['groupName'],groupId) continue self.groupList[groupId] = item print "Info : group info: %s , %s , %s , %s, %s !" % \ (item['groupName'],groupId,item['drag'],item['index'],item['UILocation']) while(self.is_grouplist() != 0): self.touch_to_leave() print "Info : total group count : %s !" % len(self.groupList) for key in self.groupList: print "Info : group info: %s , %s , %s , %s, %s !" % \ (self.groupList[key]['groupName'],key,self.groupList[key]['drag'], \ self.groupList[key]['index'],self.groupList[key]['UILocation']) self.groupListUpdating = 0 return 0 # 获取groupId,结束后仍退出至group 界面 def get_group_id(self): # 此时位于群组会话中,点击进入到群组信息里边 groupId = '' if self.touch_to_enter_info() != 0: return '' for i in range(0,3): try: xlist = self.get_hierarchy_view_by_id('id/common_xlistview') nameAndId = xlist.children[0].children[2].children[0].children[1] groupId = self.getTextByMonkeyView(nameAndId.children[1].children[0]) break except: print "Error : failed to get groupId !" continue print "Info : get this group id : %s !" % groupId if self.touch_to_enter_group() == 0: return groupId def get_group_members(self): group_members = [] is_stop_drag = 0 last_member = None while True: screen_members = self.extract_group_members() if last_member == screen_members[-1]: break last_member = screen_members[-1] group_members.extend(screen_members) self.drag_to_page_down() print "Info : group_members:",group_members return group_members def extract_group_members(self): screen_members = [] content = self.get_hierarchy_view_by_id('id/content') members_list = content.children[0].children[1].children[0].children list_top = 113 for member in members_list: if member.height != 79: list_top += member.height # 为管理员(4人),C(2人)之类的字样。72 / 33 continue member_location = list_top + 79/2 if member_location >= 800: continue self.touchByMonkeyPixel([240,member_location]) list_top += 79 qqid = self.get_member_id() if qqid in screen_members: continue screen_members.append(qqid) return screen_members def get_member_id(self): qqid = '' content = self.get_hierarchy_view_by_id('id/content') tmpqqid = '' try: tmpqqid = content.children[0].children[0].children[1].children[2].children[1].namedProperties.get('text:mText').value.encode('utf8') except: return '' qqid = tmpqqid.split(' ')[0] print "Info : get the member id %s !" % qqid self.touch_to_leave() sleep(1) return qqid def check_group_by_possible_location(self,target_group): target_group_name = self.groupList[target_group]['groupName'] possibleDrag = self.groupList[target_group]['drag'] possibleUILocation = self.groupList[target_group]['UILocation'] print "Info : possibleDrag %s , possibleUILocation %s to enter group %s !" % \ (possibleDrag, possibleUILocation, target_group) if possibleDrag > 0: for i in range(0,possibleDrag): self.drag_to_page_down() if self.touchByMonkeyPixel([self.emulator['width']/2,possibleUILocation]) == 0: if self.is_group() == 0: for i in range(0,3): groupId = '' groupId = self.get_group_id() if groupId == target_group: self.currentGroup['groupId'] = target_group self.currentGroup['groupName'] = target_group_name return 0 elif groupId != '': print "Info : get the incorrect groupid %s !" % groupId break else: print "Info : get the empty groupid !" continue print "Info : failed to enter group %s via possibleDrag %s , possibleUILocation %s !" % \ (target_group, possibleDrag, possibleUILocation) # 不是这个群,就退出至grouplist界面,然后查找一下当前界面的groups view = self.get_current_view() if view == 'is_group' or view == 'is_info': self.touch_to_enter_grouplist() if self.find_target_group_from_list(target_group) == 0: return 0 return 3 def find_target_group_from_list(self,target_group): print '------------ find_target_group_from_list ------------' if self.is_grouplist() != 0: return -1 target_group_name = self.groupList[target_group]['groupName'] # < 1s qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view') if qb_troop_list_view == None: return -1 _groupList = [] _groupList = qb_troop_list_view.children if _groupList == []: print "Error : failed to parse view qb_troop_list_view !" return -1 # first one is the search box # 通过高度来判断是否是group item(78)。 # 而enter_group时通过名字来查找,不需要此步 # del _groupList[0] for group in _groupList: # 我创建的群(16) 这样的一行 notGroup = self.getTextByMonkeyView(group.children[0]) if notGroup: continue # 先根据群名称来查找 groupNameView = group.children[1].children[2].children[1] groupName = self.getTextByMonkeyView(groupNameView) print "Info : this_group_name : ", groupName if groupName != target_group_name.encode('utf8'): continue # 363 is qb_troop_list_view.top, 156是整个一条group的高度。# 78 / 182 UILocation = group.top + 78/2 + 182 # groupName对了,然后看groupId。暂时不要去解析groupName,耗时 # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。 if UILocation < 200 or UILocation > 760: print "Info : skip this group in case we touch screen incorrectly !" continue # 0.5s if self.touchByMonkeyPixel([self.emulator['width']/2,UILocation]) == 0: if self.is_group() == 0: for i in range(0,3): groupId = '' groupId = self.get_group_id() if groupId == target_group: self.currentGroup['groupId'] = target_group self.currentGroup['groupName'] = target_group_name self.groupList[target_group]['UILocation'] = UILocation return 0 elif groupId != '': print "Info : get the incorrect groupid %s !" % groupId break else: print "Info : get the empty groupid !" continue print "Error : failed to find the target group",target_group return -1 def register_monkey(self): print '------------ register_monkey ------------' groupList = [{'groupId': key, 'groupName': value['groupName']} for key, value in self.groupList.iteritems()] data = { 'cmd': 'register', 'qq': self.qq['qqId'], 'qqName': self.qq['qqName'], 'url':self.qq['url'], 'groupList': json.dumps(groupList) } url_post(self.qq['robot_url'], data) return 0 def heartbeat_monkey(self): print '------------ heartbeat_monkey ------------' self.touchByMonkeyPixel(self.emulator['heartbeat']) groupList = [{'groupId': key, 'groupName': value['groupName']} for key, value in self.groupList.iteritems()] data = { 'cmd': 'heartbeat', 'qq': self.qq['qqId'], 'qqName': self.qq['qqName'], 'url':self.qq['url'], 'groupList': json.dumps(groupList) } url_post(self.qq['robot_url'], data) return 0 def monkey_task_loop(self): print '------------ monkey_task_loop start ------------' # this should never return while(1): # if self.is_home_screen() != 0: # continue sleep(1) if self.screenUsing == 0: self.heartbeat += 1 if self.heartbeat == 1200: # self.get_pure_group_list_monkey() # if self.groupList != {}: # self.write_grouplist() self.heartbeat_monkey() self.heartbeat = 0 else: self.heartbeat = 0 ### api for robot manager ### # 此处,不考虑UILocation def enter_group(self,data): t1=time() target_group = data['group'] target_group_name = self.groupList[target_group]['groupName'] print '------------ enter_group : %s %s' % (target_group_name.encode('utf8'),target_group) if self.groupListUpdating == 1: print "Info : groupList is updating now ! Please wait about 2 minutes !" return 1 if target_group not in self.groupList: print "Error : failed to find in the grouplist %s !" % target_group return 2 # 每次从main界面进入 self.touch_to_enter_main() if self.touch_to_enter_grouplist() != 0: print "Error : failed to touch_to_enter_grouplist !" return 3 t_tmp=time() print "Info : it takes %s time to enter grouplist" % str(t_tmp-t1) # 通过possibleDrag来缩小查找范围。然后从该页的自己、前、后 三个界面查找。 # 下一步,可以通过possibleIndex,在自己界面进一步缩小查找范围。 # 在前界面,从后往前查找;在后界面,从前往后查找。 # 0 if self.check_group_by_possible_location(target_group) == 0: t2=time() print "Info : it takes %s time to enter group" % str(t2-t1) return 0 # -1 # 向上drag一次,possibledrag非0时候 # self.device.drag((1080/2, 400),(1080/2, 1700),0.2,1) view = self.get_current_view() if view == 'is_group' or view == 'is_info': self.touch_to_enter_grouplist() if self.is_grouplist() == 0: self.drag_to_page_up() if self.find_target_group_from_list(target_group) == 0: t2=time() print "Info : it takes %s time to enter group" % str(t2-t1) return 0 # 2 # 向下drag一次 # self.device.drag((1080/2, 1700),(1080/2, 400),0.2,1) # self.device.drag((1080/2, 1700),(1080/2, 400),0.2,1) view = self.get_current_view() if view == 'is_group' or view == 'is_info': self.touch_to_enter_grouplist() if self.is_grouplist() == 0: self.drag_to_page_down() self.drag_to_page_down() if self.find_target_group_from_list(target_group) == 0 : t2=time() print "Info : it takes %s time to enter group" % str(t2-t1) return 0 print "Error : failed to enter group %s !" % target_group return -1 def send_msg(self,data): if not data.get('msg'): return 1 msg = data['msg'] print '------------ send_msg %s' % msg print ">>>send_msg 1 ",time() if self.is_group() != 0 : view = self.get_current_view() if view == 'is_info': self.touch_to_enter_group() else: print "Info : I am in the view %s !" % view return 1 print ">>>send_msg 2 ",time() get_encoded_character(self.qq['deviceid'], msg.decode('utf8')) # self.restart_qq_monkey() print ">>>send_msg 3 ",time() # self.easy_device.touch(input_location, self.easy_device.DOWN) self.device.touch(self.emulator['input'][0],self.emulator['input'][1],MonkeyDevice.DOWN) sleep(1) # self.easy_device.touch(input_location, self.easy_device.UP) self.device.touch(self.emulator['input'][0],self.emulator['input'][1],MonkeyDevice.UP) self.touchByMonkeyPixel(self.emulator['paste']) print ">>>send_msg 4 ",time() self.touchByMonkeyPixel(self.emulator['send']) # # 1s # inputid = None # try: # inputid = self.get_hierarchy_view_by_id('id/input') # except: # print "Error : failed to find view id/input !" # return 2 # print ">>>send_msg 5 ",time() # if inputid: # text = self.getTextByMonkeyView(inputid) # print "Info : get msg %s from clipboard !" % text # if text.strip().split() == msg.strip().split(): # print ">>>send_msg 6 ",time() # # 1s # if self.touchByMonkeyId('id/fun_btn') == 0: # # if self.touchByMonkeyPixel(970,1700) != 0: # print "Info : send msg %s ok !" % msg # print ">>>send_msg 7 ",time() # return 0 # else: # delete_code = "input keyevent KEYCODE_DEL" # inputid = self.get_hierarchy_view_by_id('id/input') # self.device.touch(350,750,'DOWN_AND_UP') # while( self.getTextByMonkeyView(inputid) ): # print "Info : delete the incorrect string !" # for i in range(0,20): # self.device.shell(delete_code) # inputid = self.get_hierarchy_view_by_id('id/input') # print "Error : failed to send msg %s , Incorrect msg !" % msg # return 3 def get_msgs(self,data): print '------------ get_msgs ------------' if self.is_group() != 0 : view = self.get_current_view() if view == 'is_info': self.touch_to_enter_group() else: print "Info : I am in the view %s !" % view return 1 self.currentGroup['msgs'] = [] dragCount = 3 msgs = [] # is_stop_drag = 0 for msgDrag in range(0, dragCount): # if is_stop_drag: # break if msgDrag !=0: # self.device.drag((1080/2, 500),(1080/2, 1550),0.1,1) self.drag_to_page_up() hViewer = None _msgs = [] try: listView1 = self.get_hierarchy_view_by_id('id/listView1') # 该行会出现AttributeError: 'NoneType' object has no attribute 'children _msgs = listView1.children except: print "Error : failed to parse view : listView1 !" # print 'msgs count : ', len(_msgs)-1 #最后一个为输入框 # reverse()不可用java.Arraylist tmpMsgs = [] for m in _msgs: tmpMsgs.insert(0, m) for m in tmpMsgs: if 'BaseChatItemLayout' not in str(m): continue item = {} item['nickname'] = '' layoutLeft = '' for t in m.children: if t.id == 'id/chat_item_head_icon': # < 1s layoutLeft = t.namedProperties.get('layout:mLeft').value.encode('utf8') if layoutLeft == self.emulator['self_msg']: break if t.id == 'id/chat_item_nick_name': item['nickname'] = self.getTextByMonkeyView(t) if t.id == 'id/chat_item_content_layout': item['content'] = self.getTextByMonkeyView(t) # 自己发送的消息 if layoutLeft == self.emulator['self_msg']: continue else: if item['nickname'].endswith(':'): item['nickname'] = item['nickname'][0:-1] # #此处时间暂不考虑如 Friday 10:46 的情况 # c = self.getDescByMonkeyView(m) # item['time'] = c[0:c.find(' ')] # 添加每条消息的drag次数 item['drag'] = msgDrag # # 已存储的消息,则没有必要往前drag了。 # # if item in self.currentGroup['storedMsgs']: # # is_stop_drag = 1 # # break # store_this_msg = 0 # for i in self.currentGroup['storedMsgs']: # if i['content'] == item['content'] and i['nickname'] == item['nickname']: # is_stop_drag = 1 # store_this_msg = 1 # break # if store_this_msg == 1: # continue # 未存储,则为新消息.如前一次drag已得到,则跳过. has_this_msg = 0 for j in msgs: if j['content'] == item['content'] and j['nickname'] == item['nickname']: has_this_msg = 1 break if has_this_msg == 1: continue msgs.append(item) # 针对新消息的提示处理。 for i in range(0,4): # self.device.drag((1080/2, 1550),(1080/2, 500),0.1,1) self.drag_to_page_down() if msgs: self.currentGroup['msgs'] = msgs print "Info : new msgs count : %s !" % len(msgs) for m in self.currentGroup['msgs']: print m['nickname'], m['content'], m['drag'] # default: store the last 10 msgs self.currentGroup['storedMsgs'] += self.currentGroup['msgs'] print 'Info : stored msgs count ', len(self.currentGroup['storedMsgs']) if len(self.currentGroup['storedMsgs']) > 10: self.currentGroup['storedMsgs'] = self.currentGroup['storedMsgs'][-10:] self.groupList[self.currentGroup['groupId']]['storedMsgs'] = self.currentGroup['storedMsgs'] # for n in self.currentGroup['storedMsgs']: # print n['nickname'], n['content'] return self.currentGroup['msgs']
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By import subprocess # 初始化 device = MonkeyRunner.waitForConnection(10.0, "127.0.0.1:21503") easyDevice = EasyMonkeyDevice(device) for i in range(0, 100): # 点击列表评论区域 easyDevice.touch(By.id('id/comment_cnt'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(4) # 点击内容评论区域 easyDevice.touch(By.id('id/comment_ll'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(4) # 输入评论 string = "adb shell am broadcast -a ADB_INPUT_TEXT --es msg " + u"看起来很漂亮" + str( randint(0, 1000)) subprocess.check_call(string)
#! /usr/bin/env python ''' Copyright (C) 2012 Diego Torres Milano Created on Sep 8, 2012 @author: diego @see: http://code.google.com/p/android/issues/detail?id=36544 ''' import re import sys import os # This must be imported before MonkeyRunner and MonkeyDevice, # otherwise the import fails. # PyDev sets PYTHONPATH, use it try: for p in os.environ['PYTHONPATH'].split(':'): if not p in sys.path: sys.path.append(p) except: pass try: sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src')) except: pass from androidviewclient3.viewclient import ViewClient device, serialno = ViewClient.connectToDeviceOrExit() FLAG_ACTIVITY_NEW_TASK = 0x10000000 # We are not using Settings as the bug describes because there's no WiFi dialog in emulator #componentName = 'com.android.settings/.Settings' componentName = 'com.dtmilano.android.sampleui/.MainActivity'
# test camera capture image for i in range(image_loops): print 'Test image capture: ', i # launch camera image mode print 'Launch image capture..' os.popen('adb shell "am start -a android.media.action.IMAGE_CAPTURE"') MonkeyRunner.sleep(wait_app_launch) # test camera shot device1.press('KEYCODE_CAMERA', "DOWN_AND_UP") #easy_device.touch(By.id("id/camera_shutter"), MonkeyDevice.DOWN_AND_UP ) MonkeyRunner.sleep(wait_cmd_time) # save capture picture easy_device.touch(By.id("id/btn_done"), MonkeyDevice.DOWN_AND_UP) #=> ok #device1.touch( save_capture_pic[0], save_capture_pic[1], "DOWN_AND_UP") #easy_device.touch(By.id("id/remaining_view"), MonkeyDevice.DOWN_AND_UP ) MonkeyRunner.sleep(wait_cmd_time) print 'Test image capture done..' # launch camera video mode print 'Launch video capture..' os.popen('adb shell "am start -a android.media.action.VIDEO_CAPTURE"') MonkeyRunner.sleep(wait_app_launch) print 'Test video capture..' device1.press('KEYCODE_CAMERA', "DOWN_AND_UP") # wait for video record
# init param wait_app_launch = 3 wait_button_time = 1 wait_cmd_time = 2 test_vt_time = 20 MonkeyRunner.sleep(wait_cmd_time); # launch VT working app print 'Launch Engineering Working Menu' os.popen('adb shell "am start -a android.intent.action.MAIN -n com.mediatek.engineermode/.videotelephone.WorkingMode"') MonkeyRunner.sleep(wait_app_launch); easy_device.touch(By.id("id/working_mode_media_loopback"), MonkeyDevice.DOWN_AND_UP ) MonkeyRunner.sleep(wait_button_time); easy_device.touch(By.id("id/media_loopback_stack"), MonkeyDevice.DOWN_AND_UP ) #MonkeyRunner.sleep(wait_button_time); # MonkeyRunner.sleep(wait_app_launch); # print 'launch VT Activity' # os.popen('adb shell "am start -a com.android.vt.VTLoopbackActivity.LAUNCH -n com.android.phone/.VTLoopbackActivity"') # Launch VT Lookback Activity # os.popen('adb shell "am start -a com.android.vt.VTLoopbackActivity.LAUNCH -n com.android.phone/.VTLoopbackActivity"') # #os.popen('adb shell "am start -a com.android.vt.VTLoopbackActivity.MAIN -n com.android.phone/.VTLoopbackActivity"') # #os.popen('adb shell "am start -a android.intent.action.MAIN -n com.android.phone/.VTLoopbackActivity"')
def filter_contacts(device): easy_device = EasyMonkeyDevice(device) start_activity(device, '.StartActivity') easy_device.touch(By.id('id/mpp_menu_toggle_filter_box'), MonkeyDevice.DOWN_AND_UP)
print '---- start Calculator App' device.startActivity('com.android.calculator2/.Calculator') print '---- calculator 3*8 with press method' device.press('KEYCODE_3', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_NUMPAD_MULTIPLY', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_8', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_EQUALS', MonkeyDevice.DOWN_AND_UP) easy = EasyMonkeyDevice(device) image = device.takeSnapshot() subimage = image.getSubImage(easy.locate(By.id('id/display'))) print '---- calculator 4*6 with touch method' easy.touch(By.id('id/digit4'), MonkeyDevice.DOWN_AND_UP) easy.touch(By.id('id/mul'), MonkeyDevice.DOWN_AND_UP) easy.touch(By.id('id/digit6'), MonkeyDevice.DOWN_AND_UP) easy.touch(By.id('id/equal'), MonkeyDevice.DOWN_AND_UP) image2 = device.takeSnapshot() subimage2 = image2.getSubImage(easy.locate(By.id('id/display'))) if (subimage2.sameAs(subimage, 0.8)): print '[PASS] the result of 3*8 and 4*6 is equal!' else: print '[Fail] the result of 3*8 and 4*6 is not equal!'
print("Pre-preparation is completed, start the app.") runComponent = "dong.sqlite.order/.MainActivity" # 启动首页Activity device.startActivity(component=runComponent) MonkeyRunner.sleep(2) # 打印操作信息 log.write("The script starts to run\n") # 截图 result = device.takeSnapshot() # 保存截图 result.writeToFile(path + "点击读取文件前".decode('utf-8') + now + '.png', 'png') 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') MonkeyRunner.sleep(1) # 截取点击read后的屏幕图 result2 = device.takeSnapshot() result2.writeToFile(path + "点击读取文件后".decode('utf-8') + now + ".png", 'png') # 判断图片相识度是否是为90% if (result.sameAs(result2, 0.9)): print("The main page picture comparison is successful") #打印信息到log文件 log.write("The main page picture comparison is successful\n") else: print("The main page picture comparison failed")
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" else: print "FAIL"
# input is randomized, can be replaced with a command line array, etc. enter = int(random.randrange(-100,100)) MonkeyRunner.sleep(pause) # record the original number and current player old = int(easyDevice.getText(txtNumber)) player = easyDevice.getText(txtPlayer) # enter the input easyDevice.type(editGuess, str(enter)) MonkeyRunner.sleep(pause) print '%s: old = %s, enter = %s' % (player, old, enter) # simulate press on btnPost easyDevice.touch(btnPost, MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(pause) # fetch new values actual = int(easyDevice.getText(txtNumber)) expected = old + enter # check against expected if actual == expected: print 'PASS' else: print 'FAIL: expected %s, actual %s' % (expected, actual) # --------------------------------------------------------------------- #
# test camera capture image for i in range(image_loops): print 'Test image capture: ', i # launch camera image mode print 'Launch image capture..' os.popen('adb shell "am start -a android.media.action.IMAGE_CAPTURE"') MonkeyRunner.sleep(wait_app_launch) # test camera shot device1.press( 'KEYCODE_CAMERA' , "DOWN_AND_UP") #easy_device.touch(By.id("id/camera_shutter"), MonkeyDevice.DOWN_AND_UP ) MonkeyRunner.sleep(wait_cmd_time) # save capture picture easy_device.touch(By.id("id/btn_done"), MonkeyDevice.DOWN_AND_UP ) #=> ok #device1.touch( save_capture_pic[0], save_capture_pic[1], "DOWN_AND_UP") #easy_device.touch(By.id("id/remaining_view"), MonkeyDevice.DOWN_AND_UP ) MonkeyRunner.sleep(wait_cmd_time) print 'Test image capture done..' # launch camera video mode print 'Launch video capture..' os.popen('adb shell "am start -a android.media.action.VIDEO_CAPTURE"') MonkeyRunner.sleep(wait_app_launch) print 'Test video capture..'
runComponent = package + '/' + activity # Runs the component easy_device.startActivity(component=runComponent) MonkeyRunner.sleep(5) # Press the calculate Button-without error device.press('KEYCODE_MOVE_END', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP) device.type('12.2') device.press('KEYCODE_TAB', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_MOVE_END', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP) device.type('1') easy_device.touch(By.id("id/calculate"), MonkeyDevice.DOWN_AND_UP) result = device.takeSnapshot() result.writeToFile('./shot1.png', 'png') # Press the calculate Button-with error(Pi length more than 16) device.press('KEYCODE_MOVE_END', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP) device.type('17') easy_device.touch(By.id("id/calculate"), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(5) result = device.takeSnapshot() result.writeToFile('./shot2.png', 'png') # Press the calculate Button-with error(Pi length empty) device.press('KEYCODE_MOVE_END', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP)
class fineMonkeyRunner: ''' ############################# finemonkeyrunner class ############################# ''' def __init__(self, emulatorname, switch=PHONE_EMULATOR_SWITCH): device = self.waitforconnection(waitForConnectionTime, emulatorname) self.debug( "__int__: creating the finemonkeyrunner object with emulatorname %s" % emulatorname) # use EasyMonkeyDevice and MonkeyDevice self.easydevice = EasyMonkeyDevice(device) self.device = device # presskey type self.DOWN = self.device.DOWN self.UP = self.device.UP self.DOWN_AND_UP = self.device.DOWN_AND_UP self.switch = switch self.debug('created the fineEasyDevice') self.viewlist = [] def debug(self, debuginfo): if DEBUG: print '[%s] DEBUG: %s ' % (datetime.today(), debuginfo) def info(self, info): if INFO: print '[%s] Info: %s ' % (datetime.today(), info) def error(self, error): if ERROR: print '[%s] ERROR: %s ' % (datetime.today(), error) def sleep(self, seconds): self.debug('sleeping %f seconds' % seconds) mr.sleep(seconds) def installapp(self, apppath): try: self.device.installPackage(apppath) except: self.error("Install app Fail ") def remove(self, packagename): try: self.device.removePackage(packagename) except: self.error("Uninstall app Fail ") '''建立device连接''' def waitforconnection(self, waitForConnectionTime, emulatorname): try: self.debug("waitforconnectiontime:Success") return mr.waitForConnection(waitForConnectionTime, emulatorname) except: self.error("waitForConnection error") sys.exc_info() traceback.print_exc() return None ''' 启动应用的activity''' def startactivity(self, activity): try: self.debug("starting the activity... %s" % activity) self.easydevice.startActivity(component=activity) except: self.error("starting the activity %s error" % activity) sys.exc_info() traceback.print_exc() return False '''指定的id元素是否存在''' def isexist(self, id): self.debug('check the id is exist or not') try: if (self.easydevice.exists(self.getviewbyid(id))): return True else: self.debug( 'isexist: %s this id does not exists,will try check again' % id) self.sleep(1) except: # self.debug('isexist: the %dst time check id (%s) existing error , , will retry ' % (tmp, id)) self.sleep(1) return False '''对某一个键按多次''' def presskey(self, key, times, type): # self.device.press('KEYCODE_ENTER', MonkeyDevice.DOWN_AND_UP) for i in range(times): self.device.press(key, type) self.sleep(1) '''根据ID长按''' def longpressbyid(self, id, x=0, y=0): self.debug('calling longpressbyid function') hierarchyviewer = self.device.getHierarchyViewer() view = hierarchyviewer.findViewById(id) point = hierarchyviewer.getAbsoluteCenterOfView(view) item_btn_x = point.x + x item_btn_y = point.y + y self.device.touch(item_btn_x, item_btn_y, self.DOWN) self.sleep(1) self.device.touch(item_btn_x, item_btn_y, self.UP) return True '''根据view长按''' def longpressbyview(self, view, x=0, y=0): self.debug('calling longpressbyview function') hierarchyviewer = self.device.getHierarchyViewer() point = hierarchyviewer.getAbsoluteCenterOfView(view) item_btn_x = point.x + x item_btn_y = point.y + y self.device.touch(item_btn_x, item_btn_y, self.DOWN) self.sleep(1) self.device.touch(item_btn_x, item_btn_y, self.UP) return True '''获view的信息--p''' def getviewinfo_text(self, view): # text = view.namedProperties.get('text:mText').value.encode('utf8') try: textproperty = view.namedProperties.get("text:mText").value.encode( 'utf8') except: self.debug('%s has not text:mText Property!' % str(view)) else: #self.debug('The text is %s ' % textproperty) return textproperty '''--p''' def getviewinfo_height(self, view): height = view.namedProperties.get('layout:getHeight()').value.encode( 'utf8') return height '''--p''' def getviewinfo_width(self, view): width = view.namedProperties.get('layout:getWidth()').value.encode( 'utf8') return width '''--p''' def getviewinfo_mleft(self, view): mleft = view.namedProperties.get('layout:mLeft').value.encode('utf8') return mleft '''-p''' def getviewinfo_mtop(self, view): mtop = view.namedProperties.get('layout:mTop').value.encode('utf8') '''--p''' def getviewinfo_mid(self, view): mid = view.namedProperties.get('mID').value #.encode('utf8') return mid '''--p''' def getviewinfo_visible(self, view): visible = view.namedProperties.get('getVisibility()').value.encode( 'utf8') if visible == 'VISIBLE': self.debug('visible') return True else: return False '''--p''' def getviewinfo_xy(self, view): hierarchyviewer = self.device.getHierarchyViewer() point = hierarchyviewer.getAbsoluteCenterOfView(view) return point.x, point.y '''获取文本根据id''' def gettextbyid(self, id): if self.isexist(id): view = self.getviewbyid(id) viewtext = self.getviewinfo_text(view) return viewtext else: self.error('Not look for the element or it has a error!') return False '''获取view根据id --p''' def getviewbyID(self, id): starttime = time.time() print starttime hierarchyviewer = self.device.getHierarchyViewer() view = hierarchyviewer.findViewById(id) endtime = time.time() self.debug('Elapsed Iime:%f' % (endtime - starttime)) return view '''获取view根据id --p''' def getviewbyid(self, id): self.debug('calling getviewbyid function by the id (%s)' % id) for tmp in range(repeatTimesOnError): try: return By.id(id) except: self.debug( 'getviewbyid: the %dst time error by id (%s) , will retry ' % (tmp, id)) mr.sleep(1) continue self.error( 'getviewbyid: sorry , still can\'t get the view by this id (%s). please check the view ' % id) sys.exc_info() traceback.print_exc() return None '''根据层级结构来获取view,childseq表示层级的元组(1,1,0,0,2)---p''' def getchildviewbylayer(self, parentid, childseq): self.debug('calling getchildviewbylayer function') hierarchyviewer = self.device.getHierarchyViewer() childview = "hierarchyviewer.findViewById('" + parentid + "')" for index in childseq: childview += ('.children[' + str(index) + ']') #print childview try: eval(childview) except: self.debug('No find the view and please check childseq') else: return eval(childview) '''--p''' '''根据id返回该元素的一个x,y,h,w的元组''' def getelementinfo_locate(self, id): xyhw = self.easydevice.locate(By.id(id)) return xyhw '''根据view获取类名---p''' def getviewinfo_classname(self, view): #,view self.debug('calling traversalViewnode:%s ' % str(view)) tmp = str(view).split('.') classname = tmp[-1].split('@')[0] return classname '''type:1是代表classname,type:2代表是id type:3代表是text ---p''' def traversalviewsametype(self, viewnode, name, type): # self.debug('calling traversalViewnode:%s '%str(viewnode)) #tmplist = [] for eachitem in range(len(viewnode.children)): tmpclassname = viewnode.children[eachitem] controls = 'TextView' in str(tmpclassname) or 'EditText' in str( tmpclassname) or 'tButton' in str(tmpclassname) if len(viewnode.children[eachitem].children) != 0: if type == 1 and (name in str(tmpclassname)): self.viewlist.append(viewnode.children[eachitem]) if type == 2 and self.getviewinfo_mid( viewnode.children[eachitem]) == name: self.viewlist.append(viewnode.children[eachitem]) if type == 3 and controls and self.getviewinfo_text( viewnode.children[eachitem]) == name: self.viewlist.append(viewnode.children[eachitem]) self.traversalviewsametype(viewnode.children[eachitem], name, type) # self.debug(result) else: if type == 1 and (name in str(tmpclassname)): self.viewlist.append(viewnode.children[eachitem]) if type == 2 and self.getviewinfo_mid( viewnode.children[eachitem]) == name: self.viewlist.append(viewnode.children[eachitem]) if type == 3 and controls and self.getviewinfo_text( viewnode.children[eachitem]) == name: self.viewlist.append(viewnode.children[eachitem]) '''获取指定id元素下的相同id的view对象列表 --p''' def getviewssameid(self, parentid, id): self.debug('calling getviewssameid function...') self.viewlist = [] starttime = time.time() hierarchyviewer = self.device.getHierarchyViewer() viewnode = hierarchyviewer.findViewById(parentid) self.traversalviewsametype(viewnode, id, 2) endtime = time.time() self.debug('Elapsed Iime:%f' % (endtime - starttime)) return self.viewlist #pass '''获取指定id元素下的相同classname的view对象列表 --p''' def getviewssameclassname(self, parentid, classname): self.debug('calling getviewssameclassname function...') self.viewlist = [] starttime = time.time() hierarchyviewer = self.device.getHierarchyViewer() viewnode = hierarchyviewer.findViewById(parentid) self.traversalviewsametype(viewnode, classname, 1) endtime = time.time() self.debug('Elapsed Iime:%f' % (endtime - starttime)) return self.viewlist '''获取子views根据父view ---p''' def getchildviewsbyparentview(self, parentview): self.debug('calling getchildviewsbyparentview function...') viewlists = [] if len(parentview.children) != 0: for i in range(len(parentview.children)): viewlists.append(parentview.children[i]) return viewlists else: self.debug('%s has not children view' % str(parentview)) '''获取子view的数量 ---p''' def getchilrenlength(self, parentview): self.debug('calling getchilrenlength function...') return len(parentview.children) '''获取指定id元素下的相同文本的view对象列表 ---p''' def getviewssametext(self, parentid, text): self.debug('calling getviewssametext function...') self.viewlist = [] starttime = time.time() hierarchyviewer = self.device.getHierarchyViewer() viewnode = hierarchyviewer.findViewById(parentid) self.traversalviewsametype(viewnode, text, 3) endtime = time.time() self.debug('Elapsed Iime:%f' % (endtime - starttime)) return self.viewlist '''拖拽屏幕 ---p''' def dragscreen(self, start, end, duration, steps): self.debug('calling dragscreen function...') md.drag(start, end, duration, steps) '''在指定的id上输入文字--p''' def typebyid(self, id, content): self.debug('device input the %s by id' % content) self.easydevice.type(By.id(id), content) '''在当前焦点输入文字--p''' def type(self, content): self.debug('device input the %s' % content) self.device.type(content) '''点击元素根据view 对话框除外 ---p''' def clickelementbyview(self, view, x=0, y=0): self.debug('calling clickelementbyview function') for tmp in range(repeatTimesOnError): try: hierarchyviewer = self.device.getHierarchyViewer() point = hierarchyviewer.getAbsoluteCenterOfView(view) item_btn_x = point.x + x item_btn_y = point.y + y # print item_btn_x, item_btn_y self.debug('Click Position:x = %d ,y = %d' % (item_btn_x, item_btn_y)) self.device.touch(item_btn_x, item_btn_y, self.DOWN_AND_UP) return True except: self.debug( 'clickelementbyview: the %dst time click error , not found the view , will retry ' % tmp) if (tmp > 1 & DEBUG): self.debug('Please wait to click the view') mr.sleep(1) continue self.error( 'clickelementbyview: sorry , still can\'t click view. please check the view is exist or not , or increase the repeat times variable?' ) sys.exc_info() traceback.print_exc() return False '''点击对话框中的view''' def clickdialogelementbyview(self, view): self.debug('calling clickdialogelementbyview function') hierarchyviewer = self.device.getHierarchyViewer() width = self.device.getProperty("display.width") height = self.device.getProperty("display.height") point = hierarchyviewer.getAbsoluteCenterOfView(view) p = view rootview = view while p != None: rootview = p p = p.parent x = (int(width) - int(rootview.width)) / 2 + point.x y = (int(height) - int(rootview.height)) / 2 + point.y self.debug('Position:x= %d ; y=%d' % (x, y)) self.device.touch(x, y, self.DOWN_AND_UP) #print "clicked view" def clickbyviewondialog(self): pass '''根据文本点击元素,由于根据文本获取的是相同文本的view列表,默认使用第一个view, 可以根据实际情况再调整,num代表view列表中的序号,默认0 非对话框 ---P''' def clickbytext(self, parentid, text, num=0): self.debug('calling clickbytext function') viewlist = self.getviewssametext(parentid, text) if viewlist != []: self.clickelementbyview(viewlist[num]) return True else: self.debug('No find the view, please check') return None '''根据id点击元素 ---p''' def clickbyid(self, id, type): self.debug('calling clickbyid function') for tmp in range(repeatTimesOnError): try: self.easydevice.touch(By.id(id), type) return True except: self.debug( 'clickbyid: the %dst time click error by this id (%s) , not found the view , will retry ' % (tmp, id)) if (tmp > 1 & DEBUG): self.debug('Please wait to click the view') mr.sleep(1) continue self.error( 'clickbyid: sorry , still can\'t click view. please check the view is exist or not , or increase the repeat times variable?' ) sys.exc_info() traceback.print_exc() return False '''根据point点击元素 ---p''' def clickpoint(self, x, y, type): self.debug('calling click the point ') for tmp in range(repeatTimesOnError): try: self.device.touch(x, y, type) return True except: self.debug( 'clickpoint: %d time click point error , will retry ' % tmp) mr.sleep(1) continue self.error( 'clickpoint: sorry , still can\'t click point. please check the view is exist or not , or increase the repeat times variable?' ) sys.exc_info() traceback.print_exc() return False '''判断给定的id元素是否是选中状态---p''' def isfocused(self, id): self.debug('checking the view is focused or not') # hierarchyViewer = self.device.getHierarchyViewer() # print hierarchyViewer.findViewById(id).hasFocus for tmp in range(repeatTimesOnError): try: hierarchyViewer = self.device.getHierarchyViewer() return hierarchyViewer.findViewById(id).hasFocus except: self.debug( 'isfocused: the %dst time check focus error , will retry ' % tmp) mr.sleep(1) continue self.error('isfocused: error occured') sys.exc_info() traceback.print_exc() return False '''获取指定的view文本 getviewinfo_text已经存在 def gettextbyview(self, view): # if view != None: # return (view.namedProperties.get('text:mText').value.encode('utf8')) textProperty = view.namedProperties.get("text:mText") if textProperty==None: self.debug('No text property on node') textProperty = view.namedProperties.get("mText") if textProperty == None: self.debug('No text property on node') return textProperty.value.encode('utf8') ''' '''清除编辑框的文本 ---P''' def cleartextbyid(self, id): self.debug('calling cleartextbyid function by the id (%s)' % id) if self.isexist(id): if not self.isfocused(id): self.clickbyid(id, self.DOWN_AND_UP) textview = self.getviewbyID(id) rangenumber = len(self.getviewinfo_text(textview)) for x in range(rangenumber): self.device.press('KEYCODE_DEL', self.DOWN_AND_UP) for x in range(rangenumber): self.device.press('KEYCODE_FORWARD_DEL', self.DOWN_AND_UP) self.debug('cleartextbyid: cleared the text in id (%s)' % id) return True self.error('cleartextbyid: sorry ,the id (%s) is not exist ' % id) sys.exc_info() traceback.print_exc() return False '''根据id输入文本框内容 ---p''' def inputtextbyid(self, id, text): self.debug('calling inputtextbyid function by the id (%s)' % id) self.clickbyid(id, self.DOWN_AND_UP) if self.isfocused(id): self.type(text) else: self.debug('No Selected the element by id,Please check') if self.switch == 'E': self.debug('This is an emulator') else: self.presskey('KEYCODE_BACK', self.DOWN_AND_UP, 1) # 如果是真机需要打开语句,模拟器需关闭 # self.pressKey('KEYCODE_BACK', self.DOWN_AND_UP, 1) # mr.sleep(1) return True '''根据当前界面上的任意id获取rootview ---p''' def getcurrentrootview(self, id): self.debug('calling getcurrentrootview function by the id (%s)' % id) hierarchyviewer = self.device.getHierarchyViewer() currentview = hierarchyviewer.findViewById(id) p = currentview rootview = currentview while p != None: rootview = p p = p.parent return rootview '''遍历viewnode节点,type=1是完全匹配type=0是包含关系''' def traversalviewnode(self, viewnode, text, type): # self.debug('calling traversalViewnode:%s '%str(viewnode)) tmplist = [] for eachitem in range(len(viewnode.children)): viewnodestr = str(viewnode.children[eachitem]) if len(viewnode.children[eachitem].children) != 0: result = self.traversalviewnode(viewnode.children[eachitem], text, type) if result: return self.traversalviewnode(viewnode.children[eachitem], text, type) else: if 'TextView' in viewnodestr or 'EditText' in viewnodestr or 'tButton' in viewnodestr: viewnodetext = self.getviewinfo_text( viewnode.children[eachitem] ) #viewnode.children[eachitem].namedProperties.get('text:mText').value.encode('utf8') if type == 1 and viewnodetext == text: # self.debug('1 Find the text:%s ' % viewnodetext) tmplist.append('P') return True elif type == 0 and (text in viewnodetext): # self.debug('0 Find the text: %s ' % viewnodetext) tmplist.append('P') return True else: tmplist.append('F') '''该元素内的文本是否包含指定的文本 ---p''' def elementshouldcontaintext(self, id, text, type): self.debug('calling elementshouldcontaintext function by the id (%s)' % id) # 获取指定元id元素的viewnode starttime = time.time() hierarchyviewer = self.device.getHierarchyViewer() viewnode = hierarchyviewer.findViewById(id) result = self.traversalviewnode(viewnode, text, type) endtime = time.time() #print result if result: self.debug('Elapsed Iime:%f' % (endtime - starttime)) return True else: self.debug('Elapsed Iime:%f' % (endtime - starttime)) return False '''当前界面的文本是否包含指定的文本 ---p''' def pageshouldcontaintext(self, id, text, type): # 获取指定元id元素的rootview self.debug('calling pageshouldcontaintext function by the id (%s)' % id) starttime = time.time() viewnode = self.getcurrentrootview(id) result = self.traversalviewnode(viewnode, text, type) endtime = time.time() #print result if result: self.debug('Elapsed Iime:%f' % (endtime - starttime)) return True else: self.debug('Elapsed Iime:%f' % (endtime - starttime)) return False '''判断id的元素文本是否相等---p''' def equaltextbyid(self, id, text): self.debug('calling equaltextbyid function by the id (%s)' % id) if self.isexist(id): view = self.getviewbyID(id) viewtext = self.getviewinfo_text(view) if text == viewtext: #self.debug('----Pass----') return True else: #self.debug('----Fail----') return False '''判断view的元素文本是否相等---p''' def equaltextbyview(self, view, text): self.debug('calling equaltextbyview function by the id (%s)' % str(view)) viewtext = self.getviewinfo_text(view) if text == viewtext: return True else: return False '''判断activity是否与预期的相同 def assertcurrentactivity(self,currentactivity): starttime = time.time() self.debug('calling assertcurrentactivity function ') try: activity = self.device.shell('dumpsys activity | findstr "mFocusedActivity"') #adb shell except IOError: # print '获取当前activity失败' self.debug('获取当前activity失败') else: print activity tmp = activity.split(' ') activity = tmp[3] self.debug('activity : %s' % activity) if activity == currentactivity: endtime = time.time() times = endtime - starttime self.debug('Execute time is %d' % times) return True else: return False ''' '''等待期望的activity出现,默认时间20秒 ---p''' def waitforactivity(self, waitactivity, repeatTimesOnError=20): for tmp in range(repeatTimesOnError): if self.assertfocusedwindowmame(waitactivity): return True else: self.debug( 'waitforactivity: %s this waitactivity does not exists,will try check again' % waitactivity) mr.sleep(1) continue '''判断activity是否相等 --p''' def assertfocusedwindowmame(self, expectactivity): starttime = time.time() #hierarchyviewer = self.device.getHierarchyViewer() winId = self.easydevice.getFocusedWindowId() if winId == expectactivity: self.debug('%s is correct' % winId) #.encode('utf-8') endtime = time.time() times = endtime - starttime self.debug('Execute time is %d' % times) return True #print winId.encode('utf-8') else: self.debug('%s is wrong' % winId) return False '''--p''' '''Force to stop the App''' def forcestopapp(self, packagename): self.debug('calling forcestopapp function ') try: activity = self.device.shell('am force-stop %s' % packagename) return True except IOError: self.debug('force stop the app')
# -*- coding: UTF-8 -*- # 打开C:\Users\win 10\AppData\Local\Android\Sdk\tools\bin\uiautomatorviewer.bat # 或有设置环境变量的代开cmd,输入uiautomatorviewer # 获取当前屏幕控件id,再运行脚本 from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage from com.android.monkeyrunner.easy import EasyMonkeyDevice,By device = MonkeyRunner.waitForConnection() if not device: print('devices is not connected') else: print('start') comand="com.hy.storyMachine/.view.activity.HomeActivity" device.startActivity(component=comand) easy_device = EasyMonkeyDevice(device) MonkeyRunner.sleep(10) easy_device.touch(By.id('id/img_pause_play'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(5) easy_device.touch(By.id('id/img_last'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(5) easy_device.touch(By.id('id/img_next'), MonkeyDevice.DOWN_AND_UP) # 点击左下角的按钮 MonkeyRunner.sleep(5) easy_device.touch(By.id('id/img_album'), MonkeyDevice.DOWN_AND_UP)
class MonkeyDaemon(object): def __init__(self, options): print '-------- MonkeyDaemon __init__ ---------' global emulators global robot_url if options.qq: self.qq = options.qq if self.qq not in emulators: print "Error: can not find the qq in the android ui emulators!" sys.exit(-1) if options.port: self.port = options.port if options.role: self.role = options.role self.qqName = '' # add a api to get pure group list, on-going self.screenUsing = 0 self.groupListUpdating = 0 self.heartbeat = 0 # {drag, index, groupId, groupName, UILocation, msgs, storedMsgs} self.groupList = {} # already in this group self.currentGroup = { 'groupId': '', 'groupName': '', 'UILocation': '', 'msgs': [], 'storedMsgs': [] } self.monkey_set_up() if self.restart_qq_monkey() != 0: sys.exit(-1) self.get_qqName_monkey() self.get_pure_group_list_monkey() self.register_monkey() def monkey_set_up(self): print '------------ monkey_set_up -------------' devices = os.popen('adb devices').read().strip().split('\n')[1:] global deviceid deviceid = '' if self.role == 'A' or self.role == 'a': deviceid = devices[0].split('\t')[0] if self.role == 'B' or self.role == 'b': deviceid = devices[1].split('\t')[0] self.device = MonkeyRunner.waitForConnection(5, deviceid) self.easy_device = EasyMonkeyDevice(self.device) sleep(0.5) if not self.device or not self.easy_device: print "Error : monkey_set_up failed !" sys.exit(-1) return 0 ### check steps ### # decorator to check qq status def check_qq_status(func): def new_func(self): print '------------ check qq status ------------' ret = self.is_home_screen() if ret == 0: return func(self) else: print "Error : QQ status is not correct !" return -1 return new_func def is_screen_lock(self): print '------------ is_screen_lock ------------' try: glow_pad_view = self.get_hierarchy_view_by_id('id/glow_pad_view') self.screenUsing = 1 self.device.drag((550, 1350),(1000, 1350),0.5,1) self.screenUsing = 0 return 0 except: print "Error : failed to parse view id/glow_pad_view !" return -1 def is_home_screen(self): # print '------------ is_home_screen ------------' launcher = None try: launcher = self.get_hierarchy_view_by_id('id/launcher') except: print "Error : failed to parse view id/launcher !" if launcher != None: return 0 else: return -1 def is_group(self): # print '------------ is_group ------------' listView1 = None try: listView1 = self.get_hierarchy_view_by_id('id/listView1') except: print "Error : failed to parse view id/listView1 !" if listView1: # print "Info : already in the group !" return 0 else: # print "Info : I am not in the group !" return -1 def is_info(self): # print '------------ is_info ------------' common_xlistview = None try: common_xlistview = self.get_hierarchy_view_by_id('id/common_xlistview') except: print "Error : failed to parse view id/common_xlistview !" if common_xlistview: # print "Info : already in the info !" return 0 else: # print "Info : I am not in the info !" return -1 def is_grouplist(self): # print '------------ is_grouplist ------------' qb_troop_list_view = None try: qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view') except: print "Error : failed to parse view id/qb_troop_list_view !" if qb_troop_list_view: # print "Info : already in the grouplist !" return 0 else: # print "Info : I am not in the grouplist !" return -1 def is_current_group(self): # print '------------ is_current_group ------------' print "Info : current group : %s !" % self.currentGroup['groupId'] groupId = '' if self.is_group() == 0: groupId = self.get_group_id() if self.currentGroup['groupId'] == groupId: return 0 else: print "Info : I am not in current group %s, but %s !" % \ (self.currentGroup['groupId'], groupId) return -1 else: return 1 def is_3_columns(self): # print '------------ is_3_columns ------------' recent_chat_list = None try: recent_chat_list = self.get_hierarchy_view_by_id('id/recent_chat_list') except: print "Error : failed to parse view id/recent_chat_list !" if recent_chat_list: # print "Info : already in the 3 columns !" return 0 else: # print "Info : I am not in the 3 columns !" return -1 def restart_qq_monkey(self): print '------------ restart_qq_monkey -------------' while(self.is_home_screen()==0): # self.touch_to_enter_home_screen() self.touchByMonkeyPixel(150,1650) sleep(3) # 一开始启动,QQ闪退的情况 if self.is_3_columns() == 0: self.touch_to_enter_contacts() # 点击联系人,QQ闪退的情况 print "Info : qq has been restarted correctly !" return 0 # if self.is_3_columns() == 0: # return 0 # elif self.is_grouplist() == 0: # return 0 # else: # print "Error : failed to restart QQ ! Try again !" # self.touch_to_enter_home_screen() # return -1 ### check steps ### ### basic monkey operations ### def get_hierarchy_view_by_id(self,id): try: hViewer = self.device.getHierarchyViewer() view = hViewer.findViewById(id) return view except: # print "Error : failed to get hierarchy view by id %s !" % id return None # decorator to wait screen def touch_wait_screen(func): def new_func(self, *args): if self.screenUsing == 1: print "Info : self.screenUsing == 1 !" # sleep(1) return func(self, *args) return new_func def touch_to_enter_home_screen(self): try: return self.touchByMonkeyPixel(1080/2,1850) except: print "Error : failed to touch_to_enter_home_screen !" return -1 # @touch_wait_screen 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 # @touch_wait_screen def touch_to_leave(self): # print '------------ touch_to_leave -------------' try: return self.touchByMonkeyPixel(150,150) except: print "Error : failed to touch_to_leave !" return -1 # @touch_wait_screen def touch_to_enter_info(self): # print '------------ touch_to_enter_info -------------' try: return self.touchByMonkeyPixel(1000,150) except: print "Error : failed to touch_to_enter_info !" return -1 # @touch_wait_screen # 换另外一个group,要重新进入grouplist def touch_to_enter_grouplist(self): print '------------ touch_to_enter_grouplist -------------' if self.is_3_columns() == 0: self.touch_to_enter_contacts() self.touchByMonkeyPixel(700,500) self.touchByMonkeyPixel(300,300) return 0 if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() self.touch_to_leave() self.touch_to_enter_contacts() self.touchByMonkeyPixel(700,500) self.touchByMonkeyPixel(300,300) # if self.is_grouplist(): # return 0 # else: # print "Error : failed to touch_to_enter_grouplist !" # return -1 return 0 # @touch_wait_screen def touch_to_enter_msgs(self): # 不把is_3_columns()放这里边,是为了单独处理QQ restart闪退情况。 print '------------ touch_to_enter_msgs -------------' if self.touchByMonkeyPixel(300,1700) == 0: return self.touchByMonkeyPixel(300,1700) else: print "Error : failed to touch_to_enter_msgs !" return -1 # @touch_wait_screen def touch_to_enter_contacts(self): # 不在is_3_columns()判断放在里边,是为了单独处理QQ restart闪退情况。 print '------------ touch_to_enter_contacts -------------' if self.touchByMonkeyPixel(500,1700) == 0: return self.touchByMonkeyPixel(500,1700) else: print "Error : failed to touch_to_enter_contacts !" return -1 # @touch_wait_screen def touchByMonkeyPixel(self,x,y): # print '------------ touchByMonkeyPixel %s %s -------------' % (x,y) try: self.screenUsing = 1 self.device.touch(x,y,'DOWN_AND_UP') sleep(0.5) self.screenUsing = 0 return 0 except: # sleep(1) return -1 def getTextByMonkeyView(self,view): # print '------------ getTextByMonkeyView %s -------------' % view try: return view.namedProperties.get('text:mText').value.encode('utf8') except: # images print 'Error : failed to find text for view : %s !' % view return 0 def getDescByMonkeyView(self,view): # print '------------ getDescByMonkeyView %s -------------' % view try: return view.namedProperties.get('accessibility:getContentDescription()').value.encode('utf8') except: # images print 'Error : failed to find desc for view : %s !' % view return 0 ### basic monkey operations ### # @check_qq_status def get_qqName_monkey(self): print '------------ get_qqName_monkey ------------' if self.is_3_columns() == 0: self.touch_to_enter_msgs() else: if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() if self.is_grouplist() == 0: self.touch_to_leave() # if self.touchByMonkeyPixel(90,150) != 0: # return -1 self.device.drag((300, 150),(1000, 150),0.5,1) nickname = self.get_hierarchy_view_by_id('id/nickname') self.qqName = self.getTextByMonkeyView(nickname) # if self.touchByMonkeyPixel(1050,700) != 0: # return -1 self.device.drag((1000, 150),(300, 150),0.5,1) # print "Info : now monkey daemon is running for %s %s !" % (self.qqName,self.qq) return 0 def get_pure_group_list_monkey(self): print '------------ get_pure_group_list_monkey ------------' self.groupListUpdating = 1 if self.touch_to_enter_grouplist() != 0: return -1 for drag in range(0,1): if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() print "Info : drag for %s time !" % drag if drag != 0: try: self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1) except: print "Error : failed for the %s drag !" % drag qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view') if qb_troop_list_view == None: continue _groupList = [] _groupList = qb_troop_list_view.children if _groupList == []: print "Error : failed to parse view qb_troop_list_view !" continue if drag == 0: # first one is the search box del _groupList[0] for group in _groupList: if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() # 我创建的群(16) 这样的一行 notGroup = self.getTextByMonkeyView(group.children[0]) if notGroup: # print "Info : this is not a group %s !" % notGroup continue groupNameView = group.children[1].children[2].children[1] item = { 'groupName': self.getTextByMonkeyView(groupNameView), 'drag':drag, # 363 is qb_troop_list_view.top, 156是整个一条group的高度。 'UILocation': group.top + 156/2 + 363, 'msgs': [], 'storedMsgs': [] } # 点击进入到群组会话中,去获取groupId # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。 if item['UILocation'] < 370 or item['UILocation'] > 1760: print "Info : skip this group in case we touch screen incorrectly !" continue groupId = '' if self.touchByMonkeyPixel(1080/2,item['UILocation']) == 0: groupId = self.get_group_id() if groupId in self.groupList.keys(): print "Info : this group %s %s has already exist !" % \ (item['groupName'],groupId) continue self.groupList[groupId] = item print "Info : group info: %s , %s , %s , %s !" % \ (item['groupName'],groupId,item['drag'],item['UILocation']) print "Info : total group count : %s !" % len(self.groupList) for key in self.groupList: print "Info : group info: %s , %s , %s , %s !" % \ (self.groupList[key]['groupName'],key, \ self.groupList[key]['drag'],self.groupList[key]['UILocation']) self.groupListUpdating = 0 return 0 # 获取groupId,结束后仍退出至group def get_group_id(self): # 此时位于群组会话中,点击进入到群组信息里边 groupId = '' if self.is_group() != 0: print "Error : I am not in the group !" return -1 if self.touch_to_enter_info() != 0: return -1 if self.is_info() != 0: print "Error : I am not in the info !" return -1 for i in range(0,3): try: xlist = self.get_hierarchy_view_by_id('id/common_xlistview') nameAndId = xlist.children[0].children[2].children[0].children[1] groupId = self.getTextByMonkeyView(nameAndId.children[1].children[0]) break except: print "Error : failed to get groupId !" continue print "Info : get this group id : %s !" % groupId self.touch_to_leave() return groupId def register_monkey(self): print '------------ register_monkey ------------' groupList = [{'groupId': key, 'groupName': value['groupName']} for key, value in self.groupList.iteritems()] data = { 'cmd': 'register', 'qq': self.qq, 'qqName': self.qqName, 'url': 'http://%s:%s/net_command' % (localIp,self.port), 'groupList': json.dumps(groupList) } url_post(robot_url, data) return 0 def monkey_task_loop(self): print '------------ monkey_task_loop start ------------' # this should never return while(1): # if self.is_home_screen() != 0: # continue sleep(1) if self.screenUsing == 0: self.heartbeat += 1 if self.heartbeat == 600: self.get_pure_group_list_monkey() self.heartbeat = 0 else: self.heartbeat = 0 ### api for robot manager # 此处,不考虑UILocation def enter_group(self,data): print '\n------------ enter_group ------------' if self.groupListUpdating == 1: print "Info : groupList is updating now ! Please wait about 2 minutes !" return 1 if data['group'] not in self.groupList: print "Error : failed to find in the grouplist %s !" % data['group'] return -1 if self.currentGroup['groupId'] != data['group']: self.currentGroup['groupId'] = data['group'] self.currentGroup['groupName'] = self.groupList[data['group']]['groupName'] if self.is_current_group() == 0: return 0 if self.touch_to_enter_grouplist() != 0: return -1 groupId = '' # 通过possibleDrag来缩小查找范围。然后从该页的自己、前、后 三个界面查找。 # 下一步,可以通过possibleIndex,在自己界面进一步缩小查找范围。 # 在前界面,从后往前查找;在后界面,从前往后查找。 possibleDrag = self.groupList[ data['group'] ]['drag'] possibleUILocation = self.groupList[ data['group'] ]['UILocation'] print "Info : possibleDrag %s , possibleUILocation %s to enter group %s !" % \ (possibleDrag, possibleUILocation, data['group']) if possibleDrag > 0: for i in range(0,possibleDrag): self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1) # sleep(1) # 现在,前,后的顺序查找三个界面 for j in range(0,3): if self.is_grouplist() != 0: if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() if possibleDrag == 0: if j != 0: # 向下drag一次 self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1) else: if j == 1: # 向上drag一次 self.device.drag((1080/2, 400),(1080/2, 1700),0.5,1) if j == 2: # 向下drag一次 self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1) self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1) # 每次j==0的时候,首先看下possibleUILocation对应的group if j == 0: for i in range(0,3): try: if self.touchByMonkeyPixel(1080/2,possibleUILocation) == 0: groupId = self.get_group_id() except: print "Error : failed to parse the possibleUILocation group !" if groupId == data['group']: return 0 else: # 不是这个群,就退出至grouplist界面 if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() continue qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view') if qb_troop_list_view == None: continue _groupList = [] _groupList = qb_troop_list_view.children if _groupList == []: print "Error : failed to parse view qb_troop_list_view !" continue if possibleDrag == 0: # first one is the search box del _groupList[0] elif possibleDrag == 1: if j == 1: del _groupList[0] for group in _groupList: if self.is_info() == 0: self.touch_to_leave() if self.is_group() == 0: self.touch_to_leave() if self.is_grouplist() != 0: return -1 # 我创建的群(16) 这样的一行 notGroup = self.getTextByMonkeyView(group.children[0]) if notGroup: continue # groupNameView = group.children[1].children[2].children[1] # groupName = self.getTextByMonkeyView(groupNameView) # if groupName != self.groupList.get(data['group']).get('groupName'): # continue # 363 is qb_troop_list_view.top, 156是整个一条group的高度。 UILocation = group.top + 156/2 + 363 # groupName对了,然后看groupId。暂时不要去解析groupName,耗时 # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。 if UILocation < 370 or UILocation > 1760: print "Info : skip this group in case we touch screen incorrectly !" continue if self.touchByMonkeyPixel(1080/2,UILocation) == 0: groupId = self.get_group_id() if groupId == data['group']: return 0 print "Error : failed to enter group %s !" % data['group'] return -1 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 get_msgs(self,data): print '\n------------ get_msgs ------------' if self.is_current_group() != 0: ret = [] return ret # 针对新消息的提示处理 for i in range(0,3): self.device.drag((1080/2, 1600),(1080/2, 500),0.2,1) self.currentGroup['msgs'] = [] dragCount = 3 msgs = [] is_stop_drag = 0 for msgDrag in range(0, dragCount): if is_stop_drag: break if msgDrag !=0: self.device.drag((1080/2, 500),(1080/2, 1600),0.2,1) hViewer = None _msgs = [] try: listView1 = self.get_hierarchy_view_by_id('id/listView1') # 该行会出现AttributeError: 'NoneType' object has no attribute 'children _msgs = listView1.children except: print "Error : failed to parse view : listView1 !" # print 'msgs count : ', len(_msgs)-1 #最后一个为输入框 # reverse()不可用java.Arraylist tmpMsgs = [] for m in _msgs: tmpMsgs.insert(0, m) for m in tmpMsgs: if 'BaseChatItemLayout' not in str(m): continue item = {} item['nickname'] = '' layoutLeft = '' for t in m.children: if t.id == 'id/chat_item_head_icon': layoutLeft = t.namedProperties.get('layout:mLeft').value.encode('utf8') if layoutLeft == '930': break if t.id == 'id/chat_item_nick_name': item['nickname'] = self.getTextByMonkeyView(t) if t.id == 'id/chat_item_content_layout': item['content'] = self.getTextByMonkeyView(t) if layoutLeft == '930': continue else: if item['nickname'].endswith(':'): item['nickname'] = item['nickname'][0:-1] #此处时间暂不考虑如 Friday 10:46 的情况 c = self.getDescByMonkeyView(m) item['time'] = c[0:c.find(' ')] # 已存储的消息,则没有必要往前drag了。 if item in self.currentGroup['storedMsgs']: is_stop_drag = 1 break # 未存储,则为新消息.如前一次drag已得到,则跳过。 if item in msgs: continue msgs.append(item) while(msgDrag>0): self.device.drag((1080/2, 1600),(1080/2, 500),0.2,1) msgDrag -= 1 if msgs: self.currentGroup['msgs'] = msgs print "Info : new msgs count : %s !" % len(msgs) for m in self.currentGroup['msgs']: print m['nickname'], m['content'], m['time'] # default: store the last 10 msgs self.currentGroup['storedMsgs'] += self.currentGroup['msgs'] print 'Info : stored msgs count ', len(self.currentGroup['storedMsgs']) if len(self.currentGroup['storedMsgs']) > 30: self.currentGroup['storedMsgs'] = self.currentGroup['storedMsgs'][-10:] self.groupList[self.currentGroup['groupId']]['storedMsgs'] = self.currentGroup['storedMsgs'] # for n in self.currentGroup['storedMsgs']: # print n['nickname'], n['content'], n['time'] return self.currentGroup['msgs']
# Runs the component easy_device.startActivity( component='cn.richinfo.thinkdrive/.ui.activities.NavigateActivity') # sleep 2's MonkeyRunner.sleep(2) # Takes a screenshot result = device.takeSnapshot() # Writes the screenshot to a file filepath = path + "/Test4_001.png" result.writeToFile(filepath, 'png') # Click username input box easy_device.touch(By.id('id/edt_account'), MonkeyDevice.DOWN_AND_UP) # Input username # Problem: . device.type('*****@*****.**') #device.type('you@demo') #device.type('.cn') print('Input username: [email protected]') # Click password input box easy_device.touch(By.id('id/edt_password'), MonkeyDevice.DOWN_AND_UP) # Input password device.type('123qwe') print('Input password: 123qwe') # Press the Back Key device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
class wrapEasyMonkey: ''' ############################# Wrap easy monkey class ############################# ''' def __init__(self, deviceId): device = MonkeyRunner.waitForConnection(10, deviceId) self.debug( "__int__: creating the wrap easy monkey object with deviceid %s" % deviceId) self.deviceId = deviceId self.easyDevice = EasyMonkeyDevice(device) self.device = device #self.DOWN = TouchPressType.DOWN.getIdentifier() #self.UP = TouchPressType.UP.getIdentifier() #self.DOWN_AND_UP = TouchPressType.DOWN_AND_UP.getIdentifier() self.DOWN = self.device.DOWN self.UP = self.device.UP self.DOWN_AND_UP = self.device.DOWN_AND_UP self.caseManager = testCaseManager(self) self.debug('created the wrapEasyDevice') def waitForConnection(self, seconds): try: return MonkeyRunner.waitForConnection(seconds) except: self.error("waitForConnection error") sys.exc_info() traceback.print_exc() return None def startActivity(self, activity): try: self.debug("starting the activity... %s" % activity) self.device.startActivity(component=activity) except: self.error("starting the activity %s error" % activity) sys.exc_info() traceback.print_exc() return False ''' type charactors, special charactors please the press function to input the keycode ''' def type(self, content): self.debug('device input the %s' % content) self.device.type(content) ''' press keycode, special charactor and direction button ... ''' def press(self, keycode, type): self.debug('device press the key "%s" ' % keycode) #self.sleep(0.2) self.device.press(keycode, type) ''' sleep function ''' def sleep(self, seconds): self.debug('sleeping %f seconds' % seconds) MonkeyRunner.sleep(seconds) ''' wrap easyMonkeyDevice by function will return the view object if found.if do not found will return None. ''' def getView(self, id): self.debug('calling getview function by the id (%s)' % id) for tmp in range(repeatTimesOnError): try: return By.id(id) except: self.debug( 'getView: the %dst time error by id (%s) , will retry ' % (tmp, id)) MonkeyRunner.sleep(1) continue self.error( 'getView: sorry , still can\'t get the view by this id (%s). please check the view ' % id) sys.exc_info() traceback.print_exc() return None ''' if the id object is a textview, then will clear all the text ''' def clearTextById(self, id): self.debug('calling clearTextById function by the id (%s)' % id) if (self.checkIdExist(id)): if not self.isFocused(id): self.touchViewById(id, self.DOWN_AND_UP) TextView = self.getView(id) rangenumber = len(self.getText(TextView)) for x in range(rangenumber): self.device.press('KEYCODE_DEL', self.DOWN_AND_UP) for x in range(rangenumber): self.device.press('KEYCODE_FORWARD_DEL', self.DOWN_AND_UP) self.debug('clearTextById: cleared the text in id (%s)' % id) return True self.error('clearTextById: sorry ,the id (%s) is not exist ' % id) sys.exc_info() traceback.print_exc() return False ''' wrap get text function. return text string content of the view object. If can not found the view object , will return None. ''' def getText(self, view): self.debug('calling getText function') for tmp in range(repeatTimesOnError): try: return self.easyDevice.getText(view).encode( sys.getdefaultencoding()) except: self.debug( 'getText: the %dst time getText error , will retry ' % tmp) MonkeyRunner.sleep(1) continue self.error( 'getText: sorry , still can\'t get the text. please check the view is exist or not , or does the view have text property?' ) sys.exc_info() traceback.print_exc() return None ''' ''' def getTextById(self, id): self.debug('calling getTextById function') for tmp in range(repeatTimesOnError): try: return self.getText(self.getView(id)) except: self.debug( 'getTextById: the %dst time getTextById error id (%s) , will retry ' % (tmp, id)) MonkeyRunner.sleep(1) continue self.error( 'getTextById: sorry , still can\'t get the text by id "%s". please check the view is exist or not , or does the view have text property?' % id) sys.exc_info() traceback.print_exc() return None ''' wrap easyMonkeyDevice touch view function return true or false (if cannot locate the view ,will return false) ''' def touchView(self, view, type): self.debug('calling touchView function') for tmp in range(repeatTimesOnError): try: self.easyDevice.touch(view, type) return True except: self.debug( 'touchView: the %dst time touch error , not found the view , will retry ' % tmp) if (tmp > 1 & DEBUG): self.debug('Please wait to touch the view') MonkeyRunner.sleep(1) continue self.error( 'touchView: sorry , still can\'t touch view. please check the view is exist or not , or increase the repeat times variable?' ) sys.exc_info() traceback.print_exc() return False def touchViewById(self, id, type): self.debug('calling touchViewById function') for tmp in range(repeatTimesOnError): try: self.easyDevice.touch(By.id(id), type) return True except: self.debug( 'touchViewById: the %dst time touch error by this id (%s) , not found the view , will retry ' % (tmp, id)) if (tmp > 1 & DEBUG): self.debug('Please wait to touch the view') MonkeyRunner.sleep(1) continue self.error( 'touchViewById: sorry , still can\'t touch view. please check the view is exist or not , or increase the repeat times variable?' ) sys.exc_info() traceback.print_exc() return False ''' wrap touch point function , touch screen position return true or false always return true actually ''' def touchPoint(self, x, y, type): self.debug('calling touch the point ') for tmp in range(repeatTimesOnError): try: self.device.touch(x, y, type) return True except: self.debug( 'touchPoint: %d time touch point error , will retry ' % tmp) MonkeyRunner.sleep(1) continue self.error( 'touchPoint: sorry , still can\'t touch point. please check the view is exist or not , or increase the repeat times variable?' ) sys.exc_info() traceback.print_exc() return False ''' has the view is focused or not ''' def isFocused(self, id): self.debug('checking the view is focused or not') #hierarchyViewer = self.device.getHierarchyViewer() #print hierarchyViewer.findViewById(id).hasFocus for tmp in range(repeatTimesOnError): try: hierarchyViewer = self.device.getHierarchyViewer() return hierarchyViewer.findViewById(id).hasFocus except: self.debug( 'isFocused: the %dst time check focus error , will retry ' % tmp) MonkeyRunner.sleep(1) continue self.error('isFocused: error occured') sys.exc_info() traceback.print_exc() return False ''' ''' def isExist(self, id): #self.debug('check the id is exist or not') for tmp in range(repeatTimesOnError): try: if (self.easyDevice.exists(self.getView(id))): return True else: self.debug( 'isExist: %s this id does not exists,will try check again' % id) MonkeyRunner.sleep(1) continue except: self.debug( 'isExist: the %dst time check id (%s) existing error , , will retry ' % (tmp, id)) MonkeyRunner.sleep(1) continue self.error('isExist: error occured') sys.exc_info() traceback.print_exc() return False def checkIdExist(self, id): self.debug('checking the id (%s) exist or not' % id) for tmp in range(repeatTimesOnError): try: if (self.easyDevice.exists(self.getView(id))): return True else: self.debug( 'checkIdExist: %s this id does not exists,will try check again' % id) MonkeyRunner.sleep(1) continue except: self.debug( 'checkIdExist: the %dst time check id (%s) existing error , , will retry ' % (tmp, id)) MonkeyRunner.sleep(1) continue self.error('checkIdExist: error occured') sys.exc_info() traceback.print_exc() return False def getPosition(self, id): self.debug('check the view is focused or not') for tmp in range(repeatTimesOnError): try: hierarchyViewer = self.device.getHierarchyViewer() print hierarchyViewer.findViewById(id).left print hierarchyViewer.findViewById(id).top print hierarchyViewer.findViewById(id).width print hierarchyViewer.findViewById(id).height return hierarchyViewer.findViewById(id).left except: MonkeyRunner.sleep(1) continue self.error('getPosition: error occured') sys.exc_info() traceback.print_exc() return None def touchDialogById(self, id, type): #self.debug('touch the dialog button , here need the parent id') hierarchyViewer = self.device.getHierarchyViewer() width = self.device.getProperty("display.width") height = self.device.getProperty("display.height") x = hierarchyViewer.findViewById(id).left y = hierarchyViewer.findViewById(id).top ''' print hierarchyViewer.findViewById(id).scrollX print hierarchyViewer.findViewById(id).scrollY print hierarchyViewer.findViewById(id).marginTop print hierarchyViewer.findViewById(id).marginLeft print hierarchyViewer.findViewById(id).marginRight print hierarchyViewer.findViewById(id).marginBottom print hierarchyViewer.findViewById(id).left print hierarchyViewer.findViewById(id).top print hierarchyViewer.findViewById(id).width print hierarchyViewer.findViewById(id).height print 'margin' print width print height print hierarchyViewer.findViewById(id).properties print '------------------' ''' p = hierarchyViewer.findViewById(id).parent.parent #print p.properties myself = hierarchyViewer.findViewById(id) content = hierarchyViewer.findViewById('id/content') x += p.left + (int(width) - content.width) / 2 + myself.width / 2 y += p.top + (int(height) - content.height) / 2 + myself.height / 2 #( int(width) - hierarchyViewer.findViewById(id).width)/2 + hierarchyViewer.findViewById(id).left + hierarchyViewer.findViewById(id).width/2 #y += ( int(height) - hierarchyViewer.findViewById(id).height)/2 + hierarchyViewer.findViewById(id).top + hierarchyViewer.findViewById(id).height/2 #print x #print y self.touchPoint(x, y, type) def touchDialog(self, parentIdPosition, id, type): self.debug('touch the dialog button , here need the parent id') hierarchyViewer = self.device.getHierarchyViewer() #print hierarchyViewer.findViewById(parentId).left #print hierarchyViewer.findViewById(parentId).top x = hierarchyViewer.findViewById( parentId).left + (hierarchyViewer.findViewById(parentId).width - hierarchyViewer.findViewById(id).width) / 2 y = hierarchyViewer.findViewById( parentId).top + (hierarchyViewer.findViewById(parentId).height - hierarchyViewer.findViewById(id).height) / 2 print x print y self.touchPoint(x, y, type) def touchDialogButton(self, type): if DEBUG: self.debug( 'touch the dialog button , thru controling the direction key') #self.device.press('KEYCODE_DPAD_DOWN',MonkeyDevice.DOWN_AND_UP) if type == 1: self.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #self.press('KEYCODE_DPAD_DOWN',MonkeyDevice.DOWN_AND_UP) self.press('KEYCODE_ENTER', MonkeyDevice.DOWN_AND_UP) if type == 2: #self.press('KEYCODE_DPAD_DOWN',MonkeyDevice.DOWN_AND_UP) self.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) self.press('KEYCODE_DPAD_RIGHT', self.DOWN_AND_UP) self.press('KEYCODE_ENTER', self.DOWN_AND_UP) if type == 0: self.press('KEYCODE_ENTER', self.DOWN_AND_UP) def touchContextMenu(self, position): if DEBUG: self.debug('touch the context menu') self.press('KEYCODE_MENU', self.DOWN_AND_UP) for tmp in range(position + 1): MonkeyRunner.sleep(0.5) self.press('KEYCODE_DPAD_RIGHT', self.DOWN_AND_UP) self.press('KEYCODE_ENTER', self.DOWN_AND_UP) ''' def touchDialogButtonRight(self,type): self.device.press('KEYCODE_DPAD_DOWN',type) self.device.press('KEYCODE_DPAD_DOWN',type) self.device.press('KEYCODE_DPAD_RIGHT',type) self.device.press('KEYCODE_ENTER',type) ''' def debug(self, debuginfo): if DEBUG: print '[%s] DEBUG: %s ' % (datetime.today(), debuginfo) def info(self, info): if INFO: print '[%s] Info: %s ' % (datetime.today(), info) def error(self, error): if ERROR: print '[%s] ERROR: %s ' % (datetime.today(), error) def takeSnapshot(self): print '----------start take snapshot-------------' for tmp in range(5): try: snapshot = self.device.takeSnapshot() print '----------end take snapshot-%s------------' % datetime.today( ) return snapshot except: continue self.error('takeSnapshot: error occured') sys.exc_info() traceback.print_exc() return False
# -*- coding:utf-8 -*- ''' Created on 2017年10月14日 @author: liuguoping ''' from com.android.monkeyrunner import MonkeyRunner from com.android.monkeyrunner import MonkeyDevice from com.android.monkeyrunner import MonkeyImage from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By device = MonkeyRunner.waitForConnection(6, 'emulator-5554') device.installPackage( 'C:\\Users\\liuguoping\\Downloads\\app-product-release.apk') device.startActivity( component='com.zerozero.hover/.newui.splash.SplashActivity') easy_device = EasyMonkeyDevice(device) easy_device.touch(By.id('com.zerozero.hovertest:id/btnCloseTerms'), MonkeyDevice.DOWN_AND_UP) # device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP) # device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP) device.press()
#!/usr/bin/env python # -*- coding: utf-8 -*- # coding:utf-8 import sys from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By import subprocess device = MonkeyRunner.waitForConnection(10.0, "127.0.0.1:21503") easyDevice = EasyMonkeyDevice(device) if True == easyDevice.visible(By.id('id/button1')): print "find" easyDevice.touch(By.id('id/button2'), MonkeyDevice.DOWN_AND_UP) print easyDevice.locate(By.id('id/button2')) MonkeyRunner.sleep(2)
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice from com.android.monkeyrunner.easy import EasyMonkeyDevice, By device = MonkeyRunner.waitForConnection('CB512FSJWB') device.installPackage('/Users/.../app-release.apk') package = 'com.package.name' activity = 'MainActivity' runComponent = package + '/' + activity device.startActivity(component=runComponent) easy_device = EasyMonkeyDevice(device) # com.android.packageinstaller:id/permission_allow_button easy_device.touch(By.id('permission_allow_button'),MonkeyDevice.DOWN_AND_UP) easy_device.touch(By.id('imageView'),MonkeyDevice.DOWN_AND_UP) # result = device.takeSnapshot() # result.writeToFile('/Users/.../snowy/try/shot1.png','png')
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice from com.android.monkeyrunner import MonkeyImage from com.android.monkeyrunner.easy import EasyMonkeyDevice #from com.android.monkeyrunner.easy import HierarchyViewer from com.android.monkeyrunner.easy import By #from com.android.hierarchyviewerlib.device import ViewNode device = MonkeyRunner.waitForConnection(0,"SH13TPL09945") easy_device = EasyMonkeyDevice(device) print 'start Contacts' #device.installPackage('./es.apk') #device.shell('am start -a android.intent.action.MAIN -n com.android.contacts/.DialtactsContactsEntryActivity') device.startActivity(component='netease.pomelo.chat/.MainActivity') MonkeyRunner.sleep(3) #text=easy_device.visible(By.id('id/phoneNumber')) #print text hierarchy_viewer = device.getHierarchyViewer() view_node=hierarchy_viewer.findViewById('id/channel') print view_node easy_device.touch(By.id('id/channel'),device.DOWN_AND_UP) device.type('mychn\n') view_node=hierarchy_viewer.findViewById('id/name') print view_node easy_device.touch(By.id('id/name'),device.DOWN_AND_UP) device.type('myname\n') #device.press('KEYCODE_DPAD_DOWN', 'DOWN_AND_UP')
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')
def filter_contacts(device): easy_device = EasyMonkeyDevice(device) start_activity(device, ".StartActivity") easy_device.touch(By.id("id/mpp_menu_toggle_filter_box"), MonkeyDevice.DOWN_AND_UP)
device = MonkeyRunner.waitForConnection() #start activity print('start activity') package = 'com.android.calculator2' activity = 'com.android.calculator2.Calculator' runComponent = package + '/' + activity device.startActivity(component=runComponent) MonkeyRunner.sleep(3) #init easymonkeydevice object ,this is init method print('init easymonkeydevice') easy_device = EasyMonkeyDevice(device) print('Tap 8') easy_device.touch(By.id('id/digit_8'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1.0) print('Tap *') easy_device.touch(By.id('id/op_mul'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1.0) print('Tap 9') easy_device.touch(By.id('id/digit_9'), MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(1.0) #print('Tap =') #easy_device.touch(By.id('id/eq'),MonkeyDevice.DOWN_AND_UP) if easy_device.exists(By.id('id/result')) == True: text_result = easy_device.getText(By.id('id/result')) if text_result.encode('utf-8') == "72": print("乘法运算正确") else:
# Take Snapshot take_Snapshot() # ====================================================================== # Record # [537,873][617,953] [577,913] device.touch(577, 913, 'DOWN_AND_UP') # Take Snapshot take_Snapshot() # Start recording # [280,1109][439,1268] [359,1188] # device.touch(326,232,'DOWN_AND_UP') easy_device.touch(By.id('id/start'), MonkeyDevice.DOWN_AND_UP) # Take Snapshot take_Snapshot() # Stop recording # [280,1109][439,1268] [359,1188] # device.touch(326,232,'DOWN_AND_UP') easy_device.touch(By.id('id/stop'), MonkeyDevice.DOWN_AND_UP) # Take Snapshot take_Snapshot() # Sava the recording # easy_device.touch(By.id('id/save'), MonkeyDevice.DOWN_AND_UP) # [80,567][640,621] [360,594]
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By device = MonkeyRunner.waitForConnection() device.startActivity(component="com.tencent.mobileqq/.activity.SplashActivity") easy_device = EasyMonkeyDevice(device) device.press('KEYCODE_DPAD_DOWN', 'DOWN_AND_UP') MonkeyRunner.sleep(3) # (this is very import) easy_device.touch(By.id('id/btn_login'), MonkeyDevice.DOWN_AND_UP) device.touch(120, 397, 'DOWN_AND_UP') device.type('893026750') # easy_device.touch(By.id('id/password'), MonkeyDevice.DOWN_AND_UP) # # device.type('hongnaiwu3425') # # easy_device.touch(By.id('id/login'), MonkeyDevice.DOWN_AND_UP) # # device.press('KEYCODE_BACK','DOWN_AND_UP')
# Take Snapshot take_Snapshot() # ====================================================================== # Record # [537,873][617,953] [577,913] device.touch(577,913,'DOWN_AND_UP') # Take Snapshot take_Snapshot() # Start recording # [280,1109][439,1268] [359,1188] # device.touch(326,232,'DOWN_AND_UP') easy_device.touch(By.id('id/start'), MonkeyDevice.DOWN_AND_UP) # Take Snapshot take_Snapshot() # Stop recording # [280,1109][439,1268] [359,1188] # device.touch(326,232,'DOWN_AND_UP') easy_device.touch(By.id('id/stop'), MonkeyDevice.DOWN_AND_UP) # Take Snapshot take_Snapshot() # Sava the recording # easy_device.touch(By.id('id/save'), MonkeyDevice.DOWN_AND_UP) # [80,567][640,621] [360,594]
#!/usr/bin/python #encoding:utf-8 #encoding=gbk ''' Created on 2014年11月11日 @author: EnphoneH ''' from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage from com.android.monkeyrunner.easy import EasyMonkeyDevice from com.android.monkeyrunner.easy import By from com.android.chimpchat.hierarchyviewer import HierarchyViewer device = MonkeyRunner.waitForConnection() easy_device = EasyMonkeyDevice(device) #init easymonkeydevice object must start activity at first.Because the init method hierarchyviewer = device.getHierarchyViewer() #menu = hierarchyviewer.findViewByid('id/Menu_button') for j in range(0,10000): easy_device.touch(By.id('id/Menu_button'),MonkeyDevice.DOWN_AND_UP) print("点击:" + str(j) + "次") MonkeyRunner.sleep(3)
#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')
device.touch(400,1000,MonkeyDevice.DOWN_AND_UP) image2 = device.takeSnapshot() subimage2 = image.getSubImage((300,50,356,234)) if (subimage2.sameAs(subimage,0.8)): print '[PASS] the result of 3*8 and 4*6 is equal!' else: print '[Fail] the result of 3*8 and 4*6 is not equal!' print '******Case2: Use EasyMonkeyDevice to check claculator result******' print '---- calculator 5*7 with EasyMonkeyDevice touch' easy = EasyMonkeyDevice(device) easy.touch(By.id('id/digit5'),MonkeyDevice.DOWN_AND_UP) easy.touch(By.id('id/mul'),MonkeyDevice.DOWN_AND_UP) easy.touch(By.id('id/digit7'),MonkeyDevice.DOWN_AND_UP) easy.touch(By.id('id/equal'),MonkeyDevice.DOWN_AND_UP) hv=device.getHierarchyViewer() view = hv.findViewById('id/display') str =view.children[1].namedProperties.get('text:mText').toString().encode('utf8') if (str == '35'): print '[PASS] the result of 5*7 is correct!' else: print '[Fail] the result of 5*7 is correct! the result is -- ' +str easy.touch(By.id('id/clear'),MonkeyDevice.DOWN_AND_UP)