def enter_permission(y,device):
	device.touch(300,y,MonkeyDevice.DOWN_AND_UP)
	msSleep()
	device.touch(450,80,MonkeyDevice.DOWN_AND_UP)
	MonkeyRunner.sleep(2)
	device.touch(290,80,MonkeyDevice.DOWN_AND_UP)
	msSleep()
def typeInPhNumber(pn, device):
	#print "> Entering phone number..."
	mft = device.shell('getprop ro.product.manufacturer')

	if mft.strip() == "HTC":
		keycode = 'KEYCODE_DPAD_RIGHT'
	else:
		keycode = 'KEYCODE_TAB'
	
	if 10 == len(pn) and pn.isdigit():
	
		MonkeyRunner.sleep(2)
		for c in pn[0:3]:
			device.type(c)
		
		device.press(keycode, MonkeyDevice.DOWN_AND_UP)
		for c in pn[3:6]:
			device.type(c)
			
		device.press(keycode, MonkeyDevice.DOWN_AND_UP)
		for c in pn[6:10]:
			device.type(c)
			
	else:
		print ">  ERROR:  not a 10 digit number"
Exemple #3
0
def call_video(d):
    uri = ('http://samplemedia.linaro.org/H264/'
           'big_buck_bunny_480p_H264_AAC_25fps_1800K.MP4')
    d.startActivity(uri=uri, component="com.android.browser/.BrowserActivity")
    MonkeyRunner.sleep(5.0)
    d.press('KEYCODE_BUTTON_SELECT', MonkeyDevice.DOWN_AND_UP)
    take_snapshot(d)
def operateRR():
    # Launches the app
    runComponent = PKG_NAME + '/' + ACTIVITY
    device.startActivity(component=runComponent)
    MonkeyRunner.sleep(5)
  
    touchDownUp(0.86, 0.94) # login
    touchDownUp(0.5, 0.146)
    device.type('*****@*****.**')
    touchDownUp(0.5, 0.29)
    device.type('J8d5b324')
    touchDownUp(0.5, 0.38)
    touchDownUp(0.5, 0.85, 2) # start

    touchDownUp(0.3, 0.08, 2)
    touchDownUp(0.5, 0.28)

    begin = time.time()
    last = takeSnapshot(0.3, 0.35, 0.4, 0.1)
    while True:
        for i in range(5):
            dragVertically(0.9, 0.23)
        print "  %f" % (time.time() - begin)
        now = takeSnapshot(0.3, 0.35, 0.4, 0.1)
        if now.sameAs(last):
            break
        else:
            last = now
    print "[Sestet] \t%f" % (begin - g_begin)
    MonkeyRunner.sleep(5)
    return
def testSnapshot(doinstall=True):
    if doinstall:
        print "building application..."
        subprocess.call(['./gradlew', 'assembleMonkeyDebug'])

        print "installing application..."
        device.installPackage('app/build/outputs/apk/app-monkey-debug.apk')
    
    print "launching application..."
    device.startActivity(component=RUNCOMPONENT)
    MonkeyRunner.sleep(1)

    print "taking snapshot..."
    screenshot = device.takeSnapshot()
        
    # uncomment the following line to update the reference image
    # screenshot.writeToFile(REF)

    print "retrieving reference snapshot..."
    reference = MonkeyRunner.loadImageFromFile(REF)


    print "comparing snapshots..."
    same = False
    try:
        same = screenshot.sameAs(reference, ACCEPTANCE)
    except:
        print "Unexpected error:", sys.exc_info()[0]

    if not same:
        print "comparison failed, getting visual comparison..."
        screenshot.writeToFile(SCR)
        subprocess.call(["/usr/local/bin/compare", REF, SCR, CMP])
        sys.exit(1)
def GoToUrl(url, urltextbox, device):

	if(1 != isInternetOn(device)):
		print"> WARNING:  No internet connection detected"
		sys.exit(0)
		
	OpenBrowser(device)
	MonkeyRunner.sleep(8)
	ScrollUp(device)
	h,w = FindScreenSize(device)
	
	
	#--------------- Sikuli find subimage ---------------
	isfound, xClick, yClick = findSubimageClickLocation(urltextbox,device)
	if(isfound):
		device.touch(int(int(w)/2), yClick, 'DOWN_AND_UP')
		MonkeyRunner.sleep(2)
		
		#==========  for HTC browsers only =================
		mft = getDeviceMft(device)
		if 'HTC' in mft:
			for i in range(1,14):
				device.press('KEYCODE_DEL', MonkeyDevice.DOWN_AND_UP)
		MonkeyRunner.sleep(1)
		#=========================================================	
	
		for c in url:  # 1/14 - sometimes this may not work and trigger other events.  reboot phone.
			device.type(c)
	else:
		print"> ERROR:  couldn't find URL textbox"
		sys.exit(0)
		
	MonkeyRunner.sleep(3)
	device.press('KEYCODE_ENTER', MonkeyDevice.DOWN_AND_UP)
	MonkeyRunner.sleep(15)
