Android自动化测试之MonkeyRunner录制和回放脚本(十一)
分类: 自动化测试 Android自动化 -02-22 10:57 7346人阅读 评论(2) 收藏 举报 androidAndroidANDROIDMonkeyRecordermonkeyrunnerMonkeyRunnerMonkeyrunner对于MonkeyRunner,有些人可能会想,既然是Android自动化测试,离不开测试脚本,那么,我们可不可以录制测试脚本呢,答案是可以的。
我们先看看以下monkeyrecoder.py脚本:
[html]view plaincopy #Usage:monkeyrunnerrecorder.py#recorder.py/linux/android/repository/platform/sdk/monkeyrunner/scripts/monkey_recorder.pycom.android.monkeyrunnerimportMonkeyRunnerasmrcom.android.monkeyrunner.recorderimportMonkeyRecorderasrecorderdevice=mr.waitForConnection()recorder.start(device)#ENDrecorder.py
首先,连接你已经打开调试模式的ANDROID设备或模拟器,然后运行上面的脚本,例如在cmd窗口中执行命令: monkeyrunner monkeyrecoder.py
执行下面的代码后,将运行录制脚本的程序:
#Press ExportAction to save recorded scrip to a file
#Example of result:
#PRESS|{""name"":""MENU"",""type"":""downAndUp"",}
#TOUCH|{""x"":180,""y"":175,""type"":""downAndUp"",}
#TYPE|{""message"":"""",}
=================================================
这种脚本需要另外一个monkeyrunner的脚本来解释执行。monkeyplayback.py
[html]view plaincopy #Usage:monkeyrunnerplayback.py"myscript"#playback.py/linux/android/repository/platform/sdk/monkeyrunner/scripts/monkey_playback.pyimportsyscom.android.monkeyrunnerimportMonkeyRunner#Theformatofthefileweareparsingisverycarfeullyconstructed.#Eachlinecorrespondstoasinglecommand.Thelineissplitinto2#partswitha|character.Texttotheleftofthepipedenotes#whichcommandtorun.Thetexttotherightofthepipeisapython#dictionary(itcanbeevaledintoexistence)thatspecifiesthe#argumentsforthecommand.Inmostcases,thisdirectlymapstothe#keywordargumentdictionarythatcouldbepassedtotheunderlying#command.#Lookuptabletomapcommandstringstofunctionsthatimplementthat#command.CMD_MAP={""TOUCH"":lambdadev,arg:dev.touch(**arg),""DRAG"":lambdadev,arg:dev.drag(**arg),""PRESS"":lambdadev,arg:dev.press(**arg),""TYPE"":lambdadev,arg:dev.type(**arg),""WAIT"":lambdadev,arg:MonkeyRunner.sleep(**arg)}#Processasinglefileforthespecifieddevice.defprocess_file(fp,device):forlineinfp:(cmd,rest)=line.split(""|"")try:#Parsethepydictrest=eval(rest)except:print""unabletoparseoptions""continueifcmdnotinCMD_MAP:print""unknowncommand:""+cmdcontinueCMD_MAP[cmd](device,rest)defmain():file=sys.argv[1]fp=open(file,""r"")device=MonkeyRunner.waitForConnection()process_file(fp,device)fp.close();if__name__==""__main__"":main()
=================================================
Usage:monkeyrunner playback.py "myscript"