Esempio n. 1
1
def SetWifiConnect(vc):
        package = 'com.android.settings'
        activity = '.Settings'
        component_name = package + '/' + activity
        ap_name = "dlink-549"
        ap_password = "******"
        # Open the Settings app
        vc.device.startActivity(component=component_name)
        # Enable Wi-Fi
        vc.device.shell("svc wifi enable")
        vc.dump()
        wifi = vc.findViewWithTextOrRaise(u'Wi‑Fi')        
        if wifi:
                wifi.touch()
                vc.dump()
        i = 0
        br_ap=vc.findViewWithText(ap_name)
        while not br_ap and i<30:
                br_ap=vc.findViewWithText(ap_name)
                ViewClient.sleep(1)
                vc.dump()
                i += 1
        if i == 30:
                print "Cannot enable Wi-Fi"
    
        br_ap.touch()
        vc.device.type(ap_password)
        vc.dump()
        connect = vc.findViewWithText(u'Connect')
        if connect:
                connect.touch()
                vc.sleep(3)
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 action_open_editor_and_type_text(device, serialno):
    print("open editor")
    # Open Posts
    for i in range(3):
        device.press('KEYCODE_DPAD_UP')
    device.press('KEYCODE_DPAD_DOWN')
    device.press('KEYCODE_DPAD_DOWN')
    device.press('KEYCODE_DPAD_DOWN')
    device.press('KEYCODE_ENTER')
    time.sleep(1)
    # Open editor
    device.press('KEYCODE_DPAD_RIGHT')
    device.press('KEYCODE_ENTER')
    time.sleep(1)
    device.press('KEYCODE_TAB')
    device.press('KEYCODE_DPAD_DOWN')
    # Type a sample text (spaces can't be entered via device.type())
    for word in settings.example_post_content.split():
        device.type(word)
        device.press('KEYCODE_SPACE')
    # Open virtual keyboard by touching the screen
    viewclient = ViewClient(device, serialno)
    view = viewclient.findViewWithText(settings.example_post_content)
    view.touch()
    time.sleep(1)
Esempio n. 4
0
    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 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)
Esempio n. 6
0
    def setUp(self):
        # Connnect to device
        self.device, self.serialno = ViewClient.connectToDeviceOrExit(serialno=YkspTestCase.serial)

        # Wake device
        self.device.wake()

        # Create ViewClient instance
        self.vc = ViewClient(self.device, self.serialno, autodump=False)
Esempio n. 7
0
    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()
Esempio n. 8
0
    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 init_view_client():
    package = 'kr.kdev.dg1s.biowiki'
    #activity = '.ui.posts.PostsActivity'
    activity = '.ui.accounts.NewBlogActivity'
    device, serialno = ViewClient.connectToDeviceOrExit()
    component = package + '/' + activity
    device.startActivity(component=component, flags=FLAG_ACTIVITY_NEW_TASK)
    ViewClient.sleep(2)
    return ViewClient(device, serialno), device
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)
Esempio n. 11
0
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
Esempio n. 12
0
def waitViewById(viewId,vc):
    #while True:
    for i in range(20):
        vc.dump()
        if vc.findViewById(viewId):
            print 'view with id %s is appeared----'%(viewId)
            break
        else:
            print 'view with id %s not appear wait 1 second for a while------'%(viewId)
            ViewClient.sleep(3)
Esempio n. 13
0
def waitViewByTx(text,vc):
    #while True:
    for i in range(20):
        vc.dump()
        if vc.findViewWithText(text):
            print 'view with text %s is appeared----'%(text)
            break
        else:
            print 'view with text %s not appear wait 1 second for a while------'%(text)
            ViewClient.sleep(3)
    def setUpClass(cls):
        '''
        Set ups the class.

        The preconditions to run this test is to have at least 2 emulators running:
           - emulator-5554
           - emulator-5556
        '''
        sys.argv = ['testViewClient_localPort_remotePort', serialno1]
        cls.device1, cls.serialno1 = ViewClient.connectToDeviceOrExit(timeout=30)

        sys.argv = ['testViewClient_localPort_remotePort', serialno2]
        cls.device2, cls.serialno2 = ViewClient.connectToDeviceOrExit(timeout=30)
