MonkeyRunner 的使用<一>

来源:互联网 发布:仓廪实而知礼节的一辩 编辑:程序博客网 时间:2024/05/22 06:22


MonkeyRunner的使用

如果您的英语不错那您可以自己看官网的介绍,如果您需要翻译,其实网上有很多很好的翻译,但是为了学习的完整性,自己还是做了一些重复性的劳动。

http://developer.android.com/tools/help/monkeyrunner_concepts.html

 

还是先把网站的东西翻译一遍:

The monkeyrunner tool provides an API for writing programs that control an Android device or emulator from outside of Android code. With monkeyrunner, you can write a Python program that installs an Android application or test package, runs it, sends keystrokes to it, takes screenshots of its user interface, and stores screenshots on the workstation. The monkeyrunner tool is primarily designed to test applications and devices at the functional/framework level and for running unit test suites, but you are free to use it for other purposes

monkeyrunner工具提供了一个API,使用此API写出的程序可以在Android代码之外控制Android设备和模拟器。通过monkeyrunner,您可以写出一个Python程序去安装一个Android应用程序或测试包,运行它,向它发送模拟击键,截取它的用户界面图片,并将截图存储于工作站上。monkeyrunner工具的主要设计目的是用于测试功能/框架水平上的应用程序和设备,或用于运行单元测试套件,但您当然也可以将其用于其它目的。

The monkeyrunner tool is not related to the UI/Application Exerciser Monkey, also known as the monkey tool. The monkey tool runs in an adb shell directly on the device or emulator and generates pseudo-random streams of user and system events. In comparison, the monkeyrunner tool controls devices and emulators from a workstation by sending specific commands and events from an API.

monkeyrunner工具用户界面/应用程序测试工具,也称为monkey工具并无关联。monkey工具直接运行在设备或模拟器adbshell中,生成用户或系统的伪随机事件流。而monkeyrunner工具则是在工作站上通过API定义的特定命令和事件控制设备或模拟器。

The monkeyrunner tool provides these unique features for Android testing:

Multiple device control: The monkeyrunner API can apply one or more test suites across multiple devices or emulators. You can physically attach all the devices or start up all the emulators (or both) at once, connect to each one in turn programmatically, and then run one or more tests. You can also start up an emulator configuration programmatically, run one or more tests, and then shut down the emulator.

Functional testing: monkeyrunner can run an automated start-to-finish test of an Android application. You provide input values with keystrokes or touch events, and view the results as screenshots.

Regression testing - monkeyrunner can test application stability by running an application and comparing its output screenshots to a set of screenshots that are known to be correct.

Extensible automation - Since monkeyrunner is an API toolkit, you can develop an entire system of Python-based modules and programs for controlling Android devices. Besides using the monkeyrunner API itself, you can use the standard Python os and subprocess modules to call Android tools such as Android Debug Bridge.

You can also add your own classes to the monkeyrunner API. This is described in more detail in the section Extending monkeyrunner with plugins.

monkeyrunner工具为Android测试提供了以下特性:

多设备控制:monkeyrunner API可以跨多个设备或模拟器实施测试套件。您可以在同一时间接上所有的设备或一次启动全部模拟器(或统统一起),依据程序依次连接到每一个,然后运行一个或多个测试。您也可以用程序启动一个配置好的模拟器,运行一个或多个测试,然后关闭模拟器。

 

功能测试:monkeyrunner可以为一个应用自动贯彻一次功能测试。您提供按键或触摸事件的输入数值,然后观察输出结果的截屏。    

 

回归测试:monkeyrunner可以运行某个应用,并将其结果截屏与既定已知正确的结果截屏相比较,以此测试应用的稳定性。       

    

可扩展的自动化:由于monkeyrunner是一个API工具包,您可以基于Python模块和程序开发一整套系统,以此来控制Android设备。除了使用monkeyrunner API之外,您还可以使用标准的Python ossubprocess模块来调用如adb这样的Android工具。 

您还可以向monkeyrunner API中添加您自己的类。我们将在使用插件扩展monkeyrunner一节中对此进行详细讨论。

 

A Simple monkeyrunner Program

Here is a simple monkeyrunner program that connects to a device, creating a MonkeyDevice object. Using the MonkeyDevice object, the program installs an Android application package, runs one of its activities, and sends key events to the activity. The program then takes a screenshot of the result, creating a MonkeyImage object. From this object, the program writes out a .png file containing the screenshot.

 

