Remove monkeyrunner so it can move to the SDK project.

Change-Id: Ibedfae41cf8a71d66f25267cd3a360de222e2644
This commit is contained in:
Bill Napier
2010-07-27 16:08:06 -07:00
parent 235a95ae49
commit 32553f5291
10 changed files with 0 additions and 1423 deletions

View File

@@ -1,18 +0,0 @@
#
# Copyright (C) 2009 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.
#
MONKEYRUNNER_LOCAL_DIR := $(call my-dir)
include $(MONKEYRUNNER_LOCAL_DIR)/etc/Android.mk
include $(MONKEYRUNNER_LOCAL_DIR)/src/Android.mk

View File

@@ -1,190 +0,0 @@
Copyright (c) 2005-2008, 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.
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.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -1,20 +0,0 @@
#
# Copyright (C) 2009 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.
#
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_PREBUILT_EXECUTABLES := monkeyrunner
include $(BUILD_HOST_PREBUILT)

View File

@@ -1 +0,0 @@
Main-Class: com.android.monkeyrunner.MonkeyRunner

View File

@@ -1,74 +0,0 @@
#!/bin/sh
# Copyright 2005-2007, 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.
# Set up prog to be the path of this script, including following symlinks,
# and set up progdir to be the fully-qualified pathname of its directory.
prog="$0"
while [ -h "${prog}" ]; do
newProg=`/bin/ls -ld "${prog}"`
newProg=`expr "${newProg}" : ".* -> \(.*\)$"`
if expr "x${newProg}" : 'x/' >/dev/null; then
prog="${newProg}"
else
progdir=`dirname "${prog}"`
prog="${progdir}/${newProg}"
fi
done
oldwd=`pwd`
progdir=`dirname "${prog}"`
cd "${progdir}"
progdir=`pwd`
prog="${progdir}"/`basename "${prog}"`
cd "${oldwd}"
jarfile=monkeyrunner.jar
frameworkdir="$progdir"
libdir="$progdir"
if [ ! -r "$frameworkdir/$jarfile" ]
then
frameworkdir=`dirname "$progdir"`/tools/lib
libdir=`dirname "$progdir"`/tools/lib
fi
if [ ! -r "$frameworkdir/$jarfile" ]
then
frameworkdir=`dirname "$progdir"`/framework
libdir=`dirname "$progdir"`/lib
fi
if [ ! -r "$frameworkdir/$jarfile" ]
then
echo `basename "$prog"`": can't find $jarfile"
exit 1
fi
# Check args.
if [ debug = "$1" ]; then
# add this in for debugging
java_debug=-agentlib:jdwp=transport=dt_socket,server=y,address=8050,suspend=y
shift 1
else
java_debug=
fi
if [ "$OSTYPE" = "cygwin" ] ; then
jarpath=`cygpath -w "$frameworkdir/$jarfile"`
progdir=`cygpath -w "$progdir"`
else
jarpath="$frameworkdir/$jarfile"
fi
# need to use "java.ext.dirs" because "-jar" causes classpath to be ignored
# might need more memory, e.g. -Xmx128M
exec java -Xmx128M $os_opts $java_debug -Djava.ext.dirs="$frameworkdir" -Djava.library.path="$libdir" -Dcom.android.monkeyrunner.bindir="$progdir" -jar "$jarpath" "$@"

View File

@@ -1,51 +0,0 @@
#
# Copyright (C) 2009 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.
#
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_JAR_MANIFEST := ../etc/manifest.txt
LOCAL_JAVA_LIBRARIES := \
ddmlib \
jython \
xmlwriter
LOCAL_MODULE := monkeyrunner
include $(BUILD_HOST_JAVA_LIBRARY)
# Build ext.jar
# ============================================================
ext_dirs := ../../../../external/xmlwriter/src
ext_src_files := $(call all-java-files-under,$(ext_dirs))
# ==== the library =========================================
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(ext_src_files)
LOCAL_NO_STANDARD_LIBRARIES := true
#LOCAL_JAVA_LIBRARIES := core
#LOCAL_STATIC_JAVA_LIBRARIES := libgoogleclient
LOCAL_MODULE := xmlwriter
include $(BUILD_HOST_JAVA_LIBRARY)

