前言
前面学习了使用Python进行的简单命令操作,这次我们来结合简单制作一个Android的简单的Monkey测试脚本。
步骤
###启动需要运行的脚本的APP
# 启动app
startStatus = openApp(package, launch)
if startStatus:
print('启动app成功')
else:
print('启动app失败')
return;
中断条件
App不在前端显示了
# 中断条件
activitys = getFrontActivity(package)
if len(activitys) == 0:
print('结束了~')
break
执行事件
# 点击事件
if typeStatus == 0:
rx = random.randint(0, width)
ry = random.randint(0, height)
time.sleep(rtime)
bashInfo('adb shell input tap %d %d' % (rx, ry))
canBack = False
print('点击:延迟%f秒:x:%d y:%d' % (rtime, rx, ry))
# 返回
elif typeStatus == 2:
if canBack:
continue;
bashInfo('adb shell input keyevent 4')
canBack = True
print('返回:延迟%f秒:back' % rtime)
# 滑动
elif typeStatus == 1:
rx1 = random.randint(0, width)
ry1 = random.randint(0, height)
rx2 = random.randint(0, width)
ry2 = random.randint(0, height)
bashInfo('adb shell input swipe %d %d %d %d' % (rx1, ry1, rx2, ry2))
canBack = False
print('滑动:延迟%f秒:x:%d y:%d -> x:%d y:%d' % (rtime, rx1, ry1, rx2, ry2))
完整代码
# 自动执行开始
def handle(package, launch, width, height):
# 启动app
startStatus = openApp(package, launch)
if startStatus:
print('启动app成功')
else:
print('启动app失败')
return;
time.sleep(3)
# 防止点击两次back造成程序退出
canBack = False
while 1:
# 中断条件
activitys = getFrontActivity(package)
if len(activitys) == 0:
print('结束了~')
break
# 随机有个操作类型,0~50为点击,50~80为滑动,80~100为back
typeId = random.randint(0, 100)
if typeId < 50:
typeStatus = 0
elif typeId >= 50 and typeId < 80:
typeStatus = 1
else:
typeStatus = 2
rtime = random.uniform(0, 2)
rtime = round(rtime, 3)
# 点击事件
if typeStatus == 0:
rx = random.randint(0, width)
ry = random.randint(0, height)
time.sleep(rtime)
bashInfo('adb shell input tap %d %d' % (rx, ry))
canBack = False
print('点击:延迟%f秒:x:%d y:%d' % (rtime, rx, ry))
# 返回
elif typeStatus == 2:
if canBack:
continue;
bashInfo('adb shell input keyevent 4')
canBack = True
print('返回:延迟%f秒:back' % rtime)
# 滑动
elif typeStatus == 1:
rx1 = random.randint(0, width)
ry1 = random.randint(0, height)
rx2 = random.randint(0, width)
ry2 = random.randint(0, height)
bashInfo('adb shell input swipe %d %d %d %d' % (rx1, ry1, rx2, ry2))
canBack = False
print('滑动:延迟%f秒:x:%d y:%d -> x:%d y:%d' % (rtime, rx1, ry1, rx2, ry2))
# 获取屏幕分辨率
r = getScreenResolution()
if 'Override' in r.keys():
rOverride = r['Override']
elif 'Physical' in r.keys():
rOverride = r['Physical']
if not rOverride.strip() == '':
width = int(rOverride.split('x')[0])
height = int(rOverride.split('x')[1])
handle('com.tts.hybird', 'com.tts.trip.WelcomeActivity',width, height)