Esempio n. 15
0
    def __init__(self, serialno=None, pkgname=None):
        self._last_point = None
        self._threshold = 0.3 # for findImage
        self._rotation = None # UP,DOWN,LEFT,RIGHT
        self._tmpdir = 'tmp'

        if not os.path.exists(self._tmpdir):
            base.makedirs(self._tmpdir)

        self.pkgname = pkgname
        self.adb, self._serialno = ViewClient.connectToDeviceOrExit(verbose=False, serialno=serialno)
        self.adb.reconnect = True # this way is more stable

        w = self.adb.getProperty("display.width")
        h = self.adb.getProperty("display.height")
        self._width = min(w, h)
        self._height = max(w, h)

        self.vc = ViewClient(self.adb, serialno)
        ViewClient.connectToDeviceOrExit()
        brand = self.adb.getProperty('ro.product.brand')
        serialno = self.adb.getProperty('ro.boot.serialno')
        log.debug('wake phone: brand:{brand}, serialno:{serialno}'.format(
            brand=brand, serialno=self._serialno))
        try:
            self.adb.wake()
            if not self.adb.isScreenOn():
                time.sleep(1)
            log.debug('isScreenOn: %s', self.adb.isScreenOn())
            if self.adb.isLocked():
                (w, h) = self._getShape()
                self.drag((w*0.2, h*0.5), (w*0.6, h*0.5))
        except:
            print 'Device not support screen detect'

        @patch.go
        def monitor(interval=3):
            log.debug('MONITOR started')
            if not self.pkgname:
                log.debug('MONITOR finished, no package provided')
                return
            while True:
                start = time.time()
                mem = self._getMem()
                jlog.writeline({'type':'record', 'mem':mem})
                cpu = self._getCpu()
                jlog.writeline({'type':'record', 'cpu':cpu})
                dur = time.time()-start
                if interval > dur:
                    time.sleep(interval-dur)
        monitor()
Esempio n. 16
0
    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()
Esempio n. 17
0
 def init(device):
     print 'init the test environment..ing.'
     #get Device connection
     #device = UtilTool.connectToDevice()
     #lanuch Contacts app
     device.startActivity(component='com.android.contacts/.activities.PeopleActivity')
     MonkeyRunner.sleep(15)
     #print device
     #get a ViewClient instance
     vc = ViewClient(device,'emulator-5554')
     MonkeyRunner.sleep(10)
     #get Window content of current page
     vc.dump()
     MonkeyRunner.sleep(5)
     return vc
Esempio n. 18
0
class adbDevice(object):
#     inputMethodRe = re.compile('\[\s+0,    0, 1061, 1920] InputMethod')
    
    def __init__(self, serialno=None):
        self.lock = threading.Semaphore()
        self.cmd = adbCmd(serialno)
        self.serialno = serialno

    def connect(self):
        self.d, self.serialno = ViewClient.connectToDeviceOrExit(serialno=self.serialno)
        self.vc = ViewClient(self.d, self.serialno, compresseddump=False, ignoreuiautomatorkilled=True, autodump=False)     
    
    def startActivity(self, component):
        component = component.replace('$', '\$')
        self.cmd.shell(['am', 'start', '-n', component, '--activity-clear-task'])
        
    def isConnected(self):
        if self.__getDevices(self.serialno):
            return True
        else:
            return False
    
    def listPackages(self):
        return self.cmd.shell(['pm', 'list', 'package'], output=True)
    
    def reboot(self):
        self.cmd.reboot()
        
    def findAndTouch(self, text):
        self.dump(0)
        view = self.vc.findViewWithText(text)
        if view:
            view.touch()
            return True
        else:
            return False
       
    def dump(self, sleep=0.5, window=-1):
        try:
            self.lock.acquire()
            return self.vc.dump(sleep=sleep, window=-1)
        except RuntimeError as e:
            print e.message 
        except ValueError as e:
            print e.message
        except socket.error, exc:
            print 'Caught exception socket.error : ' + str(exc)
        finally:
Esempio n. 19
0
 def __init__(self, width=1280, threshold=0.8):
     self._device, _ = ViewClient.connectToDeviceOrExit(verbose=False)
     self._actions = []
     self._scale = width / DEFAULT_RESOLUTION
     self._image_cache = {}
     self._threshold = threshold
     self._status = None