View File

@@ -1,299 +0,0 @@
/*
* Copyright (C) 2009 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.
*/
package com.android.monkeyrunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.jheer.XMLWriter;
/**
* MonkeyRecorder is a host side class that records the output of scripts that are run.
* It creates a unique directory, puts in an xml file that records each cmd and result.
* It stores every screenshot in this directory.
* When finished, it zips this all up.
*
* Calling Sequence:
* mr = new MonkeyRecorder(scriptName);
* mr.startCommand();
* [mr.addAttribute(name, value);]
* ...
* [mr.addInput(cmd);]
* [mr.addResults(result, filename);] // filename = "" if no screenshot
* mr.endCommand();
* mr.addComment(comment);
* mr.startCommand();
* ...
* mr.endCommand();
* ...
* mr.close();
*
* With MonkeyRunner this should output an xml file, <script_name>-yyyyMMdd-HH:mm:ss.xml, into the
* directory out/<script_name>-yyyyMMdd-HH:mm:ss with the contents like:
*
* <?xml version="1.0" encoding='UTF-8'?>
* <!-- Monkey Script Results -->
* <script_run script_name="filename" monkeyRunnerVersion="0.2">
* <!-- Device specific variables -->
* <device_var var_name="name" var_value="value" />
* <device_var name="build.display" value="opal-userdebug 1.6 DRC79 14207 test-keys"/>
* ...
* <!-- Script commands -->
* <command>
* dateTime="20090921-17:08:43"
* <input cmd="Pressing: menu"/>
* <response result="OK" dateTime="20090921-17:08:43"/>
* </command>
* ...
* <command>
* dateTime="20090921-17:09:44"
* <input cmd="grabscreen"/>
* <response result="OK" dateTime="20090921-17:09:45" screenshot="home_screen-20090921-17:09:45.png"/>
* </command>
* ...
* </script_run>
*
* And then zip it up with all the screenshots in the file: <script_name>-yyyyMMdd-HH:mm:ss.zip.
*/
public class MonkeyRecorder {
// xml file to store output results in
private static String mXmlFilename;
private static FileWriter mXmlFile;
private static XMLWriter mXmlWriter;
// unique subdirectory to put results in (screenshots and xml file)
private static String mDirname;
private static List<String> mScreenShotNames = new ArrayList<String>();
// where we store all the results for all the script runs
private static final String ROOT_DIR = "out";
// for getting the date and time in now()
private static final SimpleDateFormat SIMPLE_DATE_TIME_FORMAT =
new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
/**
* Create a new MonkeyRecorder that records commands and zips up screenshots for submittal
*
* @param scriptName filepath of the monkey script we are running
*/
public MonkeyRecorder(String scriptName, String version) throws IOException {
// Create directory structure to store xml file, images and zips
File scriptFile = new File(scriptName);
scriptName = scriptFile.getName(); // Get rid of path
mDirname = ROOT_DIR + "/" + stripType(scriptName) + "-" + now();
new File(mDirname).mkdirs();
// Initialize xml file
mXmlFilename = stampFilename(stripType(scriptName) + ".xml");
initXmlFile(scriptName, version);
}
// Get the current date and time in a simple string format (used for timestamping filenames)
private static String now() {
return SIMPLE_DATE_TIME_FORMAT.format(Calendar.getInstance().getTime());
}
/**
* Initialize the xml file writer
*
* @param scriptName filename (not path) of the monkey script, stored as attribute in the xml file
* @param version of the monkey runner test system
*/
private static void initXmlFile(String scriptName, String version) throws IOException {
String[] names = new String[] { "script_name", "monkeyRunnerVersion" };
String[] values = new String[] { scriptName, version };
mXmlFile = new FileWriter(mDirname + "/" + mXmlFilename);
mXmlWriter = new XMLWriter(mXmlFile);
mXmlWriter.begin();
mXmlWriter.comment("Monkey Script Results");
mXmlWriter.start("script_run", names, values, names.length);
}
/**
* Add a comment to the xml file.
*
* @param comment comment to add to the xml file
*/
public static void addComment(String comment) throws IOException {
mXmlWriter.comment(comment);
}
/**
* Begin writing a command xml element
*/
public static void startCommand() throws IOException {
mXmlWriter.start("command", "dateTime", now());
}
/**
* Write a command name attribute in a command xml element.
* It's add as a sinlge script command could be multiple monkey commands.
*
* @param cmd command sent to the monkey
*/
public static void addInput(String cmd) throws IOException {
String name = "cmd";
String value = cmd;
mXmlWriter.tag("input", name, value);
}
/**
* Write a response xml element in a command.
* Attributes include the monkey result, datetime, and possibly screenshot filename
*
* @param result response of the monkey to the command
* @param filename filename of the screen shot (or other file to be included)
*/
public static void addResult(String result, String filename) throws IOException {
int num_args = 2;
String[] names = new String[3];
String[] values = new String[3];
names[0] = "result";
values[0] = result;
names[1] = "dateTime";
values[1] = now();
if (filename.length() != 0) {
names[2] = "screenshot";
values[2] = stampFilename(filename);
addScreenShot(filename);
num_args = 3;
}
mXmlWriter.tag("response", names, values, num_args);
}
/**
* Add an attribut to an open xml element. name="escaped_value"
*
* @param name name of the attribute
* @param value value of the attribute
*/
public static void addAttribute(String name, String value) throws IOException {
mXmlWriter.addAttribute(name, value);
}
/**
* Add an xml device variable element. name="escaped_value"
*
* @param name name of the variable
* @param value value of the variable
*/
public static void addDeviceVar(String name, String value) throws IOException {
String[] names = {"name", "value"};
String[] values = {name, value};
mXmlWriter.tag("device_var", names, values, names.length);
}
/**
* Move the screenshot to storage and remember you did it so it can be zipped up later.
*
* @param filename file name of the screenshot to be stored (Not path name)
*/
private static void addScreenShot(String filename) {
File file = new File(filename);
String screenShotName = stampFilename(filename);
file.renameTo(new File(mDirname, screenShotName));
mScreenShotNames.add(screenShotName);
}
/**
* Finish writing a command xml element
*/
public static void endCommand() throws IOException {
mXmlWriter.end();
}
/**
* Add datetime in front of filetype (the stuff after and including the last infamous '.')
*
* @param filename path of file to be stamped
*/
private static String stampFilename(String filename) {
//
int typeIndex = filename.lastIndexOf('.');
if (typeIndex == -1) {
return filename + "-" + now();
}
return filename.substring(0, typeIndex) + "-" + now() + filename.substring(typeIndex);
}
/**
* Strip out the file type (the stuff after and including the last infamous '.')
*
* @param filename path of file to be stripped of type information
*/
private static String stripType(String filename) {
//
int typeIndex = filename.lastIndexOf('.');
if (typeIndex == -1)
return filename;
return filename.substring(0, typeIndex);
}
/**
* Close the monkeyRecorder by closing the xml file and zipping it up with the screenshots.
*
* @param filename path of file to be stripped of type information
*/
public static void close() throws IOException {
// zip up xml file and screenshots into ROOT_DIR.
byte[] buf = new byte[1024];
String zipFileName = mXmlFilename + ".zip";
endCommand();
mXmlFile.close();
FileOutputStream zipFile = new FileOutputStream(ROOT_DIR + "/" + zipFileName);
ZipOutputStream out = new ZipOutputStream(zipFile);
// add the xml file
addFileToZip(out, mDirname + "/" + mXmlFilename, buf);
// Add the screenshots
for (String filename : mScreenShotNames) {
addFileToZip(out, mDirname + "/" + filename, buf);
}
out.close();
}
/**
* Helper function to zip up a file into an open zip archive.
*
* @param zip the stream of the zip archive
* @param filepath the filepath of the file to be added to the zip archive
* @param buf storage place to stage reads of file before zipping
*/
private static void addFileToZip(ZipOutputStream zip, String filepath, byte[] buf) throws IOException {
FileInputStream in = new FileInputStream(filepath);
zip.putNextEntry(new ZipEntry(filepath));
int len;
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
zip.closeEntry();
in.close();
}
}

