blob: ee6b89c20f76839da923a5a8e3a6b78fbb89378d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.test;
18
19import static android.test.suitebuilder.TestPredicates.REJECT_PERFORMANCE;
Jack Wangff1df692009-08-26 17:19:13 -070020
21import com.android.internal.util.Predicate;
Brett Chabot88e03a92010-02-19 09:57:11 -080022import com.android.internal.util.Predicates;
Jack Wangff1df692009-08-26 17:19:13 -070023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.Activity;
25import android.app.Instrumentation;
26import android.os.Bundle;
27import android.os.Debug;
28import android.os.Looper;
Jack Wangff1df692009-08-26 17:19:13 -070029import android.os.Parcelable;
30import android.os.PerformanceCollector;
Jack Wangff1df692009-08-26 17:19:13 -070031import android.os.PerformanceCollector.PerformanceResultsWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.test.suitebuilder.TestMethod;
33import android.test.suitebuilder.TestPredicates;
34import android.test.suitebuilder.TestSuiteBuilder;
Brett Chabot88e03a92010-02-19 09:57:11 -080035import android.test.suitebuilder.annotation.HasAnnotation;
Doug Zongker0375fa12010-02-23 12:36:06 -080036import android.test.suitebuilder.annotation.LargeTest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.util.Log;
38
Jack Wangff1df692009-08-26 17:19:13 -070039import java.io.ByteArrayOutputStream;
40import java.io.File;
41import java.io.PrintStream;
Brett Chabot88e03a92010-02-19 09:57:11 -080042import java.lang.annotation.Annotation;
Jack Wangff1df692009-08-26 17:19:13 -070043import java.lang.reflect.InvocationTargetException;
44import java.lang.reflect.Method;
45import java.util.ArrayList;
46import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
48import junit.framework.AssertionFailedError;
49import junit.framework.Test;
50import junit.framework.TestCase;
51import junit.framework.TestListener;
52import junit.framework.TestResult;
53import junit.framework.TestSuite;
54import junit.runner.BaseTestRunner;
55import junit.textui.ResultPrinter;
56
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057/**
58 * An {@link Instrumentation} that runs various types of {@link junit.framework.TestCase}s against
59 * an Android package (application). Typical usage:
60 * <ol>
61 * <li>Write {@link junit.framework.TestCase}s that perform unit, functional, or performance tests
62 * against the classes in your package. Typically these are subclassed from:
Jack Wangff1df692009-08-26 17:19:13 -070063 * <ul><li>{@link android.test.ActivityInstrumentationTestCase2}</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 * <li>{@link android.test.ActivityUnitTestCase}</li>
65 * <li>{@link android.test.AndroidTestCase}</li>
66 * <li>{@link android.test.ApplicationTestCase}</li>
67 * <li>{@link android.test.InstrumentationTestCase}</li>
68 * <li>{@link android.test.ProviderTestCase}</li>
69 * <li>{@link android.test.ServiceTestCase}</li>
70 * <li>{@link android.test.SingleLaunchActivityTestCase}</li></ul>
71 * <li>In an appropriate AndroidManifest.xml, define the this instrumentation with
72 * the appropriate android:targetPackage set.
73 * <li>Run the instrumentation using "adb shell am instrument -w",
74 * with no optional arguments, to run all tests (except performance tests).
75 * <li>Run the instrumentation using "adb shell am instrument -w",
76 * with the argument '-e func true' to run all functional tests. These are tests that derive from
77 * {@link android.test.InstrumentationTestCase}.
78 * <li>Run the instrumentation using "adb shell am instrument -w",
79 * with the argument '-e unit true' to run all unit tests. These are tests that <i>do not</i>derive
80 * from {@link android.test.InstrumentationTestCase} (and are not performance tests).
81 * <li>Run the instrumentation using "adb shell am instrument -w",
82 * with the argument '-e class' set to run an individual {@link junit.framework.TestCase}.
83 * </ol>
84 * <p/>
85 * <b>Running all tests:</b> adb shell am instrument -w
86 * com.android.foo/android.test.InstrumentationTestRunner
87 * <p/>
88 * <b>Running all small tests:</b> adb shell am instrument -w
89 * -e size small
90 * com.android.foo/android.test.InstrumentationTestRunner
91 * <p/>
92 * <b>Running all medium tests:</b> adb shell am instrument -w
93 * -e size medium
94 * com.android.foo/android.test.InstrumentationTestRunner
95 * <p/>
96 * <b>Running all large tests:</b> adb shell am instrument -w
97 * -e size large
98 * com.android.foo/android.test.InstrumentationTestRunner
99 * <p/>
Brett Chabot88e03a92010-02-19 09:57:11 -0800100 * <b>Filter test run to tests with given annotation:</b> adb shell am instrument -w
101 * -e annotation com.android.foo.MyAnnotation
102 * com.android.foo/android.test.InstrumentationTestRunner
103 * <p/>
104 * If used with other options, the resulting test run will contain the union of the two options.
105 * e.g. "-e size large -e annotation com.android.foo.MyAnnotation" will run only tests with both
106 * the {@link LargeTest} and "com.android.foo.MyAnnotation" annotations.
107 * <p/>
108 * <b>Filter test run to tests <i>without</i> given annotation:</b> adb shell am instrument -w
109 * -e notAnnotation com.android.foo.MyAnnotation
110 * com.android.foo/android.test.InstrumentationTestRunner
111 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 * <b>Running a single testcase:</b> adb shell am instrument -w
113 * -e class com.android.foo.FooTest
114 * com.android.foo/android.test.InstrumentationTestRunner
115 * <p/>
116 * <b>Running a single test:</b> adb shell am instrument -w
117 * -e class com.android.foo.FooTest#testFoo
118 * com.android.foo/android.test.InstrumentationTestRunner
119 * <p/>
120 * <b>Running multiple tests:</b> adb shell am instrument -w
121 * -e class com.android.foo.FooTest,com.android.foo.TooTest
122 * com.android.foo/android.test.InstrumentationTestRunner
123 * <p/>
124 * <b>Including performance tests:</b> adb shell am instrument -w
125 * -e perf true
126 * com.android.foo/android.test.InstrumentationTestRunner
127 * <p/>
128 * <b>To debug your tests, set a break point in your code and pass:</b>
129 * -e debug true
130 * <p/>
131 * <b>To run in 'log only' mode</b>
132 * -e log true
Jack Wangff1df692009-08-26 17:19:13 -0700133 * This option will load and iterate through all test classes and methods, but will bypass actual
134 * test execution. Useful for quickly obtaining info on the tests to be executed by an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 * instrumentation command.
136 * <p/>
137 * <b>To generate EMMA code coverage:</b>
138 * -e coverage true
Jack Wangff1df692009-08-26 17:19:13 -0700139 * Note: this requires an emma instrumented build. By default, the code coverage results file
Brett Chabot51e03642009-05-28 18:18:15 -0700140 * will be saved in a /data/<app>/coverage.ec file, unless overridden by coverageFile flag (see
141 * below)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 * <p/>
143 * <b> To specify EMMA code coverage results file path:</b>
144 * -e coverageFile /sdcard/myFile.ec
145 * <br/>
146 * in addition to the other arguments.
147 */
148
149/* (not JavaDoc)
150 * Although not necessary in most case, another way to use this class is to extend it and have the
Jack Wangff1df692009-08-26 17:19:13 -0700151 * derived class return the desired test suite from the {@link #getTestSuite()} method. The test
152 * suite returned from this method will be used if no target class is defined in the meta-data or
153 * command line argument parameters. If a derived class is used it needs to be added as an
154 * instrumentation to the AndroidManifest.xml and the command to run it would look like:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 * <p/>
156 * adb shell am instrument -w com.android.foo/<i>com.android.FooInstrumentationTestRunner</i>
157 * <p/>
158 * Where <i>com.android.FooInstrumentationTestRunner</i> is the derived class.
159 *
160 * This model is used by many existing app tests, but can probably be deprecated.
161 */
162public class InstrumentationTestRunner extends Instrumentation implements TestSuiteProvider {
163
164 /** @hide */
165 public static final String ARGUMENT_TEST_CLASS = "class";
166 /** @hide */
167 public static final String ARGUMENT_TEST_PACKAGE = "package";
168 /** @hide */
169 public static final String ARGUMENT_TEST_SIZE_PREDICATE = "size";
170 /** @hide */
171 public static final String ARGUMENT_INCLUDE_PERF = "perf";
172 /** @hide */
173 public static final String ARGUMENT_DELAY_MSEC = "delay_msec";
174
175 private static final String SMALL_SUITE = "small";
Jack Wangff1df692009-08-26 17:19:13 -0700176 private static final String MEDIUM_SUITE = "medium";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private static final String LARGE_SUITE = "large";
Jack Wangff1df692009-08-26 17:19:13 -0700178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 private static final String ARGUMENT_LOG_ONLY = "log";
Brett Chabot88e03a92010-02-19 09:57:11 -0800180 /** @hide */
181 static final String ARGUMENT_ANNOTATION = "annotation";
182 /** @hide */
183 static final String ARGUMENT_NOT_ANNOTATION = "notAnnotation";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 /**
Jack Wangff1df692009-08-26 17:19:13 -0700186 * This constant defines the maximum allowed runtime (in ms) for a test included in the "small"
187 * suite. It is used to make an educated guess at what suite an unlabeled test belongs.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 */
189 private static final float SMALL_SUITE_MAX_RUNTIME = 100;
Jack Wangff1df692009-08-26 17:19:13 -0700190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 /**
Jack Wangff1df692009-08-26 17:19:13 -0700192 * This constant defines the maximum allowed runtime (in ms) for a test included in the
193 * "medium" suite. It is used to make an educated guess at what suite an unlabeled test belongs.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 */
195 private static final float MEDIUM_SUITE_MAX_RUNTIME = 1000;
Jack Wangff1df692009-08-26 17:19:13 -0700196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 /**
Jack Wangff1df692009-08-26 17:19:13 -0700198 * The following keys are used in the status bundle to provide structured reports to
199 * an IInstrumentationWatcher.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 */
201
202 /**
Jack Wangff1df692009-08-26 17:19:13 -0700203 * This value, if stored with key {@link android.app.Instrumentation#REPORT_KEY_IDENTIFIER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 * identifies InstrumentationTestRunner as the source of the report. This is sent with all
205 * status messages.
206 */
207 public static final String REPORT_VALUE_ID = "InstrumentationTestRunner";
208 /**
Jack Wangff1df692009-08-26 17:19:13 -0700209 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 * identifies the total number of tests that are being run. This is sent with all status
211 * messages.
212 */
213 public static final String REPORT_KEY_NUM_TOTAL = "numtests";
214 /**
Jack Wangff1df692009-08-26 17:19:13 -0700215 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 * identifies the sequence number of the current test. This is sent with any status message
217 * describing a specific test being started or completed.
218 */
219 public static final String REPORT_KEY_NUM_CURRENT = "current";
220 /**
Jack Wangff1df692009-08-26 17:19:13 -0700221 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 * identifies the name of the current test class. This is sent with any status message
223 * describing a specific test being started or completed.
224 */
225 public static final String REPORT_KEY_NAME_CLASS = "class";
226 /**
Jack Wangff1df692009-08-26 17:19:13 -0700227 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 * identifies the name of the current test. This is sent with any status message
229 * describing a specific test being started or completed.
230 */
231 public static final String REPORT_KEY_NAME_TEST = "test";
232 /**
Jack Wangff1df692009-08-26 17:19:13 -0700233 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 * reports the run time in seconds of the current test.
235 */
236 private static final String REPORT_KEY_RUN_TIME = "runtime";
237 /**
Jack Wangff1df692009-08-26 17:19:13 -0700238 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 * reports the guessed suite assignment for the current test.
240 */
241 private static final String REPORT_KEY_SUITE_ASSIGNMENT = "suiteassignment";
242 /**
Brett Chabot51e03642009-05-28 18:18:15 -0700243 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
244 * identifies the path to the generated code coverage file.
245 */
246 private static final String REPORT_KEY_COVERAGE_PATH = "coverageFilePath";
Jack Wangff1df692009-08-26 17:19:13 -0700247
248 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 * The test is starting.
250 */
251 public static final int REPORT_VALUE_RESULT_START = 1;
252 /**
253 * The test completed successfully.
254 */
255 public static final int REPORT_VALUE_RESULT_OK = 0;
256 /**
257 * The test completed with an error.
258 */
259 public static final int REPORT_VALUE_RESULT_ERROR = -1;
260 /**
261 * The test completed with a failure.
262 */
263 public static final int REPORT_VALUE_RESULT_FAILURE = -2;
264 /**
Jack Wangff1df692009-08-26 17:19:13 -0700265 * If included in the status bundle sent to an IInstrumentationWatcher, this key
266 * identifies a stack trace describing an error or failure. This is sent with any status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 * message describing a specific test being completed.
268 */
269 public static final String REPORT_KEY_STACK = "stack";
270
Brett Chabot51e03642009-05-28 18:18:15 -0700271 // Default file name for code coverage
272 private static final String DEFAULT_COVERAGE_FILE_NAME = "coverage.ec";
Jack Wangff1df692009-08-26 17:19:13 -0700273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 private static final String LOG_TAG = "InstrumentationTestRunner";
275
276 private final Bundle mResults = new Bundle();
277 private AndroidTestRunner mTestRunner;
278 private boolean mDebug;
279 private boolean mJustCount;
280 private boolean mSuiteAssignmentMode;
281 private int mTestCount;
282 private String mPackageOfTests;
283 private boolean mCoverage;
284 private String mCoverageFilePath;
285 private int mDelayMsec;
286
287 @Override
288 public void onCreate(Bundle arguments) {
289 super.onCreate(arguments);
290
291 // Apk paths used to search for test classes when using TestSuiteBuilders.
292 String[] apkPaths =
293 {getTargetContext().getPackageCodePath(), getContext().getPackageCodePath()};
294 ClassPathPackageInfoSource.setApkPaths(apkPaths);
295
296 Predicate<TestMethod> testSizePredicate = null;
Brett Chabot88e03a92010-02-19 09:57:11 -0800297 Predicate<TestMethod> testAnnotationPredicate = null;
298 Predicate<TestMethod> testNotAnnotationPredicate = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 boolean includePerformance = false;
300 String testClassesArg = null;
301 boolean logOnly = false;
302
303 if (arguments != null) {
304 // Test class name passed as an argument should override any meta-data declaration.
305 testClassesArg = arguments.getString(ARGUMENT_TEST_CLASS);
306 mDebug = getBooleanArgument(arguments, "debug");
307 mJustCount = getBooleanArgument(arguments, "count");
308 mSuiteAssignmentMode = getBooleanArgument(arguments, "suiteAssignment");
309 mPackageOfTests = arguments.getString(ARGUMENT_TEST_PACKAGE);
310 testSizePredicate = getSizePredicateFromArg(
311 arguments.getString(ARGUMENT_TEST_SIZE_PREDICATE));
Brett Chabot88e03a92010-02-19 09:57:11 -0800312 testAnnotationPredicate = getAnnotationPredicate(
313 arguments.getString(ARGUMENT_ANNOTATION));
314 testNotAnnotationPredicate = getNotAnnotationPredicate(
315 arguments.getString(ARGUMENT_NOT_ANNOTATION));
316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 includePerformance = getBooleanArgument(arguments, ARGUMENT_INCLUDE_PERF);
318 logOnly = getBooleanArgument(arguments, ARGUMENT_LOG_ONLY);
319 mCoverage = getBooleanArgument(arguments, "coverage");
320 mCoverageFilePath = arguments.getString("coverageFile");
321
322 try {
323 Object delay = arguments.get(ARGUMENT_DELAY_MSEC); // Accept either string or int
324 if (delay != null) mDelayMsec = Integer.parseInt(delay.toString());
325 } catch (NumberFormatException e) {
326 Log.e(LOG_TAG, "Invalid delay_msec parameter", e);
327 }
328 }
329
330 TestSuiteBuilder testSuiteBuilder = new TestSuiteBuilder(getClass().getName(),
331 getTargetContext().getClassLoader());
332
333 if (testSizePredicate != null) {
334 testSuiteBuilder.addRequirements(testSizePredicate);
335 }
Brett Chabot88e03a92010-02-19 09:57:11 -0800336 if (testAnnotationPredicate != null) {
337 testSuiteBuilder.addRequirements(testAnnotationPredicate);
338 }
339 if (testNotAnnotationPredicate != null) {
340 testSuiteBuilder.addRequirements(testNotAnnotationPredicate);
341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 if (!includePerformance) {
343 testSuiteBuilder.addRequirements(REJECT_PERFORMANCE);
344 }
345
346 if (testClassesArg == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 if (mPackageOfTests != null) {
348 testSuiteBuilder.includePackages(mPackageOfTests);
349 } else {
Brett Chabot61b10ac2009-03-31 17:04:34 -0700350 TestSuite testSuite = getTestSuite();
351 if (testSuite != null) {
352 testSuiteBuilder.addTestSuite(testSuite);
353 } else {
Jack Wangff1df692009-08-26 17:19:13 -0700354 // no package or class bundle arguments were supplied, and no test suite
Brett Chabot61b10ac2009-03-31 17:04:34 -0700355 // provided so add all tests in application
356 testSuiteBuilder.includePackages("");
357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 }
359 } else {
360 parseTestClasses(testClassesArg, testSuiteBuilder);
361 }
Jack Wangff1df692009-08-26 17:19:13 -0700362
Urs Grobda13ef52009-04-17 11:30:14 -0700363 testSuiteBuilder.addRequirements(getBuilderRequirements());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 mTestRunner = getAndroidTestRunner();
366 mTestRunner.setContext(getTargetContext());
Jack Wang7aba54b2009-08-20 19:20:54 -0700367 mTestRunner.setInstrumentation(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 mTestRunner.setSkipExecution(logOnly);
369 mTestRunner.setTest(testSuiteBuilder.build());
370 mTestCount = mTestRunner.getTestCases().size();
371 if (mSuiteAssignmentMode) {
372 mTestRunner.addTestListener(new SuiteAssignmentPrinter());
373 } else {
Jack Wangff1df692009-08-26 17:19:13 -0700374 WatcherResultPrinter resultPrinter = new WatcherResultPrinter(mTestCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 mTestRunner.addTestListener(new TestPrinter("TestRunner", false));
Jack Wangff1df692009-08-26 17:19:13 -0700376 mTestRunner.addTestListener(resultPrinter);
377 mTestRunner.setPerformanceResultsWriter(resultPrinter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
379 start();
380 }
381
Urs Grobda13ef52009-04-17 11:30:14 -0700382 List<Predicate<TestMethod>> getBuilderRequirements() {
383 return new ArrayList<Predicate<TestMethod>>();
384 }
385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 /**
Jack Wangff1df692009-08-26 17:19:13 -0700387 * Parses and loads the specified set of test classes
388 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 * @param testClassArg - comma-separated list of test classes and methods
390 * @param testSuiteBuilder - builder to add tests to
391 */
392 private void parseTestClasses(String testClassArg, TestSuiteBuilder testSuiteBuilder) {
393 String[] testClasses = testClassArg.split(",");
394 for (String testClass : testClasses) {
395 parseTestClass(testClass, testSuiteBuilder);
396 }
397 }
398
399 /**
400 * Parse and load the given test class and, optionally, method
Jack Wangff1df692009-08-26 17:19:13 -0700401 *
402 * @param testClassName - full package name of test class and optionally method to add.
403 * Expected format: com.android.TestClass#testMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 * @param testSuiteBuilder - builder to add tests to
405 */
406 private void parseTestClass(String testClassName, TestSuiteBuilder testSuiteBuilder) {
407 int methodSeparatorIndex = testClassName.indexOf('#');
408 String testMethodName = null;
409
410 if (methodSeparatorIndex > 0) {
411 testMethodName = testClassName.substring(methodSeparatorIndex + 1);
412 testClassName = testClassName.substring(0, methodSeparatorIndex);
413 }
Jack Wangff1df692009-08-26 17:19:13 -0700414 testSuiteBuilder.addTestClassByName(testClassName, testMethodName, getTargetContext());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 }
416
417 protected AndroidTestRunner getAndroidTestRunner() {
418 return new AndroidTestRunner();
419 }
420
421 private boolean getBooleanArgument(Bundle arguments, String tag) {
422 String tagString = arguments.getString(tag);
423 return tagString != null && Boolean.parseBoolean(tagString);
424 }
Jack Wangff1df692009-08-26 17:19:13 -0700425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 /*
427 * Returns the size predicate object, corresponding to the "size" argument value.
428 */
429 private Predicate<TestMethod> getSizePredicateFromArg(String sizeArg) {
Jack Wangff1df692009-08-26 17:19:13 -0700430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 if (SMALL_SUITE.equals(sizeArg)) {
432 return TestPredicates.SELECT_SMALL;
433 } else if (MEDIUM_SUITE.equals(sizeArg)) {
434 return TestPredicates.SELECT_MEDIUM;
435 } else if (LARGE_SUITE.equals(sizeArg)) {
436 return TestPredicates.SELECT_LARGE;
437 } else {
438 return null;
439 }
440 }
Jack Wangff1df692009-08-26 17:19:13 -0700441
Brett Chabot88e03a92010-02-19 09:57:11 -0800442 /**
443 * Returns the test predicate object, corresponding to the annotation class value provided via
444 * the {@link ARGUMENT_ANNOTATION} argument.
445 *
446 * @return the predicate or <code>null</code>
447 */
448 private Predicate<TestMethod> getAnnotationPredicate(String annotationClassName) {
449 Class<? extends Annotation> annotationClass = getAnnotationClass(annotationClassName);
450 if (annotationClass != null) {
451 return new HasAnnotation(annotationClass);
452 }
453 return null;
454 }
455
456 /**
457 * Returns the negative test predicate object, corresponding to the annotation class value
458 * provided via the {@link ARGUMENT_NOT_ANNOTATION} argument.
459 *
460 * @return the predicate or <code>null</code>
461 */
462 private Predicate<TestMethod> getNotAnnotationPredicate(String annotationClassName) {
463 Class<? extends Annotation> annotationClass = getAnnotationClass(annotationClassName);
464 if (annotationClass != null) {
465 return Predicates.not(new HasAnnotation(annotationClass));
466 }
467 return null;
468 }
469
470 /**
471 * Helper method to return the annotation class with specified name
472 *
473 * @param annotationClassName the fully qualified name of the class
474 * @return the annotation class or <code>null</code>
475 */
476 private Class<? extends Annotation> getAnnotationClass(String annotationClassName) {
477 if (annotationClassName == null) {
478 return null;
479 }
480 try {
481 Class<?> annotationClass = Class.forName(annotationClassName);
482 if (annotationClass.isAnnotation()) {
483 return (Class<? extends Annotation>)annotationClass;
484 } else {
485 Log.e(LOG_TAG, String.format("Provided annotation value %s is not an Annotation",
486 annotationClassName));
487 }
488 } catch (ClassNotFoundException e) {
489 Log.e(LOG_TAG, String.format("Could not find class for specified annotation %s",
490 annotationClassName));
491 }
492 return null;
493 }
494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 @Override
496 public void onStart() {
497 Looper.prepare();
Jack Wangff1df692009-08-26 17:19:13 -0700498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 if (mJustCount) {
500 mResults.putString(Instrumentation.REPORT_KEY_IDENTIFIER, REPORT_VALUE_ID);
501 mResults.putInt(REPORT_KEY_NUM_TOTAL, mTestCount);
502 finish(Activity.RESULT_OK, mResults);
503 } else {
504 if (mDebug) {
505 Debug.waitForDebugger();
506 }
Jack Wangff1df692009-08-26 17:19:13 -0700507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
509 PrintStream writer = new PrintStream(byteArrayOutputStream);
510 try {
511 StringResultPrinter resultPrinter = new StringResultPrinter(writer);
Jack Wangff1df692009-08-26 17:19:13 -0700512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 mTestRunner.addTestListener(resultPrinter);
Jack Wangff1df692009-08-26 17:19:13 -0700514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 long startTime = System.currentTimeMillis();
516 mTestRunner.runTest();
517 long runTime = System.currentTimeMillis() - startTime;
Jack Wangff1df692009-08-26 17:19:13 -0700518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 resultPrinter.print(mTestRunner.getTestResult(), runTime);
520 } finally {
Jack Wangff1df692009-08-26 17:19:13 -0700521 mResults.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
522 String.format("\nTest results for %s=%s",
523 mTestRunner.getTestClassName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 byteArrayOutputStream.toString()));
525
526 if (mCoverage) {
527 generateCoverageReport();
528 }
529 writer.close();
Jack Wangff1df692009-08-26 17:19:13 -0700530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 finish(Activity.RESULT_OK, mResults);
532 }
533 }
534 }
535
536 public TestSuite getTestSuite() {
537 return getAllTests();
538 }
539
540 /**
541 * Override this to define all of the tests to run in your package.
542 */
543 public TestSuite getAllTests() {
544 return null;
545 }
546
547 /**
548 * Override this to provide access to the class loader of your package.
549 */
550 public ClassLoader getLoader() {
551 return null;
552 }
Jack Wangff1df692009-08-26 17:19:13 -0700553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 private void generateCoverageReport() {
555 // use reflection to call emma dump coverage method, to avoid
556 // always statically compiling against emma jar
Brett Chabot51e03642009-05-28 18:18:15 -0700557 String coverageFilePath = getCoverageFilePath();
558 java.io.File coverageFile = new java.io.File(coverageFilePath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 try {
Brett Chabot88e03a92010-02-19 09:57:11 -0800560 Class<?> emmaRTClass = Class.forName("com.vladium.emma.rt.RT");
Jack Wangff1df692009-08-26 17:19:13 -0700561 Method dumpCoverageMethod = emmaRTClass.getMethod("dumpCoverageData",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 coverageFile.getClass(), boolean.class, boolean.class);
Jack Wangff1df692009-08-26 17:19:13 -0700563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 dumpCoverageMethod.invoke(null, coverageFile, false, false);
Brett Chabot51e03642009-05-28 18:18:15 -0700565 // output path to generated coverage file so it can be parsed by a test harness if
566 // needed
567 mResults.putString(REPORT_KEY_COVERAGE_PATH, coverageFilePath);
568 // also output a more user friendly msg
Brett Chabot08d13c32010-02-18 15:42:13 -0800569 final String currentStream = mResults.getString(
570 Instrumentation.REPORT_KEY_STREAMRESULT);
Brett Chabot51e03642009-05-28 18:18:15 -0700571 mResults.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
Brett Chabot08d13c32010-02-18 15:42:13 -0800572 String.format("%s\nGenerated code coverage data to %s", currentStream,
573 coverageFilePath));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 } catch (ClassNotFoundException e) {
575 reportEmmaError("Is emma jar on classpath?", e);
576 } catch (SecurityException e) {
577 reportEmmaError(e);
578 } catch (NoSuchMethodException e) {
579 reportEmmaError(e);
580 } catch (IllegalArgumentException e) {
581 reportEmmaError(e);
582 } catch (IllegalAccessException e) {
583 reportEmmaError(e);
584 } catch (InvocationTargetException e) {
585 reportEmmaError(e);
586 }
587 }
588
589 private String getCoverageFilePath() {
590 if (mCoverageFilePath == null) {
Brett Chabot51e03642009-05-28 18:18:15 -0700591 return getTargetContext().getFilesDir().getAbsolutePath() + File.separator +
Jack Wangff1df692009-08-26 17:19:13 -0700592 DEFAULT_COVERAGE_FILE_NAME;
593 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 return mCoverageFilePath;
595 }
596 }
597
598 private void reportEmmaError(Exception e) {
Jack Wangff1df692009-08-26 17:19:13 -0700599 reportEmmaError("", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 }
601
602 private void reportEmmaError(String hint, Exception e) {
603 String msg = "Failed to generate emma coverage. " + hint;
604 Log.e(LOG_TAG, msg, e);
605 mResults.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "\nError: " + msg);
606 }
607
608 // TODO kill this, use status() and prettyprint model for better output
609 private class StringResultPrinter extends ResultPrinter {
610
611 public StringResultPrinter(PrintStream writer) {
612 super(writer);
613 }
614
615 synchronized void print(TestResult result, long runTime) {
616 printHeader(runTime);
617 printFooter(result);
618 }
619 }
Jack Wangff1df692009-08-26 17:19:13 -0700620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 /**
Jack Wangff1df692009-08-26 17:19:13 -0700622 * This class sends status reports back to the IInstrumentationWatcher about
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 * which suite each test belongs.
624 */
Jack Wangff1df692009-08-26 17:19:13 -0700625 private class SuiteAssignmentPrinter implements TestListener {
626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 private Bundle mTestResult;
628 private long mStartTime;
629 private long mEndTime;
630 private boolean mTimingValid;
Jack Wangff1df692009-08-26 17:19:13 -0700631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 public SuiteAssignmentPrinter() {
633 }
Jack Wangff1df692009-08-26 17:19:13 -0700634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 /**
636 * send a status for the start of a each test, so long tests can be seen as "running"
637 */
638 public void startTest(Test test) {
639 mTimingValid = true;
Jack Wangff1df692009-08-26 17:19:13 -0700640 mStartTime = System.currentTimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
Jack Wangff1df692009-08-26 17:19:13 -0700642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 /**
644 * @see junit.framework.TestListener#addError(Test, Throwable)
645 */
646 public void addError(Test test, Throwable t) {
647 mTimingValid = false;
648 }
649
650 /**
651 * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
652 */
653 public void addFailure(Test test, AssertionFailedError t) {
654 mTimingValid = false;
655 }
656
657 /**
658 * @see junit.framework.TestListener#endTest(Test)
659 */
660 public void endTest(Test test) {
661 float runTime;
662 String assignmentSuite;
663 mEndTime = System.currentTimeMillis();
664 mTestResult = new Bundle();
665
666 if (!mTimingValid || mStartTime < 0) {
667 assignmentSuite = "NA";
668 runTime = -1;
669 } else {
670 runTime = mEndTime - mStartTime;
Jack Wangff1df692009-08-26 17:19:13 -0700671 if (runTime < SMALL_SUITE_MAX_RUNTIME
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 && !InstrumentationTestCase.class.isAssignableFrom(test.getClass())) {
673 assignmentSuite = SMALL_SUITE;
674 } else if (runTime < MEDIUM_SUITE_MAX_RUNTIME) {
675 assignmentSuite = MEDIUM_SUITE;
676 } else {
677 assignmentSuite = LARGE_SUITE;
678 }
679 }
680 // Clear mStartTime so that we can verify that it gets set next time.
681 mStartTime = -1;
682
Jack Wangff1df692009-08-26 17:19:13 -0700683 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
684 test.getClass().getName() + "#" + ((TestCase) test).getName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 + "\nin " + assignmentSuite + " suite\nrunTime: "
686 + String.valueOf(runTime) + "\n");
687 mTestResult.putFloat(REPORT_KEY_RUN_TIME, runTime);
688 mTestResult.putString(REPORT_KEY_SUITE_ASSIGNMENT, assignmentSuite);
689
690 sendStatus(0, mTestResult);
691 }
692 }
Jack Wangff1df692009-08-26 17:19:13 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 /**
695 * This class sends status reports back to the IInstrumentationWatcher
696 */
Jack Wangff1df692009-08-26 17:19:13 -0700697 private class WatcherResultPrinter implements TestListener, PerformanceResultsWriter {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 private final Bundle mResultTemplate;
699 Bundle mTestResult;
700 int mTestNum = 0;
701 int mTestResultCode = 0;
702 String mTestClass = null;
Jack Wang4f414bd2009-11-06 20:53:47 -0800703 PerformanceCollector mPerfCollector = new PerformanceCollector();
Jack Wangff1df692009-08-26 17:19:13 -0700704 boolean mIsTimedTest = false;
Jack Wang4f414bd2009-11-06 20:53:47 -0800705 boolean mIncludeDetailedStats = false;
Jack Wangff1df692009-08-26 17:19:13 -0700706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 public WatcherResultPrinter(int numTests) {
708 mResultTemplate = new Bundle();
709 mResultTemplate.putString(Instrumentation.REPORT_KEY_IDENTIFIER, REPORT_VALUE_ID);
710 mResultTemplate.putInt(REPORT_KEY_NUM_TOTAL, numTests);
711 }
Jack Wangff1df692009-08-26 17:19:13 -0700712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 /**
Jack Wangff1df692009-08-26 17:19:13 -0700714 * send a status for the start of a each test, so long tests can be seen
715 * as "running"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 */
717 public void startTest(Test test) {
718 String testClass = test.getClass().getName();
Jack Wangff1df692009-08-26 17:19:13 -0700719 String testName = ((TestCase)test).getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 mTestResult = new Bundle(mResultTemplate);
721 mTestResult.putString(REPORT_KEY_NAME_CLASS, testClass);
Jack Wangff1df692009-08-26 17:19:13 -0700722 mTestResult.putString(REPORT_KEY_NAME_TEST, testName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 mTestResult.putInt(REPORT_KEY_NUM_CURRENT, ++mTestNum);
724 // pretty printing
725 if (testClass != null && !testClass.equals(mTestClass)) {
Jack Wangff1df692009-08-26 17:19:13 -0700726 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 String.format("\n%s:", testClass));
728 mTestClass = testClass;
729 } else {
730 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "");
731 }
732
733 // The delay_msec parameter is normally used to provide buffers of idle time
Jack Wangff1df692009-08-26 17:19:13 -0700734 // for power measurement purposes. To make sure there is a delay before and after
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 // every test in a suite, we delay *after* every test (see endTest below) and also
Jack Wangff1df692009-08-26 17:19:13 -0700736 // delay *before* the first test. So, delay test1 delay test2 delay.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737
738 try {
739 if (mTestNum == 1) Thread.sleep(mDelayMsec);
740 } catch (InterruptedException e) {
741 throw new IllegalStateException(e);
742 }
743
744 sendStatus(REPORT_VALUE_RESULT_START, mTestResult);
745 mTestResultCode = 0;
Jack Wangff1df692009-08-26 17:19:13 -0700746
747 mIsTimedTest = false;
Jack Wang4f414bd2009-11-06 20:53:47 -0800748 mIncludeDetailedStats = false;
Jack Wangff1df692009-08-26 17:19:13 -0700749 try {
Jack Wang4f414bd2009-11-06 20:53:47 -0800750 // Look for TimedTest annotation on both test class and test method
751 if (test.getClass().getMethod(testName).isAnnotationPresent(TimedTest.class)) {
752 mIsTimedTest = true;
753 mIncludeDetailedStats = test.getClass().getMethod(testName).getAnnotation(
754 TimedTest.class).includeDetailedStats();
755 } else if (test.getClass().isAnnotationPresent(TimedTest.class)) {
756 mIsTimedTest = true;
757 mIncludeDetailedStats = test.getClass().getAnnotation(
758 TimedTest.class).includeDetailedStats();
759 }
Jack Wangff1df692009-08-26 17:19:13 -0700760 } catch (SecurityException e) {
761 throw new IllegalStateException(e);
762 } catch (NoSuchMethodException e) {
763 throw new IllegalStateException(e);
764 }
765
Jack Wang4f414bd2009-11-06 20:53:47 -0800766 if (mIsTimedTest && mIncludeDetailedStats) {
767 mPerfCollector.beginSnapshot("");
768 } else if (mIsTimedTest) {
769 mPerfCollector.startTiming("");
Jack Wangff1df692009-08-26 17:19:13 -0700770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
Jack Wangff1df692009-08-26 17:19:13 -0700772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 /**
774 * @see junit.framework.TestListener#addError(Test, Throwable)
775 */
776 public void addError(Test test, Throwable t) {
777 mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t));
778 mTestResultCode = REPORT_VALUE_RESULT_ERROR;
779 // pretty printing
Jack Wangff1df692009-08-26 17:19:13 -0700780 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
781 String.format("\nError in %s:\n%s",
782 ((TestCase)test).getName(), BaseTestRunner.getFilteredTrace(t)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 }
784
785 /**
786 * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
787 */
788 public void addFailure(Test test, AssertionFailedError t) {
789 mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t));
790 mTestResultCode = REPORT_VALUE_RESULT_FAILURE;
791 // pretty printing
Jack Wangff1df692009-08-26 17:19:13 -0700792 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
793 String.format("\nFailure in %s:\n%s",
794 ((TestCase)test).getName(), BaseTestRunner.getFilteredTrace(t)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 }
796
797 /**
798 * @see junit.framework.TestListener#endTest(Test)
799 */
800 public void endTest(Test test) {
Jack Wang4f414bd2009-11-06 20:53:47 -0800801 if (mIsTimedTest && mIncludeDetailedStats) {
802 mTestResult.putAll(mPerfCollector.endSnapshot());
803 } else if (mIsTimedTest) {
804 writeStopTiming(mPerfCollector.stopTiming(""));
Jack Wangff1df692009-08-26 17:19:13 -0700805 }
806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 if (mTestResultCode == 0) {
808 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, ".");
809 }
810 sendStatus(mTestResultCode, mTestResult);
811
Jack Wangff1df692009-08-26 17:19:13 -0700812 try { // Sleep after every test, if specified
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 Thread.sleep(mDelayMsec);
814 } catch (InterruptedException e) {
815 throw new IllegalStateException(e);
816 }
817 }
818
Jack Wangff1df692009-08-26 17:19:13 -0700819 public void writeBeginSnapshot(String label) {
820 // Do nothing
821 }
822
823 public void writeEndSnapshot(Bundle results) {
Jack Wang075997f2009-10-27 22:01:09 -0700824 // Copy all snapshot data fields into mResults, which is outputted
825 // via Instrumentation.finish
826 mResults.putAll(results);
Jack Wangff1df692009-08-26 17:19:13 -0700827 }
828
829 public void writeStartTiming(String label) {
830 // Do nothing
831 }
832
833 public void writeStopTiming(Bundle results) {
834 // Copy results into mTestResult by flattening list of iterations,
835 // which is outputted via WatcherResultPrinter.endTest
836 int i = 0;
837 for (Parcelable p :
838 results.getParcelableArrayList(PerformanceCollector.METRIC_KEY_ITERATIONS)) {
839 Bundle iteration = (Bundle)p;
Jack Wang4f414bd2009-11-06 20:53:47 -0800840 String index = "iteration" + i + ".";
Jack Wangff1df692009-08-26 17:19:13 -0700841 mTestResult.putString(index + PerformanceCollector.METRIC_KEY_LABEL,
842 iteration.getString(PerformanceCollector.METRIC_KEY_LABEL));
843 mTestResult.putLong(index + PerformanceCollector.METRIC_KEY_CPU_TIME,
844 iteration.getLong(PerformanceCollector.METRIC_KEY_CPU_TIME));
845 mTestResult.putLong(index + PerformanceCollector.METRIC_KEY_EXECUTION_TIME,
846 iteration.getLong(PerformanceCollector.METRIC_KEY_EXECUTION_TIME));
847 i++;
848 }
849 }
850
Jack Wang075997f2009-10-27 22:01:09 -0700851 public void writeMeasurement(String label, long value) {
Jack Wang4f414bd2009-11-06 20:53:47 -0800852 mTestResult.putLong(label, value);
Jack Wang075997f2009-10-27 22:01:09 -0700853 }
854
855 public void writeMeasurement(String label, float value) {
Jack Wang4f414bd2009-11-06 20:53:47 -0800856 mTestResult.putFloat(label, value);
Jack Wang075997f2009-10-27 22:01:09 -0700857 }
858
859 public void writeMeasurement(String label, String value) {
Jack Wang4f414bd2009-11-06 20:53:47 -0800860 mTestResult.putString(label, value);
Jack Wang075997f2009-10-27 22:01:09 -0700861 }
862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 // TODO report the end of the cycle
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
865}