Esempio n. 20
0
    def __init__(self, serialno=None):
        print 'SerialNo:', serialno

        self.adb, self._serialno = ViewClient.connectToDeviceOrExit(verbose=False, serialno=serialno)
        self.adb.setReconnect(True) # this way is more stable

        self.vc = ViewClient(self.adb, serialno, autodump=False)
        self._devinfo = self.getdevinfo()

        print 'ProductBrand:', self._devinfo['product_brand']
        print 'CpuCount: %d' % self._devinfo['cpu_count']
        print 'TotalMem: %d MB' % self._devinfo['mem_total']
        print 'FreeMem: %d MB' % self._devinfo['mem_free']

        try:
            if self.adb.isScreenOn():
                self.adb.wake()
        except:
            pass

        width, height = self.shape()
        width, height = min(width, height), max(width, height)
        self._airtoolbox = '/data/local/tmp/airtoolbox'
        self._init_airtoolbox()
        self._init_adbinput()
Esempio n. 21
0
	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
Esempio n. 22
0
 def get_adb(self):
     """
     get adb connection of the device
     """
     if self.adb_enabled and self.adb is None:
         # use adbclient class in com.dtmilano.adb.adbclient
         self.adb, self.serial = ViewClient.connectToDeviceOrExit(verbose=True, serialno=self.serial)
     return self.adb
Esempio n. 23
0
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'
Esempio n. 24
0
    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()
class ViewClientWrapper:
    def __init__(self, serialno):
        device, serialno = ViewClient.connectToDeviceOrExit(serialno=serialno)
        self.viewClient = ViewClient(device, serialno)
        if DEBUG:
            print >> sys.stderr, "ViewClientWrapper: connected to", device, serialno

    def dump(self):
        """Dumps window hierarchy."""
        return self.viewClient.dump()

    def start_activity(self, component):
        """Starts Activity."""
        return self.viewClient.device.startActivity(component)

    def long_touch_button(self, text):
        """Long-touches the button."""
        self.viewClient.findViewWithTextOrRaise(text).longTouch()
 def testViewClient_device_disconnected(self):
     # Script gets stuck on ViewClient(device, serial) #243
     # This cannot run on emulator because we have to disconnect the USB or network
     d, s = ViewClient.connectToDeviceOrExit()
     self.assertIsNotNone(d)
     self.assertIsNotNone(s)
     raw_input('\n** Disconnect the device now and press <ENTER>')
     device = ViewClient(d, s)
     self.assertIsNotNone(device)
Esempio n. 27
0
    def connect(self, deviceID = 'emulator-5554'):
        #check how we can move this out of this function
        from com.dtmilano.android.viewclient import ViewClient

        kwargs1 = {'verbose': True, 'serialno': deviceID}
        kwargs2 = {'forceviewserveruse': False, 'startviewserver': True}

        self.device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
        self.vc = ViewClient(self.device, serialno, **kwargs2)
Esempio n. 28
0
    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()
Esempio n. 29
0
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 run():
    stageRound = 6

    device, serialno = ViewClient.connectToDeviceOrExit()
    ##vc = ViewClient(device, serialno)

    while True:
        print("click btn choose attributes")
        device.touch(993, 439, 0)
        time.sleep(1)

        print("choose light")
        device.touch(474, 849, 0)
        time.sleep(1)

        print("choose demon")
        device.touch(225, 1007, 0)
        time.sleep(1)

        print("click btn confirm")
        device.touch(366, 1529, 0)
        time.sleep(1)

        print("choose ally (index=1)")
        device.touch(580, 700, 0)
        time.sleep(1)

        print("click btn choose ally confirm")
        device.touch(544, 1218, 0)
        time.sleep(1)

        print("entering stage...")
        device.touch(945, 2223, 0)
        time.sleep(20)

        print("turning beads ...")
        #device.touch(991, 1396, 0) # 右上第1顆
        #device.touch(1004, 1751, 0) # 右上第3顆
        for i in range(0, stageRound * 15):
            print("turn count: " + str(i))
            device._AdbClient__send("shell:input swipe 991 1396 991 1751",
                                    checkok=True,
                                    reconnect=True)
            time.sleep(0.5)

        time.sleep(30)

        print("exposure battle results")
        device.touch(564, 1043, 0)
        time.sleep(3)

        print("battle again")
        device.touch(897, 1207, 0)
        time.sleep(5)
