Beispiel #1
0
    def __init__(self, insert_sleeps=True):
        print("Waiting for device")
        self.device = MonkeyRunner.waitForConnection()
        self.easyDevice = EasyMonkeyDevice(self.device)
        self.insert_sleeps = insert_sleeps
        self.device.press('KEYCODE_HOME', MonkeyDevice.DOWN_AND_UP)
        kill_command = 'am force-stop %s' % DeviceHandler.package
        self.device.shell(kill_command)
        self.insert_sleep(time=3)
        self.err_snapshot_count = 0

        apk_path = self.device.shell('pm path ' + DeviceHandler.package)
        if apk_path.startswith('package:'):
            print "BeeeOn already installed,but I am gonna reinstall it to test the newest version"
            self.device.installPackage(DeviceHandler.apk_path)
        else:
            print "BeeeOn not installed, installing APKs..."
            self.device.installPackage(DeviceHandler.apk_path)

        # sets the name of the component to start
        runComponent = DeviceHandler.package + '/' + DeviceHandler.main_activity

        print("Starting activity " + runComponent)

        # Runs the component
        self.device.startActivity(component=runComponent)
        self.insert_sleep()
Beispiel #2
0
class MonkeyWrapImpl():
    def waitForConnection(self):
        self.device = MonkeyRunner.waitForConnection()
        self.initEasyDevice()

    def startActivity(self, runComponent):
        self.device.startActivity(component=runComponent)

    def initEasyDevice(self):
        self.easyDevice = EasyMonkeyDevice(self.device)

    def touchByViewId(self, viewId):
        self.easyDevice.touch(By.id(viewId), MonkeyDevice.DOWN_AND_UP)

    def visible(self, viewId):
        self.easyDevice.visible(By.id(viewId))

    def touch_down(self, x, y):
        self.device.touch(x, y, MonkeyDevice.DOWN)

    def touch_up(self, x, y):
        self.device.touch(x, y, MonkeyDevice.UP)

    def touch_down_and_up(self, x, y):
        self.device.touch(x, y, MonkeyDevice.DOWN_AND_UP)

    def press_menu_down_and_up(self):
        self.device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)

    def press_power_down_and_up(self):
        self.device.press('KEYCODE_POWER', MonkeyDevice.DOWN_AND_UP)

    def drag(self, sx, sy, ex, ey, duration, steps):
        self.device.drag((sx, sy), (ex, ey), duration, steps)

    def wakeup(self):
        self.device.wake()

    def sleep(self, sec):
        MonkeyRunner.sleep(sec)

    def takeAndSaveSnapshot(self, savaPath, type):
        img = self.device.takeSnapshot()
        img.writeToFile(savaPath, type)

    def screenWidth(self):
        #        w = self.device.getProperty('width')
        #        print('width=' + w)
        #        return w;
        return 720

    def screenHeight(self):
        #        h = self.device.getProperty('height')
        #        return h;
        return 1280

    def __init__(self):
        '''
Beispiel #3
0
 def __init__(self, logger, monkey_runner_impl):
     self.easy_device = EasyMonkeyDevice(monkey_runner_impl.device)
     self.action_type_dict = {
         "DOWN_AND_UP": MonkeyDevice.DOWN_AND_UP,
         "DOWN": MonkeyDevice.DOWN,
         "UP": MonkeyDevice.UP
     }
     self.class_name = "EasyDevice"
     self.m_logger = logger
Beispiel #4
0
 def __init__(self, apk, package, mainActivity, runActivity, bundle):
     # Connects to the current device, returning a MonkeyDevice object
     self.device = MonkeyRunner.waitForConnection()
     self.easy_device = EasyMonkeyDevice(self.device)
     self.apk = apk
     self.package = package
     self.bundle = bundle
     self.main = self.component(package, mainActivity)
     self.run = self.component(package, runActivity)
Beispiel #5
0
 def __init__(self, emulatorname, switch=PHONE_EMULATOR_SWITCH):
     device = self.waitforconnection(waitForConnectionTime, emulatorname)
     self.debug(
         "__int__: creating the finemonkeyrunner object with emulatorname %s"
         % emulatorname)
     # use EasyMonkeyDevice and MonkeyDevice
     self.easydevice = EasyMonkeyDevice(device)
     self.device = device
     # presskey type
     self.DOWN = self.device.DOWN
     self.UP = self.device.UP
     self.DOWN_AND_UP = self.device.DOWN_AND_UP
     self.switch = switch
     self.debug('created the fineEasyDevice')
     self.viewlist = []
Beispiel #6
0
 def __init__(self, deviceId):
     device = MonkeyRunner.waitForConnection(10, deviceId)
     self.debug(
         "__int__: creating the wrap easy monkey object with deviceid %s" %
         deviceId)
     self.deviceId = deviceId
     self.easyDevice = EasyMonkeyDevice(device)
     self.device = device
     #self.DOWN = TouchPressType.DOWN.getIdentifier()
     #self.UP = TouchPressType.UP.getIdentifier()
     #self.DOWN_AND_UP = TouchPressType.DOWN_AND_UP.getIdentifier()
     self.DOWN = self.device.DOWN
     self.UP = self.device.UP
     self.DOWN_AND_UP = self.device.DOWN_AND_UP
     self.caseManager = testCaseManager(self)
     self.debug('created the wrapEasyDevice')
 def __init__(self, logger, monkey_runner_impl):
     self.easy_device = EasyMonkeyDevice(monkey_runner_impl.device)
     self.action_type_dict = {"DOWN_AND_UP": MonkeyDevice.DOWN_AND_UP,
                              "DOWN": MonkeyDevice.DOWN,
                              "UP": MonkeyDevice.UP}
     self.class_name = "EasyDevice"
     self.m_logger = logger
Beispiel #8
0
class MonkeyWrapImpl():
    def waitForConnection(self):
        self.device = MonkeyRunner.waitForConnection()
        self.initEasyDevice()
    def startActivity(self,runComponent):
        self.device.startActivity(component=runComponent)
        
    def initEasyDevice(self):
        self.easyDevice = EasyMonkeyDevice(self.device);
    def touchByViewId(self,viewId):
        self.easyDevice.touch(By.id(viewId),MonkeyDevice.DOWN_AND_UP)
    def visible(self,viewId):
        self.easyDevice.visible(By.id(viewId))
            
    def touch_down(self,x,y):
        self.device.touch(x,y,MonkeyDevice.DOWN)
    def touch_up(self,x,y):
        self.device.touch(x,y,MonkeyDevice.UP)
    def touch_down_and_up(self,x,y):
        self.device.touch(x,y,MonkeyDevice.DOWN_AND_UP)
        
    def press_menu_down_and_up(self):
        self.device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
    def press_power_down_and_up(self):
        self.device.press('KEYCODE_POWER', MonkeyDevice.DOWN_AND_UP)
        
    def drag(self,sx,sy,ex,ey,duration,steps):
        self.device.drag((sx,sy),(ex,ey),duration,steps);
    def wakeup(self):
        self.device.wake()
    def sleep(self,sec):
        MonkeyRunner.sleep(sec);
    def takeAndSaveSnapshot(self,savaPath,type):
        img = self.device.takeSnapshot()
        img.writeToFile(savaPath,type)
    def screenWidth(self):
#        w = self.device.getProperty('width')
#        print('width=' + w)
#        return w;
        return 720; 
    def screenHeight(self):
#        h = self.device.getProperty('height')
#        return h;
        return 1280;
   
    def __init__(self):
        '''
Beispiel #9
0
class DeviceHandler():
    package = 'com.rehivetech.beeeon.debug'
    main_activity = 'com.rehivetech.beeeon.gui.activity.LoginActivity'
    apk_path = '../../../artifacts/app-debug.apk'

    def __init__(self, insert_sleeps=True):
        print("Waiting for device")
        self.device = MonkeyRunner.waitForConnection()
        self.easyDevice = EasyMonkeyDevice(self.device)
        self.insert_sleeps = insert_sleeps
        self.device.press('KEYCODE_HOME', MonkeyDevice.DOWN_AND_UP)
        kill_command = 'am force-stop %s' % DeviceHandler.package
        self.device.shell(kill_command)
        self.insert_sleep(time=3)
        self.err_snapshot_count = 0

        apk_path = self.device.shell('pm path ' + DeviceHandler.package)
        if apk_path.startswith('package:'):
            print "BeeeOn already installed,but I am gonna reinstall it to test the newest version"
            self.device.installPackage(DeviceHandler.apk_path)
        else:
            print "BeeeOn not installed, installing APKs..."
            self.device.installPackage(DeviceHandler.apk_path)

        # sets the name of the component to start
        runComponent = DeviceHandler.package + '/' + DeviceHandler.main_activity

        print("Starting activity " + runComponent)

        # Runs the component
        self.device.startActivity(component=runComponent)
        self.insert_sleep()

    def insert_sleep(self, time=3):
        if self.insert_sleep:
            MonkeyRunner.sleep(time)

    def press_button(self, id):
        try:
            self.easyDevice.touch(By.id('id/' + id), MonkeyDevice.DOWN_AND_UP)
            self.insert_sleep()
        except Exception, e:
            print('Button was not found,saving snapshot of the screen')
            self.save_snapshot(
                'button_not_found' + str(self.err_snapshot_count), 'png')
            self.err_snapshot_count += 1
            raise e
Beispiel #10
0
def close_vivo_ad():
    signal.signal(signal.SIGINT, exitGracefully)
    global t_ad_event

    while 1:

        try:

            if hViewer.getFocusedWindowName(
            ) == 'com.vivo.sdkplugin/com.vivo.unionsdk.ui.UnionActivity' and (
                    hViewer.visible(
                        hViewer.findViewById(
                            'id/vivo_acts_mutitxt_dialog_close'))
                    or hViewer.visible(
                        hViewer.findViewById(
                            'id/vivo_acts_singletxt_dialog_close'))):
                ESC_key()
                print('close ad success')
                t_ad_event.set()
                continue

            if hViewer.getFocusedWindowName(
            ) == 'com.vivo.sdkplugin/com.vivo.unionsdk.ui.UnionActivity' and hViewer.visible(
                    hViewer.findViewById(
                        'id/vivo_app_exit_dialog_txt_layout')):
                ESC_key()
                print('close esc success')
                continue

            if hViewer.getFocusedWindowName(
            ) == 'com.vivo.sdkplugin/com.vivo.unionsdk.ui.UnionActivity' and hViewer.visible(
                    hViewer.findViewById('id/vivo_title_bar')):
                ESC_key()
                print('close esc success')
                continue
        except:

            print('close_vivo_ad  error ')
            global device
            global eDevice
            global hViewer
            print('error 1')

            print('errror 100')
            device.shell('killall com.android.commands.monkey')
            device = mr.waitForConnection()
            if not device:
                print("Please connect a device to start!")

            else:
                print("Device Connected successfully!")
            print('error 2')
            eDevice = EasyMonkeyDevice(device)
            print('error 3')
            hViewer = device.getHierarchyViewer()
            print('error 4')

            continue
Beispiel #11
0
 def monkey_set_up(self):
     print '------------ monkey_set_up -------------'
     self.device = MonkeyRunner.waitForConnection(5, self.qq['deviceid'])
     self.easy_device = EasyMonkeyDevice(self.device)
     sleep(0.5)
     if not self.device or not self.easy_device:
         print "Error : monkey_set_up failed !"
         sys.exit(-1)
     return 0
Beispiel #12
0
class MyMonkeyRunner:
    idSearchStr = 'id/top_view_search'
    idMainBarStr = 'id/main_bar'

    def getDevice(self):
        self.dev = MonkeyRunner.waitForConnection()
        return self.dev

    def getEasyDevice(self, dev):
        self.eDevice = EasyMonkeyDevice(dev)
        return self.eDevice

    def getHierarchyViewer(self):
        self.hDevice = self.dev.getHierarchyViewer()
        return self.hDevice

    def touchByID(self, id):
        self.eDevice.touch(By.id(id), MonkeyDevice.DOWN_AND_UP)
Beispiel #13
0
def main():
    # Connects to the current device, returning a MonkeyDevice object
    device = MonkeyRunner.waitForConnection()
    easy_device = EasyMonkeyDevice(device)

    # sets a variable with the package's internal name
    package = 'org.vhack.dev.vhack'

    # sets a variable with the name of an Activity in the package
    activity = 'org.vhack.dev.vhack.SplashActivity'

    # sets the name of the component to start
    runComponent = package + '/' + activity

    # Runs the component
    device.startActivity(component=runComponent)

    ips = get_ips(0)
    time.sleep(3)
    print 'Start Playing........'

    easy_device.touch(By.id('id/btnNetwork'), MonkeyDevice.DOWN_AND_UP)
    time.sleep(1.5)

    for ip in ips:
        for i in xrange(15):
            device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP)
        device.type(ip.strip())
        easy_device.touch(By.id('id/btnScanIP'), MonkeyDevice.DOWN_AND_UP)
        output = 1
        print '[+] Scanning %s' % ip.strip()
        while output:
            time.sleep(3)
            # Takes a screenshot
            result = device.takeSnapshot()

            # Writes the screenshot to a file
            result.writeToFile('./screen.png', 'png')

            ocr_res = ocr().strip()
            if ocr_res == 'Attack':
                output = 0
                easy_device.touch(By.id('id/btnTransferIP'), MonkeyDevice.DOWN_AND_UP)
                print '[#] Attacking Target'
                time.sleep(2)
            elif ocr_res == 'Pass':
                output = 0
                print '[-] Pass Target'
            elif ocr_res == 'Wait':
                print '[!] Waiting'
            else:
                output = 0
                print 'Unknown'
Beispiel #14
0
def mr_test_demo_for_easydevice():
    print 'test apis for easydevice.'
    
    device = get_monkey_device()
    easy_device = EasyMonkeyDevice(device)
    
    # launcher home page