Exemple #7
0
 def deleteContact(self):
     #get Device connection
     #device = UtilTool.connectToDevice()
     #lanuch Contacts app
     #device.startActivity(component='com.android.contacts/.activities.PeopleActivity')
     #MonkeyRunner.sleep(15)
     #vc = ViewClient(device,'emulator-5554')
     #get device connection
     device = UtilTool.connectToDevice()
     #init the testing environment
     vc = UtilTool.init(device)
     print 'test environment is ready'
     print 'Starting to delete contact one by one'
     for i in range(0,2):
         MonkeyRunner.sleep(15)
         vc.dump()
         c = vc.findViewWithText('Contact00'+str(i))
         c.touch()
         MonkeyRunner.sleep(2)
         device.press('KEYCODE_DEL',MonkeyDevice.DOWN_AND_UP)
         MonkeyRunner.sleep(15)
         vc.dump()
         but_confirm = vc.findViewWithText('OK')
         but_confirm.touch()
         MonkeyRunner.sleep(10)
         print 'Contact00'+str(i)+'is being deleted'
     MonkeyRunner.sleep(10)
     vc.dump()
     contacts_number = vc.findViewWithText('No contacts.')
     text = contacts_number.getText()
     if text=='No contacts.':
         print 'passed'
     else:
         print 'failed'
     device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
def image_diff(imageA, imageB):
    # See http://rosettacode.org/wiki/Percentage_difference_between_images
    i1 = MonkeyRunner.loadImageFromFile(imageA)
    if not os.path.isfile(imageB):
        return True
    i2 = MonkeyRunner.loadImageFromFile(imageB)
    return i1.sameAs(i2, 0.9)
Exemple #9
0
 def __call__(self, number = '10086', sleepSec = 0.01):
     print '========== Dial number: (%s) ==========' % number
     if DialNumber.keyNumPadDict is None:
         DialNumber.initKeyNumPadDict()
     for c in number:
         self.phone._device.press(DialNumber.keyNumPadDict[c], MonkeyDevice.DOWN_AND_UP)
         MonkeyRunner.sleep(sleepSec)
Exemple #10
0
def firstAddContact(device):
    Log('choose create new contact')
    device.touch(200,310,'DOWN_AND_UP')
    MonkeyRunner.sleep(3)
    Log('contacts information will keep local')
    device.touch(140,480,'DOWN_AND_UP')
    MonkeyRunner.sleep(3)
Exemple #11
0
def smokeTestAllApps(device):
    allApps(device)
    for i in range(5):# 5 screens
        for j in range(3): #3 series
            for k in range(6): #6 itemes
                logging.info("Smoke Test %s_%s_%s" % (i, k, j))
                # self.device.shell("logcat -c")
                x = 70+130*k
                y = 200+100*j
                if(i and k==0): swipeLeft(device)
                MonkeyRunner.sleep(2.5)
                device.touch(x, y, MonkeyDevice.DOWN_AND_UP)
                MonkeyRunner.sleep(5.0)

                # s = self.device.shell("logcat -d")
                # s = "None" if s is None else s.encode("utf-8")
                # f = open("log_%s_%s_%s.txt" % (i, k, j), 'w')
                # f.write(s)
                # f.close()

                image = device.takeSnapshot()
                image.writeToFile("img_%s%s%s.png" % (i, k, j), "png")
                allApps(device)
                swipeLeft(device, i)
    return True
def camera_open_test(device):	
	# reboot phone for camera first open	
	print "Phone will reboot!!!"
	device.reboot()
	
	MonkeyRunner.sleep(sleep_time)
	
	# open log
	print "open log:"
	if platform:
		qcom_log_open(device)
	else:
		mtk_log_open(device)

	# first open camera
	print "First open Camera!"
	Camera_open(device)
	
	# open camera
	print "open Camera!"
	Camera_kill_and_start(device)
	
	# back open camera
	print "Back and open Camera!"
	Camera_back_and_start(device)
	
	# home open camera
	print "Home and open Camera!"
	Camera_home_and_start(device)
	
	# close camera
	print "close camera!"
	Camera_kill(device)
Exemple #13
0
def setpos(runComponent):
	global device
	global pos_title
	global pos_go
	global pos_home
	
#	getpos(pos_home,'id/0x8f90000',runComponent)
	getpos(pos_title,'id/0x2012',runComponent)
	#id/go is on anathor view
	device.touch(pos_title['x'],pos_title['y'],"DOWN_AND_UP")
	#wait for keyboard ready
	MonkeyRunner.sleep(1.0)
	#input anything to make the 'go' visiable
	device.type('a')
	getpos(pos_go,'id/cancel',runComponent)
	#close keyboard
	device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
	#back to home
	device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)

	#because there is something bug of id for uc,the bottom buttons have same id/0x8f90000
	#get screen width and height
	w=int(device.getProperty('display.width'))
	h=int(device.getProperty('display.height'))
	pos_home['x']=int(0.9*w)
	pos_home['y']=h-5
Exemple #14
0
def finishOperation(index, threshod = 0.95, interval = 0.2):
  MonkeyRunner.sleep(interval)
  state = takeSnapshot()
  while (not targets[index].sameAs(state, threshod)):
    MonkeyRunner.sleep(interval)
    state = takeSnapshot()
  return
Exemple #15
0
def operateMap():
  # Launches the app
  #runComponent = PKG_NAME + '/' + ACTIVITY
  #device.startActivity(component=runComponent)
  
  # touches the input box
  touchDownUp(0.4, 0.08, 4)
  # inputs place
  MonkeyRunner.sleep(2)
  device.type("Tsinghua")
  MonkeyRunner.sleep(3)
  
  touchDownUp(0.9, 0.17, 0)
  waitToFinish()
  
  # zoom in
  for i in range(3):
    touchDownUp(0.92, 0.76, 0.5)
  waitToFinish()
  
  for i in range(4):
    # restore
    touchDownUp(0.92, 0.83, 0.5)
  
  for i in range(6):
    touchDownUp(0.92, 0.83)
    waitToFinish()
  
  #device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
  #touchDownUp(0.85, 0.84)
  #touchDownUp(0.2, 0.6)
  print "Finished."
  return