Esempio n. 31
0
def run():
    Logger.init(Logger.Mode.STDOUT)
    log("Hello, test.")

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    gmhandler = GoogleMusicApp(device, serialno)
    gmhandler.walk_through()
    gmhandler.dump()
    log(json.dumps(gmhandler.cache, indent=2))

    Logger.finalize()
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)
Esempio n. 34
0
 def get_current_song(self):
     vc = ViewClient(self.handler.device, self.handler.serialno)
     so = StringIO()
     vc.traverse(stream=so)
     line = [
         line for line in so.getvalue().splitlines()
         if GoogleMusicApp.CONTROL_PANEL_TRACKNAME_KEY in line
     ]
     line = line[0] if len(line) > 0 else None
     if line:
         name = utf8str(
             line.split(
                 GoogleMusicApp.CONTROL_PANEL_TRACKNAME_KEY)[-1].strip())
         for playcard_title, info in self.handler.cache["playcard"].items():
             if "songs" in info.keys() and name in info["songs"].keys():
                 song = dict(info["songs"][name])
                 song["name"] = name
                 song["playcard"] = playcard_title
                 return song
     return None
Esempio n. 35
0
def runInstalledApp(path, device, serialno):
    if(appIsInstalled(path, device, serialno)):
        viewClientObject = ViewClient(device, serialno)
        package = getPackageFromApk(path) 
        activity = getLaunchableActivityFromApk(path) 
        return subprocess.check_call([viewClientObject.adb,
                                      "shell", "am", "start",
                                      "-n", package+"/"+activity],
                                      shell=False)
    else: 
        return 1
Esempio n. 36
0
 def connect(self):
     # check devices is connected
     ret = self._run_wrapper('adb devices')
     if self.serialno not in ret:
         self._error_log('device {0} not connected'.format(self.serialno))
     # connecting to device
     try:
         _adb, _serialno = ViewClient.connectToDeviceOrExit(verbose=False, serialno=self.serialno)
         return _adb
     except Exception as e:
         self._error_log('connecting to Android Device {0} Failed: {1}'.format(self.serialno, e))
Esempio n. 37
0
    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')