#     device.press('KEYCODE_HOME')
#     mr.sleep(1)
#     easy_device.touch(By.id('id/title'), MonkeyDevice.DOWN_AND_UP)
#     mr.sleep(1)
#     device.press('KEYCODE_ENTER')
#     mr.sleep(5)
    
    # film list page
#     tab_title_text = easy_device.getText(By.id('id/tab_title'))
#     print tab_title_text.encode('utf8')

    # touch on card of right area
    easy_device.touch(By.id('id/subtitle'), MonkeyDevice.DOWN_AND_UP)
    mr.sleep(1)
def testlogin():  
    import codecs  
    codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)  
  
    device = MonkeyRunner.waitForConnection()  
    easyMonkey = EasyMonkeyDevice(device)  
  
    print ("Test start")  
    # 启动应用Activity
    device.shell('am start dong.sqlite.order/dong.sqlite.order.MainActivity')  
  
    MonkeyRunner.sleep(3)  
  
    # 输入账号
    print ("Start typing user name and password")
    by_name = By.id("id/username")
    easyMonkey.type(by_name,'zdd')  
    MonkeyRunner.sleep(1)  
    # 输入密码
    by_psd = By.id('id/userpwd')
    easyMonkey.type(by_psd,"my_psd")  
    MonkeyRunner.sleep(1)  
    device.press('KEYCODE_BACK')  
    MonkeyRunner.sleep(1)  
    # 点击登录
    by_save = By.id('id/btn_save')  
    easyMonkey.touch(by_save,MonkeyDevice.DOWN_AND_UP)  
    MonkeyRunner.sleep(2)

    print ("Click the read button")
    by_read = By.id('id/btn_read') 
    easyMonkey.touch(by_read,MonkeyDevice.DOWN_AND_UP)  
    MonkeyRunner.sleep(1) 
  
    device.press('KEYCODE_BACK')
    print ("Test end")
Beispiel #16
0
def main():
    apk = sys.argv[1]
    package = sys.argv[2]
    instructions_file = sys.argv[3]
    print(instructions_file)
    print('Checking adb devices')
    devices = get_devices()
    print('Devices found: '+str(devices))
    if not len(devices):
        print('No devices found, setting up emulator')
        run_emulator()
        print('Emulator boot completed.. proceding..')

    device = MonkeyRunner.waitForConnection()
    easy_device = EasyMonkeyDevice(device)
    print('Connected\nInstalling package..')
    device.installPackage(apk)
    print('Installed!')
    print('Checking all activities..\nThis may take a while..')
    f = open(instructions_file, 'r')
    instructions = json.load(f)
    for activity in instructions:
        print(activity)
        runComponent = package + '/' + activity
        for button in instructions[activity]:
            device.startActivity(component=runComponent)
            time.sleep(1)
            if easy_device.visible(By.id('id/'+button)):
                easy_device.touch(By.id('id/'+button), MonkeyDevice.DOWN_AND_UP)
                time.sleep(1)
            else:
                device.press("KEYCODE_BACK", MonkeyDevice.DOWN_AND_UP)
                time.sleep(1)
                if easy_device.visible(By.id('id/'+button)):
                    easy_device.touch(By.id('id/'+button), MonkeyDevice.DOWN_AND_UP)

        result = device.takeSnapshot()
        result_path = os.path.join(os.path.abspath('monkeyresult/'), package)
        if not os.path.exists(result_path):
            os.makedirs(result_path)
        result.writeToFile(
            os.path.join(result_path, activity+'.png'),
            'png'
            )
    f.close()
    print('Saved some snapshots to\n'+result_path)
Beispiel #17
0
 def monkey_set_up(self):
     print '------------ monkey_set_up -------------'
     devices = os.popen('adb devices').read().strip().split('\n')[1:]
     global deviceid
     deviceid = ''
     if self.role == 'A' or self.role == 'a':
         deviceid = devices[0].split('\t')[0]
     if self.role == 'B' or self.role == 'b':
         deviceid = devices[1].split('\t')[0]
     self.device = MonkeyRunner.waitForConnection(5, deviceid)
     self.easy_device = EasyMonkeyDevice(self.device)
     sleep(0.5)
     if not self.device or not self.easy_device:
         print "Error : monkey_set_up failed !"
         sys.exit(-1)
     return 0
Beispiel #18
0
 def _connect_device(self, device, is_restart=False):
     """connect_device(device_id) -> MonkeyDevice
     
     Connect a device according to device ID.
     argv: (boolean)is_restart -- whether need restart view server before connect
     author:Zhihao.Gu
     """
     logger.debug("Device ID is " + device)
     device = MonkeyRunner.waitForConnection(5, device)
     if device is None:
         logger.critical("Cannot connect device.")
         raise RuntimeError("Cannot connect %s device." % device)
     if is_restart:
         self._restart_viewserver(device)
     easy_device = EasyMonkeyDevice(device)
     hierarchyviewer = device.getHierarchyViewer()
     return (device, easy_device, hierarchyviewer)
Beispiel #19
0
    def WaitForConnection(cls):
        print """
        
Connecting the device...

Please check blow, if without an connection in long time:

1. USB-debug model is enabled

2. Device driver is installed

"""
        p_m_env.DEVICE = MonkeyRunner.waitForConnection()
        #命令:  adb wait-for-device
        print "connect ok"
        p_m_env.EASY_DEVICE = EasyMonkeyDevice(p_m_env.DEVICE)
        print "connect easy ok"
        p_m_env.HIERARCHY = p_m_env.DEVICE.getHierarchyViewer()
        print "connect hierarchy ok"
class EasyDevice():
    def __init__(self, logger, monkey_runner_impl):
        self.easy_device = EasyMonkeyDevice(monkey_runner_impl.device)
        self.action_type_dict = {"DOWN_AND_UP": MonkeyDevice.DOWN_AND_UP,
                                 "DOWN": MonkeyDevice.DOWN,
                                 "UP": MonkeyDevice.UP}
        self.class_name = "EasyDevice"
        self.m_logger = logger

#------------------------------------------------------------------------------ 
# special functions:
#------------------------------------------------------------------------------ 
    def getFocusedWindowClassName(self):
        try:
            return self.easy_device.getFocusedWindowId()
        except Exception, e:
            msg = "[%s] Failed to get focused window class name: [%s]" %(self.class_name, str(e))
            self.m_logger.error(msg)
            return None
Beispiel #21
0
def change_user_info():
    global t_ad_event
    signal.signal(signal.SIGINT, exitGracefully)
    while 1:
        try:
            if t_ad_event.isSet():
                device.touch(1238, 560, 'DOWN_AND_UP')  #点击切换账号

                if hViewer.getFocusedWindowName(
                ) == 'com.vivo.sdkplugin/com.vivo.unionsdk.ui.UnionActivity' and hViewer.visible(
                        hViewer.findViewById('id/vivo_login_loading_switch')):
                    device.touch(640, 415, 'DOWN_AND_UP')

                if hViewer.getFocusedWindowName(
                ) == 'com.vivo.sdkplugin/com.vivo.unionsdk.ui.UnionActivity' and hViewer.visible(
                        hViewer.findViewById('id/sublist_account_exit')):
                    print(333333)
                    break

        except:
            print('change_user_info  error ')
            global device
            global eDevice
            global hViewer
            print('error 1')

            print('errror 100')
            device.shell('killall com.android.commands.monkey')
            device = mr.waitForConnection()
            if not device:
                print("Please connect a device to start!")

            else:
                print("Device Connected successfully!")
            print('error 2')
            eDevice = EasyMonkeyDevice(device)
            print('error 3')
            hViewer = device.getHierarchyViewer()
            print('error 4')

            continue
Beispiel #22
0
 def __connect(self):
     try:
         self.md = MonkeyRunner.waitForConnection(timeout=CONNECT_TIMEOUT, deviceId=self.deviceId)
         #print 'Connected.'
         if self.md is None:
             printLog(self.threadName+'[AndroidDevice] Device NOT connected...', logging.ERROR)
             return
         # get phone's screen resolution, once connected, it is fixed
         self.scn_width=int(self.md.getProperty('display.width'))
         self.scn_height=int(self.md.getProperty('display.height'))
         printLog(self.threadName+"[AndroidDevice] Device %s's screen resolution is: %d * %d" % (self.deviceId, self.scn_width, self.scn_height), logging.INFO)
         self.md.wake()
         printLog(self.threadName+'[AndroidDevice] Creating Hierarchy Viewer... ')
         self.hv=self.md.getHierarchyViewer()
         printLog(self.threadName+'[AndroidDevice] Creating easy device... ')
         self.ed = EasyMonkeyDevice(self.md)
         printLog(self.threadName+'[AndroidDevice] Device %s connected.' % self.deviceId, logging.INFO)
         self.resultFlag=True
     except java.lang.NullPointerException, e:
         printLog(self.threadName+'[AndroidDevice] CANNOT access device %s. Please check the USB cable and reconnect the device.' % self.deviceId, logging.ERROR)
         return
Beispiel #23
0
def exitGracefully(signum, frame):
    global eDevice
    global hViewer
    global device
    signal.signal(signal.SIGINT, signal.getsignal(signal.SIGINT))
    device.shell('killall com.android.commands.monkey')
    print(333)

    print('exitGracefully  error ')
    device = mr.waitForConnection()
    if not device:
        print("Please connect a device to start!")

    else:
        print("Device Connected successfully!")
    print('error 1')

    print('errror 100')
    print('error 2')
    eDevice = EasyMonkeyDevice(device)
    print('error 3')
    hViewer = device.getHierarchyViewer()
    print('error 4')
    print('exitGracefully  error ')
Beispiel #24
0
class EasyDevice():
    def __init__(self, logger, monkey_runner_impl):
        self.easy_device = EasyMonkeyDevice(monkey_runner_impl.device)
        self.action_type_dict = {
            "DOWN_AND_UP": MonkeyDevice.DOWN_AND_UP,
            "DOWN": MonkeyDevice.DOWN,
            "UP": MonkeyDevice.UP
        }
        self.class_name = "EasyDevice"
        self.m_logger = logger


#------------------------------------------------------------------------------
# special functions:
#------------------------------------------------------------------------------

    def getFocusedWindowClassName(self):
        try:
            return self.easy_device.getFocusedWindowId()
        except Exception, e:
            msg = "[%s] Failed to get focused window class name: [%s]" % (
                self.class_name, str(e))
            self.m_logger.error(msg)
            return None
Beispiel #25
0
#Import class of MonkeyRunner, MonkeyDevice, and MonkeyImage.
import os, sys
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By




if __name__ == '__main__':

    device1 = MonkeyRunner.waitForConnection()
    easy_device = EasyMonkeyDevice(device1)
    print 'connected device success..'
    
    # test config
    image_loops = 1
    wait_app_launch = 9
    wait_cmd_time = 3
    wait_video_rec_time = 7
    
    #width = device1.getProperty('display.width')
    #if int(str(width)) == 720:
    #    play_camera_video = (360, 670)
    #    save_capture_pic = (400, 600)
    #else:
    #    print('Error screen size not support..')
    #    sys.exit()
    
    print '==========================================='
Beispiel #26
0
# Vision: V1.1
# Author: Findyou
# Time: 2013.12.03
# Imports the monkeyrunner modules used by this program 
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice, By
import time,sys

# Get the current path
path = sys.path[0]
path = path.replace('\\','/')
path = path[path.rfind(":")-1:]

# Connects to the current device, returning a MonkeyDevice object 
device = MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device) 

# Runs the component
easy_device.startActivity(component='cn.richinfo.thinkdrive/.ui.activities.NavigateActivity')

def take_Snapshot():
	# sleep 3's
	MonkeyRunner.sleep(3)
	c_time = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
	# Takes a screenshot 
	result = device.takeSnapshot()
	# Writes the screenshot to a file 
	result.writeToFile(path + "/Test09_" +c_time + ".png",'png')

def system_back():
	# sleep 3's
Beispiel #27
0
#!/usr/bin/python  
#encoding:utf-8
#encoding=gbk


'''
Created on 2014年11月11日

@author: EnphoneH
'''

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
from com.android.chimpchat.hierarchyviewer import HierarchyViewer


device = MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device)  #init easymonkeydevice object must start activity at first.Because the init method
hierarchyviewer = device.getHierarchyViewer()
#menu = hierarchyviewer.findViewByid('id/Menu_button')

for j in range(0,10000):
    easy_device.touch(By.id('id/Menu_button'),MonkeyDevice.DOWN_AND_UP)
    print("点击:" + str(j) + "次")
    MonkeyRunner.sleep(3)
Beispiel #28
0
__author__ = 'Lambert Liu'
#Imports the monkeyrunner modules used by this program
import os;
from subprocess import Popen
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.MonkeyDevice import takeSnapshot
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
from com.android.chimpchat.hierarchyviewer import HierarchyViewer
from com.android.monkeyrunner import MonkeyView
import random

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
easy_device=EasyMonkeyDevice(device)
# Installs the Android package. Notice that this method returns a boolean, so you can test
# to see if the installation worked.
easy_device.installPackage('CircleAreaV1D0/bin/CircleAreaV1D0.apk')

package = 'com.example.circlearea'

# Sets the monkey adb command

command = "adb shell monkey -p " + package + " -v " + str(numberOfRandomEvents)
platformToolsPath = "C:\Kala\Android-Essential-Software-Packages\adt-bundle-windows-x86\adt-bundle-windows-x86\sdk\platform-tools"


process= Popen([platformToolsPath + command], shell=True)


# Set the initial count
Beispiel #29
0
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By

device = MonkeyRunner.waitForConnection()

device.startActivity(component="com.tencent.mobileqq/.activity.SplashActivity")

