monkeyrunner自動化測試

經過MonkeyRunner遍歷apk文件夾裏的apk文件,實現自動安裝應用,打開應用,截圖,將截圖與提早準備好的基線圖作對比,對比類似度達到90%時,則對比經過,而後自動卸載應用,進入下一個APK文件的對比流程。當對比失敗時,將自動中止測
#!/usr/bin/env monkeyrunner
# -*- coding: utf-8 -*-

import time
import sys
import os
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

#設置應用包名和入口Activity名
pakageName = 'com.hujiang.cctalk'
componentName = 'com.hujiang.cctalk/.MainActivity'

#APP啓動時等待時間(秒)
startTime = 5

#獲取年月日時分秒
now = time.strftime("%Y-%m-%d-%H-%M-%S")

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

#MonkeyRunner下獲取運行的文件所在的路徑
rootpath  = os.path.split(os.path.realpath(sys.argv[0]))[0]

#指定位置
dir = rootpath + "/apk/"
screenPath = rootpath + "/screenShot/"
logpath = rootpath + "/log/"

#獲取待測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")

#卸載應用
print('Removing...')
device.removePackage(pakageName)
print ('Remove Successful!')
MonkeyRunner.sleep(2)
log.write("初始化應用環境...\n")
countOK = 0
countNO = 0

for i in os.listdir(dir):
    print('Installing...<%s>'%i)
    log.write("==========安裝應用==========\n")
    path = dir + '//' + i
    #安裝應用
    device.installPackage(path)
    print('Install Successful!')

    #打開應用
    device.startActivity(component=componentName)
    MonkeyRunner.sleep(startTime)
    log.write("啓動App...\n")

    #截圖
    result=device.takeSnapshot()
    print("Take ScreenShot...")

    #保存截圖
    result.writeToFile(screenPath + i + '.png','png')
    
    #進行圖片比較
    resultTrue=MonkeyRunner.loadImageFromFile(screenPath + r'basePic.png')
    print "Pic Comparing..."
    log.write("對比圖片中...\n")
    if(result.sameAs(resultTrue,0.9)):
        print("%s is OK!"%i)
        log.write("比較經過!--%s--包可用!\n"%i)
        #卸載應用
        print('Removing...')
        log.write("初始化應用環境,移除中...\n")
        device.removePackage(pakageName)
        print ('Remove Successful!')
        log.write("==========移除完畢==========\n")
        countOK += 1
        MonkeyRunner.sleep(2)
    else:
        print("False!Please check %s!"%i)
        log.write("比較失敗!請檢查安裝包--%s--是否可用!\n"%i)
        break

log.write("共測試 %s 個包,%d 個經過。"%(countPak,countOK))
相關文章
相關標籤/搜索