コード例 #1
0
ファイル: deviceHandler.py プロジェクト: BeeeOn/android
    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()
コード例 #2
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
コード例 #3
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)
コード例 #4
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
コード例 #5
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'
コード例 #6
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 = []
コード例 #7
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')
コード例 #8
0
ファイル: monkeyUser.py プロジェクト: LiZoRN/flyadb
 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)
コード例 #9
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)
コード例 #10
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"
コード例 #11
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
コード例 #12
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
コード例 #13
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 ')
コード例 #14
0
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")
コード例 #15
0
ファイル: Test09.py プロジェクト: louiezhou/Monkeyrunner-1
# 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')
コード例 #16
0
 def initEasyDevice(self):
     self.easyDevice = EasyMonkeyDevice(self.device)
コード例 #17
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)
コード例 #18
0
def ESC_key():
    signal.signal(signal.SIGINT, exitGracefully)
    global edevice

    edevice = EasyMonkeyDevice(device)
    edevice.press('KEYCODE_BACK', md.DOWN_AND_UP)
コード例 #19
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)
コード例 #20
0
ファイル: ua_test.py プロジェクト: gitghought/ua_android_test
 def getEasyDevice(self, dev):
     self.eDevice = EasyMonkeyDevice(dev)
     return self.eDevice
コード例 #21
0
#! /usr/bin/env python
'''
Copyright (C) 2012  Diego Torres Milano
Created on Sep 8, 2012
@author: diego
@see: http://code.google.com/p/android/issues/detail?id=36544
'''
import re
import sys
import os
# This must be imported before MonkeyRunner and MonkeyDevice,
# otherwise the import fails.
# PyDev sets PYTHONPATH, use it
try:
    for p in os.environ['PYTHONPATH'].split(':'):
        if not p in sys.path:
            sys.path.append(p)
except:
    pass
try:
    sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'],
                                 'src'))
except:
    pass
from androidviewclient3.viewclient import ViewClient
device, serialno = ViewClient.connectToDeviceOrExit()
FLAG_ACTIVITY_NEW_TASK = 0x10000000
# We are not using Settings as the bug describes because there's no WiFi dialog in emulator
#componentName = 'com.android.settings/.Settings'
componentName = 'com.dtmilano.android.sampleui/.MainActivity'
コード例 #22
0
device.touch(400,600,MonkeyDevice.DOWN_AND_UP)
device.touch(400,1000,MonkeyDevice.DOWN_AND_UP)

image2 = device.takeSnapshot()
subimage2 = image.getSubImage((300,50,356,234))

if (subimage2.sameAs(subimage,0.8)):
	print '[PASS] the result of 3*8 and 4*6 is equal!'
else:
	print '[Fail] the result of 3*8 and 4*6 is not equal!'

print '******Case2: Use EasyMonkeyDevice to check claculator result******'

print '---- calculator 5*7 with EasyMonkeyDevice touch'

easy = EasyMonkeyDevice(device)
easy.touch(By.id('id/digit5'),MonkeyDevice.DOWN_AND_UP)
easy.touch(By.id('id/mul'),MonkeyDevice.DOWN_AND_UP)
easy.touch(By.id('id/digit7'),MonkeyDevice.DOWN_AND_UP)
easy.touch(By.id('id/equal'),MonkeyDevice.DOWN_AND_UP)


hv=device.getHierarchyViewer()
view = hv.findViewById('id/display')
str =view.children[1].namedProperties.get('text:mText').toString().encode('utf8')

if (str == '35'):
	print '[PASS] the result of 5*7 is correct!'
else:
	print '[Fail] the result of 5*7 is correct! the result is -- ' +str