easy_device = EasyMonkeyDevice(device)

device.press('KEYCODE_DPAD_DOWN', 'DOWN_AND_UP')

MonkeyRunner.sleep(3)  # (this is very import)

easy_device.touch(By.id('id/btn_login'), MonkeyDevice.DOWN_AND_UP)

device.touch(120, 397, 'DOWN_AND_UP')

device.type('893026750')

# easy_device.touch(By.id('id/password'), MonkeyDevice.DOWN_AND_UP)
#
# device.type('hongnaiwu3425')
#
# easy_device.touch(By.id('id/login'), MonkeyDevice.DOWN_AND_UP)
#
# device.press('KEYCODE_BACK','DOWN_AND_UP')
Beispiel #30
0
 def initEasyDevice(self):
     self.easyDevice = EasyMonkeyDevice(self.device)
Beispiel #31
0
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
# --------------------------------------------------------------------- #

# how much to wait between two actions
pause = 1

# connect to the device
device = MonkeyRunner.waitForConnection()

# start zerowins
device.startActivity(component="edu.osu.zerowins/.MainActivity")

# use the EasyMonkey API
easyDevice = EasyMonkeyDevice(device)

# fetch all relevant GUI components
editGuess = By.id('id/editGuess')
if not editGuess:
    raise Exception("View id/editGuess not found")

txtPlayer = By.id('id/txtPlayer')
if not editGuess:
    raise Exception("View id/txtPlayer not found")

btnPost = By.id('id/btnPost')
if not btnPost:
    raise Exception("View id/btnPost not found")

txtNumber = By.id('id/txtNumber')
Beispiel #32
0
# Vision: V1.1
# Author: Findyou
# Time: 2013.12.03
# Imports the monkeyrunner modules used by this program 
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice, By
import time,sys

# Get the current path
path = sys.path[0]
path = path.replace('\\','/')
path = path[path.rfind(":")-1:]

# Connects to the current device, returning a MonkeyDevice object 
device = MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device) 

# Runs the component
easy_device.startActivity(component='cn.richinfo.thinkdrive/.ui.activities.NavigateActivity')

def take_Snapshot():
	# sleep 3's
	MonkeyRunner.sleep(3)
	c_time = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
	# Takes a screenshot 
	result = device.takeSnapshot()
	# Writes the screenshot to a file 
	result.writeToFile(path + "/Test07_" + c_time + ".png",'png')

def right_drag():
	# Right drag ->System menu
Beispiel #33
0
 def getEasyDevice(self, dev):
     self.eDevice = EasyMonkeyDevice(dev)
     return self.eDevice
Beispiel #34
0
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By





if __name__ == '__main__':
    
    
    device1 = MonkeyRunner.waitForConnection()
    
    # Use the EasyMonkey API, all methods on device are available
    # in easy_device.
    MonkeyRunner.sleep(2);
    easy_device = EasyMonkeyDevice(device1)
    print 'Connected Device!'
    
    
    # init param
    wait_app_launch = 3
    wait_button_time = 1
    wait_cmd_time = 2
    test_vt_time = 20
        
    MonkeyRunner.sleep(wait_cmd_time);
    
    # launch VT working app
    print 'Launch Engineering Working Menu'
    os.popen('adb shell "am start -a android.intent.action.MAIN -n com.mediatek.engineermode/.videotelephone.WorkingMode"')
    MonkeyRunner.sleep(wait_app_launch);
#!/usr/bin/python
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from com.android.monkeyrunner import MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
#from com.android.monkeyrunner.easy import HierarchyViewer
from com.android.monkeyrunner.easy import By
#from com.android.hierarchyviewerlib.device import ViewNode

device = MonkeyRunner.waitForConnection(0,"SH13TPL09945")
easy_device = EasyMonkeyDevice(device)
print 'start Contacts'
#device.installPackage('./es.apk')
#device.shell('am start -a android.intent.action.MAIN -n com.android.contacts/.DialtactsContactsEntryActivity')
device.startActivity(component='netease.pomelo.chat/.MainActivity')
MonkeyRunner.sleep(3)

#text=easy_device.visible(By.id('id/phoneNumber'))
#print text
hierarchy_viewer = device.getHierarchyViewer()
view_node=hierarchy_viewer.findViewById('id/channel')
print view_node
easy_device.touch(By.id('id/channel'),device.DOWN_AND_UP) 
device.type('mychn\n')

view_node=hierarchy_viewer.findViewById('id/name')
print view_node
easy_device.touch(By.id('id/name'),device.DOWN_AND_UP) 
device.type('myname\n')

#device.press('KEYCODE_DPAD_DOWN', 'DOWN_AND_UP')
Beispiel #36
0
import os;
from subprocess import Popen
from subprocess import PIPE
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.MonkeyDevice import takeSnapshot
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
from com.android.chimpchat.hierarchyviewer import HierarchyViewer
from com.android.monkeyrunner import MonkeyView
import random
import sys
import subprocess
from sys import exit
from random import randint
device = MonkeyRunner.waitForConnection()
easy_device=EasyMonkeyDevice(device)
package = 'org.jessies.dalvikexplorer'
activity ='org.jessies.dalvikexplorer.DalvikExplorerActivity'
runComponent = package+'/'+activity
device.startActivity(component=runComponent)
MonkeyRunner.sleep(1)
device.touch(98,1159, 'DOWN_AND_UP')
MonkeyRunner.sleep(1)
device.touch(372,426, 'DOWN_AND_UP')
MonkeyRunner.sleep(1)
device.touch(10,1371, 'DOWN_AND_UP')
MonkeyRunner.sleep(1)
device.touch(306,613, 'DOWN_AND_UP')
MonkeyRunner.sleep(1)
device.touch(707,1731, 'DOWN_AND_UP')
MonkeyRunner.sleep(1)
Beispiel #37
0
# -*- coding:utf-8 -*-
'''
Created on 2017年10月14日

@author: liuguoping
'''
from com.android.monkeyrunner import MonkeyRunner
from com.android.monkeyrunner import MonkeyDevice
from com.android.monkeyrunner import MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By

device = MonkeyRunner.waitForConnection(6, 'emulator-5554')
device.installPackage(
    'C:\\Users\\liuguoping\\Downloads\\app-product-release.apk')
device.startActivity(
    component='com.zerozero.hover/.newui.splash.SplashActivity')
easy_device = EasyMonkeyDevice(device)
easy_device.touch(By.id('com.zerozero.hovertest:id/btnCloseTerms'),
                  MonkeyDevice.DOWN_AND_UP)

# device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
# device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
device.press()
Beispiel #38
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# coding:utf-8
import sys

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
import subprocess

device = MonkeyRunner.waitForConnection(10.0, "127.0.0.1:21503")

easyDevice = EasyMonkeyDevice(device)

if True == easyDevice.visible(By.id('id/button1')):

    print "find"

easyDevice.touch(By.id('id/button2'), MonkeyDevice.DOWN_AND_UP)

print easyDevice.locate(By.id('id/button2'))

MonkeyRunner.sleep(2)
Beispiel #39
0
from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By

s = 'OpenSudoku'
views = [('cz.romario.opensudoku/cz.romario.opensudoku.gui.FolderListActivity','get_more_puzzles')]
#view = 'get_more_puzzles'
device = MonkeyRunner.waitForConnection()     
easy_device = EasyMonkeyDevice(device)

for view in views:
	sourceActivity = view[0]
	v = view[1]
	easy_device.startActivity(sourceActivity)
	MonkeyRunner.sleep(3.0)     
	result1 = device.takeSnapshot()
	result1.writeToFile('./'+v+'1.png','png')
	easy_device.touch(By.id('id/'+v),MonkeyDevice.DOWN_AND_UP)
	MonkeyRunner.sleep(3.0)
	result = device.takeSnapshot()
	result.writeToFile('./'+v+'2.png','png')
Beispiel #40
0
 def initEasyDevice(self):
     self.easyDevice = EasyMonkeyDevice(self.device)