Exemple #16
0
def getpos(pos,tag,runComponent):
	global device
	viewer = device.getHierarchyViewer()
	time=2.5
	while(viewer==None):
		#wait for browser ready
		time=time*2
		MonkeyRunner.sleep(time)
		viewer = device.getHierarchyViewer()
		if(viewer==None and time>20):
			#restart browser
			device.startActivity(component = runComponent)
		elif(viewer==None and time>50):
			print "get Hierarchy Viewer error\n"
			logging.error('get Hierarchy Viewer error\n')
			sys.exit(1)			
	view = viewer.findViewById(tag)
	time=2.5
	while(view==None):
		time=time*2
		MonkeyRunner.sleep(time)
		view = viewer.findViewById(tag)
		if(view==None and time>20):
			print "get Hierarchy Viewer error\n"
			logging.error('get Hierarchy Viewer error\n')
			sys.exit(1)	
	position=viewer.getAbsoluteCenterOfView(view)
	pos['x']=position.x
	pos['y']=position.y
Exemple #17
0
def fight():
	global d
	invoke_hero()
	MonkeyRunner.sleep(0.5)	
	call_all_skill()
	MonkeyRunner.sleep(0.5)	
	max_hero_level()
Exemple #18
0
def max_hero_level():
	global d
	d.touch(1350, 1000, "DOWN_AND_UP") # change to hero
	MonkeyRunner.sleep(0.5)	
	for _ in range(50):
		touch_bottom()
		MonkeyRunner.sleep(0.1)	
Exemple #19
0
def main():
    if len(sys. argv) < 2:
        print "please input the device id"
        sys.exit(0)

    timeout_val = 5

    for dev_id in sys.argv[1:]:
        device = MonkeyRunner.waitForConnection(timeout=timeout_val,
                                                deviceId=dev_id)

        if not device:
            print "connect to the device timeout"
            sys.exit()
        else:
            print "connect to the device: " + dev_id

        #clean the enviroment
        init(device)

        # Wake up the screen and unlock
        device.shell("svc power stayon true;input keyevent 82")

        print "run %s..." % module_name
        package = "com.android.deskclock"
        activity = ".DeskClock"
        runComponent = package + '/' + activity
        device.startActivity(component=runComponent)
        MonkeyRunner.sleep(5)
        take_snapshot(device)
        device.press("KEYCODE_HOME", MonkeyDevice.DOWN_AND_UP)
        MonkeyRunner.sleep(2)
        take_snapshot(device)
    def __init__(self, logger, device_name=None):
        self.class_name = "MonkeyRunnerImpl"
        ## command map
        self.CMD_MAP = {"TOUCH": lambda dev, arg: dev.touch(**arg),
                        "DRAG": lambda dev, arg: dev.drag(**arg),
                        "PRESS": lambda dev, arg: dev.press(**arg),
                        "TYPE": lambda dev, arg: dev.type(**arg),
                        "SLEEP": lambda dev, arg: MonkeyRunner.sleep(**arg)
                        }

        self.PhysicalButton={"HOME": "KEYCODE_HOME", 
                             "SEARCH": "KEYCODE_SEARCH", 
                              "MENU": "KEYCODE_MENU", 
                              "BACK": "KEYCODE_BACK", 
                              "POWER": "KEYCODE_POWER",
                              "DPAD_UP": "DPAD_UP", 
                              "DPAD_DOWN": "DPAD_DOWN", 
                              "DPAD_LEFT": "DPAD_LEFT", 
                              "DPAD_RIGHT": "DPAD_RIGHT", 
                              "DPAD_CENTER": "DPAD_CENTER", 
                              "ENTER": "enter"
                            }
        self.action_type_list=["DOWN", "UP", "DOWN_AND_UP"]
        self.action_down = "DOWN"
        self.action_up = "UP"
        self.action_down_and_up = "DOWN_AND_UP"
        
        self.m_logger = logger
                
        if None!=device_name:
            self.device = MonkeyRunner.waitForConnection(deviceId=device_name)
        else:
            self.device = MonkeyRunner.waitForConnection()
Exemple #21
0
def run():
    clickX = 360
    click_y = 215
    num_conv = 8
    height_conv = 130
    for idx in range(0,20):
        print("go Chatroom "+str(idx))
        if (idx < num_conv):
            click(clickX,click_y + height_conv * idx)
        else:
            moveVertify(height_conv)
            MonkeyRunner.sleep(1)
            click(clickX,1080)
        MonkeyRunner.sleep(3)
        clickRightCorner()
        name = getFrontActivityName()
        if (name == ACTIVITY_CHATROOMINFO ):
            clickRightCorner()
            for i in range(0,120):
                if addFriendInChatroom(i) == False:
                    break
        else:
            print("Activity name unfit ")
            clickBack()
        print('exit Chatroom')
        clickBack()
    def pressLoginButton(self):

        # wait for 5 seconds
        MonkeyRunner.sleep(5)

        self.device.touch(963, 171, MonkeyDevice.DOWN_AND_UP)
        MonkeyRunner.sleep(1)