View File

@@ -1,674 +0,0 @@
/*
* Copyright (C) 2009 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.
*/
package com.android.monkeyrunner;
import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import com.android.ddmlib.NullOutputReceiver;
import com.android.ddmlib.RawImage;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;
import com.android.ddmlib.Log.ILogOutput;
import com.android.ddmlib.Log.LogLevel;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* MonkeyRunner is a host side application to control a monkey instance on a
* device. MonkeyRunner provides some useful helper functions to control the
* device as well as various other methods to help script tests.
*/
public class MonkeyRunner {
static String monkeyServer = "127.0.0.1";
static int monkeyPort = 1080;
static Socket monkeySocket = null;
static IDevice monkeyDevice;
static BufferedReader monkeyReader;
static BufferedWriter monkeyWriter;
static String monkeyResponse;
static MonkeyRecorder monkeyRecorder;
static String scriptName = null;
// Obtain a suitable logger.
private static Logger logger = Logger.getLogger("com.android.monkeyrunner");
// delay between key events
final static int KEY_INPUT_DELAY = 1000;
// version of monkey runner
final static String monkeyRunnerVersion = "0.4";
// TODO: interface cmd; class xml tags; fix logger; test class/script
public static void main(String[] args) throws IOException {
// haven't figure out how to get below INFO...bad parent. Pass -v INFO to turn on logging
logger.setLevel(Level.parse("WARNING"));
processOptions(args);
logger.info("initAdb");
initAdbConnection();
logger.info("openMonkeyConnection");
openMonkeyConnection();
logger.info("start_script");
start_script();
logger.info("ScriptRunner.run");
ScriptRunner.run(scriptName);
logger.info("end_script");
end_script();
logger.info("closeMonkeyConnection");
closeMonkeyConnection();
}
/**
* Initialize an adb session with a device connected to the host
*
*/
public static void initAdbConnection() {
String adbLocation = "adb";
boolean device = false;
boolean emulator = false;
String serial = null;
AndroidDebugBridge.init(false /* debugger support */);
try {
AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(
adbLocation, true /* forceNewBridge */);
// we can't just ask for the device list right away, as the internal thread getting
// them from ADB may not be done getting the first list.
// Since we don't really want getDevices() to be blocking, we wait here manually.
int count = 0;
while (bridge.hasInitialDeviceList() == false) {
try {
Thread.sleep(100);
count++;
} catch (InterruptedException e) {
// pass
}
// let's not wait > 10 sec.
if (count > 100) {
System.err.println("Timeout getting device list!");
return;
}
}
// now get the devices
IDevice[] devices = bridge.getDevices();
if (devices.length == 0) {
printAndExit("No devices found!", true /* terminate */);
}
monkeyDevice = null;
if (emulator || device) {
for (IDevice d : devices) {
// this test works because emulator and device can't both be true at the same
// time.
if (d.isEmulator() == emulator) {
// if we already found a valid target, we print an error and return.
if (monkeyDevice != null) {
if (emulator) {
printAndExit("Error: more than one emulator launched!",
true /* terminate */);
} else {
printAndExit("Error: more than one device connected!",true /* terminate */);
}
}
monkeyDevice = d;
}
}
} else if (serial != null) {
for (IDevice d : devices) {
if (serial.equals(d.getSerialNumber())) {
monkeyDevice = d;
break;
}
}
} else {
if (devices.length > 1) {
printAndExit("Error: more than one emulator or device available!",
true /* terminate */);
}
monkeyDevice = devices[0];
}
monkeyDevice.createForward(monkeyPort, monkeyPort);
String command = "monkey --port " + monkeyPort;
monkeyDevice.executeShellCommand(command, new NullOutputReceiver());
} catch(TimeoutException e) {
e.printStackTrace();
} catch (AdbCommandRejectedException e) {
e.printStackTrace();
} catch (ShellCommandUnresponsiveException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
/**
* Open a tcp session over adb with the device to communicate monkey commands
*/
public static void openMonkeyConnection() {
try {
InetAddress addr = InetAddress.getByName(monkeyServer);
monkeySocket = new Socket(addr, monkeyPort);
monkeyWriter = new BufferedWriter(new OutputStreamWriter(monkeySocket.getOutputStream()));
monkeyReader = new BufferedReader(new InputStreamReader(monkeySocket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
/**
* Close tcp session with the monkey on the device
*
*/
public static void closeMonkeyConnection() {
try {
monkeyReader.close();
monkeyWriter.close();
monkeySocket.close();
AndroidDebugBridge.terminate();
} catch(IOException e) {
e.printStackTrace();
}
}
/**
* This is a house cleaning routine to run before starting a script. Puts
* the device in a known state and starts recording interesting info.
*/
public static void start_script() throws IOException {
press("menu", false);
press("menu", false);
press("home", false);
// Start recording the script output, might want md5 signature of file for completeness
monkeyRecorder = new MonkeyRecorder(scriptName, monkeyRunnerVersion);
// Record what device we are running on
addDeviceVars();
monkeyRecorder.addComment("Script commands");
}
/**
* This is a house cleaning routine to run after finishing a script.
* Puts the monkey server in a known state and closes the recording.
*/
public static void end_script() throws IOException {
String command = "done";
sendMonkeyEvent(command, false, false);
// Stop the recording and zip up the results
monkeyRecorder.close();
}
/** This is a method for scripts to launch an activity on the device
*
* @param name The name of the activity to launch
*/
public static void launch_activity(String name) throws IOException,
TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException {
System.out.println("Launching: " + name);
recordCommand("Launching: " + name);
monkeyDevice.executeShellCommand("am start -a android.intent.action.MAIN -n "
+ name, new NullOutputReceiver());
// void return, so no response given, just close the command element in the xml file.
monkeyRecorder.endCommand();
}
/**
* Grabs the current state of the screen stores it as a png
*
* @param tag filename or tag descriptor of the screenshot
*/
public static void grabscreen(String tag) throws IOException {
tag += ".png";
try {
Thread.sleep(1000);
getDeviceImage(monkeyDevice, tag, false);
} catch (InterruptedException e) {
}
}
/**
* Sleeper method for script to call
*
* @param msec msecs to sleep for
*/
public static void sleep(int msec) throws IOException {
try {
recordCommand("sleep: " + msec);
Thread.sleep(msec);
recordResponse("OK");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Tap function for scripts to call at a particular x and y location
*
* @param x x-coordinate
* @param y y-coordinate
*/
public static boolean tap(int x, int y) throws IOException {
String command = "tap " + x + " " + y;
boolean result = sendMonkeyEvent(command);
return result;
}
/**
* Press function for scripts to call on a particular button or key
*
* @param key key to press
*/
public static boolean press(String key) throws IOException {
return press(key, true);
}
/**
* Press function for scripts to call on a particular button or key
*
* @param key key to press
* @param print whether to send output to user
*/
private static boolean press(String key, boolean print) throws IOException {
String command = "press " + key;
boolean result = sendMonkeyEvent(command, print, true);
return result;
}
/**
* dpad down function
*/
public static boolean down() throws IOException {
return press("dpad_down");
}
/**
* dpad up function
*/
public static boolean up() throws IOException {
return press("dpad_up");
}
/**
* Function to type text on the device
*
* @param text text to type
*/
public static boolean type(String text) throws IOException {
boolean result = false;
// text might have line ends, which signal new monkey command, so we have to eat and reissue
String[] lines = text.split("[\\r\\n]+");
for (String line: lines) {
result = sendMonkeyEvent("type " + line + "\n");
}
// return last result. Should never fail..?
return result;
}
/**
* Function to get a static variable from the device
*
* @param name name of static variable to get
*/
public static boolean getvar(String name) throws IOException {
return sendMonkeyEvent("getvar " + name + "\n");
}
/**
* Function to get the list of static variables from the device
*/
public static boolean listvar() throws IOException {
return sendMonkeyEvent("listvar \n");
}
/**
* This function is the communication bridge between the host and the device.
* It sends monkey events and waits for responses over the adb tcp socket.
* This version if for all scripted events so that they get recorded and reported to user.
*
* @param command the monkey command to send to the device
*/
private static boolean sendMonkeyEvent(String command) throws IOException {
return sendMonkeyEvent(command, true, true);
}
/**
* This function allows the communication bridge between the host and the device
* to be invisible to the script for internal needs.
* It splits a command into monkey events and waits for responses for each over an adb tcp socket.
* Returns on an error, else continues and sets up last response.
*
* @param command the monkey command to send to the device
* @param print whether to print out the responses to the user
* @param record whether to put the command in the xml file that stores test outputs
*/
private static boolean sendMonkeyEvent(String command, Boolean print, Boolean record) throws IOException {
command = command.trim();
if (print)
System.out.println("MonkeyCommand: " + command);
if (record)
recordCommand(command);
logger.info("Monkey Command: " + command + ".");
// send a single command and get the response
monkeyWriter.write(command + "\n");
monkeyWriter.flush();
monkeyResponse = monkeyReader.readLine();
if(monkeyResponse != null) {
// if a command returns with a response
if (print)
System.out.println("MonkeyServer: " + monkeyResponse);
if (record)
recordResponse(monkeyResponse);
logger.info("Monkey Response: " + monkeyResponse + ".");
// return on error
if (monkeyResponse.startsWith("ERROR"))
return false;
// return on ok
if(monkeyResponse.startsWith("OK"))
return true;
// return on something else?
return false;
}
// didn't get a response...
if (print)
System.out.println("MonkeyServer: ??no response");
if (record)
recordResponse("??no response");
logger.info("Monkey Response: ??no response.");
//return on no response
return false;
}
/**
* Record the command in the xml file
*
* @param command the command sent to the monkey server
*/
private static void recordCommand(String command) throws IOException {
if (monkeyRecorder != null) { // don't record setup junk
monkeyRecorder.startCommand();
monkeyRecorder.addInput(command);
}
}
/**
* Record the response in the xml file
*
* @param response the response sent by the monkey server
*/
private static void recordResponse(String response) throws IOException {
recordResponse(response, "");
}
/**
* Record the response and the filename in the xml file, store the file (to be zipped up later)
*
* @param response the response sent by the monkey server
* @param filename the filename of a file to be time stamped, recorded in the xml file and stored
*/
private static void recordResponse(String response, String filename) throws IOException {
if (monkeyRecorder != null) { // don't record setup junk
monkeyRecorder.addResult(response, filename); // ignores file if filename empty
monkeyRecorder.endCommand();
}
}
/**
* Add the device variables to the xml file in monkeyRecorder.
* The results get added as device_var tags in the script_run tag
*/
private static void addDeviceVars() throws IOException {
monkeyRecorder.addComment("Device specific variables");
sendMonkeyEvent("listvar \n", false, false);
if (monkeyResponse.startsWith("OK:")) {
// peel off "OK:" string and get the individual var names
String[] varNames = monkeyResponse.substring(3).split("\\s+");
// grab all the individual var values
for (String name: varNames) {
sendMonkeyEvent("getvar " + name, false, false);
if(monkeyResponse != null) {
if (monkeyResponse.startsWith("OK") ) {
if (monkeyResponse.length() > 2) {
monkeyRecorder.addDeviceVar(name, monkeyResponse.substring(3));
} else {
// only got OK - good variable but no value
monkeyRecorder.addDeviceVar(name, "null");
}
} else {
// error returned - couldn't get var value for name... include error return
monkeyRecorder.addDeviceVar(name, monkeyResponse);
}
} else {
// no monkeyResponse - bad variable with no value
monkeyRecorder.addDeviceVar(name, "null");
}
}
} else {
// it's an error, can't find variable names...
monkeyRecorder.addAttribute("listvar", monkeyResponse);
}
}
/**
* Process the command-line options
*
* @return Returns true if options were parsed with no apparent errors.
*/
private static void processOptions(String[] args) {
// parse command line parameters.
int index = 0;
do {
String argument = args[index++];
if ("-s".equals(argument)) {
if(index == args.length) {
printUsageAndQuit("Missing Server after -s");
}
monkeyServer = args[index++];
} else if ("-p".equals(argument)) {
// quick check on the next argument.
if (index == args.length) {
printUsageAndQuit("Missing Server port after -p");
}
monkeyPort = Integer.parseInt(args[index++]);
} else if ("-v".equals(argument)) {
// quick check on the next argument.
if (index == args.length) {
printUsageAndQuit("Missing Log Level after -v");
}
Level level = Level.parse(args[index++]);
logger.setLevel(level);
level = logger.getLevel();
System.out.println("Log level set to: " + level + "(" + level.intValue() + ").");
System.out.println("Warning: Log levels below INFO(800) not working currently... parent issues");
} else if (argument.startsWith("-")) {
// we have an unrecognized argument.
printUsageAndQuit("Unrecognized argument: " + argument + ".");
monkeyPort = Integer.parseInt(args[index++]);
} else {
// get the filepath of the script to run. This will be the last undashed argument.
scriptName = argument;
}
} while (index < args.length);
}
/*
* Grab an image from an ADB-connected device.
*/
private static void getDeviceImage(IDevice device, String filepath, boolean landscape)
throws IOException {
RawImage rawImage;
recordCommand("grabscreen");
System.out.println("Grabbing Screeshot: " + filepath + ".");
try {
rawImage = device.getScreenshot();
}
catch (IOException ioe) {
recordResponse("No frame buffer", "");
printAndExit("Unable to get frame buffer: " + ioe.getMessage(), true /* terminate */);
return;
} catch (TimeoutException toe) {
recordResponse("No frame buffer", "");
printAndExit("Unable to get frame buffer: timeout", true /* terminate */);
return;
} catch (AdbCommandRejectedException acre) {
recordResponse("No frame buffer", "");
printAndExit("Unable to get frame buffer: " + acre.getMessage(), true /* terminate */);
return;
}
// device/adb not available?
if (rawImage == null) {
recordResponse("No image", "");
return;
}
assert rawImage.bpp == 16;
BufferedImage image;
logger.info("Raw Image - height: " + rawImage.height + ", width: " + rawImage.width);
if (landscape) {
// convert raw data to an Image
image = new BufferedImage(rawImage.height, rawImage.width,
BufferedImage.TYPE_INT_ARGB);
byte[] buffer = rawImage.data;
int index = 0;
for (int y = 0 ; y < rawImage.height ; y++) {
for (int x = 0 ; x < rawImage.width ; x++) {
int value = buffer[index++] & 0x00FF;
value |= (buffer[index++] << 8) & 0x0FF00;
int r = ((value >> 11) & 0x01F) << 3;
int g = ((value >> 5) & 0x03F) << 2;
int b = ((value >> 0) & 0x01F) << 3;
value = 0xFF << 24 | r << 16 | g << 8 | b;
image.setRGB(y, rawImage.width - x - 1, value);
}
}
} else {
// convert raw data to an Image
image = new BufferedImage(rawImage.width, rawImage.height,
BufferedImage.TYPE_INT_ARGB);
byte[] buffer = rawImage.data;
int index = 0;
for (int y = 0 ; y < rawImage.height ; y++) {
for (int x = 0 ; x < rawImage.width ; x++) {
int value = buffer[index++] & 0x00FF;
value |= (buffer[index++] << 8) & 0x0FF00;
int r = ((value >> 11) & 0x01F) << 3;
int g = ((value >> 5) & 0x03F) << 2;
int b = ((value >> 0) & 0x01F) << 3;
value = 0xFF << 24 | r << 16 | g << 8 | b;
image.setRGB(x, y, value);
}
}
}
if (!ImageIO.write(image, "png", new File(filepath))) {
recordResponse("No png writer", "");
throw new IOException("Failed to find png writer");
}
recordResponse("OK", filepath);
}
private static void printUsageAndQuit(String message) {
// 80 cols marker: 01234567890123456789012345678901234567890123456789012345678901234567890123456789
System.out.println(message);
System.out.println("Usage: monkeyrunner [options] SCRIPT_FILE");
System.out.println("");
System.out.println(" -s MonkeyServer IP Address.");
System.out.println(" -p MonkeyServer TCP Port.");
System.out.println(" -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF)");
System.out.println("");
System.out.println("");
System.exit(1);
}
private static void printAndExit(String message, boolean terminate) {
System.out.println(message);
if (terminate) {
AndroidDebugBridge.terminate();
}
System.exit(1);
}
}

View File

@@ -1,96 +0,0 @@
package com.android.monkeyrunner;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import org.python.util.InteractiveConsole;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.lang.RuntimeException;
import java.util.Properties;
/**
* Runs Jython based scripts.
*/
public class ScriptRunner {
/** The "this" scope object for scripts. */
private final Object scope;
private final String variable;
/** Private constructor. */
private ScriptRunner(Object scope, String variable) {
this.scope = scope;
this.variable = variable;
}
/** Creates a new instance for the given scope object. */
public static ScriptRunner newInstance(Object scope, String variable) {
return new ScriptRunner(scope, variable);
}
/**
* Runs the specified Jython script. First runs the initialization script to
* preload the appropriate client library version.
*/
public static void run(String scriptfilename) {
try {
initPython();
PythonInterpreter python = new PythonInterpreter();
python.execfile(scriptfilename);
} catch(Exception e) {
e.printStackTrace();
}
}
/** Initialize the python interpreter. */
private static void initPython() {
Properties props = new Properties();
// Default is 'message' which displays sys-package-mgr bloat
// Choose one of error,warning,message,comment,debug
props.setProperty("python.verbose", "error");
props.setProperty("python.path", System.getProperty("java.class.path"));
PythonInterpreter.initialize(System.getProperties(), props, new String[] {""});
}
/**
* Create and run a console using a new python interpreter for the test
* associated with this instance.
*/
public void console() throws IOException {
initPython();
InteractiveConsole python = new InteractiveConsole();
initInterpreter(python, scope, variable);
python.interact();
}
/**
* Start an interactive python interpreter using the specified set of local
* variables. Use this to interrupt a running test script with a prompt:
*
* @param locals
*/
public static void console(PyObject locals) {
initPython();
InteractiveConsole python = new InteractiveConsole(locals);
python.interact();
}
/**
* Initialize a python interpreter.
*
* @param python
* @param scope
* @throws IOException
*/
public static void initInterpreter(PythonInterpreter python, Object scope, String variable)
throws IOException {
// Store the current test case as the this variable
python.set(variable, scope);
}
}