Beispiel #41
0
class wrapEasyMonkey:
    '''
	#############################
	Wrap easy monkey class
	#############################
	'''
    def __init__(self, deviceId):
        device = MonkeyRunner.waitForConnection(10, deviceId)
        self.debug(
            "__int__: creating the wrap easy monkey object with deviceid %s" %
            deviceId)
        self.deviceId = deviceId
        self.easyDevice = EasyMonkeyDevice(device)
        self.device = device
        #self.DOWN = TouchPressType.DOWN.getIdentifier()
        #self.UP = TouchPressType.UP.getIdentifier()
        #self.DOWN_AND_UP = TouchPressType.DOWN_AND_UP.getIdentifier()
        self.DOWN = self.device.DOWN
        self.UP = self.device.UP
        self.DOWN_AND_UP = self.device.DOWN_AND_UP
        self.caseManager = testCaseManager(self)
        self.debug('created the wrapEasyDevice')

    def waitForConnection(self, seconds):
        try:
            return MonkeyRunner.waitForConnection(seconds)
        except:
            self.error("waitForConnection error")
            sys.exc_info()
            traceback.print_exc()
            return None

    def startActivity(self, activity):
        try:
            self.debug("starting the activity... %s" % activity)
            self.device.startActivity(component=activity)
        except:
            self.error("starting the activity %s error" % activity)
            sys.exc_info()
            traceback.print_exc()
            return False

    '''
	type charactors, special charactors please the press function to input the keycode
	'''

    def type(self, content):
        self.debug('device input the %s' % content)
        self.device.type(content)

    '''
	press keycode, special charactor and direction button ...
	'''

    def press(self, keycode, type):

        self.debug('device press the key "%s" ' % keycode)
        #self.sleep(0.2)
        self.device.press(keycode, type)

    '''
	sleep function
	'''

    def sleep(self, seconds):
        self.debug('sleeping %f seconds' % seconds)
        MonkeyRunner.sleep(seconds)

    '''
	wrap easyMonkeyDevice by function
	will return the view object if found.if do not found will return None.
	'''

    def getView(self, id):

        self.debug('calling getview function by the id (%s)' % id)
        for tmp in range(repeatTimesOnError):
            try:
                return By.id(id)
            except:
                self.debug(
                    'getView: the %dst time error by id (%s) ,  will retry ' %
                    (tmp, id))
                MonkeyRunner.sleep(1)
                continue
        self.error(
            'getView: sorry , still can\'t get the view by this id (%s). please check the view '
            % id)
        sys.exc_info()
        traceback.print_exc()
        return None

    '''
	if the id object is a textview, then will clear all the text
	'''

    def clearTextById(self, id):
        self.debug('calling clearTextById function by the id (%s)' % id)
        if (self.checkIdExist(id)):
            if not self.isFocused(id):
                self.touchViewById(id, self.DOWN_AND_UP)
            TextView = self.getView(id)
            rangenumber = len(self.getText(TextView))
            for x in range(rangenumber):
                self.device.press('KEYCODE_DEL', self.DOWN_AND_UP)
            for x in range(rangenumber):
                self.device.press('KEYCODE_FORWARD_DEL', self.DOWN_AND_UP)
            self.debug('clearTextById: cleared the text in id (%s)' % id)
            return True
        self.error('clearTextById: sorry ,the id (%s) is not exist ' % id)
        sys.exc_info()
        traceback.print_exc()
        return False

    '''
	wrap get text function.
	return text string content of the view object. If can not found the view object , will return None.
	'''

    def getText(self, view):

        self.debug('calling getText function')
        for tmp in range(repeatTimesOnError):
            try:
                return self.easyDevice.getText(view).encode(
                    sys.getdefaultencoding())
            except:

                self.debug(
                    'getText: the %dst time getText error , will retry ' % tmp)
                MonkeyRunner.sleep(1)
                continue
        self.error(
            'getText: sorry , still can\'t get the text. please check the view is exist or not , or does the view have text property?'
        )
        sys.exc_info()
        traceback.print_exc()
        return None

    '''
	'''

    def getTextById(self, id):

        self.debug('calling getTextById function')
        for tmp in range(repeatTimesOnError):
            try:
                return self.getText(self.getView(id))
            except:

                self.debug(
                    'getTextById: the %dst time getTextById error id (%s) , will retry '
                    % (tmp, id))
                MonkeyRunner.sleep(1)
                continue
        self.error(
            'getTextById: sorry , still can\'t get the text by id "%s". please check the view is exist or not , or does the view have text property?'
            % id)
        sys.exc_info()
        traceback.print_exc()
        return None

    '''
	wrap easyMonkeyDevice touch view function
	return true or false (if cannot locate the view ,will return false)
	'''

    def touchView(self, view, type):

        self.debug('calling touchView function')
        for tmp in range(repeatTimesOnError):
            try:
                self.easyDevice.touch(view, type)
                return True
            except:

                self.debug(
                    'touchView: the %dst time touch error , not found the view , will retry '
                    % tmp)
                if (tmp > 1 & DEBUG):
                    self.debug('Please wait to touch the view')
                MonkeyRunner.sleep(1)
                continue
        self.error(
            'touchView: sorry , still can\'t touch view. please check the view is exist or not , or increase the repeat times variable?'
        )
        sys.exc_info()
        traceback.print_exc()
        return False

    def touchViewById(self, id, type):

        self.debug('calling touchViewById function')
        for tmp in range(repeatTimesOnError):
            try:
                self.easyDevice.touch(By.id(id), type)
                return True
            except:

                self.debug(
                    'touchViewById: the %dst time touch error by this id (%s) , not found the view , will retry '
                    % (tmp, id))
                if (tmp > 1 & DEBUG):
                    self.debug('Please wait to touch the view')
                MonkeyRunner.sleep(1)
                continue
        self.error(
            'touchViewById: sorry , still can\'t touch view. please check the view is exist or not , or increase the repeat times variable?'
        )
        sys.exc_info()
        traceback.print_exc()
        return False

    '''
	wrap touch point function , touch screen position
	return true or false
	always return true actually
	'''

    def touchPoint(self, x, y, type):

        self.debug('calling touch the point ')
        for tmp in range(repeatTimesOnError):
            try:
                self.device.touch(x, y, type)
                return True
            except:

                self.debug(
                    'touchPoint: %d time touch point error , will retry ' %
                    tmp)
                MonkeyRunner.sleep(1)
                continue

        self.error(
            'touchPoint: sorry , still can\'t touch point. please check the view is exist or not , or increase the repeat times variable?'
        )
        sys.exc_info()
        traceback.print_exc()
        return False

    '''
	has the view is focused or not
	'''

    def isFocused(self, id):

        self.debug('checking the view is focused or not')
        #hierarchyViewer = self.device.getHierarchyViewer()
        #print hierarchyViewer.findViewById(id).hasFocus

        for tmp in range(repeatTimesOnError):
            try:
                hierarchyViewer = self.device.getHierarchyViewer()
                return hierarchyViewer.findViewById(id).hasFocus
            except:

                self.debug(
                    'isFocused: the %dst time check focus error  , will retry '
                    % tmp)
                MonkeyRunner.sleep(1)
                continue
        self.error('isFocused: error occured')
        sys.exc_info()
        traceback.print_exc()
        return False

    '''
	
	'''

    def isExist(self, id):

        #self.debug('check the id is exist or not')

        for tmp in range(repeatTimesOnError):
            try:
                if (self.easyDevice.exists(self.getView(id))):
                    return True
                else:

                    self.debug(
                        'isExist: %s this id does not exists,will try check again'
                        % id)
                    MonkeyRunner.sleep(1)
                    continue
            except:

                self.debug(
                    'isExist: the %dst time check id (%s) existing error ,  , will retry '
                    % (tmp, id))
                MonkeyRunner.sleep(1)
                continue
        self.error('isExist: error occured')
        sys.exc_info()
        traceback.print_exc()
        return False

    def checkIdExist(self, id):
        self.debug('checking the id (%s) exist or not' % id)

        for tmp in range(repeatTimesOnError):
            try:
                if (self.easyDevice.exists(self.getView(id))):
                    return True
                else:

                    self.debug(
                        'checkIdExist: %s this id does not exists,will try check again'
                        % id)
                    MonkeyRunner.sleep(1)
                    continue
            except:

                self.debug(
                    'checkIdExist: the %dst time check id (%s) existing error ,  , will retry '
                    % (tmp, id))
                MonkeyRunner.sleep(1)
                continue
        self.error('checkIdExist: error occured')
        sys.exc_info()
        traceback.print_exc()
        return False

    def getPosition(self, id):

        self.debug('check the view is focused or not')
        for tmp in range(repeatTimesOnError):
            try:
                hierarchyViewer = self.device.getHierarchyViewer()
                print hierarchyViewer.findViewById(id).left
                print hierarchyViewer.findViewById(id).top
                print hierarchyViewer.findViewById(id).width
                print hierarchyViewer.findViewById(id).height
                return hierarchyViewer.findViewById(id).left
            except:
                MonkeyRunner.sleep(1)
                continue
        self.error('getPosition: error occured')
        sys.exc_info()
        traceback.print_exc()
        return None

    def touchDialogById(self, id, type):

        #self.debug('touch the dialog button , here need the parent id')
        hierarchyViewer = self.device.getHierarchyViewer()
        width = self.device.getProperty("display.width")
        height = self.device.getProperty("display.height")
        x = hierarchyViewer.findViewById(id).left
        y = hierarchyViewer.findViewById(id).top
        '''
		print hierarchyViewer.findViewById(id).scrollX
		print hierarchyViewer.findViewById(id).scrollY
		print hierarchyViewer.findViewById(id).marginTop
		print hierarchyViewer.findViewById(id).marginLeft
		print hierarchyViewer.findViewById(id).marginRight
		print hierarchyViewer.findViewById(id).marginBottom
		print hierarchyViewer.findViewById(id).left
		print hierarchyViewer.findViewById(id).top
		print hierarchyViewer.findViewById(id).width
		print hierarchyViewer.findViewById(id).height
		
		print 'margin'
		print width
		print height
		print hierarchyViewer.findViewById(id).properties
		print '------------------'
		'''
        p = hierarchyViewer.findViewById(id).parent.parent
        #print p.properties
        myself = hierarchyViewer.findViewById(id)
        content = hierarchyViewer.findViewById('id/content')
        x += p.left + (int(width) - content.width) / 2 + myself.width / 2
        y += p.top + (int(height) - content.height) / 2 + myself.height / 2
        #( int(width) - hierarchyViewer.findViewById(id).width)/2 + hierarchyViewer.findViewById(id).left + hierarchyViewer.findViewById(id).width/2
        #y +=  ( int(height) - hierarchyViewer.findViewById(id).height)/2 + hierarchyViewer.findViewById(id).top + hierarchyViewer.findViewById(id).height/2
        #print x
        #print y
        self.touchPoint(x, y, type)

    def touchDialog(self, parentIdPosition, id, type):

        self.debug('touch the dialog button , here need the parent id')
        hierarchyViewer = self.device.getHierarchyViewer()
        #print hierarchyViewer.findViewById(parentId).left
        #print hierarchyViewer.findViewById(parentId).top
        x = hierarchyViewer.findViewById(
            parentId).left + (hierarchyViewer.findViewById(parentId).width -
                              hierarchyViewer.findViewById(id).width) / 2
        y = hierarchyViewer.findViewById(
            parentId).top + (hierarchyViewer.findViewById(parentId).height -
                             hierarchyViewer.findViewById(id).height) / 2
        print x
        print y
        self.touchPoint(x, y, type)

    def touchDialogButton(self, type):
        if DEBUG:
            self.debug(
                'touch the dialog button , thru controling the direction key')
        #self.device.press('KEYCODE_DPAD_DOWN',MonkeyDevice.DOWN_AND_UP)
        if type == 1:
            self.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP)
            #self.press('KEYCODE_DPAD_DOWN',MonkeyDevice.DOWN_AND_UP)
            self.press('KEYCODE_ENTER', MonkeyDevice.DOWN_AND_UP)
        if type == 2:
            #self.press('KEYCODE_DPAD_DOWN',MonkeyDevice.DOWN_AND_UP)
            self.press('KEYCODE_DPAD_DOWN', MonkeyDevice.DOWN_AND_UP)
            self.press('KEYCODE_DPAD_RIGHT', self.DOWN_AND_UP)
            self.press('KEYCODE_ENTER', self.DOWN_AND_UP)
        if type == 0:
            self.press('KEYCODE_ENTER', self.DOWN_AND_UP)

    def touchContextMenu(self, position):
        if DEBUG:
            self.debug('touch the context menu')
        self.press('KEYCODE_MENU', self.DOWN_AND_UP)
        for tmp in range(position + 1):
            MonkeyRunner.sleep(0.5)
            self.press('KEYCODE_DPAD_RIGHT', self.DOWN_AND_UP)
        self.press('KEYCODE_ENTER', self.DOWN_AND_UP)

    '''
	def touchDialogButtonRight(self,type):
		self.device.press('KEYCODE_DPAD_DOWN',type)
		self.device.press('KEYCODE_DPAD_DOWN',type)
		self.device.press('KEYCODE_DPAD_RIGHT',type)
		self.device.press('KEYCODE_ENTER',type)
	'''

    def debug(self, debuginfo):
        if DEBUG:
            print '[%s] DEBUG:  %s ' % (datetime.today(), debuginfo)

    def info(self, info):
        if INFO:
            print '[%s] Info: %s ' % (datetime.today(), info)

    def error(self, error):
        if ERROR:
            print '[%s] ERROR: %s ' % (datetime.today(), error)

    def takeSnapshot(self):
        print '----------start take snapshot-------------'
        for tmp in range(5):
            try:
                snapshot = self.device.takeSnapshot()
                print '----------end take snapshot-%s------------' % datetime.today(
                )
                return snapshot

            except:
                continue
        self.error('takeSnapshot: error occured')
        sys.exc_info()
        traceback.print_exc()
        return False
Beispiel #42
0
# File:   Test06.py
# Vision: V1.1
# Author: Findyou
# Time: 2013.12.03
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice, By
import sys

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device)

# Get the current path
path = sys.path[0]
path = path.replace('\\', '/')
path = path[path.rfind(":") - 1:]

# Runs the component
easy_device.startActivity(
    component='cn.richinfo.thinkdrive/.ui.activities.NavigateActivity')

# sleep 5's
MonkeyRunner.sleep(5)
# Takes a screenshot
result = device.takeSnapshot()
# Writes the screenshot to a file
filepath = path + "/Test6_001.png"
result.writeToFile(filepath, 'png')

