blob: b9978d65dd8bb836f7b20043da732df197c03ed8 [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;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.app.Activity;
24import android.app.Instrumentation;
25import android.os.Bundle;
26import android.os.Debug;
27import android.os.Looper;
Jack Wangff1df692009-08-26 17:19:13 -070028import android.os.Parcelable;
29import android.os.PerformanceCollector;
30import android.os.Process;
31import android.os.SystemClock;
32import android.os.PerformanceCollector.PerformanceResultsWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.test.suitebuilder.TestMethod;
34import android.test.suitebuilder.TestPredicates;
35import android.test.suitebuilder.TestSuiteBuilder;
36import android.util.Log;
37
Jack Wangff1df692009-08-26 17:19:13 -070038import java.io.ByteArrayOutputStream;
39import java.io.File;
40import java.io.PrintStream;
41import java.lang.reflect.InvocationTargetException;
42import java.lang.reflect.Method;
43import java.util.ArrayList;
44import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
46import junit.framework.AssertionFailedError;
47import junit.framework.Test;
48import junit.framework.TestCase;
49import junit.framework.TestListener;
50import junit.framework.TestResult;
51import junit.framework.TestSuite;
52import junit.runner.BaseTestRunner;
53import junit.textui.ResultPrinter;
54
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055/**
56 * An {@link Instrumentation} that runs various types of {@link junit.framework.TestCase}s against
57 * an Android package (application). Typical usage:
58 * <ol>
59 * <li>Write {@link junit.framework.TestCase}s that perform unit, functional, or performance tests
60 * against the classes in your package. Typically these are subclassed from:
Jack Wangff1df692009-08-26 17:19:13 -070061 * <ul><li>{@link android.test.ActivityInstrumentationTestCase2}</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 * <li>{@link android.test.ActivityUnitTestCase}</li>
63 * <li>{@link android.test.AndroidTestCase}</li>
64 * <li>{@link android.test.ApplicationTestCase}</li>
65 * <li>{@link android.test.InstrumentationTestCase}</li>
66 * <li>{@link android.test.ProviderTestCase}</li>
67 * <li>{@link android.test.ServiceTestCase}</li>
68 * <li>{@link android.test.SingleLaunchActivityTestCase}</li></ul>
69 * <li>In an appropriate AndroidManifest.xml, define the this instrumentation with
70 * the appropriate android:targetPackage set.
71 * <li>Run the instrumentation using "adb shell am instrument -w",
72 * with no optional arguments, to run all tests (except performance tests).
73 * <li>Run the instrumentation using "adb shell am instrument -w",
74 * with the argument '-e func true' to run all functional tests. These are tests that derive from
75 * {@link android.test.InstrumentationTestCase}.
76 * <li>Run the instrumentation using "adb shell am instrument -w",
77 * with the argument '-e unit true' to run all unit tests. These are tests that <i>do not</i>derive
78 * from {@link android.test.InstrumentationTestCase} (and are not performance tests).
79 * <li>Run the instrumentation using "adb shell am instrument -w",
80 * with the argument '-e class' set to run an individual {@link junit.framework.TestCase}.
81 * </ol>
82 * <p/>
83 * <b>Running all tests:</b> adb shell am instrument -w
84 * com.android.foo/android.test.InstrumentationTestRunner
85 * <p/>
86 * <b>Running all small tests:</b> adb shell am instrument -w
87 * -e size small
88 * com.android.foo/android.test.InstrumentationTestRunner
89 * <p/>
90 * <b>Running all medium tests:</b> adb shell am instrument -w
91 * -e size medium
92 * com.android.foo/android.test.InstrumentationTestRunner
93 * <p/>
94 * <b>Running all large tests:</b> adb shell am instrument -w
95 * -e size large
96 * com.android.foo/android.test.InstrumentationTestRunner
97 * <p/>
98 * <b>Running a single testcase:</b> adb shell am instrument -w
99 * -e class com.android.foo.FooTest
100 * com.android.foo/android.test.InstrumentationTestRunner
101 * <p/>
102 * <b>Running a single test:</b> adb shell am instrument -w
103 * -e class com.android.foo.FooTest#testFoo
104 * com.android.foo/android.test.InstrumentationTestRunner
105 * <p/>
106 * <b>Running multiple tests:</b> adb shell am instrument -w
107 * -e class com.android.foo.FooTest,com.android.foo.TooTest
108 * com.android.foo/android.test.InstrumentationTestRunner
109 * <p/>
110 * <b>Including performance tests:</b> adb shell am instrument -w
111 * -e perf true
112 * com.android.foo/android.test.InstrumentationTestRunner
113 * <p/>
114 * <b>To debug your tests, set a break point in your code and pass:</b>
115 * -e debug true
116 * <p/>
117 * <b>To run in 'log only' mode</b>
118 * -e log true
Jack Wangff1df692009-08-26 17:19:13 -0700119 * This option will load and iterate through all test classes and methods, but will bypass actual
120 * 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 -0800121 * instrumentation command.
122 * <p/>
123 * <b>To generate EMMA code coverage:</b>
124 * -e coverage true
Jack Wangff1df692009-08-26 17:19:13 -0700125 * Note: this requires an emma instrumented build. By default, the code coverage results file
Brett Chabot51e03642009-05-28 18:18:15 -0700126 * will be saved in a /data/<app>/coverage.ec file, unless overridden by coverageFile flag (see
127 * below)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 * <p/>
129 * <b> To specify EMMA code coverage results file path:</b>
130 * -e coverageFile /sdcard/myFile.ec
131 * <br/>
132 * in addition to the other arguments.
133 */
134
135/* (not JavaDoc)
136 * 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 -0700137 * derived class return the desired test suite from the {@link #getTestSuite()} method. The test
138 * suite returned from this method will be used if no target class is defined in the meta-data or
139 * command line argument parameters. If a derived class is used it needs to be added as an
140 * instrumentation to the AndroidManifest.xml and the command to run it would look like:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 * <p/>
142 * adb shell am instrument -w com.android.foo/<i>com.android.FooInstrumentationTestRunner</i>
143 * <p/>
144 * Where <i>com.android.FooInstrumentationTestRunner</i> is the derived class.
145 *
146 * This model is used by many existing app tests, but can probably be deprecated.
147 */
148public class InstrumentationTestRunner extends Instrumentation implements TestSuiteProvider {
149
150 /** @hide */
151 public static final String ARGUMENT_TEST_CLASS = "class";
152 /** @hide */
153 public static final String ARGUMENT_TEST_PACKAGE = "package";
154 /** @hide */
155 public static final String ARGUMENT_TEST_SIZE_PREDICATE = "size";
156 /** @hide */
157 public static final String ARGUMENT_INCLUDE_PERF = "perf";
158 /** @hide */
159 public static final String ARGUMENT_DELAY_MSEC = "delay_msec";
160
161 private static final String SMALL_SUITE = "small";
Jack Wangff1df692009-08-26 17:19:13 -0700162 private static final String MEDIUM_SUITE = "medium";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 private static final String LARGE_SUITE = "large";
Jack Wangff1df692009-08-26 17:19:13 -0700164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private static final String ARGUMENT_LOG_ONLY = "log";
166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
Jack Wangff1df692009-08-26 17:19:13 -0700168 * This constant defines the maximum allowed runtime (in ms) for a test included in the "small"
169 * 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 -0800170 */
171 private static final float SMALL_SUITE_MAX_RUNTIME = 100;
Jack Wangff1df692009-08-26 17:19:13 -0700172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 /**
Jack Wangff1df692009-08-26 17:19:13 -0700174 * This constant defines the maximum allowed runtime (in ms) for a test included in the
175 * "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 -0800176 */
177 private static final float MEDIUM_SUITE_MAX_RUNTIME = 1000;
Jack Wangff1df692009-08-26 17:19:13 -0700178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 /**
Jack Wangff1df692009-08-26 17:19:13 -0700180 * The following keys are used in the status bundle to provide structured reports to
181 * an IInstrumentationWatcher.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 */
183
184 /**
Jack Wangff1df692009-08-26 17:19:13 -0700185 * This value, if stored with key {@link android.app.Instrumentation#REPORT_KEY_IDENTIFIER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 * identifies InstrumentationTestRunner as the source of the report. This is sent with all
187 * status messages.
188 */
189 public static final String REPORT_VALUE_ID = "InstrumentationTestRunner";
190 /**
Jack Wangff1df692009-08-26 17:19:13 -0700191 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 * identifies the total number of tests that are being run. This is sent with all status
193 * messages.
194 */
195 public static final String REPORT_KEY_NUM_TOTAL = "numtests";
196 /**
Jack Wangff1df692009-08-26 17:19:13 -0700197 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 * identifies the sequence number of the current test. This is sent with any status message
199 * describing a specific test being started or completed.
200 */
201 public static final String REPORT_KEY_NUM_CURRENT = "current";
202 /**
Jack Wangff1df692009-08-26 17:19:13 -0700203 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 * identifies the name of the current test class. This is sent with any status message
205 * describing a specific test being started or completed.
206 */
207 public static final String REPORT_KEY_NAME_CLASS = "class";
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 name of the current test. This is sent with any status message
211 * describing a specific test being started or completed.
212 */
213 public static final String REPORT_KEY_NAME_TEST = "test";
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 * reports the run time in seconds of the current test.
217 */
218 private static final String REPORT_KEY_RUN_TIME = "runtime";
219 /**
Jack Wangff1df692009-08-26 17:19:13 -0700220 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 * reports the guessed suite assignment for the current test.
222 */
223 private static final String REPORT_KEY_SUITE_ASSIGNMENT = "suiteassignment";
224 /**
Brett Chabot51e03642009-05-28 18:18:15 -0700225 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
226 * identifies the path to the generated code coverage file.
227 */
228 private static final String REPORT_KEY_COVERAGE_PATH = "coverageFilePath";
229 /**
Jack Wangff1df692009-08-26 17:19:13 -0700230 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
231 * reports the cpu time in milliseconds of the current test.
232 */
233 private static final String REPORT_KEY_PERF_CPU_TIME =
234 "performance." + PerformanceCollector.METRIC_KEY_CPU_TIME;
235 /**
236 * If included in the status or final bundle sent to an IInstrumentationWatcher, this key
237 * reports the run time in milliseconds of the current test.
238 */
239 private static final String REPORT_KEY_PERF_EXECUTION_TIME =
240 "performance." + PerformanceCollector.METRIC_KEY_EXECUTION_TIME;
241
242 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 * The test is starting.
244 */
245 public static final int REPORT_VALUE_RESULT_START = 1;
246 /**
247 * The test completed successfully.
248 */
249 public static final int REPORT_VALUE_RESULT_OK = 0;
250 /**
251 * The test completed with an error.
252 */
253 public static final int REPORT_VALUE_RESULT_ERROR = -1;
254 /**
255 * The test completed with a failure.
256 */
257 public static final int REPORT_VALUE_RESULT_FAILURE = -2;
258 /**
Jack Wangff1df692009-08-26 17:19:13 -0700259 * If included in the status bundle sent to an IInstrumentationWatcher, this key
260 * 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 -0800261 * message describing a specific test being completed.
262 */
263 public static final String REPORT_KEY_STACK = "stack";
264
Brett Chabot51e03642009-05-28 18:18:15 -0700265 // Default file name for code coverage
266 private static final String DEFAULT_COVERAGE_FILE_NAME = "coverage.ec";
Jack Wangff1df692009-08-26 17:19:13 -0700267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 private static final String LOG_TAG = "InstrumentationTestRunner";
269
270 private final Bundle mResults = new Bundle();
271 private AndroidTestRunner mTestRunner;
272 private boolean mDebug;
273 private boolean mJustCount;
274 private boolean mSuiteAssignmentMode;
275 private int mTestCount;
276 private String mPackageOfTests;
277 private boolean mCoverage;
278 private String mCoverageFilePath;
279 private int mDelayMsec;
280
281 @Override
282 public void onCreate(Bundle arguments) {
283 super.onCreate(arguments);
284
285 // Apk paths used to search for test classes when using TestSuiteBuilders.
286 String[] apkPaths =
287 {getTargetContext().getPackageCodePath(), getContext().getPackageCodePath()};
288 ClassPathPackageInfoSource.setApkPaths(apkPaths);
289
290 Predicate<TestMethod> testSizePredicate = null;
291 boolean includePerformance = false;
292 String testClassesArg = null;
293 boolean logOnly = false;
294
295 if (arguments != null) {
296 // Test class name passed as an argument should override any meta-data declaration.
297 testClassesArg = arguments.getString(ARGUMENT_TEST_CLASS);
298 mDebug = getBooleanArgument(arguments, "debug");
299 mJustCount = getBooleanArgument(arguments, "count");
300 mSuiteAssignmentMode = getBooleanArgument(arguments, "suiteAssignment");
301 mPackageOfTests = arguments.getString(ARGUMENT_TEST_PACKAGE);
302 testSizePredicate = getSizePredicateFromArg(
303 arguments.getString(ARGUMENT_TEST_SIZE_PREDICATE));
304 includePerformance = getBooleanArgument(arguments, ARGUMENT_INCLUDE_PERF);
305 logOnly = getBooleanArgument(arguments, ARGUMENT_LOG_ONLY);
306 mCoverage = getBooleanArgument(arguments, "coverage");
307 mCoverageFilePath = arguments.getString("coverageFile");
308
309 try {
310 Object delay = arguments.get(ARGUMENT_DELAY_MSEC); // Accept either string or int
311 if (delay != null) mDelayMsec = Integer.parseInt(delay.toString());
312 } catch (NumberFormatException e) {
313 Log.e(LOG_TAG, "Invalid delay_msec parameter", e);
314 }
315 }
316
317 TestSuiteBuilder testSuiteBuilder = new TestSuiteBuilder(getClass().getName(),
318 getTargetContext().getClassLoader());
319
320 if (testSizePredicate != null) {
321 testSuiteBuilder.addRequirements(testSizePredicate);
322 }
323 if (!includePerformance) {
324 testSuiteBuilder.addRequirements(REJECT_PERFORMANCE);
325 }
326
327 if (testClassesArg == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 if (mPackageOfTests != null) {
329 testSuiteBuilder.includePackages(mPackageOfTests);
330 } else {
Brett Chabot61b10ac2009-03-31 17:04:34 -0700331 TestSuite testSuite = getTestSuite();
332 if (testSuite != null) {
333 testSuiteBuilder.addTestSuite(testSuite);
334 } else {
Jack Wangff1df692009-08-26 17:19:13 -0700335 // no package or class bundle arguments were supplied, and no test suite
Brett Chabot61b10ac2009-03-31 17:04:34 -0700336 // provided so add all tests in application
337 testSuiteBuilder.includePackages("");
338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340 } else {
341 parseTestClasses(testClassesArg, testSuiteBuilder);
342 }
Jack Wangff1df692009-08-26 17:19:13 -0700343
Urs Grobda13ef52009-04-17 11:30:14 -0700344 testSuiteBuilder.addRequirements(getBuilderRequirements());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345
346 mTestRunner = getAndroidTestRunner();
347 mTestRunner.setContext(getTargetContext());
Jack Wang7aba54b2009-08-20 19:20:54 -0700348 mTestRunner.setInstrumentation(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 mTestRunner.setSkipExecution(logOnly);
350 mTestRunner.setTest(testSuiteBuilder.build());
351 mTestCount = mTestRunner.getTestCases().size();
352 if (mSuiteAssignmentMode) {
353 mTestRunner.addTestListener(new SuiteAssignmentPrinter());
354 } else {
Jack Wangff1df692009-08-26 17:19:13 -0700355 WatcherResultPrinter resultPrinter = new WatcherResultPrinter(mTestCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 mTestRunner.addTestListener(new TestPrinter("TestRunner", false));
Jack Wangff1df692009-08-26 17:19:13 -0700357 mTestRunner.addTestListener(resultPrinter);
358 mTestRunner.setPerformanceResultsWriter(resultPrinter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 }
360 start();
361 }
362
Urs Grobda13ef52009-04-17 11:30:14 -0700363 List<Predicate<TestMethod>> getBuilderRequirements() {
364 return new ArrayList<Predicate<TestMethod>>();
365 }
366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 /**
Jack Wangff1df692009-08-26 17:19:13 -0700368 * Parses and loads the specified set of test classes
369 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 * @param testClassArg - comma-separated list of test classes and methods
371 * @param testSuiteBuilder - builder to add tests to
372 */
373 private void parseTestClasses(String testClassArg, TestSuiteBuilder testSuiteBuilder) {
374 String[] testClasses = testClassArg.split(",");
375 for (String testClass : testClasses) {
376 parseTestClass(testClass, testSuiteBuilder);
377 }
378 }
379
380 /**
381 * Parse and load the given test class and, optionally, method
Jack Wangff1df692009-08-26 17:19:13 -0700382 *
383 * @param testClassName - full package name of test class and optionally method to add.
384 * Expected format: com.android.TestClass#testMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 * @param testSuiteBuilder - builder to add tests to
386 */
387 private void parseTestClass(String testClassName, TestSuiteBuilder testSuiteBuilder) {
388 int methodSeparatorIndex = testClassName.indexOf('#');
389 String testMethodName = null;
390
391 if (methodSeparatorIndex > 0) {
392 testMethodName = testClassName.substring(methodSeparatorIndex + 1);
393 testClassName = testClassName.substring(0, methodSeparatorIndex);
394 }
Jack Wangff1df692009-08-26 17:19:13 -0700395 testSuiteBuilder.addTestClassByName(testClassName, testMethodName, getTargetContext());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
397
398 protected AndroidTestRunner getAndroidTestRunner() {
399 return new AndroidTestRunner();
400 }
401
402 private boolean getBooleanArgument(Bundle arguments, String tag) {
403 String tagString = arguments.getString(tag);
404 return tagString != null && Boolean.parseBoolean(tagString);
405 }
Jack Wangff1df692009-08-26 17:19:13 -0700406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 /*
408 * Returns the size predicate object, corresponding to the "size" argument value.
409 */
410 private Predicate<TestMethod> getSizePredicateFromArg(String sizeArg) {
Jack Wangff1df692009-08-26 17:19:13 -0700411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 if (SMALL_SUITE.equals(sizeArg)) {
413 return TestPredicates.SELECT_SMALL;
414 } else if (MEDIUM_SUITE.equals(sizeArg)) {
415 return TestPredicates.SELECT_MEDIUM;
416 } else if (LARGE_SUITE.equals(sizeArg)) {
417 return TestPredicates.SELECT_LARGE;
418 } else {
419 return null;
420 }
421 }
Jack Wangff1df692009-08-26 17:19:13 -0700422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 @Override
424 public void onStart() {
425 Looper.prepare();
Jack Wangff1df692009-08-26 17:19:13 -0700426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 if (mJustCount) {
428 mResults.putString(Instrumentation.REPORT_KEY_IDENTIFIER, REPORT_VALUE_ID);
429 mResults.putInt(REPORT_KEY_NUM_TOTAL, mTestCount);
430 finish(Activity.RESULT_OK, mResults);
431 } else {
432 if (mDebug) {
433 Debug.waitForDebugger();
434 }
Jack Wangff1df692009-08-26 17:19:13 -0700435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
437 PrintStream writer = new PrintStream(byteArrayOutputStream);
438 try {
439 StringResultPrinter resultPrinter = new StringResultPrinter(writer);
Jack Wangff1df692009-08-26 17:19:13 -0700440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 mTestRunner.addTestListener(resultPrinter);
Jack Wangff1df692009-08-26 17:19:13 -0700442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 long startTime = System.currentTimeMillis();
444 mTestRunner.runTest();
445 long runTime = System.currentTimeMillis() - startTime;
Jack Wangff1df692009-08-26 17:19:13 -0700446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 resultPrinter.print(mTestRunner.getTestResult(), runTime);
448 } finally {
Jack Wangff1df692009-08-26 17:19:13 -0700449 mResults.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
450 String.format("\nTest results for %s=%s",
451 mTestRunner.getTestClassName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 byteArrayOutputStream.toString()));
453
454 if (mCoverage) {
455 generateCoverageReport();
456 }
457 writer.close();
Jack Wangff1df692009-08-26 17:19:13 -0700458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 finish(Activity.RESULT_OK, mResults);
460 }
461 }
462 }
463
464 public TestSuite getTestSuite() {
465 return getAllTests();
466 }
467
468 /**
469 * Override this to define all of the tests to run in your package.
470 */
471 public TestSuite getAllTests() {
472 return null;
473 }
474
475 /**
476 * Override this to provide access to the class loader of your package.
477 */
478 public ClassLoader getLoader() {
479 return null;
480 }
Jack Wangff1df692009-08-26 17:19:13 -0700481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 private void generateCoverageReport() {
483 // use reflection to call emma dump coverage method, to avoid
484 // always statically compiling against emma jar
Brett Chabot51e03642009-05-28 18:18:15 -0700485 String coverageFilePath = getCoverageFilePath();
486 java.io.File coverageFile = new java.io.File(coverageFilePath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 try {
488 Class emmaRTClass = Class.forName("com.vladium.emma.rt.RT");
Jack Wangff1df692009-08-26 17:19:13 -0700489 Method dumpCoverageMethod = emmaRTClass.getMethod("dumpCoverageData",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 coverageFile.getClass(), boolean.class, boolean.class);
Jack Wangff1df692009-08-26 17:19:13 -0700491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 dumpCoverageMethod.invoke(null, coverageFile, false, false);
Brett Chabot51e03642009-05-28 18:18:15 -0700493 // output path to generated coverage file so it can be parsed by a test harness if
494 // needed
495 mResults.putString(REPORT_KEY_COVERAGE_PATH, coverageFilePath);
496 // also output a more user friendly msg
497 mResults.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
498 String.format("Generated code coverage data to %s", coverageFilePath));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 } catch (ClassNotFoundException e) {
500 reportEmmaError("Is emma jar on classpath?", e);
501 } catch (SecurityException e) {
502 reportEmmaError(e);
503 } catch (NoSuchMethodException e) {
504 reportEmmaError(e);
505 } catch (IllegalArgumentException e) {
506 reportEmmaError(e);
507 } catch (IllegalAccessException e) {
508 reportEmmaError(e);
509 } catch (InvocationTargetException e) {
510 reportEmmaError(e);
511 }
512 }
513
514 private String getCoverageFilePath() {
515 if (mCoverageFilePath == null) {
Brett Chabot51e03642009-05-28 18:18:15 -0700516 return getTargetContext().getFilesDir().getAbsolutePath() + File.separator +
Jack Wangff1df692009-08-26 17:19:13 -0700517 DEFAULT_COVERAGE_FILE_NAME;
518 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 return mCoverageFilePath;
520 }
521 }
522
523 private void reportEmmaError(Exception e) {
Jack Wangff1df692009-08-26 17:19:13 -0700524 reportEmmaError("", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
526
527 private void reportEmmaError(String hint, Exception e) {
528 String msg = "Failed to generate emma coverage. " + hint;
529 Log.e(LOG_TAG, msg, e);
530 mResults.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "\nError: " + msg);
531 }
532
533 // TODO kill this, use status() and prettyprint model for better output
534 private class StringResultPrinter extends ResultPrinter {
535
536 public StringResultPrinter(PrintStream writer) {
537 super(writer);
538 }
539
540 synchronized void print(TestResult result, long runTime) {
541 printHeader(runTime);
542 printFooter(result);
543 }
544 }
Jack Wangff1df692009-08-26 17:19:13 -0700545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 /**
Jack Wangff1df692009-08-26 17:19:13 -0700547 * This class sends status reports back to the IInstrumentationWatcher about
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 * which suite each test belongs.
549 */
Jack Wangff1df692009-08-26 17:19:13 -0700550 private class SuiteAssignmentPrinter implements TestListener {
551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 private Bundle mTestResult;
553 private long mStartTime;
554 private long mEndTime;
555 private boolean mTimingValid;
Jack Wangff1df692009-08-26 17:19:13 -0700556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 public SuiteAssignmentPrinter() {
558 }
Jack Wangff1df692009-08-26 17:19:13 -0700559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 /**
561 * send a status for the start of a each test, so long tests can be seen as "running"
562 */
563 public void startTest(Test test) {
564 mTimingValid = true;
Jack Wangff1df692009-08-26 17:19:13 -0700565 mStartTime = System.currentTimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 }
Jack Wangff1df692009-08-26 17:19:13 -0700567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 /**
569 * @see junit.framework.TestListener#addError(Test, Throwable)
570 */
571 public void addError(Test test, Throwable t) {
572 mTimingValid = false;
573 }
574
575 /**
576 * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
577 */
578 public void addFailure(Test test, AssertionFailedError t) {
579 mTimingValid = false;
580 }
581
582 /**
583 * @see junit.framework.TestListener#endTest(Test)
584 */
585 public void endTest(Test test) {
586 float runTime;
587 String assignmentSuite;
588 mEndTime = System.currentTimeMillis();
589 mTestResult = new Bundle();
590
591 if (!mTimingValid || mStartTime < 0) {
592 assignmentSuite = "NA";
593 runTime = -1;
594 } else {
595 runTime = mEndTime - mStartTime;
Jack Wangff1df692009-08-26 17:19:13 -0700596 if (runTime < SMALL_SUITE_MAX_RUNTIME
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 && !InstrumentationTestCase.class.isAssignableFrom(test.getClass())) {
598 assignmentSuite = SMALL_SUITE;
599 } else if (runTime < MEDIUM_SUITE_MAX_RUNTIME) {
600 assignmentSuite = MEDIUM_SUITE;
601 } else {
602 assignmentSuite = LARGE_SUITE;
603 }
604 }
605 // Clear mStartTime so that we can verify that it gets set next time.
606 mStartTime = -1;
607
Jack Wangff1df692009-08-26 17:19:13 -0700608 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
609 test.getClass().getName() + "#" + ((TestCase) test).getName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 + "\nin " + assignmentSuite + " suite\nrunTime: "
611 + String.valueOf(runTime) + "\n");
612 mTestResult.putFloat(REPORT_KEY_RUN_TIME, runTime);
613 mTestResult.putString(REPORT_KEY_SUITE_ASSIGNMENT, assignmentSuite);
614
615 sendStatus(0, mTestResult);
616 }
617 }
Jack Wangff1df692009-08-26 17:19:13 -0700618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 /**
620 * This class sends status reports back to the IInstrumentationWatcher
621 */
Jack Wangff1df692009-08-26 17:19:13 -0700622 private class WatcherResultPrinter implements TestListener, PerformanceResultsWriter {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 private final Bundle mResultTemplate;
624 Bundle mTestResult;
625 int mTestNum = 0;
626 int mTestResultCode = 0;
627 String mTestClass = null;
Jack Wangff1df692009-08-26 17:19:13 -0700628 boolean mIsTimedTest = false;
629 long mCpuTime = 0;
630 long mExecTime = 0;
631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 public WatcherResultPrinter(int numTests) {
633 mResultTemplate = new Bundle();
634 mResultTemplate.putString(Instrumentation.REPORT_KEY_IDENTIFIER, REPORT_VALUE_ID);
635 mResultTemplate.putInt(REPORT_KEY_NUM_TOTAL, numTests);
636 }
Jack Wangff1df692009-08-26 17:19:13 -0700637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 /**
Jack Wangff1df692009-08-26 17:19:13 -0700639 * send a status for the start of a each test, so long tests can be seen
640 * as "running"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 */
642 public void startTest(Test test) {
643 String testClass = test.getClass().getName();
Jack Wangff1df692009-08-26 17:19:13 -0700644 String testName = ((TestCase)test).getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 mTestResult = new Bundle(mResultTemplate);
646 mTestResult.putString(REPORT_KEY_NAME_CLASS, testClass);
Jack Wangff1df692009-08-26 17:19:13 -0700647 mTestResult.putString(REPORT_KEY_NAME_TEST, testName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 mTestResult.putInt(REPORT_KEY_NUM_CURRENT, ++mTestNum);
649 // pretty printing
650 if (testClass != null && !testClass.equals(mTestClass)) {
Jack Wangff1df692009-08-26 17:19:13 -0700651 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 String.format("\n%s:", testClass));
653 mTestClass = testClass;
654 } else {
655 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "");
656 }
657
658 // The delay_msec parameter is normally used to provide buffers of idle time
Jack Wangff1df692009-08-26 17:19:13 -0700659 // for power measurement purposes. To make sure there is a delay before and after
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 // every test in a suite, we delay *after* every test (see endTest below) and also
Jack Wangff1df692009-08-26 17:19:13 -0700661 // delay *before* the first test. So, delay test1 delay test2 delay.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662
663 try {
664 if (mTestNum == 1) Thread.sleep(mDelayMsec);
665 } catch (InterruptedException e) {
666 throw new IllegalStateException(e);
667 }
668
669 sendStatus(REPORT_VALUE_RESULT_START, mTestResult);
670 mTestResultCode = 0;
Jack Wangff1df692009-08-26 17:19:13 -0700671
672 mIsTimedTest = false;
673 try {
674 // Look for TimedTest annotation on both test class and test
675 // method
676 mIsTimedTest = test.getClass().isAnnotationPresent(TimedTest.class) ||
677 test.getClass().getMethod(testName).isAnnotationPresent(TimedTest.class);
678 } catch (SecurityException e) {
679 throw new IllegalStateException(e);
680 } catch (NoSuchMethodException e) {
681 throw new IllegalStateException(e);
682 }
683
684 if (mIsTimedTest) {
685 mExecTime = SystemClock.uptimeMillis();
686 mCpuTime = Process.getElapsedCpuTime();
687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
Jack Wangff1df692009-08-26 17:19:13 -0700689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 /**
691 * @see junit.framework.TestListener#addError(Test, Throwable)
692 */
693 public void addError(Test test, Throwable t) {
694 mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t));
695 mTestResultCode = REPORT_VALUE_RESULT_ERROR;
696 // pretty printing
Jack Wangff1df692009-08-26 17:19:13 -0700697 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
698 String.format("\nError in %s:\n%s",
699 ((TestCase)test).getName(), BaseTestRunner.getFilteredTrace(t)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 }
701
702 /**
703 * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
704 */
705 public void addFailure(Test test, AssertionFailedError t) {
706 mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t));
707 mTestResultCode = REPORT_VALUE_RESULT_FAILURE;
708 // pretty printing
Jack Wangff1df692009-08-26 17:19:13 -0700709 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT,
710 String.format("\nFailure in %s:\n%s",
711 ((TestCase)test).getName(), BaseTestRunner.getFilteredTrace(t)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713
714 /**
715 * @see junit.framework.TestListener#endTest(Test)
716 */
717 public void endTest(Test test) {
Jack Wangff1df692009-08-26 17:19:13 -0700718 if (mIsTimedTest) {
719 mCpuTime = Process.getElapsedCpuTime() - mCpuTime;
720 mExecTime = SystemClock.uptimeMillis() - mExecTime;
721 mTestResult.putLong(REPORT_KEY_PERF_CPU_TIME, mCpuTime);
722 mTestResult.putLong(REPORT_KEY_PERF_EXECUTION_TIME, mExecTime);
723 }
724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mTestResultCode == 0) {
726 mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, ".");
727 }
728 sendStatus(mTestResultCode, mTestResult);
729
Jack Wangff1df692009-08-26 17:19:13 -0700730 try { // Sleep after every test, if specified
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 Thread.sleep(mDelayMsec);
732 } catch (InterruptedException e) {
733 throw new IllegalStateException(e);
734 }
735 }
736
Jack Wangff1df692009-08-26 17:19:13 -0700737 public void writeBeginSnapshot(String label) {
738 // Do nothing
739 }
740
741 public void writeEndSnapshot(Bundle results) {
742 // Copy all snapshot data fields as type long into mResults, which
743 // is outputted via Instrumentation.finish
744 for (String key : results.keySet()) {
745 mResults.putLong(key, results.getLong(key));
746 }
747 }
748
749 public void writeStartTiming(String label) {
750 // Do nothing
751 }
752
753 public void writeStopTiming(Bundle results) {
754 // Copy results into mTestResult by flattening list of iterations,
755 // which is outputted via WatcherResultPrinter.endTest
756 int i = 0;
757 for (Parcelable p :
758 results.getParcelableArrayList(PerformanceCollector.METRIC_KEY_ITERATIONS)) {
759 Bundle iteration = (Bundle)p;
760 String index = "performance.iteration" + i + ".";
761 mTestResult.putString(index + PerformanceCollector.METRIC_KEY_LABEL,
762 iteration.getString(PerformanceCollector.METRIC_KEY_LABEL));
763 mTestResult.putLong(index + PerformanceCollector.METRIC_KEY_CPU_TIME,
764 iteration.getLong(PerformanceCollector.METRIC_KEY_CPU_TIME));
765 mTestResult.putLong(index + PerformanceCollector.METRIC_KEY_EXECUTION_TIME,
766 iteration.getLong(PerformanceCollector.METRIC_KEY_EXECUTION_TIME));
767 i++;
768 }
769 }
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 // TODO report the end of the cycle
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
773}