class NineGameEmulate(): def __init__(self): self.device = None self.serialno = None self.vc = None self.accountfilename = '360mobile_imei_list.'+time.strftime('%Y-%m-%d',time.localtime(time.time())) def openapp(self): self.device,self.serialno = ViewClient.connectToDeviceOrExit(serialno=None) FLAG_ACTIVITY_NEW_TASK = 0x10000000 componentName = 'com.qihoo.browser/.activity.SplashActivity' self.device.startActivity(component=componentName,flags=FLAG_ACTIVITY_NEW_TASK) ViewClient.sleep(3) self.vc = ViewClient(self.device,self.serialno,forceviewserveruse=True) def doSomeClick(self,imei,imsi=None): if self.device == None : self.openapp() #self.device.dragDip((400,400),(10,400),800,5) #ViewClient.sleep(3) #self.device.dragDip((400,400),(10,400),800,5) #ViewClient.sleep(3) #waitViewByTx('立即修复',self.vc) #self.vc.findViewWithText('立即修复').touch() ViewClient.sleep(1) self.device.drag((600,400),(10,400),2000) ViewClient.sleep(1) self.device.drag((600,400),(10,400),2000) self.vc.dump() waitViewById('id/ensure',self.vc) #self.vc.findViewById('id/ensure').touch() self.device.touch(345,1070,2) ViewClient.sleep(2) waitViewById('id/first_nav',self.vc) self.vc.findViewById('id/first_nav').touch() ViewClient.sleep(5) f = open(self.accountfilename,'a') try: f.writelines(imei+"\t"+imsi+"\r\n") finally: f.flush() f.close() def reactiveMobile(self): if self.device == None : self.openapp() waitViewById('id/rgBottomNav',self.vc) self.device.touch(675,95,2) ViewClient.sleep(3) self.vc.findViewById('id/game_name').touch()
class ViewClientWrapper: def __init__(self, serialno): device, serialno = ViewClient.connectToDeviceOrExit(serialno=serialno) self.vc = ViewClient(device, serialno) self.device = device if DEBUG: print >> sys.stderr, "ViewClientWrapper: connected to", device, serialno def dump(self): """Dumps window hierarchy.""" return self.vc.dump() def touch(self, x, y): """Touches a point. :param x: x :param y: y :return: """ return self.vc.touch(x, y) @staticmethod def long_touch_view(view): """Long-touches the view.""" return view.longTouch() @staticmethod def touch_view(view): """Touches the View""" return view.touch() @staticmethod def get_view_position_and_size(view): """ Gets the View position and size :param view: the View :return: the position and size """ return view.getPositionAndSize() def find_view_with_text(self, text): return self.vc.findViewWithText(text) def find_view_by_id(self, id): return self.vc.findViewById(id) def start_activity(self, component): """Starts Activity.""" return self.vc.device.startActivity(component) def get_top_activity_name(self): return self.device.getTopActivityName() def force_stop_package(self, package): self.device.shell('am force-stop %s' % package) def get_windows(self): return self.device.getWindows() def is_keyboard_show(self): return self.device.isKeyboardShown()
class ViewClientWrapper: def __init__(self, serialno): device, serialno = ViewClient.connectToDeviceOrExit(serialno=serialno) self.vc = ViewClient(device, serialno) self.device = device if DEBUG: print >> sys.stderr, "ViewClientWrapper: connected to", device, serialno def dump(self): """Dumps window hierarchy.""" return self.vc.dump() def touch(self, x, y): """Touches a point. :param x: x :param y: y :return: """ return self.vc.touch(x, y) @staticmethod def long_touch_view(view): """Long-touches the view.""" return view.longTouch() @staticmethod def touch_view(view): """Touches the View""" return view.touch() @staticmethod def get_view_position_and_size(view): """ Gets the View position and size :param view: the View :return: the position and size """ return view.getPositionAndSize() def find_view_with_text(self, text): return self.vc.findViewWithText(text) def find_view_by_id(self, id): return self.vc.findViewById(id) def start_activity(self, component): """Starts Activity.""" return self.vc.device.startActivity(component) def get_top_activity_name(self): return self.device.getTopActivityName() def force_stop_package(self, package): self.device.shell('am force-stop %s' % package) def get_windows(self): return self.device.getWindows() def is_keyboard_show(self): return self.device.isKeyboardShown()
def screen_on_splash(device, serialno): logger.info("get vc on SplashActivity begin...") vc = ViewClient(device=device, serialno=serialno) logger.info("get vc on SplashActivity end") tab_content = vc.findViewById('id/tabcontent') x, y = tab_content.getXY() if x > HORIZON_MID: return 'PROFILE_ENTRY' tab_view = vc.findViewById('id/tabs') if tab_view.children[0].isSelected(): return 'MESSAGES' elif tab_view.children[1].isSelected(): return 'CONTACTS' else: return 'UNKNOWN_SCREEN'
def action_open_editor_and_type_text(device, serialno): print("open editor") # Open My Sites for i in range(5): device.press('KEYCODE_DPAD_LEFT') viewclient = ViewClient(device, serialno) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/fab_button") view.touch() time.sleep(2) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/post_content") # Type a sample text (spaces can't be entered via device.type()) view.type(settings.example_post_content) time.sleep(2)
def action_open_editor_and_type_text(device, serialno): print("open editor") # Open My Sites for i in range(5): device.press('KEYCODE_DPAD_LEFT') viewclient = ViewClient(device, serialno) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/fab_button") view.touch() time.sleep(2) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/post_content") # Type a sample text (spaces can't be entered via device.type()) view.type(settings.example_post_content) time.sleep(2)
def action_open_stats(device, serialno): print("open stats tab") device.press('KEYCODE_TAB') for i in range(5): device.press('KEYCODE_DPAD_LEFT') viewclient = ViewClient(device, serialno) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/row_stats") view.touch() time.sleep(5)
def get_vc_view_by_id(device, serialno, id, retry=1): for i in xrange(retry): try: vc = ViewClient(device=device, serialno=serialno) ret = vc.findViewById(id) except: logger.warning('get viewclient view by id[%s] failed!', id) ret = None if ret: return ret
class NineGameEmulate(): def __init__(self): self.device = None self.serialno = None self.vc = None self.accountfilename = '9game_imei_list.'+time.strftime('%Y-%m-%d',time.localtime(time.time())) def openapp(self): self.device,self.serialno = ViewClient.connectToDeviceOrExit(serialno=None) FLAG_ACTIVITY_NEW_TASK = 0x10000000 componentName = 'cn.ninegame.gamemanager/.activity.MainActivity' self.device.startActivity(component=componentName,flags=FLAG_ACTIVITY_NEW_TASK) ViewClient.sleep(3) self.vc = ViewClient(self.device,self.serialno,forceviewserveruse=True) def doSomeClick(self,imei,imsi=None): if self.device == None : self.openapp() waitViewById('id/rgBottomNav',self.vc) self.device.touch(675,95,2) ViewClient.sleep(3) self.vc.findViewById('id/game_name').touch() ViewClient.sleep(5) f = open(self.accountfilename,'a') try: f.writelines(imei+"\t"+imsi+"\r\n") finally: f.flush() f.close() def reactiveMobile(self): if self.device == None : self.openapp() waitViewById('id/rgBottomNav',self.vc) self.device.touch(675,95,2) ViewClient.sleep(3) self.vc.findViewById('id/game_name').touch()
def action_open_stats(device, serialno): print("open stats tab") device.press('KEYCODE_TAB') for i in range(5): device.press('KEYCODE_DPAD_LEFT') viewclient = ViewClient(device, serialno) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/row_stats") view.touch() time.sleep(5)
class DeviceModify(): def __init__(self): self.device = None self.serialno = None self.vc = None self.openapp() def openapp(self): self.device,self.serialno = ViewClient.connectToDeviceOrExit() FLAG_ACTIVITY_NEW_TASK = 0x10000000 componentName = 'com.example.myxposed/.ParamActivity' self.device.startActivity(component=componentName,flags=FLAG_ACTIVITY_NEW_TASK) ViewClient.sleep(2) self.vc = ViewClient(self.device,self.serialno,forceviewserveruse=True) def modifyRandom(self): waitViewById('id/imei',self.vc) self.vc.findViewById('id/button2').touch() self.vc.dump() deviceIMEI = self.vc.findViewById('id/imei').getText() deviceIMSI = self.vc.findViewById('id/subscriberId').getText() f = open('device_imei.txt','w+') try: print 'save imei %s to file device_imei.txt'%(deviceIMEI) f.writelines(deviceIMEI +"\t"+deviceIMSI) finally: if(f != None): f.close() def modify2IMEI(self,imei,imsi=None): waitViewById('id/imei',self.vc) self.vc.dump() #print 'imei is ',imei self.vc.findViewById('id/imei').setText(imei[0:15]) #if imsi != None: # self.vc.findViewById('id/subscriberId').setText(imsi[0:15]) self.vc.findViewById('id/button1').touch()
def action_open_editor_and_type_text(device, serialno): print("open editor") # Open My Sites for i in range(5): device.press('KEYCODE_DPAD_LEFT') viewclient = ViewClient(device, serialno) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/fab_button") view.touch() time.sleep(2) # Type a sample title device.type(settings.example_post_title) # Switch to the content field device.press('KEYCODE_TAB') # Type a sample content device.type(settings.example_post_content) # Wait for the Webview :/ time.sleep(5)
def action_open_editor_and_type_text(device, serialno): print("open editor") # Open My Sites for i in range(5): device.press('KEYCODE_DPAD_LEFT') viewclient = ViewClient(device, serialno) viewclient.dump() view = viewclient.findViewById("org.wordpress.android:id/fab_button") view.touch() time.sleep(2) # Type a sample title device.type(settings.example_post_title) # Switch to the content field device.press('KEYCODE_TAB') # Type a sample content device.type(settings.example_post_content) # Wait for the Webview :/ time.sleep(5)
def unlock_device(self, udid, pin): pin = map(int, str(pin)) device, serialno = ViewClient.connectToDeviceOrExit() vc = ViewClient(device=device, serialno=udid) if device.isLocked(): print 'device with serial no ' + udid + ' is locked' device.wake() vc.dump() device.shell('input swipe 357 1227 357 680') vc.dump() for item in pin: item = str(item) key = vc.findViewWithText(item) if key: key.touch() else: print 'key not found or locator is incorrect' enter = vc.findViewById('com.android.systemui:id/key_enter') if enter: enter.touch() else: print 'key not found or locator is incorrect' else: print 'device with serial no ' + udid + ' is unlocked'
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 com.dtmilano.android.viewclient import ViewClient, View from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice device, serialno = ViewClient.connectToDeviceOrExit() vc = ViewClient(device=device, serialno=serialno) button = vc.findViewById('id/button1') print "button: ", button.getClass(), button.getId(), button.getCoords()
class LeHaiEmulate(): def __init__(self): self.device = None self.serialno = None self.vc = None self.accountfilename = 'lehai_imei_list.'+time.strftime('%Y-%m-%d',time.localtime(time.time())) def openapp(self): self.device,self.serialno = ViewClient.connectToDeviceOrExit(serialno=None) FLAG_ACTIVITY_NEW_TASK = 0x10000000 componentName = 'com.lehai.ui/com.showself.ui.LoadingActivity' self.device.startActivity(component=componentName,flags=FLAG_ACTIVITY_NEW_TASK) ViewClient.sleep(3) self.vc = ViewClient(self.device,self.serialno,forceviewserveruse=True) def activeMobile(self,imei,imsi=None): if self.device == None : self.openapp() waitViewById('id/quick_guide_viewpager',self.vc) self.device.dragDip((500,300),(30,300),200,2) self.vc.dump() self.device.touch(615,378,2) waitViewById('id/home_bottom_tab5',self.vc) self.vc.findViewById('id/home_bottom_tab5').touch() self.vc.dump() waitViewById('id/btn_login_note_left',self.vc) #self.vc.findViewById('id/btn_login_note_left').touch() self.device.touch(160,1188,2) self.vc.dump() waitViewByTx('乐嗨号注册',self.vc) self.vc.findViewWithText('乐嗨号注册').touch() self.vc.dump() name = ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(5))) self.vc.findViewById('id/et_lehai_reg_account').setText(name) self.vc.findViewById('id/et_reg_password').setText('abc1234') self.vc.findViewById('id/btn_lehai_reg').touch() self.vc.dump() waitViewById('id/btn_register_finish',self.vc) self.vc.findViewById('id/btn_register_finish').touch() self.vc.dump() waitViewById('id/imageView_classify_more_recommend',self.vc) self.vc.findViewById('id/imageView_classify_more_recommend').touch() ViewClient.sleep(5) f = open(self.accountfilename,'a') try: f.writelines(name+"\t"+imei+"\t"+imsi+"\r\n") finally: f.flush() f.close() def reactiveMobile(self): if self.device == None : self.openapp() waitViewById('id/rgBottomNav',self.vc) self.device.touch(675,95,2) ViewClient.sleep(3) self.vc.findViewById('id/game_name').touch()
def refresh(): try: cdir=os.getcwd() adir=str(glob.glob(cdir + "/" + "logcat.txt")) cut=adir.split("/") before=cut[-1] global final final=before.replace("']", "") if final=="logcat.txt": print("Log file found Removing now.....") os.remove(final) else: print("No log File found....") from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) device.shell("input keyevent KEYCODE_HOME") vc.dump() for i in range(6): from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewById("android:id/switch_widget").touch() vc.dump() time.sleep(3) vc.findViewById("android:id/switch_widget").touch() vc.dump() device.shell("input keyevent KEYCODE_HOME") vc.dump() break else: os.system("adb shell input swipe 876 856 102 949 ") time.sleep(1) from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewById("android:id/switch_widget").touch() vc.dump() time.sleep(3) vc.findViewById("android:id/switch_widget").touch() vc.dump() device.shell("input keyevent KEYCODE_HOME") vc.dump() break os.system("adb logcat -d time >> logcat.txt") time.sleep(4) file=open("logcat.txt", "r") lines= file.read() if "ims registered= true" in lines: sheet1.write(j,0,PLMN) sheet1.write(j,1,"PASS") time.sleep(1) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"Registration.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"Registration.png "+fin+PLMN+"Registration.png" ) time.sleep(1) print("writing1") file.close() else: sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL") time.sleep(1) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"Registration.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"Registration.png "+fin+PLMN+"Registration.png" ) time.sleep(1) print("writing1") file.close() except: print("An Exception occured......")
def Network(): try: from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("MAI TEST"): vc.dump() if vc.findViewById("android:id/button1"): vc.dump() time.sleep(1) vc.findViewById("android:id/button1").touch() vc.dump() print("clicked") else: time.sleep(15) else: print"" check() if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): print("4g") os.system("adb shell cmd statusbar collapse") refresh() elif String==str("3G") or combine==str("No signal") or sets==str("4G No signal"): print("3g") time.sleep(1) cdir=os.getcwd() adir=str(glob.glob(cdir + "/" + "logcat.txt")) cut=adir.split("/") before=cut[-1] final=before.replace("']", "") if final=="logcat.txt": print("Log file found Removing now.....") os.remove(final) else: print("No log file found...........") time.sleep(1) os.system("adb shell cmd statusbar collapse") for i in range(4): from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewWithText("Mobile network").touch() vc.dump() break else: os.system("adb shell input swipe 876 856 102 949 ") time.sleep(1) from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewWithText("Mobile network").touch() vc.dump() break from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) vc.findViewWithText("Carrier").touch() vc.dump() try: if not vc.findViewWithText("Automatic") and not vc.findViewWithText("Disable auto-select"): time.sleep(50) vc.dump() check() os.system("adb shell cmd statusbar collapse") if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): refresh() else: time.sleep(1) if vc.findViewWithText(u"中国联通 4G"): vc.dump() vc.findViewWithText(u"中国联通 4G").touch() time.sleep(8) vc.dump() if not vc.findViewWithText("MAI TEST"): time.sleep(32) vc.dump() if vc.findViewWithText("MAI TEST"): vc.dump() PassRegister() elif vc.findViewWithText("Network registration failed"): vc.dump() FailRegister() elif vc.findViewWithText(u"中国联通 LTE"): vc.dump() vc.findViewWithText(u"中国联通 LTE").touch() time.sleep(8) vc.dump() if not vc.findViewWithText("MAI TEST"): time.sleep(32) vc.dump() if vc.findViewWithText("MAI TEST"): vc.dump() PassRegister() elif vc.findViewWithText("Network registration failed"): vc.dump() FailRegister() else: sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL") check() os.system("adb shell cmd statusbar collapse") if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): refresh() else: print("") except: print("An Exception occured......") ############################################## ####################################################### try: if vc.findViewWithText("Automatic"): time.sleep(2) vc.dump() vc.findViewById("android:id/switch_widget").touch() vc.dump() vc.findViewById("android:id/button1").touch() time.sleep(50) vc.dump() check() os.system("adb shell cmd statusbar collapse") if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): refresh() else: time.sleep(1) if vc.findViewWithText(u"中国联通 4G"): vc.dump() vc.findViewWithText(u"中国联通 4G").touch() time.sleep(8) if not vc.findViewWithText("MAI TEST") : time.sleep(32) vc.dump() if vc.findViewWithText("MAI TEST"): vc.dump() PassRegister() elif vc.findViewWithText("Network registration failed"): vc.dump() FailRegister() elif vc.findViewWithText(u"中国联通 LTE"): vc.dump() vc.findViewWithText(u"中国联通 LTE").touch() time.sleep(8) vc.dump() if not vc.findViewWithText("MAI TEST"): vc.dump() time.sleep(32) if vc.findViewWithText("MAI TEST"): vc.dump() PassRegister() elif vc.findViewWithText("Network registration failed"): vc.dump() FailRegister() else: sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL") check() os.system("adb shell cmd statusbar collapse") if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): refresh() else: print("") except: print("An Exception occured......") try: if vc.findViewWithText("Disable auto-select"): time.sleep(1) vc.dump() vc.findViewById("android:id/button1").touch() time.sleep(50) vc.dump() check() os.system("adb shell cmd statusbar collapse") if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): refresh() else: time.sleep(1) if vc.findViewWithText(u"中国联通 4G"): vc.dump() vc.findViewWithText(u"中国联通 4G").touch() time.sleep(8) vc.dump() if not vc.findViewWithText("MAI TEST") : time.sleep(32) vc.dump() if vc.findViewWithText("MAI TEST"): vc.dump() PassRegister() elif vc.findViewWithText("Network registration failed"): vc.dump() FailRegister() elif vc.findViewWithText(u"中国联通 LTE"): vc.dump() vc.findViewWithText(u"中国联通 LTE").touch() time.sleep(40) vc.dump() if not vc.findViewWithText("MAI TEST"): time.sleep(32) vc.dump() if vc.findViewWithText("MAI TEST"): vc.dump() PassRegister() elif vc.findViewWithText("Network registration failed"): vc.dump() FailRegister() else: sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL") check() os.system("adb shell cmd statusbar collapse") if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): refresh() else: print("") except: print("An Exception occured......") except: print("An Exception occured......")
sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL to write IMSI") sheet1.write(j,2,"FAIL to write IMSI") sheet1.write(j,3,"FAIL to write IMSI") wb1.save('report.xls') elif str("pass") in linez: os.system("adb shell pm clear com.android.phone") os.system("adb reboot") time.sleep(85) from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("MAI TEST"): vc.dump() if vc.findViewById("android:id/button1"): vc.dump() time.sleep(1) vc.findViewById("android:id/button1").touch() vc.dump() print("clicked") Network() Call() SMS() wb1.save('report.xls') else: print("") else: check()
if True: device.startActivity(component=component) ViewClient.sleep(3) device.press('KEYCODE_DPAD_DOWN') # extra VMT setting WARNING! ViewClient.sleep(1) device.press('KEYCODE_DPAD_CENTER', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #device.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #device.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #device.press('KEYCODE_DPAD_CENTER', "DOWN_AND_UP") #device.press('KEYCODE_DPAD_CENTER', "DOWN_AND_UP") vc = ViewClient(device, serialno) regex = "id/checkbox.*" p = re.compile(regex) found = False for id in vc.getViewIds(): #print id m = p.match(id) if m: found = True attrs = vc.findViewById(id) if attrs['isSelected()'] == 'true': print "Wi-Fi is", if attrs['isChecked()'] != 'true': print "not", print "set" if not found: print "No Views found that match " + regex
activity = 'com.hoard.hoard.SplashScreen' # sets the name of the component to start runComponent = package + '/' + activity # Runs the component device.startActivity(component=runComponent) ViewClient.sleep(1) device.takeSnapshot(reconnect=True).save('./screenshots/favorites/favorites-pre.png','png') vc = ViewClient(*ViewClient.connectToDeviceOrExit()) vc.dump() email = vc.findViewById('com.hoard.hoard:id/login_email') email.type('*****@*****.**') vc.dump() password = vc.findViewById('com.hoard.hoard:id/login_password') password.type('u1') button = vc.findViewByIdOrRaise('com.hoard.hoard:id/login_button') button.touch() vc.dump() device.takeSnapshot(reconnect=True).save('./screenshots/favorites/login-pos.png','png') ViewClient.sleep(3)
activity = '.TemperatureConverterActivity' componentName = package + "/" + activity device = MonkeyRunner.waitForConnection(60, "emulator-5554") if not device: raise Exception('Cannot connect to device') device.startActivity(component=componentName) MonkeyRunner.sleep(5) device.type("123") vc = ViewClient(device) vc.dump() # obtain the views by id celsius = vc.findViewById("id/celsius") if not celsius: raise "Couldn't find View with id/celsius" fahrenheit = vc.findViewById("id/fahrenheit") if not fahrenheit: raise "Couldn't find View with id/fahrenheit" # in android-15 this is text:mText while in previous versions it was just mText version = int(device.getSystemProperty('ro.build.version.sdk')) if version >= 15: c = float(celsius.text_mText()) f = float(fahrenheit.text_mText()) else: c = float(celsius.mText())
'startviewserver': True, 'forceviewserveruse': False, 'autodump': False, 'ignoreuiautomatorkilled': True, 'compresseddump': False } vc = ViewClient(device, serialno, **kwargs2) time.sleep(2) vc.dump(window='-1') start_single_button = vc.findViewByIdOrRaise( "com.greenecomputing.linpack:id/btnsingle") start_single_button.touch() time.sleep(2) vc.dump(window='-1') start_single_button = vc.findViewById( "com.greenecomputing.linpack:id/btnsingle") while not start_single_button: time.sleep(2) vc.dump(window='-1') start_single_button = vc.findViewById( "com.greenecomputing.linpack:id/btnsingle") mflops_single_score = vc.findViewByIdOrRaise( "com.greenecomputing.linpack:id/txtmflops_result") time_single_score = vc.findViewByIdOrRaise( "com.greenecomputing.linpack:id/txttime_result") call([ f_output_result, 'Linpack_MFLOPSSingleScore', 'pass', mflops_single_score.getText(), 'MFLOPS' ])
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # 01-04 18:23:42.000: I/ActivityManager(4288): Displayed com.android.development/.DevelopmentSettings: +379ms package = 'com.android.development' activity = '.DevelopmentSettings' componentName = package + "/" + activity device = MonkeyRunner.waitForConnection(60, "emulator-5554") if not device: raise Exception('Cannot connect to device') device.startActivity(component=componentName) MonkeyRunner.sleep(5) vc = ViewClient(device) vc.dump() showCpu = vc.findViewById("id/show_cpu") showLoad = vc.findViewById("id/show_load") alwaysFinish = vc.findViewById("id/always_finish") if not showLoad.isChecked(): showLoad.touch() if not alwaysFinish.isChecked(): alwaysFinish.touch() if not showCpu.isChecked(): # WARNING: Show CPU usage is de-activated as soon as it's activated, that's why it seems it # is never set showCpu.touch()
# 01-04 18:23:42.000: I/ActivityManager(4288): Displayed com.android.development/.DevelopmentSettings: +379ms package = 'com.android.development' activity = '.DevelopmentSettings' componentName = package + "/" + activity device = MonkeyRunner.waitForConnection(60, "emulator-5554") if not device: raise Exception('Cannot connect to device') device.startActivity(component=componentName) MonkeyRunner.sleep(5) vc = ViewClient(device) vc.dump() showCpu = vc.findViewById("id/show_cpu") showLoad = vc.findViewById("id/show_load") alwaysFinish = vc.findViewById("id/always_finish") if not showLoad.isChecked(): showLoad.touch() if not alwaysFinish.isChecked(): alwaysFinish.touch() if not showCpu.isChecked(): # WARNING: Show CPU usage is de-activated as soon as it's activated, that's why it seems it # is never set showCpu.touch()
'ignoreuiautomatorkilled': True, 'compresseddump': False } vc = ViewClient(device, serialno, **kwargs2) vc.dump('-1') btn_start = vc.findViewByIdOrRaise( "com.wtsang02.sqliteutil.activities:id/btStart") btn_start.touch() finished = False btn_results = None while (not finished): try: time.sleep(5) vc.dump('-1') btn_results = vc.findViewById( "com.wtsang02.sqliteutil.activities:id/btToResults") if btn_results: finished = True except RuntimeError: pass print "benchmark finished" btn_results.touch() time.sleep(1) vc.dump('-1') get_score_with_text(vc, "Insert 200 Statments ") get_score_with_text(vc, "Insert 15000 Statments in Transaction ") get_score_with_text(vc, "Update 500 Statments ") get_score_with_text(vc, "Update 15000 Statments in Transaction ") get_score_with_text(vc, "Select 15000 Statements ") get_score_with_text(vc, "Delete 200 Statments ")
def test2(): vc = ViewClient(*ViewClient.connectToDeviceOrExit()) for i in range(1, 9): view = vc.findViewById("id/no_id/%d" % i) if view: print view.__tinyStr__()
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554',sample = False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device=device self.sample=sample self.contactCounter=0 self.startStatus=False '''the status which indicate whether the contacts activity is started''' #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight #define the point coordinate used to slide screen self.left = (width/4, height/2) self.right = (width/4*3, height/2) self.up = (width/2, height/4) self.down = (width/2, height/4*3) self.center = (width/2, height/2) trace('before instance') self.vc=ViewClient(device, devID) trace('after instance') def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' trace('Starting activity ...') self.device.startActivity(component=componentName) sleep(2) self.startStatus = self.goList() trace('Contacts is started, checking the contacts status...') self.isReady() sleep(2) def stop(self): ''' stop the contacts activity and set the startStatus False ''' self.device.shell('am force-stop %s' % package) trace('force stop contacts package %s' % package) self.startStatus = False def menu(self): ''' press menu ''' self.device.press('KEYCODE_MENU','DOWN_AND_UP') trace('press menu') def scroll(self,down=True,times=1): ''' scoll up or down for some times then touch the highlight submenu item @type down: boolead @param down: scroll down if True or scroll up @type times: int @param times: how many times to scroll ''' keycode = 'KEYCODE_DPAD_DOWN' if down else 'KEYCODE_DPAD_UP' for i in range(times): self.device.press(keycode,'DOWN_AND_UP') trace('scroll %s' % keycode.split('_')[-1].lower()) self.device.press('KEYCODE_ENTER','DOWN_AND_UP') trace('press Enter') def back(self): ''' press back ''' self.device.press('KEYCODE_BACK','DOWN_AND_UP') trace('press back') def slide(self,str,view=None): ''' slide the screen @type: str @param: 'left','right','up','down' @type view: @param view: specify the view, default to None ''' if str not in ['left','right','up','down']: raise SyntaxError("wrong parameter: choose from 'left','right','up' or 'down'") try: cX,cY = view.getCenter() width = view.getWidth() height = view.getHeight() cL = cX - width/4, cY cR = cX + width/4, cY cU = cX, cY - height/4 cD = cX, cY + height/4 except AttributeError: pass (left, right, up, down) = (cL, cR, cU, cD) if view else (self.left, self.right, self.up, self.down) nav = { 'left':{'start':right,'end':left}, 'right':{'start':left,'end':right}, 'up':{'start':down,'end':up}, 'down':{'start':up,'end':down} } self.device.drag(nav[str]['start'], nav[str]['end'], 0.1, 10) trace('slide the screen from %s to %s ' % (nav[str]['start'],nav[str]['end'])) sleep(2) def getView(self,str,cD=False,iD=False,dump=True,regex=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @type dump: boolean @param dump: whether execute dump before findView, depending on whether the screen is changed @return: the view found ''' if dump: trace('before dump') self.vc.dump() trace('after dump') if cD: view=self.vc.findViewWithContentDescription(str) trace('Query view with content description: %s, return is %s' % (str, view is not None)) return view elif iD: view=self.vc.findViewById(str) trace('Query view by id: %s, return is %s' % (str, view is not None)) return view elif regex: view=self.vc.findViewWithAttributeThatMatches('text',re.compile(str)) trace('Query view that match attribute: %s, return is %s' % (str, view is not None)) return view else: view=self.vc.findViewWithText(str) trace('Query view with text: %s, return is %s ' % (str, view is not None)) return view def isReady(self): ''' check whether the contacts is ready. @return: True ''' while True: view=self.getView('Contacts list is being updated to reflect the change of language.') if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def isEmpty(self): ''' check whether the contacts is empty @return: True or False ''' self.check() view=self.getView('No contacts.') if view: trace('Contacts list is empty') return True else: trace('Contacts list is not empty') return False def getCounter(self): ''' get the contacts counter @return: the current contacts counter ''' self.goList() if self.isEmpty(): self.contactCounter=0 else: while True: try: self.contactCounter = int(self.getView('\d+ contacts?',regex=True).getText().split()[0]) break except AttributeError: self.slide('down') sleep(1) trace('current contacts counter is %d' % self.contactCounter) return self.contactCounter def goList(self): ''' check whether the screen is in contacts list view, if not, go list view via pressing back key @return: True ''' while True: view=self.getView("All contacts",cD=True) if not view: self.back() sleep(3) else: if not view.isSelected(): trace('Touch "All contacts"') view.touch() break trace('Goto contacts list view') return True def goEdit(self): ''' check whether the contacts is empty, then select adding and go to edit view. @return: True ''' self.check() try: self.getView('Add Contact',cD=True,dump=False).touch() trace('Touch "Add Contact"') sleep(5) return True except AttributeError: pass try: self.getView('Create a new contact',dump=False).touch() trace('Touch "Create a new contact"') sleep(5) self.getView('Keep local').touch() trace('Select "Keep local"') sleep(5) return True except AttributeError: pass def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.startStatus: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self,title): ''' take snapshot @type title: str @param title: specify the title of snapshot @return: snapshot object ''' snapName = title + '.png' snapFolder = 'snapshot' os.system('if not exist %s\\%s mkdir %s\\%s' % (logPath, snapFolder, logPath, snapFolder)) snapFile = logPath + '\\' + snapFolder + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) trace('take snapshot without the statusbar') result.writeToFile(snapFile,'png') trace('save the snapshot to file: %s ' % snapFile) return result def wipe(self,view): ''' wipe the text in specified view ''' try: self.device.drag(view.getXY(),view.getXY(),1,1) trace('wipe text: %s' % str(view.getText())) self.device.press('KEYCODE_DEL','DOWN_AND_UP') except: Exception('wipe failed') def addContact(self,name='',phone='',email='',address=''): self.goEdit() try: offset = 0 if name: view=self.getView('id/no_id/27',iD=True) trace('type %s' % name) view.type(name) view.touch() if phone: view=self.getView('id/no_id/46',iD=True,dump=False) trace('type %s' % phone) view.type(phone) offset += 4 sleep(2) if email: view=self.getView('id/no_id/' + str(57 + offset), iD=True) trace('type %s' % email) view.type(email) offset += 4 sleep(2) if address: view=self.getView('id/no_id/' + str(68 + offset), iD=True) trace('type %s' % address) view.type(address) sleep(2) view=self.getView('Done',dump=False) view.touch() trace('Touch Done') finally: sleep(5) self.goList() def goEditExistContact(self,searchInfo): ''' go to Edit view of exist contact @type searchInfo: str @param searchInfo: information of contacts @return:True ''' trace('Search a contact to edit') view=self.search(searchInfo) if not view: raise SyntaxError('No '+searchInfo+' contact to edit') view.touch() sleep(4) self.device.press('KEYCODE_MENU') sleep(2) self.device.press('KEYCODE_DPAD_DOWN') sleep(1) self.device.press('KEYCODE_ENTER') sleep(4) return True def editName(self,name): ''' edit Name details of contacts @type name: str @param name: content of Name @return: True ''' #find EditText of Name view = self.getView('id/no_id/27',iD=True) #edit name self.wipe(view) view.type(name) sleep(1) trace("edit contact's name OK") return True def editCompany(self,company): ''' edit Company details of contacts @type company: str @param company: content of Company @return: True ''' view=self.getView('Add organization') if view: trace('Step: add a organization info') view.touch() sleep(1) trace('add the company info') self.device.type(company) sleep(1) else: trace('Step: Edit the organization info') view=self.getView('id/no_id/42',iD=True) self.wipe(view) trace('Edit the company info') self.device.type(company) sleep(1) return True def editDetails(self,contactsInfo,action='update',**editInfo): ''' edit details of contact with add or update @type contactsInfo: str @param contactsInfo: information of contacts @type action: str @param action: 'add' or 'update' details @type editInfo: str @param editInfo: collect all need edit information @return: True ''' self.goEditExistContact(contactsInfo) for fieldName in editInfo: if fieldName not in ['Name','Phone','Email','Address','Company','Website','Nickname','Notes']: raise SyntaxError("wrong parameter: fieldName choose from 'Name','Phone','Email','Address','Company','Website','Nickname','Notes'") if 'update'==action: for updateField in editInfo: if 'Name' == updateField: self.editName(editInfo[updateField]) elif 'Company' == updateField: self.editCompany(editInfo[updateField]) else: self.updateDetails(updateField,editInfo[updateField]) if 'add'==action: for addField in editInfo: if 'Name' == addField: self.editName(editInfo[addField]) elif 'Company' == addField: self.editCompany(editInfo[addField]) else: self.addDetails(addField,editInfo[addField]) self.getView('Done').touch() trace('Click Done') sleep(3) self.goList() return True def addDetails(self,fieldName,content): ''' add details of 'fieldName' with 'content' @type fieldName: str @param fieldName: name of field that will be eidt , e.g: Phone,Email,etc @type content: str @param content: edit content @return:True ''' trace('edit '+fieldName+ ' with add') #touch 'Add another field' while True: try: self.getView('Add another field').touch() sleep(3) break except AttributeError: self.slide('up') sleep(2) #touch fieldName and edit while True: try: self.getView(fieldName).touch() sleep(2) break except AttributeError: view2 = self.getView('id/no_id/2',iD=True,dump=False) self.slide('up',view2) sleep(1) self.device.type(content) sleep(1) trace('edit '+fieldName+' with add OK') return True def updateDetails(self,fieldName,content): ''' update details of 'fieldName' with 'content' @type fieldName: str @param fieldName: name of field that will be eidt , e.g: Phone,Email,etc @type content: str @param content: edit content @return:True ''' trace('Edit field '+fieldName+' info') #find fieldName while not self.getView(fieldName): self.slide('up') sleep(2) #get editView of fieldName view = self.getView(fieldName,dump=False) view2=self.getView(view.getId()[:-2]+str(int(view.getId()[-2:])+6),iD=True) #wipe old content and update with new content self.wipe(view2) sleep(1) view2.type(content) sleep(1) return True def search(self,str): ''' search contact by keyword @type str: str @param str: specify the search keyword @return: the view of search result if search result is not null, else return False ''' trace("start searching...") try: self.getView("Search",True).touch() sleep(2) self.device.type(str) trace("search keyword is: "+str) except AttributeError: if self.isEmpty(): trace("No contacts exist") else: trace("No contacts searched") return False #the id of 1st search result is always 28 return self.getView("id/no_id/28",iD=True) def sortAndViewAs(self, sort=True, first=True): ''' sort and view contact name @type sort: boolean @param sort: whether sort contact name or view contact @type first: boolean @param first: whether sort and view contact by first name or last name @return: boolean ''' trace("start sorting...") self.menu() self.scroll(times=4) sleep(2) sortOrView="Sort list by" if sort else "View contact names as" firstOrLast="First name*" if first else "Last name*" try: self.getView(sortOrView).touch() sleep(1) self.getView(firstOrLast,regex=True).touch() return True except AttributeError: return False finally: self.goList() def favor(self,str,favor=True): ''' add or cancel contact to favorites @type str: str @param str: specify the search string @type favor: boolean @param favor: add if True ''' try: self.search(str).touch() sleep(3) except AttributeError: trace('no matched contact found, operation failed!') self.goList() return False aim, action = ('Add to favorites', 'add') if favor else ('Remove from favorites', 'remov') try: self.getView(aim, cD=True).touch() trace('%s successfully' % aim) except AttributeError: trace('%s has been %sed in favorites, not have to %s repeatedly' % (str, action, action)) sleep(3) self.goList() return True def delete(self,kwd = ''): '''delete one contact @type kwd: string @param kwd: keyword which contact to be delete, if none,delete first contact @return: True if operate sucess, False if operate fail. ''' if self.isEmpty(): trace('Could not find any contact data,no record!') return False find = self.search(kwd) if kwd else self.getView('id/no_id/27',iD=True,dump=False) try: # delete operate find.touch() sleep(4) trace('show contact detail information') self.menu() sleep(3) self.scroll(times=3) trace('choose delete contact') self.getView('OK').touch() sleep(3) return True except AttributeError: return False finally: self.goList()
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' device.startActivity(component=componentName, flags=FLAG_ACTIVITY_NEW_TASK) ViewClient.sleep(3) # Set it to True or False to decide if AndroidViewClient or plain monkeyrunner is used USE_AVC = True if USE_AVC: # AndroidViewClient vc = ViewClient(device=device, serialno=serialno) showDialogButton = vc.findViewById('id/show_dialog_button') if showDialogButton: showDialogButton.touch() vc.dump() vc.findViewById('id/0x123456').type('Donald') ok = vc.findViewWithText('OK') if ok: # 09-08 20:17:47.860: D/MonkeyStub(2033): translateCommand: tap 265 518 ok.touch() vc.dump() hello = vc.findViewById('id/hello') if hello: if hello.getText() == "Hello Donald": print "OK" else: print "FAIL"
kwargs1 = {'verbose': False, 'ignoresecuredevice': False} device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) kwargs2 = {'startviewserver': True, 'forceviewserveruse': False, 'autodump': False, 'ignoreuiautomatorkilled': True, 'compresseddump': False} vc = ViewClient(device, serialno, **kwargs2) vc.dump('-1') btn_start = vc.findViewByIdOrRaise("com.wtsang02.sqliteutil.activities:id/btStart") btn_start.touch() finished = False btn_results = None while(not finished): try: time.sleep(5) vc.dump('-1') btn_results = vc.findViewById("com.wtsang02.sqliteutil.activities:id/btToResults") if btn_results: finished = True except RuntimeError: pass print "benchmark finished" btn_results.touch() time.sleep(1) vc.dump('-1') get_score_with_text(vc, "Insert 200 Statments ") get_score_with_text(vc, "Insert 15000 Statments in Transaction ") get_score_with_text(vc, "Update 500 Statments ") get_score_with_text(vc, "Update 15000 Statments in Transaction ") get_score_with_text(vc, "Select 15000 Statements ") get_score_with_text(vc, "Delete 200 Statments ")
import sys import os import time # this must be imported before MonkeyRunner and MonkeyDevice, # otherwise the import fails try: ANDROID_VIEW_CLIENT_HOME = os.environ['ANDROID_VIEW_CLIENT_HOME'] except KeyError: print >>sys.stderr, "%s: ERROR: ANDROID_VIEW_CLIENT_HOME not set in environment" % __file__ sys.exit(1) sys.path.append(ANDROID_VIEW_CLIENT_HOME + '/src') from com.dtmilano.android.viewclient import ViewClient from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice device = MonkeyRunner.waitForConnection(60, "emulator-5554") if not device: raise Exception('Cannot connect to device') MonkeyRunner.sleep(5) vc = ViewClient(device) vc.dump() for i in range(1, 9): view = vc.findViewById("id/no_id/%d" % i) print view #button2.touch(MonkeyDevice.DOWN_AND_UP) print >>sys.stderr, "bye"
vc = ViewClient(device=device, serialno=serialno) if DEBUG: vc.traverse(transform=ViewClient.TRAVERSE_CIT) sound = vc.findViewWithText('Sound') if sound: sound.touch() vc.dump() phoneRingtone = vc.findViewWithText('Phone ringtone') if phoneRingtone: phoneRingtone.touch() vc.dump() vespa = vc.findViewWithText('Vespa') if vespa: vespa.touch() MonkeyRunner.sleep(1) ok = vc.findViewById('id/button1') if ok: ok.touch() vc.dump() vespa = vc.findViewWithText('Vespa') # If for some reason the dialog is still there we will have Vespa and OK ok = vc.findViewById('id/button1') if vespa and not ok: print "OK" else: print "FAIL to set ringtone Vespa" sys.exit(1) else: print >> sys.stderr, "'OK' not found" else: print >> sys.stderr, "'Phone ringtone' not found"
'compresseddump': True } vc = ViewClient(device, serialno, **kwargs2) device.shell('input keyevent KEYCODE_HOME') device.startActivity(main_activity) vc.sleep(_s) ## STARTUP # pantalla principal vc.dump(window=-1) vc.findViewByIdOrRaise('com.olx.olx:id/fab_posting_masonry_home').touch() vc.sleep(_s) vc.dump(window=-1) if vc.findViewById('com.olx.olx:id/retry_catalog'): print "connection fail modal appears, fff" vc.findViewByIdOrRaise('com.olx.olx:id/retry_catalog').touch() ## pantalla de elegir foto vc.dump(window=-1) vc.findViewByIdOrRaise( 'com.olx.olx:id/gridTile').touch() #primer elemento de la grilla vc.dump(window=-1) vc.findViewByIdOrRaise('com.olx.olx:id/select_photos').touch() # vc.sleep(_s) vc.dump(window=-1) # pantalla de ingresar el titulo vc.findViewByIdOrRaise('com.olx.olx:id/posting_title').setText(title) vc.findViewByIdOrRaise('com.olx.olx:id/posting_title_button').touch()
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' device.startActivity(component=componentName, flags=FLAG_ACTIVITY_NEW_TASK) ViewClient.sleep(3) # Set it to True or False to decide if AndroidViewClient or plain monkeyrunner is used USE_AVC = True if USE_AVC: # AndroidViewClient vc = ViewClient(device=device, serialno=serialno) showDialogButton = vc.findViewById('id/show_dialog_button') if showDialogButton: showDialogButton.touch() vc.dump() vc.findViewById('id/0x123456').type('Donald') ok = vc.findViewWithText('OK') if ok: # 09-08 20:17:47.860: D/MonkeyStub(2033): translateCommand: tap 265 518 ok.touch() vc.dump() hello = vc.findViewById('id/hello') if hello: if hello.getText() == "Hello Donald": print "OK" else: print "FAIL"
def FailRegister(): try: from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) vc.findViewById("android:id/button1").touch() vc.dump() os.system("adb shell input keyevent KEYCODE_HOME") time.sleep(2) os.system("adb shell pm clear com.android.phone") time.sleep(1) print(sendCommand("AT+CFUN=0")) time.sleep(3) print(sendCommand("AT+CFUN=1")) time.sleep(3) print(sendCommand("AT+CFUN=1,1")) time.sleep(45) from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("MAI TEST"): vc.dump() if vc.findViewById("android:id/button1"): vc.dump() time.sleep(1) vc.findViewById("android:id/button1").touch() vc.dump() print("clicked") check() if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): os.system("adb shell cmd statusbar collapse") refresh() else: print("") else: for i in range(4): from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewWithText("Mobile network").touch() vc.dump() break else: os.system("adb shell input swipe 876 856 102 949 ") time.sleep(1) from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewWithText("Mobile network").touch() vc.dump() break from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) vc.findViewWithText("Carrier").touch() time.sleep(2) vc.dump() vc.findViewById("android:id/switch_widget").touch() vc.dump() vc.findViewById("android:id/button1").touch() time.sleep(50) vc.dump() check() if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): os.system("adb shell cmd statusbar collapse") refresh() else: os.system("adb shell cmd statusbar collapse") time.sleep(1) if vc.findViewWithText(u"中国联通 4G"): vc.dump() vc.findViewWithText(u"中国联通 4G").touch() time.sleep(2) vc.dump() if vc.findViewWithText("Network registration failed"): vc.dump() vc.findViewById("android:id/button1").touch() vc.dump() sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL") time.sleep(1) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"Registration.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"Registration.png "+fin+PLMN+"Registration.png" ) time.sleep(1) elif vc.findViewWithText("MAI TEST"): vc.dump() vc.findViewById("android:id/button1").touch() vc.dump() refresh() elif vc.findViewWithText(u"中国联通 LTE"): vc.dump() vc.findViewWithText(u"中国联通 LTE").touch() time.sleep(2) vc.dump() if vc.findViewWithText("Network registration failed"): vc.dump() vc.findViewById("android:id/button1").touch() vc.dump() sheet1.write(j,0,PLMN) sheet1.write(j,1,"FAIL") time.sleep(1) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"Registration.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"Registration.png "+fin+PLMN+"Registration.png" ) time.sleep(1) elif vc.findViewWithText("MAI TEST"): vc.dump() vc.findViewById("android:id/button1").touch() vc.dump() refresh() except: print("Found an exception......")
parent_dir = os.path.realpath(os.path.dirname(__file__)) f_output_result="%s/../common/output-test-result.sh" % parent_dir kwargs1 = {'verbose': False, 'ignoresecuredevice': False} device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) kwargs2 = {'startviewserver': True, 'forceviewserveruse': False, 'autodump': False, 'ignoreuiautomatorkilled': True, 'compresseddump': False} vc = ViewClient(device, serialno, **kwargs2) time.sleep(2) vc.dump(window='-1') start_single_button = vc.findViewByIdOrRaise("com.greenecomputing.linpack:id/btnsingle") start_single_button.touch() time.sleep(2) vc.dump(window='-1') start_single_button = vc.findViewById("com.greenecomputing.linpack:id/btnsingle") while not start_single_button: time.sleep(2) vc.dump(window='-1') start_single_button = vc.findViewById("com.greenecomputing.linpack:id/btnsingle") mflops_single_score = vc.findViewByIdOrRaise("com.greenecomputing.linpack:id/txtmflops_result") time_single_score = vc.findViewByIdOrRaise("com.greenecomputing.linpack:id/txttime_result") call([f_output_result, 'Linpack_MFLOPSSingleScore', 'pass', mflops_single_score.getText(), 'MFLOPS']) call([f_output_result, 'Linpack_TimeSingleScore', 'pass', time_single_score.getText(), 'seconds']) start_multi_button = vc.findViewByIdOrRaise("com.greenecomputing.linpack:id/btncalculate") start_multi_button.touch() time.sleep(2) vc.dump(window='-1')
def SMS(): try: cdir=os.getcwd() adir=str(glob.glob(cdir + "/" + "logcat.txt")) cut=adir.split("/") before=cut[-1] global final final=before.replace("']", "") os.system("adb shell pm clear com.android.phone") time.sleep(10) check() os.system("adb shell cmd statusbar collapse") time.sleep(1) if gets==str("4G Signal") or String==str("LTE Signal") or String==str("4G"): if final=="logcat.txt": print("Log file found Removing now.....") os.remove(final) else: print("No log file found..........") try: time.sleep(1) os.system("adb shell pm clear com.google.android.apps.messaging") from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithContentDescription("Messages"): vc.findViewWithContentDescription("Messages").touch() time.sleep(1) vc.dump() else: device.startActivity("com.huawei.android.launcher/com.huawei.android.launcher.unihome.UniHomeLauncher") time.sleep(1) vc.dump() vc.findViewWithContentDescription("Start chat").touch() time.sleep(1) vc.dump() vc.findViewById("com.google.android.apps.messaging:id/recipient_text_view").touch() time.sleep(2) vc.dump() device.shell("input text " + str(ISDN)) vc.dump() time.sleep(3) vc.findViewById("com.google.android.apps.messaging:id/contact_picker_create_group").touch() time.sleep(1) vc.dump() vc.findViewById("com.google.android.apps.messaging:id/compose_message_text").setText("Hi") time.sleep(1) vc.dump() vc.findViewById("com.google.android.apps.messaging:id/send_message_button_container").touch() time.sleep(4) vc.dump() os.system("adb logcat -d time >> logcat.txt") time.sleep(6) file=open("logcat.txt", "r") lines= file.read() if "BugleDataMode: Processing changed messages for 357" in lines or "Done sending SMS message{id:357} conversation{id:50}, status: MANUAL_RETRY" in lines or "process from ProcessSentMessageAction due to sms_send failure with queues:" in lines: sheet1.write(j,3,"FAIL") time.sleep(1) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"sms.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"sms.png "+fin+PLMN+"sms.png" ) time.sleep(1) file.close() elif "status: SUCCEEDED" in lines: sheet1.write(j,3,"PASS") time.sleep(1) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"sms.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"sms.png "+fin+PLMN+"sms.png" ) time.sleep(1) file.close() #Take screenshot except: print("Exception while sending SMS..............") time.sleep(1) os.system("adb shell pm clear com.google.android.apps.messaging") time.sleep(1) else: sheet1.write(j,3,"FAIL") os.system("adb shell input keyevent KEYCODE_HOME") time.sleep(2) for i in range(4): from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewWithText("Mobile network").touch() vc.dump() break else: os.system("adb shell input swipe 876 856 102 949 ") time.sleep(1) from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) if vc.findViewWithText("Settings"): vc.dump() vc.findViewWithText("Settings").touch() vc.dump() vc.findViewWithText("Wireless & networks").touch() vc.dump() vc.findViewWithText("Mobile network").touch() vc.dump() break from com.dtmilano.android.viewclient import ViewClient device, serialno=ViewClient.connectToDeviceOrExit() vc=ViewClient(device=device, serialno=serialno) os.system("adb shell screencap -p /sdcard/Automation/"+PLMN+"Settings.png") time.sleep(1) os .system("adb pull /sdcard/Automation/"+PLMN+"Settings.png "+fin+PLMN+"Settings.png" ) time.sleep(1) except: print("An Exception occured......")
try: ANDROID_VIEW_CLIENT_HOME = os.environ['ANDROID_VIEW_CLIENT_HOME'] except KeyError: print >>sys.stderr, "%s: ERROR: ANDROID_VIEW_CLIENT_HOME not set in environment" % __file__ sys.exit(1) sys.path.append(ANDROID_VIEW_CLIENT_HOME + '/src') from com.dtmilano.android.viewclient import ViewClient from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # Starting: Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.android.browser/.BrowserActivity } package = 'com.android.browser' activity = '.BrowserActivity' component = package + "/" + activity uri = 'http://dtmilano.blogspot.com' device = MonkeyRunner.waitForConnection(60) if not device: raise Exception('Cannot connect to device') device.startActivity(component=component, uri=uri) MonkeyRunner.sleep(3) vc = ViewClient(device) vc.dump() title = vc.findViewById("id/title")['mText'] if string.find(title, uri) != -1: print "%s successfully loaded" % uri else: print "%s was not loaded, title=%s" % (uri, title)
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554', sample=False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device = device self.sample = sample self.startStatus = False '''the status which indicate whether the contacts activity is started''' self.vc = ViewClient(device, devID) #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' self.device.startActivity(component=componentName) sleep(3) self.startStatus = self.isReady() def back(self): ''' press back ''' self.device.press('KEYCODE_BACK', 'DOWN_AND_UP') def getView(self, str, cD=False, iD=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @return: the view found ''' self.vc.dump() sleep(3) if not cD: if not iD: return self.vc.findViewWithText(str) else: return self.vc.findViewById(str) else: return self.vc.findViewWithContentDescription(str) def isReady(self): ''' check whether the contacts is ready. ''' while True: view = self.getView( 'Contact list is being updated to reflect the change of language.' ) if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def goEdit(self): ''' check whether the contact is empty, then select adding and go to edit view. @return: True ''' self.check() view = self.getView('Create a new contact') if view: view.touch() trace('Click "Create a new contact"') view = self.getView('Keep local') if view: view.touch() trace('Select "Keep local"') else: view = self.getView('Add Contact', True) view.touch() trace('Click "Add Contact"') return True def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.status: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self, title): ''' take snapshot @type title: str @param title: specify the title of snapshot ''' snapName = title + '.png' snapFile = logPath + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) result.writeToFile(snapFile, 'png') def addContact(self, name='', phone='', email=''): #notice firstly call self.goEdit() pass def editDetails(self, phone=''): pass def search(self, str): ''' @type str: str @param str: specify the search keyword ##@return: the view of search result if search result is not null, else return None ''' trace("start searching...") trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search", True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() searchView = self.getView("Search", True) searchView.touch() self.device.type(str) trace("search keyword is: " + str) self.snapshot("search_result") ''' tmp=[] self.vc.dump() trace("dump, please wait...") #the id of 1st search result is always 28 for i in self.vc.findViewsContainingPoint((100,200)): tmp.append(i.getId()) result=int(tmp[len(tmp)-1][-2:]) if(result<28): trace("search result: nothing") return None else: self.snapshot("search_result") return self.vc.findViewById(tmp[len(tmp)-1]) ''' def sortAs(self, sortByFirstName=True): ''' sort contact name @type sortByFirstName: boolean @param sortByFirstName: whether sort contact name by first name ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search", True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start sorting...") self.device.press("KEYCODE_MENU", "DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView = self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("Sort list by").touch() trace("click Sort list by, dump, please wait...") self.vc.dump() if sortByFirstName: self.vc.findViewWithTextOrRaise("First name").touch() else: self.vc.findViewWithTextOrRaise("Last name").touch() sleep(2) #conflict with check at the begining #self.device.press("KEYCODE_BACK","DOWN_AND_UP") #sleep(2) def viewAs(self, viewAsFirstNameFirst=True): ''' view contact name @type viewAsFirstNameFirst: boolean @param viewAsFirstNameFirst: whether view contact by first name first ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search", True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start viewing...") self.device.press("KEYCODE_MENU", "DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView = self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("View contact names as").touch() trace("click View contact names as, dump, please wait...") self.vc.dump() if viewAsFirstNameFirst: self.vc.findViewWithTextOrRaise("First name first").touch() else: self.vc.findViewWithTextOrRaise("Last name first").touch() sleep(2) #conflict with check at the begining #self.device.press("KEYCODE_BACK","DOWN_AND_UP") #sleep(2) def favorite(self, name=''): pass
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554', sample=False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device = device self.sample = sample self.startStatus = False '''the status which indicate whether the contacts activity is started''' self.vc = ViewClient(device, devID) #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' self.device.startActivity(component=componentName) sleep(3) self.startStatus = self.isReady() def back(self): ''' press back ''' self.device.press('KEYCODE_BACK', 'DOWN_AND_UP') def getView(self, str, cD=False, iD=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @return: the view found ''' self.vc.dump() sleep(3) if not cD: if not iD: return self.vc.findViewWithText(str) else: return self.vc.findViewById(str) else: return self.vc.findViewWithContentDescription(str) def isReady(self): ''' check whether the contacts is ready. ''' while True: view = self.getView( 'Contact list is being updated to reflect the change of language.' ) if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def goEdit(self): ''' check whether the contact is empty, then select adding and go to edit view. @return: True ''' self.check() view = self.getView('Create a new contact') if view: view.touch() trace('Click "Create a new contact"') view = self.getView('Keep local') if view: view.touch() trace('Select "Keep local"') else: view = self.getView('Add Contact', True) view.touch() trace('Click "Add Contact"') return True def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.startStatus: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self, title): ''' take snapshot @type title: str @param title: specify the title of snapshot ''' snapName = title + '.png' snapFile = logPath + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) result.writeToFile(snapFile, 'png') def addContact(self, name='', phone='', email=''): #notice firstly call self.goEdit() pass def editDetails(self, name='', phone='', email='', notes='', address='', nickname=''): ''' edit contact details ''' self.check() view = self.getView('id/no_id/27', iD=True) view.touch() sleep(4) trace('enter contact OK') self.device.press('KEYCODE_MENU', 'DOWN_AND_UP') view = self.getView('Edit') view.touch() sleep(3) trace('enter contact edit view OK') if not name == '': self.editName(name) if not phone == '': if self.getDetails('Phone'): self.editPhone(phone) else: self.editPhone(phone, add=True) self.back() sleep(3) self.back() def getDetails(self, getItem): if self.getView(getItem): return True else: self.device.drag((240, 750), (240, 50), 5.0) sleep(1) if self.getView(getItem): return True else: return False def editName(self, name): trace("edit contact's name") self.check() #find EditText of Name view = self.getView('id/no_id/27', iD=True) #edit name self.device.drag(view.getXY(), view.getXY(), 3.0) self.device.press('KEYCODE_DEL', 'DOWN_AND_UP') view.type(name) sleep(1) trace("edit contact's name OK") def editPhone(self, phone, add=False): trace("edit contact's phone") self.check() if not add: trace('edit phone with no add') #find EditText of Phone view = self.getView('Phone') editId = 'id/no_id/' + str(int((view.getId())[-2:]) + 6) view = self.getView(editId, iD=True) #edit phone number self.device.drag(view.getXY(), view.getXY(), 3.0) self.device.press('KEYCODE_DEL', 'DOWN_AND_UP') view.type(phone) sleep(1) trace('edit phone with no add OK') else: trace('edit phone with add') #touch 'Add another field' view = self.getView('Add another field') view.touch() sleep(3) #touch 'Phone' and edit view = self.getView('Phone') view.touch() sleep(2) self.device.type(phone) sleep(1) trace('edit phone with add OK') def editEmail(self, email): pass def search(self, str): pass def sort(self): pass def favorite(self, name=''): pass
while not found_test_btn: try: dump_always() button_test = vc.findViewByIdOrRaise( "com.antutu.ABenchMark:id/btn_test_now") button_test.touch() found_test_btn = True except ViewNotFoundException: print("Not find com.antutu.ABenchMark:id/btn_test_now yet, continue") finished = False while (not finished): time.sleep(1) try: vc.dump(window='-1') if vc.findViewById("com.antutu.ABenchMark:id/layoutScoresHeader"): finished = True except RuntimeError: pass except ValueError: pass print "benchmark finished" # close unnecessary windows if they appear for index in range(0, 3): time.sleep(1) vc.dump(window='-1') if vc.findViewById("com.antutu.ABenchMark:id/num_1"): break else:
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554',sample = False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device=device self.sample=sample self.startStatus=False '''the status which indicate whether the contacts activity is started''' self.vc=ViewClient(device, devID) #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' self.device.startActivity(component=componentName) sleep(3) self.startStatus = self.isReady() def back(self): ''' press back ''' self.device.press('KEYCODE_BACK','DOWN_AND_UP') def getView(self,str,cD=False,iD=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @return: the view found ''' self.vc.dump() sleep(3) if not cD: if not iD: return self.vc.findViewWithText(str) else: return self.vc.findViewById(str) else: return self.vc.findViewWithContentDescription(str) def isReady(self): ''' check whether the contacts is ready. ''' while True: view=self.getView('Contact list is being updated to reflect the change of language.') if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def goEdit(self): ''' check whether the contact is empty, then select adding and go to edit view. @return: True ''' self.check() view=self.getView('Create a new contact') if view: view.touch() trace('Click "Create a new contact"') view=self.getView('Keep local') if view: view.touch() trace('Select "Keep local"') else: view=self.getView('Add Contact',True) view.touch() trace('Click "Add Contact"') return True def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.startStatus: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self,title): ''' take snapshot @type title: str @param title: specify the title of snapshot ''' snapName = title + '.png' snapFile = logPath + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) result.writeToFile(snapFile,'png') def addContact(self,name='',phone='',email=''): #notice firstly call self.goEdit() pass def editDetails(self,name='',phone='',email='',notes='',address='',nickname=''): ''' edit contact details ''' self.check() view = self.getView('id/no_id/27',iD=True) view.touch() sleep(4) trace('enter contact OK') self.device.press('KEYCODE_MENU','DOWN_AND_UP') view = self.getView('Edit') view.touch() sleep(3) trace('enter contact edit view OK') if not name=='': self.editName(name) if not phone=='': if self.getDetails('Phone'): self.editPhone(phone) else: self.editPhone(phone,add=True) self.back() sleep(3) self.back() def getDetails(self,getItem): if self.getView(getItem): return True else: self.device.drag((240,750),(240,50),5.0) sleep(1) if self.getView(getItem): return True else: return False def editName(self,name): trace("edit contact's name") self.check() #find EditText of Name view = self.getView('id/no_id/27',iD=True) #edit name self.device.drag(view.getXY(),view.getXY(),3.0) self.device.press('KEYCODE_DEL','DOWN_AND_UP') view.type(name) sleep(1) trace("edit contact's name OK") def editPhone(self,phone,add=False): trace("edit contact's phone") self.check() if not add: trace('edit phone with no add') #find EditText of Phone view = self.getView('Phone') editId = 'id/no_id/'+str(int((view.getId())[-2:])+6) view = self.getView(editId,iD=True) #edit phone number self.device.drag(view.getXY(),view.getXY(),3.0) self.device.press('KEYCODE_DEL','DOWN_AND_UP') view.type(phone) sleep(1) trace('edit phone with no add OK') else: trace('edit phone with add') #touch 'Add another field' view = self.getView('Add another field') view.touch() sleep(3) #touch 'Phone' and edit view = self.getView('Phone') view.touch() sleep(2) self.device.type(phone) sleep(1) trace('edit phone with add OK') def editEmail(self,email): pass def search(self,str): pass def sort(self): pass def favorite(self,name=''): pass
if True: device.startActivity(component=component) MonkeyRunner.sleep(3) device.press('KEYCODE_DPAD_DOWN') # extra VMT setting WARNING! MonkeyRunner.sleep(1) device.press('KEYCODE_DPAD_CENTER', MonkeyDevice.DOWN_AND_UP) device.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #device.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #device.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP) #device.press('KEYCODE_DPAD_CENTER', "DOWN_AND_UP") #device.press('KEYCODE_DPAD_CENTER', "DOWN_AND_UP") vc = ViewClient(device, serialno) regex = "id/checkbox.*" p = re.compile(regex) found = False for id in vc.getViewIds(): #print id m = p.match(id) if m: found = True attrs = vc.findViewById(id) if attrs['isSelected()'] == 'true': print "Wi-Fi is", if attrs['isChecked()'] != 'true': print "not", print "set" if not found: print "No Views found that match " + regex
viewclient_home = os.environ['ANDROID_VIEW_CLIENT_DIR'] sys.path.append(os.path.join(viewclient_home, 'src')) except: raise from com.dtmilano.android.viewclient import ViewClient, View package = 'com.hecorat.screenrecorder.free' activity = '.activities.MainActivity' component = package + '/' + activity device, serialno = ViewClient.connectToDeviceOrExit( serialno='0094d3075388ceb1') FLAG_ACTIVITY_NEW_TASK = 0x10000000 device.startActivity(component=component, flags=FLAG_ACTIVITY_NEW_TASK) vc = ViewClient(device=device, serialno=serialno, startviewserver=True) device.drag((100, 0), (100, 1500), 1000) vc.dump() view = vc.findViewById('com.hecorat.screenrecorder.free:id/btn_record') view.touch() ViewClient.sleep(2) os.system( 'adb shell am start -a android.intent.action.VIEW \"http://www.youtube.com/watch?v=YRhFSWz_J3I\"' ) sleep(2) subprocess.call('adb shell am force-stop com.hecorat.screenrecorder.free', shell=True) os.system( 'adb shell am force-stop android.intent.action.VIEW \"http://www.youtube.com/watch?v=YRhFSWz_J3I\"' )
device.takeSnapshot(reconnect=True).save('./screenshots/register/login-to-register.png','png') vc = ViewClient(*ViewClient.connectToDeviceOrExit()) vc.dump() button = vc.findViewByIdOrRaise('com.hoard.hoard:id/login_register_button') button.touch() vc.dump() ViewClient.sleep(3) device.takeSnapshot(reconnect=True).save('./screenshots/register/register-pre.png','png') email = vc.findViewById('com.hoard.hoard:id/register_email') email.type('*****@*****.**') vc.dump() password = vc.findViewById('com.hoard.hoard:id/register_password') password.type('u1') vc.dump() password = vc.findViewById('com.hoard.hoard:id/register_password_confirmation') password.type('u1') device.takeSnapshot(reconnect=True).save('./screenshots/register/register-pos.png','png') button = vc.findViewByIdOrRaise('com.hoard.hoard:id/register_button')
class WhatsApp: def __init__(self, adb_client): self.adb_client = adb_client self.device = None self.vc = None self.logger = logging.getLogger("{} - WhatsApp".format(self.adb_client.serial)) def extract_msgstore(self, dst_path): storage_paths = [self.adb_client.shell("echo $EXTERNAL_STORAGE"), "/storage/emulated/0"] # get most recent msgstore db path for spath in storage_paths: db_path = self.adb_client.shell("ls -t %s/Whatsapp/Databases/msgstore* | head -1" % spath.rstrip()).rstrip() if not db_path: continue dst_full_path = os.path.join(dst_path, os.path.basename(db_path)) self.logger.info("Extracting msgstore database from path: %s", db_path) # Returns None on success if self.adb_client.pull(db_path, dst_full_path) is None: return dst_full_path return None def extract_priv_key(self, dst_path): dst_full_path = os.path.join(dst_path, "key") return self.adb_client.pull("/data/data/com.whatsapp/files/key", dst_full_path) is None def register_phone(self, msgstore_path, country_code, phone_no): time.sleep(2.5) # Step 1: cleanup if not self._uninstall(): raise WaException("Can not cleanup device") # Step 2: install self.logger.info("Installing WhatsApp...") try: if not self._install(): raise WaException("Can not install WhatsApp APK") except InstallError as e: raise WaException(e.message) # Step 3a: create / clean /WhatsApp/ data directory self.logger.info("Cleaning WhatsApp...") self.adb_client.shell("rm -rf /sdcard/WhatsApp/Databases/*") # Step 3b: move msgstore.db to correct location self.logger.info("Moving extracted database into emulator...") self.adb_client.push(msgstore_path, "/sdcard/WhatsApp/Databases/msgstore.db.crypt12") self.connect_device() self.logger.info("Grant permission to android WRITE/READ_CONTACTS, WRITE/READ_EXTERNAL_STORAGE") for permission in [ "android.permission.WRITE_CONTACTS", "android.permission.READ_CONTACTS", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE", ]: self.adb_client.shell("pm grant com.whatsapp {}".format(permission)) time.sleep(0.05) if not self._open_app(): raise WaException("Can not open WhatsApp application") time.sleep(15) if not self._automate_accept_eula(): raise WaException("Can not accept EULA") if not self._do_verify(country_code, phone_no): raise WaException("Can not verify phone number") def _do_verify(self, cc, phone): # Set country code cc_view = self._wait_views("com.whatsapp:id/registration_cc") self.logger.info("Touching and changing country code TextEdit...") if not cc_view: return False cc_view.touch() cc_view.setText(str(cc)) # Set phone number number_view = self._wait_views("com.whatsapp:id/registration_phone") self.logger.info("Touching and changing phone number TextEdit...") if not number_view: return False number_view.touch() number_view.setText(str(phone)) # Click "Next" next_view = self._wait_views("com.whatsapp:id/registration_submit") self.logger.info("Touching registration submit button...") if not next_view: return False next_view.touch() # Confirm Dialog clicking "OK" # Extend timeout to be 6*5 seconds (5 minutes) because WhatsApp could take time to send code confirm_view = self._wait_views("android:id/button1", max_tries=60, frequency=5) self.logger.info("Touching OK confirmation button...") if not confirm_view: return False confirm_view.touch() return True def connect_device(self, back_home=False): if self.device is None: # We have founded a strange issue, when the screen appear on wait security code the countdown for another code refresh too frequently # Go back to home please ... if back_home is True: self.adb_client.shell("input keyevent KEYCODE_HOME") time.sleep(2) kwargs1 = {'serialno': self.adb_client.serial, 'verbose': False, 'ignoresecuredevice': False, 'ignoreversioncheck': False} self.device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) kwargs2 = {'forceviewserveruse': False, 'startviewserver': True, 'autodump': False, 'ignoreuiautomatorkilled': True, 'compresseddump': True, 'useuiautomatorhelper': False, 'debug': {}} self.vc = ViewClient(self.device, serialno, **kwargs2) def _verify_by_sms(self, code_callback): self.connect_device() while True: code = code_callback if type(code_callback) in [str, int] else code_callback() if code is not None: if self._try_code(code): return True self.logger.error("Verification code NOT valid!") else: # Attempt to re-send SMS self.logger.info("Attempting to re-send verification code...") try: seconds_to_wait = self._get_countdown_sms() # Got countdown seconds, wait and request new code self.logger.info("Waiting %d seconds to request new SMS", seconds_to_wait) time.sleep(seconds_to_wait) except WaException: pass # Resend SMS resend_view = self._wait_views("com.whatsapp:id/resend_sms_btn") if not resend_view: raise WaException("Cannot find resend sms button view") # Resend SMS button might be disabled for few hours if resend_view.getText().find(" in ") != -1: raise WaException("Cannot request new code, try again later: %s" % resend_view.getText()) # Touch resend_view = self._wait_views("com.whatsapp:id/resend_sms_btn") resend_view.touch() def _verify_by_call(self, code_callback): self.connect_device() request_call = True time.sleep(1) while True: call_btn_view = self._wait_views("com.whatsapp:id/call_btn") countdown_view = self._wait_views("com.whatsapp:id/countdown_time_voice", max_tries=1) if not call_btn_view: raise WaException("Could not find call button view") if request_call and call_btn_view.getText().find(" in ") != -1: raise WaException("Cannot request new code, try again later: %s" % call_btn_view.getText()) if request_call and countdown_view: try: seconds_to_wait = self._get_countdown_call() # Got countdown seconds, wait and request new code self.logger.info("Waiting %d seconds to request a call", seconds_to_wait) time.sleep(seconds_to_wait) except WaException: pass if request_call: # Update & Touch resend_view = self._wait_views("com.whatsapp:id/call_btn") resend_view.touch() call_btn_view = self._wait_views("com.whatsapp:id/call_btn") call_btn_view.touch() # Ask code code = code_callback if type(code_callback) in [str, int] else code_callback() if code is not None: if self._try_code(code): return True self.logger.error("Verification code NOT valid!") request_call = False else: # Request call again self.logger.info("Attempting to request a new Call...") request_call = True def _try_code_adb(self, code): self.logger.info("am start -a android.intent.action.VIEW -d https://v.whatsapp.com/{} com.whatsapp".format(code)) return self.adb_client.shell("am start -a android.intent.action.VIEW -d https://v.whatsapp.com/{} com.whatsapp".format(code)).find("Error") == -1 def _try_code(self, code, use_adb=True): if use_adb is True and self._try_code_adb(code) is True: return True # If failed, continue with ui interaction # Input text code_input_view = self._wait_views("com.whatsapp:id/verify_sms_code_input") if not code_input_view: self.logger.error("Could not find SMS code input TextEdit") raise WaException("Could not find SMS code input TextEdit") code_input_view.setText(code) # Check if valid msg_view = self._wait_views("android:id/message") if msg_view: self.logger.info("Dialog message: %s", msg_view.getText()) # Click OK button to close dialog ok_btn = self._wait_views("android:id/button1") if ok_btn: ok_btn.touch() # If input is blocked, wait while True: input_blocked_view = self._wait_views("com.whatsapp:id/description_2_bottom", max_tries=3) if not input_blocked_view: return True if input_blocked_view.getText().find("Wait") == -1: break self.logger.info("Waiting for input to unblock...") time.sleep(10) return False return True def _get_countdown_sms(self): return self._get_countdown("com.whatsapp:id/countdown_time_sms") def _get_countdown_call(self): return self._get_countdown("com.whatsapp:id/countdown_time_voice") def _get_countdown(self, id): sms_count_view = self._wait_views(id) if sms_count_view: sms_text = sms_count_view.getText() sms_text_parts = sms_text.split(":") if len(sms_text_parts) != 2: raise WaException("Malformed sms countdown text! (%s)" % sms_text) return int(sms_text_parts[0]) * 60 + int(sms_text_parts[1]) raise WaException("Cannot find countdown seconds") def _allow_access(self): continue_view = self._wait_views("com.whatsapp:id/submit", frequency=3, max_tries=5) if not continue_view: return False self.logger.info('Touching "Continue" on permissions box...') continue_view.touch() # Allow for both photos/media/files and contacts (asked twice) for i in range(2): allow_view = self._wait_views("com.android.packageinstaller:id/permission_allow_button", frequency=3, max_tries=5) if not allow_view: return False self.logger.info('Touch "Allow" (step %d)...', i + 1) allow_view.touch() return True def _automate_accept_eula(self): msg_view = self._wait_views("android:id/message", frequency=6, max_tries=5) # Accept custom ROM alert if msg_view and msg_view.getText().find("ROM") != -1: ok_btn = self._wait_views("android:id/button2") if not ok_btn: return False self.logger.info('Touching "OK" at custom ROM alert...') ok_btn.touch() # Agree to EULA msg_view = self._wait_views("com.whatsapp:id/eula_accept") if not msg_view: return False self.logger.info("Agreeing to EULA...") msg_view.touch() return True def _install(self): apk_path = os.path.abspath(os.path.join("apks", "WhatsApp.apk")) if self._is_app_installed(): return True return self.adb_client.install(apk_path) def _uninstall(self): if not self._is_app_installed(): return True return self.adb_client.uninstall("com.whatsapp") def _open_app(self): return self.adb_client.shell("am start -n com.whatsapp/com.whatsapp.registration.EULA").find("Error") == -1 def _is_app_installed(self): return self.adb_client.is_installed("com.whatsapp") def _wait_views(self, ids, frequency=3, max_tries=15): ids = ids if isinstance(ids, list) else [ids] for attempt in range(max_tries): try: # Update view with suppress_stderr(): self.vc.dump(window='-1') except RuntimeError as e: self.logger.error("{} - Exception while trying to dump views: {}".format(attempt, e)) # Check if it can find any of the IDs for _id in ids: view = self.vc.findViewById(_id) if view: # if self.logger.level == logging.DEBUG: # self.vc.traverse() return view time.sleep(frequency) # Check every X seconds return None def complete_registration(self, cc, phone): time.sleep(2.5) gdrive_msg_view = self._wait_views("com.whatsapp:id/permission_message", max_tries=7) skip_btn_view = self._wait_views("com.whatsapp:id/submit", max_tries=7) if not gdrive_msg_view and not skip_btn_view: self.logger.info("1. Expected Google Drive permission dialog, ignoring..") else: skip_btn_view.touch() # Restore messages gdrive_msg_view = self._wait_views("android:id/message", max_tries=3) skip_btn_view = self._wait_views("android:id/button2", max_tries=3) if not gdrive_msg_view and not skip_btn_view: self.logger.info("2. Expected Google Drive permission dialog, ignoring..") else: skip_btn_view.touch() # Restore messages Activity restore_btn_view = self._wait_views("com.whatsapp:id/perform_restore", max_tries=30, frequency=5) if not restore_btn_view: raise WaException("Cannot find restore button, is msgcrypt associated with +%d %s?" % (cc, phone)) self.logger.info("Restoring messages... (might take a while)") restore_btn_view.touch() # Wait for result (max 15 minutes) result_msg_view = self._wait_views("com.whatsapp:id/msgrestore_result_box", frequency=10, max_tries=90) if not result_msg_view: raise WaException("Could not restore messages") self.logger.info("%s", result_msg_view.getText()) return True
found_test_btn = False while not found_test_btn: try: dump_always() button_test = vc.findViewByIdOrRaise("com.antutu.ABenchMark:id/btn_test_now") button_test.touch() found_test_btn = True except ViewNotFoundException: print("Not find com.antutu.ABenchMark:id/btn_test_now yet, continue") finished = False while(not finished): time.sleep(1) try: vc.dump(window='-1') if vc.findViewById("com.antutu.ABenchMark:id/layoutScoresHeader"): finished = True except RuntimeError: pass except ValueError: pass print "benchmark finished" # close unnecessary windows if they appear for index in range(0, 3): time.sleep(1) vc.dump(window='-1') if vc.findViewById("com.antutu.ABenchMark:id/num_1"): break else:
vc.dump(window='-1') vc.sleep(_s) vc.dump(window='-1') #Theme 1 = STACK STACK if vc.findViewWithContentDescription(u'''stack_stack'''): id_scroll_view = vc.findViewByIdOrRaise("com.restwla.z"+appid+":id/scroll_view") #screenshot of information page vc.findViewByIdOrRaise('com.restwla.z'+appid+':id/home_option_information').touch() vc.sleep(_s) device.takeSnapshot().save(path+'/whitelabel/WLA_database/'+appid+'/screenshots/6.png','PNG') device.press('KEYCODE_BACK') #screenshot of photos page if vc.findViewById('com.restwla.z'+appid+':id/home_option_photos'): vc.findViewByIdOrRaise('com.restwla.z'+appid+':id/home_option_photos').touch() vc.sleep(_s) device.takeSnapshot().save(path+'/whitelabel/WLA_database/'+appid+'/screenshots/4.png','PNG') device.press('KEYCODE_BACK') #screenshot of Table Reservation if vc.findViewById('com.restwla.z'+appid+':id/home_option_table_reservation'): vc.findViewById('com.restwla.z'+appid+':id/home_option_table_reservation').touch() vc.sleep(_s) vc.dump(window='-1') if vc.findViewById('com.restwla.z'+appid+':id/sign_in_email'): vc.findViewByIdOrRaise('com.restwla.z'+appid+':id/sign_in_email').touch() vc.sleep(_s) vc.dump(window='-1') vc.findViewById('com.restwla.z'+appid+':id/name').touch()
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554', sample=False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device = device self.sample = sample self.contactCounter = 0 self.startStatus = False '''the status which indicate whether the contacts activity is started''' #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight #define the point coordinate used to slide screen self.left = (width / 4, height / 2) self.right = (width / 4 * 3, height / 2) self.up = (width / 2, height / 4) self.down = (width / 2, height / 4 * 3) self.center = (width / 2, height / 2) trace('before instance') self.vc = ViewClient(device, devID) trace('after instance') def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' trace('Starting activity ...') self.device.startActivity(component=componentName) sleep(2) self.startStatus = self.goList() trace('Contacts is started, checking the contacts status...') self.isReady() sleep(2) def stop(self): ''' stop the contacts activity and set the startStatus False ''' self.device.shell('am force-stop %s' % package) trace('force stop contacts package %s' % package) self.startStatus = False def menu(self): ''' press menu ''' self.device.press('KEYCODE_MENU', 'DOWN_AND_UP') trace('press menu') def scroll(self, down=True, times=1): ''' scoll up or down for some times @type down: boolead @param down: scroll down if True or scroll up @type times: int @param times: how many times to scroll ''' keycode = 'KEYCODE_DPAD_DOWN' if down else 'KEYCODE_DPAD_UP' for i in range(times): self.device.press(keycode, 'DOWN_AND_UP') trace('scroll %s' % str) def back(self): ''' press back ''' self.device.press('KEYCODE_BACK', 'DOWN_AND_UP') trace('press back') def slide(self, str, view=None): ''' slide the screen @type: str @param: 'left','right','up','down' @type view: @param view: specify the view, default to None ''' if str not in ['left', 'right', 'up', 'down']: raise SyntaxError( "wrong parameter: choose from 'left','right','up' or 'down'") try: cX, cY = view.getCenter() width = view.getWidth() height = view.getHeight() cL = cX - width / 4, cY cR = cX + width / 4, cY cU = cX, cY - height / 4 cD = cX, cY + height / 4 except AttributeError: pass (left, right, up, down) = (cL, cR, cU, cD) if view else (self.left, self.right, self.up, self.down) nav = { 'left': { 'start': right, 'end': left }, 'right': { 'start': left, 'end': right }, 'up': { 'start': down, 'end': up }, 'down': { 'start': up, 'end': down } } self.device.drag(nav[str]['start'], nav[str]['end'], 0.1, 1) trace('slide the screen from %s to %s ' % (nav[str]['start'], nav[str]['end'])) sleep(2) def getView(self, str, cD=False, iD=False, dump=True, regex=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @type dump: boolean @param dump: whether execute dump before findView, depending on whether the screen is changed @return: the view found ''' if dump: trace('before dump') self.vc.dump() trace('after dump') if cD: view = self.vc.findViewWithContentDescription(str) trace('Query view with content description: %s, return is %s' % (str, view is not None)) return view elif iD: view = self.vc.findViewById(str) trace('Query view by id: %s, return is %s' % (str, view is not None)) return view elif regex: view = self.vc.findViewWithAttributeThatMatches( 'text', re.compile(str)) trace('Query view that match attribute: %s, return is %s' % (str, view is not None)) return view else: view = self.vc.findViewWithText(str) trace('Query view with text: %s, return is %s ' % (str, view is not None)) return view def isReady(self): ''' check whether the contacts is ready. @return: True ''' while True: view = self.getView( 'Contacts list is being updated to reflect the change of language.' ) if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def isEmpty(self): ''' check whether the contacts is empty @return: True or False ''' self.check() view = self.getView('No contacts.') if view: trace('Contacts list is empty') return True else: trace('Contacts list is not empty') return False def getCounter(self): ''' get the contacts counter @return: the current contacts counter ''' self.goList() if self.isEmpty(): self.contactCounter = 0 else: while not self.getView('\d+ contacts?', regex=True): self.slide('down') sleep(3) self.contactCounter = int( self.getView('\d+ contacts?', regex=True, dump=False).getText().split()[0]) trace('current contacts counter is %d' % self.contactCounter) return self.contactCounter def goList(self): ''' check whether the screen is in contacts list view, if not, go list view via pressing back key @return: True ''' while True: view = self.getView("All contacts", cD=True) if not view: self.back() sleep(3) else: if not view.isSelected(): trace('Touch "All contacts"') view.touch() break trace('Goto contacts list view') return True def goEdit(self): ''' check whether the contacts is empty, then select adding and go to edit view. @return: True ''' self.check() try: self.getView('Add Contact', cD=True, dump=False).touch() trace('Touch "Add Contact"') sleep(5) return True except AttributeError: pass try: self.getView('Create a new contact', dump=False).touch() trace('Touch "Create a new contact"') sleep(5) self.getView('Keep local').touch() trace('Select "Keep local"') sleep(5) return True except AttributeError: pass def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.startStatus: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self, title): ''' take snapshot @type title: str @param title: specify the title of snapshot @return: snapshot object ''' snapName = title + '.png' snapFolder = 'snapshot' os.system('if not exist %s\\%s mkdir %s\\%s' % (logPath, snapFolder, logPath, snapFolder)) snapFile = logPath + '\\' + snapFolder + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) trace('take snapshot without the statusbar') result.writeToFile(snapFile, 'png') trace('save the snapshot to file: %s ' % snapFile) return result def wipe(self, view): ''' wipe the text in specified view ''' try: self.device.drag(view.getXY(), view.getXY(), 1, 1) trace('wipe text: %s' % str(view.getText())) self.device.press('KEYCODE_DEL', 'DOWN_AND_UP') except: Exception('wipe failed') def addContact(self, name='', phone='', email='', address=''): self.goEdit() try: offset = 0 if name: view = self.getView('id/no_id/27', iD=True) trace('type %s' % name) view.type(name) view.touch() if phone: view = self.getView('id/no_id/46', iD=True, dump=False) trace('type %s' % phone) view.type(phone) offset += 4 sleep(2) if email: view = self.getView('id/no_id/' + str(57 + offset), iD=True) trace('type %s' % email) view.type(email) offset += 4 sleep(2) if address: view = self.getView('id/no_id/' + str(68 + offset), iD=True) trace('type %s' % address) view.type(address) sleep(2) view = self.getView('Done', dump=False) view.touch() trace('Touch Done') finally: sleep(5) self.goList() def goEditExistContact(self, str): try: self.search(str).touch() sleep(4) except AttributeError: trace('No contact with info ' + str + ' found') return False self.menu() sleep(1) self.scroll(1) self.device.press('KEYCODE_ENTER') sleep(3) return True def editCompany(self, company): view = self.getView('Add organization') if view: trace('Step: add a organization info') view.touch() sleep(1) trace('add the company info') self.device.type(company) sleep(1) else: trace('Step: Edit the organization info') view = self.getView('id/no_id/42', iD=True) self.wipe(view) trace('Edit the company info') self.device.type(company) sleep(1) def editDetails(self, contactsInfo, fieldName, content, update=True): ''' edit details of contact with add or update @type contactsInfo: str @param contactsInfo: information of contacts @type fieldName: str @param fieldName: field string of @return: snapshot object ''' self.goEditExistContact(contactsInfo) if fieldName not in [ 'Name', 'Phone', 'Email', 'Address', 'Company', 'Website', 'Nickname', 'Notes' ]: raise SyntaxError( "wrong 2nd parameter: fieldName choose from 'Name','Phone','Email','Address','Company','Website','Nickname','Notes'" ) if 'Name' == fieldName: self.editName(content) if 'Company' == fieldName: self.editCompany(content) addOrUpdate = 'update' if update else 'add' if 'update' == addOrUpdate: self.updateDetails(fieldName, content) if 'add' == addOrUpdate: self.addDetails(fieldName, content) self.getView('Done', dump=False).touch() trace('Click Done') sleep(3) self.goList() def editName(self, str): #find EditText of Name view = self.getView('id/no_id/27', iD=True) #edit name self.wipe(view) view.type(str) sleep(1) trace("edit contact's name OK") def addDetails(self, fieldName, content): trace('edit' + fieldName + 'with add') #touch 'Add another field' while not self.getView('Add another field').touch(): self.slide('up') sleep(2) sleep(3) #touch fieldName and edit while not self.getView(fieldName): view2 = self.getView('id/no_id/2', iD=True, dump=False) self.slide('up', view2) self.getView(fieldName, dump=False).touch() sleep(2) self.device.type(content) sleep(1) trace('edit' + fieldName + 'with add OK') def updateDetails(self, fieldName, content): trace('Edit field ' + fieldName + ' info') while not self.getView(fieldName): self.slide('up') sleep(2) view = self.getView(fieldName, dump=False) view2 = self.getView(view.getId()[:-2] + str(int(view.getId()[-2:]) + 6), iD=True) self.wipe(view2) sleep(1) view2.type(content) sleep(1) return True def search(self, str): ''' @type str: str @param str: specify the search keyword ##@return: the view of search result if search result is not null, else return None ''' trace("start searching...") self.goList() searchView = self.getView("Search", True) searchView.touch() sleep(2) self.device.type(str) trace("search keyword is: " + str) #the id of 1st search result is always 28 if self.getView("No contacts"): trace("No contact searched") return None else: return self.getView("id/no_id/28", iD=True) def sortAndViewAs(self, sortByFirstName=True, viewAsFirstNameFirst=True): ''' sort contact name @type sortByFirstName: boolean @param sortByFirstName: whether sort contact name by first name @type viewAsFirstNameFirst: boolean @param viewAsFirstNameFirst: whether view contact by first name first ''' self.goList() trace("start sorting...") self.device.press("KEYCODE_MENU", "DOWN_AND_UP") settingsView = self.getView("Settings") settingsView.touch() sleep(2) self.getView("Sort list by").touch() if sortByFirstName: self.getView("First name").touch() sleep(2) self.getView("View contact names as").touch() sleep(2) if viewAsFirstNameFirst: self.getView("First name first").touch() else: self.getView("Last name first").touch() else: self.getView("Last name").touch() sleep(2) self.getView("View contact names as").touch() sleep(2) if viewAsFirstNameFirst: self.getView("First name first").touch() else: self.getView("Last name first").touch() sleep(2) def favor(self, str, favor=True): ''' add or cancel contact to favorites @type str: str @param str: specify the search string @type favor: boolean @param favor: add if True ''' try: self.search(str).touch() sleep(3) except AttributeError: trace('no matched contact found, operation failed!') self.goList() return False aim, action = ('Add to favorites', 'add') if favor else ('Remove from favorites', 'remov') try: self.getView(aim, cD=True).touch() trace('%s successfully' % aim) except AttributeError: trace('%s has been %sed in favorites, not have to %s repeatedly' % (str, action, action)) sleep(3) self.goList() return True def delete(self, kwd=''): '''delete one contact @type kwd: string @param kwd: keyword which contact to be delete, if none,delete first contact @return: ''' #self.start() #trace('launch on contact application') self.goList() if self.isEmpty(): trace('Could not find any contact data,no record!') raise SyntaxError('Could not find any contact data,no record!') if not kwd: # keyword is empty,delete first contact trace('keyword is none, first contact with be delete') find = self.getView('id/no_id/27', iD=True, dump=False) #if find != None: else: # keyword is not none # search specifying contact by keyword find = self.search(kwd) trace('') # if find != None: if not find: trace('Could not find the contact : ' + kwd) raise SyntaxError('Could not find the contact : ' + kwd) else: # delete operate find.touch() sleep(3) trace('show contact detail information') sleep(1) self.device.press('KEYCODE_MENU') sleep(4) delete_menu = self.getView('Delete') trace('choose delete contact') delete_menu.touch() # confirm delete operate ok_menu = self.getView('OK') ok_menu.touch() sleep(3) # if current activity is not Main Activity back to Main Activity self.goList() if 0 == self.getCounter(): trace(' all contacts has been deleted, no record!') trace('operation success.')
class action(object): def __init__(self,device,feature,devID='emulator-5554'): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type feature: str @param feature: feature name, use to mark in trace log @type devID: str @param serialno: the serial number of the device or emulator to connect to ''' self.device = device self.feature = feature #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == u'.75': statusBarHeight = 19 elif density == u'1.5': statusBarHeight = 38 elif density == u'2.0': statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight #define the point coordinate used to slide screen self.left = (width/4, height/2) self.right = (width/4*3, height/2) self.up = (width/2, height/4) self.down = (width/2, height/4*3) self.center = (width/2, height/2) self.trace('Before instance') self.vc=ViewClient(device, devID) self.trace('After instance') def trace(self,str): ''' trace @type str: str @param str: specified trace info ''' mTrace('[%s]:%s'%(self.feature,str)) def sleep(self,duration=1): ''' Monkey sleep @type duration: int @param duration: how long to sleep ''' MonkeyRunner.sleep(duration) def menu(self): ''' press menu ''' self.device.press('KEYCODE_MENU','DOWN_AND_UP') self.trace('Press menu') self.sleep(3) def scroll(self,times=1,down=True): ''' scoll up or down for some times then touch the highlight submenu item @type down: boolead @param down: scroll down if True or scroll up @type times: int @param times: how many times to scroll ''' keycode = 'KEYCODE_DPAD_DOWN' if down else 'KEYCODE_DPAD_UP' for i in range(times): self.device.press(keycode,'DOWN_AND_UP') self.trace('Scroll %s' % keycode.split('_')[-1].lower()) self.device.press('KEYCODE_ENTER','DOWN_AND_UP') self.trace('Press Enter') self.sleep(2) def back(self): ''' press back ''' self.device.press('KEYCODE_BACK','DOWN_AND_UP') self.trace('Press back') def startComponent(self,componentName): ''' start activity @type componentName: str @param componentName: component name ''' self.device.startActivity(component=componentName) self.trace('Start component: %s' % componentName) self.sleep(2) def stopPackage(self,package): ''' stop activity @type package: str @param package: package name ''' self.device.shell('am force-stop %s' % package) self.trace('Force stop contacts package %s' % package) def type(self,str): ''' type @type str: str @param str: strings to type ''' self.device.type(str) self.trace('Type %s' % str) def slide(self,str,view=None): ''' slide the screen @type: str @param: 'left','right','up','down' @type view: view @param view: specify the view, default to None ''' if str not in ['left','right','up','down']: raise SyntaxError("Wrong Parameter: choose from 'left','right','up' or 'down'") try: cX = view.getX() cY = view.getY() width = view.getWidth() height = view.getHeight() cL = cX + width/4, cY + height/2 cR = cX + width/4*3, cY + height/2 cU = cX + width/2, cY + height/4 cD = cX + width/2, cY + height/4*3 except AttributeError: pass (left, right, up, down) = (cL, cR, cU, cD) if view else (self.left, self.right, self.up, self.down) nav = { 'left':{'start':right,'end':left}, 'right':{'start':left,'end':right}, 'up':{'start':down,'end':up}, 'down':{'start':up,'end':down} } self.device.drag(nav[str]['start'], nav[str]['end'], 0.1, 10) self.trace('Slide the screen from %s to %s ' % (nav[str]['start'],nav[str]['end'])) self.sleep(2) def getView(self,str,cD=False,iD=False,dump=True,regex=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @type dump: boolean @param dump: whether execute dump before findView, depending on whether the screen is changed @return: the view found ''' if dump: if DEBUG: self.trace('Before dump') self.vc.dump() if DEBUG: self.trace('After dump') if cD: view=self.vc.findViewWithContentDescription(str) self.trace('Query view with content description: %s, return is %s' % (str, view is not None)) return view elif iD: view=self.vc.findViewById(str) self.trace('Query view by id: %s, return is %s' % (str, view is not None)) return view elif regex: view=self.vc.findViewWithAttributeThatMatches('text',re.compile(str)) self.trace('Query view that match attribute: %s, return is %s' % (str, view is not None)) return view else: view=self.vc.findViewWithText(str) self.trace('Query view with text: %s, return is %s ' % (str, view is not None)) return view def touch(self,view): ''' touch the specified view @type view: view @param view: specified view @return: True ''' x = view.getX() y = view.getY() w = view.getWidth() h = view.getHeight() self.device.touch(x + w/2, y + h/2,'DWON_AND_UP') self.trace('Touch (%d,%d)' % (x + w/2, y + h/2)) self.sleep(3) return True def snapshot(self,title): ''' take snapshot @type title: str @param title: specify the title of snapshot @return: snapshot object ''' snapName = title + '_' + snapTime() + '.png' snapFolder = 'snapshot' os.system('if not exist %s\\%s mkdir %s\\%s' % (logPath, snapFolder, logPath, snapFolder)) snapFile = logPath + '\\' + snapFolder + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) self.trace('Take snapshot without the statusbar') result.writeToFile(snapFile,'png') self.trace('Save snapshot to file: %s ' % snapFile) return result def wipe(self,view): ''' wipe the text in specified view @type view: view @param view: specified view ''' try: self.device.drag(view.getXY(),view.getXY(),1,1) self.trace('Wipe text: %s' % str(view.getText())) self.device.press('KEYCODE_DEL','DOWN_AND_UP') except: Exception('Wipe failed')
#! /usr/bin/env python # -*- coding: utf-8 -*- import time from com.dtmilano.android.viewclient import ViewClient from com.dtmilano.android.adb import adbclient device, serialno = ViewClient.connectToDeviceOrExit() vc = ViewClient(device, serialno) adb = adbclient.AdbClient(serialno='.*') def wait_for_id(vc, 'id): while True: vc.dump(window=-1) if vc.findViewById(id) is None: time.sleep(0.5) else: return def wait_for_id_and_touch(id): while True: vc.dump(window=-1) if vc.findViewById(id) is None: time.sleep(0.5) else: vc.findViewByIdOrRaise(id).touch() return def wait_for_text(vc, 'text): while True: vc.dump(window=-1)
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554',sample = False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device=device self.sample=sample self.startStatus=False '''the status which indicate whether the contacts activity is started''' self.vc=ViewClient(device, devID) #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' self.device.startActivity(component=componentName) sleep(3) self.startStatus = self.isReady() def back(self): ''' press back ''' self.device.press('KEYCODE_BACK','DOWN_AND_UP') def getView(self,str,cD=False,iD=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @return: the view found ''' self.vc.dump() sleep(3) if not cD: if not iD: return self.vc.findViewWithText(str) else: return self.vc.findViewById(str) else: return self.vc.findViewWithContentDescription(str) def isReady(self): ''' check whether the contacts is ready. ''' while True: view=self.getView('Contact list is being updated to reflect the change of language.') if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def goEdit(self): ''' check whether the contact is empty, then select adding and go to edit view. @return: True ''' self.check() view=self.getView('Create a new contact') if view: view.touch() trace('Click "Create a new contact"') view=self.getView('Keep local') if view: view.touch() trace('Select "Keep local"') else: view=self.getView('Add Contact',True) view.touch() trace('Click "Add Contact"') return True def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.status: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self,title): ''' take snapshot @type title: str @param title: specify the title of snapshot ''' snapName = title + '.png' snapFile = logPath + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) result.writeToFile(snapFile,'png') def addContact(self,name='',phone='',email=''): #notice firstly call self.goEdit() pass def editDetails(self,phone=''): pass def search(self,str): ''' @type str: str @param str: specify the search keyword ##@return: the view of search result if search result is not null, else return None ''' trace("start searching...") trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search",True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() searchView=self.getView("Search",True) searchView.touch() self.device.type(str) trace("search keyword is: "+str) self.snapshot("search_result") ''' tmp=[] self.vc.dump() trace("dump, please wait...") #the id of 1st search result is always 28 for i in self.vc.findViewsContainingPoint((100,200)): tmp.append(i.getId()) result=int(tmp[len(tmp)-1][-2:]) if(result<28): trace("search result: nothing") return None else: self.snapshot("search_result") return self.vc.findViewById(tmp[len(tmp)-1]) ''' def sortAs(self, sortByFirstName=True): ''' sort contact name @type sortByFirstName: boolean @param sortByFirstName: whether sort contact name by first name ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search",True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start sorting...") self.device.press("KEYCODE_MENU","DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView=self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("Sort list by").touch() trace("click Sort list by, dump, please wait...") self.vc.dump() if sortByFirstName: self.vc.findViewWithTextOrRaise("First name").touch() else: self.vc.findViewWithTextOrRaise("Last name").touch() sleep(2) #conflict with check at the begining #self.device.press("KEYCODE_BACK","DOWN_AND_UP") #sleep(2) def viewAs(self, viewAsFirstNameFirst=True): ''' view contact name @type viewAsFirstNameFirst: boolean @param viewAsFirstNameFirst: whether view contact by first name first ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search",True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start viewing...") self.device.press("KEYCODE_MENU","DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView=self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("View contact names as").touch() trace("click View contact names as, dump, please wait...") self.vc.dump() if viewAsFirstNameFirst: self.vc.findViewWithTextOrRaise("First name first").touch() else: self.vc.findViewWithTextOrRaise("Last name first").touch() sleep(2) #conflict with check at the begining #self.device.press("KEYCODE_BACK","DOWN_AND_UP") #sleep(2) def favorite(self,name=''): pass
class contacts: ''' contacts class ''' def __init__(self, device, devID='emulator-5554',sample = False): ''' constructor @type device: MonkeyDevice @param device: The device or emulator connected @type devID: str @param serialno: the serial number of the device or emulator to connect to @type sample: boolean @param sample: whether take snapshot as an sampling ''' self.device=device self.sample=sample self.contactCounter=0 self.startStatus=False '''the status which indicate whether the contacts activity is started''' #use below code to remove the status bar from the snapshot width = int(device.getProperty('display.width')) height = int(device.getProperty('display.height')) density = device.getProperty('display.density') if density == .75: statusBarHeight = 19 elif density == 1.5: statusBarHeight = 38 elif density == 2.0: statusBarHeight = 50 else: statusBarHeight = 25 self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight #define the point coordinate used to slide screen self.left = (width/4, height/2) self.right = (width/4*3, height/2) self.up = (width/2, height/4) self.down = (width/2, height/4*3) self.center = (width/2, height/2) trace('before instance') self.vc=ViewClient(device, devID) trace('after instance') def start(self): ''' start the contacts activity and set the startStatus True if contacts is ready. ''' trace('Starting activity ...') self.device.startActivity(component=componentName) sleep(2) self.startStatus = self.goList() trace('Contacts is started, checking the contacts status...') self.isReady() sleep(2) def stop(self): ''' stop the contacts activity and set the startStatus False ''' self.device.shell('am force-stop %s' % package) trace('force stop contacts package %s' % package) self.startStatus = False def back(self): ''' press back ''' self.device.press('KEYCODE_BACK','DOWN_AND_UP') trace('press back') def slide(self,str): ''' slide the screen @type: str @param: 'left','right','up','down' ''' if str not in ['left','right','up','down']: raise SyntaxError("wrong parameter: choose from 'left','right','up' or 'down'") nav = { 'left':{'start':self.right,'end':self.left}, 'right':{'start':self.left,'end':self.right}, 'up':{'start':self.down,'end':self.up}, 'down':{'start':self.up,'end':self.down} } self.device.drag(nav[str]['start'], nav[str]['end'], 0.1, 1) trace('slide the screen from %s to %s ' % (nav[str]['start'],nav[str]['end'])) sleep(2) def getView(self,str,cD=False,iD=False,dump=True,regex=False): ''' get the view with the specified text, content description or viewId @type str: str @param str: the query string @type cD: boolean @param cD: whether handle the query str as content description @type iD: boolean @param iD: whether handle the query str as viewId @type dump: boolean @param dump: whether execute dump before findView, depending on whether the screen is changed @return: the view found ''' if dump: trace('before dump') self.vc.dump() trace('after dump') if cD: view=self.vc.findViewWithContentDescription(str) trace('Query view with content description: %s, return is %s' % (str, view is not None)) return view elif iD: view=self.vc.findViewById(str) trace('Query view by id: %s, return is %s' % (str, view is not None)) return view elif regex: view=self.vc.findViewWithAttributeThatMatches('text',re.compile(str)) trace('Query view that match attribute: %s, return is %s' % (str, view is not None)) return view else: view=self.vc.findViewWithText(str) trace('Query view with text: %s, return is %s ' % (str, view is not None)) return view def isReady(self): ''' check whether the contacts is ready. @return: True ''' while True: view=self.getView('Contacts list is being updated to reflect the change of language.') if not view: trace('Contacts is ready') break else: trace('Contacts is not ready, please wait!') sleep(2) return True def isEmpty(self): ''' check whether the contacts is empty @return: True or False ''' self.check() view=self.getView('No contacts.') if view: trace('Contacts list is empty') return True else: trace('Contacts list is not empty') return False def getCounter(self): ''' get the contacts counter @return: the current contacts counter ''' self.goList() if self.isEmpty(): self.contactCounter=0 else: while not self.getView('\d+ contacts?',regex=True): self.slide('down') sleep(3) self.contactCounter = int(self.getView('\d+ contacts?',regex=True,dump=False).getText().split()[0]) trace('current contacts counter is %d' % self.contactCounter) return self.contactCounter def goList(self): ''' check whether the screen is in contacts list view, if not, go list view via pressing back key @return: True ''' while True: view=self.getView("All contacts",cD=True) if not view: self.back() sleep(3) else: if not view.isSelected(): trace('Touch "All contacts"') view.touch() break trace('Goto contacts list view') return True def goEdit(self): ''' check whether the contacts is empty, then select adding and go to edit view. @return: True ''' self.check() try: self.getView('Add Contact',cD=True,dump=False).touch() trace('Touch "Add Contact"') sleep(5) return True except AttributeError: pass try: self.getView('Create a new contact',dump=False).touch() trace('Touch "Create a new contact"') sleep(5) self.getView('Keep local').touch() trace('Select "Keep local"') sleep(5) return True except AttributeError: pass def check(self): ''' check whether the contacts is started before other operation about contacts @return: True ''' if not self.startStatus: trace("Wrong code! please start contacts firstly in you code") raise SyntaxError('contacts should be start firstly!') return True def snapshot(self,title): ''' take snapshot @type title: str @param title: specify the title of snapshot @return: snapshot object ''' snapName = title + '.png' snapFolder = 'snapshot' os.system('if not exist %s\\%s mkdir %s\\%s' % (logPath, snapFolder, logPath, snapFolder)) snapFile = logPath + '\\' + snapFolder + '\\' + snapName result = self.device.takeSnapshot().getSubImage(self.snap_rect) trace('take snapshot without the statusbar') result.writeToFile(snapFile,'png') trace('save the snapshot to file: %s ' % snapFile) return result def wipe(self,view): ''' wipe the text in specified view ''' try: self.device.drag(view.getXY(),view.getXY(),1,1) trace('wipe text: %s' % str(view.getText())) self.device.press('KEYCODE_DEL','DOWN_AND_UP') except: Exception('wipe failed') def addContact(self,name='',phone='',email='',address=''): self.goEdit() try: offset = 0 if name: view=self.getView('id/no_id/27',iD=True) trace('type %s' % name) view.type(name) view.touch() if phone: view=self.getView('id/no_id/46',iD=True,dump=False) trace('type %s' % phone) view.type(phone) offset += 4 sleep(2) if email: view=self.getView('id/no_id/' + str(57 + offset), iD=True) trace('type %s' % email) view.type(email) offset += 4 sleep(2) if address: view=self.getView('id/no_id/' + str(68 + offset), iD=True) trace('type %s' % address) view.type(address) sleep(2) view=self.getView('Done',dump=False) view.touch() trace('Touch Done') finally: sleep(5) self.goList() def goEditExistContact(self,str): trace('Search a contact to edit') view=self.search(str) if not view: raise SyntaxError('No '+str+' contact to edit') view.touch() sleep(4) self.device.press('KEYCODE_MENU') sleep(2) self.device.press('KEYCODE_DPAD_DOWN') sleep(1) self.device.press('KEYCODE_ENTER') sleep(3) def slideByView(self,view): trace('SlideByView') startp=(view.getX()+view.getWidth()-10,view.getY()+view.getHeight()-10) endpoint=(view.getX()+view.getWidth()-10,view.getY()+10) self.device.drag(startp,endpoint,0.5,1) sleep(1) def editCompany(self,company,action): view=self.getView('Add organization') if view: trace('Step: add a organization info') view.touch() sleep(1) trace('add the company info') self.device.type(company) sleep(1) view=self.getView('Title') trace("add a company's Title") view.type(company) else: trace('Step: Edit the organization info') view=self.getView('id/no_id/42',iD=True) self.wipe(view) trace('Edit the company info') self.device.type(company) view=self.getView('id/no_id/43',iD=True) trace("Edit the company's Title") self.wipe(view) self.device.type(company) def editAnotherField(self,fieldName,content,action): find=1 view=self.getView(fieldName) view2=self.getView('Add another field') while not view: self.device.drag((440,760),(440,160),2,5) sleep(1) view=self.getView(fieldName) view2=self.getView('Add another field') if view2: if not view: find=0 break if 0==find: trace('Step: add field '+fieldName+' info') view2.touch() trace('Click Add another field') sleep(2) view=self.getView(fieldName) if not view: view2=self.getView('id/no_id/2',iD=True) self.slideByView(view2) view=self.getView(fieldName) view.touch() sleep(1) #view=self.getView(fieldName) #view2=self.getView(view.getId()[:-2]+str(int(view.getId()[-2:])+6),iD=True) #view2.type(content) sleep(1) self.device.type(content) sleep(2) else: trace('Step: Edit field '+fieldName+' info') view2=self.getView(view.getId()[:-2]+str(int(view.getId()[-2:])+6),iD=True) self.wipe(view2) sleep(1) view2.type(content) sleep(1) def editDetails(self,nameOrNumber,company='',website='',nickname='',notes='',action='add'): ''' ''' self.goEditExistContact(nameOrNumber) if not company=='': self.editCompany(company,action) if not website=='': self.editAnotherField('Website',website,action) if not nickname=='': self.editAnotherField('Nickname',nickname,action) if not website=='': self.editAnotherField('Notes',notes,action) view=self.getView('Done') trace('Click Done') view.touch() sleep(3) self.goList() def search(self,str): ''' @type str: str @param str: specify the search keyword ##@return: the view of search result if search result is not null, else return None ''' trace("start searching...") self.goList() searchView=self.getView("Search",True) searchView.touch() sleep(2) self.device.type(str) trace("search keyword is: "+str) #the id of 1st search result is always 28 if self.getView("No contacts"): trace("No contact searched") return None else: return self.getView("id/no_id/28",iD=True) def sortAndViewAs(self, sortByFirstName=True, viewAsFirstNameFirst=True): ''' sort contact name @type sortByFirstName: boolean @param sortByFirstName: whether sort contact name by first name @type viewAsFirstNameFirst: boolean @param viewAsFirstNameFirst: whether view contact by first name first ''' self.goList() trace("start sorting...") self.device.press("KEYCODE_MENU","DOWN_AND_UP") settingsView=self.getView("Settings") settingsView.touch() sleep(2) self.getView("Sort list by").touch() if sortByFirstName: self.getView("First name").touch() sleep(2) self.getView("View contact names as").touch() sleep(2) if viewAsFirstNameFirst: self.getView("First name first").touch() else: self.getView("Last name first").touch() else: self.getView("Last name").touch() sleep(2) self.getView("View contact names as").touch() sleep(2) if viewAsFirstNameFirst: self.getView("First name first").touch() else: self.getView("Last name first").touch() sleep(2) def favor(self,str,favor=True): ''' add or cancel contact to favorites @type str: str @param str: specify the search string @type favor: boolean @param favor: add if True ''' try: self.search(str).touch() sleep(3) except AttributeError: trace('no matched contact found, operation failed!') self.goList() return False aim, action = ('Add to favorites', 'add') if favor else ('Remove from favorites', 'remov') try: self.getView(aim, cD=True).touch() trace('%s successfully' % aim) except AttributeError: trace('%s has been %sed in favorites, not have to %s repeatedly' % (str, action, action)) sleep(3) self.goList() return True def delete(self,kwd = ''): '''delete one contact @type kwd: string @param kwd: keyword which contact to be delete, if none,delete first contact @return: ''' #self.start() #trace('launch on contact application') self.goList() if self.isEmpty(): trace('Could not find any contact data,no record!') raise SyntaxError('Could not find any contact data,no record!') if not kwd : # keyword is empty,delete first contact trace('keyword is none, first contact with be delete') find = self.getView('id/no_id/27',iD=True,dump=False) #if find != None: else : # keyword is not none # search specifying contact by keyword find = self.search(kwd) trace('') # if find != None: if not find : trace('Could not find the contact : ' + kwd) raise SyntaxError('Could not find the contact : ' + kwd) else: # delete operate find.touch() sleep(3) trace('show contact detail information') sleep(1) self.device.press('KEYCODE_MENU') sleep(4) delete_menu = self.getView('Delete') trace('choose delete contact') delete_menu.touch() # confirm delete operate ok_menu = self.getView('OK') ok_menu.touch() sleep(3) # if current activity is not Main Activity back to Main Activity self.goList() if 0 == self.getCounter() : trace(' all contacts has been deleted, no record!') trace('operation success.')
vc.dump(window='-1') vc.sleep(_s) vc.dump(window='-1') #Theme 1 = STACK STACK if vc.findViewWithContentDescription(u'''stack_stack'''): id_scroll_view = vc.findViewByIdOrRaise("com.restwla.z"+appid+":id/scroll_view") #screenshot of information page vc.findViewByIdOrRaise('com.restwla.z'+appid+':id/home_option_information').touch() vc.sleep(_s) device.takeSnapshot().save(path+'/whitelabel/WLA_database/'+appid+'/screenshots/info_page.png','PNG') device.press('KEYCODE_BACK') #screenshot of photos page if vc.findViewById('com.restwla.z'+appid+':id/home_option_photos'): vc.findViewByIdOrRaise('com.restwla.z'+appid+':id/home_option_photos').touch() vc.sleep(_s) device.takeSnapshot().save(path+'/whitelabel/WLA_database/'+appid+'/screenshots/photos_page.png','PNG') device.press('KEYCODE_BACK') id_scroll_view.uiScrollable.flingToEnd() vc.sleep(_s) vc.dump(window='-1') #screenshot of Menus page if vc.findViewById('com.restwla.z'+appid+':id/home_option_menus'): vc.findViewByIdOrRaise('com.restwla.z'+appid+':id/home_option_menus').touch() vc.sleep(_s)