# Right drag ->System menu
Beispiel #43
0
class MonkeyDaemon(object):
    def __init__(self, options):
        print '-------- MonkeyDaemon __init__ ---------'
        global emulators
        global robot_url

        if options.qq:
            self.qq = options.qq
        if self.qq not in emulators:
            print "Error: can not find the qq in the android ui emulators!"
            sys.exit(-1)
        if options.port:
            self.port = options.port
        if options.role:
            self.role = options.role

        self.qqName = ''
        # add a api to get pure group list, on-going
        self.screenUsing = 0
        self.groupListUpdating = 0
        self.heartbeat = 0
        # {drag, index, groupId, groupName, UILocation, msgs, storedMsgs}
        self.groupList = {}
        # already in this group
        self.currentGroup = {
            'groupId': '',
            'groupName': '',
            'UILocation': '',
            'msgs': [],
            'storedMsgs': []
        }

        self.monkey_set_up()
        if self.restart_qq_monkey() != 0:
            sys.exit(-1)
        self.get_qqName_monkey()
        self.get_pure_group_list_monkey()
        self.register_monkey()

    def monkey_set_up(self):
        print '------------ monkey_set_up -------------'
        devices = os.popen('adb devices').read().strip().split('\n')[1:]
        global deviceid
        deviceid = ''
        if self.role == 'A' or self.role == 'a':
            deviceid = devices[0].split('\t')[0]
        if self.role == 'B' or self.role == 'b':
            deviceid = devices[1].split('\t')[0]
        self.device = MonkeyRunner.waitForConnection(5, deviceid)
        self.easy_device = EasyMonkeyDevice(self.device)
        sleep(0.5)
        if not self.device or not self.easy_device:
            print "Error : monkey_set_up failed !"
            sys.exit(-1)
        return 0

    ### check steps ###

    # decorator to check qq status
    def check_qq_status(func):
        def new_func(self):
            print '------------ check qq status ------------'
            ret = self.is_home_screen()
            if ret == 0:
                return func(self)
            else:
                print "Error : QQ status is not correct !"
                return -1
        return new_func

    def is_screen_lock(self):
        print '------------ is_screen_lock ------------'
        try:
            glow_pad_view = self.get_hierarchy_view_by_id('id/glow_pad_view')
            self.screenUsing = 1
            self.device.drag((550, 1350),(1000, 1350),0.5,1)
            self.screenUsing = 0
            return 0
        except:
            print "Error : failed to parse view id/glow_pad_view !"
            return -1

    def is_home_screen(self):
        # print '------------ is_home_screen ------------'
        launcher = None
        try:
            launcher = self.get_hierarchy_view_by_id('id/launcher')
        except:
            print "Error : failed to parse view id/launcher !"

        if launcher != None:
            return 0
        else:
            return -1

    def is_group(self):
        # print '------------ is_group ------------'
        listView1 = None
        try:
            listView1 = self.get_hierarchy_view_by_id('id/listView1')
        except:
            print "Error : failed to parse view id/listView1 !"
        if listView1:
            # print "Info : already in the group !"
            return 0
        else:
            # print "Info : I am not in the group !"
            return -1

    def is_info(self):
        # print '------------ is_info ------------'
        common_xlistview = None
        try:
            common_xlistview = self.get_hierarchy_view_by_id('id/common_xlistview')
        except:
            print "Error : failed to parse view id/common_xlistview !"
        if common_xlistview:
            # print "Info : already in the info !"
            return 0
        else:
            # print "Info : I am not in the info !"
            return -1

    def is_grouplist(self):
        # print '------------ is_grouplist ------------'
        qb_troop_list_view = None
        try:
            qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view')
        except:
            print "Error : failed to parse view id/qb_troop_list_view !"
        if qb_troop_list_view:
            # print "Info : already in the grouplist !"
            return 0
        else:
            # print "Info : I am not in the grouplist !"
            return -1

    def is_current_group(self):
        # print '------------ is_current_group ------------'
        print "Info : current group : %s !" % self.currentGroup['groupId']
        groupId = ''
        if self.is_group() == 0:
            groupId = self.get_group_id()
            if self.currentGroup['groupId'] == groupId:
                return 0
            else:
                print "Info : I am not in current group %s, but %s !" % \
                    (self.currentGroup['groupId'], groupId)
                return -1
        else:
            return 1

    def is_3_columns(self):
        # print '------------ is_3_columns ------------'
        recent_chat_list = None
        try:
            recent_chat_list = self.get_hierarchy_view_by_id('id/recent_chat_list')
        except:
            print "Error : failed to parse view id/recent_chat_list !"
        if recent_chat_list:
            # print "Info : already in the 3 columns !"
            return 0
        else:
            # print "Info : I am not in the 3 columns !"
            return -1

    def restart_qq_monkey(self):
        print '------------ restart_qq_monkey -------------'
        while(self.is_home_screen()==0):
            # self.touch_to_enter_home_screen()
            self.touchByMonkeyPixel(150,1650)
            sleep(3)
            # 一开始启动,QQ闪退的情况
            if self.is_3_columns() == 0:
                self.touch_to_enter_contacts()
            # 点击联系人,QQ闪退的情况
        print "Info : qq has been restarted correctly !"
        return 0           
        # if self.is_3_columns() == 0:
        #     return 0
        # elif self.is_grouplist() == 0:
        #     return 0
        # else:
        #     print "Error : failed to restart QQ ! Try again !"
        #     self.touch_to_enter_home_screen()
        #     return -1

    ### check steps ###

    ### basic monkey operations ###

    def get_hierarchy_view_by_id(self,id):
        try:
            hViewer = self.device.getHierarchyViewer()
            view = hViewer.findViewById(id)
            return view
        except:
            # print "Error : failed to get hierarchy view by id %s !" % id
            return None

    # decorator to wait screen
    def touch_wait_screen(func):
        def new_func(self, *args):
            if self.screenUsing == 1:
                print "Info : self.screenUsing == 1 !"
                # sleep(1)
            return func(self, *args)
        return new_func

    def touch_to_enter_home_screen(self):
        try:
            return self.touchByMonkeyPixel(1080/2,1850)
        except:
            print "Error : failed to touch_to_enter_home_screen !"
            return -1            

    # @touch_wait_screen
    def touchByMonkeyId(self,id):
        # print '------------ touchByMonkeyId %s -------------' % id
        try:
            self.screenUsing = 1
            self.easy_device.touch(By.id(id), self.easy_device.DOWN_AND_UP)
            sleep(0.5)
            self.screenUsing = 0
            return 0
        except:
            print 'Error : failed to dump view : %s !' % id
            return -1

    # @touch_wait_screen
    def touch_to_leave(self):
        # print '------------ touch_to_leave -------------'
        try:
            return self.touchByMonkeyPixel(150,150)
        except:
            print "Error : failed to touch_to_leave !"
            return -1

    # @touch_wait_screen
    def touch_to_enter_info(self):
        # print '------------ touch_to_enter_info -------------'
        try:
            return self.touchByMonkeyPixel(1000,150)
        except:
            print "Error : failed to touch_to_enter_info !"
            return -1

    # @touch_wait_screen
    # 换另外一个group,要重新进入grouplist
    def touch_to_enter_grouplist(self):
        print '------------ touch_to_enter_grouplist -------------'
        if self.is_3_columns() == 0:
            self.touch_to_enter_contacts()
            self.touchByMonkeyPixel(700,500)
            self.touchByMonkeyPixel(300,300)
            return 0
        if self.is_info() == 0:
            self.touch_to_leave()
        if self.is_group() == 0:
            self.touch_to_leave()
        self.touch_to_leave()
        self.touch_to_enter_contacts()
        self.touchByMonkeyPixel(700,500)
        self.touchByMonkeyPixel(300,300)
        # if self.is_grouplist():
        #     return 0
        # else:        
        #     print "Error : failed to touch_to_enter_grouplist !"
        #     return -1
        return 0

    # @touch_wait_screen
    def touch_to_enter_msgs(self):
        # 不把is_3_columns()放这里边,是为了单独处理QQ restart闪退情况。
        print '------------ touch_to_enter_msgs -------------'
        if self.touchByMonkeyPixel(300,1700) == 0:
            return self.touchByMonkeyPixel(300,1700)
        else:
            print "Error : failed to touch_to_enter_msgs !"
            return -1

    # @touch_wait_screen
    def touch_to_enter_contacts(self):
        # 不在is_3_columns()判断放在里边,是为了单独处理QQ restart闪退情况。
        print '------------ touch_to_enter_contacts -------------'
        if self.touchByMonkeyPixel(500,1700) == 0:
            return self.touchByMonkeyPixel(500,1700)
        else:
            print "Error : failed to touch_to_enter_contacts !"
            return -1

    # @touch_wait_screen
    def touchByMonkeyPixel(self,x,y):
        # print '------------ touchByMonkeyPixel %s %s -------------' % (x,y)
        try:
            self.screenUsing = 1            
            self.device.touch(x,y,'DOWN_AND_UP')
            sleep(0.5)
            self.screenUsing = 0
            return 0
        except:
            # sleep(1)
            return -1

    def getTextByMonkeyView(self,view):
        # print '------------ getTextByMonkeyView %s -------------' % view
        try:
            return view.namedProperties.get('text:mText').value.encode('utf8')
        except:
            # images
            print 'Error : failed to find text for view : %s !' % view
            return 0

    def getDescByMonkeyView(self,view):
        # print '------------ getDescByMonkeyView %s -------------' % view
        try:
            return view.namedProperties.get('accessibility:getContentDescription()').value.encode('utf8')
        except:
            # images
            print 'Error : failed to find desc for view : %s !' % view
            return 0

    ### basic monkey operations ###


    # @check_qq_status
    def get_qqName_monkey(self):
        print '------------ get_qqName_monkey ------------'
        if self.is_3_columns() == 0:
            self.touch_to_enter_msgs()
        else:
            if self.is_info() == 0:
                self.touch_to_leave()
            if self.is_group() == 0:
                self.touch_to_leave()
            if self.is_grouplist() == 0:
                self.touch_to_leave()
        # if self.touchByMonkeyPixel(90,150) != 0:
        #     return -1
        self.device.drag((300, 150),(1000, 150),0.5,1)
        nickname = self.get_hierarchy_view_by_id('id/nickname')
        self.qqName = self.getTextByMonkeyView(nickname)
        # if self.touchByMonkeyPixel(1050,700) != 0:
        #     return -1
        self.device.drag((1000, 150),(300, 150),0.5,1)
        # print "Info : now monkey daemon is running for %s %s !" % (self.qqName,self.qq)
        return 0

    def get_pure_group_list_monkey(self):
        print '------------ get_pure_group_list_monkey ------------'
        self.groupListUpdating = 1
        if self.touch_to_enter_grouplist() != 0:
            return -1
        for drag in range(0,1):
            if self.is_info() == 0:
                self.touch_to_leave()
            if self.is_group() == 0:
                self.touch_to_leave()
            print "Info : drag for %s time !" % drag
            if drag != 0:
                try:
                    self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1)
                except:
                    print "Error : failed for the %s drag !" % drag

            qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view')
            if qb_troop_list_view == None:
                continue
            _groupList = []
            _groupList = qb_troop_list_view.children
            if _groupList == []:
                print "Error : failed to parse view qb_troop_list_view !"
                continue

            if drag == 0:
                # first one is the search box
                del _groupList[0]

            for group in _groupList:
                if self.is_info() == 0:
                    self.touch_to_leave()
                if self.is_group() == 0:
                    self.touch_to_leave()
                # 我创建的群(16) 这样的一行
                notGroup = self.getTextByMonkeyView(group.children[0])
                if notGroup:
                    # print "Info : this is not a group %s !" % notGroup
                    continue
                groupNameView = group.children[1].children[2].children[1]
                item = {
                    'groupName': self.getTextByMonkeyView(groupNameView),
                    'drag':drag,
                    # 363 is qb_troop_list_view.top, 156是整个一条group的高度。
                    'UILocation': group.top + 156/2 + 363,
                    'msgs': [],
                    'storedMsgs': []
                }

                # 点击进入到群组会话中,去获取groupId
                # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。
                if item['UILocation'] < 370 or item['UILocation'] > 1760:
                    print "Info : skip this group in case we touch screen incorrectly !"
                    continue
                groupId = ''
                if self.touchByMonkeyPixel(1080/2,item['UILocation']) == 0:
                    groupId = self.get_group_id()
                if groupId in self.groupList.keys():
                    print "Info : this group %s %s has already exist !" % \
                        (item['groupName'],groupId)
                    continue
                self.groupList[groupId] = item
                print "Info : group info: %s , %s , %s , %s !" % \
                    (item['groupName'],groupId,item['drag'],item['UILocation'])

        print "Info : total group count : %s !" % len(self.groupList)
        for key in self.groupList:
            print "Info : group info: %s , %s , %s , %s !" % \
                (self.groupList[key]['groupName'],key, \
                    self.groupList[key]['drag'],self.groupList[key]['UILocation'])
        
        self.groupListUpdating = 0
        return 0

    # 获取groupId,结束后仍退出至group
    def get_group_id(self):
        # 此时位于群组会话中,点击进入到群组信息里边
        groupId = ''
        if self.is_group() != 0:
            print "Error : I am not in the group !"
            return -1
        if self.touch_to_enter_info() != 0:
            return -1
        if self.is_info() != 0:
            print "Error : I am not in the info !"
            return -1
        for i in range(0,3):       
            try:
                xlist = self.get_hierarchy_view_by_id('id/common_xlistview')
                nameAndId = xlist.children[0].children[2].children[0].children[1]
                groupId = self.getTextByMonkeyView(nameAndId.children[1].children[0])
                break
            except:
                print "Error : failed to get groupId !"
                continue
        print "Info : get this group id : %s !" % groupId
        self.touch_to_leave()
        return groupId

    def register_monkey(self):
        print '------------ register_monkey ------------'
        groupList = [{'groupId': key, 'groupName': value['groupName']} 
                     for key, value in self.groupList.iteritems()]
        data = {
            'cmd': 'register',
            'qq': self.qq,
            'qqName': self.qqName,
            'url': 'http://%s:%s/net_command' % (localIp,self.port),
            'groupList': json.dumps(groupList)
        }
        url_post(robot_url, data)
        return 0

    def monkey_task_loop(self):
        print '------------ monkey_task_loop start ------------'
        # this should never return        
        while(1):
            # if self.is_home_screen() != 0:
                # continue
            sleep(1)
            if self.screenUsing == 0:
                self.heartbeat += 1
                if self.heartbeat == 600:
                    self.get_pure_group_list_monkey()
                    self.heartbeat = 0
            else:
                self.heartbeat = 0


    ### api for robot manager

    # 此处,不考虑UILocation
    def enter_group(self,data):
        print '\n------------ enter_group ------------'
        if self.groupListUpdating == 1:
            print "Info : groupList is updating now ! Please wait about 2 minutes !"
            return 1
        if data['group'] not in self.groupList:
            print "Error : failed to find in the grouplist %s !" % data['group']
            return -1
        if self.currentGroup['groupId'] != data['group']:
            self.currentGroup['groupId'] = data['group']
            self.currentGroup['groupName'] = self.groupList[data['group']]['groupName']
        if self.is_current_group() == 0:
            return 0
        if self.touch_to_enter_grouplist() != 0:
            return -1
        
        groupId = ''
        # 通过possibleDrag来缩小查找范围。然后从该页的自己、前、后 三个界面查找。
        # 下一步,可以通过possibleIndex,在自己界面进一步缩小查找范围。
        #       在前界面,从后往前查找;在后界面,从前往后查找。
        possibleDrag = self.groupList[ data['group'] ]['drag']
        possibleUILocation = self.groupList[ data['group'] ]['UILocation']
        print "Info : possibleDrag %s , possibleUILocation %s to enter group %s !" % \
                (possibleDrag, possibleUILocation, data['group'])
        if possibleDrag > 0:
            for i in range(0,possibleDrag):
                self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1)
                # sleep(1)

        # 现在,前,后的顺序查找三个界面
        for j in range(0,3):
            if self.is_grouplist() != 0:
                if self.is_info() == 0:
                    self.touch_to_leave()
                if self.is_group() == 0:
                    self.touch_to_leave()
            if possibleDrag == 0:
                if j != 0:
                    # 向下drag一次
                    self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1)
            else:
                if j == 1:
                    # 向上drag一次
                    self.device.drag((1080/2, 400),(1080/2, 1700),0.5,1)
                if j == 2:
                    # 向下drag一次
                    self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1)
                    self.device.drag((1080/2, 1700),(1080/2, 400),0.5,1)

            # 每次j==0的时候,首先看下possibleUILocation对应的group
            if j == 0:
                for i in range(0,3):
                    try:
                        if self.touchByMonkeyPixel(1080/2,possibleUILocation) == 0:
                            groupId = self.get_group_id()
                    except:
                        print "Error : failed to parse the possibleUILocation group !"
                    if groupId == data['group']:
                        return 0
                    else:
                        # 不是这个群,就退出至grouplist界面
                        if self.is_info() == 0:
                            self.touch_to_leave()
                        if self.is_group() == 0:
                            self.touch_to_leave()
                        continue                   

            qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view')
            if qb_troop_list_view == None:
                continue
            _groupList = []
            _groupList = qb_troop_list_view.children
            if _groupList == []:
                print "Error : failed to parse view qb_troop_list_view !"
                continue

            if possibleDrag == 0:
                # first one is the search box
                del _groupList[0]
            elif possibleDrag == 1:
                if j == 1:
                    del _groupList[0]

            for group in _groupList:
                if self.is_info() == 0:
                    self.touch_to_leave()
                if self.is_group() == 0:
                    self.touch_to_leave()
                if self.is_grouplist() != 0:
                    return -1
                # 我创建的群(16) 这样的一行
                notGroup = self.getTextByMonkeyView(group.children[0])
                if notGroup:
                    continue
                # groupNameView = group.children[1].children[2].children[1]
                # groupName = self.getTextByMonkeyView(groupNameView)
                # if groupName != self.groupList.get(data['group']).get('groupName'):
                #     continue

                # 363 is qb_troop_list_view.top, 156是整个一条group的高度。                    
                UILocation = group.top + 156/2 + 363
                # groupName对了,然后看groupId。暂时不要去解析groupName,耗时
                # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。
                if UILocation < 370 or UILocation > 1760:
                    print "Info : skip this group in case we touch screen incorrectly !"
                    continue
                if self.touchByMonkeyPixel(1080/2,UILocation) == 0:             
                    groupId = self.get_group_id()
                    if groupId == data['group']:
                        return 0
        print "Error : failed to enter group %s !" % data['group']
        return -1

    def send_msg(self,data):
        print '\n------------ send_msg ------------'
        if not data.get('msg'):
            return -1        
        if self.is_current_group() != 0:
            return -1

        utils.get_encoded_character(deviceid, data['msg'].decode('utf8'))
        self.restart_qq_monkey()

        self.easy_device.touch(By.id("id/input"), self.easy_device.DOWN)
        # self.device.touch(500,1700,'DOWN')
        sleep(0.5)
        self.easy_device.touch(By.id("id/input"), self.easy_device.UP)
        # self.device.touch(500,1700,'UP')
        # sleep(1)
        self.touchByMonkeyPixel(270,1590)

        inputid = self.get_hierarchy_view_by_id('id/input')
        if inputid:
            text = self.getTextByMonkeyView(inputid)
            print "Info : get msg %s from clipboard !" % text
            if text.strip().split() == data['msg'].strip().split():
                if self.touchByMonkeyId('id/fun_btn') != 0:
                # if self.touchByMonkeyPixel(970,1700) != 0:
                    return -1
        print "Info : send msg %s !" % data['msg']
        return 0

    def get_msgs(self,data):
        print '\n------------ get_msgs ------------'
        if self.is_current_group() != 0:
            ret = []
            return ret        
        # 针对新消息的提示处理
        for i in range(0,3):
            self.device.drag((1080/2, 1600),(1080/2, 500),0.2,1)

        self.currentGroup['msgs'] = []
        dragCount = 3
        msgs = []
        is_stop_drag = 0
        for msgDrag in range(0, dragCount):
            if is_stop_drag:
                break
            if msgDrag !=0:
                self.device.drag((1080/2, 500),(1080/2, 1600),0.2,1)

            hViewer = None
            _msgs = []
            try:
                listView1 = self.get_hierarchy_view_by_id('id/listView1')
                # 该行会出现AttributeError: 'NoneType' object has no attribute 'children
                _msgs = listView1.children
            except:
                print "Error : failed to parse view : listView1 !"

            # print 'msgs count : ', len(_msgs)-1 #最后一个为输入框
            # reverse()不可用java.Arraylist
            tmpMsgs = []
            for m in _msgs:
                tmpMsgs.insert(0, m)
            for m in tmpMsgs:
                if 'BaseChatItemLayout' not in str(m):
                    continue
                item = {}
                item['nickname'] = ''
                layoutLeft = ''
                for t in m.children:
                    if t.id == 'id/chat_item_head_icon':
                        layoutLeft = t.namedProperties.get('layout:mLeft').value.encode('utf8')
                        if layoutLeft == '930':
                            break
                    if t.id == 'id/chat_item_nick_name':
                        item['nickname'] = self.getTextByMonkeyView(t)
                    if t.id == 'id/chat_item_content_layout':
                        item['content'] = self.getTextByMonkeyView(t)
                if layoutLeft == '930':
                    continue
                else:
                    if item['nickname'].endswith(':'):
                        item['nickname'] = item['nickname'][0:-1]

                #此处时间暂不考虑如 Friday 10:46 的情况
                c = self.getDescByMonkeyView(m)
                item['time'] = c[0:c.find(' ')]
 
                # 已存储的消息,则没有必要往前drag了。
                if item in self.currentGroup['storedMsgs']:
                    is_stop_drag = 1
                    break
                # 未存储,则为新消息.如前一次drag已得到,则跳过。             
                if item in msgs:
                    continue
                msgs.append(item)
        while(msgDrag>0):
            self.device.drag((1080/2, 1600),(1080/2, 500),0.2,1)
            msgDrag -= 1

        if msgs:
            self.currentGroup['msgs'] = msgs
            print "Info : new msgs count : %s !" % len(msgs)
            for m in self.currentGroup['msgs']:
                print m['nickname'], m['content'], m['time']
            # default: store the last 10 msgs
            self.currentGroup['storedMsgs'] += self.currentGroup['msgs']            
            print 'Info : stored msgs count ', len(self.currentGroup['storedMsgs'])
            if len(self.currentGroup['storedMsgs']) > 30:
                self.currentGroup['storedMsgs'] = self.currentGroup['storedMsgs'][-10:]
            self.groupList[self.currentGroup['groupId']]['storedMsgs'] = self.currentGroup['storedMsgs']                
            # for n in self.currentGroup['storedMsgs']:
                # print n['nickname'], n['content'], n['time']
      
        return self.currentGroup['msgs']