# 导入此程序所需的monkeyrunner模块 from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # 连接当前设备,返回一个MonkeyDevice对象 device = MonkeyRunner.waitForConnection() # 安装Android包,注意,此方法返回的返回值为boolean,由此您可以判断安装过程是否正常 device.installPackage('myproject/bin/MyApplication.apk') # 运行此应用中的一个活动 device.startActivity(component='com.example.android.myapplication.MainActivity') # 按下菜单按键 device.press('KEYCODE_MENU','DOWN_AND_UP') # 截取屏幕截图 result = device.takeSnapShot# 将截图保存至文件 result.writeToFile('myproject/shot1.png','png')

The monkeyrunner API

The monkeyrunner API is contained in three modules in the package com.android.monkeyrunner:

 

MonkeyRunner: A class of utility methods for monkeyrunner programs. This class provides a method for connecting monkeyrunner to a device or emulator. It also provides methods for creating UIs for a monkeyrunner program and for displaying the built-in help.

MonkeyDevice: Represents a device or emulator. This class provides methods for installing and uninstalling packages, starting an Activity, and sending keyboard or touch events to an application. You also use this class to run test packages.

MonkeyImage: Represents a screen capture image. This class provides methods for capturing screens, converting bitmap images to various formats, comparing two MonkeyImage objects, and writing an image to a file.

MonkeyRunner    :一个为monkeyrunner程序提供工具方法的类。这个类提供了用于连接monkeyrunner至设备或模拟器的方法。它还提供了用于创建一个monkeyrunner程序的用户界面以及显示内置帮助的方法。        

    


 MonkeyDevice    :表示一个设备或模拟器。这个类提供了安装和卸载程序包、启动一个活动以及发送键盘或触摸事件到应用程序的方法。您也可以用这个类来运行测试包。        

       

 

 MonkeyImage    :表示一个截图对象。这个类提供了截图、将位图转换成各种格式、比较两个MonkeyImage对象以及写图像到文件的方法。        

  

在python程序中,您将以Python模块的形式使用这些类。monkeyrunner工具不会自动导入这些模块。您必须使用类似如下的from语句:

  from com.android.monkeyrunner import

其中,为您想要导入的类名。您可以在一个from语句中导入超过一个模块,其间以逗号分隔。

Runningmonkeyrunner


You can either runmonkeyrunner programs from a file, or enter monkeyrunner statements in aninteractive session. You do both by invoking the monkeyrunner command which isfound in the tools/ subdirectory of yourSDK directory. If you provide a filename as an argument, the monkeyrunner command runs thefile's contents as a Python program; otherwise, it starts an interactivesession.

The syntax of the monkeyrunner command is

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

运行monkeyrunner

您可以直接使用一个代码文件运行monkeyrunner,抑或在交互式对话中输入monkeyrunner语句。不论使用哪种方式,您都需要调用SDK目录的tools子目录下的monkeyrunner命令。如果您提供一个文件名作为运行参数,则monkeyrunner将视文件内容为Python程序,并加以运行;否则,它将提供一个交互对话环境。

monkeyrunner命令的语法为:

monkeyrunner -plugin  <程序文件名> <程序选项>

Table 1 explainsthe flags and arguments.

Table 1. monkeyrunner flags andarguments.

Argument

Description

-plugin <plugin_jar>

(Optional) Specifies a .jar file containing a plugin for monkeyrunner. To learn more about monkeyrunner plugins, see Extending monkeyrunner with plugins. To specify more than one file, include the argument multiple times.

<program_filename>

If you provide this argument, the monkeyrunner command runs the contents of the file as a Python program. If the argument is not provided, the command starts an interactive session.

<program_options>

(Optional) Flags and arguments for the program in <program_file>.

 

1阐释了命令的标志和参数。

1.monkeyrunner标志和参数。

参数

描述

-plugin <plugin_jar>

(可选)指定一个内含monkeyrunner插件的.jar文件。欲了解更多关于monkeyrunner插件的内容,请参照使用插件扩展monkeyrunner。要指定多个文件,包括多次论证。如欲指定超过一个文件,可以多次使用此参数。

<程序文件名>

  如果您指定此参数,monkeyrunner将视文件内容为Python程序并予以执行。如果此参数未予指定,则开启一个交互式会话。

<程序选项>

                

<程序文件名>            所指定的程序所需的参数


monkeyrunner内建帮助

您可以用以下命令来生成monkeyrunnerAPI参考:

monkeyrunner help.py

参数说明:

  可以为texthtml,分别代表纯文本和HTML输出。

·        指定了输出文件的全路经名称。

使用插件扩展monkeyrunner

您可以用Java语言创建新的类,并打包成一个或多个.jar文件,以此来扩展monkeyrunnerAPI。您可以使用您自己写的类或者继承现有的类来扩展monkeyrunnerAPI。您还可以使用此功能来初始化monkeyrunner环境。