def main(argv):
  # Parse options.
  parser = OptionParser()
  parser.add_option("--serial", dest="serial",
                    help="connect to device with specified SERIAL",
                    metavar="SERIAL")
  parser.add_option("--file", dest="filename",
                    help="write screenshot to FILE",
                    metavar="FILE", default="Screenshot.png")
  parser.add_option("--timeout", dest="timeout",
                    help="TIMEOUT in seconds for connecting to a device",
                    metavar="TIMEOUT", default=120)
  (options, args) = parser.parse_args(argv)

  # Connect to the current device, returning a MonkeyDevice object.
  # Monkeyrunner fails with a NullPointerException if options.serial is None.
  if options.serial:
    device = MonkeyRunner.waitForConnection(options.timeout, options.serial)
  else:
    device = MonkeyRunner.waitForConnection(options.timeout)

  if not device:
    return 1

  # Grab screenshot and write to disk.
  result = device.takeSnapshot()
  result.writeToFile(options.filename, 'png')
  return 0
Exemple #24
0
def swipe_back(number):
	for n in range(0,number):
		if lang == 'he':
			device.drag(((screen_width)*2/3, screen_height/2),((screen_width)/3,screen_height/2),0.15,5)
		else:
			device.drag((screen_width/3, screen_height/2),((screen_width)*2/3,screen_height/2),0.15,5)
		print "[Action] swipe"
		MonkeyRunner.sleep(1)
 def sleep(self, time_sec):
     try:
         MonkeyRunner.sleep(time_sec)
         return True
     except Exception, e:
         msg = "[%s] Failed to sleep [%s]" %(self.class_name, str(e))
         self.m_logger.error(msg)
         return False
Exemple #26
0
def sleep(duration = 1):
	'''
	Monkey sleep
	
	@type duration: int
	@param duration: how long to sleep
	'''
	MonkeyRunner.sleep(duration)
Exemple #27
0
 def back_to_home(self):
     """check if the screen is on or not"""
     self._logger.debug("Back to home screen.")
     for backtimes in range(6):
         self._device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
         MonkeyRunner.sleep(0.2)
     self._device.press('KEYCODE_HOME', MonkeyDevice.DOWN_AND_UP)
     MonkeyRunner.sleep(1)
def take_Snapshot():
	# sleep 3's
	MonkeyRunner.sleep(5)
		# Takes a screenshot 
	result = device.takeSnapshot()
	# Writes the screenshot to a file 
	c_time = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
	result.writeToFile('./shotbegin' + c_time + '.png','png')
Exemple #29
0
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')
# Imports the monkeyrunner modules
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

# Alert the user a MonkeyRunner script is about to execute
MonkeyRunner.alert("Monkeyrunner about to execute", "Monkeyrunner", "OK")

# Connects to the current emulator
emulator = MonkeyRunner.waitForConnection()

# Install the Android app package and test package
emulator.installPackage(
    'C:\\Users\\James White\\Desktop\\Exercise Files\\04_02\\04_02_end\\app\\build\\outputs\\apk\\app-debug-unaligned.apk'
)
emulator.installPackage(
    'C:\\Users\\James White\\Desktop\\Exercise Files\\04_02\\04_02_end\\app\\build\\outputs\\apk\\app-debug-androidTest-unaligned.apk'
)

# sets a variable with the package's internal name
package = 'com.mycompany.example.myapplication'

# sets a variable with the name of an Activity in the package
activity = 'com.mycompany.example.myapplication.MainActivity'

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

# Runs the component
emulator.startActivity(runComponent)

# wait for the screen to fully come up
MonkeyRunner.sleep(2.0)
Exemple #31
0
#!/usr/bin/python
# -*- coding:utf8 -*-

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

# 连接设备
device = MonkeyRunner.waitForConnection(3, '1849cdbf')

# 启动App
device.startActivity('com.android.browser/com.android.browser.BrowserActivity')
MonkeyRunner.sleep(2)

# 点击搜索框
device.touch(409, 351, 'DOWN_AND_UP')
MonkeyRunner.sleep(1)

#输入查询词
device.type('test')
MonkeyRunner.sleep(1)

#点击回车键
#device.press('KEYCODE_ENTER','DOWN_AND_UP')
#MonkeyRunner.sleep(1)

#点击搜索按钮
device.touch(982, 143, 'DOWN_AND_UP')
MonkeyRunner.sleep(6)

#截图
image = device.takeSnapshot()
image.writeToFile('./test.png', 'png')
#!/user/bin/python
# coding=utf-8
#-*-UTF-8-*-
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# MonkeyRunner.alert('Hello mook friends','This is title',"OK")
#连接设备
device = MonkeyRunner.waitForConnection(3, "W8R0215A16001204")
#启动APP
device.startActivity("com.tianyancha.skyeye/.activity.SplashActivity")
MonkeyRunner.sleep(9)
#点击首页搜索框
device.touch(400, 480, "DOWN_AND_UP")
MonkeyRunner.sleep(1)
#点击搜索中间页搜索框
device.touch(420, 140, "DOWN_AND_UP")
MonkeyRunner.sleep(1)
#输入查询词
device.type('test')
MonkeyRunner.sleep
#点击回车键
device.press('KEYCODE_ENTER', 'DOWN_AND_UP')
MonkeyRunner.sleep(1)
#点击排序按钮
device.touch(1000, 140, "DOWN_AND_UP")
MonkeyRunner.sleep(6)
#截图
image = device.takeSnapshot()
image.writeToFile('C:/Users/Edianzu/Desktop/test.png', 'png')
Exemple #33
0
 def __init__(self, apk_path, package_name, data_app_name):
     self.apk_path = apk_path
     self.package_name = package_name
     self.data_app_name = data_app_name
     self.device = MonkeyRunner.waitForConnection()