Beispiel #44
0
def filter_contacts(device):
    easy_device = EasyMonkeyDevice(device)
    start_activity(device, ".StartActivity")

    easy_device.touch(By.id("id/mpp_menu_toggle_filter_box"), MonkeyDevice.DOWN_AND_UP)
Beispiel #45
0
#connect device
print('connect device!')
device = MonkeyRunner.waitForConnection()

#start activity
print('start activity')
package = 'com.android.calculator2'
activity = 'com.android.calculator2.Calculator'
runComponent = package + '/' + activity
device.startActivity(component=runComponent)
MonkeyRunner.sleep(3)

#init easymonkeydevice object ,this is init method
print('init easymonkeydevice')

easy_device = EasyMonkeyDevice(device)
print('Tap 8')
easy_device.touch(By.id('id/digit_8'), MonkeyDevice.DOWN_AND_UP)
MonkeyRunner.sleep(1.0)
print('Tap *')
easy_device.touch(By.id('id/op_mul'), MonkeyDevice.DOWN_AND_UP)
MonkeyRunner.sleep(1.0)
print('Tap 9')
easy_device.touch(By.id('id/digit_9'), MonkeyDevice.DOWN_AND_UP)
MonkeyRunner.sleep(1.0)
#print('Tap =')
#easy_device.touch(By.id('id/eq'),MonkeyDevice.DOWN_AND_UP)

if easy_device.exists(By.id('id/result')) == True:
    text_result = easy_device.getText(By.id('id/result'))
    if text_result.encode('utf-8') == "72":
        vc.dump()
        hello = vc.findViewById('id/hello')
        if hello:
            if hello.getText() == "Hello Donald":
                print "OK"
            else:
                print "FAIL"
        else:
            print >> sys.stderr, "'hello' not found" 
    else:
        print >> sys.stderr, "'Show Dialog' button not found"
else:
    # MonkeyRunner
    from com.android.monkeyrunner.easy import EasyMonkeyDevice
    from com.android.monkeyrunner.easy import By
    easyDevice = EasyMonkeyDevice(device)
    showDialogButton = By.id('id/show_dialog_button')
    if showDialogButton:
        easyDevice.touch(showDialogButton, MonkeyDevice.DOWN_AND_UP)
        ViewClient.sleep(3)
        editText = By.id('id/0x123456')
        print editText
        easyDevice.type(editText, 'Donald')
        ViewClient.sleep(3)
        ok = By.id('id/button1')
        if ok:
            # 09-08 20:16:41.119: D/MonkeyStub(1992): translateCommand: tap 348 268
            easyDevice.touch(ok, MonkeyDevice.DOWN_AND_UP)
        hello = By.id('id/hello')
        if hello:
            if easyDevice.getText(hello) == "Hello Donald":
Beispiel #47
0
# Vision: V1.1
# Author: Findyou
# Time: 2013.12.03
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice, By
import time, sys

# Get the current path
path = sys.path[0]
path = path.replace('\\', '/')
path = path[path.rfind(":") - 1:]

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device)

# Runs the component
easy_device.startActivity(
    component='cn.richinfo.thinkdrive/.ui.activities.NavigateActivity')


def take_Snapshot():
    # sleep 3's
    MonkeyRunner.sleep(3)
    c_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # Takes a screenshot
    result = device.takeSnapshot()
    # Writes the screenshot to a file
    result.writeToFile(path + "/Test09_" + c_time + ".png", 'png')
Beispiel #48
0
    def __init__(self, test_name):
        self.test_name = test_name

        # Connects to the current device
        self.device = MonkeyRunner.waitForConnection()
        self.easyDevice = EasyMonkeyDevice(self.device)