为了使monkeyrunner加载一个插件,您应当如使用如1中所述的-plugin参数来调用monkeyrunner命令。

在您编写的插件中,您可以导入或继承位于com.android.monkeyrunner包中的几个主要的monkeyrunner类:MonkeyDeviceMonkeyImageMonkeyRunner(参见monkeyrunnerAPI)。

请注意,插件无法让你访问AndroidSDK。您不能导入com.android.app等包。这是因为monkeyrunner是在框架API层次之下与设备或模拟器进行交互的。

插件启动类

用于插件的.jar文件可以指定一个类,使其在脚本执行之前就实例化。如欲指定这个类,您需要在.jar文件的manifest中添加键MonkeyRunnerStartupRunner。其值为启动时运行的类的名称。以下代码段显示了如何在一个ant构建脚本达到这样的目的:

                

如欲访问monkeyrunner的运行时环境,启动类可以实现com.google.common.base.Predicate。例如,用这个类在默认的命名空间中设置一些变量:

package com.android.example;  import com.google.common.base.Predicate; import org.python.util.PythonInterpreter;  public class Main implements Predicate {     @Override     public boolean apply(PythonInterpreter anInterpreter) {          /*         * Examples of creating and initializing variables in the monkeyrunner environment's         * namespace. During execution, the monkeyrunner program can refer to the variables "newtest"         * and "use_emulator"         *         */         anInterpreter.set("newtest", "enabled");         anInterpreter.set("use_emulator", 1);          return true;     } }

