巴黎的灯光下 发表于 2017-6-29 14:49:06

使用 MonkeyRunner 做批量过渠道包的小工具

上周公司有同事抱怨说过渠道包太累,一下60多个包。由于某些安全机制,要检测每个包里面的一个视频播放功能是否可用,所有得一个个过下来,很累。
刚好看到@zouaiyong 同学用MonkeyRunner写的代码,就借鉴改造了一下,随便折腾了一份批量测渠道包的代码。
这里我就放出 循环安装、打开应用、截图对比、卸载的代码。打开应用之后播放视频的操作就去掉了,毕竟都是一堆坐标。仅供大家参考参考。
扔多少个APK进去,就自动跑多少个,跑完出log,对比失败时自动停止。
不说了,看代码呗。
#!/usr/bin/env monkeyrunner
# -*- coding: utf-8 -*-

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

#设置应用包名和入口Activity名
pakageName = 'com.Your.www'
componentName = 'com.Your.www/.MainActivity'

#APP启动时等待时间(秒)
startTime = 5

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

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

#MonkeyRunner下获取运行的文件所在的路径
rootpath= os.path.split(os.path.realpath(sys.argv))

#指定位置
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 + "-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

#从dir路径下循环取出apk文件进行操作
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))

悠悠小仙仙 发表于 2017-6-29 14:51:39

之前写了基于robotium的遍历 半成品。。。 思想就是树结构 叶子 节点,不过我觉得效率好低 后来就没再搞。不过前几天刚搞了个android的兼容性遍历,原理就是将intent序列化,保存成2进制文件,使用的时候读到内存中就好,直接跳进相应activity,截图保存。

悠悠小仙仙 发表于 2017-6-29 14:55:41

最近在看monkeyrunner,刚好学习一下,感谢。

巴黎的灯光下 发表于 2017-6-29 14:57:18

悠悠小仙仙 发表于 2017-6-29 14:55
最近在看monkeyrunner,刚好学习一下,感谢。

有帮助就好!
页: [1]
查看完整版本: 使用 MonkeyRunner 做批量过渠道包的小工具