Esempio n. 38
0
def run(num_iter=1):
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    os.system("mkdir -p {}/ssr_report > /dev/null".format(ROOT_DIR))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    package = "com.htc.audiofunctionsdemo"
    activity = ".activities.MainActivity"
    component = package + "/" + activity

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    wake_device(device, serialno)
    SSRDumpListener.init(device, serialno)

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    device.press("HOME")
    time.sleep(1)
    device.startActivity(component=component)
    time.sleep(1)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += playback_task_run(device,
                                          serialno,
                                          num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += record_task_run(device,
                                        serialno,
                                        num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += voip_task_run(device,
                                      serialno,
                                      num_iter=min([num_iter, BATCH_SIZE]))

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch
        with open("{}/ssr_report/{}".format(ROOT_DIR, filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        num_iter -= BATCH_SIZE
        batch_count += 1

    AudioFunction.finalize()
    Logger.finalize()
    SSRDumpListener.finalize()
    device.press("HOME")
Esempio n. 39
0
def control_Stop_Call(device, serialno):
    vc = ViewClient(device, serialno)
    time.sleep(1)
    end_id = get_end_id(vc)

    if end_id == None:
        log("control_Stop_Call fail")
        return False

    control_Btn(vc, end_id)

    return True
Esempio n. 40
0
 def get_view_client(self):
     """
     get view_client connection of the device
     :return:
     """
     if self.view_client_enabled and self.view_client is None:
         kwargs = {'startviewserver': True,
                   'autodump': False,
                   # 'forceviewserveruse': True,
                   'ignoreuiautomatorkilled': True}
         self.view_client = ViewClient(self.adb, self.serial, **kwargs)
     return self.view_client
def exportContacts():
#adb shell content query --uri content://contacts/phones/  --projection display_name:number 
	kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
	device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
	kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
	vc = ViewClient(device, serialno, **kwargs2)
	app_log.info('Getting device contacts')
	proc = subprocess.Popen([vc.adb, "shell", "content query --uri content://contacts/phones/  --projection display_name:number "], stdout=subprocess.PIPE)
	ret = proc.stdout.read()
	if os.path.exists(PROC_CONTACTS_FILE_PATH): 
		os.remove(PROC_CONTACTS_FILE_PATH) 
	with io.open(PROC_CONTACTS_FILE_PATH, 'w', encoding="utf-8") as filehandle:
		#app_log.info(ret)
		filehandle.write(unicode(ret, "utf-8"))
	with io.open(EXPORT_CONTACTS_FILE_PATH, 'w', encoding="utf-8") as export_filehandle:
		with io.open(PROC_CONTACTS_FILE_PATH, 'r', encoding='utf8') as proc_filehandle:
			for line in proc_filehandle:
				matches = re.finditer(ur'^Row\:\s\d*\sdisplay_name\=(?P<name>.+)\,\snumber\=(?P<number>.+)$',line, re.MULTILINE)
				for matchNum, match in enumerate(matches, start=1):
					export_filehandle.write(match.group('name')+" = "+match.group('number')+"\n")
	app_log.info('Contacts extracted.')
def SimSourceInOut(device, vc):
    global status
    device.startActivity(component=component_battery)
    ViewClient.sleep(3)
    vc.dump()
    no_id7 = vc.findViewByIdOrRaise("id/no_id/7")
    print('Simulation USB Plug-in...')
    temp_in = vc.findViewByIdOrRaise("android:id/title").getText().split('-')
    for x in temp_in:
        if x.find(charge_charging) != -1:
            print('Okay, charging...')
            status = 'true'
        elif x.find(charge_full_charging) != -1:
            print('Okay, Full so not charging...')
            status = 'true'
    if status != 'true':
        print('Fail, not charging...')
        return -1
    print('Simulation USB Plug-out...')
    os.system(sus_vbus_cmd)
    ViewClient.sleep(3)
    vc.dump()
    temp_out = vc.findViewByIdOrRaise("android:id/title").getText().split('-')
    for x in temp_out:
        if x.find(charge_not_charging) != -1:
            print('Okay, Not charging...')
            status = 'true'
    if status != 'true':
        print('Fail, charging...')
        return -1
    ViewClient.sleep(3)
    os.system(nonsus_vbus_cmd)
    print("END")
def check():
    print("check")
    os.system("adb shell cmd statusbar expand-notifications")

    from com.dtmilano.android.viewclient import ViewClient

    device, serialno=ViewClient.connectToDeviceOrExit()
    vc=ViewClient(device=device, serialno=serialno)

    Icon=vc.findViewsWithAttribute("resource-id","com.android.systemui:id/mobile_combo_card")
    time.sleep(1)
    vc.dump()
    Mode=(Icon[0].getContentDescription())
    List=list(Mode)
    L1=List[0]
    L2=List[1]
    global String
    String= L1+ L2
    print(String)
    Split=Mode.split(' ')
    
    L3=Split[1]
    
    L4=Split[2]
    combine=L3+" " + L4
    print(combine)
          
    sets=String+" " + combine
    print(sets)
    
    global gets
    gets=String+" "+ L3
    print(gets)
def main():
    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    vc = ViewClient(device, serialno)
    views_dict = vc.getViewsById()

    print(
        "-------- Show the detail in the returned by the API ViewClient.getViewsById() --------"
    )
    for key, value in views_dict.items():
        print("{}:\n{}\n".format(key, unicode(value).encode("UTF-8")))

    views = filter(lambda v: len(v.getId()) > 0, views_dict.values())
    id_view_dict = {}
    for v in views:
        if v.getId() in id_view_dict.keys():
            id_view_dict[v.getId()].append(v)
        else:
            id_view_dict[v.getId()] = [v]

    print("\n")
    print("-------- Print the id-to-view pairs --------")
    for key, value in id_view_dict.items():
        for each in value:
            print("{}:\n{}\n".format(key, unicode(each).encode("UTF-8")))

    vc.traverse()

    pass
Esempio n. 45
0
    def testViewClient_oneDevice_TwoViewClients(self):
        localPort1 = 9005
        remotePort1 = 9006
        print "Conencting to", remotePort1
        vc1 = ViewClient(device=ViewClientTest.device1,
                         serialno=ViewClientTest.serialno1,
                         localport=localPort1,
                         remoteport=remotePort1,
                         autodump=True)
        self.assertTrue(vc1.getRoot() != None)
        vc1.traverse()

        localPort2 = 9007
        remotePort2 = 9008
        print "Conencting to", remotePort2
        vc2 = ViewClient(device=ViewClientTest.device2,
                         serialno=ViewClientTest.serialno2,
                         localport=localPort2,
                         remoteport=remotePort2,
                         autodump=True)
        self.assertTrue(vc2.getRoot() != None)
        vc2.traverse()
def installTools():
	kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
	device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
	kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
	vc = ViewClient(device, serialno, **kwargs2)
	app_log.debug('Installing APK...');
	subprocess.check_call([vc.adb, "install", "./bin/SPI_ZAPiX.apk"], shell=False)
	app_log.debug('Testing apk');
	subprocess.check_call([vc.adb, "shell", "am", "start", "-n", "br.spi.whatsapp.spi_zapix/br.spi.whatsapp.spi_zapix.MainActivity"], shell=False)
	time.sleep(SLEEP_2)
	'''proc = subprocess.Popen([vc.adb, "shell", "dumpsys package br.spi.whatsapp.spi_zapix |grep -c '^.*android.permission.WRITE_EXTERNAL_STORAGE: granted=true$'",], stdout=subprocess.PIPE)
	permission = proc.stdout.readline()[:-1]
	while int(permission) == 0:
		raw_input('Allow READ/WRITE permission to SPI_ZAPiX and hit a key...')
		proc = subprocess.Popen([vc.adb, "shell", "dumpsys package br.spi.whatsapp.spi_zapix |grep -c '^.*android.permission.WRITE_EXTERNAL_STORAGE: granted=true$'",], stdout=subprocess.PIPE)
		permission = proc.stdout.readline()[:-1]'''
	
	subprocess.check_call([vc.adb, "shell", "am", "force-stop", "com.rarlab.rar"], shell=False)
	
	app_log.debug('Installing Busybox...');
	subprocess.check_call([vc.adb, "push", "./bin/busybox", DEVICE_TMP], shell=False)
	subprocess.check_call([vc.adb, "shell", "chmod", "777", DEVICE_BUSYBOX], shell=False)
Esempio n. 47
0
def main(output_path="out.png"):
    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    vc = ViewClient(device, serialno)

    img = np.array(device.takeSnapshot())
    plt.imshow(img)

    views_dict = vc.getViewsById()
    # clickables = filter(lambda v: v.getClickable(), views_dict.values())
    # views = clickables
    views = views_dict.values()

    for v in views:
        min_c, max_c = v.getBounds()
        draw_rect(min_c, max_c, style="r--", linewidth=1)
        plt.annotate(v.getId().split("/")[-1] if len(v.getId()) > 0 else "\"empty\"", xy=v.getCenter(),
            horizontalalignment="center", verticalalignment="center", color="b", size=2.5)

    plt.gca().get_xaxis().set_visible(False)
    plt.gca().get_yaxis().set_visible(False)
    plt.savefig(output_path, bbox_inches="tight", pad_inches=0, dpi=300)

    pass    
Esempio n. 48
0
def run(num_iter=1):
    # initail componet
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    if PLATFORM == WINDOWS:
        os.system("mkdir {}/{} ".format(ROOT_DIR, REPORT_DIR))
    elif PLATFORM == LINUX:
        os.system("mkdir -p {}/{} ".format(ROOT_DIR, REPORT_DIR))

    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    wake_device(device, serialno)

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    device.press("HOME")
    time.sleep(0.5)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += record_task_run(device,
                                        serialno,
                                        num_iter=min([num_iter, BATCH_SIZE]))
        #trials_batch += recordHD_task_run(device, serialno, num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += record_VoiceRecord_run(device,
                                               serialno,
                                               num_iter=min(
                                                   [num_iter, BATCH_SIZE]))

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch
        with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        num_iter -= BATCH_SIZE
        batch_count += 1

    device.press("HOME")

    AudioFunction.finalize()
    Logger.finalize()
Esempio n. 49
0
 def startInstagram(self):
     package = 'com.instagram.android'
     activity = '.activity.MainTabActivity'
     component = package + "/" + activity
     device, serialno = ViewClient.connectToDeviceOrExit()
     device.startActivity(component=component)
     self.vc.sleep(5)
     try:
         self.vc.uiAutomatorHelper.findObject(
             bySelector=
             'desc@Home,[email protected],text@$,[email protected]'
         ).clickAndWait(eventCondition='until:newWindow', timeout=4000)
     except (RuntimeError, AttributeError) as e:
         pass
     self.vc.sleep(5)
Esempio n. 50
0
    def unlock_device_old(self, udid):
        print 'hello' + udid
        self.device_udid = udid

        print self.device_udid
        #device, serialno = ViewClient.connectToDeviceOrExit(5,self.device_udid)
        device, serialno = ViewClient.connectToDeviceOrExit(
            serialno=self.device_udid)
        if device.isLocked():
            device.wake()
            device.unlock()

        else:
            device.wake()
            device.unlock()
Esempio n. 51
0
def control_MT_phone(device, serialno):
    time.sleep(3)
    timeout = 0
    while timeout < 10:
        timeout += 1
        log("detect phone {}".format(timeout))
        vc = ViewClient(device, serialno)
        answer_id = get_answer_id(vc)
        if answer_id == None:
            time.sleep(1)
            continue
        control_Btn(vc, answer_id)
        return True

    return False
Esempio n. 52
0
def control_MT_phone(device, serialno):
    timeout = 60
    log("start detecting phone call in 60 secs")
    while timeout > 0:
        timeout -= 5
        log("detect phone call comming... {}".format(timeout))
        vc = ViewClient(device, serialno)
        answer_id = get_answer_id(vc)
        if answer_id == None:
            time.sleep(1)
            continue
        control_Btn(vc, answer_id)
        return True

    return False
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)
Esempio n. 54
0
 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'
Esempio n. 55
0
def run(num_iter=1):
    # initail componet
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    os.system("mkdir -p {}/ssr_report > /dev/null".format(ROOT_DIR))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    package = "com.htc.audiofunctionsdemo"
    activity = ".activities.MainActivity"
    component = package + "/" + activity

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    wake_device(device, serialno)
    #push_files_if_needed(serialno)

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py

    device.press("HOME")
    #time.sleep(1)
    #push_files_if_needed(serialno)
    time.sleep(1)

    #device.startActivity(component=component)
    #time.sleep(1)

    for i in range(1):
        #swith_effect_ui(device, serialno)
        #device.press("HOME")
        playback_task_run(device, num_iter=num_iter)
        #AATApp.playback_nonoffload(device, "pop.wav")
        #time.sleep(5)
        #device.press("HOME")
        #playback_task2_run(device, num_iter=num_iter)
        #device.press("HOME")
        #control_GoogleMusic(device, serialno, num_iter=num_iter)

    AudioFunction.finalize()
    Logger.finalize()
Esempio n. 56
0
def wake_device(device, serialno):
    if device.isScreenOn():
        return

    device.wake()
    vc = ViewClient(device, serialno, autodump=False)
    try:
        vc.dump(sleep=0)
        so = sio.StringIO()
        vc.traverse(stream=so)

        if "lockscreen" in so.getvalue():
            device.unlock()
    except:
        pass
Esempio n. 57
0
 def get(self):
     return_dict = {}
     apk = self.parser.parse_args()['name']
     app_path = "apps/" + apk
     return_dict['apk_used'] = app_path
     device, serialno = ViewClient.connectToDeviceOrExit(verbose=True)
     uninstallApp(app_path, device, serialno)
     install_error = installApp(app_path, device, serialno)
     running_error = runInstalledApp(app_path, device, serialno)
     time.sleep(5)
     screenshot_name = apk + "_" + str(time.time())
     screenshot_error = takeScreenshot(device, screenshot_name)
     if (not screenshot_error):
         return_dict[
             'screenshot_status'] = "Screenshot taken and saved as " + screenshot_name
     else:
         return_dict['screenshot_status'] = "Error while taking screenshot"
     return_dict[
         'installation_status'] = "Success" if not install_error else "Error"
     return_dict[
         'running_status'] = "Success" if not running_error else "Error"
     return return_dict, 200
 def dump_view_server(package):
     kwargs1 = {VERBOSE: False, 'ignoresecuredevice': False, 'ignoreversioncheck': False}
     kwargs2 = {ViewClientOptions.FORCE_VIEW_SERVER_USE: False, ViewClientOptions.START_VIEW_SERVER: True,
                ViewClientOptions.AUTO_DUMP: False, ViewClientOptions.IGNORE_UIAUTOMATOR_KILLED: True,
                ViewClientOptions.COMPRESSED_DUMP: True,
                ViewClientOptions.USE_UIAUTOMATOR_HELPER: False,
                ViewClientOptions.DEBUG: {},
                }
     kwargs2[ViewClientOptions.FORCE_VIEW_SERVER_USE] = True
     vc = ViewClient(*ViewClient.connectToDeviceOrExit(**kwargs1), **kwargs2)
     options = {WINDOW: -1, SAVE_SCREENSHOT: None, SAVE_VIEW_SCREENSHOTS: None, DO_NOT_DUMP_VIEWS: False,
                DEVICE_ART: None, DROP_SHADOW: False, SCREEN_GLARE: False}
     windows = vc.list()
     print windows
     transform = MAP['b']
     for window in windows:
         if package not in windows[window]:
             continue
         print windows[window]
         vc.dump(window=int(window))
         # ViewClient.imageDirectory = options[SAVE_VIEW_SCREENSHOTS]
         return ViewClientHandler.traverse(vc, transform=transform)
Esempio n. 59
0
#! /usr/bin/env python2.7

'''
Copyright (C) 2012  Diego Torres Milano
Created on Feb 5, 2012

@author: diego
'''

import sys
import os
import unittest

# PyDev sets PYTHONPATH, use it
if 'PYTHONPATH' in os.environ:
    for p in os.environ['PYTHONPATH'].split(':'):
        if not p in sys.path:
            sys.path.append(p)
try:
    sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
    pass

from com.dtmilano.android.viewclient import View, TextView, EditText, ViewClient


# Script gets stuck on ViewClient(device, serial) #243
d, s = ViewClient.connectToDeviceOrExit()
input('\n** Disconnect the device now and press <ENTER>')
device = ViewClient(d, s)
Esempio n. 60
0
LONG_OPTS =  [HELP, VERBOSE, IGNORE_SECURE_DEVICE, FORCE_VIEW_SERVER_USE, DO_NOT_START_VIEW_SERVER]

def usage(exitVal=1):
    print >> sys.stderr, 'usage: list.py [-H|--%s] [-V|--%s] [-I|--%s] [-F|--%s] [-S|--%s] [serialno]' % \
        tuple(LONG_OPTS)
    sys.exit(exitVal)

try:
    opts, args = getopt.getopt(sys.argv[1:], SHORT_OPTS, LONG_OPTS)
except getopt.GetoptError, e:
    print >>sys.stderr, 'ERROR:', str(e)
    usage()

kwargs1 = {VERBOSE: False, 'ignoresecuredevice': False}
# We force viewserver use by default
kwargs2 = {'forceviewserveruse': True, 'startviewserver': True, 'autodump': False}
for o, a in opts:
    o = o.strip('-')
    if o in ['H', HELP]:
        usage(0)
    elif o in ['V', VERBOSE]:
        kwargs1[VERBOSE] = True
    elif o in ['I', IGNORE_SECURE_DEVICE]:
        kwargs1['ignoresecuredevice'] = True
    elif o in ['F', FORCE_VIEW_SERVER_USE]:
        kwargs2['forceviewserveruse'] = True
    elif o in ['S', DO_NOT_START_VIEW_SERVER]:
        kwargs2['startviewserver'] = False

print ViewClient(*ViewClient.connectToDeviceOrExit(**kwargs1), **kwargs2).list()