Beispiel #49
0
class MonkeyDaemon(object):
    def __init__(self, qq):
        print '-------- MonkeyDaemon __init__ ---------'
        self.qq = qq

        # self.emulator = {
        #     'width':1080,
        #     'height':1920,
        #     'qqStart':[150,1650],
        #     'qqName':[75,150],
        #     'msgs':[200,1700],
        #     'contacts':[500,1700],
        #     'groups':[700,500],
        #     'myGroups':[300,300],
        #     'info':[1000,150],
        #     'heartbeat':[430,150],
        #     'paste':[270,1590],
        #     'leave':[150,150],
        #     'self_msg':'930',
        # }

        self.emulator = {
            'width':480,
            'height':800,
            'qqStart':[50,750],
            'qqName':[40,75],
            'msgs':[80,750],
            'contacts':[240,750],
            'groups':[300,230],
            'myGroups':[100,150],
            'info':[450,75],
            'heartbeat':[200,75],
            'paste':[150,725],
            'leave':[60,70],
            'input':[200,760],
            'send':[430,760],
            'self_msg':'404',
        }
        self.path_dict = {
            'is_grouplist':{
                'is_main' : ['contacts','groups'],
                'is_grouplist': 'leave', # 重新进入grouplist
                'is_group': 'leave',
                'is_info' : 'leave',
            },
            'is_group':{
                'is_main': 'is_grouplist',
                'is_grouplist':'enter_group',
                'is_group': None,
                'is_info': 'leave',
            },
            'is_info':{
                'is_main': 'is_grouplist',
                'is_grouplist':'enter_group',
                'is_group': 'info',
                'is_info': None,
            },
            'is_main':{
                'is_home_screen': 'qqStart',
                'is_main': None,
                'is_grouplist': 'leave',
                'is_group': 'leave',
                'is_info': 'leave',
            },
        }
        # add a api to get pure group list, on-going
        self.screenUsing = 0
        self.groupListUpdating = 0
        self.heartbeat = 0
        # {drag, index, groupId, groupName, UILocation, msgs, storedMsgs}
        self.groupList = {}
        # already in this group
        self.currentGroup = {
            'groupId': '',
            'groupName': '',
            'UILocation': '',
            'msgs': [],
            'storedMsgs': []
        }

        self.monkey_set_up()
        if self.restart_qq_monkey() != 0:
            sys.exit(-1)
        if self.get_qqName_monkey() != 0:
            sys.exit(-1)
        if self.get_grouplist() != 0:
            self.get_pure_group_list_monkey()
            if self.groupList != {}:
                self.write_grouplist()
        self.register_monkey()

    def monkey_set_up(self):
        print '------------ monkey_set_up -------------'
        self.device = MonkeyRunner.waitForConnection(5, self.qq['deviceid'])
        self.easy_device = EasyMonkeyDevice(self.device)
        sleep(0.5)
        if not self.device or not self.easy_device:
            print "Error : monkey_set_up failed !"
            sys.exit(-1)
        return 0


    ### basic check steps ###

    # decorator to check qq status
    def check_qq_status(func):
        def new_func(self):
            print '------------ check qq status ------------'
            ret = self.is_home_screen()
            if ret == 0:
                return func(self)
            else:
                print "Error : QQ status is not correct !"
                return -1
        return new_func

    def is_screen_lock(self):
        try:
            if 'Keyguard' not in self.get_focus_window_name():
                return 0
            else:
                self.screenUsing = 1
                self.device.drag((240, 550),(450, 550),0.2,1)
                self.screenUsing = 0
        except:
            print "Error : failed to get focus window name Keyguard !"
            return -1

    def is_home_screen(self):
        try:
            if 'Launcher' in self.get_focus_window_name():
                return 0
        except:
            print "Error : failed to get focus window name Launcher !"
            return 1

    def is_main(self):
        try:
            if 'SplashActivity' in self.get_focus_window_name():
                return 0
        except:
            print "Error : failed to get focus window name SplashActivity !"
            return 1

    def is_group(self):
        try:
            if 'ChatActivity' in self.get_focus_window_name():
                return 0
        except:
            print "Error : failed to get focus window name ChatActivity !"
            return 1

    def is_info(self):
        try:
            if 'ChatSettingForTroop' in self.get_focus_window_name():
                return 0
        except:
            print "Error : failed to get focus window name ChatSettingForTroop !"
            return 1

    def is_grouplist(self):
        try:
            if 'TroopActivity' in self.get_focus_window_name():
                return 0
        except:
            print "Error : failed to get focus window name TroopActivity !"
            return 1

    def is_current_group(self):
        # 暂时没有用到,以后单口的时候可能会用到。
        # print '------------ is_current_group ------------'
        print "Info : current group : %s !" % self.currentGroup['groupId']
        groupId = ''
        if self.is_group() == 0:
            groupId = self.get_group_id()
            if self.currentGroup['groupId'] == groupId:
                return 0
            else:
                print "Info : I am not in current group %s, but %s !" % \
                    (self.currentGroup['groupId'], groupId)
                return -1
        else:
            return 1

    ### basic check steps ###


    ### basic monkey operations ###

    def get_hierarchy_view_by_id(self,id):
        try:
            hViewer = self.device.getHierarchyViewer()
            view = hViewer.findViewById(id)
            return view
        except:
            return None

    def get_focus_window_name(self):
        try:
            hViewer = self.device.getHierarchyViewer()
            window_name = hViewer.focusedWindowName
            return window_name
        except:
            return ''

    def get_current_view(self):
        window_name = self.get_focus_window_name()
        if 'ChatActivity' in window_name: ### NoneType' object is not iterable
            return 'is_group'
        elif 'TroopActivity' in window_name:
            return 'is_grouplist'
        elif 'SplashActivity' in window_name:
            return 'is_main'
        elif 'ChatSettingForTroop' in window_name:
            return 'is_info'
        elif 'Launcher' in window_name:
            return 'is_home_screen'            
        else:
            return ''

    def goto_window(self,dest):
        print "------------ goto_window %s" % dest
        current_view = self.get_current_view()
        while( current_view != dest ):
            action = self.path_dict[dest][current_view]
            if callable(action):
                action()
            elif 'is_' in action:
                pass
                # action = self.path_dict[dest][current_view]
            elif type(action) is list:
                for i in action:
                    self.touchByMonkeyPixel(self.emulator[i])
            else:
                self.touchByMonkeyPixel(self.emulator[action])
            sleep(1)
            current_view = self.get_current_view()
        return 0

    # decorator to wait screen
    def touch_wait_screen(func):
        def new_func(self, *args):
            if self.screenUsing == 1:
                print "Info : self.screenUsing == 1 !"
                # sleep(1)
            return func(self, *args)
        return new_func

    def drag_to_page_down(self):
        try:
            # self.device.shell("input keyevent KEYCODE_PAGE_DOWN")
            # self.device.press('KEYCODE_PAGE_DOWN','DOWN_AND_UP','')
            self.device.drag((480/2, 710),(480/2, 130),0.2,1)
        except:
            print "Error : failed to drag_to_page_down !"
            return -1

    def drag_to_page_up(self):
        try:
            # self.device.shell("input keyevent KEYCODE_PAGE_UP")
            # self.device.press('KEYCODE_PAGE_UP','DOWN_AND_UP','')
            self.device.drag((480/2, 130),(480/2, 710),0.2,1)
        except:
            print "Error : failed to drag_to_page_up !"
            return -1

    def touch_to_enter_home_screen(self):
        self.device.press('KEYCODE_HOME','DOWN_AND_UP','')
        while(self.is_home_screen() != 0):
            self.device.press('KEYCODE_HOME','DOWN_AND_UP','')

    # @touch_wait_screen
    def touch_to_leave(self):
        try:
            self.touchByMonkeyPixel(self.emulator['leave'])
            return 0
        except:
            print "Error : failed to touch_to_leave !"
            return 1

    def touch_to_enter_main(self):
        # 先回到chatlist或contacts
        return self.goto_window('is_main')

    # @touch_wait_screen
    def touch_to_enter_group(self):
        return self.goto_window('is_group')

    # @touch_wait_screen
    def touch_to_enter_info(self):
        return self.goto_window('is_info')

    # @touch_wait_screen
    # 换另外一个group,要重新进入grouplist
    def touch_to_enter_grouplist(self):   
        return self.goto_window('is_grouplist')

    # @touch_wait_screen
    def touch_to_enter_msgs(self):
        if self.touch_to_enter_main() == 0:
            if self.touchByMonkeyPixel(self.emulator['msgs']) == 0:
                return self.touchByMonkeyPixel(self.emulator['msgs'])

    # @touch_wait_screen
    def touch_to_enter_contacts(self):
        # 不把touch_to_enter_main()判断放在里边,是为了单独处理QQ restart闪退情况。
        if self.touchByMonkeyPixel(self.emulator['contacts']) == 0:
            return self.touchByMonkeyPixel(self.emulator['contacts'])
        else:
            print "Error : failed to touch_to_enter_contacts !"
            return -1

    # @touch_wait_screen
    def touchByMonkeyPixel(self,point):
        # print '------------ touchByMonkeyPixel %s %s -------------' % (x,y)
        try:
            self.screenUsing = 1            
            self.device.touch(point[0],point[1],'DOWN_AND_UP')
            sleep(0.5)
            self.screenUsing = 0
            return 0
        except:
            # sleep(1)
            return -1

    # @touch_wait_screen
    def touchByMonkeyId(self,id):
        # print '------------ touchByMonkeyId %s -------------' % id
        try:
            self.screenUsing = 1
            self.easy_device.touch(By.id(id), self.easy_device.DOWN_AND_UP)
            sleep(0.5)
            self.screenUsing = 0
            return 0
        except:
            print 'Error : failed to dump view : %s !' % id
            return -1

    def getTextByMonkeyView(self,view):
        # print '------------ getTextByMonkeyView %s -------------' % view
        try:
            return view.namedProperties.get('text:mText').value.encode('utf8')
        except:
            # images
            print 'Error : failed to find text for view : %s !' % view
            return ''

    def getDescByMonkeyView(self,view):
        # print '------------ getDescByMonkeyView %s -------------' % view
        try:
            return view.namedProperties.get('accessibility:getContentDescription()').value.encode('utf8')
        except:
            # images
            print 'Error : failed to find desc for view : %s !' % view
            return ''

    ### basic monkey operations ###


    def restart_qq_monkey(self):
        print '------------ restart_qq_monkey -------------'
        while(self.is_home_screen()==0):
            # self.touch_to_enter_home_screen()
            self.touchByMonkeyPixel(self.emulator['qqStart'])
            sleep(3)
            # 一开始启动,QQ闪退的情况
            if self.is_main() == 0:
                self.touch_to_enter_contacts()
            # 点击联系人,QQ闪退的情况
            sleep(2)
        print "Info : qq has been restarted correctly !"
        return 0

    # @check_qq_status
    def get_qqName_monkey(self):
        print '------------ get_qqName_monkey ------------'
        self.touch_to_enter_msgs()
        # self.device.drag((300, 150),(1000, 150),0.2,1)
        self.touchByMonkeyPixel(self.emulator['qqName'])
        nickname = self.get_hierarchy_view_by_id('id/nickname')
        self.qq['qqName'] = self.getTextByMonkeyView(nickname)
        self.device.drag((410, 70),(150, 70),0.2,1)
        if self.qq['qqName']:
            print "Info : qq name is %s !" % self.qq['qqName']
            return 0
        return -1

    def get_grouplist(self):
        if not os.path.isfile(self.qq['grouplistfile']):
            return 1
        f = open(self.qq['grouplistfile'],'r')
        self.groupList = json.loads(f.read())
        f.close()
        return 0

    def write_grouplist(self):
        if not os.path.isfile(self.qq['grouplistfile']):
            os.system('touch %s' % self.qq['grouplistfile'])
        f = open(self.qq['grouplistfile'],'w')
        f.write(json.dumps(self.groupList).encode('utf8'))
        f.close()
        return 0

    def get_pure_group_list_monkey(self):
        print '------------ get_pure_group_list_monkey ------------'
        self.groupListUpdating = 1
        if self.touch_to_enter_grouplist() != 0:
            return 1
        for drag in range(0,10):
            print "Info : drag for %s time !" % drag
            if drag != 0:
                try:
                    # self.device.drag((1080/2, 1700),(1080/2, 400),0.2,1)
                    # self.device.drag((480/2, 750),(480/2, 190),0.2,1)
                    self.drag_to_page_down()
                except:
                    print "Error : failed for the %s drag !" % drag

            qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view')
            if qb_troop_list_view == None:
                continue
            _groupList = []
            _groupList = qb_troop_list_view.children
            if _groupList == []:
                print "Error : failed to parse view qb_troop_list_view !"
                continue

            if drag == 0:
                # first one is the search box
                del _groupList[0]

            index = 0
            for group in _groupList:
                index += 1
                view = self.get_current_view()
                if view == 'is_group' or view == 'is_info':
                    self.touch_to_enter_grouplist()
                # 我创建的群(16) 这样的一行
                notGroup = self.getTextByMonkeyView(group.children[0])
                if notGroup:
                    # print "Info : this is not a group %s !" % notGroup
                    continue
                groupNameView = group.children[1].children[2].children[1]
                item = {
                    'groupName': self.getTextByMonkeyView(groupNameView),
                    'drag':drag,
                    # 363 is qb_troop_list_view.top, 156是整个一条group的高度。
                    # 78 / 182
                    'UILocation': group.top + 78/2 + 182,
                    'index':index,
                    'msgs': [],
                    'storedMsgs': []
                }

                # 点击进入到群组会话中,去获取groupId
                # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。
                # if item['UILocation'] < 370 or item['UILocation'] > 1760:
                if item['UILocation'] < 200 or item['UILocation'] > 760:
                    print "Info : skip this group in case we touch screen incorrectly !"
                    continue
                groupId = ''
                if self.touchByMonkeyPixel([self.emulator['width']/2,item['UILocation']]) == 0:
                    if self.is_group() == 0:
                        for i in range(0,3):
                            groupId = self.get_group_id()
                            if groupId == '':
                                continue
                            else:
                                break
                if groupId == '':
                    print "Error : failed to get the group id for group %s !" % \
                        item['groupName']
                    continue
                else:
                    if groupId in self.groupList.keys():
                        print "Info : this group %s %s has already exist !" % \
                            (item['groupName'],groupId)
                        continue
                self.groupList[groupId] = item
                print "Info : group info: %s , %s , %s , %s, %s !" % \
                    (item['groupName'],groupId,item['drag'],item['index'],item['UILocation'])

            while(self.is_grouplist() != 0):
                self.touch_to_leave()
        print "Info : total group count : %s !" % len(self.groupList)
        for key in self.groupList:
            print "Info : group info: %s , %s , %s , %s, %s !" % \
                (self.groupList[key]['groupName'],key,self.groupList[key]['drag'], \
                    self.groupList[key]['index'],self.groupList[key]['UILocation'])
        
        self.groupListUpdating = 0
        return 0

    # 获取groupId,结束后仍退出至group 界面
    def get_group_id(self):
        # 此时位于群组会话中,点击进入到群组信息里边
        groupId = ''
        if self.touch_to_enter_info() != 0:
            return ''
        for i in range(0,3):       
            try:
                xlist = self.get_hierarchy_view_by_id('id/common_xlistview')
                nameAndId = xlist.children[0].children[2].children[0].children[1]
                groupId = self.getTextByMonkeyView(nameAndId.children[1].children[0])
                break
            except:
                print "Error : failed to get groupId !"
                continue
        print "Info : get this group id : %s !" % groupId
        if self.touch_to_enter_group() == 0:
            return groupId

    def get_group_members(self):
        group_members = []
        is_stop_drag = 0
        last_member = None
        while True:
            screen_members = self.extract_group_members()
            if last_member == screen_members[-1]:
                break
            last_member = screen_members[-1]
            group_members.extend(screen_members)
            self.drag_to_page_down()
        print "Info : group_members:",group_members            
        return group_members

    def extract_group_members(self):
        screen_members = []       
        content = self.get_hierarchy_view_by_id('id/content')
        members_list = content.children[0].children[1].children[0].children
        list_top = 113
        for member in members_list:
            if member.height != 79:
                list_top += member.height
                # 为管理员(4人),C(2人)之类的字样。72 / 33
                continue
            member_location = list_top + 79/2
            if member_location >= 800:
                continue
            self.touchByMonkeyPixel([240,member_location])
            list_top += 79
            qqid = self.get_member_id()
            if qqid in screen_members:
                continue
            screen_members.append(qqid)
        return screen_members

    def get_member_id(self):
        qqid = ''
        content = self.get_hierarchy_view_by_id('id/content')
        tmpqqid = ''
        try:
            tmpqqid = content.children[0].children[0].children[1].children[2].children[1].namedProperties.get('text:mText').value.encode('utf8')
        except:
            return ''
        qqid = tmpqqid.split(' ')[0]
        print "Info : get the member id %s !" % qqid
        self.touch_to_leave()
        sleep(1)
        return qqid

    def check_group_by_possible_location(self,target_group):
        target_group_name = self.groupList[target_group]['groupName']
        possibleDrag = self.groupList[target_group]['drag']
        possibleUILocation = self.groupList[target_group]['UILocation']
        print "Info : possibleDrag %s , possibleUILocation %s to enter group %s !" % \
                (possibleDrag, possibleUILocation, target_group)
        if possibleDrag > 0:
            for i in range(0,possibleDrag):
                self.drag_to_page_down()

        if self.touchByMonkeyPixel([self.emulator['width']/2,possibleUILocation]) == 0:
            if self.is_group() == 0:
                for i in range(0,3):
                    groupId = ''
                    groupId = self.get_group_id()
                    if groupId == target_group:
                        self.currentGroup['groupId'] = target_group
                        self.currentGroup['groupName'] = target_group_name
                        return 0
                    elif groupId != '':
                        print "Info : get the incorrect groupid %s !" % groupId
                        break
                    else:
                        print "Info : get the empty groupid !"
                        continue
                print "Info : failed to enter group %s via possibleDrag %s , possibleUILocation %s !" % \
                        (target_group, possibleDrag, possibleUILocation)
                # 不是这个群,就退出至grouplist界面,然后查找一下当前界面的groups
                view = self.get_current_view()
                if view == 'is_group' or view == 'is_info':
                    self.touch_to_enter_grouplist()
                if self.find_target_group_from_list(target_group) == 0:
                    return 0
                return 3

    def find_target_group_from_list(self,target_group):
        print '------------ find_target_group_from_list ------------'
        if self.is_grouplist() != 0:
            return -1
        target_group_name = self.groupList[target_group]['groupName']
        # < 1s
        qb_troop_list_view = self.get_hierarchy_view_by_id('id/qb_troop_list_view')
        if qb_troop_list_view == None:
            return -1
        _groupList = []
        _groupList = qb_troop_list_view.children
        if _groupList == []:
            print "Error : failed to parse view qb_troop_list_view !"
            return -1

        # first one is the search box
        # 通过高度来判断是否是group item(78)。
        # 而enter_group时通过名字来查找,不需要此步
        # del _groupList[0]
        for group in _groupList:
            # 我创建的群(16) 这样的一行
            notGroup = self.getTextByMonkeyView(group.children[0])
            if notGroup:
                continue

            # 先根据群名称来查找
            groupNameView = group.children[1].children[2].children[1]
            groupName = self.getTextByMonkeyView(groupNameView)
            print "Info : this_group_name : ", groupName
            if groupName != target_group_name.encode('utf8'):
                continue

            # 363 is qb_troop_list_view.top, 156是整个一条group的高度。# 78 / 182
            UILocation = group.top + 78/2 + 182
            # groupName对了,然后看groupId。暂时不要去解析groupName,耗时
            # 第一个和最后一个群组的uilocation需要额外处理,以防点到屏幕外边去了。
            if UILocation < 200 or UILocation > 760:
                print "Info : skip this group in case we touch screen incorrectly !"
                continue
            # 0.5s
            if self.touchByMonkeyPixel([self.emulator['width']/2,UILocation]) == 0:
                if self.is_group() == 0:
                    for i in range(0,3):
                        groupId = ''
                        groupId = self.get_group_id()
                        if groupId == target_group:
                            self.currentGroup['groupId'] = target_group
                            self.currentGroup['groupName'] = target_group_name
                            self.groupList[target_group]['UILocation'] = UILocation
                            return 0
                        elif groupId != '':
                            print "Info : get the incorrect groupid %s !" % groupId
                            break
                        else:
                            print "Info : get the empty groupid !"
                            continue
        print "Error : failed to find the target group",target_group
        return -1

    def register_monkey(self):
        print '------------ register_monkey ------------'
        groupList = [{'groupId': key, 'groupName': value['groupName']} 
                     for key, value in self.groupList.iteritems()]
        data = {
            'cmd': 'register',
            'qq': self.qq['qqId'],
            'qqName': self.qq['qqName'],
            'url':self.qq['url'],
            'groupList': json.dumps(groupList)
        }
        url_post(self.qq['robot_url'], data)
        return 0

    def heartbeat_monkey(self):
        print '------------ heartbeat_monkey ------------'
        self.touchByMonkeyPixel(self.emulator['heartbeat'])
        groupList = [{'groupId': key, 'groupName': value['groupName']}
                     for key, value in self.groupList.iteritems()]
        data = {
            'cmd': 'heartbeat',
            'qq': self.qq['qqId'],
            'qqName': self.qq['qqName'],
            'url':self.qq['url'],
            'groupList': json.dumps(groupList)
        }
        url_post(self.qq['robot_url'], data)
        return 0

    def monkey_task_loop(self):
        print '------------ monkey_task_loop start ------------'
        # this should never return        
        while(1):
            # if self.is_home_screen() != 0:
                # continue
            sleep(1)
            if self.screenUsing == 0:
                self.heartbeat += 1
                if self.heartbeat == 1200:
                    # self.get_pure_group_list_monkey()
                    # if self.groupList != {}:
                        # self.write_grouplist()
                    self.heartbeat_monkey()
                    self.heartbeat = 0
            else:
                self.heartbeat = 0


    ### api for robot manager ###

    # 此处,不考虑UILocation
    def enter_group(self,data):
        t1=time()
        target_group = data['group']
        target_group_name = self.groupList[target_group]['groupName']
        print '------------ enter_group : %s %s' % (target_group_name.encode('utf8'),target_group)

        if self.groupListUpdating == 1:
            print "Info : groupList is updating now ! Please wait about 2 minutes !"
            return 1
        if target_group not in self.groupList:
            print "Error : failed to find in the grouplist %s !" % target_group
            return 2
        # 每次从main界面进入
        self.touch_to_enter_main()
        if self.touch_to_enter_grouplist() != 0:
            print "Error : failed to touch_to_enter_grouplist !"
            return 3
        t_tmp=time()
        print "Info : it takes %s time to enter grouplist" % str(t_tmp-t1)

        # 通过possibleDrag来缩小查找范围。然后从该页的自己、前、后 三个界面查找。
        # 下一步,可以通过possibleIndex,在自己界面进一步缩小查找范围。
        #       在前界面,从后往前查找;在后界面,从前往后查找。

        # 0
        if self.check_group_by_possible_location(target_group) == 0:
            t2=time()
            print "Info : it takes %s time to enter group" % str(t2-t1)
            return 0
        # -1
        # 向上drag一次,possibledrag非0时候
        # self.device.drag((1080/2, 400),(1080/2, 1700),0.2,1)
        view = self.get_current_view()
        if view == 'is_group' or view == 'is_info':
            self.touch_to_enter_grouplist()
        if self.is_grouplist() == 0:
            self.drag_to_page_up()
            if self.find_target_group_from_list(target_group) == 0:
                t2=time()
                print "Info : it takes %s time to enter group" % str(t2-t1)
                return 0
        # 2
        # 向下drag一次
        # self.device.drag((1080/2, 1700),(1080/2, 400),0.2,1)
        # self.device.drag((1080/2, 1700),(1080/2, 400),0.2,1)
        view = self.get_current_view()
        if view == 'is_group' or view == 'is_info':
            self.touch_to_enter_grouplist()
        if self.is_grouplist() == 0:        
            self.drag_to_page_down()
            self.drag_to_page_down()
            if self.find_target_group_from_list(target_group) == 0 :
                t2=time()
                print "Info : it takes %s time to enter group" % str(t2-t1)
                return 0
        print "Error : failed to enter group %s !" % target_group
        return -1

    def send_msg(self,data):
        if not data.get('msg'):
            return 1
        msg = data['msg']
        print '------------ send_msg %s' % msg
        print ">>>send_msg 1 ",time()
        if self.is_group() != 0 :
            view = self.get_current_view()
            if view == 'is_info':
                self.touch_to_enter_group()
            else:
                print "Info : I am in the view %s !" % view
                return 1
        print ">>>send_msg 2 ",time()  
        get_encoded_character(self.qq['deviceid'], msg.decode('utf8'))
        # self.restart_qq_monkey()
        print ">>>send_msg 3 ",time()
        # self.easy_device.touch(input_location, self.easy_device.DOWN)
        self.device.touch(self.emulator['input'][0],self.emulator['input'][1],MonkeyDevice.DOWN)
        sleep(1)
        # self.easy_device.touch(input_location, self.easy_device.UP)
        self.device.touch(self.emulator['input'][0],self.emulator['input'][1],MonkeyDevice.UP)
        self.touchByMonkeyPixel(self.emulator['paste'])
        print ">>>send_msg 4 ",time()
        self.touchByMonkeyPixel(self.emulator['send'])
        # # 1s
        # inputid = None
        # try:
        #     inputid = self.get_hierarchy_view_by_id('id/input')
        # except:
        #     print "Error : failed to find view id/input !"
        #     return 2
        # print ">>>send_msg 5 ",time()            
        # if inputid:
        #     text = self.getTextByMonkeyView(inputid)
        #     print "Info : get msg %s from clipboard !" % text
        #     if text.strip().split() == msg.strip().split():
        #         print ">>>send_msg 6 ",time()
        #         # 1s
        #         if self.touchByMonkeyId('id/fun_btn') == 0:
        #         # if self.touchByMonkeyPixel(970,1700) != 0:
        #             print "Info : send msg %s ok !" % msg
        #             print ">>>send_msg 7 ",time()
        #             return 0
        #     else:
        #         delete_code = "input keyevent KEYCODE_DEL"
        #         inputid = self.get_hierarchy_view_by_id('id/input')
        #         self.device.touch(350,750,'DOWN_AND_UP')
        #         while( self.getTextByMonkeyView(inputid) ):
        #             print "Info : delete the incorrect string !"
        #             for i in range(0,20):
        #                 self.device.shell(delete_code)
        #             inputid = self.get_hierarchy_view_by_id('id/input')
        #         print "Error : failed to send msg %s , Incorrect msg !" % msg
        #         return 3

    def get_msgs(self,data):
        print '------------ get_msgs ------------'
        if self.is_group() != 0 :
            view = self.get_current_view()
            if view == 'is_info':
                self.touch_to_enter_group()
            else:
                print "Info : I am in the view %s !" % view
                return 1
        self.currentGroup['msgs'] = []
        dragCount = 3
        msgs = []
        # is_stop_drag = 0
        for msgDrag in range(0, dragCount):
            # if is_stop_drag:
            #     break
            if msgDrag !=0:
                # self.device.drag((1080/2, 500),(1080/2, 1550),0.1,1)
                self.drag_to_page_up()

            hViewer = None
            _msgs = []
            try:
                listView1 = self.get_hierarchy_view_by_id('id/listView1')
                # 该行会出现AttributeError: 'NoneType' object has no attribute 'children
                _msgs = listView1.children
            except:
                print "Error : failed to parse view : listView1 !"

            # print 'msgs count : ', len(_msgs)-1 #最后一个为输入框
            # reverse()不可用java.Arraylist
            tmpMsgs = []
            for m in _msgs:
                tmpMsgs.insert(0, m)
            for m in tmpMsgs:
                if 'BaseChatItemLayout' not in str(m):
                    continue
                item = {}
                item['nickname'] = ''
                layoutLeft = ''
                for t in m.children:
                    if t.id == 'id/chat_item_head_icon':
                        # < 1s
                        layoutLeft = t.namedProperties.get('layout:mLeft').value.encode('utf8')
                        if layoutLeft == self.emulator['self_msg']:
                            break
                    if t.id == 'id/chat_item_nick_name':
                        item['nickname'] = self.getTextByMonkeyView(t)
                    if t.id == 'id/chat_item_content_layout':
                        item['content'] = self.getTextByMonkeyView(t)
                # 自己发送的消息
                if layoutLeft == self.emulator['self_msg']:
                    continue
                else:
                    if item['nickname'].endswith(':'):
                        item['nickname'] = item['nickname'][0:-1]

                # #此处时间暂不考虑如 Friday 10:46 的情况
                # c = self.getDescByMonkeyView(m)
                # item['time'] = c[0:c.find(' ')]
                
                # 添加每条消息的drag次数
                item['drag'] = msgDrag

                # # 已存储的消息,则没有必要往前drag了。
                # # if item in self.currentGroup['storedMsgs']:
                # #     is_stop_drag = 1
                # #     break
                # store_this_msg = 0
                # for i in self.currentGroup['storedMsgs']:
                #     if i['content'] == item['content'] and i['nickname'] == item['nickname']:
                #         is_stop_drag = 1
                #         store_this_msg = 1
                #         break
                # if store_this_msg == 1:
                #     continue
                # 未存储,则为新消息.如前一次drag已得到,则跳过.
                has_this_msg = 0
                for j in msgs:
                    if j['content'] == item['content'] and j['nickname'] == item['nickname']:
                        has_this_msg = 1
                        break
                if has_this_msg == 1:
                    continue
                msgs.append(item)
        # 针对新消息的提示处理。                
        for i in range(0,4):
            # self.device.drag((1080/2, 1550),(1080/2, 500),0.1,1)
            self.drag_to_page_down()

        if msgs:
            self.currentGroup['msgs'] = msgs
            print "Info : new msgs count : %s !" % len(msgs)
            for m in self.currentGroup['msgs']:
                print m['nickname'], m['content'], m['drag']
            # default: store the last 10 msgs
            self.currentGroup['storedMsgs'] += self.currentGroup['msgs']            
            print 'Info : stored msgs count ', len(self.currentGroup['storedMsgs'])
            if len(self.currentGroup['storedMsgs']) > 10:
                self.currentGroup['storedMsgs'] = self.currentGroup['storedMsgs'][-10:]
            self.groupList[self.currentGroup['groupId']]['storedMsgs'] = self.currentGroup['storedMsgs']
            # for n in self.currentGroup['storedMsgs']:
                # print n['nickname'], n['content']
      
        return self.currentGroup['msgs']                
