Android初體驗之Monkey和MonkeyRunner


本文部分解釋性語段摘自網絡百科或其它BLOG,語句內容網絡隨處可見,也不知道誰是初始原創,便不再署名出處,如有雷同,還請見諒。


Monkey


 什麼是Monkey


Monkey是Android中的一個命令行工具,可以運行在模擬器裏或實際設備中。它向系統發送僞隨機的用戶事件流(如按鍵輸入、觸摸屏輸入、手勢輸入等),實現對正在開發的應用程序進行壓力測試。Monkey測試是一種爲了測試軟件的穩定性、健壯性的快速有效的方法。


 Monkey的特徵

1、 測試的對象僅爲應用程序包,有一定的侷限性。

2、 Monky測試使用的事件流數據流是隨機的,不能進行自定義。

3、 可對Test的對象,事件數量,類型,頻率等進行設置。

Monkey的基本用法

基本語法如下:

adb shell monkey [options] <event-count>


options event-count
這個是配置monkey的設置,例如,指定啓動那個包,不指定將會隨機啓動所有程序 這個是讓monkey發送多少次事件
詳細的monkey介紹,和options的參數請查看 (http://developer.android.com/guide/developing/tools/monkey.html)

如果不指定options,Monkey將以無反饋模式啓動,並把事件任意發送到安裝在目標環境中的全部包。


Monkey測試的停止條件

 
1、如果限定了Monkey運行在一個或幾個特定的包上,那麼它會監測試圖轉到其它包的操作,並對其進行阻止。

2、如果應用程序崩潰或接收到任何失控異常,Monkey將停止並報錯。

3、如果應用程序產生了應用程序不響應(application not responding)的錯誤,Monkey將會停止並報錯。


實例

下面是一個更爲典型的命令行示例,它啓動指定的應用程序,並向其發送500個僞隨機事件:

adb shell monkey -p your.package.name -vvv 500 > monkeytest.txt

-p表示對象包  -v 爲 verbose的縮寫(信息級別就是日誌的詳細程度),就是詳細輸出事件等級,這個3個v就是輸出等級1至3的所有事件.(使用管道命令將輸出結果放到一個文本里面方便查看)


舉例:

eclipse連接真機設備,Window打開CMD,命令行輸入:adb shell,進入shell界面後:


我運行的是手機上的 計算器 程序,具體你可以指定自己的APP包名就可以了~

真機效果:


如圖所示,它真的就是隨機輸入數值,隨機按鈕,隨機.....的...................缺點是我們不能控制觸摸或按鈕事件,接下來MonkeyRunner就要登場了~




MonkeyRunner


什麼是monkeyrunner

monkeyrunner工具提供了一個API,使用此API寫出的程序可以在Android代碼之外控制Android設備和模擬器。通過monkeyrunner,您可以寫出一個Python程序去安裝一個Android應用程序或測試包,運行它,向它發送模擬擊鍵,截取它的用戶界面圖片,並將截圖存儲於工作站上。monkeyrunner工具的主要設計目的是用於測試功能/框架水平上的應用程序和設備,或用於運行單元測試套件。


monkeyrunner同monkey的區別

Monkey工具直接運行在設備或模擬器的adb shell中,生成用戶或系統的僞隨機事件流。monkeyrunner工具則是在工作站上通過API定義的特定命令和事件控制設備或模擬器,它支持,自己編寫插件,控制事件,隨時截圖,簡而言之,任何你在模擬器/設備中能幹的事情,MonkeyRunner都能幹,而且還可以記錄和回放。


monkeyrunner的測試類型

1、多設備控制:monkeyrunner API可以跨多個設備或模擬器實施測試套件。您可以在同一時間接上所有的設備或一次啓動全部模擬器(或統統一起),依據程序依次連接到每一個,然後運行一個或多個測試。您也可以用程序啓動一個配置好的模擬器,運行一個或多個測試,然後關閉模擬器。

2、 功能測試: monkeyrunner可以爲一個應用自動貫徹一次功能測試。您提供按鍵或觸摸事件的輸入數值,然後觀察輸出結果的截屏。

3、 迴歸測試:monkeyrunner可以運行某個應用,並將其結果截屏與既定已知正確的結果截屏相比較,以此測試應用的穩定性。

4、 可擴展的自動化:由於monkeyrunner是一個API工具包,您可以基於Python模塊和程序開發一整套系統,以此來控制Android設備。除了使用monkeyrunner API之外,您還可以使用標準的Python os和subprocess模塊來調用Android Debug Bridge這樣的Android工具。


運行monkeyrunner

您可以直接使用一個代碼文件運行monkeyrunner,抑或在交互式對話中輸入monkeyrunner語句。不論使用哪種方式,您都需要調用SDK目錄的tools子目錄下的monkeyrunner命令。如果您提供一個文件名作爲運行參數,則monkeyrunner將視文件內容爲Python程序,並加以運行;否則,它將提供一個交互對話環境。


monkeyrunner基本語法

monkeyrunner -plugin <plugin_jar> <program_filename> <program_options>


具體介紹…看官方文檔(http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html)


實例

連接真機(模擬器),打開CMD,進入:E:\android-sdk-windows\tools文件夾內(裏面有monkeyrunner.bat)

創建一個Python腳本文件:testrunner.py,內容如下:

注意!如果monkeyrunner腳本文件要使用中文,記得格式保存爲utf8,不然會ASCNII無法支持錯誤

#導入我們需要用到的包和類並且起別名
import sys
from com.android.monkeyrunner import MonkeyRunner as mr
from com.android.monkeyrunner import MonkeyDevice as md
from com.android.monkeyrunner import MonkeyImage as mi
 
#connect device 連接設備
#第一個參數爲等待連接設備時間
#第二個參數爲具體連接的設備
device = mr.waitForConnection(1.0,'e0d98451')
if not device:
    print >> sys.stderr,"fail"
    sys.exit(1)
#定義要啓動的Activity
componentName='com.example.simulate/.ShellActivity'
#啓動特定的Activity
device.startActivity(component=componentName)
mr.sleep(3.0)
#do someting 進行我們的操作
#輸入 helloworld
device.type('helloworld')
#輸入回車
device.press('KEYCODE_ENTER')
#return keyboard
#device.press('KEYCODE_BACK')
#------
#takeSnapshot截圖
mr.sleep(3.0)
result = device.takeSnapshot()
 
#save to file 保存到文件
result.writeToFile('./shot1.png','png');


接下來命令行輸入:

monkeyrunner testrunner.py


這是一個小的腳本文件,主要是啓動com.example.simulate包名下的ShellActivity界面,接下來按下Enter按鈕,最後截屏,並保存在當前目錄下爲shot1.png,可以在toosl文件夾下查看。


這個腳本的實質就是一個python腳本,懂python的朋友,可以利用這個實現非常強悍的功能~~~~~~~~~~~~~~~~~~~~~~~~



monkeyRunner 的記錄和回放

這纔是真正實用的功能,直接看代碼,創建一個recoder.py:

#!/usr/bin/env monkeyrunner
# Copyright 2010, The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from com.android.monkeyrunner import MonkeyRunner as mr
from com.android.monkeyrunner.recorder import MonkeyRecorder as recorder

device = mr.waitForConnection()
recorder.start(device)

命令行下運行:

monkeyrunner monkey_recorder.py

這時會彈出這樣的界面:


按鈕以及一些功能說明:

Button Description
Wait 等待時間
Press a Button 發送,MENU,HOME,or SEARCH 按鈕.Press,Down,or Up事件
Type Something 發送一些字符串
Fling 用來操作虛擬鍵盤 
image
Export Action 將我們的腳本導出來
Refresh Display 刷新當前界面

自己隨心所以創建一些事件腳本,想做什麼就可以做什麼,通過MonkeyRecorder這個工具來操作設備界面,事件編輯完後選擇Export Actions,導出到我們tools目錄下命名爲:action.mr

我們看一下工具生成的action.mr腳本,如下:

TOUCH|{'x':297,'y':533,'type':'downAndUp',}
WAIT|{'seconds':2.0,}
TOUCH|{'x':136,'y':278,'type':'downAndUp',}
WAIT|{'seconds':2.0,}
TOUCH|{'x':123,'y':356,'type':'downAndUp',}
WAIT|{'seconds':10.0,}
PRESS|{'name':'HOME','type':'downAndUp',}
WAIT|{'seconds':2.0,}
TOUCH|{'x':235,'y':720,'type':'downAndUp',}
WAIT|{'seconds':2.0,}
TOUCH|{'x':303,'y':630,'type':'downAndUp',}
WAIT|{'seconds':2.0,}
TOUCH|{'x':16,'y':71,'type':'downAndUp',}
WAIT|{'seconds':2.0,}
TOUCH|{'x':244,'y':735,'type':'downAndUp',}



然後需要製作一個運行這一系列動作的腳本:monkey_playback.py,保存到tools目錄下:

#!/usr/bin/env monkeyrunner
# Copyright 2010, The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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()



接下來運行我們的保存的腳本,然後,你就看到真機(模擬器),進行你剛纔一樣的操作~

E:\android-sdk-windows\tools>monkeyrunner monkey_playback.py action.mr


我的腳本是執行一些press down 和press up動作,同時會有延遲,之後按下home按鈕,最後打開桌面的短信程序,並打開某一條信息~是不是有點像按鍵精靈的感覺?但是得依靠命令行執行腳本~~~


至此,monkey和monkeyrunner介紹完畢。


附件傳送門地址,網上一位朋友寫好的常用的recorder、playback腳本,包括我以上所列py,你可以自己看着修改,別人的資源,免費共享:

http://download.csdn.net/detail/mad1989/7674089


發佈了95 篇原創文章 · 獲贊 123 · 訪問量 486萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章