In previous articles, we have introduced monkey, JUnit, robotium, And the JUnit-based Android testing framework. In this article, we will introduce monkeyrunner.
1. What is monkeyrunner?
The monkeyrunner tool provides an API to control Android devices and Simulators in addition to Android code. With monkeyrunner, you can write a python program to install an Android Application or test package, run it, send a simulated press key to it, and capture its user interface image, and stored on the workstation. The primary purpose of the monkeyrunner tool is to test applications and devices at the functional/framework level, or to run the unit test suite, but you can also use it for other purposes.
2. Differences between the monkeyrunner tool and the monkey Tool
Monkey:
The monkey tool runs directly in the ADB shell of the device or simulator to generate a pseudo-random event stream of the user or system.
Monkeyrunner:
The monkeyrunner tool is a specific command and event control device or simulator defined on the workstation through APIS.
3. monkeyrunner test Type
- 1. Multi-Device Control: the monkeyrunner API can implement a test suite across multiple devices or simulators. You can connect to all devices at the same time or start all simulators (or all together), connect to each device in sequence based on programs, and then run one or more tests. You can also use a program to start a configured simulator, run one or more tests, and then close the simulator.
- Function Test: monkeyrunner can automatically perform a function test for an application. You can provide the input values of buttons or touch events, and then observe the screenshots of the output results.
- Regression testing: monkeyrunner can run an application and compare the result screenshots with the results screenshots that are known to be correct to test the stability of the application.
- Scalable automation: Since monkeyrunner is an API toolkit, you can develop a complete set of systems based on Python modules and programs to control Android devices. In addition to using the monkeyrunner API, you can also use standard Python OS and subprocess modules to call Android tools such as Android debug bridge.
4. Run monkeyrunner.
You can directly use a code file to run monkeyrunner, or enter the monkeyrunner statement in the Interactive dialog box. Either way, you need to call the monkeyrunner command under the tools subdirectory of the SDK directory. If you provide a file name as a running parameter, monkeyrunner regards the file content as a python program and runs it. Otherwise, it provides an Interactive dialog environment.
The command syntax of monkeyrunner is:
Monkeyrunner-plugin <plugin_jar> <program_filename> <program_options>
5. instance 1
5.1 simple instanceTake apidemos in sampleas an example to generate apidemos.apk first.
Premise: A device is connected.
1) Place apidemos.apk under $ android_root \ tools.
2) create a monkeyrunnerprogram. py file under $ android_root \ tools with the following content:
# Imports the monkeyrunner modules used by this programfrom com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage# Connects to the current device, returning a MonkeyDevice objectdevice = MonkeyRunner.waitForConnection()# Installs the Android package. Notice that this method returns a boolean, so you can test# to see if the installation worked.device.installPackage('./ApiDemos.apk')# Runs the componentdevice.startActivity(component='com.example.android.apis/.ApiDemos')# Presses the Menu buttondevice.press('KEYCODE_MENU','DOWN_AND_UP')# Takes a screenshotresult = device.takeSnapshot()# Writes the screenshot to a fileresult.writeToFile('./shot1.png','png')
Note: Some examples on the SDK are incorrect and cannot be copied directly. Otherwise, an error occurs during command execution. You can compare it with the above Code.
3) Open the command line and go to the android_root \ tools directory to run the command:
Monkeyrunner monkeyrunnerprogram. py if no error occurs, the shot1.png file is generated in the $ android_root \ toolsdirectory after the task is completed. Note that the command line does not output any errors during running.5.2 extended instancesBecause no menu appears when you press the menu key on the apidemos homepage, you can continue the experiment on the basis of instance 5 for better visualization:
1) create a monkeyrunnerprogram1.py file under $ android_root \ tools with the following content:
# Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage# Connects to the current device, returning a MonkeyDevice objectdevice = MonkeyRunner.waitForConnection()# Takes a screenshotresult = device.takeSnapshot()# Writes the screenshot to a file result.writeToFile('./shotbegin.png','png')# Presses the Down buttondevice.press('KEYCODE_DPAD_DOWN','DOWN_AND_UP')device.press('KEYCODE_DPAD_DOWN','DOWN_AND_UP')device.press('KEYCODE_DPAD_DOWN','DOWN_AND_UP')device.press('KEYCODE_DPAD_DOWN','DOWN_AND_UP')device.press('KEYCODE_DPAD_DOWN','DOWN_AND_UP')# Takes a screenshotresult = device.takeSnapshot()# Writes the screenshot to a fileresult.writeToFile('./shotend.png','png')
2) position the screen on the homepage of apidemos, and position the cursor on the first item.
3) run the following command in the $ android_root \ tools directory:
Monkeyrunner monkeyrunnerprogram1.py
4) during the running process, we can see that the cursor keeps moving down and can customize it in the current directory:
Before running: shotbegin.png6. extend the application instanceThe following provides some common scripts for you to change them ..
Monkey_recorder.py
Monkey_placback.py
Help. py is specific to: monkeyrunner_pyscript. rar although there are few missing items, it does not affect most of our needs. Next we will use a typical monkeyrunner code to explain it!
Note! If the monkeyrunner script file must be in Chinese, remember to save it as utf8. Otherwise, ascnii (forgot how to spell...) cannot support errors.6.1 takescreen. pyFile takescreen. py
# Import the packages and classes we need and use the alias import sysfrom COM. android. monkeyrunner import monkeyrunner as mrfrom COM. android. monkeyrunner import monkeydevice as mdfrom COM. android. monkeyrunner import monkeyimage as mi # connect device connects to the device # The first parameter is waiting for the device to be connected # The second parameter is the device to be connected = mr. waitforconnection () if not device: Print> sys. stderr, "fail" sys. exit (1) # define activitycomponentname = 'com. example. android. notepad /. noteslist '# Start a specific activitydevice. startactivity (Component = componentname) Mr. sleep (3.0) # do someting for our operation # input a s d # device. press ('keycode _ home') # device. touch (418,736, 'down _ and_up ') # mr. sleep (3.0) # device. touch (180,520, 'down _ and_up ') # mr. sleep (3.0) device. press ('keycode _ menu ') Mr. sleep (3.0) device. touch (243,745, 'down _ and_up ') Mr. sleep (3.0) device. type ('woaini ') device. press ('keycode _ enter') Mr. sleep (3.0) device. type (',') device. press ('keycode _ enter') Mr. sleep (3.0) device. type ('yunwen') device. press ('keycode _ enter') Mr. sleep (3.0) device. press ('keycode _ back') # device. press ('keycode _ home') # device. type ('asd ') # enter the carriage return # device. press ('keycode _ enter') # Return keyboard click back to cancel the white bars at the bottom of the page. # device. press ('keycode _ back') # ------ # takesnapshotmr. sleep (3.0) Result = device. takesnapshot () # Save to file to save to file result.writetofile('result1.png ', 'png ');
The notelist instance used here is similar to the notepad instance provided by Android.
The running result is (fig. result1.png ):
6.2 Record and playback of monkeyrunnerI 've talked about some operations on the command line. I can't remember so many command operations. I don't know what the coordinates of the point I clicked are. How much hope I have, I can record my operations on the visual interface and then play them again directly, just like a macro. I'm glad to tell you that, monkeyrunner has this function, which is also very simple to implement. One of the package files I provide is monkey_recorder.py, which is directly marked with monkeyrunner monkey_recorder.py on the command line. The mobile phone screen part is shown, it is consistent with the screen display of the currently connected Mobile phone device. Some instructions on the script display: Next, run our saved script, and then you will see the simulator, run the same monkeyrunner monkey_playback.py monkey_test.mr. Open our file and you can see that it is actually some monkeyrunner scripts.
TOUCH|{'x':329,'y':132,'type':'downAndUp',} TOUCH|{'x':100,'y':100,'type':'downAndUp',} TOUCH|{'x':296,'y':407,'type':'downAndUp',} TOUCH|{'x':296,'y':407,'type':'downAndUp',} TOUCH|{'x':296,'y':407,'type':'downAndUp',} TOUCH|{'x':296,'y':407,'type':'downAndUp',} TOUCH|{'x':351,'y':227,'type':'downAndUp',}
Of course, why not use an interface ~~~ Haha ~
Add: What if we want to perform a multi-device test?
You can open the monkey_playback.py file.
#!/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 sysfrom 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()
So far, we have briefly introduced monkeyrunner. I believe you have a general understanding of others and can simply use them. If you still cannot understand it, you can check all the source code in mongomonkeyrunner_pyscript .rar and the description files of various classes of monkeyrunner. In addition, the original Google instruction file is http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html. For more information, see. Download the source code: http://download.csdn.net/detail/xianming01/4103617 :: monkeyrunnertool automatically tested by android.
Monkey and monkeyrunner for Android