Skip to content
Browse files

Added licensing and documentation. Reformatted to match Android conve…

…ntions.
  • Loading branch information...
1 parent d9489d7 commit 5a491efcb102c2989e5bfd9b4008331c18a12f17 @jsankey committed Jul 14, 2010
Showing with 588 additions and 210 deletions.
  1. +202 −0 LICENSE
  2. +173 −0 README
  3. +14 −6 build.xml
  4. +135 −159 src/com/zutubi/android/junitreport/JUnitReportListener.java
  5. +64 −45 src/com/zutubi/android/junitreport/JUnitReportTestRunner.java
View
202 LICENSE
@@ -0,0 +1,202 @@
+
+ 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
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
View
173 README
@@ -0,0 +1,173 @@
+Android JUnit Report Test Runner
+================================
+
+Introduction
+------------
+
+The Android JUnit report test runner is a custom instrumentation test
+runner for Android that creates XML test reports. These reports are
+in a similar format to those created by the Ant JUnit task's XML
+formatter, allowing them to be integrated with tools that support that
+format (e.g. continuous integration servers).
+
+How It Works
+------------
+
+This test runner may be used as a drop-in replacement for the standard
+InstrumentationTestRunner provided in the Android SDK. It is in fact
+an extension of that runner, supporting the same functionality with
+the addition of XML report generation.
+
+To be consistent with existing SDK support for generating coverage
+reports, this runner outputs its XML report in the file storage area
+for the application under test. By default, the report file is
+produced at:
+
+/data/data/<tested application package>/files/junit-report.xml
+
+The file may be retrieved from the device using adb pull (see below
+for more details).
+
+Using the Runner
+----------------
+
+USING WITH ANT BUILDS
+
+To use this runner with an Ant build (based on the Android SDK support
+for Ant):
+
+ * Add android-junit-report-<version>.jar to your test project's
+ libraries by dropping the jar into a libs/ subdirectory.
+
+ * Update your test project's manifest <instrumentation> tag. Change
+ the android:name attribute's value to:
+
+ com.zutubi.android.junitreport.JUnitReportTestRunner
+
+ * Edit your build.xml file and set the test.runner property to:
+
+ com.zutubi.android.junitreport.JUnitReportTestRunner
+
+ This must be set *before* running the Android <setup/> task.
+
+These steps will cause your tests to be executed with the custom
+runner, which will produce the junit-report.xml file in the storage
+area for the project under test. To retrieve the file from the
+device, you can use Ant to run an adb pull, for example:
+
+ <target name="fetch-test-report">
+ <echo>Downloading XML test report...</echo>
+ <mkdir dir="${reports.dir}"/>
+ <exec executable="${adb}" failonerror="true">
+ <arg line="${adb.device.arg}"/>
+ <arg value="pull" />
+ <arg value="/data/data/${tested.manifest.package}/files/junit-report.xml" />
+ <arg value="${reports.dir}/junit-report.xml" />
+ </exec>
+ </target>
+
+USING WITH ECLIPSE
+
+When running within Eclipse, there is not much call for XML test
+reports. However, assuming you have edited you test project's
+manifest to specify this custom runner (as described above), you may
+also need to tell Eclipse to use this runner to avoid problems. You
+can do this by:
+
+ * Adding android-junit-report-<version>.jar to the build path of
+ your test project in Eclipse.
+ * Ensuring all existing run configurations for unit tests specify
+ an Instrumentation runner of:
+
+ com.zutubi.android.junitreport.JUnitReportTestRunner
+
+If you see an error about not being able to find a target package for
+android.test.InstrumentationTestRunner, it is likely you have an
+existing run configuration that is set to use the default runner. You
+can recreate any such configurations and the issue will disappear.
+
+Report Format
+-------------
+
+As stated above, the XML report format is based on the Ant JUnit
+task's XML formatter. A few caveats apply:
+
+ * Multiple suites are all placed in a single file under a root
+ <testsuites> element.
+ * Redundant information about the number of nested cases within a
+ suite is omitted.
+ * Durations are omitted from both suites and cases.
+ * Neither standard output nor system properties are included.
+
+The differences mainly revolve around making this reporting as
+lightweight as possible. The report is streamed as the tests run,
+making it impossible to, e.g. include the case count in a
+<testsuite> element. It is possible that durations may be added to
+cases in the future, as this requires minimal buffering.
+
+The format is intended to be "compatible enough" for integration with
+existing tools. In my particular case I use the reports with my own
+Pulse Continuous Integration Server, so compatibility with it was my
+first target. If you find an incompatibility with another tool, let
+me know (see below) and I will see what can be done.
+
+Customising Via Arguments
+-------------------------
+
+The runner supports two arguments:
+
+ * reportFilePath: the path, relative to the root of the tested
+ application's file storage area, of the report file to generate.
+ Defaults to junit-report.xml.
+ * filterTraces: if true, stack traces in the report will be filtered
+ to remove common noise (e.g. framework methods). Defaults to
+ true.
+
+To specify arguments, use the -e flag to adb shell am instrument, for
+example:
+
+adb shell am instrument -w -e reportFilePath my-report.xml \
+ com.example.test/com.zutubi.android.junitreport.JUnitReportTestRunner
+
+Building From Source
+--------------------
+
+If you would like to modify the runner, or build it yourself for any
+other reason, you will need:
+
+ * A JDK, version 1.5 or later.
+ * The Android SDK (or at least a stub android.jar as provided in the
+ SDK).
+ * Apache Ant version 1.7 or later.
+
+To run a build:
+
+ * Create a file local.properties in the directory containing this
+ README. In this file, define the location of an android.jar to
+ build against, for example:
+
+ android.jar=/usr/local/java/android/platforms/android-8/android.jar
+
+ where /usr/local/java/android is the root of an Android SDK.
+
+ * Run ant in this same directory:
+
+ $ ant
+
+The jar will be created at build/android-junit-report-dev.jar.
+
+Contact
+-------
+
+If you have any thoughts, questions etc about the runner, you can
+contact me at:
+
+ jason@zutubi.com
+
+All feedback is welcome.
+
+License
+-------
+
+This code is licensed under the Apache License, Version 2.0. See the
+LICENSE file for details.
View
20 build.xml
@@ -1,20 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project name="andoird-junit-report" default="jar">
+<project name="android-junit-report" default="jar">
<!-- Should define the location of android.jar to build against. -->
<property file="local.properties"/>
- <property name="source.dir" value="src"/>
+ <property name="version" value="dev"/>
+ <property name="source.dir" value="src"/>
<property name="out.dir" value="build"/>
<property name="classes.dir" value="${out.dir}/classes"/>
-
+ <property name="jar" value="${out.dir}/android-junit-report-${version}.jar"/>
+
<target name="clean">
<delete dir="${out.dir}"/>
</target>
<target name="-init">
- <mkdir dir="${out.dir}"/>
- <mkdir dir="${classes.dir}"/>
+ <mkdir dir="${out.dir}"/>
+ <mkdir dir="${classes.dir}"/>
</target>
<target name="compile" depends="-init">
@@ -24,6 +26,12 @@
</target>
<target name="jar" depends="compile">
- <jar destfile="${out.dir}/android-junit-report.jar" basedir="${classes.dir}"/>
+ <jar destfile="${jar}" basedir="${classes.dir}">
+ <manifest>
+ <attribute name="Implementation-Vendor" value="Zutubi Pty Ltd"/>
+ <attribute name="Implementation-Title" value="Android JUnit Report Test Runner"/>
+ <attribute name="Implementation-Version" value="${version}"/>
+ </manifest>
+ </jar>
</target>
</project>
View
294 src/com/zutubi/android/junitreport/JUnitReportListener.java
@@ -1,11 +1,24 @@
+/*
+ * Copyright (C) 2010 Zutubi Pty Ltd
+ *
+ * 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.zutubi.android.junitreport;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.Writer;
+import android.content.Context;
+import android.util.Log;
+import android.util.Xml;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
@@ -14,245 +27,208 @@
import org.xmlpull.v1.XmlSerializer;
-import android.content.Context;
-import android.util.Log;
-import android.util.Xml;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
/**
- * Custom test listener that outputs test results to a single XML file. The
- * file uses a similar format the to Ant JUnit task XML formatter, with a
- * couple of caveats:
+ * Custom test listener that outputs test results to a single XML file. The file
+ * uses a similar format the to Ant JUnit task XML formatter, with a couple of
+ * caveats:
* <ul>
- * <li>Multiple suites are all placed in a single file under a root
- * &lt;testsuites&gt; element.</li>
- * <li>Redundant information about the number of nested cases within a
- * suite is omitted.</li>
- * <li>Durations are omitted from both suites and cases.</li>
- * <li>Neither standard output nor system properties are included.</li>
+ * <li>Multiple suites are all placed in a single file under a root
+ * &lt;testsuites&gt; element.</li>
+ * <li>Redundant information about the number of nested cases within a suite is
+ * omitted.</li>
+ * <li>Durations are omitted from both suites and cases.</li>
+ * <li>Neither standard output nor system properties are included.</li>
* </ul>
- * The differences mainly revolve around making this reporting as lightweight
- * as possible. The report is streamed as the tests run, making it impossible
- * to, e.g. include the case count in a &lt;testsuite&gt; element. It is
- * possible that durations may be added to cases in the future, as this
- * requires minimal buffering.
+ * The differences mainly revolve around making this reporting as lightweight as
+ * possible. The report is streamed as the tests run, making it impossible to,
+ * e.g. include the case count in a &lt;testsuite&gt; element. It is possible
+ * that durations may be added to cases in the future, as this requires minimal
+ * buffering.
*/
-public class JUnitReportListener implements TestListener
-{
+public class JUnitReportListener implements TestListener {
private static final String LOG_TAG = "JUnitReportListener";
-
+
private static final String ENCODING_UTF_8 = "utf-8";
private static final String TAG_SUITES = "testsuites";
private static final String TAG_SUITE = "testsuite";
private static final String TAG_CASE = "testcase";
private static final String TAG_ERROR = "error";
private static final String TAG_FAILURE = "failure";
+
private static final String ATTRIBUTE_NAME = "name";
private static final String ATTRIBUTE_CLASS = "classname";
private static final String ATTRIBUTE_TYPE = "type";
private static final String ATTRIBUTE_MESSAGE = "message";
-
+
// With thanks to org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.
// Trimmed some entries, added others for Android.
private static final String[] DEFAULT_TRACE_FILTERS = new String[] {
- "junit.framework.TestCase",
- "junit.framework.TestResult",
- "junit.framework.TestSuite",
- "junit.framework.Assert.", // don't filter AssertionFailure
- "java.lang.reflect.Method.invoke(",
- "sun.reflect.",
- // JUnit 4 support:
- "org.junit.",
- "junit.framework.JUnit4TestAdapter",
- " more",
- // Added for Android
- "android.test.",
- "android.app.Instrumentation",
- "java.lang.reflect.Method.invokeNative",
- };
+ "junit.framework.TestCase", "junit.framework.TestResult",
+ "junit.framework.TestSuite",
+ "junit.framework.Assert.", // don't filter AssertionFailure
+ "java.lang.reflect.Method.invoke(", "sun.reflect.",
+ // JUnit 4 support:
+ "org.junit.", "junit.framework.JUnit4TestAdapter", " more",
+ // Added for Android
+ "android.test.", "android.app.Instrumentation",
+ "java.lang.reflect.Method.invokeNative",
+ };
+
+ private Context mContext;
+ private String mReportFilePath;
+ private boolean mFilterTraces;
+ private FileOutputStream mOutputStream;
+ private XmlSerializer mSerializer;
+ private String mCurrentSuite;
- private Context context;
- private String reportFilePath;
- private boolean filterTraces;
- private FileOutputStream os;
- private XmlSerializer serializer;
- private String currentSuite;
-
/**
* Creates a new listener.
*
- * @param context context of the target application under test
+ * @param context context of the target application under test
* @param reportFilePath path of the report file to create (under the
- * context using {@link Context#openFileOutput(String, int)}).
- * @param filterTraces if true, stack traces will have common noise (e.g.
- * framework methods) omitted for clarity
+ * context using {@link Context#openFileOutput(String, int)}).
+ * @param filterTraces if true, stack traces will have common noise (e.g.
+ * framework methods) omitted for clarity
*/
- public JUnitReportListener(Context context, String reportFilePath, boolean filterTraces)
- {
- this.context = context;
- this.reportFilePath = reportFilePath;
- this.filterTraces = filterTraces;
+ public JUnitReportListener(Context context, String reportFilePath, boolean filterTraces) {
+ this.mContext = context;
+ this.mReportFilePath = reportFilePath;
+ this.mFilterTraces = filterTraces;
}
-
+
@Override
- public void startTest(Test test)
- {
- try
- {
+ public void startTest(Test test) {
+ try {
openIfRequired(test);
- if (test instanceof TestCase)
- {
+ if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
checkForNewSuite(testCase);
- serializer.startTag("", TAG_CASE);
- serializer.attribute("", ATTRIBUTE_CLASS, currentSuite);
- serializer.attribute("", ATTRIBUTE_NAME, testCase.getName());
+ mSerializer.startTag("", TAG_CASE);
+ mSerializer.attribute("", ATTRIBUTE_CLASS, mCurrentSuite);
+ mSerializer.attribute("", ATTRIBUTE_NAME, testCase.getName());
}
- }
- catch (Exception e)
- {
+ } catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
- private void checkForNewSuite(TestCase testCase) throws Exception
- {
+ private void checkForNewSuite(TestCase testCase) throws IOException {
String suiteName = testCase.getClass().getName();
- if (currentSuite == null || !currentSuite.equals(suiteName))
- {
- if (currentSuite != null)
- {
- serializer.endTag("", TAG_SUITE);
+ if (mCurrentSuite == null || !mCurrentSuite.equals(suiteName)) {
+ if (mCurrentSuite != null) {
+ mSerializer.endTag("", TAG_SUITE);
}
-
- serializer.startTag("", TAG_SUITE);
- serializer.attribute("", ATTRIBUTE_NAME, suiteName);
- currentSuite = suiteName;
+
+ mSerializer.startTag("", TAG_SUITE);
+ mSerializer.attribute("", ATTRIBUTE_NAME, suiteName);
+ mCurrentSuite = suiteName;
}
}
- private void openIfRequired(Test test) throws FileNotFoundException, IOException
- {
- if (os == null)
- {
- os = context.openFileOutput(reportFilePath, 0);
- serializer = Xml.newSerializer();
- serializer.setOutput(os, ENCODING_UTF_8);
- serializer.startDocument(ENCODING_UTF_8, true);
- serializer.startTag("", TAG_SUITES);
+ private void openIfRequired(Test test) throws IOException {
+ if (mOutputStream == null) {
+ mOutputStream = mContext.openFileOutput(mReportFilePath, 0);
+ mSerializer = Xml.newSerializer();
+ mSerializer.setOutput(mOutputStream, ENCODING_UTF_8);
+ mSerializer.startDocument(ENCODING_UTF_8, true);
+ mSerializer.startTag("", TAG_SUITES);
}
}
@Override
- public void addError(Test test, Throwable error)
- {
+ public void addError(Test test, Throwable error) {
addProblem(TAG_ERROR, error);
}
@Override
- public void addFailure(Test test, AssertionFailedError error)
- {
+ public void addFailure(Test test, AssertionFailedError error) {
addProblem(TAG_FAILURE, error);
}
- private void addProblem(String tag, Throwable error)
- {
- try
- {
- serializer.startTag("", tag);
- serializer.attribute("", ATTRIBUTE_MESSAGE, safeMessage(error));
- serializer.attribute("", ATTRIBUTE_TYPE, error.getClass().getName());
- StringWriter w = new StringWriter();
- error.printStackTrace(filterTraces ? new FilteringWriter(w) : new PrintWriter(w));
- serializer.text(w.toString());
- serializer.endTag("", tag);
- }
- catch (Exception e)
- {
+ private void addProblem(String tag, Throwable error) {
+ try {
+ mSerializer.startTag("", tag);
+ mSerializer.attribute("", ATTRIBUTE_MESSAGE, safeMessage(error));
+ mSerializer.attribute("", ATTRIBUTE_TYPE, error.getClass().getName());
+ StringWriter w = new StringWriter();
+ error.printStackTrace(mFilterTraces ? new FilteringWriter(w) : new PrintWriter(w));
+ mSerializer.text(w.toString());
+ mSerializer.endTag("", tag);
+ } catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
@Override
- public void endTest(Test test)
- {
- try
- {
- if (test instanceof TestCase)
- {
- serializer.endTag("", TAG_CASE);
+ public void endTest(Test test) {
+ try {
+ if (test instanceof TestCase) {
+ mSerializer.endTag("", TAG_CASE);
}
- }
- catch (Exception e)
- {
+ } catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
- public void close()
- {
- if (serializer != null)
- {
- try
- {
- if (currentSuite != null)
- {
- serializer.endTag("", TAG_SUITE);
+ /**
+ * Releases all resources associated with this listener. Must be called
+ * when the listener is finished with.
+ */
+ public void close() {
+ if (mSerializer != null) {
+ try {
+ if (mCurrentSuite != null) {
+ mSerializer.endTag("", TAG_SUITE);
}
- serializer.endTag("", TAG_SUITES);
- serializer.endDocument();
- serializer = null;
- }
- catch (Exception e)
- {
+ mSerializer.endTag("", TAG_SUITES);
+ mSerializer.endDocument();
+ mSerializer = null;
+ } catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
-
- if (os != null)
- {
- try
- {
- os.close();
- os = null;
- }
- catch (IOException e)
- {
+
+ if (mOutputStream != null) {
+ try {
+ mOutputStream.close();
+ mOutputStream = null;
+ } catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
}
- private String safeMessage(Throwable error)
- {
- String message = error.getMessage();
+ private String safeMessage(Throwable error) {
+ String message = error.getMessage();
return error.getClass().getName() + ": " + (message == null ? "<null>" : message);
}
-
+
/**
* Wrapper around a print writer that filters out common noise from stack
* traces, making it easier to see the actual failure.
*/
- private static class FilteringWriter extends PrintWriter
- {
- public FilteringWriter(Writer out)
- {
+ private static class FilteringWriter extends PrintWriter {
+ public FilteringWriter(Writer out) {
super(out);
}
@Override
- public void println(String s)
- {
- for (String filtered: DEFAULT_TRACE_FILTERS)
- {
- if (s.contains(filtered))
- {
+ public void println(String s) {
+ for (String filtered : DEFAULT_TRACE_FILTERS) {
+ if (s.contains(filtered)) {
return;
}
}
-
+
super.println(s);
}
}
View
109 src/com/zutubi/android/junitreport/JUnitReportTestRunner.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2010 Zutubi Pty Ltd
+ *
+ * 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.zutubi.android.junitreport;
import android.os.Bundle;
@@ -6,74 +22,77 @@
/**
* Custom test runner that adds a {@link JUnitReportListener} to the underlying
- * test runner in order to capture test results in an XML report. You may use
+ * test runner in order to capture test results in an XML report. You may use
* this class in place of {@link InstrumentationTestRunner} in your test
- * project's manifest, and/or specify it to your Ant build using the
- * test.runner property.
+ * project's manifest, and/or specify it to your Ant build using the test.runner
+ * property.
* <p/>
- * This runner behaves identically to the default, with the added side-effect
- * of producing a JUnit XML report. The report format is similar to that
- * produced by the Ant JUnit task's XML formatter, making it compatible with
- * existing tools that can process that format. See
- * {@link JUnitReportListener} for further details.
+ * This runner behaves identically to the default, with the added side-effect of
+ * producing a JUnit XML report. The report format is similar to that produced
+ * by the Ant JUnit task's XML formatter, making it compatible with existing
+ * tools that can process that format. See {@link JUnitReportListener} for
+ * further details.
* <p/>
* This runner accepts the following arguments:
* <ul>
- * <li>reportFilePath: path of the file to write the XML report to, in the
- * target application's data area (default: junit-report.xml).</li>
- * <li>filterTraces: if true, stack traces in test failure reports will be
- * filtered to remove noise such as framework methods (default: true)</li>
+ * <li>reportFilePath: path of the file to write the XML report to, in the
+ * target application's data area (default: junit-report.xml).</li>
+ * <li>filterTraces: if true, stack traces in test failure reports will be
+ * filtered to remove noise such as framework methods (default: true)</li>
* </ul>
* These arguments may be specified as follows:
- * <pre>{@code adb shell am instrument -w -e reportFile my-report-file.xml}</pre>
+ *
+ * <pre>
+ * {@code adb shell am instrument -w -e reportFile my-report-file.xml}
+ * </pre>
*/
-public class JUnitReportTestRunner extends InstrumentationTestRunner
-{
+public class JUnitReportTestRunner extends InstrumentationTestRunner {
+ /**
+ * Path, relative to the target applications file root, at which to write the report file.
+ */
private static final String ARG_REPORT_FILE_PATH = "reportFilePath";
- private static final String ARG_FILTER_TRACES = "filterTraces";
-
+ /**
+ * If true, stack traces in the report will be filtered to remove common noise (e.g. framework
+ * methods).
+ */
+ private static final String ARG_FILTER_TRACES = "filterTraces";
+ /**
+ * Default path of the report file.
+ */
private static final String DEFAULT_REPORT_FILE = "junit-report.xml";
-
- private JUnitReportListener listener;
- private String reportFilePath;
- private boolean filterTraces = true;
-
+
+ private JUnitReportListener mListener;
+ private String mReportFilePath;
+ private boolean mFilterTraces = true;
+
@Override
- public void onCreate(Bundle arguments)
- {
- if (arguments != null)
- {
- reportFilePath = arguments.getString(ARG_REPORT_FILE_PATH);
- filterTraces = arguments.getBoolean(ARG_FILTER_TRACES, true);
+ public void onCreate(Bundle arguments) {
+ if (arguments != null) {
+ mReportFilePath = arguments.getString(ARG_REPORT_FILE_PATH);
+ mFilterTraces = arguments.getBoolean(ARG_FILTER_TRACES, true);
}
-
- if (reportFilePath == null)
- {
- reportFilePath = DEFAULT_REPORT_FILE;
+
+ if (mReportFilePath == null) {
+ mReportFilePath = DEFAULT_REPORT_FILE;
}
super.onCreate(arguments);
}
-
+
@Override
- protected AndroidTestRunner getAndroidTestRunner()
- {
+ protected AndroidTestRunner getAndroidTestRunner() {
AndroidTestRunner runner = new AndroidTestRunner();
- listener = new JUnitReportListener(getTargetContext(), reportFilePath, filterTraces);
- runner.addTestListener(listener);
+ mListener = new JUnitReportListener(getTargetContext(), mReportFilePath, mFilterTraces);
+ runner.addTestListener(mListener);
return runner;
}
@Override
- public void finish(int resultCode, Bundle results)
- {
- if (listener != null)
- {
- listener.close();
+ public void finish(int resultCode, Bundle results) {
+ if (mListener != null) {
+ mListener.close();
}
-
+
super.finish(resultCode, results);
}
-
-
}

0 comments on commit 5a491ef

Please sign in to comment.
Something went wrong with that request. Please try again.