大家周末好,臨近年末,大家要注意保暖喲。近期小弟在自學monkeyrunner,於是一邊學習一邊就想寫點東西啦,或許有些人也學過並且精通這個測試工具。但是將自己的經驗寫出來並分享給大家才是真的好哈哈。接下來切入正題,第一講是monkeyrunner的錄制和回放。
這篇文章里,我的demo都是用自己手機來操作的,因為android原生的模擬器實在太卡了,如果朋友們想學模擬器的操作請自行百度。
1.第一步:大家玩android測試,環境sdk,ADT不用我說了吧,都去部署好,之前的博客我也有寫環境變量,注意大家最好去配完整,shell端就不用自己找系統路徑了,http://www.cnblogs.com/wyx123/articles/4133001.html
2.用usb連上你的手機,注意幾個情況:
2.1如果手機只顯示
,估計是你usb沒接好,再去檢查檢查有沒有插好
2.2有時候我們會遇到port5037被占用;記住5037是adb的默認端口,這種情況是你的手機助手或者其他進程占用了它,解決這個問題兩種解決方式:
2.2.1一種常見的解決方法是:找出占用5037端口的程序,然后殺掉它;
使用:netstat -aon | findstr 127.0.0.1:5037 來找到占用5037的進程ID;
使用:kill -f pid 去殺掉它們。(或者在任務管理器 -進程中,結束進程。PS:需要事先在 windows任務管理器-查看-選擇列,勾選PID)
2.2.2.自己配置 adb server 端口,使用一個生僻的值。很簡單,只要在系統環境變量中定義 ANDROID_ADB_SERVER_PORT 的值即可。最好選擇一個5位數的端口號(10000 ~ 65535),不易重復。
win下只要在環境變量中增加一個ANDROID_ADB_SERVER_PORT ,值填你自己定義的端口。
linux下只要 export $ANDROID_ADB_SERVER_PORT = 自定義端口,即可。
這時打開一個命令行,輸入adb devices,看看是不是在新的端口上啟動了啊?
3.
這是我的真機了,左邊是名稱,右邊是device狀態,為已連接
4.預熱部分完成,正式進入monkeyrunner的錄制

monkeyrunner這個monkeyrunner_recorder.py文件
請看源代碼,用py寫的,大家這里注意縮進,是四個空格,十分嚴格
from com.android.monkeyrunner import MonkeyRunner as mr from com.android.monkeyrunner.recorder import MonkeyRecorder as recorder device = mr.waitForConnection() recorder.start(device)

大家啟動好這個界面,就可以真機亂點啦哈哈,右側的代碼是你的操作步驟。自己去試試操作,這里詳細說的是導出你的操作步驟:
點擊Export Actions,於是會跳出啦,然后選擇一個文件夾進行保存
如圖:
5.回放我的操作腳本
得有monkey_playback.py這個文件,源代碼如下:
import sys
from com.android.monkeyrunner import MonkeyRunner
# The format of the file we are parsing is very carfeully constructed.
# Each line corresponds to a single command. The line is split into 2
# parts with a | character. Text to the left of the pipe denotes
# which command to run. The text to the right of the pipe is a python
# dictionary (it can be evaled into existence) that specifies the
# arguments for the command. In most cases, this directly maps to the
# keyword argument dictionary that could be passed to the underlying
# command.
# Lookup table to map command strings to functions that implement that
# command.
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),
'WAIT': lambda dev, arg: MonkeyRunner.sleep(**arg)
}
# Process a single file for the specified device.
def process_file(fp, device):
for line in fp:
(cmd, rest) = line.split('|')
try:
# Parse the pydict
rest = eval(rest)
except:
print 'unable to parse options'
continue
if cmd not in CMD_MAP:
print 'unknown command: ' + cmd
continue
CMD_MAP[cmd](device, rest)
def main():
file = sys.argv[1]
fp = open(file, 'r')
device = MonkeyRunner.waitForConnection()
process_file(fp, device)
fp.close();
if __name__ == '__main__':
main()
最后在shell端敲
具體觀察自己手機是不是在自動跑操作了