Exemple #34
0
apk = '/home/serso/projects/java/android/calculatorpp/calculatorpp/misc/other/tmp/2012.11.25/calculatorpp.apk'
package = 'org.solovyev.android.calculator'
activity = 'org.solovyev.android.calculator.CalculatorActivity'
operatorsActivity = 'org.solovyev.android.calculator.math.edit.CalculatorOperatorsActivity'
deviceName = 'emulator-5580'


def takeScreenshot(folder, filename):
    screenshot = device.takeSnapshot()
    screenshot.writeToFile(folder + '/' + filename + '.png', 'png')
    return


print 'Waiting for device ' + deviceName + '...'
device = MonkeyRunner.waitForConnection(100, deviceName)

if device:

    print 'Device found, removing application if any ' + package + '...'
    device.removePackage(package)

    print 'Installing apk ' + apk + '...'
    device.installPackage(apk)

    runComponent = package + '/' + activity

    print 'Starting activity ' + runComponent + '...'
    device.startActivity(component=runComponent)

    # sleep while application will be loaded
Exemple #35
0
 def resetGame(self, device):
     activity = 'com.android.systemui/.recent.RecentsActivity'
     device.startActivity(component=activity)
     MonkeyRunner.sleep(1)
     device.touch(600, 915, MonkeyDevice.DOWN_AND_UP)
     print 'click app 2'
     MonkeyRunner.sleep(2)
     device.touch(600, 600, MonkeyDevice.DOWN_AND_UP)
     print 'clear data'
     MonkeyRunner.sleep(2)
     device.touch(600, 747, MonkeyDevice.DOWN_AND_UP)
     print 'confirm'
     MonkeyRunner.sleep(1)
     activity = 'com.avalon.cave/org.cocos2dx.cpp.AppActivity'
     device.startActivity(component=activity)
     MonkeyRunner.sleep(1)
     MonkeyRunner.sleep(20)
     self.checkApp(device)
     device.touch(400, 900, MonkeyDevice.DOWN_AND_UP)
     print 'new character'
     MonkeyRunner.sleep(17)
     device.touch(400, 1222, MonkeyDevice.DOWN_AND_UP)
     print 'start game'
     MonkeyRunner.sleep(5)
     device.touch(700, 1200, MonkeyDevice.DOWN_AND_UP)
     print 'click bag'
     MonkeyRunner.sleep(1)
     device.touch(600, 1200, MonkeyDevice.DOWN_AND_UP)
     print 'click setting'
     MonkeyRunner.sleep(3)
     device.touch(600, 700, MonkeyDevice.DOWN_AND_UP)
     print 'download'
     MonkeyRunner.sleep(7)
     self.checkDownload(device)
     device.touch(222, 666, MonkeyDevice.DOWN_AND_UP)
     print 'confirm'
     MonkeyRunner.sleep(5)
     self.checkOverwrite(device)
     self.checkApp(device)
     MonkeyRunner.sleep(7)
Exemple #36
0
    result.writeToFile(curdir + '/screenShot/' + path + '/' + str(num) + '.png','png')
    print "end screenshot: " + str(num) + ".png"

#写入相应的日志
def writeToLog(f,string):
    f.write(string + getTime())
    f.flush()

def writeToDetails(fi,details):
    fi.write(details + "\n")
    fi.flush()


#连接设备
print "connecting device..."
device = MonkeyRunner.waitForConnection()


print
print
print "###############################################"
print
print "          start run automatic script           "
print
print "###############################################"
print
#显示手机型号
print str(device.getProperty('build.model'))
#获取手机的width,height
print 'width'+ ':'+ str(device.getProperty('display.width'))
print 'height'+ ':'+ str(device.getProperty('display.height'))
#ASCII

# script for automated tasks in Android applications

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

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

#set variables array #agency+countId 
accounts = []
for line in open('/folder/file.txt','r'):
	accounts.append(line.rstrip())

# sets a variable with the package’s internal name
package = 'com.example'

# sets a variable with the name of an Activity in the PACKAGE
activity = 'com.example.activity.Login'
# sets the name of the component to start
runComponent = package + '/' + activity

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

#loop access each account in array	
Exemple #38
0
# otherwise the import fails
try:
    ANDROID_VIEW_CLIENT_HOME = os.environ['ANDROID_VIEW_CLIENT_HOME']
except KeyError:
    print >> sys.stderr, "%s: ERROR: ANDROID_VIEW_CLIENT_HOME not set in environment" % __file__
    sys.exit(1)
sys.path.append(ANDROID_VIEW_CLIENT_HOME + '/src')
from com.dtmilano.android.viewclient import ViewClient

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# 01-04 18:23:42.000: I/ActivityManager(4288): Displayed com.android.development/.DevelopmentSettings: +379ms
package = 'com.android.development'
activity = '.DevelopmentSettings'
componentName = package + "/" + activity
device = MonkeyRunner.waitForConnection(60, "emulator-5554")
if not device:
    raise Exception('Cannot connect to device')

device.startActivity(component=componentName)
MonkeyRunner.sleep(5)

vc = ViewClient(device)
vc.dump()