Beispiel #50
0
from com.android.hierarchyviewerlib.models import ViewNode
#这个函数时确认年月日时分秒
now=time.strftime("%Y-%m-%d-%H-%M-%S")
#指定我们要保存图片的位置和打印log的位置
path='C:\\pic\\'
logpath="C:\\log\\"

#python中获取当前运行的文件的名字
name=sys.argv[0].split("\\")
filename=name[len(name)-1]

#新建一个log文件
log=open(logpath+filename[0:-3]+"-log"+now+".txt",'w')
#连接设备,两个参数分别是等待的时间(这里的时间都是秒为单位),设备的序列号。169.254.105.102:5555    device
device=MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device)
#启动activity
device.startActivity(component='com.android.calculator2/.Calculator')
MonkeyRunner.sleep(3)

#通过坐标执行1+2并截图
#device.touch(156,1354,'DOWN_AND_UP')
easy_device.touch(By.id('id/digit1'),MonkeyDevice.DOWN_AND_UP)
MonkeyRunner.sleep(1)
result1=device.takeSnapshot()
result1.writeToFile(path+"button-1"+'.png','png')

#device.touch(900,1604,'DOWN_AND_UP')
easy_device.touch(By.id('id/plus'),MonkeyDevice.DOWN_AND_UP)
MonkeyRunner.sleep(1)
result2=device.takeSnapshot()
Beispiel #51
0
def jisuanji():

    # 滑动解锁
    jiesuo()

    # 打开计算器
    device.startActivity(component="com.tencent.qrom.calculator/com.tencent.qrom.calculator.Calculator")
    time.sleep(1)
    print ("ok")

    # 将device对象包装成EasyMonkeyDevice类对象

    ed = EasyMonkeyDevice(device)
    print ("okok")

    # 96*3=
    ed.touch(By.id("id/digit9"), MonkeyDevice.DOWN_AND_UP)

    ed.touch(By.id("id/digit6"), MonkeyDevice.DOWN_AND_UP)

    ed.touch(By.id("id/mul"), MonkeyDevice.DOWN_AND_UP)

    ed.touch(By.id("id/digit3"), MonkeyDevice.DOWN_AND_UP)

    ed.touch(By.id("id/equal"), MonkeyDevice.DOWN_AND_UP)

    print ("ok2")

    # 通过ID获取mText
    h = ed.getText(By.id("id/digit9"))

    print (h)