MonkeyRunner的help文档:
MonkeyRunner helpcom.android.monkeyrunner.MonkeyRunner.alert  Display an alert dialog to the process running the current script.  The dialog is modal, so the script stops until the user dismisses the dialog.    Args:    message - The message to display in the dialog.     title - The dialog's title. The default value is 'Alert'.     okTitle - The text to use in the dialog button. The default value is 'OK'.   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.broadcastIntent  Sends a broadcast intent to the device.    Args:    uri - The URI for the Intent.     action - The action for the Intent.     data - The data URI for the Intent     mimetype - The mime type for the Intent.     categories - An iterable of category names for the Intent.     extras - A dictionary of extras to add to the Intent. Types of these extras are inferred from the python types of the values.     component - The component of the Intent.     flags - An iterable of flags for the Intent.All arguments are optional. The default value for each argument is null.(see android.content.Context.sendBroadcast(Intent))   Returns: returns nothing. com.android.monkeyrunner.MonkeyRunner.choice  Display a choice dialog that allows the user to select a single item from a list of items.    Args:    message - The prompt message to display in the dialog.     choices - An iterable Python type containing a list of choices to display     title - The dialog's title. The default is 'Input'   Returns: The 0-based numeric offset of the selected item in the iterable. com.android.monkeyrunner.MonkeyImage.convertToBytes  Converts the MonkeyImage into a particular format and returns the result as a String. Use this to get access to the rawpixels in a particular format. String output is for better performance.    Args:    format - The destination format (for example, 'png' for Portable Network Graphics format). The default is png.   Returns: The resulting image as a String. com.android.monkeyrunner.MonkeyDevice.drag  Simulates dragging (touch, hold, and move) on the device screen.    Args:    start - The starting point for the drag (a tuple (x,y) in pixels)     end - The end point for the drag (a tuple (x,y) in pixels     duration - Duration of the drag in seconds (default is 1.0 seconds)     steps - The number of steps to take when interpolating points. (default is 10)   Returns: returns nothing. com.android.monkeyrunner.MonkeyView.getAccessibilityIds  Returns the accessibility ids of the current view    Returns: The accessibility ids of the view as a list of ints com.android.monkeyrunner.MonkeyRect.getCenter  Returns a two item list that contains the x and y value of the center of the rectangle    Returns: The center coordinates as a two item list of integers com.android.monkeyrunner.MonkeyView.getChecked  Get the checked status of the view    Returns: A boolean value for whether the item is checked or not com.android.monkeyrunner.MonkeyView.getChildren  Returns the children of the current view    Returns: The children of the view as a list of MonkeyView objects com.android.monkeyrunner.MonkeyView.getEnabled  Returns the enabled status of the view    Returns: The enabled status of the view as a boolean com.android.monkeyrunner.MonkeyView.getFocused  Returns the focused status of the view    Returns: The focused status of the view as a boolean com.android.monkeyrunner.MonkeyRect.getHeight  Returns the height of the rectangle    Returns: The height of the rectangle as an integer com.android.monkeyrunner.MonkeyDevice.getHierarchyViewer  Get the HierarchyViewer object for the device.    Returns: A HierarchyViewer object com.android.monkeyrunner.MonkeyView.getLocation  Returns the location of the view in the form of a MonkeyRect    Returns: The location of the view as a MonkeyRect object com.android.monkeyrunner.MonkeyView.getParent  Returns the parent of the current view    Returns: The parent of the view as a MonkeyView object com.android.monkeyrunner.MonkeyDevice.getProperty  Given the name of a variable on the device, returns the variable's value    Args:    key - The name of the variable. The available names are listed in http://developer.android.com/guide/topics/testing/monkeyrunner.html.   Returns: The variable's value com.android.monkeyrunner.MonkeyDevice.getPropertyList  Retrieve the properties that can be queried    Returns: returns nothing. com.android.monkeyrunner.MonkeyImage.getRawPixel  Get a single ARGB (alpha, red, green, blue) pixel at location x,y. The arguments x and y are 0-based, expressed in pixel dimensions. X increases to the right, and Y increases towards the bottom. This method returns a tuple.    Args:    x - the x offset of the pixel     y - the y offset of the pixel   Returns: A tuple of (A, R, G, B) for the pixel. Each item in the tuple has the range 0-255. com.android.monkeyrunner.MonkeyImage.getRawPixelInt  Get a single ARGB (alpha, red, green, blue) pixel at location x,y. The arguments x and y are 0-based, expressed in pixel dimensions. X increases to the right, and Y increases towards the bottom. This method returns an Integer.    Args:    x - the x offset of the pixel     y - the y offset of the pixel   Returns: An unsigned integer pixel for x,y. The 8 high-order bits are A, followedby 8 bits for R, 8 for G, and 8 for B. com.android.monkeyrunner.MonkeyDevice.getRootView  Obtains current root view    Returns: The root view object com.android.monkeyrunner.MonkeyView.getSelected  Returns the selected status of the view    Returns: The selected status of the view as a boolean com.android.monkeyrunner.MonkeyImage.getSubImage  Copy a rectangular region of the image.    Args:    rect - A tuple (x, y, w, h) describing the region to copy. x and y specify upper lefthand corner of the region. w is the width of the region in pixels, and h is its height.   Returns: a MonkeyImage object representing the copied region. com.android.monkeyrunner.MonkeyDevice.getSystemProperty  Synonym for getProperty()    Args:    key - The name of the system variable.   Returns: The variable's value. com.android.monkeyrunner.MonkeyView.getText  Returns the text contained by the view    Returns: The text contained in the view com.android.monkeyrunner.MonkeyDevice.getViewByAccessibilityIds  Obtains the view with the specified accessibility ids.    Args:    windowId - The window id of the view to retrieve.     accessibility id - The accessibility id of the view to retrieve.   Returns: The view object with the specified id. com.android.monkeyrunner.MonkeyDevice.getViewById  Obtains the view with the specified id.    Args:    id - The id of the view to retrieve.   Returns: The view object with the specified id. com.android.monkeyrunner.MonkeyView.getViewClass  Returns the class name of the view    Returns: The class name of the view as a string com.android.monkeyrunner.MonkeyDevice.getViewIdList  Retrieve the view ids for the current application    Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.getViewsByText  Obtains a list of views that contain the specified text.    Args:    text - The text to search for   Returns: A list of view objects that contain the specified text. com.android.monkeyrunner.MonkeyRect.getWidth  Returns the width of the rectangle    Returns: The width of the rectangle as an integer com.android.monkeyrunner.MonkeyRunner.help  Format and display the API reference for MonkeyRunner.    Args:    format - The desired format for the output, either 'text' for plain text or 'html' for HTML markup.   Returns: A string containing the help text in the desired format. com.android.monkeyrunner.MonkeyRunner.input  Display a dialog that accepts input. The dialog is ,modal, so the script stops until the user clicks one of the two dialog buttons. To enter a value, the user enters the value and clicks the 'OK' button. To quit the dialog without entering a value, the user clicks the 'Cancel' button. Use the supplied arguments for this method to customize the text for these buttons.    Args:    message - The prompt message to display in the dialog.     initialValue - The initial value to supply to the user. The default is an empty string)     title - The dialog's title. The default is 'Input'     okTitle - The text to use in the dialog's confirmation button. The default is 'OK'.The text to use in the dialog's 'cancel' button. The default is 'Cancel'.     cancelTitle -   Returns: The test entered by the user, or None if the user canceled the input; com.android.monkeyrunner.MonkeyDevice.installPackage  Installs the specified Android package (.apk file) onto the device. If the package already exists on the device, it is replaced.    Args:    path - The package's path and filename on the host filesystem.   Returns: True if the install succeeded com.android.monkeyrunner.MonkeyDevice.instrument  Run the specified package with instrumentation and return the output it generates. Use this to run a test package using InstrumentationTestRunner.    Args:    className - The class to run with instrumentation. The format is packagename/classname. Use packagename to specify the Android package to run, and classname to specify the class to run within that package. For test packages, this is usually testpackagename/InstrumentationTestRunner     args - A map of strings to objects containing the arguments to pass to this instrumentation (default value is None).   Returns: A map of strings to objects for the output from the package. For a test package, contains a single key-value pair: the key is 'stream' and the value is a string containing the test output. com.android.monkeyrunner.MonkeyRunner.loadImageFromFile  Loads a MonkeyImage from a file.    Args:    path - The path to the file to load.  This file path is in terms of the computer running MonkeyRunner and not a path on the Android Device.    Returns: A new MonkeyImage representing the specified file com.android.monkeyrunner.MonkeyDevice.press  Send a key event to the specified key    Args:    name - the keycode of the key to press (see android.view.KeyEvent)     type - touch event type as returned by TouchPressType(). To simulate typing a key, send DOWN_AND_UP   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.reboot  Reboots the specified device into a specified bootloader.    Args:    into - the bootloader to reboot into: bootloader, recovery, or None   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.removePackage  Deletes the specified package from the device, including its associated data and cache.    Args:    package - The name of the package to delete.   Returns: True if remove succeeded com.android.monkeyrunner.MonkeyImage.sameAs  Compare this MonkeyImage object to aother MonkeyImage object.    Args:    other - The other MonkeyImage object.     percent - A float in the range 0.0 to 1.0, indicating the percentage of pixels that need to be the same for the method to return 'true'. Defaults to 1.0.   Returns: boolean 'true' if the two objects contain the same image. com.android.monkeyrunner.MonkeyView.setFocused  Sets the focused status of the view    Args:    focused - The boolean value to set focused to   Returns: returns nothing. com.android.monkeyrunner.MonkeyView.setSelected  Sets the selected status of the view    Args:    selected - The boolean value to set selected to   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.shell  Executes an adb shell command and returns the result, if any.    Args:    cmd - The adb shell command to execute.   Returns: The output from the command. com.android.monkeyrunner.MonkeyRunner.sleep  Pause the currently running program for the specified number of seconds.    Args:    seconds - The number of seconds to pause.   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.startActivity  Starts an Activity on the device by sending an Intent constructed from the specified parameters.    Args:    uri - The URI for the Intent.     action - The action for the Intent.     data - The data URI for the Intent     mimetype - The mime type for the Intent.     categories - A Python iterable containing the category names for the Intent.     extras - A dictionary of extras to add to the Intent. Types of these extras are inferred from the python types of the values.     component - The component of the Intent.     flags - An iterable of flags for the Intent.All arguments are optional. The default value for each argument is null.(see android.content.Intent)   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.takeSnapshot  Gets the device's screen buffer, yielding a screen capture of the entire display.    Returns: A MonkeyImage object (a bitmap wrapper) com.android.monkeyrunner.MonkeyDevice.touch  Sends a touch event at the specified location    Args:    x - x coordinate in pixels     y - y coordinate in pixels     type - touch event type as returned by TouchPressType()   Returns: returns nothing. com.android.monkeyrunner.MonkeyDevice.type  Types the specified string on the keyboard. This is equivalent to calling press(keycode,DOWN_AND_UP) for each character in the string.    Args:    message - The string to send to the keyboard.   Returns: returns nothing. com.android.monkeyrunner.MonkeyRunner.waitForConnection  Waits for the workstation to connect to the device.    Args:    timeout - The timeout in seconds to wait. The default is to wait indefinitely.     deviceId - A regular expression that specifies the device name. See the documentation for 'adb' in the Developer Guide to learn more about device names.   Returns: A ChimpDevice object representing the connected device. com.android.monkeyrunner.MonkeyDevice.wake  Wake up the screen on the device    Returns: returns nothing. com.android.monkeyrunner.MonkeyImage.writeToFile  Write the MonkeyImage to a file.  If no format is specified, this method guesses the output format based on the extension of the provided file extension. If it is unable to guess the format, it uses PNG.    Args:    path - The output filename, optionally including its path     format - The destination format (for example, 'png' for  Portable Network Graphics format.   Returns: boolean true if writing succeeded. 




 

原创粉丝点击