showCpu = vc.findViewById("id/show_cpu")
showLoad = vc.findViewById("id/show_load")
alwaysFinish = vc.findViewById("id/always_finish")

if not showLoad.isChecked():
    showLoad.touch()
# we will wait for the emulator and then install apk
i = 1
for r in range(9):
    dots = '.' * i
    sys.stdout.write("                                            \r")
    sys.stdout.write("Waiting for emulator" + str(dots) + "\r")
    sys.stdout.flush()
    time.sleep(0.5)
    i = i + 1
    if i == 4:
        i = 1
while androidDevice == None:
    try:
        print("Waiting for emulator...")
        # now we wait for emulator 3 seconds of timeout
        androidDevice = MonkeyRunner.waitForConnection(3)
    except:
        pass

# since this moment, we will use functions from monkeyrunner
print("[+] Installing the application %s..." % apkName)
androidDevice.installPackage(apkName)

# Now create the name for MainActivity to start for example:
#
#   package: .cnt   MainActivity: Class     Path = .cnt./.cnt.Class
#   package: com.cnt    MainActivity: Class Path = com.cnt/Class
#   package: cnt    MainActivity: Class     Path = cnt/cnt.Class

if "." in Mainactivity:
    if Mainactivity.startswith('.'):
Exemple #40
0
 def loadImageFromFile(self, fileName):
     return MonkeyRunner.loadImageFromFile(fileName)
Exemple #41
0
 def sleep(self, seconds):
     MonkeyRunner.sleep(seconds)
     return self
Exemple #42
0
class Reset:
    device = MonkeyRunner.waitForConnection()

    def checkApp(self, device):
        loop = True
        while loop:
            print 'check main'
            img = device.takeSnapshot()
            if (img.getSubImage((377, 600, 50, 15)).sameAs(load_main, 0.6)):
                loop = False
                device.touch(400, 1222, MonkeyDevice.DOWN_AND_UP)
                print 'start game'
                MonkeyRunner.sleep(3)

    def checkDownload(self, device):
        loop = True
        while loop:
            print 'check download'
            img = device.takeSnapshot()
            if (img.getSubImage(
                (60, 585, 680, 111)).sameAs(load_download, 0.8)):
                loop = False

    def checkOverwrite(self, device):
        loop = True
        while loop:
            print 'check overwrite'
            img = device.takeSnapshot()
            if (img.getSubImage(
                (0, 555, 800, 160)).sameAs(load_overwrite, 0.7)):
                loop = False
                device.touch(300, 666, MonkeyDevice.DOWN_AND_UP)
                print 'confirm'
                MonkeyRunner.sleep(1)
                device.touch(400, 666, MonkeyDevice.DOWN_AND_UP)
                print 'confirm'
                MonkeyRunner.sleep(5)

    def resetGame(self, device):
        activity = 'com.android.systemui/.recent.RecentsActivity'
        device.startActivity(component=activity)
        MonkeyRunner.sleep(1)
        device.touch(600, 915, MonkeyDevice.DOWN_AND_UP)
        print 'click app 2'
        MonkeyRunner.sleep(2)
        device.touch(600, 600, MonkeyDevice.DOWN_AND_UP)
        print 'clear data'
        MonkeyRunner.sleep(2)
        device.touch(600, 747, MonkeyDevice.DOWN_AND_UP)
        print 'confirm'
        MonkeyRunner.sleep(1)
        activity = 'com.avalon.cave/org.cocos2dx.cpp.AppActivity'
        device.startActivity(component=activity)
        MonkeyRunner.sleep(1)
        MonkeyRunner.sleep(20)
        self.checkApp(device)
        device.touch(400, 900, MonkeyDevice.DOWN_AND_UP)
        print 'new character'
        MonkeyRunner.sleep(17)
        device.touch(400, 1222, MonkeyDevice.DOWN_AND_UP)
        print 'start game'
        MonkeyRunner.sleep(5)
        device.touch(700, 1200, MonkeyDevice.DOWN_AND_UP)
        print 'click bag'
        MonkeyRunner.sleep(1)
        device.touch(600, 1200, MonkeyDevice.DOWN_AND_UP)
        print 'click setting'
        MonkeyRunner.sleep(3)
        device.touch(600, 700, MonkeyDevice.DOWN_AND_UP)
        print 'download'
        MonkeyRunner.sleep(7)
        self.checkDownload(device)
        device.touch(222, 666, MonkeyDevice.DOWN_AND_UP)
        print 'confirm'
        MonkeyRunner.sleep(5)
        self.checkOverwrite(device)
        self.checkApp(device)
        MonkeyRunner.sleep(7)
Exemple #43
0
def runLoop():
    while True:
        processLoopAction()
        MonkeyRunner.sleep(LOOP_SECONDS)
Exemple #44
0
import time, sys
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

repeat = 5
startPos = (100, 600)
endPos = (100, 300)
steps = 10
duration = 0.1
wait = 1

if len(sys.argv) > 1:
    device = MonkeyRunner.waitForConnection(10, sys.argv[1])
else:
    device = MonkeyRunner.waitForConnection()
package = 'com.android.browser'
activity = 'com.android.browser.BrowserActivity'
runComponent = package + '/' + activity

# Start Activity

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

#
for i in range(0, repeat):
    device.drag(startPos, endPos, duration, steps)
    time.sleep(1)
    device.drag(endPos, startPos, duration, steps)
    time.sleep(1)
def nameko_harvest(device, target):
    testcase = __name__.encode('utf-8')
    dpiRatio = monkeyutils.get_dpi_ratio(device, 480, 800)

    # Launch application.
    runComponent = target['package_name'] + '/' + target['launch_activity']
    device.startActivity(component=runComponent)
    MonkeyRunner.sleep(15)

    #Touch tostart
    device.touch(int(dpiRatio[0] * 240), int(dpiRatio[1] * 550), 'DOWN_AND_UP')
    MonkeyRunner.sleep(5)

    #harvest
    for y in [310, 280, 250, 200]:
        dragStart = (int(dpiRatio[0] * 0), int(dpiRatio[1] * y))
        dragEnd = (int(dpiRatio[0] * 479), int(dpiRatio[1] * y))
        device.drag(dragStart, dragEnd, 2.0, 10)
        MonkeyRunner.sleep(2)

    #food
    food_pos_x = [50, 140, 240, 340, 430]
    device.touch(int(dpiRatio[0] * food_pos_x[2]), int(dpiRatio[1] * 670),
                 'DOWN_AND_UP')
    MonkeyRunner.sleep(3)
    device.touch(int(dpiRatio[0] * 340), int(dpiRatio[1] * 540), 'DOWN_AND_UP')
    MonkeyRunner.sleep(5)

    #exit
    device.press('KEYCODE_BACK', 'DOWN_AND_UP', "1")
    MonkeyRunner.sleep(5)
    device.press('KEYCODE_BACK', 'DOWN_AND_UP', "1")
    MonkeyRunner.sleep(5)
Exemple #46
0
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
print 'reset.py'

load_download = MonkeyRunner.loadImageFromFile('./download.png', 'png')
load_main = MonkeyRunner.loadImageFromFile('./main.png', 'png')
load_overwrite = MonkeyRunner.loadImageFromFile('./overwrite.png', 'png')


class Reset:
    device = MonkeyRunner.waitForConnection()

    def checkApp(self, device):
        loop = True
        while loop:
            print 'check main'
            img = device.takeSnapshot()
            if (img.getSubImage((377, 600, 50, 15)).sameAs(load_main, 0.6)):
                loop = False
                device.touch(400, 1222, MonkeyDevice.DOWN_AND_UP)
                print 'start game'
                MonkeyRunner.sleep(3)

    def checkDownload(self, device):
        loop = True
        while loop:
            print 'check download'
            img = device.takeSnapshot()
            if (img.getSubImage(
                (60, 585, 680, 111)).sameAs(load_download, 0.8)):
                loop = False
Exemple #47
0
# Imports
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

device = MonkeyRunner.waitForConnection()
MonkeyRunner.sleep(8)

# paket, tj. .apk fajl koji se pokrece
package = 'com.zesium.android.themeio'
# pocetna aktivnost koja se pokrece
activity = '.ui.login_and_register.LoginActivity'
runComponent = package + '/' + activity

# Testiranje Create account ekrana
print('Test poceo\n')
MonkeyRunner.sleep(2)

x = 0
while (x < 10):
    x = x + 1
    print 'krug:', x

    # Pokrece komponentu, tj. aktivnost
    print(runComponent)
    device.startActivity(component=runComponent)
    MonkeyRunner.sleep(5)

    #klik na Login via Google dugme
    #device.touch(526, 1261, "DOWN_AND_UP")
    device.touch(508, 1323, "DOWN_AND_UP")
    MonkeyRunner.sleep(8)
    # klik na potvrdu korisnickog Google profila
Exemple #48
0
    'width': 419,
    'height': 121,
    'imgfile': 'cancel-fight.png',
    'img': None
}]

logging.basicConfig(
    filename='artsofwarbot/logs/artsofwarbot.log',
    filemode='a',
    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
    datefmt='%H:%M:%S',
    level=logging.DEBUG)

logging.info("Starting ARTS OF WAR bot")

device = MonkeyRunner.waitForConnection()

for button in buttons:
    button['img'] = MonkeyRunner.loadImageFromFile(
        os.path.join(BUTTONS_PATH, button['imgfile']))

for button in timeoutButtons:
    button['img'] = MonkeyRunner.loadImageFromFile(
        os.path.join(BUTTONS_PATH, button['imgfile']))

unknownSnapsCnt = 0


def checkButton(snap, button):
    snapButton = snap.getSubImage(
        (button['x'], button['y'], button['width'], button['height']))
Exemple #49
0
# ! /usr/bin/env python
# - * - coding:utf-8 - * -
# __author__ : KingWolf
# createtime : 2019/3/19 3:04

#不能再代码中运行文件,需要在命令行下执行monkeyrunner .py文件
from com.android.monkeyrunner import MonkeyRunner as MR
from com.android.monkeyrunner import MonkeyDevice as MD
from com.android.monkeyrunner import MonkeyImage as MI

print('Connect devices......')
#等待连接设备
device = MR.waitForConnection()

# print('installing App.......')
# #安装app
# device.installPackage(r"D:\appium_apk_test\kaoyanbang.apk")

#app的包名和activity名
package = 'com.tal.kaoyan'
activity = 'com.tal.kaoyan.ui.activity.SplashActivity'
runComponent = package + '/' + activity

#启动Activity
print("launch App...")
device.startActivity(component=runComponent)

# #点击“跳过”按钮
# print("touch skip button")
# device.touch(961,104,'DOWN_AND_UP')
# MR.sleep(3)
Exemple #50
0
#start monkey test seedNo 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()
package = 'nerd.tuxmobil.fahrplan.congress.debug'
activity = 'nerd.tuxmobil.fahrplan.congress.MainActivity'
runComponent = package + '/' + activity
device.startActivity(component=runComponent)
MonkeyRunner.sleep(0.8)
MonkeyRunner.sleep(0.8)
device.touch(848, 520, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.8)
device.touch(223, 1871, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.8)
device.touch(74, 139, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.8)
device.touch(1030, 134, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.8)
device.touch(863, 379, 'DOWN_AND_UP')
Exemple #51
0
 def __init__(self, timeout=5):
     self.dev = MonkeyRunner.waitForConnection(timeout)
     self.displayWidth = int(self.getProperty("display.width"))
     self.displayHeight = int(self.getProperty("display.height"))
Exemple #52
0
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

device = MonkeyRunner.waitForConnection()
activity = 'com.avalon.cave/org.cocos2dx.cpp.AppActivity'
#device.startActivity(component=activity); MonkeyRunner.sleep(10);

load_checkMark = MonkeyRunner.loadImageFromFile('./checkMark.png', 'png')
load_gem = MonkeyRunner.loadImageFromFile('./gem.png', 'png')
load_goOut = MonkeyRunner.loadImageFromFile('./goOut.png', 'png')


def watchAd():
    device.touch(41, 176, MonkeyDevice.DOWN_AND_UP)
    print 'click gem'
    MonkeyRunner.sleep(1)
    device.touch(244, 684, MonkeyDevice.DOWN_AND_UP)
    print 'click accept'
    MonkeyRunner.sleep(1)
    device.touch(400, 670, MonkeyDevice.DOWN_AND_UP)
    print 'click second accept'
    MonkeyRunner.sleep(1)

    print 'wait 18'
    MonkeyRunner.sleep(18)

    device.press("KEYCODE_BACK", MonkeyDevice.DOWN_AND_UP)
    print 'back'
    MonkeyRunner.sleep(3)


while True:
Exemple #53
0
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

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

# sets a variable with the package's internal name
package = 'app.buzz.share'

# sets a variable with the name of an Activity in the package
activity = 'com.ss.android.buzz.BuzzMainActivity'

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

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

# MonkeyRunner.sleep(5)
# activity = 'com.bytedance.polaris.browser.PolarisBrowserActivity'
# runComponent = package + '/' + activity
# device.startActivity(component=runComponent)

Exemple #54
0
dir = rootpath + "/apk/hz/"
screenPath = rootpath + "/screenShot/hz/"
duibiPath = rootpath + "/duibiPath/hz/"
logpath = rootpath + "/log/hz/"

#获取待测APK个数
countPak = len(os.listdir(dir))

#新建一个Log文件
if not os.path.isdir(logpath):
    os.mkdir(logpath)
log = open( logpath + filename[0:-3] + "-log" +now + ".txt" , 'w')

#开始连接设备
print("Connecting...")
device = MonkeyRunner.waitForConnection()
log.write("连接设备...\n")

#卸载应用
def uninstall():
    print('Removing...')
    device.removePackage(pakageName)
    print ('Remove Successful!')
    MonkeyRunner.sleep(2)
    log.write("初始化应用环境...\n")
countOK = 0
countNO = 0


#安装目录下的apk
for i in os.listdir(dir):
Exemple #55
0
 def sleep(self, delay=1):
     if not delay == 0:
         print 'wait %fs' % (delay)
         MonkeyRunner.sleep(delay)
Exemple #56
0
def uninstall():
    print('Removing...')
    device.removePackage(pakageName)
    print ('Remove Successful!')
    MonkeyRunner.sleep(2)
    log.write("初始化应用环境...\n")
Exemple #57
0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import os
from com.android.monkeyrunner import MonkeyRunner as mr
device = mr.waitForConnection()
files = sys.argv[1:]
k = len(files)

path = 'D:/img/'
logPath = 'E:/Module/Monkeyrunner/05-21/log.txt'
title = ''
flag = 'img1'
flag2 = ''

num = 2
total = num * k
#print total;
j = 0
z = 0
Exemple #58
0

#写入相应的日志
def writeToLog(f, string):
    f.write(string + getTime())
    f.flush()


def writeToDetails(fi, details):
    fi.write(details + "\n")
    fi.flush()


#连接设备
print "connecting device..."
device = MonkeyRunner.waitForConnection()

print
print
print "###############################################"
print
print "          start run automatic script           "
print
print "###############################################"
print
#显示手机型号
print str(device.getProperty('build.model'))
#获取手机的width,height
print 'width' + ':' + str(device.getProperty('display.width'))
print 'height' + ':' + str(device.getProperty('display.height'))
print
def run_back_button():
    device = MonkeyRunner.waitForConnection()
    for _ in range(loop_count.BACK_BUTTON):
        device.press("KEYCODE_BACK", MonkeyDevice.DOWN_AND_UP)
def pressDone():
    print("----- pressDone button")
    print("----- Done button X = " + str(deviceSceen.CAMERA_SAVE_BUTTON_X))
    print("----- Done button Y = " + str(deviceSceen.CAMERA_SAVE_BUTTON_Y))
    device.touch(deviceSceen.CAMERA_SAVE_BUTTON_X, deviceSceen.CAMERA_SAVE_BUTTON_Y, MonkeyDevice.DOWN_AND_UP)
    MonkeyRunner.sleep(3);    
    return