am d797c1b5: (-s ours) am 922fca93: Merge "Enhance the options check so that if we expect to see a null options bundle we accept a non-null but empty bundle as well." into gingerbread
* commit 'd797c1b5d95850828ff5d20f0842549d72839bfc':
Enhance the options check so that if we expect to see a null options bundle we accept a non-null but empty bundle as well.
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index 60e6858..8667573 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -37,6 +37,7 @@
CtsDatabaseTestCases \
CtsDpiTestCases \
CtsDpiTestCases2 \
+ CtsDrmTestCases \
CtsExampleTestCases \
CtsGestureTestCases \
CtsGraphicsTestCases \
@@ -50,6 +51,7 @@
CtsPermission2TestCases \
CtsPreferenceTestCases \
CtsProviderTestCases \
+ CtsRenderscriptTestCases \
CtsSaxTestCases \
CtsSpeechTestCases \
CtsTelephonyTestCases \
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
index aad97ad..8543890 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
@@ -125,6 +125,10 @@
new Feature("android.software.sip.voip", false),
};
+ public static final Feature[] ALL_HONEYCOMB_FEATURES = {
+ new Feature("android.hardware.faketouch", true),
+ };
+
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -162,6 +166,9 @@
if (apiVersion >= Build.VERSION_CODES.GINGERBREAD) {
Collections.addAll(features, ALL_GINGERBREAD_FEATURES);
}
+ if (apiVersion >= Build.VERSION_CODES.HONEYCOMB) {
+ Collections.addAll(features, ALL_HONEYCOMB_FEATURES);
+ }
for (Feature f : features) {
HashMap<String, Object> row = new HashMap<String, Object>();
listViewData.add(row);
diff --git a/development/ide/eclipse/.classpath b/development/ide/eclipse/.classpath
index ac56b05..8d10955 100644
--- a/development/ide/eclipse/.classpath
+++ b/development/ide/eclipse/.classpath
@@ -21,6 +21,7 @@
<classpathentry kind="src" path="cts/tests/tests/database/src"/>
<classpathentry kind="src" path="cts/tests/tests/dpi/src"/>
<classpathentry kind="src" path="cts/tests/tests/dpi2/src"/>
+ <classpathentry kind="src" path="cts/tests/tests/drm/src"/>
<classpathentry kind="src" path="cts/tests/tests/example/src"/>
<classpathentry kind="src" path="cts/tests/tests/gesture/src"/>
<classpathentry kind="src" path="cts/tests/tests/graphics/src"/>
@@ -39,6 +40,7 @@
<classpathentry kind="src" path="cts/tests/tests/permission2/src"/>
<classpathentry kind="src" path="cts/tests/tests/preference/src"/>
<classpathentry kind="src" path="cts/tests/tests/provider/src"/>
+ <classpathentry kind="src" path="cts/tests/tests/renderscript/src"/>
<classpathentry kind="src" path="cts/tests/tests/speech/src"/>
<classpathentry kind="src" path="cts/tests/tests/telephony/src"/>
<classpathentry kind="src" path="cts/tests/tests/text/src"/>
diff --git a/tests/Android.mk b/tests/Android.mk
index 838d01d..641d053 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -18,6 +18,7 @@
LOCAL_MODULE_TAGS := tests
LOCAL_SRC_FILES := $(call all-java-files-under, src)\
+ $(call all-renderscript-files-under, src)\
$(call all-java-files-under, core/runner/src)\
src/android/app/cts/ISecondary.aidl\
src/android/os/cts/IEmptyService.aidl
diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml
index 7eaafb3..6f302a6 100644
--- a/tests/AndroidManifest.xml
+++ b/tests/AndroidManifest.xml
@@ -938,6 +938,11 @@
android:resource="@xml/preferences_from_intent" />
</activity>
+ <activity android:name="android.app.cts.ActivityManagerMemoryClassLaunchActivity" />
+
+ <activity android:name="android.app.cts.ActivityManagerMemoryClassTestActivity"
+ android:process=":memoryclass" />
+
</application>
<!--Test for PackageManager, please put this at the very beginning-->
diff --git a/tests/SignatureTest/Android.mk b/tests/SignatureTest/Android.mk
index 18c7cea..4166002 100644
--- a/tests/SignatureTest/Android.mk
+++ b/tests/SignatureTest/Android.mk
@@ -20,7 +20,7 @@
# and when built explicitly put it in the data partition
LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_JAVA_LIBRARIES := android.test.runner
diff --git a/tests/SignatureTest/AndroidManifest.xml b/tests/SignatureTest/AndroidManifest.xml
index 696dc57..762dfae 100644
--- a/tests/SignatureTest/AndroidManifest.xml
+++ b/tests/SignatureTest/AndroidManifest.xml
@@ -30,10 +30,16 @@
</intent-filter>
</activity>
+ <uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name=".InstrumentationRunner"
android:targetPackage="android.tests.sigtest"
android:label="API Signature Test"/>
+ <instrumentation android:name="android.test.InstrumentationTestRunner"
+ android:targetPackage="android.tests.sigtest"
+ android:label="Simple API Signature Test">
+ </instrumentation>
+
</manifest>
diff --git a/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java b/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java
new file mode 100644
index 0000000..c206c9a
--- /dev/null
+++ b/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java
@@ -0,0 +1,324 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.tests.sigtest;
+
+import android.content.res.Resources;
+import android.test.AndroidTestCase;
+import android.tests.sigtest.JDiffClassDescription.JDiffConstructor;
+import android.tests.sigtest.JDiffClassDescription.JDiffField;
+import android.tests.sigtest.JDiffClassDescription.JDiffMethod;
+import android.tests.sigtest.SignatureTestActivity.FAILURE_TYPE;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+
+/**
+ * A simpler version of {@link SignatureTest} that performs the signature check via a JUnit test.
+ * <p/>
+ * Eventually the existing {@link SignatureTest} and {@link SignatureActivity} will be deleted
+ * once the move to a tradefederation based CTS harness is complete.
+ */
+public class SimpleSignatureTest extends AndroidTestCase {
+
+ private static final String TAG_ROOT = "api";
+ private static final String TAG_PACKAGE = "package";
+ private static final String TAG_CLASS = "class";
+ private static final String TAG_INTERFACE = "interface";
+ private static final String TAG_IMPLEMENTS = "implements";
+ private static final String TAG_CONSTRUCTOR = "constructor";
+ private static final String TAG_METHOD = "method";
+ private static final String TAG_PARAM = "parameter";
+ private static final String TAG_EXCEPTION = "exception";
+ private static final String TAG_FIELD = "field";
+
+ private static final String MODIFIER_ABSTRACT = "abstract";
+ private static final String MODIFIER_FINAL = "final";
+ private static final String MODIFIER_NATIVE = "native";
+ private static final String MODIFIER_PRIVATE = "private";
+ private static final String MODIFIER_PROTECTED = "protected";
+ private static final String MODIFIER_PUBLIC = "public";
+ private static final String MODIFIER_STATIC = "static";
+ private static final String MODIFIER_SYNCHRONIZED = "synchronized";
+ private static final String MODIFIER_TRANSIENT = "transient";
+ private static final String MODIFIER_VOLATILE = "volatile";
+ private static final String MODIFIER_VISIBILITY = "visibility";
+
+ private static final String ATTRIBUTE_NAME = "name";
+ private static final String ATTRIBUTE_EXTENDS = "extends";
+ private static final String ATTRIBUTE_TYPE = "type";
+ private static final String ATTRIBUTE_RETURN = "return";
+
+ private static ArrayList<String> mDebugArray = new ArrayList<String>();
+
+ private HashSet<String> mKeyTagSet;
+ private TestResultObserver mResultObserver;
+
+ private class TestResultObserver implements ResultObserver {
+ boolean mDidFail = false;
+ StringBuilder mErrorString = new StringBuilder();
+
+ public void notifyFailure(FAILURE_TYPE type, String name, String errorMessage) {
+ mDidFail = true;
+ mErrorString.append("\n");
+ mErrorString.append(type.toString().toLowerCase());
+ mErrorString.append(":\t");
+ mErrorString.append(name);
+ }
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mKeyTagSet = new HashSet<String>();
+ mKeyTagSet.addAll(Arrays.asList(new String[] {
+ TAG_PACKAGE, TAG_CLASS, TAG_INTERFACE, TAG_IMPLEMENTS, TAG_CONSTRUCTOR,
+ TAG_METHOD, TAG_PARAM, TAG_EXCEPTION, TAG_FIELD }));
+ mResultObserver = new TestResultObserver();
+ }
+
+ /**
+ * Tests that the device's API matches the expected set defined in xml.
+ * <p/>
+ * Will check the entire API, and then report the complete list of failures
+ */
+ public void testSignature() {
+ Resources r = getContext().getResources();
+ Class rClass = R.xml.class;
+ Field[] fs = rClass.getFields();
+ for (Field f : fs) {
+ try {
+ start(r.getXml(f.getInt(rClass)));
+ } catch (Exception e) {
+ mResultObserver.notifyFailure(FAILURE_TYPE.CAUGHT_EXCEPTION, e.getMessage(),
+ e.getMessage());
+ }
+ }
+ if (mResultObserver.mDidFail) {
+ fail(mResultObserver.mErrorString.toString());
+ }
+ }
+
+ private void beginDocument(XmlPullParser parser, String firstElementName)
+ throws XmlPullParserException, IOException {
+ int type;
+ while ((type=parser.next()) != XmlPullParser.START_TAG
+ && type != XmlPullParser.END_DOCUMENT) { }
+
+ if (type != XmlPullParser.START_TAG) {
+ throw new XmlPullParserException("No start tag found");
+ }
+
+ if (!parser.getName().equals(firstElementName)) {
+ throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
+ ", expected " + firstElementName);
+ }
+ }
+
+ /**
+ * Signature test entry point.
+ */
+ private void start(XmlPullParser parser) throws XmlPullParserException, IOException {
+ JDiffClassDescription currentClass = null;
+ String currentPackage = "";
+ JDiffMethod currentMethod = null;
+
+ beginDocument(parser, TAG_ROOT);
+ int type;
+ while (true) {
+ type = XmlPullParser.START_DOCUMENT;
+ while ((type=parser.next()) != XmlPullParser.START_TAG
+ && type != XmlPullParser.END_DOCUMENT
+ && type != XmlPullParser.END_TAG) {
+
+ }
+
+ if (type == XmlPullParser.END_TAG) {
+ if (TAG_CLASS.equals(parser.getName())
+ || TAG_INTERFACE.equals(parser.getName())) {
+ currentClass.checkSignatureCompliance();
+ } else if (TAG_PACKAGE.equals(parser.getName())) {
+ currentPackage = "";
+ }
+ continue;
+ }
+
+ if (type == XmlPullParser.END_DOCUMENT) {
+ break;
+ }
+
+ String tagname = parser.getName();
+ if (!mKeyTagSet.contains(tagname)) {
+ continue;
+ }
+
+ if (type == XmlPullParser.START_TAG && tagname.equals(TAG_PACKAGE)) {
+ currentPackage = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+ } else if (tagname.equals(TAG_CLASS)) {
+ currentClass = loadClassInfo(parser, false, currentPackage);
+ } else if (tagname.equals(TAG_INTERFACE)) {
+ currentClass = loadClassInfo(parser, true, currentPackage);
+ } else if (tagname.equals(TAG_IMPLEMENTS)) {
+ currentClass.addImplInterface(parser.getAttributeValue(null, ATTRIBUTE_NAME));
+ } else if (tagname.equals(TAG_CONSTRUCTOR)) {
+ JDiffConstructor constructor = loadConstructorInfo(parser, currentClass);
+ currentClass.addConstructor(constructor);
+ currentMethod = constructor;
+ } else if (tagname.equals(TAG_METHOD)) {
+ currentMethod = loadMethodInfo(currentClass.getClassName(), parser);
+ currentClass.addMethod(currentMethod);
+ } else if (tagname.equals(TAG_PARAM)) {
+ currentMethod.addParam(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
+ } else if (tagname.equals(TAG_EXCEPTION)) {
+ currentMethod.addException(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
+ } else if (tagname.equals(TAG_FIELD)) {
+ JDiffField field = loadFieldInfo(currentClass.getClassName(), parser);
+ currentClass.addField(field);
+ } else {
+ throw new RuntimeException(
+ "unknow tag exception:" + tagname);
+ }
+ }
+ }
+
+ /**
+ * Load field information from xml to memory.
+ *
+ * @param className of the class being examined which will be shown in error messages
+ * @param parser The XmlPullParser which carries the xml information.
+ * @return the new field
+ */
+ private JDiffField loadFieldInfo(String className, XmlPullParser parser) {
+ String fieldName = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+ String fieldType = parser.getAttributeValue(null, ATTRIBUTE_TYPE);
+ int modifier = jdiffModifierToReflectionFormat(className, parser);
+ return new JDiffField(fieldName, fieldType, modifier);
+ }
+
+ /**
+ * Load method information from xml to memory.
+ *
+ * @param className of the class being examined which will be shown in error messages
+ * @param parser The XmlPullParser which carries the xml information.
+ * @return the newly loaded method.
+ */
+ private JDiffMethod loadMethodInfo(String className, XmlPullParser parser) {
+ String methodName = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+ String returnType = parser.getAttributeValue(null, ATTRIBUTE_RETURN);
+ int modifier = jdiffModifierToReflectionFormat(className, parser);
+ return new JDiffMethod(methodName, modifier, returnType);
+ }
+
+ /**
+ * Load constructor information from xml to memory.
+ *
+ * @param parser The XmlPullParser which carries the xml information.
+ * @param currentClass the current class being loaded.
+ * @return the new constructor
+ */
+ private JDiffConstructor loadConstructorInfo(XmlPullParser parser,
+ JDiffClassDescription currentClass) {
+ String name = currentClass.getClassName();
+ int modifier = jdiffModifierToReflectionFormat(name, parser);
+ return new JDiffConstructor(name, modifier);
+ }
+
+ /**
+ * Load class or interface information to memory.
+ *
+ * @param parser The XmlPullParser which carries the xml information.
+ * @param isInterface true if the current class is an interface, otherwise is false.
+ * @param pkg the name of the java package this class can be found in.
+ * @return the new class description.
+ */
+ private JDiffClassDescription loadClassInfo(XmlPullParser parser,
+ boolean isInterface,
+ String pkg) {
+ String className = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+ JDiffClassDescription currentClass = new JDiffClassDescription(pkg,
+ className,
+ mResultObserver);
+ currentClass.setModifier(jdiffModifierToReflectionFormat(className, parser));
+ currentClass.setType(isInterface ? JDiffClassDescription.JDiffType.INTERFACE :
+ JDiffClassDescription.JDiffType.CLASS);
+ currentClass.setExtendsClass(parser.getAttributeValue(null, ATTRIBUTE_EXTENDS));
+ return currentClass;
+ }
+
+ /**
+ * Convert string modifier to int modifier.
+ *
+ * @param name of the class/method/field being examined which will be shown in error messages
+ * @param key modifier name
+ * @param value modifier value
+ * @return converted modifier value
+ */
+ private static int modifierDescriptionToReflectedType(String name, String key, String value) {
+ if (key.equals(MODIFIER_ABSTRACT)) {
+ return value.equals("true") ? Modifier.ABSTRACT : 0;
+ } else if (key.equals(MODIFIER_FINAL)) {
+ return value.equals("true") ? Modifier.FINAL : 0;
+ } else if (key.equals(MODIFIER_NATIVE)) {
+ return value.equals("true") ? Modifier.NATIVE : 0;
+ } else if (key.equals(MODIFIER_STATIC)) {
+ return value.equals("true") ? Modifier.STATIC : 0;
+ } else if (key.equals(MODIFIER_SYNCHRONIZED)) {
+ return value.equals("true") ? Modifier.SYNCHRONIZED : 0;
+ } else if (key.equals(MODIFIER_TRANSIENT)) {
+ return value.equals("true") ? Modifier.TRANSIENT : 0;
+ } else if (key.equals(MODIFIER_VOLATILE)) {
+ return value.equals("true") ? Modifier.VOLATILE : 0;
+ } else if (key.equals(MODIFIER_VISIBILITY)) {
+ if (value.equals(MODIFIER_PRIVATE)) {
+ throw new RuntimeException("Private visibility found in API spec: " + name);
+ } else if (value.equals(MODIFIER_PROTECTED)) {
+ return Modifier.PROTECTED;
+ } else if (value.equals(MODIFIER_PUBLIC)) {
+ return Modifier.PUBLIC;
+ } else if ("".equals(value)) {
+ // If the visibility is "", it means it has no modifier.
+ // which is package private. We should return 0 for this modifier.
+ return 0;
+ } else {
+ throw new RuntimeException("Unknown modifier found in API spec: " + value);
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Transfer string modifier to int one.
+ *
+ * @param name of the class/method/field being examined which will be shown in error messages
+ * @param parser XML resource parser
+ * @return converted modifier
+ */
+ private static int jdiffModifierToReflectionFormat(String name, XmlPullParser parser){
+ int modifier = 0;
+ for (int i = 0;i < parser.getAttributeCount();i++) {
+ modifier |= modifierDescriptionToReflectedType(name, parser.getAttributeName(i),
+ parser.getAttributeValue(i));
+ }
+ return modifier;
+ }
+}
diff --git a/tests/accessibilityservice/res/values/strings.xml b/tests/accessibilityservice/res/values/strings.xml
index 4c717c1..3730f85 100644
--- a/tests/accessibilityservice/res/values/strings.xml
+++ b/tests/accessibilityservice/res/values/strings.xml
@@ -20,31 +20,4 @@
<!-- String title of the mock accessibility service -->
<string name="title_delegating_accessibility_service">Delegating Accessibility Service</string>
- <!-- String title of the accessibility end-to-end test activity -->
- <string name="accessibility_end_to_end_test_activity">End-to-end test</string>
-
- <!-- String value of used as text input -->
- <string name="text_input_blah">Blah</string>
-
- <!-- String value of used as text input -->
- <string name="text_input_blah_blah">Blah blah</string>
-
- <!-- String title of the button -->
- <string name="button_title">Click me</string>
-
- <!-- String value of the first list item -->
- <string name="first_list_item">First list item</string>
-
- <!-- String value of the second list item -->
- <string name="second_list_item">Second list item</string>
-
- <!-- String alert title -->
- <string name="alert_title">Alert title</string>
-
- <!-- String alert message -->
- <string name="alert_message">Alert message</string>
-
- <!-- String notification message -->
- <string name="notification_message">Notification message</string>
-
</resources>
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
index 683ec9e..de71966 100644
--- a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
@@ -31,6 +31,8 @@
<application>
<receiver android:name="GrantUriPermission" android:exported="true">
</receiver>
+ <receiver android:name="SetInstallerPackage" android:exported="true">
+ </receiver>
<!-- Need a way for another app to try to access the permission. So create a content
provider which is enforced by the permission -->
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java
index 8c14575..31a3f47 100644
--- a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package com.android.cts.permissiondeclareapp;
import android.content.BroadcastReceiver;
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java
new file mode 100644
index 0000000..ea06d8c
--- /dev/null
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.permissiondeclareapp;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+public class SetInstallerPackage extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String targetPackage = intent.getStringExtra("target");
+ String installerPackage = intent.getStringExtra("installer");
+ try {
+ context.getPackageManager().setInstallerPackageName(targetPackage, installerPackage);
+ if (isOrderedBroadcast()) {
+ setResultCode(101);
+ }
+ } catch (SecurityException e) {
+ Log.i("SetInstallerPackage", "Security exception", e);
+ if (isOrderedBroadcast()) {
+ setResultCode(100);
+ }
+ }
+ }
+}
diff --git a/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java b/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java
new file mode 100644
index 0000000..989e24b
--- /dev/null
+++ b/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.usespermissiondiffcertapp;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.os.SystemClock;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+/**
+ * Tests that one application can and can not modify the installer package
+ * of another application is appropriate.
+ *
+ * Accesses app cts/tests/appsecurity-tests/test-apps/PermissionDeclareApp/...
+ */
+public class ModifyInstallerPackageTest extends AndroidTestCase {
+ static final ComponentName SET_INSTALLER_PACKAGE_COMP
+ = new ComponentName("com.android.cts.permissiondeclareapp",
+ "com.android.cts.permissiondeclareapp.SetInstallerPackage");
+ static final String OTHER_PACKAGE = "com.android.cts.permissiondeclareapp";
+ static final String MY_PACKAGE = "com.android.cts.usespermissiondiffcertapp";
+
+ static class SetInstallerPackageReceiver extends BroadcastReceiver {
+ boolean mHaveResult = false;
+ boolean mGoodResult = false;
+ boolean mSucceeded = false;
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ synchronized (this) {
+ mHaveResult = true;
+ switch (getResultCode()) {
+ case 100:
+ mGoodResult = true;
+ mSucceeded = false;
+ break;
+ case 101:
+ mGoodResult = true;
+ mSucceeded = true;
+ break;
+ default:
+ mGoodResult = false;
+ break;
+ }
+ notifyAll();
+ }
+ }
+
+ void assertSuccess(String failureMessage) {
+ synchronized (this) {
+ final long startTime = SystemClock.uptimeMillis();
+ while (!mHaveResult) {
+ try {
+ wait(5000);
+ } catch (InterruptedException e) {
+ }
+ if (SystemClock.uptimeMillis() >= (startTime+5000)) {
+ throw new RuntimeException("Timeout");
+ }
+ }
+ if (!mGoodResult) {
+ fail("Broadcast receiver did not return good result");
+ }
+ if (!mSucceeded) {
+ fail(failureMessage);
+ }
+ }
+ }
+
+ void assertFailure(String failureMessage) {
+ synchronized (this) {
+ final long startTime = SystemClock.uptimeMillis();
+ while (!mHaveResult) {
+ try {
+ wait(5000);
+ } catch (InterruptedException e) {
+ }
+ if (SystemClock.uptimeMillis() >= (startTime+5000)) {
+ throw new RuntimeException("Timeout");
+ }
+ }
+ if (!mGoodResult) {
+ fail("Broadcast receiver did not return good result");
+ }
+ if (mSucceeded) {
+ fail(failureMessage);
+ }
+ }
+ }
+ }
+
+ PackageManager getPackageManager() {
+ return getContext().getPackageManager();
+ }
+
+ /**
+ * Test that we can set the installer package name.
+ */
+ public void testSetInstallPackage() {
+ // Pre-condition.
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+ getPackageManager().setInstallerPackageName(OTHER_PACKAGE, MY_PACKAGE);
+ assertEquals(MY_PACKAGE, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+ // Clean up.
+ getPackageManager().setInstallerPackageName(OTHER_PACKAGE, null);
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+ }
+
+ /**
+ * Test that we fail if trying to set an installer package with an unknown
+ * target package name.
+ */
+ public void testSetInstallPackageBadTarget() {
+ try {
+ getPackageManager().setInstallerPackageName("thisdoesnotexistihope!", MY_PACKAGE);
+ fail("setInstallerPackageName did not throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // That's what we want!
+ }
+ }
+
+ /**
+ * Test that we fail if trying to set an installer package with an unknown
+ * installer package name.
+ */
+ public void testSetInstallPackageBadInstaller() {
+ try {
+ getPackageManager().setInstallerPackageName(OTHER_PACKAGE, "thisdoesnotexistihope!");
+ fail("setInstallerPackageName did not throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // That's what we want!
+ }
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+ }
+
+ /**
+ * Test that we fail if trying to set an installer package that is not
+ * signed with our cert.
+ */
+ public void testSetInstallPackageWrongCertificate() {
+ // Pre-condition.
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+ try {
+ getPackageManager().setInstallerPackageName(OTHER_PACKAGE, OTHER_PACKAGE);
+ fail("setInstallerPackageName did not throw SecurityException");
+ } catch (SecurityException e) {
+ // That's what we want!
+ }
+
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+ }
+
+ /**
+ * Test that we fail if trying to set an installer package that is not
+ * signed with the same cert as the currently set installer.
+ */
+ public void testSetInstallPackageConflictingInstaller() {
+ // Pre-condition.
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+ // Have the other package set the installer, under its cert.
+ Intent intent = new Intent();
+ intent.setComponent(SET_INSTALLER_PACKAGE_COMP);
+ intent.putExtra("target", OTHER_PACKAGE);
+ intent.putExtra("installer", OTHER_PACKAGE);
+ SetInstallerPackageReceiver receiver = new SetInstallerPackageReceiver();
+ getContext().sendOrderedBroadcast(intent, null, receiver, null, 0, null, null);
+ receiver.assertSuccess("Failure initializing with other installer");
+
+ assertEquals(OTHER_PACKAGE, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+ try {
+ getPackageManager().setInstallerPackageName(OTHER_PACKAGE, MY_PACKAGE);
+ fail("setInstallerPackageName did not throw SecurityException");
+ } catch (SecurityException e) {
+ // That's what we want!
+ }
+
+ assertEquals(OTHER_PACKAGE, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+ // Now clear the installer
+ intent.putExtra("target", OTHER_PACKAGE);
+ intent.putExtra("installer", (String)null);
+ receiver = new SetInstallerPackageReceiver();
+ getContext().sendOrderedBroadcast(intent, null, receiver, null, 0, null, null);
+ receiver.assertSuccess("Failure clearing other installer");
+
+ assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+ }
+}
diff --git a/tests/assets/webkit/jsform.html b/tests/assets/webkit/jsform.html
index ddf01f8..1781194 100644
--- a/tests/assets/webkit/jsform.html
+++ b/tests/assets/webkit/jsform.html
@@ -24,7 +24,7 @@
}
}
</script>
- <body onload="fireSubmit()">
+ <body onload="window.setTimeout(function() { fireSubmit(); }, 0);">
javascript form test
<form id="formId" action="test.html#result" method="post">
<input type="hidden" name="foo" value="bar" />
diff --git a/tests/core/luni-io/Android.mk b/tests/core/luni-io/Android.mk
index ed39e03..6669c6a 100644
--- a/tests/core/luni-io/Android.mk
+++ b/tests/core/luni-io/Android.mk
@@ -24,7 +24,7 @@
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/java/io) \
- $(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/io) \
+ $(call all-java-files-under,../../../../libcore/luni/src/test/java/libcore/java/io) \
$(call all-java-files-under,../../../../libcore/support/src/test/java/) \
$(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/pkg1) \
$(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/pkg2) \
diff --git a/tests/core/luni-lang/Android.mk b/tests/core/luni-lang/Android.mk
index a31b881..c3528ec 100644
--- a/tests/core/luni-lang/Android.mk
+++ b/tests/core/luni-lang/Android.mk
@@ -23,7 +23,7 @@
##########################################################
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang) \
+LOCAL_SRC_FILES := \
$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/java/lang) \
$(call all-java-files-under,../../../../libcore/support/src/test/java/) \
../../../../libcore/luni/src/test/java/tests/luni/AllTestsLang.java
diff --git a/tests/core/xml/Android.mk b/tests/core/xml/Android.mk
index 4f8af07..0f643a0 100644
--- a/tests/core/xml/Android.mk
+++ b/tests/core/xml/Android.mk
@@ -26,7 +26,6 @@
LOCAL_SRC_FILES := $(call all-java-files-under,../../../../libcore/xml/src/test/java) \
$(call all-java-files-under,../../../../libcore/dom/src/test) \
$(call all-java-files-under,../../../../libcore/junit/src/test/java/junit) \
- $(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/xml) \
$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/javax/xml/parsers) \
$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/org/xml/sax) \
$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/org/xml/sax/support) \
diff --git a/tests/expectations/knownfailures-3.0_r1.txt b/tests/expectations/knownfailures-3.0_r1.txt
new file mode 100644
index 0000000..a13d081
--- /dev/null
+++ b/tests/expectations/knownfailures-3.0_r1.txt
@@ -0,0 +1,38 @@
+[
+/* Framework problems. */
+{
+ name: "android.telephony.cts.PhoneNumberFormattingTextWatcherTest#testPhoneNumberFormattingTextWatcher",
+ bug: 3198578
+},
+{
+ name: "android.webkit.cts.WebViewTest#testRequestFocusNodeHref",
+ bug: 3241968
+},
+
+{
+ description: "Need investigation.",
+ names: [
+ "android.provider.cts.Contacts_PeopleTest#testAddToGroup",
+ "android.provider.cts.MediaStore_Audio_Playlists_MembersTest",
+ "android.webkit.cts.WebViewTest#testRequestImageRef",
+ "tests.api.java.util.CalendarTest#test_getInstance"
+ ]
+},
+
+{
+ description: "Test should be made independent from theme.",
+ name: "android.content.cts.ContextWrapperTest#testAccessTheme"
+},
+
+{
+ description: "Flakey",
+ names: [
+ "android.hardware.cts.CameraTest#testSetPreviewDisplay",
+ "android.view.cts.GestureDetectorTest#testOnTouchEvent",
+ "android.view.cts.ViewTest#testWindowVisibilityChanged",
+ "android.webkit.cts.WebChromeClientTest#testOnReceivedIcon",
+ "android.widget.cts.AbsListViewTest#testGetContextMenuInfo"
+ ]
+}
+
+]
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
deleted file mode 100644
index 6292d7a..0000000
--- a/tests/expectations/knownfailures.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-[
-/* These tests consistently fail on GRH78. */
-{ name: "android.location.cts.GeocoderTest#testGetFromLocation" },
-{ name: "android.location.cts.GeocoderTest#testGetFromLocationName" },
-{ name: "android.webkit.cts.WebSettingsTest#testSetAppCacheEnabled" },
-{ name: "android.net.cts.SSLCertificateSocketFactoryTest" },
-
-{
- description: "Flaky tests that need to be rewritten or deleted.",
- names: [
- "android.media.cts.MediaRecorderTest#testSetCamera",
- "android.webkit.cts.CacheManagerTest#testCacheFile",
- "android.widget.cts.AutoCompleteTextViewTest#testOnFilterComplete"
- ]
-},
-
-{
- description: "Broken test that is fixed in a future release.",
- name: "android.provider.cts.MediaStore_Audio_Playlists_MembersTest"
-},
-
-{
- description: "These tests pass when executed individually but fail when running CTS as a whole on GRH78.",
- bug: 3184701,
- names: [
- "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyConnection",
- "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyAuthConnection",
- "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testConsequentProxyConnection",
- "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyAuthConnection_doOutput",
- "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyAuthConnectionFailed",
- "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyConnection_Not_Found_Response"
- ]
-}
-
-]
diff --git a/tests/res/layout/checkedtextview_layout.xml b/tests/res/layout/checkedtextview_layout.xml
index f8085a3..d5b9c1f 100644
--- a/tests/res/layout/checkedtextview_layout.xml
+++ b/tests/res/layout/checkedtextview_layout.xml
@@ -16,7 +16,7 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
- android:layout_height="wrap_content">
+ android:layout_height="match_parent">
<ListView android:id="@+id/checkedtextview_listview"
android:orientation="vertical"
diff --git a/tests/res/layout/dialog_stub_layout.xml b/tests/res/layout/dialog_stub_layout.xml
index 11b502f..b0a8861 100644
--- a/tests/res/layout/dialog_stub_layout.xml
+++ b/tests/res/layout/dialog_stub_layout.xml
@@ -14,65 +14,8 @@
limitations under the License.
-->
-<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen"
- android:layout_width="match_parent" android:layout_height="match_parent"
- android:orientation="vertical">
- <LinearLayout
- android:layout_width="match_parent" android:layout_height="match_parent"
- android:orientation="vertical">
- <Button android:id="@+id/dialog_test_button_1"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button1"/>
- <Button android:id="@+id/dialog_test_button_2"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button2"/>
- <Button android:id="@+id/dialog_test_button_3"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button3"/>
- <Button android:id="@+id/dialog_test_button_4"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button4"/>
- <Button android:id="@+id/dialog_test_button_5"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button5"/>
- <Button android:id="@+id/dialog_test_button_6"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button6"/>
- <Button android:id="@+id/dialog_test_button_7"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button7"/>
- <Button android:id="@+id/dialog_test_button_8"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button8"/>
- <Button android:id="@+id/dialog_test_button_9"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button9"/>
- <Button android:id="@+id/dialog_test_button_10"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button10"/>
- <Button android:id="@+id/dialog_test_button_11"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button11"/>
- <Button android:id="@+id/dialog_test_button_12"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button12"/>
- <Button android:id="@+id/dialog_test_button_13"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button13"/>
- <Button android:id="@+id/dialog_test_button_14"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button14"/>
- <Button android:id="@+id/dialog_test_button_15"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button15"/>
- <Button android:id="@+id/dialog_test_button_16"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button16"/>
- <Button android:id="@+id/dialog_test_button_17"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button17"/>
- <Button android:id="@+id/dialog_test_button_18"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:text="@string/dialog_stub_dialog_test_button18"/>
- </LinearLayout>
-</ScrollView>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ >
+</LinearLayout>
diff --git a/tests/res/values/strings.xml b/tests/res/values/strings.xml
index a779b47..8fcd75a 100644
--- a/tests/res/values/strings.xml
+++ b/tests/res/values/strings.xml
@@ -40,24 +40,6 @@
<string name="text">DialogTest</string>
<string name="text_country">Country</string>
<string name="text_name">Name</string>
- <string name="dialog_stub_dialog_test_button1">Test Dialog without theme</string>
- <string name="dialog_stub_dialog_test_button2">Test Dialog with theme</string>
- <string name="dialog_stub_dialog_test_button3">Test AlertDialog</string>
- <string name="dialog_stub_dialog_test_button4">Test AlertDialog with theme</string>
- <string name="dialog_stub_dialog_test_button5">Test DatePickerDialog</string>
- <string name="dialog_stub_dialog_test_button6">Test DatePickerDialog with theme</string>
- <string name="dialog_stub_dialog_test_button7">Test TimePickerDialog</string>
- <string name="dialog_stub_dialog_test_button8">Test TimePickerDialog with theme</string>
- <string name="dialog_stub_dialog_test_button9">Test onStart() and onStop()</string>
- <string name="dialog_stub_dialog_test_button10">Test AlertDialog deprecated</string>
- <string name="dialog_stub_dialog_test_button11">Test AlertDialog callback</string>
- <string name="dialog_stub_dialog_test_button12">Test AlertDialog setview </string>
- <string name="dialog_stub_dialog_test_button13">Test AlertDialog deprecated with Message</string>
- <string name="dialog_stub_dialog_test_button14">Test AlertDialog with theme</string>
- <string name="dialog_stub_dialog_test_button15">Test AlertDialog cancelable</string>
- <string name="dialog_stub_dialog_test_button16">Test AlertDialog can\'n cancelable</string>
- <string name="dialog_stub_dialog_test_button17">Test Dialog cancelable</string>
- <string name="dialog_stub_dialog_test_button18">Test Dialog not cancelable</string>
<string name="hello_world">Hello, World!</string>
<string name="hello_android">Hello, Android!</string>
<string name="alert_dialog_username">Name:</string>
diff --git a/tests/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java b/tests/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java
new file mode 100644
index 0000000..f1f95b8
--- /dev/null
+++ b/tests/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.app.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * {@link Activity} that just launches {@link ActivityManagerMemoryClassTestActivity} and
+ * returns the result of that activity.
+ */
+public class ActivityManagerMemoryClassLaunchActivity extends Activity {
+
+ public static final String MEMORY_CLASS_EXTRA = "activityMemoryClass";
+
+ private static final int TEST_ACTIVITY_REQUEST_CODE = 1337;
+
+ private final CountDownLatch mLatch = new CountDownLatch(1);
+
+ private int mChildResult = RESULT_CANCELED;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ // Start the activity that runs in a separate process to do the actual testing,
+ // since the test itself cannot start an activity in a separate process. A separate
+ // process is used to avoid including the overhead of the test instrumentation process.
+
+ Intent intent = getIntent();
+ int memoryClass = intent.getIntExtra(MEMORY_CLASS_EXTRA, -1);
+
+ Intent testIntent = new Intent(this, ActivityManagerMemoryClassTestActivity.class);
+ testIntent.putExtra(MEMORY_CLASS_EXTRA, memoryClass);
+ startActivityForResult(testIntent, TEST_ACTIVITY_REQUEST_CODE);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (requestCode == 1337) {
+ synchronized (this) {
+ mChildResult = resultCode;
+ }
+ } else {
+ throw new IllegalStateException("Request code: " + requestCode);
+ }
+ }
+
+ public int getResult() throws InterruptedException {
+ mLatch.await(5, TimeUnit.SECONDS);
+ synchronized (this) {
+ return mChildResult;
+ }
+ }
+}
diff --git a/tests/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java b/tests/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java
new file mode 100644
index 0000000..e717b03
--- /dev/null
+++ b/tests/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.app.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.util.Log;
+
+/**
+ * {@link Activity} that allocates arrays of 256k until reaching 75% of the specified memory class.
+ */
+public class ActivityManagerMemoryClassTestActivity extends Activity {
+
+ private static final String TAG = "ActivityManagerMemoryClassTest";
+
+ private static final double FREE_MEMORY_PERCENTAGE = 0.75;
+
+ private static final int ARRAY_BYTES_SIZE = 256 * 1024;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ Intent intent = getIntent();
+ int memoryClass =
+ intent.getIntExtra(ActivityManagerMemoryClassLaunchActivity.MEMORY_CLASS_EXTRA, -1);
+ new AllocateMemoryTask(memoryClass).execute();
+ }
+
+ private class AllocateMemoryTask extends AsyncTask<Void, Void, Void> {
+
+ private final int mMemoryClass;
+
+ AllocateMemoryTask(int memoryClass) {
+ this.mMemoryClass = memoryClass;
+ }
+
+ @Override
+ protected Void doInBackground(Void... params) {
+ int targetMbs = (int) (mMemoryClass * FREE_MEMORY_PERCENTAGE);
+ int numArrays = targetMbs * 1024 * 1024 / ARRAY_BYTES_SIZE;
+ Log.i(TAG, "Memory class: " + mMemoryClass + "mb Target memory: "
+ + targetMbs + "mb Number of arrays: " + numArrays);
+
+ byte[][] arrays = new byte[numArrays][];
+ for (int i = 0; i < arrays.length; i++) {
+ Log.i(TAG, "Allocating array " + i + " of " + arrays.length
+ + " (" + (i * ARRAY_BYTES_SIZE / 1024 / 1024) + "mb)");
+ arrays[i] = new byte[ARRAY_BYTES_SIZE];
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Void result) {
+ super.onPostExecute(result);
+ setResult(RESULT_OK);
+ finish();
+ }
+ }
+}
diff --git a/tests/src/android/app/cts/DialogStubActivity.java b/tests/src/android/app/cts/DialogStubActivity.java
index f715b51..817e716 100644
--- a/tests/src/android/app/cts/DialogStubActivity.java
+++ b/tests/src/android/app/cts/DialogStubActivity.java
@@ -16,6 +16,8 @@
package android.app.cts;
+import com.android.cts.stub.R;
+
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
@@ -25,21 +27,19 @@
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
+import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
+import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
-import com.android.cts.stub.R;
-
/*
* Stub class for Dialog, AlertDialog, DatePickerDialog, TimePickerDialog etc.
*/
@@ -289,49 +289,27 @@
return (String) mDialog.getWindow().getAttributes().getTitle();
}
+ private static final String TEST_DIALOG_NUMBER_EXTRA = "testDialogNumber";
+
+ public static <T extends Activity> T startDialogActivity(
+ ActivityInstrumentationTestCase2<T> testCase, int dialogNumber) {
+ Intent intent = new Intent(Intent.ACTION_MAIN);
+ intent.putExtra(TEST_DIALOG_NUMBER_EXTRA, dialogNumber);
+ testCase.setActivityIntent(intent);
+ return testCase.getActivity();
+ }
+
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_stub_layout);
- findViewById(R.id.dialog_test_button_1).setOnClickListener(
- new MockClickListener(TEST_DIALOG_WITHOUT_THEME));
- findViewById(R.id.dialog_test_button_2).setOnClickListener(
- new MockClickListener(TEST_DIALOG_WITH_THEME));
- findViewById(R.id.dialog_test_button_3).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG));
- findViewById(R.id.dialog_test_button_4).setOnClickListener(
- new MockClickListener(TEST_CUSTOM_ALERTDIALOG));
- final Button dialogTestButton5 = (Button) findViewById(R.id.dialog_test_button_5);
- dialogTestButton5.setOnClickListener(new MockClickListener(TEST_DATEPICKERDIALOG));
- findViewById(R.id.dialog_test_button_6).setOnClickListener(
- new MockClickListener(TEST_DATEPICKERDIALOG_WITH_THEME));
- findViewById(R.id.dialog_test_button_7).setOnClickListener(
- new MockClickListener(TEST_TIMEPICKERDIALOG));
- findViewById(R.id.dialog_test_button_8).setOnClickListener(
- new MockClickListener(TEST_TIMEPICKERDIALOG_WITH_THEME));
- findViewById(R.id.dialog_test_button_9).setOnClickListener(
- new MockClickListener(TEST_ONSTART_AND_ONSTOP));
- findViewById(R.id.dialog_test_button_10).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG_DEPRECATED));
- findViewById(R.id.dialog_test_button_11).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG_CALLBACK));
- findViewById(R.id.dialog_test_button_12).setOnClickListener(
- new MockClickListener(TEST_CUSTOM_ALERTDIALOG_VIEW));
- findViewById(R.id.dialog_test_button_13).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE));
-
- findViewById(R.id.dialog_test_button_14).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG_THEME));
- findViewById(R.id.dialog_test_button_15).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG_CANCELABLE));
- findViewById(R.id.dialog_test_button_16).setOnClickListener(
- new MockClickListener(TEST_ALERTDIALOG_NOT_CANCELABLE));
- findViewById(R.id.dialog_test_button_17).setOnClickListener(
- new MockClickListener(TEST_PROTECTED_CANCELABLE));
- findViewById(R.id.dialog_test_button_18).setOnClickListener(
- new MockClickListener(TEST_PROTECTED_NOT_CANCELABLE));
+ Intent intent = getIntent();
+ int dialogNum = intent.getIntExtra(TEST_DIALOG_NUMBER_EXTRA, -1);
+ if (dialogNum != -1) {
+ showDialog(dialogNum);
+ }
}
public void setUpTitle(final String title) {
@@ -383,18 +361,6 @@
}
- private class MockClickListener implements OnClickListener {
- private final int mId;
-
- public MockClickListener(final int id) {
- mId = id;
- }
-
- public void onClick(View v) {
- showDialog(mId);
- }
- }
-
class MockOnClickListener implements DialogInterface.OnClickListener {
private final int mId;
diff --git a/tests/src/android/app/cts/LaunchpadActivity.java b/tests/src/android/app/cts/LaunchpadActivity.java
index fa18ec5..7191e03 100644
--- a/tests/src/android/app/cts/LaunchpadActivity.java
+++ b/tests/src/android/app/cts/LaunchpadActivity.java
@@ -184,20 +184,20 @@
});
} else if (LIFECYCLE_SCREEN.equals(action)) {
addPossibleLifecycle(LIFECYCLE_SCREEN + "_RESTART", new String[] {
- ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_FREEZE, ON_PAUSE,
+ ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_PAUSE,
ON_RESTART, ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
});
addPossibleLifecycle(LIFECYCLE_SCREEN + "_RESUME", new String[] {
- ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_FREEZE, ON_PAUSE,
+ ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_PAUSE,
ON_RESUME, DO_FINISH, ON_PAUSE
});
} else if (LIFECYCLE_DIALOG.equals(action)) {
addPossibleLifecycle(LIFECYCLE_DIALOG + "_RESTART", new String[] {
- ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_FREEZE, ON_PAUSE,
+ ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_PAUSE,
ON_RESTART, ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
});
addPossibleLifecycle(LIFECYCLE_DIALOG + "_RESUME", new String[] {
- ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_FREEZE, ON_PAUSE,
+ ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_PAUSE,
ON_RESUME, DO_FINISH, ON_PAUSE
});
}
@@ -399,7 +399,6 @@
@Override
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
- checkLifecycle(ON_FREEZE);
if (mBadParcelable) {
icicle.putParcelable("baddy", new MyBadParcelable());
}
@@ -451,13 +450,15 @@
do {
if (mExpectedLifecycle[mNextLifecycle].equals(where)) {
+ Log.w(TAG, "Matched: " + where);
break;
+ } else {
+ Log.w(TAG, "Expected " + mExpectedLifecycle[mNextLifecycle] + " but got " + where);
}
} while (switchToNextPossibleLifecycle());
if (mExpectedLifecycle == null) {
finishBad("Activity lifecycle for " + action + " incorrect: received " + where
- + " but expected " + mExpectedLifecycle[mNextLifecycle]
+ " at " + mNextLifecycle);
return;
}
diff --git a/tests/src/android/app/cts/LocalActivityManagerTestHelper.java b/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
index 0d21a9c..76af648 100644
--- a/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
+++ b/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
@@ -28,7 +28,7 @@
public class LocalActivityManagerTestHelper extends ActivityGroup {
public static final String ACTION_DISPATCH_RESUME = "dispatchResume";
- public static final String ACTION_START_ACTIIVTY = "startActivity";
+ public static final String ACTION_START_ACTIVITY = "startActivity";
public static final String ACTION_DISPATCH_CREATE = "dispatchCreate";
public static final String ACTION_DISPATCH_STOP = "dispatchStop";
public static final String ACTION_DISPATCH_PAUSE_TRUE = "dispatchPauseTrue";
@@ -66,7 +66,7 @@
super.onResume();
if (mCurrentAction.equals(ACTION_DISPATCH_RESUME)) {
testDispatchResume();
- } else if (mCurrentAction.equals(ACTION_START_ACTIIVTY)) {
+ } else if (mCurrentAction.equals(ACTION_START_ACTIVITY)) {
testStartActivity();
} else if (mCurrentAction.equals(ACTION_DISPATCH_CREATE)) {
testDispatchCreate();
@@ -109,9 +109,7 @@
fail();
return;
}
-
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testDispatchDestroy() {
@@ -146,9 +144,7 @@
fail();
return;
}
-
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testSaveInstanceState() {
@@ -175,9 +171,7 @@
fail();
return;
}
-
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testDispatchPauseFalse() {
@@ -191,9 +185,7 @@
fail();
return;
}
-
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testDispatchPauseTrue() {
@@ -207,9 +199,7 @@
fail();
return;
}
-
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testDispatchStop() {
@@ -229,9 +219,7 @@
fail();
return;
}
-
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testDispatchCreate() {
@@ -269,8 +257,7 @@
fail();
return;
}
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
+ pass();
}
private void testStartActivity() {
@@ -324,13 +311,7 @@
return;
} catch (NullPointerException e) {
}
- sResult.setResult(CTSResult.RESULT_OK);
- finish();
- }
-
- private void fail() {
- sResult.setResult(CTSResult.RESULT_FAIL);
- finish();
+ pass();
}
private void testDispatchResume() {
@@ -341,11 +322,19 @@
LocalActivityManagerStubActivity.sIsOnResumeCalled = false;
mLocalActivityManager.dispatchResume();
if (LocalActivityManagerStubActivity.sIsOnResumeCalled) {
- sResult.setResult(CTSResult.RESULT_OK);
+ pass();
} else {
- sResult.setResult(CTSResult.RESULT_FAIL);
+ fail();
}
+ }
+
+ private void fail() {
+ sResult.setResult(CTSResult.RESULT_FAIL);
finish();
}
+ private void pass() {
+ sResult.setResult(CTSResult.RESULT_OK);
+ finish();
+ }
}
diff --git a/tests/src/android/content/cts/MockSyncAdapter.java b/tests/src/android/content/cts/MockSyncAdapter.java
index 32b3a8d..df24749 100644
--- a/tests/src/android/content/cts/MockSyncAdapter.java
+++ b/tests/src/android/content/cts/MockSyncAdapter.java
@@ -23,13 +23,14 @@
import android.os.Bundle;
import android.os.RemoteException;
+import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class MockSyncAdapter extends ISyncAdapter.Stub {
private static MockSyncAdapter sSyncAdapter = null;
- private Account mAccount;
+ private ArrayList<Account> mAccounts = new ArrayList<Account>();
private String mAuthority;
private Bundle mExtras;
private boolean mInitialized;
@@ -37,8 +38,8 @@
private boolean mCancelSync;
private CountDownLatch mLatch;
- public Account getAccount() {
- return mAccount;
+ public ArrayList<Account> getAccounts() {
+ return mAccounts;
}
public String getAuthority() {
@@ -62,7 +63,7 @@
}
public void clearData() {
- mAccount = null;
+ mAccounts.clear();
mAuthority = null;
mExtras = null;
mInitialized = false;
@@ -78,7 +79,7 @@
public void startSync(ISyncContext syncContext, String authority, Account account,
Bundle extras) throws RemoteException {
- mAccount = account;
+ mAccounts.add(account);
mAuthority = authority;
mExtras = extras;
@@ -98,7 +99,7 @@
}
public void cancelSync(ISyncContext syncContext) throws RemoteException {
- mAccount = null;
+ mAccounts.clear();
mAuthority = null;
mExtras = null;
@@ -114,7 +115,7 @@
public void initialize(android.accounts.Account account, java.lang.String authority)
throws android.os.RemoteException {
- mAccount = account;
+ mAccounts.add(account);
mAuthority = authority;
mInitialized = true;
diff --git a/tests/src/android/provider/cts/FileCopyHelper.java b/tests/src/android/provider/cts/FileCopyHelper.java
index a9c53e5..4ee93ac 100644
--- a/tests/src/android/provider/cts/FileCopyHelper.java
+++ b/tests/src/android/provider/cts/FileCopyHelper.java
@@ -18,6 +18,8 @@
import android.content.Context;
+import java.io.File;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -95,4 +97,18 @@
mContext.deleteFile(path);
}
}
+
+ public static void createFile(File file, int numBytes) throws IOException {
+ File parentFile = file.getParentFile();
+ if (parentFile != null) {
+ parentFile.mkdirs();
+ }
+ byte[] buffer = new byte[numBytes];
+ FileOutputStream output = new FileOutputStream(file);
+ try {
+ output.write(buffer);
+ } finally {
+ output.close();
+ }
+ }
}
diff --git a/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java b/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java
index 3cc3bbe..e6c9809 100644
--- a/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java
+++ b/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java
@@ -112,7 +112,7 @@
public static final String EXTERNAL_DATA = Environment.getExternalStorageDirectory() +
"/" + FILE_NAME;
- public static final long DATE_MODIFIED = System.currentTimeMillis();
+ public static final long DATE_MODIFIED = System.currentTimeMillis() / 1000;
public static final String GENRE = "POP";
@Override
diff --git a/tests/src/android/provider/cts/TestSearchRecentSuggestionsProvider.java b/tests/src/android/provider/cts/TestSearchRecentSuggestionsProvider.java
new file mode 100644
index 0000000..d1cb1ef
--- /dev/null
+++ b/tests/src/android/provider/cts/TestSearchRecentSuggestionsProvider.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * 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 android.provider.cts;
+
+import android.content.SearchRecentSuggestionsProvider;
+
+public class TestSearchRecentSuggestionsProvider extends SearchRecentSuggestionsProvider {
+ final static String AUTHORITY = "android.provider.cts.TestSRSProvider";
+ final static int MODE = DATABASE_MODE_QUERIES + DATABASE_MODE_2LINES;
+
+ public TestSearchRecentSuggestionsProvider() {
+ super();
+ setupSuggestions(AUTHORITY, MODE);
+ }
+}
diff --git a/tests/src/android/renderscript/cts/passthrough.rs b/tests/src/android/renderscript/cts/passthrough.rs
new file mode 100644
index 0000000..008f7f2
--- /dev/null
+++ b/tests/src/android/renderscript/cts/passthrough.rs
@@ -0,0 +1,8 @@
+#pragma version(1)
+#pragma rs java_package_name(android.renderscript.cts)
+
+void passthrough(int i) {
+ rsDebug("i: ", i);
+ return;
+}
+
diff --git a/tests/src/android/renderscript/cts/primitives.rs b/tests/src/android/renderscript/cts/primitives.rs
new file mode 100644
index 0000000..d2ffd26
--- /dev/null
+++ b/tests/src/android/renderscript/cts/primitives.rs
@@ -0,0 +1,61 @@
+#include "shared.rsh"
+
+// Testing primitive types
+float floatTest = 1.99f;
+double doubleTest = 2.05;
+char charTest = -8;
+short shortTest = -16;
+int intTest = -32;
+long longTest = 17179869184l; // 1 << 34
+long long longlongTest = 68719476736l; // 1 << 36
+
+uchar ucharTest = 8;
+ushort ushortTest = 16;
+uint uintTest = 32;
+ulong ulongTest = 4611686018427387904L;
+int64_t int64_tTest = -17179869184l; // - 1 << 34
+uint64_t uint64_tTest = 117179869184l;
+
+static bool test_primitive_types() {
+ bool failed = false;
+ start();
+
+ _RS_ASSERT(floatTest == 2.99f);
+ _RS_ASSERT(doubleTest == 3.05);
+ _RS_ASSERT(charTest == -16);
+ _RS_ASSERT(shortTest == -32);
+ _RS_ASSERT(intTest == -64);
+ _RS_ASSERT(longTest == 17179869185l);
+ _RS_ASSERT(longlongTest == 68719476735l);
+
+ _RS_ASSERT(ucharTest == 8);
+ _RS_ASSERT(ushortTest == 16);
+ _RS_ASSERT(uintTest == 32);
+ _RS_ASSERT(ulongTest == 4611686018427387903L);
+ _RS_ASSERT(int64_tTest == -17179869184l);
+ _RS_ASSERT(uint64_tTest == 117179869185l);
+
+ float time = end();
+
+ if (failed) {
+ rsDebug("test_primitive_types FAILED", time);
+ }
+ else {
+ rsDebug("test_primitive_types PASSED", time);
+ }
+
+ return failed;
+}
+
+void test() {
+ bool failed = false;
+ failed |= test_primitive_types();
+
+ if (failed) {
+ rsSendToClientBlocking(RS_MSG_TEST_FAILED);
+ }
+ else {
+ rsSendToClientBlocking(RS_MSG_TEST_PASSED);
+ }
+}
+
diff --git a/tests/src/android/renderscript/cts/shared.rsh b/tests/src/android/renderscript/cts/shared.rsh
new file mode 100644
index 0000000..b91611d
--- /dev/null
+++ b/tests/src/android/renderscript/cts/shared.rsh
@@ -0,0 +1,27 @@
+#pragma version(1)
+#pragma rs java_package_name(android.renderscript.cts)
+
+static int64_t g_time;
+
+static void start(void) {
+ g_time = rsUptimeMillis();
+}
+
+static float end(void) {
+ int64_t t = rsUptimeMillis() - g_time;
+ return ((float)t) / 1000.f;
+}
+
+#define _RS_ASSERT(b) \
+do { \
+ if (!(b)) { \
+ failed = true; \
+ rsDebug(#b " FAILED", 0); \
+ } \
+\
+} while (0)
+
+/* These constants must match those in UnitTest.java */
+static const int RS_MSG_TEST_PASSED = 100;
+static const int RS_MSG_TEST_FAILED = 101;
+
diff --git a/tests/src/android/view/cts/FocusHandlingStubActivity.java b/tests/src/android/view/cts/FocusHandlingStubActivity.java
index 2124550..9faa609 100644
--- a/tests/src/android/view/cts/FocusHandlingStubActivity.java
+++ b/tests/src/android/view/cts/FocusHandlingStubActivity.java
@@ -16,9 +16,10 @@
package android.view.cts;
+import com.android.cts.stub.R;
+
import android.app.Activity;
import android.os.Bundle;
-import com.android.cts.stub.R;
/**
* A simple activity to test "Focus Handling"
@@ -27,6 +28,7 @@
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ setTheme(android.R.style.Theme_Holo_NoActionBar);
setContentView(R.layout.focus_handling_layout);
}
}
diff --git a/tests/src/android/webkit/cts/CtsTestServer.java b/tests/src/android/webkit/cts/CtsTestServer.java
index 49603bc..707455b 100644
--- a/tests/src/android/webkit/cts/CtsTestServer.java
+++ b/tests/src/android/webkit/cts/CtsTestServer.java
@@ -408,14 +408,12 @@
if (path.startsWith(AUTH_PREFIX)) {
// authentication required
Header[] auth = request.getHeaders("Authorization");
- if (auth.length > 0) {
- if (auth[0].getValue().equals(AUTH_CREDENTIALS)) {
- // fall through and serve content
- path = path.substring(AUTH_PREFIX.length());
- } else {
- // incorrect password
- response = createResponse(HttpStatus.SC_FORBIDDEN);
- }
+ if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
+ // This is a hack to make sure that loads to this url's will always
+ // ask for authentication. This is what the test expects.
+ && !path.endsWith("embedded_image.html")) {
+ // fall through and serve content
+ path = path.substring(AUTH_PREFIX.length());
} else {
// request authorization
response = createResponse(HttpStatus.SC_UNAUTHORIZED);
diff --git a/tests/tests/accessibilityservice/AndroidManifest.xml b/tests/tests/accessibilityservice/AndroidManifest.xml
index 811c87f..b4fe6ab 100644
--- a/tests/tests/accessibilityservice/AndroidManifest.xml
+++ b/tests/tests/accessibilityservice/AndroidManifest.xml
@@ -24,7 +24,7 @@
<uses-library android:name="android.test.runner"/>
<activity android:label="@string/accessibility_end_to_end_test_activity"
- android:name="android.accessibilityservice.cts.AccessibilityEndToEndTestActivity"/>
+ android:name="android.accessibilityservice.cts.AccessibilityEndToEndTestActivity"/>
</application>
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
index 5259753..89e5473 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
@@ -16,6 +16,8 @@
package android.accessibilityservice.cts;
+import com.android.cts.accessibilityservice.R;
+
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.IAccessibilityServiceDelegate;
import android.accessibilityservice.IAccessibilityServiceDelegateConnection;
@@ -33,6 +35,7 @@
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
@@ -47,8 +50,6 @@
import android.widget.EditText;
import android.widget.ListView;
-import com.android.cts.accessibilityservice.R;
-
import junit.framework.TestCase;
import java.util.Iterator;
@@ -56,23 +57,25 @@
import java.util.List;
import java.util.Queue;
+import junit.framework.TestCase;
+
/**
* This class performs end-to-end testing of the accessibility feature by
* creating an {@link Activity} and poking around so {@link AccessibilityEvent}s
* are generated and their correct dispatch verified.
- * </p>
- * Note: The end-to-end test is composed of two APKs, one with a delegating accessibility
+ * <p>
+ * Note: The end-to-end test is composed of two APKs, one with a mock accessibility
* service, another with the instrumented activity and test cases. The motivation for
* two APKs design is that CTS tests cannot access the secure settings which is
* required for enabling accessibility and accessibility services. Therefore, manual
- * installation of the <strong>CtsDelegatingAccessibilityService.apk</strong>
- * whose source is located at <strong>cts/tests/accessibilityservice</strong> is required.
+ * installation of the <strong>CtsAccessibilityServiceTestMockService.apk</strong>
+ * whose source is located at <strong>cts/tests/accessibility</strong> is required.
* Once the former package has been installed accessibility must be enabled (Settings ->
- * Accessibility), the delegating service must be enabled (Settings -> Accessibility
- * -> Delegating Accessibility Service), and then the CTS tests in this package can be
- * successfully run. Further, the delegate and tests run in separate processes since
+ * Accessibility), the mock service must be enabled (Settings -> Accessibility
+ * -> Mock Accessibility Service), and then the CTS tests in this package can be
+ * successfully run. Further, the mock and tests run in separate processes since
* the instrumentation restarts the process in which it is running and this
- * breaks the binding between the delegating accessibility service and the system.
+ * breaks the binding between the mock accessibility service and the system.
*/
public class AccessibilityEndToEndTest extends
ActivityInstrumentationTestCase2<AccessibilityEndToEndTestActivity> {
@@ -114,15 +117,7 @@
* @throws Exception If any error occurs.
*/
public AccessibilityEndToEndTest() throws Exception {
- super("com.android.cts.accessibilityservice", AccessibilityEndToEndTestActivity.class);
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- // wait for the activity to settle down so we do not receive
- // the event for its start, thus breaking the tests
- getInstrumentation().waitForIdleSync();
+ super(AccessibilityEndToEndTestActivity.class);
}
@LargeTest
@@ -224,8 +219,13 @@
focusedEvent.setClassName(Button.class.getName());
focusedEvent.setPackageName(getActivity().getPackageName());
focusedEvent.getText().add(activity.getString(R.string.button_title));
- focusedEvent.setItemCount(3);
- focusedEvent.setCurrentItemIndex(2);
+ if (hasActivityActionBar()) {
+ focusedEvent.setItemCount(4);
+ focusedEvent.setCurrentItemIndex(3);
+ } else {
+ focusedEvent.setItemCount(3);
+ focusedEvent.setCurrentItemIndex(2);
+ }
focusedEvent.setEnabled(true);
// set expectations
@@ -247,7 +247,7 @@
@LargeTest
public void testTypeViewTextChangedAccessibilityEvent() throws Throwable {
- Activity activity = getActivity();
+ final Activity activity = getActivity();
// focus the edit text
final EditText editText = (EditText) activity.findViewById(R.id.edittext);
@@ -413,6 +413,14 @@
throw lastVerifyThrowable;
}
+ /**
+ * @return Whether the activity has action bar.
+ */
+ private boolean hasActivityActionBar() {
+ return (getActivity().getApplicationInfo().targetSdkVersion
+ >= Build.VERSION_CODES.HONEYCOMB);
+ }
+
static class MockAccessibilityService extends AccessibilityService implements
ServiceConnection {
@@ -606,7 +614,6 @@
}
AccessibilityEvent expectedEvent = mExpectedEvents.poll();
assertEqualsAccessiblityEvent(expectedEvent, receivedEvent);
-
}
}
@@ -677,8 +684,7 @@
receivedEvent.isFullScreen());
TestCase.assertEquals("itemCount has incorrect value", expectedEvent.getItemCount(),
receivedEvent.getItemCount());
- // This will fail due to a bug fixed in Gingerbread. Bug 2593810 (removed the method).
- // assertEqualsNotificationAsParcelableData(expectedEvent, receivedEvent);
+ assertEqualsNotificationAsParcelableData(expectedEvent, receivedEvent);
TestCase.assertEquals("password has incorrect value", expectedEvent.isPassword(),
receivedEvent.isPassword());
TestCase.assertEquals("removedCount has incorrect value", expectedEvent
@@ -687,6 +693,30 @@
}
/**
+ * Compares the {@link android.os.Parcelable} data of the
+ * <code>expectedEvent</code> and <code>receivedEvent</code> to verify
+ * that the received event is the one that is expected.
+ */
+ private void assertEqualsNotificationAsParcelableData(AccessibilityEvent expectedEvent,
+ AccessibilityEvent receivedEvent) {
+ String message = "parcelableData has incorrect value";
+ Notification expectedNotification = (Notification) expectedEvent.getParcelableData();
+ Notification receivedNotification = (Notification) receivedEvent.getParcelableData();
+
+ if (expectedNotification == null) {
+ if (receivedNotification == null) {
+ return;
+ }
+ }
+
+ TestCase.assertNotNull(message, receivedNotification);
+
+ // we do a very simple sanity check
+ TestCase.assertEquals(message, expectedNotification.tickerText.toString(),
+ receivedNotification.tickerText.toString());
+ }
+
+ /**
* Compares the text of the <code>expectedEvent</code> and
* <code>receivedEvent</code> by comparing the string representation of
* the corresponding {@link CharSequence}s.
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java
index e806622..adfc9e6 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java
@@ -16,6 +16,8 @@
package android.accessibilityservice.cts;
+import com.android.cts.accessibilityservice.R;
+
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
@@ -26,8 +28,6 @@
import android.widget.ListView;
import android.widget.TextView;
-import com.android.cts.accessibilityservice.R;
-
/**
* This class is an {@link Activity} used to perform end-to-end
* testing of the accessibility feature by interaction with the
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java
index 48b4aae..ab7ecd7 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java
@@ -72,8 +72,7 @@
receivedInfo.eventTypes);
assertEquals("feedbackType not marshalled properly", sentInfo.feedbackType,
receivedInfo.feedbackType);
- // This will fail here and is fixed in Froyo. Bug 2448479.
- // assertEquals("flags not marshalled properly", sentInfo.flags, receivedInfo.flags);
+ assertEquals("flags not marshalled properly", sentInfo.flags, receivedInfo.flags);
assertEquals("notificationTimeout not marshalled properly", sentInfo.notificationTimeout,
receivedInfo.notificationTimeout);
assertEquals("packageNames not marshalled properly", sentInfo.packageNames.length,
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
index c306c79..4414617 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
@@ -28,6 +28,7 @@
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
+import android.os.StrictMode;
import android.test.AndroidTestCase;
import java.io.IOException;
@@ -151,7 +152,7 @@
private void validateOptions(Bundle expectedOptions, Bundle actualOptions) {
if (expectedOptions == null) {
if (actualOptions != null) {
- assertTrue(actualOptions.isEmpty());
+ assertTrue(actualOptions.isEmpty());
}
} else {
assertNotNull(actualOptions);
@@ -1328,4 +1329,28 @@
handler);
waitForLatch(latch);
}
+
+ /**
+ * Tests that AccountManagerService is properly caching data.
+ */
+ public void testGetsAreCached() throws IOException, AuthenticatorException,
+ OperationCanceledException {
+
+ // Add an account,
+ assertEquals(false, isAccountPresent(am.getAccounts(), ACCOUNT));
+ addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
+
+ // Then verify that we don't hit disk retrieving it,
+ StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
+ try {
+ StrictMode.setThreadPolicy(
+ new StrictMode.ThreadPolicy.Builder().detectDiskReads().penaltyDeath().build());
+ Account[] accounts = am.getAccounts();
+ assertNotNull(accounts);
+ assertTrue(accounts.length > 0);
+ } finally {
+ StrictMode.setThreadPolicy(oldPolicy);
+ }
+ }
+
}
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java
new file mode 100644
index 0000000..9506261
--- /dev/null
+++ b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.app.cts;
+
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Configuration;
+import android.test.ActivityInstrumentationTestCase2;
+import android.util.DisplayMetrics;
+import android.view.Display;
+import android.view.WindowManager;
+
+/**
+ * {@link ActivityInstrumentationTestCase2} that tests {@link ActivityManager#getMemoryClass()}
+ * by checking that the memory class matches the proper screen density and by launching an
+ * application that attempts to allocate memory on the heap.
+ */
+public class ActivityManagerMemoryClassTest
+ extends ActivityInstrumentationTestCase2<ActivityManagerMemoryClassLaunchActivity> {
+
+ public ActivityManagerMemoryClassTest() {
+ super(ActivityManagerMemoryClassLaunchActivity.class);
+ }
+
+ public void testGetMemoryClass() throws Exception {
+ int memoryClass = getMemoryClass();
+ int screenDensity = getScreenDensity();
+ int screenSize = getScreenSize();
+ assertMemoryForScreenDensity(memoryClass, screenDensity, screenSize);
+
+ runHeapTestApp(memoryClass);
+ }
+
+ private int getMemoryClass() {
+ Context context = getInstrumentation().getTargetContext();
+ ActivityManager activityManager =
+ (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
+ return activityManager.getMemoryClass();
+ }
+
+ private int getScreenDensity() {
+ Context context = getInstrumentation().getTargetContext();
+ WindowManager windowManager =
+ (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+ Display display = windowManager.getDefaultDisplay();
+ DisplayMetrics metrics = new DisplayMetrics();
+ display.getMetrics(metrics);
+ return metrics.densityDpi;
+ }
+
+ private int getScreenSize() {
+ Context context = getInstrumentation().getTargetContext();
+ Configuration config = context.getResources().getConfiguration();
+ return config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
+ }
+
+ private void assertMemoryForScreenDensity(int memoryClass, int screenDensity, int screenSize) {
+ int expectedMinimumMemory = -1;
+ boolean isXLarge = screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE;
+ switch (screenDensity) {
+ case DisplayMetrics.DENSITY_LOW:
+ expectedMinimumMemory = 16;
+ break;
+
+ case DisplayMetrics.DENSITY_MEDIUM:
+ expectedMinimumMemory = isXLarge ? 32 : 16;
+ break;
+
+ case DisplayMetrics.DENSITY_HIGH:
+ case DisplayMetrics.DENSITY_XHIGH:
+ expectedMinimumMemory = isXLarge ? 48 : 24;
+ break;
+
+ default:
+ throw new IllegalArgumentException("No memory requirement specified "
+ + " for screen density " + screenDensity);
+ }
+
+ assertTrue("Expected to have at least " + expectedMinimumMemory
+ + "mb of memory for screen density " + screenDensity,
+ memoryClass >= expectedMinimumMemory);
+ }
+
+ private void runHeapTestApp(int memoryClass) throws InterruptedException {
+ Intent intent = new Intent();
+ intent.putExtra(ActivityManagerMemoryClassLaunchActivity.MEMORY_CLASS_EXTRA,
+ memoryClass);
+ setActivityIntent(intent);
+ ActivityManagerMemoryClassLaunchActivity activity = getActivity();
+ assertEquals("The test application couldn't allocate memory close to the amount "
+ + " specified by the memory class.", Activity.RESULT_OK, activity.getResult());
+ }
+}
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
index 5b1c2b3..217a17c 100644
--- a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -305,4 +305,21 @@
ConfigurationInfo conInf = mActivityManager.getDeviceConfigurationInfo();
assertNotNull(conInf);
}
+
+ /**
+ * Simple test for {@link ActivityManager.isUserAMonkey()} - verifies its false.
+ *
+ * TODO: test positive case
+ */
+ public void testIsUserAMonkey() {
+ assertFalse(ActivityManager.isUserAMonkey());
+ }
+
+ /**
+ * Verify that {@link ActivityManager.isRunningInTestHarness()} is false.
+ */
+ public void testIsRunningInTestHarness() {
+ assertFalse("isRunningInTestHarness must be false in production builds",
+ ActivityManager.isRunningInTestHarness());
+ }
}
diff --git a/tests/tests/app/src/android/app/cts/AlertDialogTest.java b/tests/tests/app/src/android/app/cts/AlertDialogTest.java
index 4ab57da..b5711ed 100644
--- a/tests/tests/app/src/android/app/cts/AlertDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/AlertDialogTest.java
@@ -16,6 +16,11 @@
package android.app.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.content.Context;
@@ -29,10 +34,6 @@
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
/*
* Test AlertDialog
@@ -55,15 +56,10 @@
protected void setUp() throws Exception {
super.setUp();
mInstrumentation = getInstrumentation();
- mActivity = getActivity();
}
- protected void popDialog(int index) {
- while (index != 0) {
- sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
- index--;
- }
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+ protected void startDialogActivity(int dialogNumber) {
+ mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
}
@TestTargets({
@@ -121,7 +117,7 @@
}
private void doTestAlertDialog(int index) throws Throwable {
- popDialog(index);
+ startDialogActivity(index);
assertTrue(mActivity.getDialog().isShowing());
mPositiveButton = ((AlertDialog) (mActivity.getDialog())).getButton(
@@ -294,7 +290,7 @@
)
})
public void testAlertDialogDeprecatedAPIWithMessage() throws Throwable {
- popDialog(DialogStubActivity.TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE);
+ startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE);
assertTrue(mActivity.getDialog().isShowing());
mPositiveButton = ((AlertDialog) (mActivity.getDialog())).getButton(
@@ -368,7 +364,7 @@
)
})
public void testCustomAlertDialog() {
- popDialog(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG);
+ startDialogActivity(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG);
assertTrue(mActivity.getDialog().isShowing());
}
@@ -405,7 +401,7 @@
)
})
public void testCustomAlertDialogView() {
- popDialog(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG_VIEW);
+ startDialogActivity(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG_VIEW);
assertTrue(mActivity.getDialog().isShowing());
}
@@ -437,7 +433,7 @@
)
})
public void testCallback() {
- popDialog(DialogStubActivity.TEST_ALERTDIALOG_CALLBACK);
+ startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_CALLBACK);
assertTrue(mActivity.onCreateCalled);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_0);
@@ -453,7 +449,7 @@
args = {Context.class, int.class}
)
public void testAlertDialogTheme() throws Exception {
- popDialog(DialogStubActivity.TEST_ALERTDIALOG_THEME);
+ startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_THEME);
assertTrue(mActivity.getDialog().isShowing());
}
@@ -464,7 +460,7 @@
args = {Context.class, boolean.class, OnCancelListener.class}
)
public void testAlertDialogCancelable() throws Exception {
- popDialog(DialogStubActivity.TEST_ALERTDIALOG_CANCELABLE);
+ startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_CANCELABLE);
assertTrue(mActivity.getDialog().isShowing());
assertFalse(mActivity.onCancelCalled);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
@@ -479,7 +475,7 @@
args = {Context.class, boolean.class, OnCancelListener.class}
)
public void testAlertDialogNotCancelable() throws Exception {
- popDialog(DialogStubActivity.TEST_ALERTDIALOG_NOT_CANCELABLE);
+ startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_NOT_CANCELABLE);
assertTrue(mActivity.getDialog().isShowing());
assertFalse(mActivity.onCancelCalled);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
diff --git a/tests/tests/app/src/android/app/cts/DialogTest.java b/tests/tests/app/src/android/app/cts/DialogTest.java
index 77c55fb..0afb051 100644
--- a/tests/tests/app/src/android/app/cts/DialogTest.java
+++ b/tests/tests/app/src/android/app/cts/DialogTest.java
@@ -15,8 +15,14 @@
*/
package android.app.cts;
-import java.lang.ref.WeakReference;
import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
import android.app.Dialog;
import android.app.Instrumentation;
import android.content.Context;
@@ -24,7 +30,6 @@
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnKeyListener;
-import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
@@ -35,29 +40,24 @@
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
+import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
import android.view.animation.cts.DelayedCheck;
import android.view.KeyEvent;
import android.view.LayoutInflater;
-import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+
+import java.lang.ref.WeakReference;
@TestTargetClass(Dialog.class)
public class DialogTest extends ActivityInstrumentationTestCase2<DialogStubActivity> {
protected static final long SLEEP_TIME = 200;
- private static final long MOTION_DOWN_TIME = 0L;
- private static final long MOTION_EVENT_TIME = 0L;
private static final float MOTION_X = -20.0f;
private static final float MOTION_Y = -20.0f;
private static final String STUB_ACTIVITY_PACKAGE = "com.android.cts.stub";
@@ -86,30 +86,12 @@
@Override
protected void setUp() throws Exception {
super.setUp();
-
mInstrumentation = getInstrumentation();
mContext = mInstrumentation.getContext();
- mActivity = getActivity();
}
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
-
- if (mActivity != null) {
- mActivity.finish();
- }
- }
-
- protected void popDialog(int index) {
- assertTrue(index >= 0);
-
- while (index != 0) {
- sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
- index--;
- }
-
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+ private void startDialogActivity(int dialogNumber) {
+ mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
}
@TestTargets({
@@ -141,7 +123,7 @@
args = {}
)
})
- public void testDialog(){
+ public void testConstructor(){
new Dialog(mContext);
Dialog d = new Dialog(mContext, 0);
// According to javadoc of constructors, it will set theme to system default theme,
@@ -156,16 +138,17 @@
final Window w = d.getWindow();
ta = w.getContext().getTheme().obtainStyledAttributes(R.styleable.TextAppearance);
assertTextAppearanceStyle(ta);
+ }
- // test protected constructor
- // Dialog(Context context, boolean cancelable, OnCancelListener cancelListener)
+ public void testConstructor_protectedCancellable() {
+ startDialogActivity(DialogStubActivity.TEST_PROTECTED_CANCELABLE);
mActivity.onCancelListenerCalled = false;
- popDialog(DialogStubActivity.TEST_PROTECTED_CANCELABLE);
sendKeys(KeyEvent.KEYCODE_BACK);
assertTrue(mActivity.onCancelListenerCalled);
+ }
- // open DialogStubActivity.TEST_PROTECTED_NOT_CANCELABLE
- sendKeys(KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_CENTER);
+ public void testConstructor_protectedNotCancellable() {
+ startDialogActivity(DialogStubActivity.TEST_PROTECTED_NOT_CANCELABLE);
mActivity.onCancelListenerCalled = false;
sendKeys(KeyEvent.KEYCODE_BACK);
assertFalse(mActivity.onCancelListenerCalled);
@@ -211,7 +194,7 @@
)
})
public void testOnStartCreateStop(){
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertTrue(d.isOnStartCalled);
@@ -245,7 +228,7 @@
)
})
public void testAccessOwnerActivity() {
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
Dialog d = mActivity.getDialog();
assertNotNull(d);
assertSame(mActivity, d.getOwnerActivity());
@@ -286,7 +269,7 @@
)
})
public void testShow() throws Throwable {
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
final View decor = d.getWindow().getDecorView();
@@ -326,7 +309,7 @@
)
})
public void testOnSaveInstanceState() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertFalse(d.isOnSaveInstanceStateCalled);
@@ -344,7 +327,7 @@
args = {}
)
public void testGetCurrentFocus() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNull(d.getCurrentFocus());
runTestOnUiThread(new Runnable() {
@@ -388,7 +371,7 @@
)
})
public void testSetContentView() throws Throwable {
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertNotNull(d);
@@ -474,7 +457,7 @@
})
public void testSetTitle() {
final String expectedTitle = "Test Dialog Without theme";
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
assertNotNull(mActivity.getDialog());
mActivity.setUpTitle(expectedTitle);
@@ -502,7 +485,7 @@
)
})
public void testOnKeyDownKeyUp() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertFalse(d.isOnKeyDownCalled);
assertFalse(d.isOnKeyUpCalled);
@@ -526,7 +509,7 @@
args = {int.class, int.class, android.view.KeyEvent.class}
)
public void testOnKeyMultiple() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNull(d.keyMultipleEvent);
@@ -555,15 +538,16 @@
)
})
public void testTouchEvent() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNull(d.onTouchEvent);
assertNull(d.touchEvent);
assertFalse(d.isOnTouchEventCalled);
- MotionEvent touchMotionEvent = MotionEvent.obtain(MOTION_DOWN_TIME,
- MOTION_EVENT_TIME, MotionEvent.ACTION_DOWN,
+ long eventTime = SystemClock.uptimeMillis();
+ MotionEvent touchMotionEvent = MotionEvent.obtain(eventTime,
+ eventTime, MotionEvent.ACTION_DOWN,
MOTION_X, MOTION_Y, 0);
// send a touch motion event, and System will call onTouchEvent
mInstrumentation.sendPointerSync(touchMotionEvent);
@@ -578,8 +562,8 @@
// set cancel on touch out side
d.setCanceledOnTouchOutside(true);
- touchMotionEvent = MotionEvent.obtain(MOTION_DOWN_TIME + 1,
- MOTION_EVENT_TIME, MotionEvent.ACTION_DOWN,
+ touchMotionEvent = MotionEvent.obtain(eventTime + 1,
+ eventTime, MotionEvent.ACTION_DOWN,
MOTION_X, MOTION_Y, 0);
// send a out side touch motion event, then the dialog will dismiss
mInstrumentation.sendPointerSync(touchMotionEvent);
@@ -605,9 +589,10 @@
)
})
public void testTrackballEvent() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
- final MotionEvent trackBallEvent = MotionEvent.obtain(MOTION_DOWN_TIME, MOTION_EVENT_TIME,
+ long eventTime = SystemClock.uptimeMillis();
+ final MotionEvent trackBallEvent = MotionEvent.obtain(eventTime, eventTime,
MotionEvent.ACTION_DOWN, MOTION_X, MOTION_Y, 0);
assertNull(d.trackballEvent);
@@ -638,7 +623,7 @@
args = {android.view.WindowManager.LayoutParams.class}
)
public void testOnWindowAttributesChanged() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertTrue(d.isOnWindowAttributesChangedCalled);
@@ -663,7 +648,7 @@
args = {}
)
public void testOnContentChanged() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNotNull(d);
@@ -685,7 +670,7 @@
args = {boolean.class}
)
public void testOnWindowFocusChanged() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertTrue(d.isOnWindowFocusChangedCalled);
d.isOnWindowFocusChangedCalled = false;
@@ -719,7 +704,7 @@
)
})
public void testDispatchKeyEvent() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
sendKeys(KeyEvent.KEYCODE_0);
@@ -755,149 +740,6 @@
/*
* Test point
- * 1. First open a option menu will make onMenuOpened onCreatePanelView onCreatePanelMenu
- * and onPreparePanel to be called.
- * 2. When first open the option menu onCreatePanelMenu will calls through to
- * the new onCreateOptionsMenu method.
- * 3. When open the option menu onPreparePanel will calls through to
- * the new onPrepareOptionsMenu method.
- * 4. Closed option menu will make onPanelClosed to be called,
- * and onPanelClosed will calls through to the new onPanelClosed method.
- * 5. Every time open option menu will make onCreatePanelView and onPreparePanel to be called.
- * 6. Selected a item on the option menu will make onMenuItemSelected to be called,
- * and onMenuItemSelected will calls through to the new onOptionsItemSelected method.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "openOptionsMenu",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "closeOptionsMenu",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onMenuOpened",
- args = {int.class, android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onCreatePanelView",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onCreatePanelMenu",
- args = {int.class, android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onCreateOptionsMenu",
- args = {android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onPreparePanel",
- args = {int.class, android.view.View.class, android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onPrepareOptionsMenu",
- args = {android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- method = "onPanelClosed",
- args = {int.class, android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "onOptionsMenuClosed should be called when onPanelClosed Called.",
- method = "onOptionsMenuClosed",
- args = {android.view.Menu.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- method = "onMenuItemSelected",
- args = {int.class, android.view.MenuItem.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- method = "onOptionsItemSelected",
- args = {MenuItem.class}
- )
- })
- @ToBeFixed(bug = "1716918", explanation = "As Javadoc of onMenuItemSelected() and "
- + "onPanelClosed(), onOptionsItemSelected() and onContextItemSelected() should be "
- + "called in onMenuItemSelected() source code, onOptionMenuClosed() and "
- + "onContextMenuClosed() should be called in onPanelClosed() source code, "
- + "but now onMenuItemSelected() and onPanelClosed() method are empty, is this a bug?")
- public void testOptionMenu() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
- final TestDialog d = (TestDialog) mActivity.getDialog();
- assertFalse(d.isOnMenuOpenedCalled);
- assertFalse(d.isOnCreatePanelViewCalled);
- assertFalse(d.isOnCreatePanelMenuCalled);
- assertFalse(d.isOnCreateOptionsMenuCalled);
- assertFalse(d.isOnPreparePanelCalled);
- assertFalse(d.isOnPrepareOptionsMenuCalled);
- // first open option menu
- dialogOpenOptionMenu(d);
-
- assertTrue(d.isOnMenuOpenedCalled);
- assertTrue(d.isOnCreatePanelViewCalled);
- assertTrue(d.isOnCreatePanelMenuCalled);
- assertTrue(d.isOnCreateOptionsMenuCalled);
- assertTrue(d.isOnPreparePanelCalled);
- assertTrue(d.isOnPrepareOptionsMenuCalled);
-
- assertFalse(d.isOnPanelClosedCalled);
- // closed option menu
- runTestOnUiThread(new Runnable() {
- public void run() {
- d.closeOptionsMenu();
- }
- });
- mInstrumentation.waitForIdleSync();
-
- assertTrue(d.isOnPanelClosedCalled);
-
- d.isOnCreatePanelViewCalled = false;
- d.isOnCreatePanelMenuCalled = false;
- d.isOnPreparePanelCalled = false;
- assertFalse(d.isOnOptionsMenuClosedCalled);
- // open option menu again
- dialogOpenOptionMenu(d);
-
- assertTrue(d.isOnCreatePanelViewCalled);
- assertFalse(d.isOnCreatePanelMenuCalled);
- assertTrue(d.isOnPreparePanelCalled);
- // Here isOnOptionsMenuClosedCalled should be true, see bug 1716918.
- assertFalse(d.isOnOptionsMenuClosedCalled);
-
- assertFalse(d.isOnMenuItemSelectedCalled);
- assertFalse(d.isOnOptionsItemSelectedCalled);
- // selected a item of option menu
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
- assertTrue(d.isOnMenuItemSelectedCalled);
- // Here isOnOptionsItemSelectedCalled should be true, see bug 1716918.
- assertFalse(d.isOnOptionsItemSelectedCalled);
- }
-
- private void dialogOpenOptionMenu(final Dialog d) throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- d.openOptionsMenu();
- }
- });
- mInstrumentation.waitForIdleSync();
- }
-
- /*
- * Test point
* 1. registerForContextMenu() will OnCreateContextMenuListener on the view to this activity,
* so onCreateContextMenu() will be called when it is time to show the context menu.
* 2. Close context menu will make onPanelClosed to be called,
@@ -950,7 +792,7 @@
+ "onContextMenuClosed() should be called in onPanelClosed() source code, "
+ "but now onMenuItemSelected() and onPanelClosed() method are empty, is this a bug?")
public void testContextMenu() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
final LinearLayout parent = new LinearLayout(mContext);
final MockView v = new MockView(mContext);
@@ -1042,7 +884,7 @@
@ToBeFixed(bug = "1695243",
explanation = "It still get KeyEvent while set takeKeyEvents to false")
public void testTakeKeyEvents() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
final View v = d.getWindow().getDecorView();
assertNull(d.getCurrentFocus());
@@ -1074,7 +916,7 @@
args = {int.class}
)
public void testRequestWindowFeature() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
// called requestWindowFeature at TestDialog onCreate method
assertTrue(((TestDialog) mActivity.getDialog()).isRequestWindowFeature);
}
@@ -1087,7 +929,7 @@
args = {int.class, int.class}
)
public void testSetFeatureDrawableResource() throws Throwable {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
runTestOnUiThread(new Runnable() {
public void run() {
mActivity.getDialog().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
@@ -1105,7 +947,7 @@
args = {int.class, android.net.Uri.class}
)
public void testSetFeatureDrawableUri() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
mActivity.getDialog().setFeatureDrawableUri(0, Uri.parse("http://www.google.com"));
}
@@ -1117,7 +959,7 @@
args = {int.class, android.graphics.drawable.Drawable.class}
)
public void testSetFeatureDrawable() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
mActivity.getDialog().setFeatureDrawable(0, new MockDrawable());
}
@@ -1129,7 +971,7 @@
args = {int.class, int.class}
)
public void testSetFeatureDrawableAlpha() {
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
mActivity.getDialog().setFeatureDrawableAlpha(0, 0);
}
@@ -1139,7 +981,7 @@
args = {}
)
public void testGetLayoutInflater() {
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertEquals(d.getWindow().getLayoutInflater(), d.getLayoutInflater());
}
@@ -1149,17 +991,21 @@
method = "setCancelable",
args = {boolean.class}
)
- public void testSetCancelable() {
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ public void testSetCancelable_true() {
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
d.setCancelable(true);
assertTrue(d.isShowing());
sendKeys(KeyEvent.KEYCODE_BACK);
assertFalse(d.isShowing());
+ }
+
+ public void testSetCancellable_false() {
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ final Dialog d = mActivity.getDialog();
d.setCancelable(false);
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
assertTrue(d.isShowing());
sendKeys(KeyEvent.KEYCODE_BACK);
assertTrue(d.isShowing());
@@ -1182,8 +1028,8 @@
args = {android.content.DialogInterface.OnCancelListener.class}
)
})
- public void testCancel() throws Throwable {
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ public void testCancel_listener() throws Throwable {
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertTrue(d.isShowing());
@@ -1197,8 +1043,12 @@
assertFalse(d.isShowing());
assertTrue(mOnCancelListenerCalled);
+ }
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+ public void testCancel_noListener() throws Throwable {
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ final Dialog d = mActivity.getDialog();
+
assertTrue(d.isShowing());
mOnCancelListenerCalled = false;
d.setOnCancelListener(null);
@@ -1216,7 +1066,7 @@
)
public void testSetCancelMessage() throws Exception {
mCalledCallback = false;
- popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
final HandlerThread ht = new HandlerThread("DialogTest");
ht.start();
@@ -1246,9 +1096,9 @@
method = "setOnDismissListener",
args = {android.content.DialogInterface.OnDismissListener.class}
)
- public void testSetOnDismissListener() throws Throwable {
+ public void testSetOnDismissListener_listener() throws Throwable {
mCalledCallback = false;
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
d.setOnDismissListener(new OnDismissListener() {
@@ -1262,9 +1112,11 @@
dialogDismiss(d);
assertTrue(mCalledCallback);
assertFalse(d.isShowing());
+ }
- // show the dialog again
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+ public void testSetOnDismissListener_noListener() throws Throwable {
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ final Dialog d = mActivity.getDialog();
assertTrue(d.isShowing());
mCalledCallback = false;
d.setOnDismissListener(null);
@@ -1280,7 +1132,7 @@
)
public void testSetDismissMessage() throws Throwable {
mCalledCallback = false;
- popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
final HandlerThread ht = new HandlerThread("DialogTest");
diff --git a/tests/tests/app/src/android/app/cts/InstrumentationTest.java b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
index e3eb46d..d2c55c2 100644
--- a/tests/tests/app/src/android/app/cts/InstrumentationTest.java
+++ b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
@@ -16,7 +16,12 @@
package android.app.cts;
-import java.util.List;
+import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
import android.app.Activity;
import android.app.Application;
@@ -46,12 +51,7 @@
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
-import com.android.cts.stub.R;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
+import java.util.List;
@TestTargetClass(Instrumentation.class)
public class InstrumentationTest extends InstrumentationTestCase {
@@ -73,8 +73,8 @@
final long eventTime = SystemClock.uptimeMillis();
// use coordinates for MotionEvent that do not include the status bar
// TODO: is there a more deterministic way to get these values
- final long x = 55;
- final long y = 55;
+ final long x = 100;
+ final long y = 100;
final int metaState = 0;
mMotionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y,
metaState);
@@ -88,6 +88,7 @@
mIntent = null;
if (mActivity != null) {
mActivity.finish();
+ mActivity = null;
}
super.tearDown();
}
@@ -493,7 +494,7 @@
assertEquals(text.length(), keyDownList.size());
assertEquals(text.length(), keyUpList.size());
- KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
KeyEvent[] keyEvents = kcm.getEvents(text.toCharArray());
int i = 0;
@@ -508,10 +509,14 @@
method = "callActivityOnSaveInstanceState",
args = {Activity.class, Bundle.class}
)
- public void testCallActivityOnSaveInstanceState() {
+ public void testCallActivityOnSaveInstanceState() throws Throwable {
final Bundle bundle = new Bundle();
mActivity.setOnSaveInstanceState(false);
- mInstrumentation.callActivityOnSaveInstanceState(mActivity, bundle);
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ mInstrumentation.callActivityOnSaveInstanceState(mActivity, bundle);
+ }
+ });
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnSaveInstanceState());
@@ -604,18 +609,6 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "callActivityOnDestroy",
- args = {Activity.class}
- )
- public void testCallActivityOnDestroy() throws Exception {
- mActivity.setOnDestroyCalled(false);
- mInstrumentation.callActivityOnDestroy(mActivity);
- mInstrumentation.waitForIdleSync();
- assertTrue(mActivity.isOnDestroyCalled());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "sendKeyDownUpSync",
args = {int.class}
)
@@ -849,6 +842,10 @@
}
@Override
+ public void alwaysReadCloseOnTouchAttr() {
+ }
+
+ @Override
public View peekDecorView() {
return null;
}
@@ -942,6 +939,11 @@
}
@Override
+ public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
+ return false;
+ }
+
+ @Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return false;
}
@@ -952,17 +954,26 @@
}
@Override
+ public boolean superDispatchGenericMotionEvent(MotionEvent event) {
+ return false;
+ }
+
+ @Override
public void takeKeyEvents(boolean get) {
}
@Override
public void togglePanel(int featureId, KeyEvent event) {
}
-
+
+ @Override
+ public void invalidatePanelMenu(int featureId) {
+ }
+
@Override
public void takeSurface(SurfaceHolder.Callback2 callback) {
}
-
+
@Override
public void takeInputQueue(InputQueue.Callback queue) {
}
diff --git a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
index efb5413..189a83f 100644
--- a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
@@ -112,7 +112,7 @@
})
public void testStartActivity() throws InterruptedException {
LocalActivityManagerTestHelper.setResult(this);
- setupActivity(LocalActivityManagerTestHelper.ACTION_START_ACTIIVTY);
+ setupActivity(LocalActivityManagerTestHelper.ACTION_START_ACTIVITY);
waitForResult();
}
diff --git a/tests/tests/app/src/android/app/cts/ServiceTest.java b/tests/tests/app/src/android/app/cts/ServiceTest.java
index 7f6fe94..0b2b767 100644
--- a/tests/tests/app/src/android/app/cts/ServiceTest.java
+++ b/tests/tests/app/src/android/app/cts/ServiceTest.java
@@ -16,6 +16,11 @@
package android.app.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
@@ -27,10 +32,6 @@
import android.os.Parcel;
import android.os.RemoteException;
import android.test.suitebuilder.annotation.MediumTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
@TestTargetClass(Service.class)
public class ServiceTest extends ActivityTestsBase {
@@ -49,8 +50,8 @@
private Intent mLocalService;
private Intent mLocalDeniedService;
private Intent mLocalGrantedService;
- private Intent mLocalServiceGranted;
- private Intent mLocalServiceDenied;
+ private Intent mLocalService_ApplicationHasPermission;
+ private Intent mLocalService_ApplicationDoesNotHavePermission;
private IBinder mStateReceiver;
@@ -317,8 +318,8 @@
mLocalService = new Intent(mContext, LocalService.class);
mLocalDeniedService = new Intent(mContext, LocalDeniedService.class);
mLocalGrantedService = new Intent(mContext, LocalGrantedService.class);
- mLocalServiceGranted = new Intent(LocalService.SERVICE_LOCAL_GRANTED);
- mLocalServiceDenied = new Intent(LocalService.SERVICE_LOCAL_DENIED);
+ mLocalService_ApplicationHasPermission = new Intent(LocalService.SERVICE_LOCAL_GRANTED);
+ mLocalService_ApplicationDoesNotHavePermission = new Intent(LocalService.SERVICE_LOCAL_DENIED);
mStateReceiver = new MockBinder();
}
@@ -388,7 +389,7 @@
super.tearDown();
mContext.stopService(mLocalService);
mContext.stopService(mLocalGrantedService);
- mContext.stopService(mLocalServiceGranted);
+ mContext.stopService(mLocalService_ApplicationHasPermission);
}
@TestTargets({
@@ -634,8 +635,9 @@
)
})
@MediumTest
- public void testLocalStartClassPermissionGranted() throws Exception {
+ public void testLocalStartClassPermissions() throws Exception {
startExpectResult(mLocalGrantedService);
+ startExpectResult(mLocalDeniedService);
}
@TestTargets({
@@ -666,8 +668,9 @@
)
})
@MediumTest
- public void testLocalStartActionPermissionGranted() throws Exception {
- startExpectResult(mLocalServiceGranted);
+ public void testLocalStartActionPermissions() throws Exception {
+ startExpectResult(mLocalService_ApplicationHasPermission);
+ startExpectResult(mLocalService_ApplicationDoesNotHavePermission);
}
@TestTargets({
@@ -698,8 +701,9 @@
)
})
@MediumTest
- public void testLocalBindClassPermissionGranted() throws Exception {
+ public void testLocalBindClassPermissions() throws Exception {
bindExpectResult(mLocalGrantedService);
+ bindExpectResult(mLocalDeniedService);
}
@TestTargets({
@@ -730,8 +734,9 @@
)
})
@MediumTest
- public void testLocalBindActionPermissionGranted() throws Exception {
- bindExpectResult(mLocalServiceGranted);
+ public void testLocalBindActionPermissions() throws Exception {
+ bindExpectResult(mLocalService_ApplicationHasPermission);
+ bindExpectResult(mLocalService_ApplicationDoesNotHavePermission);
}
@TestTargets({
@@ -795,135 +800,7 @@
})
@MediumTest
public void testLocalBindAutoActionPermissionGranted() throws Exception {
- bindAutoExpectResult(mLocalServiceGranted);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onStart",
- args = {android.content.Intent.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDestroy",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onBind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onRebind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onUnbind",
- args = {android.content.Intent.class}
- )
- })
- @MediumTest
- public void testLocalStartClassPermissionDenied() throws Exception {
- startExpectNoPermission(mLocalDeniedService);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onStart",
- args = {android.content.Intent.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDestroy",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onBind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onRebind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onUnbind",
- args = {android.content.Intent.class}
- )
- })
- @MediumTest
- public void testLocalStartActionPermissionDenied() throws Exception {
- startExpectNoPermission(mLocalServiceDenied);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onStart",
- args = {android.content.Intent.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDestroy",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onBind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onRebind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onUnbind",
- args = {android.content.Intent.class}
- )
- })
- @MediumTest
- public void testLocalBindClassPermissionDenied() throws Exception {
- bindExpectNoPermission(mLocalDeniedService);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onStart",
- args = {android.content.Intent.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDestroy",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onBind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onRebind",
- args = {android.content.Intent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onUnbind",
- args = {android.content.Intent.class}
- )
- })
- @MediumTest
- public void testLocalBindActionPermissionDenied() throws Exception {
- bindExpectNoPermission(mLocalServiceDenied);
+ bindAutoExpectResult(mLocalService_ApplicationHasPermission);
}
@TestTargets({
@@ -957,7 +834,7 @@
public void testLocalUnbindTwice() throws Exception {
EmptyConnection conn = new EmptyConnection();
mContext.bindService(
- mLocalServiceGranted, conn, 0);
+ mLocalService_ApplicationHasPermission, conn, 0);
mContext.unbindService(conn);
try {
mContext.unbindService(conn);
diff --git a/tests/tests/app/src/android/app/cts/TabActivityTest.java b/tests/tests/app/src/android/app/cts/TabActivityTest.java
index 649a56d..920ec11 100644
--- a/tests/tests/app/src/android/app/cts/TabActivityTest.java
+++ b/tests/tests/app/src/android/app/cts/TabActivityTest.java
@@ -30,7 +30,6 @@
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.test.InstrumentationTestCase;
-import android.view.KeyEvent;
import android.widget.TabHost;
@TestTargetClass(TabActivity.class)
@@ -132,21 +131,6 @@
final TabHost tabHost = mActivity.getTabHost();
assertNotNull(tabHost);
assertNotNull(tabHost.getTabWidget());
-
- // Test onSaveInstanceState
- assertFalse(mActivity.isOnSaveInstanceStateCalled);
- final Intent embedded = new Intent(mInstrumentation.getTargetContext(),
- ChildTabActivity.class);
- mActivity.startActivity(embedded);
- mInstrumentation.waitForIdleSync();
- assertTrue(mActivity.isOnSaveInstanceStateCalled);
-
- // Test onRestoreInstanceState
- sendKeys(KeyEvent.KEYCODE_BACK);
- mInstrumentation.waitForIdleSync();
- assertFalse(MockTabActivity.isOnRestoreInstanceStateCalled);
- OrientationTestUtils.toggleOrientationSync(mActivity, mInstrumentation);
- assertTrue(MockTabActivity.isOnRestoreInstanceStateCalled);
}
@TestTargetNew(
diff --git a/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java b/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
index 01f1ec9..417d046 100644
--- a/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
@@ -26,7 +26,6 @@
import android.content.Context;
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
-import android.view.KeyEvent;
import android.widget.TimePicker;
/**
@@ -59,7 +58,6 @@
super.setUp();
mContext = getInstrumentation().getContext();
- mActivity = getActivity();
mOnTimeSetListener = new OnTimeSetListener(){
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCallbackHour = hourOfDay;
@@ -131,7 +129,7 @@
)
public void testOnTimeChanged() throws Throwable {
final int minute = 34;
- popDialog(DialogStubActivity.TEST_TIMEPICKERDIALOG);
+ startDialogActivity(DialogStubActivity.TEST_TIMEPICKERDIALOG);
final TimePickerDialog d = (TimePickerDialog) mActivity.getDialog();
runTestOnUiThread(new Runnable() {
@@ -181,14 +179,7 @@
assertFalse(b2.getBoolean(IS_24_HOUR));
}
- private void popDialog(int index) {
- assertTrue(index > 0);
-
- while (index != 0) {
- sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
- index--;
- }
-
- sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+ private void startDialogActivity(int dialogNumber) {
+ mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
}
}
diff --git a/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java b/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java
index 7fb403e..62d8724 100644
--- a/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java
+++ b/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java
@@ -77,33 +77,6 @@
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "abortBroadcast",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "clearAbortBroadcast",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getAbortBroadcast",
- args = {}
- )
- })
- public void testAccessAbortBroadcast() {
- MockReceiverInternal mockReceiver = new MockReceiverInternal();
-
- mockReceiver.abortBroadcast();
- assertTrue(mockReceiver.getAbortBroadcast());
-
- mockReceiver.clearAbortBroadcast();
- assertFalse(mockReceiver.getAbortBroadcast());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getDebugUnregister",
args = {}
),
@@ -377,7 +350,7 @@
static class MyServiceConnection implements ServiceConnection {
private boolean serviceConnected;
-
+
public synchronized void onServiceConnected(ComponentName name, IBinder service) {
serviceConnected = true;
notifyAll();
@@ -385,7 +358,7 @@
public synchronized void onServiceDisconnected(ComponentName name) {
}
-
+
public synchronized boolean waitForService(long timeout) {
if (!serviceConnected) {
try {
diff --git a/tests/tests/content/src/android/content/cts/ContentProviderTest.java b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
index 0824e84..eabd470 100644
--- a/tests/tests/content/src/android/content/cts/ContentProviderTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
@@ -394,6 +394,15 @@
public Bundle call(String method, String request, Bundle args) {
return null;
}
+
+ public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException {
+ return null;
+ }
+
+ public AssetFileDescriptor openTypedAssetFile(Uri url, String mimeType, Bundle opts)
+ throws RemoteException, FileNotFoundException {
+ return null;
+ }
};
assertNull(ContentProvider.coerceToLocalContentProvider(iContentProvider));
}
diff --git a/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java b/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java
index ecad3e4..1cc4cfb 100644
--- a/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java
+++ b/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java
@@ -93,7 +93,7 @@
}
private void addAccountAndVerifyInitSync(Account account, String password,
- String authority, int latchTimeoutMs) {
+ String authority, int latchTimeoutMs, int accountIndex) {
CountDownLatch latch = setNewLatch(new CountDownLatch(1));
@@ -109,7 +109,7 @@
assertFalse(getMockSyncAdapter().isStartSync());
assertFalse(getMockSyncAdapter().isCancelSync());
assertTrue(getMockSyncAdapter().isInitialized());
- assertEquals(account, getMockSyncAdapter().getAccount());
+ assertEquals(account, getMockSyncAdapter().getAccounts().get(accountIndex));
assertEquals(authority, getMockSyncAdapter().getAuthority());
}
@@ -159,8 +159,11 @@
ContentResolver.setMasterSyncAutomatically(false);
assertEquals(false, ContentResolver.getMasterSyncAutomatically());
- addAccountAndVerifyInitSync(ACCOUNT, MockAccountAuthenticator.ACCOUNT_PASSWORD, AUTHORITY,
- LATCH_TIMEOUT_MS);
+ addAccountAndVerifyInitSync(ACCOUNT,
+ MockAccountAuthenticator.ACCOUNT_PASSWORD,
+ AUTHORITY,
+ LATCH_TIMEOUT_MS,
+ 0);
getMockSyncAdapter().clearData();
@@ -174,7 +177,7 @@
assertTrue(getMockSyncAdapter().isStartSync());
assertFalse(getMockSyncAdapter().isCancelSync());
assertFalse(getMockSyncAdapter().isInitialized());
- assertEquals(ACCOUNT, getMockSyncAdapter().getAccount());
+ assertEquals(ACCOUNT, getMockSyncAdapter().getAccounts().get(0));
assertEquals(AUTHORITY, getMockSyncAdapter().getAuthority());
}
@@ -188,8 +191,11 @@
ContentResolver.setMasterSyncAutomatically(false);
assertEquals(false, ContentResolver.getMasterSyncAutomatically());
- addAccountAndVerifyInitSync(ACCOUNT, MockAccountAuthenticator.ACCOUNT_PASSWORD, AUTHORITY,
- LATCH_TIMEOUT_MS);
+ addAccountAndVerifyInitSync(ACCOUNT,
+ MockAccountAuthenticator.ACCOUNT_PASSWORD,
+ AUTHORITY,
+ LATCH_TIMEOUT_MS,
+ 0);
getMockSyncAdapter().clearData();
@@ -224,6 +230,10 @@
* Test if we can set and get the SyncAutomatically switch for an account
*/
public void testGetAndSetSyncAutomatically() {
+ try {
+ Thread.sleep(5000);
+ } catch (InterruptedException e) {
+ }
// Prevent auto sync
ContentResolver.setMasterSyncAutomatically(false);
assertEquals(false, ContentResolver.getMasterSyncAutomatically());
@@ -316,4 +326,35 @@
//expected.
}
}
+
+ /**
+ * Test to verify that a SyncAdapter is called on all the accounts accounts
+ */
+ public void testCallMultipleAccounts() {
+ // Prevent auto sync
+ ContentResolver.setMasterSyncAutomatically(false);
+ assertEquals(false, ContentResolver.getMasterSyncAutomatically());
+
+ addAccountAndVerifyInitSync(ACCOUNT,
+ MockAccountAuthenticator.ACCOUNT_PASSWORD,
+ AUTHORITY,
+ LATCH_TIMEOUT_MS,
+ 0);
+
+ getMockSyncAdapter().clearData();
+
+ setIsSyncable(ACCOUNT, AUTHORITY, true);
+ cancelSync(ACCOUNT, AUTHORITY, LATCH_TIMEOUT_MS);
+
+ getMockSyncAdapter().clearData();
+
+ requestSync(null /* all accounts */, AUTHORITY, LATCH_TIMEOUT_MS);
+
+ assertTrue(getMockSyncAdapter().isStartSync());
+ assertFalse(getMockSyncAdapter().isCancelSync());
+ assertFalse(getMockSyncAdapter().isInitialized());
+ assertEquals(ACCOUNT, getMockSyncAdapter().getAccounts().get(0));
+ assertEquals(AUTHORITY, getMockSyncAdapter().getAuthority());
+
+ }
}
diff --git a/tests/tests/content/src/android/content/cts/ContextTest.java b/tests/tests/content/src/android/content/cts/ContextTest.java
index c2a27ae..9661a1d 100644
--- a/tests/tests/content/src/android/content/cts/ContextTest.java
+++ b/tests/tests/content/src/android/content/cts/ContextTest.java
@@ -174,7 +174,6 @@
args = {android.util.AttributeSet.class, int[].class}
)
})
- @ToBeFixed(bug=" ", explanation = "Wrong resource ID can not result in a exception.")
public void testObtainStyledAttributes() {
// Test obtainStyledAttributes(int[])
TypedArray testTypedArray = mContext
@@ -207,17 +206,18 @@
testTypedArray.recycle();
// Test obtainStyledAttributes(AttributeSet, int[])
+ int[] attrs = android.R.styleable.DatePicker;
testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout),
- android.R.styleable.DatePicker);
+ attrs);
assertNotNull(testTypedArray);
- assertEquals(2, testTypedArray.length());
+ assertEquals(attrs.length, testTypedArray.length());
testTypedArray.recycle();
// Test obtainStyledAttributes(AttributeSet, int[], int, int)
testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout),
- android.R.styleable.DatePicker, 0, 0);
+ attrs, 0, 0);
assertNotNull(testTypedArray);
- assertEquals(2, testTypedArray.length());
+ assertEquals(attrs.length, testTypedArray.length());
testTypedArray.recycle();
}
diff --git a/tests/tests/content/src/android/content/cts/IntentTest.java b/tests/tests/content/src/android/content/cts/IntentTest.java
index 15400be..995c668 100644
--- a/tests/tests/content/src/android/content/cts/IntentTest.java
+++ b/tests/tests/content/src/android/content/cts/IntentTest.java
@@ -16,11 +16,13 @@
package android.content.cts;
-import java.io.IOException;
-import java.io.Serializable;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Set;
+import com.android.internal.app.ResolverActivity;
+import com.android.internal.util.XmlUtils;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
@@ -45,13 +47,11 @@
import android.util.AttributeSet;
import android.util.Xml;
-import com.android.internal.app.ResolverActivity;
-import com.android.internal.util.XmlUtils;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Set;
@TestTargetClass(Intent.class)
public class IntentTest extends AndroidTestCase {
@@ -1746,7 +1746,7 @@
assertEquals(Intent.FILL_IN_DATA, destIntent.fillIn(sourceIntent, Intent.FILL_IN_DATA));
assertEquals(TEST_URI, destIntent.getData());
}
-
+
/**
* Test that fillIn copies data type.
*/
@@ -2087,8 +2087,6 @@
assertFalse(mIntent.filterEquals(target));
mIntent.addCategory(TEST_CATEGORY + "test");
assertFalse(mIntent.filterEquals(target));
- mIntent.addCategory(null);
- assertFalse(mIntent.filterEquals(target));
mIntent.addCategory(TEST_CATEGORY);
assertFalse(mIntent.filterEquals(target));
}
diff --git a/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java b/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java
index bc81c4c..004fa9e 100644
--- a/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java
+++ b/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java
@@ -29,6 +29,7 @@
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
+import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.test.AndroidTestCase;
import android.util.Log;
@@ -317,4 +318,30 @@
}
}
+ public void testModeMultiProcess() {
+ // Pre-load it.
+ mContext.getSharedPreferences("multiprocessTest", 0);
+
+ final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
+ try {
+ StrictMode.ThreadPolicy diskReadDeath =
+ new StrictMode.ThreadPolicy.Builder().detectDiskReads().penaltyDeath().build();
+ StrictMode.setThreadPolicy(diskReadDeath);
+
+ // This shouldn't hit disk. (it was already pre-loaded above)
+ mContext.getSharedPreferences("multiprocessTest", 0);
+
+ boolean didRead = false;
+ // This SHOULD hit disk. (multi-process flag is set)
+ try {
+ mContext.getSharedPreferences("multiprocessTest", Context.MODE_MULTI_PROCESS);
+ fail(); // we shouldn't get here.
+ } catch (StrictMode.StrictModeViolation e) {
+ didRead = true;
+ }
+ assertTrue(didRead);
+ } finally {
+ StrictMode.setThreadPolicy(oldPolicy);
+ }
+ }
}
diff --git a/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java b/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java
index 3f0c4ae..512aa7a 100644
--- a/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java
@@ -181,6 +181,24 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
+ method = "isEnabled",
+ args = {}
+ )
+ public void testIsEnabled() {
+ mComponentInfo = new ComponentInfo();
+ mComponentInfo.applicationInfo = new ApplicationInfo();
+ assertTrue(mComponentInfo.isEnabled());
+
+ mComponentInfo.enabled = false;
+ assertFalse(mComponentInfo.isEnabled());
+
+ mComponentInfo.enabled = true;
+ mComponentInfo.applicationInfo.enabled = false;
+ assertFalse(mComponentInfo.isEnabled());
+ }
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
method = "dumpFront",
args = {android.util.Printer.class, java.lang.String.class}
)
diff --git a/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java b/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java
index 1ff3f49..de9f0e3 100644
--- a/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java
+++ b/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java
@@ -16,80 +16,252 @@
package android.content.res.cts;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import android.content.res.AssetFileDescriptor;
-import android.os.ParcelFileDescriptor;
-import android.test.AndroidTestCase;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
+import android.content.res.AssetFileDescriptor;
+import android.os.ParcelFileDescriptor;
+import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
@TestTargetClass(AssetFileDescriptor.AutoCloseInputStream.class)
public class AssetFileDescriptor_AutoCloseInputStreamTest extends AndroidTestCase {
private static final int FILE_END = -1;
- private static final int FILE_LENGTH = 10;
private static final String FILE_NAME = "testAssertFileDescriptorAutoCloseInputStream";
private static final byte[] FILE_DATA = new byte[] {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
};
- private static final int OFFSET = 0;
- private static final int READ_LENGTH = 1;
+ private static final int FILE_LENGTH = FILE_DATA.length;
private File mFile;
- private AssetFileDescriptor mAssetFileDes;
+ private AssetFileDescriptor mFd;
+ private AssetFileDescriptor.AutoCloseInputStream mInput;
@Override
protected void setUp() throws Exception {
super.setUp();
mFile = new File(getContext().getFilesDir(), FILE_NAME);
- mFile.createNewFile();
+ FileOutputStream outputStream = new FileOutputStream(mFile);
+ outputStream.write(FILE_DATA);
+ outputStream.close();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
- // As {@link AssetFileDescripter#createOutputStream()}
- // and {@link AssetFileDescripter#createInputStream()} doc,
- // the input and output stream will be auto closed when the AssetFileDescriptor closed.
- // Here is no need to close AutoCloseInputStream, as AssetFileDescriptor will do it for us.
- if (mAssetFileDes != null) {
- mAssetFileDes.close();
+ if (mFd != null) {
+ mFd.close();
+ mFd = null;
}
- getContext().deleteFile(FILE_NAME);
+ mFile.delete();
}
- /*
- * Test AutoInputStream life circle.
- * Test point:
- * 1. Test AutoInputStream read what we write into file.
- */
@TestTargets({
@TestTargetNew(
- level = TestLevel.COMPLETE,
+ level = TestLevel.PARTIAL_COMPLETE,
method = "AssetFileDescriptor.AutoCloseInputStream",
args = {AssetFileDescriptor.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
+ method = "skip",
+ args = {long.class}
+ )
+ })
+ public void testSkip() throws IOException {
+ openInput(0, FILE_LENGTH);
+ assertEquals(FILE_DATA[0], mInput.read());
+ assertEquals(0, mInput.skip(0));
+ assertEquals(FILE_DATA[1], mInput.read());
+ assertEquals(3, mInput.skip(3));
+ assertEquals(FILE_DATA[5], mInput.read());
+ assertEquals(3, mInput.skip(10));
+ assertEquals(FILE_END, mInput.read());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
method = "read",
args = {}
+ )
+ })
+ public void testRead() throws IOException {
+ openInput(0, FILE_LENGTH);
+ for (int i = 0; i < FILE_LENGTH; i++) {
+ assertEquals(FILE_DATA[i], mInput.read());
+ }
+ assertEquals(FILE_END, mInput.read());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
),
@TestTargetNew(
- level = TestLevel.COMPLETE,
+ level = TestLevel.PARTIAL_COMPLETE,
method = "read",
- args = {byte[].class, int.class, int.class}
+ args = {}
+ )
+ })
+ public void testReadPartial() throws IOException {
+ long len = 6;
+ openInput(0, len);
+ for (int i = 0; i < len; i++) {
+ assertEquals(FILE_DATA[i], mInput.read());
+ }
+ assertEquals(FILE_END, mInput.read());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
),
@TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {byte[].class}
+ level = TestLevel.COMPLETE,
+ method = "read",
+ args = {byte[].class, int.class, int.class}
+ )
+ })
+ public void testReadBufferLen() throws IOException {
+ openInput(0, FILE_LENGTH);
+ byte[] buf = new byte[FILE_LENGTH];
+ assertEquals(3, mInput.read(buf, 0, 3));
+ assertEquals(3, mInput.read(buf, 3, 3));
+ assertEquals(3, mInput.read(buf, 6, 4));
+ MoreAsserts.assertEquals(FILE_DATA, buf);
+ assertEquals(FILE_END, mInput.read(buf, 0, 4));
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
),
@TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "read",
+ args = {byte[].class}
+ )
+ })
+ public void testReadBuffer() throws IOException {
+ openInput(0, FILE_LENGTH);
+ byte[] buf = new byte[6];
+ assertEquals(6, mInput.read(buf));
+ assertEquals(FILE_DATA[0], buf[0]);
+ assertEquals(3, mInput.read(buf));
+ assertEquals(FILE_DATA[6], buf[0]);
+ assertEquals(FILE_END, mInput.read(buf));
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "read",
+ args = {byte[].class}
+ )
+ })
+ public void testReadBufferPartial() throws IOException {
+ long len = 8;
+ openInput(0, len);
+ byte[] buf = new byte[6];
+ assertEquals(6, mInput.read(buf));
+ assertEquals(FILE_DATA[0], buf[0]);
+ assertEquals(2, mInput.read(buf));
+ assertEquals(FILE_DATA[6], buf[0]);
+ assertEquals(FILE_END, mInput.read(buf));
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "available",
+ args = {}
+ )
+ })
+ public void testAvailableRead() throws IOException {
+ openInput(0, FILE_LENGTH);
+ assertEquals(FILE_LENGTH, mInput.available());
+ assertEquals(FILE_DATA[0], mInput.read());
+ assertEquals(FILE_LENGTH -1 , mInput.available());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "available",
+ args = {}
+ )
+ })
+ public void testAvailableReadBuffer() throws IOException {
+ openInput(0, FILE_LENGTH);
+ byte[] buf = new byte[3];
+ assertEquals(FILE_LENGTH, mInput.available());
+ assertEquals(buf.length, mInput.read(buf));
+ assertEquals(FILE_LENGTH - buf.length, mInput.available());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "available",
+ args = {}
+ )
+ })
+ public void testAvailableReadBufferLen() throws IOException {
+ openInput(0, FILE_LENGTH);
+ byte[] buf = new byte[3];
+ assertEquals(FILE_LENGTH, mInput.available());
+ assertEquals(2, mInput.read(buf, 0, 2));
+ assertEquals(FILE_LENGTH - 2, mInput.available());
+ }
+
+ /*
+ * Tests that AutoInputStream doesn't support mark().
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "AssetFileDescriptor.AutoCloseInputStream",
+ args = {AssetFileDescriptor.class}
+ ),
+ @TestTargetNew(
level = TestLevel.COMPLETE,
method = "mark",
args = {int.class}
@@ -103,57 +275,27 @@
level = TestLevel.COMPLETE,
method = "markSupported",
args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "available",
- args = {}
)
})
- public void testInputStream() throws IOException {
- initAssetFileDescriptor();
- FileOutputStream outputStream = null;
- outputStream = mAssetFileDes.createOutputStream();
- outputStream.write(FILE_DATA);
- mAssetFileDes.close();
-
- initAssetFileDescriptor();
- AssetFileDescriptor.AutoCloseInputStream inputStream = null;
- inputStream = new AssetFileDescriptor.AutoCloseInputStream(mAssetFileDes);
- assertEquals(FILE_LENGTH, inputStream.available());
- assertEquals(FILE_DATA[0], inputStream.read());
- byte[] readFromFile = new byte[2];
- int readBytes = inputStream.read(readFromFile);
- assertTrue(FILE_END != readBytes);
- while (readBytes < readFromFile.length) {
- readFromFile[readBytes] = (byte) inputStream.read();
- readBytes++;
- }
- assertEquals(FILE_DATA[1], readFromFile[0]);
- assertEquals(FILE_DATA[2], readFromFile[1]);
- inputStream.mark(FILE_LENGTH);
- assertEquals(5, inputStream.skip(5));
- readBytes = inputStream.read(readFromFile, OFFSET, READ_LENGTH);
- while (readBytes < READ_LENGTH) {
- readFromFile[readBytes] = (byte) inputStream.read();
- readBytes++;
- }
- assertEquals(FILE_DATA[8], readFromFile[0]);
- assertEquals(FILE_END, inputStream.read());
- inputStream.reset();
- assertEquals(FILE_END, inputStream.read(readFromFile));
- assertEquals(FILE_END, inputStream.read(readFromFile, 0, 1));
- assertFalse(inputStream.markSupported());
+ public void testMark() throws IOException {
+ openInput(0, FILE_LENGTH);
+ assertFalse(mInput.markSupported());
+ assertEquals(FILE_DATA[0], mInput.read());
+ mInput.mark(FILE_LENGTH); // should do nothing
+ assertEquals(FILE_DATA[1], mInput.read());
+ mInput.reset(); // should do nothing
+ assertEquals(FILE_DATA[2], mInput.read());
}
- private void initAssetFileDescriptor() throws FileNotFoundException {
+ private void openInput(long startOffset, long length)
+ throws IOException {
+ if (mFd != null) {
+ mFd.close();
+ mFd = null;
+ }
ParcelFileDescriptor fd =
- ParcelFileDescriptor.open(mFile, ParcelFileDescriptor.MODE_READ_WRITE);
- mAssetFileDes = new AssetFileDescriptor(fd, 0, FILE_LENGTH);
+ ParcelFileDescriptor.open(mFile, ParcelFileDescriptor.MODE_READ_WRITE);
+ mFd = new AssetFileDescriptor(fd, startOffset, length);
+ mInput = new AssetFileDescriptor.AutoCloseInputStream(mFd);
}
}
diff --git a/tests/tests/database/src/android/database/cts/AbstractCursorTest.java b/tests/tests/database/src/android/database/cts/AbstractCursorTest.java
index 47c52ba..8f5fead 100644
--- a/tests/tests/database/src/android/database/cts/AbstractCursorTest.java
+++ b/tests/tests/database/src/android/database/cts/AbstractCursorTest.java
@@ -453,16 +453,9 @@
method = "getUpdatedField",
args = {int.class}
)
- @ToBeFixed(bug = "1569265", explanation = "All other updating-related methods are 'hide' and "
- + "'deprecated.")
public void testGetUpdatedField() {
mTestAbstractCursor.moveToFirst();
- try {
- assertEquals("hello", mTestAbstractCursor.getUpdatedField(0));
- fail("getUpdatedField should throws a NullPointerException here.");
- } catch (NullPointerException e) {
- // expected
- }
+ assertNull(mTestAbstractCursor.getUpdatedField(0));
}
@TestTargetNew(
@@ -746,12 +739,6 @@
return mRows.length;
}
- @Deprecated
- @Override
- public boolean deleteRow() {
- return false;
- }
-
@Override
public String[] getColumnNames() {
return mColumnNames;
diff --git a/tests/tests/database/src/android/database/cts/CursorWrapperTest.java b/tests/tests/database/src/android/database/cts/CursorWrapperTest.java
index dba9784..df90237 100644
--- a/tests/tests/database/src/android/database/cts/CursorWrapperTest.java
+++ b/tests/tests/database/src/android/database/cts/CursorWrapperTest.java
@@ -750,7 +750,17 @@
private void setupDatabase() {
File dbDir = getContext().getDir("tests", Context.MODE_PRIVATE);
- mDatabaseFile = new File(dbDir, "database_test.db");
+ /* don't use the same database name as the one in super class
+ * this class's setUp() method deletes a database file just opened by super.setUp().
+ * that can cause corruption in database in the following situation:
+ * super.setUp() creates the database, inserts some data into it.
+ * this class setUp() deletes just the database file but not the associated
+ * database files such as wal, shm files.
+ * solution is to have this class delete the whole database directory.
+ * better yet, this class shouldn't extend DatabaseCursortest at all.
+ * TODO: fix this bogus cts class hierarchy
+ */
+ mDatabaseFile = new File(dbDir, "cursor_test.db");
if (mDatabaseFile.exists()) {
mDatabaseFile.delete();
}
diff --git a/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java b/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java
index 4d0c6ac..7a8657d 100644
--- a/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java
+++ b/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java
@@ -103,43 +103,6 @@
}
@MediumTest
- public void testCursorUpdate() {
- mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, d INTEGER, s INTEGER);");
- for (int i = 0; i < 20; i++) {
- mDatabase.execSQL("INSERT INTO test (d, s) VALUES (" + i + "," + i % 2 + ");");
- }
-
- Cursor testCursor = getTestCursor(mDatabase.query("test", null, "s = 0", null, null, null,
- null));
-
- int dCol = testCursor.getColumnIndexOrThrow("d");
- int sCol = testCursor.getColumnIndexOrThrow("s");
-
- int count = 0;
- while (testCursor.moveToNext()) {
- assertTrue(testCursor.updateInt(dCol, 3));
- count++;
- }
- assertEquals(10, count);
-
- assertTrue(testCursor.commitUpdates());
-
- assertTrue(testCursor.requery());
-
- count = 0;
- while (testCursor.moveToNext()) {
- assertEquals(3, testCursor.getInt(dCol));
- count++;
- }
-
- assertEquals(10, count);
- assertTrue(testCursor.moveToFirst());
- assertTrue(testCursor.deleteRow());
- assertEquals(9, testCursor.getCount());
- testCursor.close();
- }
-
- @MediumTest
public void testBlob() throws Exception {
// create table
mDatabase.execSQL(
@@ -178,23 +141,6 @@
assertEquals(s, testCursor.getString(sCol));
assertEquals((double) d, testCursor.getDouble(dCol));
assertEquals((long) l, testCursor.getLong(lCol));
-
- // new byte[]
- byte[] newblob = new byte[1000];
- value = 98;
- Arrays.fill(blob, value);
-
- testCursor.updateBlob(bCol, newblob);
- cBlob = testCursor.getBlob(bCol);
- assertTrue(Arrays.equals(newblob, cBlob));
-
- // commit
- assertTrue(testCursor.commitUpdates());
- assertTrue(testCursor.requery());
- testCursor.moveToNext();
- cBlob = testCursor.getBlob(bCol);
- assertTrue(Arrays.equals(newblob, cBlob));
- testCursor.close();
}
@MediumTest
diff --git a/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java b/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java
index c47b65b..ae2a204 100644
--- a/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java
+++ b/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java
@@ -33,11 +33,15 @@
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import android.os.Parcel;
+import android.os.ParcelFileDescriptor;
import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.PrintStream;
@TestTargetClass(android.database.DatabaseUtils.class)
@@ -64,6 +68,8 @@
assertNotNull(mDatabase);
mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY, " +
"name TEXT, age INTEGER, address TEXT);");
+ mDatabase.execSQL(
+ "CREATE TABLE blob_test (_id INTEGER PRIMARY KEY, name TEXT, data BLOB)");
}
@Override
@@ -769,11 +775,98 @@
args = new String[] { "1000" }; // NO people can be older than this.
try {
- DatabaseUtils.stringForQuery(statement, args);
+ DatabaseUtils.blobFileDescriptorForQuery(statement, args);
fail("should throw SQLiteDoneException");
} catch (SQLiteDoneException e) {
// expected
}
statement.close();
}
-}
\ No newline at end of file
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "blobFileDescriptorForQuery",
+ args = {android.database.sqlite.SQLiteDatabase.class, java.lang.String.class,
+ java.lang.String[].class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "blobFileDescriptorForQuery",
+ args = {android.database.sqlite.SQLiteStatement.class, java.lang.String[].class}
+ )
+ })
+ public void testBlobFileDescriptorForQuery() throws Exception {
+ String data1 = "5300FEFF";
+ String data2 = "DECAFBAD";
+ mDatabase.execSQL("INSERT INTO blob_test (name, data) VALUES ('Mike', X'" + data1 + "')");
+
+ String query = "SELECT data FROM blob_test";
+ assertFileDescriptorContent(parseBlob(data1),
+ DatabaseUtils.blobFileDescriptorForQuery(mDatabase, query, null));
+
+ mDatabase.execSQL("INSERT INTO blob_test (name, data) VALUES ('Jack', X'" + data2 + "');");
+ query = "SELECT data FROM blob_test WHERE name = ?";
+ String[] args = new String[] { "Jack" };
+ assertFileDescriptorContent(parseBlob(data2),
+ DatabaseUtils.blobFileDescriptorForQuery(mDatabase, query, args));
+
+ args = new String[] { "No such name" };
+ try {
+ DatabaseUtils.stringForQuery(mDatabase, query, args);
+ fail("should throw SQLiteDoneException");
+ } catch (SQLiteDoneException e) {
+ // expected
+ }
+
+ query = "SELECT data FROM blob_test WHERE name = ?;";
+ SQLiteStatement statement = mDatabase.compileStatement(query);
+ args = new String[] { "Mike" };
+ assertFileDescriptorContent(parseBlob(data1),
+ DatabaseUtils.blobFileDescriptorForQuery(statement, args));
+
+ args = new String[] { "No such name" };
+ try {
+ DatabaseUtils.blobFileDescriptorForQuery(statement, args);
+ fail("should throw SQLiteDoneException");
+ } catch (SQLiteDoneException e) {
+ // expected
+ }
+ statement.close();
+ }
+
+ private static byte[] parseBlob(String src) {
+ int len = src.length();
+ byte[] result = new byte[len / 2];
+
+ for (int i = 0; i < len/2; i++) {
+ int val;
+ char c1 = src.charAt(i*2);
+ char c2 = src.charAt(i*2+1);
+ int val1 = Character.digit(c1, 16);
+ int val2 = Character.digit(c2, 16);
+ val = (val1 << 4) | val2;
+ result[i] = (byte)val;
+ }
+ return result;
+ }
+
+ private static void assertFileDescriptorContent(byte[] expected, ParcelFileDescriptor fd)
+ throws IOException {
+ assertInputStreamContent(expected, new ParcelFileDescriptor.AutoCloseInputStream(fd));
+ }
+
+ private static void assertInputStreamContent(byte[] expected, InputStream is)
+ throws IOException {
+ try {
+ byte[] observed = new byte[expected.length];
+ int count = is.read(observed);
+ assertEquals(expected.length, count);
+ assertEquals(-1, is.read());
+ MoreAsserts.assertEquals(expected, observed);
+ } finally {
+ is.close();
+ }
+ }
+
+}
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java
index ae5b9d4..c684a69 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java
@@ -24,6 +24,7 @@
import android.content.Context;
import android.database.AbstractCursor;
+import android.database.Cursor;
import android.database.CursorWindow;
import android.database.DataSetObserver;
import android.database.StaleDataException;
@@ -79,8 +80,8 @@
TEST_SQL, TABLE_NAME);
try {
new SQLiteCursor(mDatabase, cursorDriver, TABLE_NAME, null);
- fail("constructor didn't throw NullPointerException when SQLiteQuery is null");
- } catch (NullPointerException e) {
+ fail("constructor didn't throw IllegalArgumentException when SQLiteQuery is null");
+ } catch (IllegalArgumentException e) {
}
// get SQLiteCursor by querying database
@@ -221,6 +222,39 @@
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
+ method = "requery",
+ args = {}
+ )
+ })
+ public void testRequery2() {
+ mDatabase.disableWriteAheadLogging();
+ mDatabase.execSQL("create table testRequery2 (i int);");
+ mDatabase.execSQL("insert into testRequery2 values(1);");
+ mDatabase.execSQL("insert into testRequery2 values(2);");
+ Cursor c = mDatabase.rawQuery("select * from testRequery2 order by i", null);
+ assertEquals(2, c.getCount());
+ assertTrue(c.moveToFirst());
+ assertEquals(1, c.getInt(0));
+ assertTrue(c.moveToNext());
+ assertEquals(2, c.getInt(0));
+ // add more data to the table and requery
+ mDatabase.execSQL("insert into testRequery2 values(3);");
+ assertTrue(c.requery());
+ assertEquals(3, c.getCount());
+ assertTrue(c.moveToFirst());
+ assertEquals(1, c.getInt(0));
+ assertTrue(c.moveToNext());
+ assertEquals(2, c.getInt(0));
+ assertTrue(c.moveToNext());
+ assertEquals(3, c.getInt(0));
+ // close the database and see if requery throws an exception
+ mDatabase.close();
+ assertFalse(c.requery());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
method = "getColumnIndex",
args = {java.lang.String.class}
),
@@ -242,16 +276,6 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "getDatabase",
- args = {}
- )
- public void testGetDatabase() {
- SQLiteCursor cursor = getCursor();
- assertSame(mDatabase, cursor.getDatabase());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "setSelectionArguments",
args = {java.lang.String[].class}
)
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
index 7a18cd8..4d2724a 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
@@ -18,10 +18,7 @@
import java.io.File;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
import android.content.ContentValues;
import android.database.Cursor;
@@ -37,6 +34,8 @@
import android.database.sqlite.SQLiteTransactionListener;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.SmallTest;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestLevel;
@@ -139,17 +138,8 @@
assertNotNull(db);
db.close();
- try {
- // do not allow to create file in the directory
- SQLiteDatabase.openDatabase("/system/database.db", factory,
- SQLiteDatabase.CREATE_IF_NECESSARY);
- fail("didn't throw SQLiteException when do not allow to create database file");
- } catch (SQLiteException e) {
- } finally {
- db.close();
- }
-
File dbFile = new File(mDatabaseDir, "database_test12345678.db");
+ dbFile.delete();
assertFalse(dbFile.exists());
db = SQLiteDatabase.openOrCreateDatabase(dbFile.getPath(), factory);
assertNotNull(db);
@@ -338,88 +328,6 @@
}
}
- @SuppressWarnings("deprecation")
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test getSyncedTables()",
- method = "getSyncedTables",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test markTableSyncable(String, String)",
- method = "markTableSyncable",
- args = {java.lang.String.class, java.lang.String.class}
- )
- })
- public void testGetSyncedTables() {
- mDatabase.execSQL("CREATE TABLE people (_id INTEGER PRIMARY KEY, name TEXT, "
- + "_sync_dirty INTEGER);");
- mDatabase.execSQL("CREATE TABLE _delete_people (name TEXT);");
- Map<String, String> tableMap = mDatabase.getSyncedTables();
- assertEquals(0, tableMap.size());
- mDatabase.markTableSyncable("people", "_delete_people");
- tableMap = mDatabase.getSyncedTables();
- assertEquals(1, tableMap.size());
- Set<String> keys = tableMap.keySet();
- Iterator<String> iterator = keys.iterator();
- assertTrue(iterator.hasNext());
- assertEquals("people", iterator.next());
- assertEquals("_delete_people", tableMap.get("people"));
- assertFalse(iterator.hasNext());
-
- // test sync
- mDatabase.execSQL("INSERT INTO people VALUES (0, \"foo\", 0);");
- Cursor c = mDatabase.query("people", new String[] {"_id", "name" },
- "_id = 0", null, null, null, null);
- assertTrue(c.moveToFirst());
- c.updateString(1, "updated");
- c.commitUpdates();
- c.close();
- c = mDatabase.query("people", new String[] {"_id", "_sync_dirty" },
- "_id = 0", null, null, null, null);
- assertTrue(c.moveToFirst());
- // _sync_dirty flag has been set
- assertEquals(1, c.getInt(1));
- c.close();
- }
-
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test markTableSyncable(String, String, String)",
- method = "markTableSyncable",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void testMarkTableSyncable() {
- mDatabase.execSQL("CREATE TABLE phone (_id INTEGER PRIMARY KEY, _people_id INTEGER, " +
- "name TEXT);");
- mDatabase.execSQL("CREATE TABLE people (_id INTEGER PRIMARY KEY, " +
- "name TEXT, _sync_dirty INTEGER);");
- mDatabase.markTableSyncable("phone", "_people_id", "people");
-
- Map<String, String> tableMap = mDatabase.getSyncedTables();
- // since no delete table was given, there is no mapping
- assertEquals(0, tableMap.size());
-
- // test sync
- mDatabase.execSQL("INSERT INTO people VALUES (13, \"foo\", 0);");
- mDatabase.execSQL("INSERT INTO phone VALUES (0, 13, \"bar\");");
- Cursor c = mDatabase.query("phone", new String[] {"_id", "name" },
- "_id = 0", null, null, null, null);
- assertTrue(c.moveToFirst());
- c.updateString(1, "updated");
- c.commitUpdates();
- c.close();
- c = mDatabase.query("people", new String[] {"_id", "_sync_dirty" },
- "_id = 13", null, null, null, null);
- assertTrue(c.moveToFirst());
- // _sync_dirty flag has been set
- assertEquals(1, c.getInt(1));
- c.close();
- }
-
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -546,7 +454,8 @@
mDatabase.execSQL("INSERT INTO test (name, age, address) VALUES ('Jim', 35, 'Chicago');");
// delete one record.
- mDatabase.delete(TABLE_NAME, "name = 'Mike'", null);
+ int count = mDatabase.delete(TABLE_NAME, "name = 'Mike'", null);
+ assertEquals(1, count);
Cursor cursor = mDatabase.query(TABLE_NAME, TEST_PROJECTION, null,
null, null, null, null);
@@ -564,7 +473,8 @@
cursor.close();
// delete another record.
- mDatabase.delete(TABLE_NAME, "name = ?", new String[] { "Jack" });
+ count = mDatabase.delete(TABLE_NAME, "name = ?", new String[] { "Jack" });
+ assertEquals(1, count);
cursor = mDatabase.query(TABLE_NAME, TEST_PROJECTION, null, null, null,
null, null);
@@ -581,7 +491,8 @@
mDatabase.execSQL("INSERT INTO test (name, age, address) VALUES ('Jack', 30, 'London');");
// delete all records.
- mDatabase.delete(TABLE_NAME, null, null);
+ count = mDatabase.delete(TABLE_NAME, null, null);
+ assertEquals(3, count);
cursor = mDatabase.query(TABLE_NAME, TEST_PROJECTION, null, null, null, null, null);
assertNotNull(cursor);
@@ -1594,4 +1505,128 @@
assertEquals(1, cursor.getInt(0));
assertEquals(2, cursor.getInt(1));
}
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "test enableWriteAheadLogging",
+ method = "enableWriteAheadLogging",
+ args = {}
+ )
+ /**
+ * With sqlite's write-ahead-logging (WAL) enabled, readers get old version of data
+ * from the table that a writer is modifying at the same time.
+ * <p>
+ * This method does the following to test this sqlite3 feature
+ * <ol>
+ * <li>creates a table in the database and populates it with 5 rows of data</li>
+ * <li>do "select count(*) from this_table" and expect to receive 5</li>
+ * <li>start a writer thread who BEGINs a transaction, INSERTs a single row
+ * into this_table</li>
+ * <li>writer stops the transaction at this point, kicks off a reader thread - which will
+ * do the above SELECT query: "select count(*) from this_table"</li>
+ * <li>this query should return value 5 - because writer is still in transaction and
+ * sqlite returns OLD version of the data</li>
+ * <li>writer ends the transaction, thus making the extra row now visible to everyone</li>
+ * <li>reader is kicked off again to do the same query. this time query should
+ * return value = 6 which includes the newly inserted row into this_table.</li>
+ *</p>
+ * @throws InterruptedException
+ */
+ @LargeTest
+ public void testReaderGetsOldVersionOfDataWhenWriterIsInXact() throws InterruptedException {
+ // redo setup to create WAL enabled database
+ mDatabase.close();
+ new File(mDatabase.getPath()).delete();
+ mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null);
+ boolean rslt = mDatabase.enableWriteAheadLogging();
+ assertTrue(rslt);
+ assertNotNull(mDatabase);
+
+ // create a new table and insert 5 records into it.
+ mDatabase.execSQL("CREATE TABLE t1 (i int, j int);");
+ mDatabase.beginTransaction();
+ for (int i = 0; i < 5; i++) {
+ mDatabase.execSQL("insert into t1 values(?,?);", new String[] {i+"", i+""});
+ }
+ mDatabase.setTransactionSuccessful();
+ mDatabase.endTransaction();
+
+ // make sure a reader can read the above data
+ ReaderQueryingData r1 = new ReaderQueryingData(5);
+ r1.start();
+ Thread.yield();
+ try {r1.join();} catch (Exception e) {}
+
+ WriterDoingSingleTransaction w = new WriterDoingSingleTransaction();
+ w.start();
+ w.join();
+ }
+
+ private class WriterDoingSingleTransaction extends Thread {
+ @Override public void run() {
+ // start a transaction
+ mDatabase.beginTransactionNonExclusive();
+ mDatabase.execSQL("insert into t1 values(?,?);", new String[] {"11", "11"});
+ assertTrue(mDatabase.isOpen());
+
+ // while the writer is in a transaction, start a reader and make sure it can still
+ // read 5 rows of data (= old data prior to the current transaction)
+ ReaderQueryingData r1 = new ReaderQueryingData(5);
+ r1.start();
+ try {r1.join();} catch (Exception e) {}
+
+ // now, have the writer do the select count(*)
+ // it should execute on the same connection as this transaction
+ // and count(*) should reflect the newly inserted row
+ Long l = DatabaseUtils.longForQuery(mDatabase, "select count(*) from t1", null);
+ assertEquals(6, l.intValue());
+
+ // end transaction
+ mDatabase.setTransactionSuccessful();
+ mDatabase.endTransaction();
+
+ // reader should now be able to read 6 rows = new data AFTER this transaction
+ r1 = new ReaderQueryingData(6);
+ r1.start();
+ try {r1.join();} catch (Exception e) {}
+ }
+ }
+
+ private class ReaderQueryingData extends Thread {
+ private int count;
+ /**
+ * constructor with a param to indicate the number of rows expected to be read
+ */
+ public ReaderQueryingData(int count) {
+ this.count = count;
+ }
+ @Override public void run() {
+ Long l = DatabaseUtils.longForQuery(mDatabase, "select count(*) from t1", null);
+ assertEquals(count, l.intValue());
+ }
+ }
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "test exceptions from enableWriteAheadLogging().",
+ method = "enableWriteAheadLogging",
+ args = {}
+ )
+ public void testExceptionsFromEnableWriteAheadLogging() {
+ // attach a database
+ // redo setup to create WAL enabled database
+ mDatabase.close();
+ new File(mDatabase.getPath()).delete();
+ mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null);
+
+ // attach a database and call enableWriteAheadLogging - should not be allowed
+ mDatabase.execSQL("attach database ':memory:' as memoryDb");
+ boolean rslt = mDatabase.enableWriteAheadLogging();
+ assertFalse(rslt);
+ // enableWriteAheadLogging on memory database is not allowed
+ SQLiteDatabase db = SQLiteDatabase.create(null);
+ rslt = db.enableWriteAheadLogging();
+ assertFalse(rslt);
+ db.close();
+ }
}
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java
index 89918a1..a9a3293 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java
@@ -20,13 +20,13 @@
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteException;
+import android.database.sqlite.SQLiteQuery;
import android.database.sqlite.SQLiteStatement;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
@@ -37,9 +37,6 @@
private SQLiteDatabase mDatabase;
- @ToBeFixed(bug="1448885", explanation="SQLiteProgram is an abstract class and its " +
- "constructor is package private, so it can not be extended directly to test. " +
- "For this reason, the test uses SQLiteStatement instead.")
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -57,79 +54,6 @@
super.tearDown();
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test getUniqueId()",
- method = "getUniqueId",
- args = {}
- )
- public void testGetUniqueId() {
- mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " +
- "num1 INTEGER, num2 INTEGER, image BLOB);");
- final String statement = "DELETE FROM test WHERE _id=?;";
- SQLiteStatement statementOne = mDatabase.compileStatement(statement);
- SQLiteStatement statementTwo = mDatabase.compileStatement(statement);
- // since the same compiled statement is being accessed at the same time by 2 different
- // objects, they each get their own statement id
- assertTrue(statementOne.getUniqueId() != statementTwo.getUniqueId());
- statementOne.close();
- statementTwo.close();
-
- statementOne = mDatabase.compileStatement(statement);
- int n = statementOne.getUniqueId();
- statementOne.close();
- statementTwo = mDatabase.compileStatement(statement);
- assertEquals(n, statementTwo.getUniqueId());
- statementTwo.close();
-
- // now try to compile 2 different statements and they should have different uniquerIds.
- SQLiteStatement statement1 = mDatabase.compileStatement("DELETE FROM test WHERE _id=1;");
- SQLiteStatement statement2 = mDatabase.compileStatement("DELETE FROM test WHERE _id=2;");
- assertTrue(statement1.getUniqueId() != statement2.getUniqueId());
- statement1.close();
- statement2.close();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test onAllReferencesReleased(). Since sql statements are always cached in " +
- "SQLiteDatabase, compiledSql should NOT be released " +
- "when onAllReferencesReleased() is called",
- method = "onAllReferencesReleased",
- args = {}
- )
- public void testOnAllReferencesReleased() {
- mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " +
- "num1 INTEGER, num2 INTEGER, image BLOB);");
- final String statement = "DELETE FROM test WHERE _id=?;";
- SQLiteStatement statementOne = mDatabase.compileStatement(statement);
- assertTrue(statementOne.getUniqueId() > 0);
- int nStatement = statementOne.getUniqueId();
- statementOne.releaseReference();
- assertTrue(statementOne.getUniqueId() == nStatement);
- statementOne.close();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test onAllReferencesReleasedFromContainer(). " +
- "Since sql statements are always cached in " +
- "SQLiteDatabase, compiledSql should NOT be released " +
- "when onAllReferencesReleasedFromContainer() is called",
- args = {}
- )
- public void testOnAllReferencesReleasedFromContainer() {
- mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " +
- "num1 INTEGER, num2 INTEGER, image BLOB);");
- final String statement = "DELETE FROM test WHERE _id=?;";
- SQLiteStatement statementOne = mDatabase.compileStatement(statement);
- assertTrue(statementOne.getUniqueId() > 0);
- int nStatement = statementOne.getUniqueId();
- statementOne.releaseReferenceFromContainer();
- assertTrue(statementOne.getUniqueId() == nStatement);
- statementOne.close();
- }
-
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -195,39 +119,36 @@
}
statement.close();
- statement = mDatabase.compileStatement("SELECT text1 FROM test;");
+ Cursor cursor = null;
try {
- statement.bindString(1, "foo");
+ cursor = mDatabase.query("test", new String[]{"text1"}, "where text1='a'",
+ new String[]{"foo"}, null, null, null);
fail("Should throw exception (no value to bind)");
} catch (SQLiteException expected) {
// expected
- }
-
- statement =
- mDatabase.compileStatement("SELECT text1 FROM test WHERE text2 = ? AND num2 = ?;");
-
- try {
- statement.bindString(0, "Jack");
- fail("Should throw exception (index is 0)");
- } catch (SQLiteException expected) {
- // expected
+ } finally {
+ if (cursor != null) {
+ cursor.close();
+ }
}
try {
- statement.bindLong(-1, 30);
- fail("Should throw exception (index is negative)");
- } catch (SQLiteException expected) {
- // expected
- }
- try {
- statement.bindDouble(3, 589.0);
+ cursor = mDatabase.query("test", new String[]{"text1"}, "where text1='a'",
+ new String[]{"foo", "bar"}, null, null, null);
fail("Should throw exception (index too large)");
} catch (SQLiteException expected) {
// expected
+ } finally {
+ if (cursor != null) {
+ cursor.close();
+ }
}
// test positive case
+ statement = mDatabase.compileStatement(
+ "SELECT text1 FROM test WHERE text2 = ? AND num2 = ?;");
statement.bindString(1, "Jack");
statement.bindLong(2, 30);
assertEquals("Mike", statement.simpleQueryForString());
+ statement.close();
}
@TestTargetNew(
@@ -303,64 +224,4 @@
MoreAsserts.assertEquals(blob, value);
cursor.close();
}
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "onAllReferencesReleased",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "onAllReferencesReleasedFromContainer",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "compile",
- args = {java.lang.String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "native_bind_blob",
- args = {int.class, byte[].class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "native_bind_double",
- args = {int.class, double.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "native_bind_long",
- args = {int.class, long.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "native_bind_null",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "native_compile",
- args = {java.lang.String.class}
- )
- })
- @ToBeFixed(bug = "1448885", explanation = "Cannot test protected methods, since constructor" +
- " is private.")
- public void testProtectedMethods() {
- // cannot test
- }
-
- private void closeDatabaseWithOrphanedStatement(){
- try {
- mDatabase.close();
- } catch (SQLiteException e) {
- // A SQLiteException is thrown if there are some unfinialized exceptions
- // This is expected as some tests explicitly leave statements in this state
- if (!e.getMessage().equals("Unable to close due to unfinalised statements")) {
- throw e;
- }
- }
- }
}
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
index ec6b79a..b568b8c 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
@@ -21,19 +21,35 @@
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
+import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
+import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteStatement;
+import android.os.ParcelFileDescriptor;
import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
+
+import java.io.IOException;
+import java.io.InputStream;
@TestTargetClass(android.database.sqlite.SQLiteStatement.class)
public class SQLiteStatementTest extends AndroidTestCase {
private static final String STRING1 = "this is a test";
private static final String STRING2 = "another test";
+ private static final byte[][] BLOBS = new byte [][] {
+ parseBlob("86FADCF1A820666AEBD0789F47932151A2EF734269E8AC4E39630AB60519DFD8"),
+ new byte[1],
+ null,
+ parseBlob("00"),
+ parseBlob("FF"),
+ parseBlob("D7B500FECF25F7A4D83BF823D3858690790F2526013DE6CAE9A69170E2A1E47238"),
+ };
+
private static final String DATABASE_NAME = "database_test.db";
private static final int CURRENT_DATABASE_VERSION = 42;
@@ -60,40 +76,62 @@
mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);");
}
+ private void populateBlobTable() {
+ mDatabase.execSQL("CREATE TABLE blob_test (_id INTEGER PRIMARY KEY, data BLOB)");
+ for (int i = 0; i < BLOBS.length; i++) {
+ ContentValues values = new ContentValues();
+ values.put("_id", i);
+ values.put("data", BLOBS[i]);
+ mDatabase.insert("blob_test", null, values);
+ }
+ }
+
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "execute",
+ method = "executeUpdateDelete",
args = {}
)
public void testExecute() {
+ mDatabase.disableWriteAheadLogging();
populateDefaultTable();
- Cursor c = mDatabase.query("test", null, null, null, null, null, null);
- assertEquals(0, c.getCount());
+ assertEquals(0, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
- // test insert
- SQLiteStatement statement = mDatabase.compileStatement(
- "INSERT INTO test (data) VALUES ('" + STRING1 + "')");
- statement.execute();
+ // test update
+ // insert 2 rows and then update them.
+ SQLiteStatement statement1 = mDatabase.compileStatement(
+ "INSERT INTO test (data) VALUES ('" + STRING2 + "')");
+ assertEquals(1, statement1.executeInsert());
+ assertEquals(2, statement1.executeInsert());
+ SQLiteStatement statement2 =
+ mDatabase.compileStatement("UPDATE test set data = 'a' WHERE _id > 0");
+ assertEquals(2, statement2.executeUpdateDelete());
+ statement2.close();
+ // should still have 2 rows in the table
+ assertEquals(2, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
- c = mDatabase.query("test", null, null, null, null, null, null);
- assertEquals(1, c.getCount());
+ // test delete
+ // insert 2 more rows and delete 3 of them
+ assertEquals(3, statement1.executeInsert());
+ assertEquals(4, statement1.executeInsert());
+ statement1.close();
+ statement2 = mDatabase.compileStatement("DELETE from test WHERE _id < 4");
+ assertEquals(3, statement2.executeUpdateDelete());
+ statement2.close();
+ // should still have 1 row1 in the table
+ assertEquals(1, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
- c.moveToFirst();
- assertEquals(STRING1, c.getString(c.getColumnIndex("data")));
-
- // invalid SQL statement
- statement = mDatabase.compileStatement(
- "SELECT * FROM test WHERE data=\"" + STRING1 + "\"");
+ // if the SQL statement is something that causes rows of data to
+ // be returned, executeUpdateDelete() (and execute()) throw an exception.
+ statement2 = mDatabase.compileStatement("SELECT count(*) FROM test");
try {
- statement.execute();
- fail("There should be a SQLException thrown out.");
+ statement2.executeUpdateDelete();
+ fail("exception expected");
} catch (SQLException e) {
- // expected.
+ // expected
+ } finally {
+ statement2.close();
}
-
- c.deactivate();
- statement.close();
}
@TestTargets({
@@ -118,25 +156,33 @@
SQLiteStatement statement = mDatabase.compileStatement(
"INSERT INTO test (data) VALUES ('" + STRING2 + "')");
assertEquals(1, statement.executeInsert());
+ statement.close();
+
+ // try to insert another row with the same id. last inserted rowid should be -1
+ statement = mDatabase.compileStatement("insert or ignore into test values(1, 1);");
+ assertEquals(-1, statement.executeInsert());
+ statement.close();
c = mDatabase.query("test", null, null, null, null, null, null);
assertEquals(1, c.getCount());
c.moveToFirst();
assertEquals(STRING2, c.getString(c.getColumnIndex("data")));
+ c.close();
- // invalid SQL statement
+ // if the sql statement is something that causes rows of data to
+ // be returned, executeInsert() throws an exception
statement = mDatabase.compileStatement(
"SELECT * FROM test WHERE data=\"" + STRING2 + "\"");
try {
statement.executeInsert();
- fail("There should be a SQLException thrown out.");
+ fail("exception expected");
} catch (SQLException e) {
- // expected.
- }
+ // expected
+ } finally {
+ statement.close();
- c.deactivate();
- statement.close();
+ }
}
@TestTargetNew(
@@ -196,4 +242,177 @@
statement.close();
}
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccessNormal() throws IOException {
+ doTestSimpleQueryForBlobFileDescriptorSuccess(0);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccessEmpty() throws IOException {
+ doTestSimpleQueryForBlobFileDescriptorSuccess(1);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccessNull() {
+ populateBlobTable();
+
+ String sql = "SELECT data FROM blob_test WHERE _id = " + 2;
+ SQLiteStatement stm = mDatabase.compileStatement(sql);
+ assertNull(stm.simpleQueryForBlobFileDescriptor());
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccess00() throws IOException {
+ doTestSimpleQueryForBlobFileDescriptorSuccess(3);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccessFF() throws IOException {
+ doTestSimpleQueryForBlobFileDescriptorSuccess(4);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccessEmbeddedNul() throws IOException {
+ doTestSimpleQueryForBlobFileDescriptorSuccess(5);
+ }
+
+ private void doTestSimpleQueryForBlobFileDescriptorSuccess(int i) throws IOException {
+ populateBlobTable();
+
+ String sql = "SELECT data FROM blob_test WHERE _id = " + i;
+ SQLiteStatement stm = mDatabase.compileStatement(sql);
+ ParcelFileDescriptor fd = stm.simpleQueryForBlobFileDescriptor();
+ assertFileDescriptorContent(BLOBS[i], fd);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testSimpleQueryForBlobFileDescriptorSuccessParam() throws IOException {
+ populateBlobTable();
+
+ String sql = "SELECT data FROM blob_test WHERE _id = ?";
+ SQLiteStatement stm = mDatabase.compileStatement(sql);
+ stm.bindLong(1, 0);
+ ParcelFileDescriptor fd = stm.simpleQueryForBlobFileDescriptor();
+ assertFileDescriptorContent(BLOBS[0], fd);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testGetBlobFailureNoParam() throws Exception {
+ populateBlobTable();
+
+ String sql = "SELECT data FROM blob_test WHERE _id = 100";
+ SQLiteStatement stm = mDatabase.compileStatement(sql);
+ ParcelFileDescriptor fd = null;
+ SQLiteDoneException expectedException = null;
+ try {
+ fd = stm.simpleQueryForBlobFileDescriptor();
+ } catch (SQLiteDoneException ex) {
+ expectedException = ex;
+ } finally {
+ if (fd != null) {
+ fd.close();
+ fd = null;
+ }
+ }
+ assertNotNull("Should have thrown SQLiteDoneException", expectedException);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "simpleQueryForBlobFileDescriptor",
+ args = {}
+ )
+ public void testGetBlobFailureParam() throws Exception {
+ populateBlobTable();
+
+ String sql = "SELECT data FROM blob_test WHERE _id = ?";
+ SQLiteStatement stm = mDatabase.compileStatement(sql);
+ stm.bindLong(1, 100);
+ ParcelFileDescriptor fd = null;
+ SQLiteDoneException expectedException = null;
+ try {
+ fd = stm.simpleQueryForBlobFileDescriptor();
+ } catch (SQLiteDoneException ex) {
+ expectedException = ex;
+ } finally {
+ if (fd != null) {
+ fd.close();
+ fd = null;
+ }
+ }
+ assertNotNull("Should have thrown SQLiteDoneException", expectedException);
+ }
+
+ /*
+ * Convert string of hex digits to byte array.
+ * Results are undefined for poorly formed string.
+ *
+ * @param src hex string
+ */
+ private static byte[] parseBlob(String src) {
+ int len = src.length();
+ byte[] result = new byte[len / 2];
+
+ for (int i = 0; i < len/2; i++) {
+ int val;
+ char c1 = src.charAt(i*2);
+ char c2 = src.charAt(i*2+1);
+ int val1 = Character.digit(c1, 16);
+ int val2 = Character.digit(c2, 16);
+ val = (val1 << 4) | val2;
+ result[i] = (byte)val;
+ }
+ return result;
+ }
+
+ private static void assertFileDescriptorContent(byte[] expected, ParcelFileDescriptor fd)
+ throws IOException {
+ assertInputStreamContent(expected, new ParcelFileDescriptor.AutoCloseInputStream(fd));
+ }
+
+ private static void assertInputStreamContent(byte[] expected, InputStream is)
+ throws IOException {
+ try {
+ byte[] observed = new byte[expected.length];
+ int count = is.read(observed);
+ assertEquals(expected.length, count);
+ assertEquals(-1, is.read());
+ MoreAsserts.assertEquals(expected, observed);
+ } finally {
+ is.close();
+ }
+ }
}
diff --git a/tests/tests/drm/Android.mk b/tests/tests/drm/Android.mk
new file mode 100644
index 0000000..61e1f10
--- /dev/null
+++ b/tests/tests/drm/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# don't include this package in any target
+LOCAL_MODULE_TAGS := optional
+# and when built explicitly put it in the data partition
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_JAVA_LIBRARIES := android.test.runner
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsDrmTestCases
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+# uncomment when dalvik.annotation.Test* are removed or part of SDK
+#LOCAL_SDK_VERSION := current
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/drm/AndroidManifest.xml b/tests/tests/drm/AndroidManifest.xml
new file mode 100644
index 0000000..fe515f3
--- /dev/null
+++ b/tests/tests/drm/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.cts.drm">
+
+ <application>
+ <uses-library android:name="android.test.runner" />
+ </application>
+
+ <instrumentation android:name="android.test.InstrumentationCtsTestRunner"
+ android:targetPackage="com.android.cts.stub"
+ android:label="CTS tests of android.drm"/>
+
+</manifest>
+
diff --git a/tests/tests/drm/README b/tests/tests/drm/README
new file mode 100644
index 0000000..dd0ef17
--- /dev/null
+++ b/tests/tests/drm/README
@@ -0,0 +1,6 @@
+- User of CTS code needs to edit configuration files in
+ "src/android/drm/cts/configs/" according to the specification
+ of user's DRM plug-in.
+- If new plug-in is added, user should add corresponding configuration
+ file under "src/android/drm/cts/configs/" and update
+ "src/android/drm/cts/ConfigFactory.java".
diff --git a/tests/tests/drm/src/android/drm/cts/Config.java b/tests/tests/drm/src/android/drm/cts/Config.java
new file mode 100644
index 0000000..736c0ad
--- /dev/null
+++ b/tests/tests/drm/src/android/drm/cts/Config.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.drm.cts;
+
+import java.util.HashMap;
+
+public interface Config {
+ String getPluginName();
+ String getMimeType();
+ String getAccountId();
+ String getRightsPath();
+ String getContentPath();
+ HashMap<String, String> getInfoOfRegistration();
+ HashMap<String, String> getInfoOfUnregistration();
+ HashMap<String, String> getInfoOfRightsAcquisition();
+}
diff --git a/tests/tests/drm/src/android/drm/cts/ConfigFactory.java b/tests/tests/drm/src/android/drm/cts/ConfigFactory.java
new file mode 100644
index 0000000..643bb67
--- /dev/null
+++ b/tests/tests/drm/src/android/drm/cts/ConfigFactory.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.drm.cts;
+
+import android.util.Log;
+
+import android.drm.cts.configs.PassthruConfig;
+import android.drm.cts.configs.FwdLockConfig;
+
+public final class ConfigFactory {
+ private static final String TAG = "ConfigFactory";
+
+ /**
+ * Get configurations of specified plug-in name.
+ *
+ * @param plugInName Name of DRM plug-in. The name SHOULD be consistent with
+ * the name defined in plug-in's onGetSupportInfo().
+ */
+ public static Config getConfig(String plugInName) {
+ if (plugInName.equals("Passthru plug-in")) {
+ return PassthruConfig.getInstance();
+ } else if (plugInName.equals("OMA V1 Forward Lock")) {
+ return FwdLockConfig.getInstance();
+ } else {
+ Log.e(TAG, "Configuration for " + plugInName + " is not registered.");
+ return null;
+ }
+ }
+}
diff --git a/tests/tests/drm/src/android/drm/cts/DRMTest.java b/tests/tests/drm/src/android/drm/cts/DRMTest.java
new file mode 100644
index 0000000..c43bf4b
--- /dev/null
+++ b/tests/tests/drm/src/android/drm/cts/DRMTest.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.drm.cts;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+
+import android.content.ContentValues;
+import android.test.AndroidTestCase;
+import android.util.Log;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import android.drm.DrmManagerClient;
+import android.drm.DrmConvertedStatus;
+import android.drm.DrmEvent;
+import android.drm.DrmInfo;
+import android.drm.DrmInfoRequest;
+import android.drm.DrmInfoStatus;
+import android.drm.DrmRights;
+import android.drm.DrmStore;
+import android.drm.DrmUtils;
+
+@TestTargetClass(DrmManagerClient.class)
+public class DRMTest extends AndroidTestCase {
+ private static String TAG = "CtsDRMTest";
+ private static final int WAIT_TIME = 60000; // 1 min max
+
+ private Object mLock = new Object();
+ private ArrayList<Config> mConfigs = new ArrayList<Config>();
+ private DrmRights mDrmRights;
+ private DrmManagerClient mDrmManagerClient;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mDrmManagerClient = new DrmManagerClient(getContext());
+ String[] plugins = mDrmManagerClient.getAvailableDrmEngines();
+
+ mConfigs.clear();
+ for(String plugInName : plugins) {
+ Config config = ConfigFactory.getConfig(plugInName);
+ if (null != config) {
+ mConfigs.add(config);
+ }
+ }
+ }
+
+ private void register(Config config) throws Exception {
+ DrmInfo drmInfo = executeAcquireDrmInfo(DrmInfoRequest.TYPE_REGISTRATION_INFO,
+ config.getInfoOfRegistration(),
+ config.getMimeType());
+ executeProcessDrmInfo(drmInfo, config);
+ }
+
+ private void acquireRights(Config config) throws Exception {
+ DrmInfo drmInfo = executeAcquireDrmInfo(DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO,
+ config.getInfoOfRightsAcquisition(),
+ config.getMimeType());
+ executeProcessDrmInfo(drmInfo, config);
+ }
+
+ private void deregister(Config config) throws Exception {
+ DrmInfo drmInfo = executeAcquireDrmInfo(DrmInfoRequest.TYPE_UNREGISTRATION_INFO,
+ config.getInfoOfRegistration(),
+ config.getMimeType());
+ executeProcessDrmInfo(drmInfo, config);
+ }
+
+ public void testRegisterAndDeregister() throws Exception {
+ for (Config config : mConfigs) {
+ register(config);
+ deregister(config);
+ }
+ }
+
+ public void testAcquireRights() throws Exception {
+ for (Config config : mConfigs) {
+ register(config);
+ acquireRights(config);
+ deregister(config);
+ }
+ }
+
+ public void testGetConstraints() throws Exception {
+ for (Config config : mConfigs) {
+ register(config);
+ acquireRights(config);
+ ContentValues constraints = mDrmManagerClient.getConstraints(
+ config.getContentPath(),
+ DrmStore.Action.DEFAULT);
+ assertNotNull("Failed on plugin: " + config.getPluginName(), constraints);
+ deregister(config);
+ }
+ }
+
+ public void testCanHandle() throws Exception {
+ for (Config config : mConfigs) {
+ assertTrue("Failed on plugin: " + config.getPluginName(),
+ mDrmManagerClient.canHandle(config.getContentPath(), config.getMimeType()));
+ }
+ }
+
+ public void testGetOriginalMimeType() throws Exception {
+ for (Config config : mConfigs) {
+ assertNotNull("Failed on plugin: " + config.getPluginName(),
+ mDrmManagerClient.getOriginalMimeType(config.getContentPath()));
+ }
+ }
+
+ public void testCheckRightsStatus() throws Exception {
+ for (Config config : mConfigs) {
+ register(config);
+ acquireRights(config);
+ int rightsStatus = mDrmManagerClient.checkRightsStatus(
+ config.getContentPath(),
+ DrmStore.Action.PLAY);
+ assertEquals("Failed on plugin: " + config.getPluginName(),
+ DrmStore.RightsStatus.RIGHTS_VALID, rightsStatus);
+ deregister(config);
+ }
+ }
+
+ public void testRemoveRights() throws Exception {
+ for (Config config : mConfigs) {
+ assertEquals("Failed on plugin: " + config.getPluginName(),
+ DrmManagerClient.ERROR_NONE,
+ mDrmManagerClient.removeRights(config.getContentPath()));
+ }
+ }
+
+ public void testRemoveAllRights() throws Exception {
+ for (Config config : mConfigs) {
+ assertEquals("Failed on plugin: " + config.getPluginName(),
+ mDrmManagerClient.removeAllRights(), DrmManagerClient.ERROR_NONE);
+ }
+ }
+
+ public void testConvertData() throws Exception {
+ for (Config config : mConfigs) {
+ byte[] inputData = new byte[]{'T','E','S','T'};
+
+ int convertId = mDrmManagerClient.openConvertSession(config.getMimeType());
+ DrmConvertedStatus drmConvertStatus
+ = mDrmManagerClient.convertData(convertId, inputData);
+ mDrmManagerClient.closeConvertSession(convertId);
+ }
+ }
+
+ private DrmInfo executeAcquireDrmInfo(
+ int type, HashMap<String, String> request, String mimeType) throws Exception {
+ DrmInfoRequest infoRequest = new DrmInfoRequest(type, mimeType);
+
+ for (Iterator it = request.keySet().iterator(); it.hasNext(); ) {
+ String key = (String) it.next();
+ String value = request.get(key);
+ infoRequest.put(key, value);
+ }
+
+ return mDrmManagerClient.acquireDrmInfo(infoRequest);
+ }
+
+ private void executeProcessDrmInfo(DrmInfo drmInfo, Config config) throws Exception {
+ assertNotNull("Failed on plugin: " + config.getPluginName(), drmInfo);
+
+ mDrmManagerClient.setOnEventListener(new OnEventListenerImpl(config));
+ drmInfo.put(DrmInfoRequest.ACCOUNT_ID, config.getAccountId());
+ assertEquals("Failed on plugin: " + config.getPluginName(),
+ DrmManagerClient.ERROR_NONE, mDrmManagerClient.processDrmInfo(drmInfo));
+
+ synchronized(mLock) {
+ try {
+ mLock.wait(WAIT_TIME);
+ } catch(Exception e) {
+ Log.v(TAG, "ProcessDrmInfo: wait was interrupted.");
+ }
+ }
+ }
+
+ private class OnEventListenerImpl implements DrmManagerClient.OnEventListener {
+ private Config mConfig;
+ public OnEventListenerImpl(Config config) {
+ mConfig = config;
+ }
+
+ @Override
+ public void onEvent(DrmManagerClient client, DrmEvent event) {
+ switch (event.getType()) {
+ case DrmEvent.TYPE_DRM_INFO_PROCESSED:
+ Log.d(TAG, "processDrmInfo() completed");
+ DrmInfoStatus infoStatus
+ = (DrmInfoStatus) event.getAttribute(DrmEvent.DRM_INFO_STATUS_OBJECT);
+ switch (infoStatus.infoType) {
+ case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
+ mDrmRights = new DrmRights(infoStatus.data, infoStatus.mimeType);
+ assertNotNull(mDrmRights);
+ try {
+ assertEquals(DrmManagerClient.ERROR_NONE, mDrmManagerClient.saveRights(
+ mDrmRights, mConfig.getRightsPath(), mConfig.getContentPath()));
+ Log.d(TAG, "Rights saved");
+ } catch (IOException e) {
+ Log.e(TAG, "Save Rights failed");
+ e.printStackTrace();
+ }
+ break;
+ case DrmInfoRequest.TYPE_REGISTRATION_INFO:
+ Log.d(TAG, "Registration completed");
+ break;
+ case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
+ Log.d(TAG, "Deregistration completed");
+ break;
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+ synchronized (mLock) {
+ mLock.notify();
+ }
+ }
+ }
+}
diff --git a/tests/tests/drm/src/android/drm/cts/configs/FwdLockConfig.java b/tests/tests/drm/src/android/drm/cts/configs/FwdLockConfig.java
new file mode 100644
index 0000000..e67ff03
--- /dev/null
+++ b/tests/tests/drm/src/android/drm/cts/configs/FwdLockConfig.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.drm.cts.configs;
+
+import java.util.HashMap;
+
+import android.drm.cts.Config;
+
+public class FwdLockConfig implements Config {
+ private static FwdLockConfig sInstance = new FwdLockConfig();
+ private FwdLockConfig() {}
+ public static FwdLockConfig getInstance() {
+ return sInstance;
+ }
+ public String getPluginName() {
+ return "Forward Lock";
+ }
+ public String getMimeType() {
+ return "application/x-android-drm-fl";
+ }
+ public String getAccountId() {
+ return "01234567";
+ }
+ public String getRightsPath() {
+ // Fwd lock does not have rights but send back dummy string anyways.
+ return "/sdcard/non_existing_rights.xml";
+ }
+ public String getContentPath() {
+ return "/sdcard/dummy_fwdlock_content.dm";
+ }
+ public HashMap<String, String> getInfoOfRegistration() {
+ return sInfoOfRegistration;
+ }
+ public HashMap<String, String> getInfoOfUnregistration() {
+ return sInfoOfUnregistration;
+ }
+ public HashMap<String, String> getInfoOfRightsAcquisition(){
+ return sInfoOfRightsAcquisition;
+ }
+
+ private static HashMap<String, String> sInfoOfRegistration = new HashMap<String, String>();
+ private static HashMap<String, String> sInfoOfUnregistration = new HashMap<String, String>();
+ private static HashMap<String, String> sInfoOfRightsAcquisition =
+ new HashMap<String, String>();
+
+ static {
+ sInfoOfRegistration.put("Dummy-FwdLock-1", "Dummy-FwdLock-1");
+
+ sInfoOfUnregistration.put("Dummy-FwdLock-2", "Dummy-FwdLock-2");
+
+ sInfoOfRightsAcquisition.put("Dummy-FwdLock-3", "Dummy-FwdLock-3");
+ }
+}
diff --git a/tests/tests/drm/src/android/drm/cts/configs/PassthruConfig.java b/tests/tests/drm/src/android/drm/cts/configs/PassthruConfig.java
new file mode 100644
index 0000000..7310825
--- /dev/null
+++ b/tests/tests/drm/src/android/drm/cts/configs/PassthruConfig.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.drm.cts.configs;
+
+import java.util.HashMap;
+
+import android.drm.cts.Config;
+
+public class PassthruConfig implements Config {
+ private static PassthruConfig sInstance = new PassthruConfig();
+ private PassthruConfig() {}
+ public static PassthruConfig getInstance() {
+ return sInstance;
+ }
+ public String getPluginName() {
+ return "Passthru";
+ }
+ public String getMimeType() {
+ return "application/vnd.passthru.drm";
+ }
+ public String getAccountId() {
+ return "01234567";
+ }
+ public String getRightsPath() {
+ return "/sdcard/dummy_passthru_rights.xml";
+ }
+ public String getContentPath() {
+ return "/sdcard/dummy_passthru_content.passthru";
+ }
+ public HashMap<String, String> getInfoOfRegistration() {
+ return sInfoOfRegistration;
+ }
+ public HashMap<String, String> getInfoOfUnregistration() {
+ return sInfoOfUnregistration;
+ }
+ public HashMap<String, String> getInfoOfRightsAcquisition(){
+ return sInfoOfRightsAcquisition;
+ }
+
+ private static HashMap<String, String> sInfoOfRegistration = new HashMap<String, String>();
+ private static HashMap<String, String> sInfoOfUnregistration = new HashMap<String, String>();
+ private static HashMap<String, String> sInfoOfRightsAcquisition = new HashMap<String, String>();
+
+ static {
+ sInfoOfRegistration.put("Foo-1", "foo-1");
+
+ sInfoOfUnregistration.put("Foo-2", "foo-2");
+
+ sInfoOfRightsAcquisition.put("Foo-3", "foo-3");
+ }
+}
diff --git a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
index 07612d4..b00a383 100644
--- a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
@@ -96,7 +96,6 @@
)
public void testCanvas1() {
final Canvas c = new Canvas();
- assertNull(c.getGL());
}
@TestTargetNew(
@@ -128,36 +127,6 @@
new Canvas(mMutableBitmap);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "Canvas",
- args = {javax.microedition.khronos.opengles.GL.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getGL",
- args = {}
- )
- })
- public void testCanvas3() {
- Canvas c = new Canvas();
- assertNull(c.getGL());
- final MyGL myGL = new MyGL();
- c = new Canvas(myGL);
- assertTrue(myGL.equals(c.getGL()));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "freeGlCaches",
- args = {}
- )
- public void testFreeGlCaches() {
- // can't get the changed state
- Canvas.freeGlCaches();
- }
-
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setBitmap",
@@ -173,16 +142,6 @@
// expected
}
- // abnormal case: GL not null
- final Canvas c = new Canvas(new MyGL());
- try {
- c.setBitmap(mMutableBitmap);
- fail("should throw out RuntimeException when setting MutableBitmap to Canvas "
- + "when the Canvas is created with GL");
- } catch (RuntimeException e) {
- // expected
- }
-
// abnormal case: bitmap to be set has been recycled
mMutableBitmap.recycle();
try {
@@ -199,39 +158,6 @@
assertEquals(31, mCanvas.getHeight());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "setViewport",
- args = {int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getWidth",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getHeight",
- args = {}
- )
- })
- public void testSetViewport() {
- assertEquals(BITMAP_WIDTH, mCanvas.getWidth());
- assertEquals(BITMAP_HEIGHT, mCanvas.getHeight());
-
- // set viewport has no effect for bitmap based canvas
- mCanvas.setViewport(BITMAP_HEIGHT, BITMAP_WIDTH);
- assertEquals(BITMAP_WIDTH, mCanvas.getWidth());
- assertEquals(BITMAP_HEIGHT, mCanvas.getHeight());
-
- // only GL based canvas that can set viewport
- mCanvas = new Canvas(new MyGL());
- mCanvas.setViewport(BITMAP_HEIGHT, BITMAP_WIDTH);
- assertEquals(BITMAP_HEIGHT, mCanvas.getWidth());
- assertEquals(BITMAP_WIDTH, mCanvas.getHeight());
- }
-
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "isOpaque",
@@ -2266,8 +2192,4 @@
assertEquals(0.0f, values[7]);
assertEquals(1.0f, values[8]);
}
-
- private class MyGL implements GL {
- //do nothing
- }
}
diff --git a/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java b/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java
deleted file mode 100644
index 170992d..0000000
--- a/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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 android.graphics.cts;
-
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuff.Mode;
-import android.test.AndroidTestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PorterDuff.Mode.class)
-public class PorterDuff_ModeTest extends AndroidTestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void testValueOf() {
- assertEquals(Mode.CLEAR, Mode.valueOf("CLEAR"));
- assertEquals(Mode.SRC, Mode.valueOf("SRC"));
- assertEquals(Mode.DST, Mode.valueOf("DST"));
- assertEquals(Mode.SRC_OVER, Mode.valueOf("SRC_OVER"));
- assertEquals(Mode.DST_OVER, Mode.valueOf("DST_OVER"));
- assertEquals(Mode.SRC_IN, Mode.valueOf("SRC_IN"));
- assertEquals(Mode.DST_IN, Mode.valueOf("DST_IN"));
- assertEquals(Mode.SRC_OUT, Mode.valueOf("SRC_OUT"));
- assertEquals(Mode.DST_OUT, Mode.valueOf("DST_OUT"));
- assertEquals(Mode.SRC_ATOP, Mode.valueOf("SRC_ATOP"));
- assertEquals(Mode.DST_ATOP, Mode.valueOf("DST_ATOP"));
- assertEquals(Mode.XOR, Mode.valueOf("XOR"));
- assertEquals(Mode.DARKEN, Mode.valueOf("DARKEN"));
- assertEquals(Mode.LIGHTEN, Mode.valueOf("LIGHTEN"));
- assertEquals(Mode.MULTIPLY, Mode.valueOf("MULTIPLY"));
- assertEquals(Mode.SCREEN, Mode.valueOf("SCREEN"));
- // Every Mode element will be tested in other test cases.
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "values",
- args = {}
- )
- public void testValues() {
- // set the expected value
- Mode[] expected = {
- Mode.CLEAR,
- Mode.SRC,
- Mode.DST,
- Mode.SRC_OVER,
- Mode.DST_OVER,
- Mode.SRC_IN,
- Mode.DST_IN,
- Mode.SRC_OUT,
- Mode.DST_OUT,
- Mode.SRC_ATOP,
- Mode.DST_ATOP,
- Mode.XOR,
- Mode.DARKEN,
- Mode.LIGHTEN,
- Mode.MULTIPLY,
- Mode.SCREEN};
- Mode[] actual = Mode.values();
- assertEquals(expected.length, actual.length);
- for (int i = 0; i < actual.length; i ++) {
- assertEquals(expected[i], actual[i]);
- }
- }
-
-}
diff --git a/tests/tests/graphics/src/android/graphics/cts/RadialGradientTest.java b/tests/tests/graphics/src/android/graphics/cts/RadialGradientTest.java
deleted file mode 100644
index 3db864b..0000000
--- a/tests/tests/graphics/src/android/graphics/cts/RadialGradientTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.graphics.cts;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.RadialGradient;
-import android.graphics.Shader;
-import android.graphics.Shader.TileMode;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(RadialGradient.class)
-public class RadialGradientTest extends TestCase {
- private static final int SIZE = 200;
- private static final int RADIUS = 80;
- private static final int CENTER = SIZE / 2;
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "RadialGradient",
- args = {float.class, float.class, float.class, int[].class, float[].class,
- TileMode.class}
- )
- public void testRadialGradient() {
- final int[] colors = { Color.BLUE, Color.GREEN, Color.RED };
- final float[] positions = { 0f, 0.3f, 1f };
- int tolerance = (int)(0xFF / (0.3f * RADIUS) * 2);
- RadialGradient rg = new RadialGradient(CENTER, CENTER, RADIUS, colors, positions,
- Shader.TileMode.CLAMP);
- Bitmap b = Bitmap.createBitmap(SIZE, SIZE, Bitmap.Config.ARGB_8888);
- Canvas canvas = new Canvas(b);
- Paint p = new Paint();
- p.setShader(rg);
- canvas.drawRect(0, 0, SIZE, SIZE, p);
- checkPixels(b, colors, positions, tolerance);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "RadialGradient",
- args = {float.class, float.class, float.class, int.class, int.class, TileMode.class}
- )
- public void testRadialGradientWithColor() {
- final int[] colors = { Color.BLUE, Color.GREEN };
- final float[] positions = { 0f, 1f };
- int tolerance = (int)(0xFF / RADIUS * 2);
- RadialGradient rg = new RadialGradient(CENTER, CENTER, RADIUS, colors[0], colors[1],
- Shader.TileMode.CLAMP);
- Bitmap b = Bitmap.createBitmap(SIZE, SIZE, Bitmap.Config.ARGB_8888);
- Canvas canvas = new Canvas(b);
- Paint p = new Paint();
- p.setShader(rg);
- canvas.drawRect(0, 0, SIZE, SIZE, p);
- checkPixels(b, colors, positions, tolerance);
- }
-
- private void checkPixels(Bitmap bitmap, int[] colors, float[] positions, int tolerance) {
- for (int y = 0; y < SIZE; y++) {
- for (int x = 0; x < SIZE; x++) {
- double dist = dist(x, y, CENTER, CENTER) / RADIUS;
- int idx;
- int color;
- for (idx = 0; idx < positions.length; idx++) {
- if (positions[idx] > dist) {
- break;
- }
- }
- if (idx == 0) {
- // use start color
- color = colors[0];
- } else if (idx == positions.length) {
- // clamp to end color
- color = colors[positions.length - 1];
- } else {
- // linear interpolation
- int i1 = idx - 1; // index of next lower color and position
- int i2 = idx; // index of next higher color and position
- double delta = (dist - positions[i1]) / (positions[i2] - positions[i1]);
- int alpha = (int) ((1d - delta) * Color.alpha(colors[i1]) +
- delta * Color.alpha(colors[i2]));
- int red = (int) ((1d - delta) * Color.red(colors[i1]) +
- delta * Color.red(colors[i2]));
- int green = (int) ((1d - delta) * Color.green(colors[i1]) +
- delta * Color.green(colors[i2]));
- int blue = (int) ((1d - delta) * Color.blue(colors[i1]) +
- delta * Color.blue(colors[i2]));
- color = Color.argb(alpha, red, green, blue);
- }
- int pixel = bitmap.getPixel(x, y);
-
- assertEquals(Color.alpha(color), Color.alpha(pixel), tolerance);
- assertEquals(Color.red(color), Color.red(pixel), tolerance);
- assertEquals(Color.green(color), Color.green(pixel), tolerance);
- assertEquals(Color.blue(color), Color.blue(pixel), tolerance);
- }
- }
- }
-
- /**
- * Calculate distance between two points.
- */
- private double dist(int x1, int y1, int x2, int y2) {
- int distX = x1 - x2;
- int distY = y1 - y2;
- return Math.sqrt(distX * distX + distY * distY);
- }
-
-}
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java
index 15ae0b6..bfe3ec7 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java
@@ -241,8 +241,8 @@
})
public void testConstantHeightsAndWidths() {
assertEquals(0, mDrawableContainerState.getChildCount());
- assertEquals(0, mDrawableContainerState.getConstantHeight());
- assertEquals(0, mDrawableContainerState.getConstantWidth());
+ assertEquals(-1, mDrawableContainerState.getConstantHeight());
+ assertEquals(-1, mDrawableContainerState.getConstantWidth());
assertEquals(0, mDrawableContainerState.getConstantMinimumHeight());
assertEquals(0, mDrawableContainerState.getConstantMinimumWidth());
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
index b47d906..604f1e2 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
@@ -283,9 +283,6 @@
assertFalse(layerDrawable.setDrawableByLayerId(30, d1));
- layerDrawable.setDrawableByLayerId(20, null);
- assertEquals(null, layerDrawable.getDrawable(1));
-
try {
layerDrawable.getDrawable(layerDrawable.getNumberOfLayers());
fail("Should throw IndexOutOfBoundsException");
diff --git a/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java b/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java
index fa164e3..ada9d69 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java
@@ -62,11 +62,7 @@
} catch (ArrayIndexOutOfBoundsException e) {
}
- try {
- new RoundRectShape(null, new RectF(), new float[8]);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- }
+ new RoundRectShape(null, new RectF(), new float[8]);
try {
new RoundRectShape(new float[8], new RectF(), new float[7]);
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
index 60b8459..d75b5bc 100644
--- a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
@@ -31,6 +31,7 @@
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
+import android.media.CamcorderProfile;
import android.media.ExifInterface;
import android.media.MediaRecorder;
import android.os.ConditionVariable;
@@ -161,7 +162,9 @@
public void onPreviewFrame(byte [] data, Camera camera) {
assertNotNull(data);
Size size = camera.getParameters().getPreviewSize();
- assertEquals(size.width * size.height * 3 / 2, data.length);
+ int format = camera.getParameters().getPreviewFormat();
+ int bitsPerPixel = ImageFormat.getBitsPerPixel(format);
+ assertEquals(size.width * size.height * bitsPerPixel / 8, data.length);
mPreviewCallbackResult = true;
mCamera.stopPreview();
if (LOGV) Log.v(TAG, "notify the preview callback");
@@ -222,7 +225,7 @@
private final class TestErrorCallback implements ErrorCallback {
public void onError(int error, Camera camera) {
mErrorCallbackResult = true;
- fail("The Error code is: " + error);
+ fail("Got camera error from ErrorCallback: " + error);
}
}
@@ -331,9 +334,11 @@
assertTrue(mShutterCallbackResult);
assertTrue(mJpegPictureCallbackResult);
assertNotNull(mJpegData);
- Bitmap b = BitmapFactory.decodeByteArray(mJpegData, 0, mJpegData.length);
- assertEquals(pictureSize.width, b.getWidth());
- assertEquals(pictureSize.height, b.getHeight());
+ BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
+ bmpOptions.inJustDecodeBounds = true;
+ BitmapFactory.decodeByteArray(mJpegData, 0, mJpegData.length, bmpOptions);
+ assertEquals(pictureSize.width, bmpOptions.outWidth);
+ assertEquals(pictureSize.height, bmpOptions.outHeight);
}
@TestTargets({
@@ -574,7 +579,6 @@
// Parameters constants
final int PICTURE_FORMAT = ImageFormat.JPEG;
final int PREVIEW_FORMAT = ImageFormat.NV21;
- final int PREVIEW_FRAMERATE = 10;
// Before setting Parameters
final int origPictureFormat = parameters.getPictureFormat();
@@ -600,6 +604,10 @@
// If camera supports flash, the default flash mode must be off.
String flashMode = parameters.getFlashMode();
assertTrue(flashMode == null || flashMode.equals(parameters.FLASH_MODE_OFF));
+ String wb = parameters.getWhiteBalance();
+ assertTrue(wb == null || wb.equals(parameters.WHITE_BALANCE_AUTO));
+ String effect = parameters.getColorEffect();
+ assertTrue(effect == null || effect.equals(parameters.EFFECT_NONE));
// Some parameters must be supported.
List<Size> previewSizes = parameters.getSupportedPreviewSizes();
@@ -616,7 +624,9 @@
int jpegThumnailQuality = parameters.getJpegThumbnailQuality();
assertTrue(previewSizes != null && previewSizes.size() != 0);
assertTrue(pictureSizes != null && pictureSizes.size() != 0);
- assertTrue(previewFormats != null && previewFormats.size() != 0);
+ assertTrue(previewFormats != null && previewFormats.size() >= 2);
+ assertTrue(previewFormats.contains(ImageFormat.NV21));
+ assertTrue(previewFormats.contains(ImageFormat.YV12));
assertTrue(pictureFormats != null && pictureFormats.size() != 0);
assertTrue(frameRates != null && frameRates.size() != 0);
assertTrue(focusModes != null && focusModes.size() != 0);
@@ -694,6 +704,45 @@
assertTrue(paramActual.getPreviewFrameRate() > 0);
checkExposureCompensation(parameters);
+ checkPreferredPreviewSizeForVideo(parameters);
+ }
+
+ private void checkPreferredPreviewSizeForVideo(Parameters parameters) {
+ List<Size> videoSizes = parameters.getSupportedVideoSizes();
+ Size preferredPreviewSize = parameters.getPreferredPreviewSizeForVideo();
+
+ // If getSupportedVideoSizes() returns null,
+ // getPreferredPreviewSizeForVideo() will return null;
+ // otherwise, if getSupportedVideoSizes() does not return null,
+ // getPreferredPreviewSizeForVideo() will not return null.
+ if (videoSizes == null) {
+ assertNull(preferredPreviewSize);
+ } else {
+ assertNotNull(preferredPreviewSize);
+ }
+
+ // If getPreferredPreviewSizeForVideo() returns null,
+ // getSupportedVideoSizes() will return null;
+ // otherwise, if getPreferredPreviewSizeForVideo() does not return null,
+ // getSupportedVideoSizes() will not return null.
+ if (preferredPreviewSize == null) {
+ assertNull(videoSizes);
+ } else {
+ assertNotNull(videoSizes);
+ }
+
+ if (videoSizes != null) { // implies: preferredPreviewSize != null
+ // If getSupportedVideoSizes() does not return null,
+ // the returned list will contain at least one size.
+ assertTrue(videoSizes.size() > 0);
+
+ // In addition, getPreferredPreviewSizeForVideo() returns a size
+ // that is among the supported preview sizes.
+ List<Size> previewSizes = parameters.getSupportedPreviewSizes();
+ assertNotNull(previewSizes);
+ assertTrue(previewSizes.size() > 0);
+ assertTrue(previewSizes.contains(preferredPreviewSize));
+ }
}
private void checkExposureCompensation(Parameters parameters) {
@@ -761,9 +810,11 @@
ExifInterface exif = new ExifInterface(JPEG_PATH);
assertTrue(exif.hasThumbnail());
byte[] thumb = exif.getThumbnail();
- Bitmap b = BitmapFactory.decodeByteArray(thumb, 0, thumb.length);
- assertEquals(size.width, b.getWidth());
- assertEquals(size.height, b.getHeight());
+ BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
+ bmpOptions.inJustDecodeBounds = true;
+ BitmapFactory.decodeByteArray(thumb, 0, thumb.length, bmpOptions);
+ assertEquals(size.width, bmpOptions.outWidth);
+ assertEquals(size.height, bmpOptions.outHeight);
// Test no thumbnail case.
p.setJpegThumbnailSize(0, 0);
@@ -810,25 +861,10 @@
assertEquals(focalLength, exifFocalLength, 0.001);
// Test gps exif tags.
- mCamera.startPreview();
- parameters.setGpsLatitude(37.736071);
- parameters.setGpsLongitude(-122.441983);
- parameters.setGpsAltitude(21);
- parameters.setGpsTimestamp(1199145600);
- String thirtyTwoCharacters = "GPS NETWORK HYBRID ARE ALL FINE.";
- parameters.setGpsProcessingMethod(thirtyTwoCharacters);
- mCamera.setParameters(parameters);
- mCamera.takePicture(mShutterCallback, mRawPictureCallback, mJpegPictureCallback);
- waitForSnapshotDone();
- exif = new ExifInterface(JPEG_PATH);
- assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
- assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
- assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
- assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
- assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP));
- assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_DATESTAMP));
- assertEquals(thirtyTwoCharacters,
- exif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD));
+ testGpsExifValues(parameters, 37.736071, -122.441983, 21, 1199145600,
+ "GPS NETWORK HYBRID ARE ALL FINE.");
+ testGpsExifValues(parameters, 0.736071, 0.441983, 1, 1199145601, "GPS");
+ testGpsExifValues(parameters, -89.736071, -179.441983, 100000, 1199145602, "NETWORK");
// Test gps tags do not exist after calling removeGpsData.
mCamera.startPreview();
@@ -841,6 +877,34 @@
terminateMessageLooper();
}
+ private void testGpsExifValues(Parameters parameters, double latitude,
+ double longitude, double altitude, long timestamp, String method)
+ throws IOException {
+ mCamera.startPreview();
+ parameters.setGpsLatitude(latitude);
+ parameters.setGpsLongitude(longitude);
+ parameters.setGpsAltitude(altitude);
+ parameters.setGpsTimestamp(timestamp);
+ parameters.setGpsProcessingMethod(method);
+ mCamera.setParameters(parameters);
+ mCamera.takePicture(mShutterCallback, mRawPictureCallback, mJpegPictureCallback);
+ waitForSnapshotDone();
+ ExifInterface exif = new ExifInterface(JPEG_PATH);
+ assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
+ assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
+ assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
+ assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
+ assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP));
+ assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_DATESTAMP));
+ assertEquals(method, exif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD));
+ float[] latLong = new float[2];
+ assertTrue(exif.getLatLong(latLong));
+ assertEquals((float)latitude, latLong[0], 0.0001f);
+ assertEquals((float)longitude, latLong[1], 0.0001f);
+ assertEquals(altitude, exif.getAltitude(-1), 1);
+ assertEquals(timestamp, exif.getGpsDateTime() / 1000);
+ }
+
private void checkGpsDataNull(ExifInterface exif) {
assertNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
assertNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
@@ -877,13 +941,31 @@
Camera.Parameters parameters = mCamera.getParameters();
SurfaceHolder surfaceHolder;
surfaceHolder = getActivity().getSurfaceView().getHolder();
- Size size = parameters.getPreviewSize();
+ CamcorderProfile profile = CamcorderProfile.get(cameraId,
+ CamcorderProfile.QUALITY_LOW);
+
+ // Set the preview size.
+ if (parameters.getSupportedVideoSizes() == null) {
+ parameters.setPreviewSize(profile.videoFrameWidth,
+ profile.videoFrameHeight);
+ } else { // Driver supports separates outputs for preview and video.
+ List<Size> sizes = parameters.getSupportedPreviewSizes();
+ Size preferred = parameters.getPreferredPreviewSizeForVideo();
+ int product = preferred.width * preferred.height;
+ for (Size size: sizes) {
+ if (size.width * size.height <= product) {
+ parameters.setPreviewSize(size.width, size.height);
+ break;
+ }
+ }
+ }
+
mCamera.setParameters(parameters);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.lock(); // Locking again from the same process has no effect.
try {
- recordVideo(size, surfaceHolder);
+ recordVideo(profile, surfaceHolder);
fail("Recording should not succeed because camera is locked.");
} catch (Exception e) {
// expected
@@ -897,26 +979,25 @@
// expected
}
- try {
- recordVideo(size, surfaceHolder);
- } catch (Exception e) {
- fail("Should not throw exception");
- }
+ recordVideo(profile, surfaceHolder); // should not throw exception
+ // Media recorder already releases the camera so the test application
+ // can lock and use the camera now.
mCamera.lock(); // should not fail
mCamera.setParameters(parameters); // should not fail
terminateMessageLooper();
}
- private void recordVideo(Size size, SurfaceHolder surfaceHolder) throws Exception {
+ private void recordVideo(CamcorderProfile profile,
+ SurfaceHolder holder) throws Exception {
MediaRecorder recorder = new MediaRecorder();
try {
+ // Pass the camera from the test application to media recorder.
recorder.setCamera(mCamera);
+ recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
- recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
+ recorder.setProfile(profile);
recorder.setOutputFile("/dev/null");
- recorder.setVideoSize(size.width, size.height);
- recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
- recorder.setPreviewDisplay(surfaceHolder.getSurface());
+ recorder.setPreviewDisplay(holder.getSurface());
recorder.prepare();
recorder.start();
Thread.sleep(5000);
@@ -962,9 +1043,11 @@
callback.mNumCbWithBuffer1 = 0;
callback.mNumCbWithBuffer2 = 0;
callback.mNumCbWithBuffer3 = 0;
- callback.mBuffer1 = new byte[size.width * size.height * 3 / 2];
- callback.mBuffer2 = new byte[size.width * size.height * 3 / 2];
- callback.mBuffer3 = new byte[size.width * size.height * 3 / 2];
+ int format = mCamera.getParameters().getPreviewFormat();
+ int bitsPerPixel = ImageFormat.getBitsPerPixel(format);
+ callback.mBuffer1 = new byte[size.width * size.height * bitsPerPixel / 8];
+ callback.mBuffer2 = new byte[size.width * size.height * bitsPerPixel / 8];
+ callback.mBuffer3 = new byte[size.width * size.height * bitsPerPixel / 8];
// Test if we can get the preview callbacks with specified buffers.
mCamera.addCallbackBuffer(callback.mBuffer1);
@@ -1116,10 +1199,12 @@
// It should not generate callbacks if zoom value is not changed.
mCamera.startSmoothZoom(0);
assertFalse(zoomListener.mZoomDone.block(500));
+ assertEquals(0, mCamera.getParameters().getZoom());
// Test startSmoothZoom.
mCamera.startSmoothZoom(maxZoom);
assertEquals(true, zoomListener.mZoomDone.block(5000));
+ assertEquals(maxZoom, mCamera.getParameters().getZoom());
assertEquals(maxZoom, zoomListener.mValues.size());
for(int i = 0; i < maxZoom; i++) {
// Make sure we get all the callbacks in order.
@@ -1134,6 +1219,7 @@
zoomListener.mZoomDone.close();
mCamera.startSmoothZoom(maxZoom / 2);
assertTrue(zoomListener.mZoomDone.block(5000));
+ assertEquals(maxZoom / 2, mCamera.getParameters().getZoom());
assertEquals(maxZoom - (maxZoom / 2), zoomListener.mValues.size());
int i = maxZoom - 1;
for(Integer value: zoomListener.mValues) {
@@ -1160,6 +1246,7 @@
mCamera.startSmoothZoom(maxZoom);
mCamera.stopSmoothZoom();
assertTrue(zoomListener.mZoomDone.block(5000));
+ assertEquals(zoomListener.mValues.size(), mCamera.getParameters().getZoom());
for(int i = 0; i < zoomListener.mValues.size() - 1; i++) {
// Make sure we get all the callbacks in order (except the last).
assertEquals(i + 1, zoomListener.mValues.get(i).intValue());
@@ -1451,11 +1538,11 @@
waitForSnapshotDone();
assertTrue(mJpegPictureCallbackResult);
assertNotNull(mJpegData);
- Bitmap b = BitmapFactory.decodeByteArray(mJpegData, 0, mJpegData.length);
- assertEquals(pictureSize.width, b.getWidth());
- assertEquals(pictureSize.height, b.getHeight());
- b.recycle();
- b = null;
+ BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
+ bmpOptions.inJustDecodeBounds = true;
+ BitmapFactory.decodeByteArray(mJpegData, 0, mJpegData.length, bmpOptions);
+ assertEquals(pictureSize.width, bmpOptions.outWidth);
+ assertEquals(pictureSize.height, bmpOptions.outHeight);
}
}
terminateMessageLooper();
@@ -1468,7 +1555,9 @@
assertNotNull(data);
Size size = camera.getParameters().getPreviewSize();
assertEquals(expectedPreviewSize, size);
- assertEquals(size.width * size.height * 3 / 2, data.length);
+ int format = camera.getParameters().getPreviewFormat();
+ int bitsPerPixel = ImageFormat.getBitsPerPixel(format);
+ assertEquals(size.width * size.height * bitsPerPixel / 8, data.length);
camera.setPreviewCallback(null);
mPreviewCallbackResult = true;
mPreviewDone.open();
@@ -1516,9 +1605,11 @@
// Test if the actual fps is within fps range.
Size size = parameters.getPreviewSize();
- byte[] buffer1 = new byte[size.width * size.height * 3 / 2];
- byte[] buffer2 = new byte[size.width * size.height * 3 / 2];
- byte[] buffer3 = new byte[size.width * size.height * 3 / 2];
+ int format = mCamera.getParameters().getPreviewFormat();
+ int bitsPerPixel = ImageFormat.getBitsPerPixel(format);
+ byte[] buffer1 = new byte[size.width * size.height * bitsPerPixel / 8];
+ byte[] buffer2 = new byte[size.width * size.height * bitsPerPixel / 8];
+ byte[] buffer3 = new byte[size.width * size.height * bitsPerPixel / 8];
FpsRangePreviewCb callback = new FpsRangePreviewCb();
int[] readBackFps = new int[2];
for (int[] fps: fpsList) {
@@ -1654,4 +1745,224 @@
Character.isLetter(c) && c != 'x');
}
}
+
+ @UiThreadTest
+ public void testSceneMode() throws Exception {
+ int nCameras = Camera.getNumberOfCameras();
+ for (int id = 0; id < nCameras; id++) {
+ Log.v(TAG, "Camera id=" + id);
+ testSceneModeByCamera(id);
+ }
+ }
+
+ private class SceneModeSettings {
+ public String mScene, mFlash, mFocus, mWhiteBalance;
+ public List<String> mSupportedFlash, mSupportedFocus, mSupportedWhiteBalance;
+
+ public SceneModeSettings(Parameters parameters) {
+ mScene = parameters.getSceneMode();
+ mFlash = parameters.getFlashMode();
+ mFocus = parameters.getFocusMode();
+ mWhiteBalance = parameters.getWhiteBalance();
+ mSupportedFlash = parameters.getSupportedFlashModes();
+ mSupportedFocus = parameters.getSupportedFocusModes();
+ mSupportedWhiteBalance = parameters.getSupportedWhiteBalance();
+ }
+ }
+
+ private void testSceneModeByCamera(int cameraId) throws Exception {
+ initializeMessageLooper(cameraId);
+ Parameters parameters = mCamera.getParameters();
+ List<String> supportedSceneModes = parameters.getSupportedSceneModes();
+ if (supportedSceneModes != null) {
+ assertEquals(Parameters.SCENE_MODE_AUTO, parameters.getSceneMode());
+ SceneModeSettings autoSceneMode = new SceneModeSettings(parameters);
+
+ // Store all scene mode affected settings.
+ SceneModeSettings[] settings = new SceneModeSettings[supportedSceneModes.size()];
+ for (int i = 0; i < supportedSceneModes.size(); i++) {
+ parameters.setSceneMode(supportedSceneModes.get(i));
+ mCamera.setParameters(parameters);
+ parameters = mCamera.getParameters();
+ settings[i] = new SceneModeSettings(parameters);
+ }
+
+ // Make sure scene mode settings are consistent before preview and
+ // after preview.
+ mCamera.setPreviewDisplay(getActivity().getSurfaceView().getHolder());
+ mCamera.startPreview();
+ waitForPreviewDone();
+ for (int i = 0; i < supportedSceneModes.size(); i++) {
+ String sceneMode = supportedSceneModes.get(i);
+ parameters.setSceneMode(sceneMode);
+ mCamera.setParameters(parameters);
+ parameters = mCamera.getParameters();
+
+ // In auto scene mode, camera HAL will not remember the previous
+ // flash, focus, and white-balance. It will just take values set
+ // by parameters. But the supported flash, focus, and
+ // white-balance should still be restored in auto scene mode.
+ if (!Parameters.SCENE_MODE_AUTO.equals(sceneMode)) {
+ assertEquals("Flash is inconsistent in scene mode " + sceneMode,
+ settings[i].mFlash, parameters.getFlashMode());
+ assertEquals("Focus is inconsistent in scene mode " + sceneMode,
+ settings[i].mFocus, parameters.getFocusMode());
+ assertEquals("White balance is inconsistent in scene mode " + sceneMode,
+ settings[i].mWhiteBalance, parameters.getWhiteBalance());
+ }
+ assertEquals("Suppported flash modes are inconsistent in scene mode " + sceneMode,
+ settings[i].mSupportedFlash, parameters.getSupportedFlashModes());
+ assertEquals("Suppported focus modes are inconsistent in scene mode " + sceneMode,
+ settings[i].mSupportedFocus, parameters.getSupportedFocusModes());
+ assertEquals("Suppported white balance are inconsistent in scene mode " + sceneMode,
+ settings[i].mSupportedWhiteBalance, parameters.getSupportedWhiteBalance());
+ }
+
+ for (int i = 0; i < settings.length; i++) {
+ if (Parameters.SCENE_MODE_AUTO.equals(settings[i].mScene)) continue;
+
+ // If the scene mode overrides the flash mode, it should also override
+ // the supported flash modes.
+ if (autoSceneMode.mSupportedFlash != null) {
+ if (!autoSceneMode.mFlash.equals(settings[i].mFlash)) {
+ assertEquals(1, settings[i].mSupportedFlash.size());
+ assertTrue(settings[i].mSupportedFlash.contains(settings[i].mFlash));
+ }
+ }
+
+ // If the scene mode overrides the focus mode, it should also override
+ // the supported focus modes.
+ if (autoSceneMode.mSupportedFocus != null) {
+ if (!autoSceneMode.mFocus.equals(settings[i].mFocus)) {
+ assertEquals(1, settings[i].mSupportedFocus.size());
+ assertTrue(settings[i].mSupportedFocus.contains(settings[i].mFocus));
+ }
+ }
+
+ // If the scene mode overrides the white balance, it should also override
+ // the supported white balance.
+ if (autoSceneMode.mSupportedWhiteBalance != null) {
+ if (!autoSceneMode.mWhiteBalance.equals(settings[i].mWhiteBalance)) {
+ assertEquals(1, settings[i].mSupportedWhiteBalance.size());
+ assertTrue(settings[i].mSupportedWhiteBalance.contains(settings[i].mWhiteBalance));
+ }
+ }
+ }
+ }
+ terminateMessageLooper();
+ }
+
+ @UiThreadTest
+ public void testInvalidParameters() throws Exception {
+ int nCameras = Camera.getNumberOfCameras();
+ for (int id = 0; id < nCameras; id++) {
+ Log.v(TAG, "Camera id=" + id);
+ testInvalidParametersByCamera(id);
+ }
+ }
+
+ private void testInvalidParametersByCamera(int cameraId) throws Exception {
+ initializeMessageLooper(cameraId);
+ // Test flash mode.
+ Parameters parameters = mCamera.getParameters();
+ List<String> list = parameters.getSupportedFlashModes();
+ if (list != null && list.size() > 0) {
+ String original = parameters.getFlashMode();
+ parameters.setFlashMode("invalid");
+ try {
+ mCamera.setParameters(parameters);
+ fail("Should throw exception for invalid parameters");
+ } catch (RuntimeException e) {
+ // expected
+ }
+ parameters = mCamera.getParameters();
+ assertEquals(original, parameters.getFlashMode());
+ }
+
+ // Test focus mode.
+ String originalFocus = parameters.getFocusMode();
+ parameters.setFocusMode("invalid");
+ try {
+ mCamera.setParameters(parameters);
+ fail("Should throw exception for invalid parameters");
+ } catch (RuntimeException e) {
+ // expected
+ }
+ parameters = mCamera.getParameters();
+ assertEquals(originalFocus, parameters.getFocusMode());
+
+ // Test preview size.
+ Size originalSize = parameters.getPreviewSize();
+ parameters.setPreviewSize(-1, -1);
+ try {
+ mCamera.setParameters(parameters);
+ fail("Should throw exception for invalid parameters");
+ } catch (RuntimeException e) {
+ // expected
+ }
+ parameters = mCamera.getParameters();
+ assertEquals(originalSize, parameters.getPreviewSize());
+
+ terminateMessageLooper();
+ }
+
+ public void testGetParameterDuringFocus() throws Exception {
+ int nCameras = Camera.getNumberOfCameras();
+ for (int id = 0; id < nCameras; id++) {
+ Log.v(TAG, "Camera id=" + id);
+ testGetParameterDuringFocusByCamera(id);
+ }
+ }
+
+ private void testGetParameterDuringFocusByCamera(int cameraId) throws Exception {
+ initializeMessageLooper(cameraId);
+ mCamera.setPreviewDisplay(getActivity().getSurfaceView().getHolder());
+ mCamera.setErrorCallback(mErrorCallback);
+ mCamera.startPreview();
+ Parameters parameters = mCamera.getParameters();
+ for (String focusMode: parameters.getSupportedFocusModes()) {
+ if (focusMode.equals(parameters.FOCUS_MODE_AUTO)
+ || focusMode.equals(parameters.FOCUS_MODE_MACRO)) {
+ parameters.setFocusMode(focusMode);
+ mCamera.setParameters(parameters);
+ mCamera.autoFocus(mAutoFocusCallback);
+ // This should not crash or throw exception.
+ mCamera.getParameters();
+ waitForFocusDone();
+
+
+ mCamera.autoFocus(mAutoFocusCallback);
+ // Add a small delay to make sure focus has started.
+ Thread.sleep(100);
+ // This should not crash or throw exception.
+ mCamera.getParameters();
+ }
+ }
+ terminateMessageLooper();
+ }
+
+ public void testPreviewFormats() throws Exception {
+ int nCameras = Camera.getNumberOfCameras();
+ for (int id = 0; id < nCameras; id++) {
+ Log.v(TAG, "Camera id=" + id);
+ testPreviewFormatsByCamera(id);
+ }
+ }
+
+ private void testPreviewFormatsByCamera(int cameraId) throws Exception {
+ initializeMessageLooper(cameraId);
+ mCamera.setPreviewDisplay(getActivity().getSurfaceView().getHolder());
+ mCamera.setErrorCallback(mErrorCallback);
+ Parameters parameters = mCamera.getParameters();
+ for (int format: parameters.getSupportedPreviewFormats()) {
+ Log.v(TAG, "Test preview format " + format);
+ parameters.setPreviewFormat(format);
+ mCamera.setParameters(parameters);
+ mCamera.setOneShotPreviewCallback(mPreviewCallback);
+ mCamera.startPreview();
+ waitForPreviewDone();
+ assertTrue(mPreviewCallbackResult);
+ }
+ terminateMessageLooper();
+ }
}
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index b4053cf..5dbec66 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -22,6 +22,7 @@
import static android.media.AudioManager.FLAG_ALLOW_RINGER_MODES;
import static android.media.AudioManager.FLAG_SHOW_UI;
import static android.media.AudioManager.MODE_IN_CALL;
+import static android.media.AudioManager.MODE_IN_COMMUNICATION;
import static android.media.AudioManager.MODE_NORMAL;
import static android.media.AudioManager.MODE_RINGTONE;
import static android.media.AudioManager.RINGER_MODE_NORMAL;
@@ -199,6 +200,8 @@
assertEquals(MODE_RINGTONE, mAudioManager.getMode());
mAudioManager.setMode(MODE_IN_CALL);
assertEquals(MODE_IN_CALL, mAudioManager.getMode());
+ mAudioManager.setMode(MODE_IN_COMMUNICATION);
+ assertEquals(MODE_IN_COMMUNICATION, mAudioManager.getMode());
mAudioManager.setMode(MODE_NORMAL);
assertEquals(MODE_NORMAL, mAudioManager.getMode());
}
@@ -260,25 +263,30 @@
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_RINGTONE));
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_NORMAL));
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+ assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
mAudioManager.setBluetoothScoOn(true);
assertTrue(mAudioManager.isBluetoothScoOn());
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_RINGTONE));
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_NORMAL));
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+ assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
mAudioManager.setBluetoothScoOn(false);
assertFalse(mAudioManager.isBluetoothScoOn());
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_RINGTONE));
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_NORMAL));
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+ assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
mAudioManager.setSpeakerphoneOn(true);
assertTrue(mAudioManager.isSpeakerphoneOn());
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+ assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
mAudioManager.setSpeakerphoneOn(false);
assertFalse(mAudioManager.isSpeakerphoneOn());
assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+ assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
}
@TestTargets({
@@ -501,7 +509,7 @@
AudioManager.STREAM_VOICE_CALL,
AudioManager.STREAM_RING };
- mAudioManager.adjustVolume(ADJUST_RAISE, 100);
+ mAudioManager.adjustVolume(ADJUST_RAISE, 0);
mAudioManager.adjustSuggestedStreamVolume(
ADJUST_LOWER, USE_DEFAULT_STREAM_TYPE, FLAG_SHOW_UI);
@@ -525,44 +533,27 @@
assertEquals(k - 1, mAudioManager.getStreamVolume(streams[i]));
}
+ // test ringer modes changes
mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
mAudioManager.setStreamVolume(streams[i], 1, FLAG_SHOW_UI);
assertEquals(1, mAudioManager.getStreamVolume(streams[i]));
- if (streams[i] == AudioManager.STREAM_RING) {
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_SHOW_UI);
- assertEquals(0, mAudioManager.getStreamVolume(streams[i]));
- // adjusting the volume to zero should result in either silent or vibrate mode
- assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE ||
- mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
- mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
- assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
- assertEquals(1, mAudioManager.getStreamVolume(streams[i]));
- } else {
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_SHOW_UI);
- assertEquals(0, mAudioManager.getStreamVolume(streams[i]));
- // lowering the volume should NOT have changed the ringer mode
- assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
- // API quirk: volume must be decremented from 1 to get ringer mode change
- mAudioManager.setStreamVolume(streams[i], 1, FLAG_SHOW_UI);
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_ALLOW_RINGER_MODES);
- // lowering the volume should have changed the ringer mode
- assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE ||
- mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_ALLOW_RINGER_MODES);
- // adjusting the volume to zero should result in either silent or vibrate mode
- assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE ||
- mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_RAISE, FLAG_ALLOW_RINGER_MODES);
- // There are two possible ways the device may work. It may have a silent/vibrate
- // mode or it may have distinct silent and vibrate modes.
- assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_NORMAL ||
- mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE);
- // Increase the volume one more time to get out of the vibrate mode which may
- // be separate from silent mode.
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_RAISE, FLAG_ALLOW_RINGER_MODES);
- assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
- }
+
+ // decreasing the volume from 1 to 0 shouldn't change ringer modes
+ adjustStreamVolumeAndRingerMode(streams[i], ADJUST_LOWER);
+ assertEquals("Stream: " + i, 0, mAudioManager.getStreamVolume(streams[i]));
+ assertEquals("Stream: " + i, RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+
+ // decreasing the volume from 0 should change ringer modes
+ adjustStreamVolumeAndRingerMode(streams[i], ADJUST_LOWER);
+ assertEquals("Stream: " + i, 0, mAudioManager.getStreamVolume(streams[i]));
+ assertTrue("Stream: " + i, mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE
+ || mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
+
+ // increasing the volume from 0 should change back to normal
+ adjustStreamVolumeAndRingerMode(streams[i], ADJUST_RAISE);
+ assertEquals("Stream: " + i, 0, mAudioManager.getStreamVolume(streams[i]));
+ assertTrue("Stream: " + i, mAudioManager.getRingerMode() == RINGER_MODE_NORMAL);
// volume raise
mAudioManager.setStreamVolume(streams[i], 0, FLAG_SHOW_UI);
@@ -583,7 +574,7 @@
// adjust volume
int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
- mAudioManager.adjustVolume(ADJUST_RAISE, 100);
+ mAudioManager.adjustVolume(ADJUST_RAISE, 0);
MediaPlayer mp = MediaPlayer.create(mContext, MP3_TO_PLAY);
mp.setAudioStreamType(STREAM_MUSIC);
@@ -617,6 +608,17 @@
assertFalse(mAudioManager.isMusicActive());
}
+ /**
+ * Imitate how pressing the volume key adjusts the volume either up or down and releasing the
+ * key causes an ADJUST_SAME direction afterwards.
+ */
+ private void adjustStreamVolumeAndRingerMode(int streamType, int direction) {
+ mAudioManager.adjustStreamVolume(streamType, direction,
+ FLAG_SHOW_UI | FLAG_ALLOW_RINGER_MODES);
+ mAudioManager.adjustStreamVolume(streamType, ADJUST_SAME,
+ FLAG_SHOW_UI | FLAG_ALLOW_RINGER_MODES);
+ }
+
public void setResult(int resultCode) {
mSync.notifyResult();
mResultCode = resultCode;
diff --git a/tests/tests/media/src/android/media/cts/AudioRecordTest.java b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
index 5f6fc2c..74b0952 100644
--- a/tests/tests/media/src/android/media/cts/AudioRecordTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
@@ -18,6 +18,7 @@
import java.nio.ByteBuffer;
+import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
@@ -40,6 +41,7 @@
private boolean mIsOnPeriodicNotificationCalled;
private boolean mIsHandleMessageCalled;
private Looper mLooper;
+ private int MAX_RECORD_START_TIME_MS = 100;
@Override
protected void setUp() throws Exception {
@@ -228,6 +230,9 @@
final int RECORD_TIME = 10000;
assertEquals(AudioRecord.STATE_INITIALIZED, mAudioRecord.getState());
+ PackageManager pm = getContext().getPackageManager();
+ boolean isLowLatency = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);
+
int markerInFrames = mAudioRecord.getSampleRate() / 2;
assertEquals(AudioRecord.SUCCESS,
mAudioRecord.setNotificationMarkerPosition(markerInFrames));
@@ -253,6 +258,10 @@
byte[] byteData = new byte[BUFFER_SIZE];
long time = System.currentTimeMillis();
mAudioRecord.startRecording();
+ if (isLowLatency) {
+ assertTrue("Record start time too long",
+ (System.currentTimeMillis() - time) < MAX_RECORD_START_TIME_MS);
+ }
assertEquals(AudioRecord.RECORDSTATE_RECORDING, mAudioRecord.getRecordingState());
while (System.currentTimeMillis() - time < RECORD_TIME) {
Thread.sleep(SLEEP_TIME);
diff --git a/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java b/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
index b94da11..e2cbebb 100644
--- a/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
+++ b/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
@@ -22,6 +22,8 @@
import dalvik.annotation.TestTargets;
import android.hardware.Camera;
+import android.hardware.Camera.Parameters;
+import android.hardware.Camera.Size;
import android.media.CamcorderProfile;
import android.test.AndroidTestCase;
import android.util.Log;
@@ -33,7 +35,16 @@
private static final String TAG = "CamcorderProfileTest";
- private void checkProfile(CamcorderProfile profile) {
+ // Uses get without id if cameraId == -1 and get with id otherwise.
+ private CamcorderProfile getWithOptionalId(int quality, int cameraId) {
+ if (cameraId == -1) {
+ return CamcorderProfile.get(quality);
+ } else {
+ return CamcorderProfile.get(cameraId, quality);
+ }
+ }
+
+ private void checkProfile(CamcorderProfile profile, List<Size> videoSizes) {
Log.v(TAG, String.format("profile: duration=%d, quality=%d, " +
"fileFormat=%d, videoCodec=%d, videoBitRate=%d, videoFrameRate=%d, " +
"videoFrameWidth=%d, videoFrameHeight=%d, audioCodec=%d, " +
@@ -52,7 +63,19 @@
profile.audioChannels));
assertTrue(profile.duration > 0);
assertTrue(profile.quality == CamcorderProfile.QUALITY_LOW ||
- profile.quality == CamcorderProfile.QUALITY_HIGH);
+ profile.quality == CamcorderProfile.QUALITY_HIGH ||
+ profile.quality == CamcorderProfile.QUALITY_QCIF ||
+ profile.quality == CamcorderProfile.QUALITY_CIF ||
+ profile.quality == CamcorderProfile.QUALITY_480P ||
+ profile.quality == CamcorderProfile.QUALITY_720P ||
+ profile.quality == CamcorderProfile.QUALITY_1080P ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_LOW ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_HIGH ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_QCIF ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_CIF ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_480P ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_720P ||
+ profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_1080P);
assertTrue(profile.videoBitRate > 0);
assertTrue(profile.videoFrameRate > 0);
assertTrue(profile.videoFrameWidth > 0);
@@ -60,6 +83,148 @@
assertTrue(profile.audioBitRate > 0);
assertTrue(profile.audioSampleRate > 0);
assertTrue(profile.audioChannels > 0);
+ assertTrue(isSizeSupported(profile.videoFrameWidth,
+ profile.videoFrameHeight,
+ videoSizes));
+ }
+
+ private void assertProfileEquals(CamcorderProfile expectedProfile,
+ CamcorderProfile actualProfile) {
+ assertEquals(expectedProfile.duration, actualProfile.duration);
+ assertEquals(expectedProfile.fileFormat, actualProfile.fileFormat);
+ assertEquals(expectedProfile.videoCodec, actualProfile.videoCodec);
+ assertEquals(expectedProfile.videoBitRate, actualProfile.videoBitRate);
+ assertEquals(expectedProfile.videoFrameRate, actualProfile.videoFrameRate);
+ assertEquals(expectedProfile.videoFrameWidth, actualProfile.videoFrameWidth);
+ assertEquals(expectedProfile.videoFrameHeight, actualProfile.videoFrameHeight);
+ assertEquals(expectedProfile.audioCodec, actualProfile.audioCodec);
+ assertEquals(expectedProfile.audioBitRate, actualProfile.audioBitRate);
+ assertEquals(expectedProfile.audioSampleRate, actualProfile.audioSampleRate);
+ assertEquals(expectedProfile.audioChannels, actualProfile.audioChannels);
+ }
+
+ private void checkSpecificProfileDimensions(CamcorderProfile profile, int quality) {
+ Log.v(TAG, String.format("specific profile: quality=%d, width = %d, height = %d",
+ profile.quality, profile.videoFrameWidth, profile.videoFrameHeight));
+
+ switch (quality) {
+ case CamcorderProfile.QUALITY_QCIF:
+ case CamcorderProfile.QUALITY_TIME_LAPSE_QCIF:
+ assertEquals(176, profile.videoFrameWidth);
+ assertEquals(144, profile.videoFrameHeight);
+ break;
+
+ case CamcorderProfile.QUALITY_CIF:
+ case CamcorderProfile.QUALITY_TIME_LAPSE_CIF:
+ assertEquals(352, profile.videoFrameWidth);
+ assertEquals(288, profile.videoFrameHeight);
+ break;
+
+ case CamcorderProfile.QUALITY_480P:
+ case CamcorderProfile.QUALITY_TIME_LAPSE_480P:
+ assertTrue(720 == profile.videoFrameWidth || // SMPTE 293M/ITU-R Rec. 601
+ 640 == profile.videoFrameWidth || // ATSC/NTSC (square sampling)
+ 704 == profile.videoFrameWidth); // ATSC/NTSC (non-square sampling)
+ assertEquals(480, profile.videoFrameHeight);
+ break;
+
+ case CamcorderProfile.QUALITY_720P:
+ case CamcorderProfile.QUALITY_TIME_LAPSE_720P:
+ assertEquals(1280, profile.videoFrameWidth);
+ assertEquals(720, profile.videoFrameHeight);
+ break;
+
+ case CamcorderProfile.QUALITY_1080P:
+ case CamcorderProfile.QUALITY_TIME_LAPSE_1080P:
+ // 1080p could be either 1920x1088 or 1920x1080.
+ assertEquals(1920, profile.videoFrameWidth);
+ assertTrue(1088 == profile.videoFrameHeight ||
+ 1080 == profile.videoFrameHeight);
+ break;
+ }
+ }
+
+ // Checks if the existing specific profiles have the correct dimensions.
+ // Also checks that the mimimum quality specific profile matches the low profile and
+ // similarly that the maximum quality specific profile matches the high profile.
+ private void checkSpecificProfiles(
+ int cameraId,
+ CamcorderProfile low,
+ CamcorderProfile high,
+ int[] specificQualities,
+ List<Size> videoSizes) {
+
+ CamcorderProfile minProfile = null;
+ CamcorderProfile maxProfile = null;
+
+ for (int i = 0; i < specificQualities.length; i++) {
+ int quality = specificQualities[i];
+ if ((cameraId != -1 && CamcorderProfile.hasProfile(cameraId, quality)) ||
+ (cameraId == -1 && CamcorderProfile.hasProfile(quality))) {
+ CamcorderProfile profile = getWithOptionalId(quality, cameraId);
+ checkSpecificProfileDimensions(profile, quality);
+
+ assertTrue(isSizeSupported(profile.videoFrameWidth,
+ profile.videoFrameHeight,
+ videoSizes));
+
+ if (minProfile == null) {
+ minProfile = profile;
+ }
+ maxProfile = profile;
+ }
+ }
+
+ assertNotNull(minProfile);
+ assertNotNull(maxProfile);
+
+ Log.v(TAG, String.format("min profile: quality=%d, width = %d, height = %d",
+ minProfile.quality, minProfile.videoFrameWidth, minProfile.videoFrameHeight));
+ Log.v(TAG, String.format("max profile: quality=%d, width = %d, height = %d",
+ maxProfile.quality, maxProfile.videoFrameWidth, maxProfile.videoFrameHeight));
+
+ assertProfileEquals(low, minProfile);
+ assertProfileEquals(high, maxProfile);
+
+ }
+
+ private void checkGet(int cameraId) {
+ Log.v(TAG, (cameraId == -1)
+ ? "Checking get without id"
+ : "Checking get with id = " + cameraId);
+
+ final List<Size> videoSizes = getSupportedVideoSizes(cameraId);
+
+ CamcorderProfile lowProfile =
+ getWithOptionalId(CamcorderProfile.QUALITY_LOW, cameraId);
+ CamcorderProfile highProfile =
+ getWithOptionalId(CamcorderProfile.QUALITY_HIGH, cameraId);
+ checkProfile(lowProfile, videoSizes);
+ checkProfile(highProfile, videoSizes);
+
+ CamcorderProfile lowTimeLapseProfile =
+ getWithOptionalId(CamcorderProfile.QUALITY_TIME_LAPSE_LOW, cameraId);
+ CamcorderProfile highTimeLapseProfile =
+ getWithOptionalId(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH, cameraId);
+ checkProfile(lowTimeLapseProfile, null);
+ checkProfile(highTimeLapseProfile, null);
+
+ int[] specificProfileQualities = {CamcorderProfile.QUALITY_QCIF,
+ CamcorderProfile.QUALITY_CIF,
+ CamcorderProfile.QUALITY_480P,
+ CamcorderProfile.QUALITY_720P,
+ CamcorderProfile.QUALITY_1080P};
+
+ int[] specificTimeLapseProfileQualities = {CamcorderProfile.QUALITY_TIME_LAPSE_QCIF,
+ CamcorderProfile.QUALITY_TIME_LAPSE_CIF,
+ CamcorderProfile.QUALITY_TIME_LAPSE_480P,
+ CamcorderProfile.QUALITY_TIME_LAPSE_720P,
+ CamcorderProfile.QUALITY_TIME_LAPSE_1080P};
+
+ checkSpecificProfiles(cameraId, lowProfile, highProfile,
+ specificProfileQualities, videoSizes);
+ checkSpecificProfiles(cameraId, lowTimeLapseProfile, highTimeLapseProfile,
+ specificTimeLapseProfileQualities, null);
}
@TestTargets({
@@ -70,10 +235,7 @@
)
})
public void testGet() {
- CamcorderProfile lowProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
- CamcorderProfile highProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
- checkProfile(lowProfile);
- checkProfile(highProfile);
+ checkGet(-1);
}
@TestTargets({
@@ -85,13 +247,31 @@
})
public void testGetWithId() {
int nCamera = Camera.getNumberOfCameras();
- for (int id = 0; id < nCamera; id++) {
- CamcorderProfile lowProfile = CamcorderProfile.get(id,
- CamcorderProfile.QUALITY_LOW);
- CamcorderProfile highProfile = CamcorderProfile.get(id,
- CamcorderProfile.QUALITY_HIGH);
- checkProfile(lowProfile);
- checkProfile(highProfile);
+ for (int cameraId = 0; cameraId < nCamera; cameraId++) {
+ checkGet(cameraId);
}
}
+
+ private List<Size> getSupportedVideoSizes(int cameraId) {
+ Camera camera = (cameraId == -1)? Camera.open(): Camera.open(cameraId);
+ Parameters parameters = camera.getParameters();
+ List<Size> videoSizes = parameters.getSupportedVideoSizes();
+ if (videoSizes == null) {
+ videoSizes = parameters.getSupportedPreviewSizes();
+ assertNotNull(videoSizes);
+ }
+ camera.release();
+ return videoSizes;
+ }
+
+ private boolean isSizeSupported(int width, int height, List<Size> sizes) {
+ if (sizes == null) return true;
+
+ for (Size size: sizes) {
+ if (size.width == width && size.height == height) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index 12cc21e..3751b3c 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -48,11 +48,13 @@
public static final int TYPE_MOBILE = ConnectivityManager.TYPE_MOBILE;
public static final int TYPE_WIFI = ConnectivityManager.TYPE_WIFI;
private static final int HOST_ADDRESS = 0x7f000001;// represent ip 127.0.0.1
+
+ // device could have only one interface: data, wifi.
+ private static final int MIN_NUM_NETWORK_TYPES = 1;
+
private ConnectivityManager mCm;
private WifiManager mWifiManager;
private PackageManager mPackageManager;
- // must include both mobile data + wifi
- private static final int MIN_NUM_NETWORK_TYPES = 2;
@Override
protected void setUp() throws Exception {
@@ -68,28 +70,27 @@
args = {int.class}
)
public void testGetNetworkInfo() {
-
- // this test assumes that there are at least two network types.
assertTrue(mCm.getAllNetworkInfo().length >= MIN_NUM_NETWORK_TYPES);
- NetworkInfo ni = mCm.getNetworkInfo(1);
- State state = ni.getState();
- assertTrue(State.UNKNOWN.ordinal() >= state.ordinal()
- && state.ordinal() >= State.CONNECTING.ordinal());
- DetailedState ds = ni.getDetailedState();
- assertTrue(DetailedState.FAILED.ordinal() >= ds.ordinal()
- && ds.ordinal() >= DetailedState.IDLE.ordinal());
-
- ni = mCm.getNetworkInfo(0);
- state = ni.getState();
- assertTrue(State.UNKNOWN.ordinal() >= state.ordinal()
- && state.ordinal() >= State.CONNECTING.ordinal());
- ds = ni.getDetailedState();
- assertTrue(DetailedState.FAILED.ordinal() >= ds.ordinal()
- && ds.ordinal() >= DetailedState.IDLE.ordinal());
-
+ NetworkInfo ni = mCm.getNetworkInfo(TYPE_WIFI);
+ if (ni != null) {
+ State state = ni.getState();
+ assertTrue(State.UNKNOWN.ordinal() >= state.ordinal()
+ && state.ordinal() >= State.CONNECTING.ordinal());
+ DetailedState ds = ni.getDetailedState();
+ assertTrue(DetailedState.FAILED.ordinal() >= ds.ordinal()
+ && ds.ordinal() >= DetailedState.IDLE.ordinal());
+ }
+ ni = mCm.getNetworkInfo(TYPE_MOBILE);
+ if (ni != null) {
+ State state = ni.getState();
+ assertTrue(State.UNKNOWN.ordinal() >= state.ordinal()
+ && state.ordinal() >= State.CONNECTING.ordinal());
+ DetailedState ds = ni.getDetailedState();
+ assertTrue(DetailedState.FAILED.ordinal() >= ds.ordinal()
+ && ds.ordinal() >= DetailedState.IDLE.ordinal());
+ }
ni = mCm.getNetworkInfo(-1);
assertNull(ni);
-
}
@TestTargets({
@@ -142,9 +143,21 @@
final String invalidateFeature = "invalidateFeature";
final String mmsFeature = "enableMMS";
final int failureCode = -1;
+ final int wifiOnlyStartFailureCode = 3;
+ final int wifiOnlyStopFailureCode = 1;
- assertEquals(failureCode, mCm.startUsingNetworkFeature(TYPE_MOBILE, invalidateFeature));
- assertEquals(failureCode, mCm.stopUsingNetworkFeature(TYPE_MOBILE, invalidateFeature));
+ NetworkInfo ni = mCm.getNetworkInfo(TYPE_MOBILE);
+ if (ni != null) {
+ assertEquals(failureCode, mCm.startUsingNetworkFeature(TYPE_MOBILE,
+ invalidateFeature));
+ assertEquals(failureCode, mCm.stopUsingNetworkFeature(TYPE_MOBILE,
+ invalidateFeature));
+ } else {
+ assertEquals(wifiOnlyStartFailureCode, mCm.startUsingNetworkFeature(TYPE_MOBILE,
+ invalidateFeature));
+ assertEquals(wifiOnlyStopFailureCode, mCm.stopUsingNetworkFeature(TYPE_MOBILE,
+ invalidateFeature));
+ }
// Should return failure(-1) because MMS is not supported on WIFI.
assertEquals(failureCode, mCm.startUsingNetworkFeature(TYPE_WIFI, mmsFeature));
diff --git a/tests/tests/net/src/android/net/cts/NetworkInfoTest.java b/tests/tests/net/src/android/net/cts/NetworkInfoTest.java
index 99e8e15..b333be7 100644
--- a/tests/tests/net/src/android/net/cts/NetworkInfoTest.java
+++ b/tests/tests/net/src/android/net/cts/NetworkInfoTest.java
@@ -120,50 +120,47 @@
public void testAccessNetworkInfoProperties() {
ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
-
NetworkInfo[] ni = cm.getAllNetworkInfo();
assertTrue(ni.length >= 2);
- assertFalse(ni[TYPE_MOBILE].isFailover());
- assertFalse(ni[TYPE_WIFI].isFailover());
-
- // test environment:connect as TYPE_MOBILE, and connect to internet.
- assertEquals(TYPE_MOBILE, ni[TYPE_MOBILE].getType());
- assertEquals(TYPE_WIFI, ni[TYPE_WIFI].getType());
-
- // don't know the return value
- ni[TYPE_MOBILE].getSubtype();
- ni[TYPE_WIFI].getSubtype();
-
- assertEquals(MOBILE_TYPE_NAME, ni[TYPE_MOBILE].getTypeName());
- assertEquals(WIFI_TYPE_NAME, ni[TYPE_WIFI].getTypeName());
-
- // don't know the return value
- ni[TYPE_MOBILE].getSubtypeName();
- ni[TYPE_WIFI].getSubtypeName();
-
- if(ni[TYPE_MOBILE].isConnectedOrConnecting()) {
- assertTrue(ni[TYPE_MOBILE].isAvailable());
- assertTrue(ni[TYPE_MOBILE].isConnected());
- assertEquals(State.CONNECTED, ni[TYPE_MOBILE].getState());
- assertEquals(DetailedState.CONNECTED, ni[TYPE_MOBILE].getDetailedState());
- ni[TYPE_MOBILE].getReason();
- ni[TYPE_MOBILE].getExtraInfo();
+ for (NetworkInfo netInfo: ni) {
+ switch (netInfo.getType()) {
+ case TYPE_MOBILE:
+ // don't know the return value
+ netInfo.getSubtype();
+ assertEquals(MOBILE_TYPE_NAME, netInfo.getTypeName());
+ // don't know the return value
+ netInfo.getSubtypeName();
+ if(netInfo.isConnectedOrConnecting()) {
+ assertTrue(netInfo.isAvailable());
+ assertTrue(netInfo.isConnected());
+ assertEquals(State.CONNECTED, netInfo.getState());
+ assertEquals(DetailedState.CONNECTED, netInfo.getDetailedState());
+ netInfo.getReason();
+ netInfo.getExtraInfo();
+ }
+ assertFalse(netInfo.isRoaming());
+ assertNotNull(netInfo.toString());
+ break;
+ case TYPE_WIFI:
+ netInfo.getSubtype();
+ assertEquals(WIFI_TYPE_NAME, netInfo.getTypeName());
+ netInfo.getSubtypeName();
+ if(netInfo.isConnectedOrConnecting()) {
+ assertTrue(netInfo.isAvailable());
+ assertTrue(netInfo.isConnected());
+ assertEquals(State.CONNECTED, netInfo.getState());
+ assertEquals(DetailedState.CONNECTED, netInfo.getDetailedState());
+ netInfo.getReason();
+ netInfo.getExtraInfo();
+ }
+ assertFalse(netInfo.isRoaming());
+ assertNotNull(netInfo.toString());
+ break;
+ // TODO: Add BLUETOOTH_TETHER testing
+ default:
+ break;
+ }
}
-
- if(ni[TYPE_WIFI].isConnectedOrConnecting()) {
- assertTrue(ni[TYPE_WIFI].isAvailable());
- assertTrue(ni[TYPE_WIFI].isConnected());
- assertEquals(State.CONNECTED, ni[TYPE_WIFI].getState());
- assertEquals(DetailedState.CONNECTED, ni[TYPE_WIFI].getDetailedState());
- ni[TYPE_WIFI].getReason();
- ni[TYPE_WIFI].getExtraInfo();
- }
-
- assertFalse(ni[TYPE_MOBILE].isRoaming());
- assertFalse(ni[TYPE_WIFI].isRoaming());
-
- assertNotNull(ni[TYPE_MOBILE].toString());
- assertNotNull(ni[TYPE_WIFI].toString());
}
}
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index ec3f49a..89f26f2 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -114,6 +114,8 @@
Pattern.compile("^([0-9A-Za-z._-]+)$");
private static final Pattern ID_PATTERN =
Pattern.compile("^([0-9A-Za-z._-]+)$");
+ private static final Pattern HARDWARE_PATTERN =
+ Pattern.compile("^([0-9A-Za-z.,_-]+)$");
private static final Pattern PRODUCT_PATTERN =
Pattern.compile("^([0-9A-Za-z._-]+)$");
private static final Pattern SERIAL_NUMBER_PATTERN =
@@ -135,10 +137,14 @@
// Build.FINGERPRINT tested by BuildVersionTest
+ assertTrue(HARDWARE_PATTERN.matcher(Build.HARDWARE).matches());
+
assertNotEmpty(Build.HOST);
assertTrue(ID_PATTERN.matcher(Build.ID).matches());
+ assertNotEmpty(Build.MANUFACTURER);
+
assertNotEmpty(Build.MODEL);
assertTrue(PRODUCT_PATTERN.matcher(Build.PRODUCT).matches());
diff --git a/tests/tests/os/src/android/os/cts/BuildVersionTest.java b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
index cc15f6f..954507b 100644
--- a/tests/tests/os/src/android/os/cts/BuildVersionTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
@@ -32,8 +32,8 @@
private static final String LOG_TAG = "BuildVersionTest";
private static final Set<String> EXPECTED_RELEASES =
- new HashSet<String>(Arrays.asList("2.3.3", "2.3.4"));
- private static final int EXPECTED_SDK = 10;
+ new HashSet<String>(Arrays.asList("3.1"));
+ private static final int EXPECTED_SDK = 12;
public void testReleaseVersion() {
// Applications may rely on the exact release version
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
index ce6658f..3974b6c 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
@@ -28,9 +28,14 @@
import android.os.Parcelable;
import android.os.ParcelFileDescriptor.AutoCloseInputStream;
import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
@@ -110,6 +115,72 @@
}
@TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ method = "fromData",
+ args = {byte[].class}
+ )
+ public void testFromData() throws IOException {
+ assertNull(ParcelFileDescriptor.fromData(null, null));
+ byte[] data = new byte[] { 0 };
+ assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
+ data = new byte[] { 0, 1, 2, 3 };
+ assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
+ data = new byte[0];
+ assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
+
+ // Check that modifying the data does not modify the data in the FD
+ data = new byte[] { 0, 1, 2, 3 };
+ ParcelFileDescriptor pfd = ParcelFileDescriptor.fromData(data, null);
+ data[1] = 42;
+ assertFileDescriptorContent(new byte[] { 0, 1, 2, 3 }, pfd);
+ }
+
+ private static void assertFileDescriptorContent(byte[] expected, ParcelFileDescriptor fd)
+ throws IOException {
+ assertInputStreamContent(expected, new ParcelFileDescriptor.AutoCloseInputStream(fd));
+ }
+
+ private static void assertInputStreamContent(byte[] expected, InputStream is)
+ throws IOException {
+ try {
+ byte[] observed = new byte[expected.length];
+ int count = is.read(observed);
+ assertEquals(expected.length, count);
+ assertEquals(-1, is.read());
+ MoreAsserts.assertEquals(expected, observed);
+ } finally {
+ is.close();
+ }
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "Tests that skip() works on FDs returned by fromData()",
+ method = "fromData",
+ args = {byte[].class}
+ )
+ public void testFromDataSkip() throws IOException {
+ byte[] data = new byte[] { 40, 41, 42, 43, 44, 45, 46 };
+ ParcelFileDescriptor pfd = ParcelFileDescriptor.fromData(data, null);
+ assertNotNull(pfd);
+ FileDescriptor fd = pfd.getFileDescriptor();
+ assertNotNull(fd);
+ assertTrue(fd.valid());
+ FileInputStream is = new FileInputStream(fd);
+ try {
+ assertEquals(1, is.skip(1));
+ assertEquals(41, is.read());
+ assertEquals(42, is.read());
+ assertEquals(2, is.skip(2));
+ assertEquals(45, is.read());
+ assertEquals(46, is.read());
+ assertEquals(-1, is.read());
+ } finally {
+ is.close();
+ }
+ }
+
+ @TestTargetNew(
level = TestLevel.COMPLETE,
method = "toString",
args = {}
diff --git a/tests/tests/os/src/android/os/cts/ParcelTest.java b/tests/tests/os/src/android/os/cts/ParcelTest.java
index 28d7728..52b068f 100644
--- a/tests/tests/os/src/android/os/cts/ParcelTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelTest.java
@@ -776,6 +776,30 @@
assertEquals(c[i], d[i]);
}
p.recycle();
+
+ // Test array bounds checks (null already checked above).
+ p = Parcel.obtain();
+ try {
+ p.writeByteArray(c, -1, 1); // Negative offset.
+ fail();
+ } catch (RuntimeException expected) {
+ }
+ try {
+ p.writeByteArray(c, 0, -1); // Negative count.
+ fail();
+ } catch (RuntimeException expected) {
+ }
+ try {
+ p.writeByteArray(c, c.length + 1, 1); // High offset.
+ fail();
+ } catch (RuntimeException expected) {
+ }
+ try {
+ p.writeByteArray(c, 0, c.length + 1); // High count.
+ fail();
+ } catch (RuntimeException expected) {
+ }
+ p.recycle();
}
@TestTargets({
@@ -875,12 +899,11 @@
d = new byte[c.length - 2];
p.setDataPosition(0);
p.readByteArray(d);
- assertEquals(7, d.length);;
for (int i = 0; i < d.length; i++) {
Log.d("Trace", "i=" + i + " d[i]=" + d[i]);
}
for (int i = 0; i < 7; i++) {
- assertEquals(c[i], d[i]);
+ assertEquals(c[i + 1], d[i]);
}
p.recycle();
}
diff --git a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
index a645424..fab9cf6 100644
--- a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
@@ -20,9 +20,13 @@
import android.app.Activity;
import android.app.ActivityManager;
+import android.app.AlertDialog;
import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.MediumTest;
+import android.test.suitebuilder.annotation.Suppress;
+import android.view.WindowManager;
+import android.view.WindowManager.BadTokenException;
/**
* Verify the Activity related operations require specific permissions.
diff --git a/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java b/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
index f34e380..6258667 100755
--- a/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
@@ -77,6 +77,7 @@
Log.w(LOG_TAG, "wait for sms interrupted");
}
}
+
assertTrue("Sms not sent successfully, test environment problem?",
receiver.isMessageSent());
assertFalse("Sms received without proper permissions", receiver.isSmsReceived());
diff --git a/tests/tests/provider/src/android/provider/cts/BrowserTest.java b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
index 2486efa..73db4c3 100644
--- a/tests/tests/provider/src/android/provider/cts/BrowserTest.java
+++ b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
@@ -28,8 +28,10 @@
import android.provider.Browser;
import android.provider.Browser.BookmarkColumns;
import android.provider.Browser.SearchColumns;
+import android.provider.BrowserContract;
+import android.provider.BrowserContract.Bookmarks;
+import android.provider.BrowserContract.History;
import android.test.ActivityInstrumentationTestCase2;
-import android.webkit.WebIconDatabase;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestLevel;
@@ -50,6 +52,7 @@
private ContentResolver mContentResolver;
private IContentProvider mProvider;
private BrowserStubActivity mActivity;
+ private boolean mMasterSyncEnabled;
// the backup for the 2 tables which we will modify in test cases
private ArrayList<ContentValues> mBookmarksBackup;
@@ -70,20 +73,38 @@
mBookmarksBackup = new ArrayList<ContentValues>();
mSearchesBackup = new ArrayList<ContentValues>();
+ // Disable sync
+ mMasterSyncEnabled = ContentResolver.getMasterSyncAutomatically();
+ ContentResolver.setMasterSyncAutomatically(false);
+
// backup the current contents in database
- Cursor cursor = mProvider.query(Browser.BOOKMARKS_URI, null, null, null, null);
+ Cursor cursor = mProvider.query(Bookmarks.CONTENT_URI, null, null, null, null);
if (cursor.moveToFirst()) {
+ String[] colNames = cursor.getColumnNames();
while (!cursor.isAfterLast()) {
ContentValues value = new ContentValues();
- value.put(BookmarkColumns._ID, cursor.getInt(0));
- value.put(BookmarkColumns.TITLE, cursor.getString(1));
- value.put(BookmarkColumns.URL, cursor.getString(2));
- value.put(BookmarkColumns.VISITS, cursor.getInt(3));
- value.put(BookmarkColumns.DATE, cursor.getLong(4));
- value.put(BookmarkColumns.CREATED, cursor.getLong(5));
- value.put(BookmarkColumns.BOOKMARK, cursor.getInt(7));
- value.put(BookmarkColumns.FAVICON, cursor.getBlob(8));
+ for (int i = 0; i < colNames.length; i++) {
+ if (Bookmarks.PARENT_SOURCE_ID.equals(colNames[i])
+ || Bookmarks.INSERT_AFTER_SOURCE_ID.equals(colNames[i])) {
+ // These aren't actual columns, so skip them in the backup
+ continue;
+ }
+ switch (cursor.getType(i)) {
+ case Cursor.FIELD_TYPE_BLOB:
+ value.put(colNames[i], cursor.getBlob(i));
+ break;
+ case Cursor.FIELD_TYPE_FLOAT:
+ value.put(colNames[i], cursor.getFloat(i));
+ break;
+ case Cursor.FIELD_TYPE_INTEGER:
+ value.put(colNames[i], cursor.getLong(i));
+ break;
+ case Cursor.FIELD_TYPE_STRING:
+ value.put(colNames[i], cursor.getString(i));
+ break;
+ }
+ }
mBookmarksBackup.add(value);
cursor.moveToNext();
@@ -106,28 +127,41 @@
}
cursor.close();
- mProvider.delete(Browser.BOOKMARKS_URI, null, null);
+ Uri uri = Bookmarks.CONTENT_URI.buildUpon()
+ .appendQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, "true")
+ .build();
+ mProvider.delete(uri, null, null);
mProvider.delete(Browser.SEARCHES_URI, null, null);
+ mProvider.delete(History.CONTENT_URI, null, null);
mActivity = getActivity();
}
@Override
protected void tearDown() throws Exception {
- // clear all new contents added in test cases.
- mProvider.delete(Browser.BOOKMARKS_URI, null, null);
- mProvider.delete(Browser.SEARCHES_URI, null, null);
+ try {
- // recover the old backup contents
- for (ContentValues value : mBookmarksBackup) {
- mProvider.insert(Browser.BOOKMARKS_URI, value);
+ // clear all new contents added in test cases.
+ Uri uri = Bookmarks.CONTENT_URI.buildUpon()
+ .appendQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, "true")
+ .build();
+ mProvider.delete(uri, null, null);
+ mProvider.delete(Browser.SEARCHES_URI, null, null);
+
+ // recover the old backup contents
+ for (ContentValues value : mBookmarksBackup) {
+ mProvider.insert(uri, value);
+ }
+
+ for (ContentValues value : mSearchesBackup) {
+ mProvider.insert(Browser.SEARCHES_URI, value);
+ }
+
+ // Re-enable sync
+ ContentResolver.setMasterSyncAutomatically(mMasterSyncEnabled);
+ } finally {
+ super.tearDown();
}
-
- for (ContentValues value : mSearchesBackup) {
- mProvider.insert(Browser.SEARCHES_URI, value);
- }
-
- super.tearDown();
}
@TestTargets({
@@ -305,7 +339,7 @@
assertEquals(1, cursor.getCount());
cursor.moveToFirst();
assertEquals(visitedHistoryUrl, cursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
- assertEquals(visitedHistoryUrl,
+ assertEquals(visitedHistoryUrl,
cursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
assertEquals(0, cursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
assertEquals(1, cursor.getInt(Browser.HISTORY_PROJECTION_VISITS_INDEX));
@@ -320,7 +354,7 @@
assertEquals(1, cursor.getCount());
cursor.moveToFirst();
assertEquals(visitedHistoryUrl, cursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
- assertEquals(visitedHistoryUrl,
+ assertEquals(visitedHistoryUrl,
cursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
assertEquals(0, cursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
assertEquals(2, cursor.getInt(Browser.HISTORY_PROJECTION_VISITS_INDEX));
@@ -450,7 +484,7 @@
int historyCountAfterDelete = cursor.getCount();
assertEquals(historyCountBeforeDelete - 1, historyCountAfterDelete);
cursor.moveToLast();
- assertEquals(MAX_HISTORY_COUNT - 1,
+ assertEquals(MAX_HISTORY_COUNT - 1,
cursor.getLong(Browser.HISTORY_PROJECTION_DATE_INDEX));
cursor.close();
@@ -541,7 +575,7 @@
level = TestLevel.COMPLETE,
notes = "test requestAllIcons(ContentResolver, String, WebIconDatabase.IconListener).",
method = "requestAllIcons",
- args = {android.content.ContentResolver.class, java.lang.String.class,
+ args = {android.content.ContentResolver.class, java.lang.String.class,
android.webkit.WebIconDatabase.IconListener.class}
)
public void testRequestAllIcons() {
diff --git a/tests/tests/provider/src/android/provider/cts/ContactsTest.java b/tests/tests/provider/src/android/provider/cts/ContactsTest.java
index fa1e431..1c74b7f 100644
--- a/tests/tests/provider/src/android/provider/cts/ContactsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/ContactsTest.java
@@ -820,10 +820,20 @@
GroupMembership.CONTENT_URI, GROUP_MEMBERSHIP_PROJECTION,
GroupMembership.PERSON_ID + " = " + peopleId,
null, null);
- assertTrue(cursor.moveToNext());
- assertEquals(peopleId, cursor.getInt(PERSON_ID_INDEX));
- assertEquals(groupId1, cursor.getInt(GROUP_ID_INDEX));
- int id = cursor.getInt(ID_INDEX);
+
+ // Check that the person has been associated with the group. The person may be in
+ // additional groups by being added automatically.
+ int id = -1;
+ while(true) {
+ assertTrue(cursor.moveToNext());
+ assertEquals(peopleId, cursor.getInt(PERSON_ID_INDEX));
+ int cursorGroupId = cursor.getInt(GROUP_ID_INDEX);
+ if (groupId1 == cursorGroupId) {
+ id = cursor.getInt(ID_INDEX);
+ break;
+ }
+ }
+ assertTrue(id != -1);
cursor.close();
// Test: update
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
index e50abf4..48ae5d7 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
@@ -30,6 +30,8 @@
import android.provider.MediaStore.Audio.Playlists;
import android.test.InstrumentationTestCase;
+import java.util.regex.Pattern;
+
@TestTargetClass(Playlists.class)
public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
private ContentResolver mContentResolver;
@@ -74,9 +76,8 @@
ContentValues values = new ContentValues();
values.put(Playlists.NAME, "My favourites");
values.put(Playlists.DATA, externalPlaylistPath);
- long dateAdded = System.currentTimeMillis();
- values.put(Playlists.DATE_ADDED, dateAdded);
- long dateModified = System.currentTimeMillis();
+ long dateAdded = System.currentTimeMillis() / 1000;
+ long dateModified = System.currentTimeMillis() / 1000;
values.put(Playlists.DATE_MODIFIED, dateModified);
// insert
Uri uri = mContentResolver.insert(Playlists.EXTERNAL_CONTENT_URI, values);
@@ -91,7 +92,8 @@
assertEquals(externalPlaylistPath,
c.getString(c.getColumnIndex(Playlists.DATA)));
- assertEquals(dateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
+ long realDateAdded = c.getLong(c.getColumnIndex(Playlists.DATE_ADDED));
+ assertTrue(realDateAdded >= dateAdded);
assertEquals(dateModified, c.getLong(c.getColumnIndex(Playlists.DATE_MODIFIED)));
assertTrue(c.getLong(c.getColumnIndex(Playlists._ID)) > 0);
c.close();
@@ -108,7 +110,7 @@
assertEquals(externalPlaylistPath,
c.getString(c.getColumnIndex(Playlists.DATA)));
- assertEquals(dateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
+ assertEquals(realDateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
assertEquals(dateModified, c.getLong(c.getColumnIndex(Playlists.DATE_MODIFIED)));
c.close();
} finally {
@@ -117,7 +119,6 @@
}
public void testStoreAudioPlaylistsInternal() {
- // the internal database does not have play lists
ContentValues values = new ContentValues();
values.put(Playlists.NAME, "My favourites");
values.put(Playlists.DATA, "/data/data/com.android.cts.stub/files/my_favorites.pl");
@@ -126,6 +127,8 @@
long dateModified = System.currentTimeMillis();
values.put(Playlists.DATE_MODIFIED, dateModified);
Uri uri = mContentResolver.insert(Playlists.INTERNAL_CONTENT_URI, values);
- assertNull(uri);
+ assertNotNull(uri);
+ assertTrue(Pattern.matches("content://media/internal/audio/playlists/\\d+",
+ uri.toString()));
}
}
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
index 12d080e..36d4303 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
@@ -31,6 +31,8 @@
import android.provider.cts.MediaStoreAudioTestHelper.Audio2;
import android.test.InstrumentationTestCase;
+import java.util.regex.Pattern;
+
@TestTargetClass(Members.class)
public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestCase {
private String[] mAudioProjection = {
@@ -153,8 +155,9 @@
Uri membersUri = Members.getContentUri(MediaStoreAudioTestHelper.EXTERNAL_VOLUME_NAME,
playlistId);
Uri audioUri = mContentResolver.insert(membersUri, values);
+
assertNotNull(audioUri);
- assertEquals(Uri.withAppendedPath(membersUri, Long.toString(mIdOfAudio1)), audioUri);
+ assertTrue(audioUri.toString().startsWith(membersUri.toString()));
try {
// query the audio info
@@ -162,7 +165,7 @@
assertEquals(1, c.getCount());
c.moveToFirst();
long memberId = c.getLong(c.getColumnIndex(Members._ID));
- assertTrue(memberId > 0);
+ assertEquals(memberId, Long.parseLong(audioUri.getPathSegments().get(5)));
assertEquals(Audio1.EXTERNAL_DATA, c.getString(c.getColumnIndex(Members.DATA)));
assertTrue(c.getLong(c.getColumnIndex(Members.DATE_ADDED)) > 0);
assertEquals(Audio1.DATE_MODIFIED, c.getLong(c.getColumnIndex(Members.DATE_MODIFIED)));
@@ -247,7 +250,6 @@
}
public void testStoreAudioPlaylistsMembersInternal() {
- // the internal database does not have play lists
ContentValues values = new ContentValues();
values.put(Playlists.NAME, "My favourites");
values.put(Playlists.DATA, "/data/data/com.android.cts.stub/files/my_favorites.pl");
@@ -256,6 +258,8 @@
long dateModified = System.currentTimeMillis();
values.put(Playlists.DATE_MODIFIED, dateModified);
Uri uri = mContentResolver.insert(Playlists.INTERNAL_CONTENT_URI, values);
- assertNull(uri);
+ assertNotNull(uri);
+ assertTrue(Pattern.matches("content://media/internal/audio/playlists/\\d+",
+ uri.toString()));
}
}
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
index 2de72c8..8e8d650 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
@@ -35,10 +35,10 @@
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.test.InstrumentationTestCase;
-import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
@@ -247,11 +247,15 @@
assertNull(mContentResolver.query(Media.getContentUri(volume), null, null, null, null));
}
- public void testStoreImagesMediaExternal() {
+ public void testStoreImagesMediaExternal() throws Exception {
final String externalPath = Environment.getExternalStorageDirectory().getPath() +
"/testimage.jpg";
final String externalPath2 = Environment.getExternalStorageDirectory().getPath() +
"/testimage1.jpg";
+
+ int numBytes = 1337;
+ FileCopyHelper.createFile(new File(externalPath), numBytes);
+
ContentValues values = new ContentValues();
values.put(Media.ORIENTATION, 0);
values.put(Media.PICASA_ID, 0);
@@ -265,11 +269,11 @@
values.put(Media.DATA, externalPath);
values.put(Media.DISPLAY_NAME, "testimage");
values.put(Media.MIME_TYPE, "image/jpeg");
- values.put(Media.SIZE, 86853);
+ values.put(Media.SIZE, numBytes);
values.put(Media.TITLE, "testimage");
- long dateAdded = System.currentTimeMillis();
+ long dateAdded = System.currentTimeMillis() / 1000;
values.put(Media.DATE_ADDED, dateAdded);
- long dateModified = System.currentTimeMillis();
+ long dateModified = System.currentTimeMillis() / 1000;
values.put(Media.DATE_MODIFIED, dateModified);
// insert
@@ -296,9 +300,9 @@
assertEquals("testimage", c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
assertEquals("image/jpeg", c.getString(c.getColumnIndex(Media.MIME_TYPE)));
assertEquals("testimage", c.getString(c.getColumnIndex(Media.TITLE)));
- assertEquals(86853, c.getInt(c.getColumnIndex(Media.SIZE)));
+ assertEquals(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
long realDateAdded = c.getLong(c.getColumnIndex(Media.DATE_ADDED));
- assertTrue(realDateAdded > 0);
+ assertTrue(realDateAdded >= dateAdded);
assertEquals(dateModified, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
c.close();
@@ -318,7 +322,7 @@
values.put(Media.MIME_TYPE, "image/jpeg");
values.put(Media.SIZE, 86854);
values.put(Media.TITLE, "testimage1");
- dateModified = System.currentTimeMillis();
+ dateModified = System.currentTimeMillis() / 1000;
values.put(Media.DATE_MODIFIED, dateModified);
assertEquals(1, mContentResolver.update(uri, values, null, null));
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java
index 9a720e5..6f7842c 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java
@@ -29,6 +29,8 @@
import android.provider.MediaStore.Video.Media;
import android.test.InstrumentationTestCase;
+import java.io.File;
+
@TestTargetClass(MediaStore.Video.Media.class)
public class MediaStore_Video_MediaTest extends InstrumentationTestCase {
private ContentResolver mContentResolver;
@@ -56,11 +58,15 @@
assertNull(mContentResolver.query(Media.getContentUri(volume), null, null, null, null));
}
- public void testStoreVideoMediaExternal() {
+ public void testStoreVideoMediaExternal() throws Exception {
final String externalVideoPath = Environment.getExternalStorageDirectory().getPath() +
"/video/testvideo.3gp";
final String externalVideoPath2 = Environment.getExternalStorageDirectory().getPath() +
"/video/testvideo1.3gp";
+
+ int numBytes = 1337;
+ FileCopyHelper.createFile(new File(externalVideoPath), numBytes);
+
ContentValues values = new ContentValues();
values.put(Media.ALBUM, "cts");
values.put(Media.ARTIST, "cts team");
@@ -79,11 +85,11 @@
values.put(Media.DATA, externalVideoPath);
values.put(Media.DISPLAY_NAME, "testvideo");
values.put(Media.MIME_TYPE, "video/3gpp");
- values.put(Media.SIZE, 86853);
+ values.put(Media.SIZE, numBytes);
values.put(Media.TITLE, "testvideo");
- long dateAdded = System.currentTimeMillis();
+ long dateAdded = System.currentTimeMillis() / 1000;
values.put(Media.DATE_ADDED, dateAdded);
- long dateModified = System.currentTimeMillis();
+ long dateModified = System.currentTimeMillis() / 1000;
values.put(Media.DATE_MODIFIED, dateModified);
// insert
@@ -115,9 +121,9 @@
assertEquals("testvideo.3gp", c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
assertEquals("video/3gpp", c.getString(c.getColumnIndex(Media.MIME_TYPE)));
assertEquals("testvideo", c.getString(c.getColumnIndex(Media.TITLE)));
- assertEquals(86853, c.getInt(c.getColumnIndex(Media.SIZE)));
+ assertEquals(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
long realDateAdded = c.getLong(c.getColumnIndex(Media.DATE_ADDED));
- assertTrue(realDateAdded > 0);
+ assertTrue(realDateAdded >= dateAdded);
assertEquals(dateModified, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
c.close();
diff --git a/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java b/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java
new file mode 100644
index 0000000..1395de1
--- /dev/null
+++ b/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * 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 android.provider.cts;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.SearchRecentSuggestions;
+import android.test.ProviderTestCase2;
+import android.view.animation.cts.DelayedCheck;
+
+@TestTargetClass(android.provider.SearchRecentSuggestions.class)
+public class SearchRecentSuggestionsTest extends
+ ProviderTestCase2<TestSearchRecentSuggestionsProvider> {
+ private final static String AUTHORITY_HEAD = "content://"
+ + TestSearchRecentSuggestionsProvider.AUTHORITY;
+
+ private Uri mTestUri;
+ private TestSearchRecentSuggestionsProvider mTestSRSProvider;
+ private Context mContext;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ mTestUri = Uri.parse(AUTHORITY_HEAD + "/suggestions");
+ mTestSRSProvider = getProvider();
+ mContext = mTestSRSProvider.getContext();
+ }
+
+ public SearchRecentSuggestionsTest() {
+ super(TestSearchRecentSuggestionsProvider.class,
+ TestSearchRecentSuggestionsProvider.AUTHORITY);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "SearchRecentSuggestions",
+ args = {android.content.Context.class, java.lang.String.class, int.class}
+ )
+ public void testConstructor() {
+ new SearchRecentSuggestions(mContext, TestSearchRecentSuggestionsProvider.AUTHORITY,
+ TestSearchRecentSuggestionsProvider.MODE);
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "SearchRecentSuggestions",
+ args = {android.content.Context.class, java.lang.String.class, int.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "saveRecentQuery",
+ args = {java.lang.String.class, java.lang.String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "clearHistory",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "truncateHistory",
+ args = {android.content.ContentResolver.class, int.class}
+ )
+ })
+ public void testSearchRecentSuggestions() {
+ MySearchRecentSuggestions srs = new MySearchRecentSuggestions(mContext,
+ TestSearchRecentSuggestionsProvider.AUTHORITY,
+ TestSearchRecentSuggestionsProvider.MODE);
+ Cursor c = mTestSRSProvider.query(mTestUri, null, null, null, null);
+
+ try {
+ assertNotNull(c);
+ assertEquals(0, c.getCount());
+ c.close();
+
+ // insert three rows
+ String query1 = "query1";
+ String line1 = "line1";
+ srs.saveRecentQuery(query1, line1);
+
+ waitForCursorCount(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE, 1);
+
+ c = mTestSRSProvider.query(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE,
+ null, null, null);
+ c.moveToFirst();
+ assertEquals(query1, c
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+ assertEquals(line1, c
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+ c.close();
+
+ String query2 = "query2";
+ String line2 = "line2";
+ srs.saveRecentQuery(query2, line2);
+ waitForCursorCount(mTestUri, null, 2);
+
+ String query3 = "query3";
+ String line3 = "line3";
+ srs.saveRecentQuery(query3, line3);
+ waitForCursorCount(mTestUri, null, 3);
+
+ // truncateHistory will delete the oldest one record
+ ContentResolver cr = mContext.getContentResolver();
+ srs.truncateHistory(cr, 2);
+
+ waitForCursorCount(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE, 2);
+
+ c = mTestSRSProvider.query(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE,
+ null, null, null);
+
+ // and the left two should be: test2 and test3, test1 should be delete
+ c.moveToFirst();
+ assertEquals(query2, c
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+ assertEquals(line2, c
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+ c.moveToNext();
+ assertEquals(query3, c
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+ assertEquals(line3, c
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+ c.close();
+
+ // clear all history
+ srs.clearHistory();
+ waitForCursorCount(mTestUri, null, 0);
+ } finally {
+ c.close();
+ }
+ }
+
+ public void testSuggestionsTable() {
+ String insertDisplay1 = "display1_insert";
+ String insertDisplay2 = "display2_insert";
+ String insertQuery = "query_insert";
+
+ String updateDisplay1 = "display1_update";
+ String updateDisplay2 = "display2_update";
+ String updateQuery = "query_update";
+
+ // Test: insert
+ ContentValues value = new ContentValues();
+ value.put("display1", insertDisplay1);
+ value.put("display2", insertDisplay2);
+ value.put("query", insertQuery);
+ value.put("date", 1);
+
+ mTestSRSProvider.insert(mTestUri, value);
+
+ Cursor cursor = mTestSRSProvider.query(mTestUri,
+ SearchRecentSuggestions.QUERIES_PROJECTION_2LINE,
+ "display1=\"" + insertDisplay1 + "\"", null, null);
+ try {
+ assertNotNull(cursor);
+ assertEquals(1, cursor.getCount());
+ assertTrue(cursor.moveToFirst());
+ assertEquals(insertDisplay2, cursor
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+ assertEquals(insertQuery, cursor
+ .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+ assertEquals(1, cursor.getInt(SearchRecentSuggestions.QUERIES_PROJECTION_DATE_INDEX));
+ cursor.close();
+
+ // Test: update
+ /**
+ * SearchRecentSuggestionsProvider.update is not implement, always
+ * throw an UnsupportedOperationException.
+ */
+ value.clear();
+ value.put("display1", updateDisplay1);
+ value.put("display2", updateDisplay2);
+ value.put("query", updateQuery);
+ value.put("date", 2);
+
+ try {
+ mTestSRSProvider.update(mTestUri, value, "display1=\"" + insertDisplay1 + "\"",
+ null);
+ fail("There should be an UnsupportedOperationException thrown out.");
+ } catch (UnsupportedOperationException e) {
+ // expected, test success.
+ }
+
+ // Test: delete
+ mTestSRSProvider.delete(mTestUri, "display1=\"" + insertDisplay1 + "\"", null);
+ cursor = mTestSRSProvider.query(mTestUri,
+ SearchRecentSuggestions.QUERIES_PROJECTION_2LINE, "display1=\""
+ + insertDisplay1 + "\"", null, null);
+ assertNotNull(cursor);
+ assertEquals(0, cursor.getCount());
+ } finally {
+ cursor.close();
+ }
+ }
+
+ private class MySearchRecentSuggestions extends SearchRecentSuggestions {
+ public MySearchRecentSuggestions(Context context, String authority, int mode) {
+ super(context, authority, mode);
+ }
+
+ protected void truncateHistory(ContentResolver cr, int maxEntries) {
+ super.truncateHistory(cr, maxEntries);
+ }
+ }
+
+ private void waitForCursorCount(final Uri uri, final String[] projection,
+ final int expectedCount) {
+ new DelayedCheck() {
+ protected boolean check() {
+ Cursor cursor = null;
+ try {
+ cursor = mTestSRSProvider.query(uri, projection, null, null, null);
+ return cursor != null && cursor.getCount() == expectedCount;
+ } finally {
+ if (cursor != null) {
+ cursor.close();
+ }
+ }
+ }
+ }.run();
+ }
+}
diff --git a/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java b/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
index c325abf..13a32d6 100644
--- a/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
+++ b/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
@@ -117,11 +117,10 @@
} catch (SecurityException expected) {
}
- // TODO: Should be fixed to throw SettingNotFoundException.
try {
Secure.getFloat(cr, NO_SUCH_SETTING);
- fail("NullPointerException should have been thrown!");
- } catch (NullPointerException expected) {
+ fail("SettingNotFoundException should have been thrown!");
+ } catch (SettingNotFoundException expected) {
}
try {
diff --git a/tests/tests/renderscript/Android.mk b/tests/tests/renderscript/Android.mk
new file mode 100644
index 0000000..fc64614
--- /dev/null
+++ b/tests/tests/renderscript/Android.mk
@@ -0,0 +1,37 @@
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Replace "Example" with your name.
+LOCAL_PACKAGE_NAME := CtsRenderscriptTestCases
+
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := optional
+
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+# All tests should include android.test.runner.
+LOCAL_JAVA_LIBRARIES := android.test.runner
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/renderscript/AndroidManifest.xml b/tests/tests/renderscript/AndroidManifest.xml
new file mode 100644
index 0000000..7205b3c
--- /dev/null
+++ b/tests/tests/renderscript/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Replace all the "example" stuff below with your package name, and
+ remove this comment.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.cts.renderscript">
+
+ <application>
+ <uses-library android:name="android.test.runner" />
+ </application>
+
+ <!-- This is a self-instrumenting test package. -->
+ <instrumentation android:name="android.test.InstrumentationTestRunner"
+ android:targetPackage="com.android.cts.stub"
+ android:label="CTS tests of Renderscript component"/>
+
+</manifest>
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AllocationTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AllocationTest.java
new file mode 100644
index 0000000..0f77369
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AllocationTest.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.Allocation;
+import android.renderscript.Allocation.MipmapControl;
+import android.renderscript.Element;
+import android.renderscript.Type;
+import android.renderscript.Type.Builder;
+
+public class AllocationTest extends RSBaseGraphics {
+
+ // Test power of two and non power of two, equal and non-equal sizes
+ void createTypedHelper(Element e) {
+
+ Type.Builder typeBuilder = new Type.Builder(mRS, e);
+ for (int mips = 0; mips <= 1; mips ++) {
+ boolean useMips = (mips == 1);
+
+ for (int faces = 0; faces <= 1; faces++) {
+ boolean useFaces = (faces == 1);
+
+ for (int x = 1; x < 8; x ++) {
+ for (int y = 1; y < 8; y ++) {
+ typeBuilder.setMipmaps(useMips);
+ typeBuilder.setFaces(useFaces);
+ typeBuilder.setX(x).setY(y);
+ Allocation.createTyped(mRS, typeBuilder.create());
+ }
+ }
+ }
+ }
+
+ }
+
+ void createTypedTextureHelper(Element e) {
+ // No mips graphics
+ Type.Builder typeBuilder = new Type.Builder(mRS, e);
+ Allocation.createTyped(mRS, typeBuilder.setX(8).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE);
+ Allocation.createTyped(mRS, typeBuilder.setY(8).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE);
+ // No mips graphics and script
+ Allocation.createTyped(mRS, typeBuilder.create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE |
+ Allocation.USAGE_SCRIPT);
+ // With mips
+ Allocation.createTyped(mRS, typeBuilder.create(),
+ MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE,
+ Allocation.USAGE_GRAPHICS_TEXTURE);
+ Allocation.createTyped(mRS, typeBuilder.create(),
+ MipmapControl.MIPMAP_FULL,
+ Allocation.USAGE_GRAPHICS_TEXTURE |
+ Allocation.USAGE_SCRIPT);
+
+ // Only texture npot
+ Allocation.createTyped(mRS, typeBuilder.setX(7).setY(1).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE);
+ Allocation.createTyped(mRS, typeBuilder.setX(7).setY(3).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE);
+ Allocation.createTyped(mRS, typeBuilder.setX(7).setY(7).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE);
+
+ // Script and texture
+ Allocation.createTyped(mRS, typeBuilder.setX(7).setY(1).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE |
+ Allocation.USAGE_SCRIPT);
+ Allocation.createTyped(mRS, typeBuilder.setX(7).setY(3).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE |
+ Allocation.USAGE_SCRIPT);
+ Allocation.createTyped(mRS, typeBuilder.setX(7).setY(7).create(),
+ MipmapControl.MIPMAP_NONE,
+ Allocation.USAGE_GRAPHICS_TEXTURE |
+ Allocation.USAGE_SCRIPT);
+ }
+
+ void createSizedHelper(Element e) {
+ for (int i = 1; i <= 8; i ++) {
+ Allocation.createSized(mRS, e, i);
+ }
+ }
+
+ public void testCreateTyped() {
+ createTypedHelper(Element.A_8(mRS));
+ createTypedHelper(Element.RGB_565(mRS));
+ createTypedHelper(Element.RGB_888(mRS));
+ createTypedHelper(Element.RGBA_8888(mRS));
+ createTypedHelper(Element.F32(mRS));
+ createTypedHelper(Element.F32_2(mRS));
+ createTypedHelper(Element.F32_3(mRS));
+ createTypedHelper(Element.F32_4(mRS));
+ createTypedHelper(Element.BOOLEAN(mRS));
+ createTypedHelper(Element.F64(mRS));
+ createTypedHelper(Element.I8(mRS));
+ createTypedHelper(Element.I16(mRS));
+ createTypedHelper(Element.I32(mRS));
+ createTypedHelper(Element.I64(mRS));
+ createTypedHelper(Element.U8(mRS));
+ createTypedHelper(Element.U8_4(mRS));
+ createTypedHelper(Element.U16(mRS));
+ createTypedHelper(Element.U32(mRS));
+ createTypedHelper(Element.U64(mRS));
+ createTypedHelper(Element.MATRIX_2X2(mRS));
+ createTypedHelper(Element.MATRIX_3X3(mRS));
+ createTypedHelper(Element.MATRIX_4X4(mRS));
+ createTypedHelper(Element.MESH(mRS));
+ createTypedHelper(Element.PROGRAM_FRAGMENT(mRS));
+ createTypedHelper(Element.PROGRAM_RASTER(mRS));
+ createTypedHelper(Element.PROGRAM_STORE(mRS));
+ createTypedHelper(Element.PROGRAM_VERTEX(mRS));
+ createTypedHelper(Element.ALLOCATION(mRS));
+ createTypedHelper(Element.SAMPLER(mRS));
+ createTypedHelper(Element.SCRIPT(mRS));
+ createTypedHelper(Element.TYPE(mRS));
+
+ createTypedTextureHelper(Element.A_8(mRS));
+ createTypedTextureHelper(Element.RGB_565(mRS));
+ createTypedTextureHelper(Element.RGB_888(mRS));
+ createTypedTextureHelper(Element.RGBA_8888(mRS));
+ }
+
+ public void testCreateSized() {
+ createSizedHelper(Element.A_8(mRS));
+ createSizedHelper(Element.RGB_565(mRS));
+ createSizedHelper(Element.RGB_888(mRS));
+ createSizedHelper(Element.RGBA_8888(mRS));
+ createSizedHelper(Element.F32(mRS));
+ createSizedHelper(Element.F32_2(mRS));
+ createSizedHelper(Element.F32_3(mRS));
+ createSizedHelper(Element.F32_4(mRS));
+ createSizedHelper(Element.BOOLEAN(mRS));
+ createSizedHelper(Element.F64(mRS));
+ createSizedHelper(Element.I8(mRS));
+ createSizedHelper(Element.I16(mRS));
+ createSizedHelper(Element.I32(mRS));
+ createSizedHelper(Element.I64(mRS));
+ createSizedHelper(Element.U8(mRS));
+ createSizedHelper(Element.U8_4(mRS));
+ createSizedHelper(Element.U16(mRS));
+ createSizedHelper(Element.U32(mRS));
+ createSizedHelper(Element.U64(mRS));
+ createSizedHelper(Element.MATRIX_2X2(mRS));
+ createSizedHelper(Element.MATRIX_3X3(mRS));
+ createSizedHelper(Element.MATRIX_4X4(mRS));
+ createSizedHelper(Element.MESH(mRS));
+ createSizedHelper(Element.PROGRAM_FRAGMENT(mRS));
+ createSizedHelper(Element.PROGRAM_RASTER(mRS));
+ createSizedHelper(Element.PROGRAM_STORE(mRS));
+ createSizedHelper(Element.PROGRAM_VERTEX(mRS));
+ createSizedHelper(Element.ALLOCATION(mRS));
+ createSizedHelper(Element.SAMPLER(mRS));
+ createSizedHelper(Element.SCRIPT(mRS));
+ createSizedHelper(Element.TYPE(mRS));
+ }
+}
+
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ComputeTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ComputeTest.java
new file mode 100644
index 0000000..a5c4f16
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/ComputeTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.RenderScript;
+import android.renderscript.RenderScript.RSMessageHandler;
+import android.test.AndroidTestCase;
+import com.android.cts.stub.R;
+
+public class ComputeTest extends RSBaseCompute {
+
+ private boolean initializeGlobals(ScriptC_primitives s) {
+ float pF = s.get_floatTest();
+ if (pF != 1.99f) {
+ return false;
+ }
+ s.set_floatTest(2.99f);
+
+ double pD = s.get_doubleTest();
+ if (pD != 2.05) {
+ return false;
+ }
+ s.set_doubleTest(3.05);
+
+ byte pC = s.get_charTest();
+ if (pC != -8) {
+ return false;
+ }
+ s.set_charTest((byte)-16);
+
+ short pS = s.get_shortTest();
+ if (pS != -16) {
+ return false;
+ }
+ s.set_shortTest((short)-32);
+
+ int pI = s.get_intTest();
+ if (pI != -32) {
+ return false;
+ }
+ s.set_intTest(-64);
+
+ long pL = s.get_longTest();
+ if (pL != 17179869184l) {
+ return false;
+ }
+ s.set_longTest(17179869185l);
+
+ long puL = s.get_ulongTest();
+ if (puL != 4611686018427387904L) {
+ return false;
+ }
+ s.set_ulongTest(4611686018427387903L);
+
+
+ long pLL = s.get_longlongTest();
+ if (pLL != 68719476736L) {
+ return false;
+ }
+ s.set_longlongTest(68719476735L);
+
+ long pu64 = s.get_uint64_tTest();
+ if (pu64 != 117179869184l) {
+ return false;
+ }
+ s.set_uint64_tTest(117179869185l);
+
+ return true;
+ }
+
+ /**
+ * Test primitive types.
+ */
+ public void testPrimitives() {
+ ScriptC_primitives t = new ScriptC_primitives(mRS,
+ mRes,
+ R.raw.primitives);
+
+ assertTrue(initializeGlobals(t));
+ t.invoke_test();
+ waitForMessage();
+ assertEquals(result, RS_MSG_TEST_PASSED);
+ }
+
+}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ElementTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ElementTest.java
new file mode 100644
index 0000000..55572a3
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/ElementTest.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.Element;
+import android.renderscript.Element.DataType;
+import android.renderscript.Element.DataKind;
+
+public class ElementTest extends RSBaseCompute {
+
+ public void testCreatePixel() {
+ assertTrue(Element.createPixel(mRS,
+ DataType.UNSIGNED_8,
+ DataKind.PIXEL_A) != null);
+ assertTrue(Element.createPixel(mRS,
+ DataType.UNSIGNED_5_6_5,
+ DataKind.PIXEL_RGB) != null);
+ assertTrue(Element.createPixel(mRS,
+ DataType.UNSIGNED_8,
+ DataKind.PIXEL_RGB) != null);
+ assertTrue(Element.createPixel(mRS,
+ DataType.UNSIGNED_5_5_5_1,
+ DataKind.PIXEL_RGBA) != null);
+ assertTrue(Element.createPixel(mRS,
+ DataType.UNSIGNED_4_4_4_4,
+ DataKind.PIXEL_RGBA) != null);
+ assertTrue(Element.createPixel(mRS,
+ DataType.UNSIGNED_8,
+ DataKind.PIXEL_RGBA) != null);
+ }
+
+ public void testCreateVector() {
+
+ Element e = null;
+ for (int len = 2; len <= 4; len ++) {
+ assertTrue(Element.createVector(mRS, DataType.FLOAT_32, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.FLOAT_64, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.SIGNED_8, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.SIGNED_16, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.SIGNED_32, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.SIGNED_64, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.UNSIGNED_8, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.UNSIGNED_16, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.UNSIGNED_32, len) != null);
+ assertTrue(Element.createVector(mRS, DataType.UNSIGNED_64, len) != null);
+ }
+ }
+
+ public void testPrebuiltElements() {
+ assertTrue(Element.A_8(mRS) != null);
+ assertTrue(Element.RGBA_4444(mRS) != null);
+ assertTrue(Element.RGBA_5551(mRS) != null);
+ assertTrue(Element.RGB_565(mRS) != null);
+ assertTrue(Element.RGB_888(mRS) != null);
+ assertTrue(Element.RGBA_8888(mRS) != null);
+ assertTrue(Element.F32(mRS) != null);
+ assertTrue(Element.F32_2(mRS) != null);
+ assertTrue(Element.F32_3(mRS) != null);
+ assertTrue(Element.F32_4(mRS) != null);
+ assertTrue(Element.F64(mRS) != null);
+ assertTrue(Element.I8(mRS) != null);
+ assertTrue(Element.I16(mRS) != null);
+ assertTrue(Element.I32(mRS) != null);
+ assertTrue(Element.I64(mRS) != null);
+ assertTrue(Element.U8(mRS) != null);
+ assertTrue(Element.U8_4(mRS) != null);
+ assertTrue(Element.U16(mRS) != null);
+ assertTrue(Element.U32(mRS) != null);
+ assertTrue(Element.U64(mRS) != null);
+ assertTrue(Element.MATRIX_2X2(mRS) != null);
+ assertTrue(Element.MATRIX_3X3(mRS) != null);
+ assertTrue(Element.MATRIX_4X4(mRS) != null);
+ assertTrue(Element.MESH(mRS) != null);
+ assertTrue(Element.PROGRAM_FRAGMENT(mRS) != null);
+ assertTrue(Element.PROGRAM_RASTER(mRS) != null);
+ assertTrue(Element.PROGRAM_STORE(mRS) != null);
+ assertTrue(Element.PROGRAM_VERTEX(mRS) != null);
+ assertTrue(Element.ALLOCATION(mRS) != null);
+ assertTrue(Element.SAMPLER(mRS) != null);
+ assertTrue(Element.SCRIPT(mRS) != null);
+ assertTrue(Element.TYPE(mRS) != null);
+ assertTrue(Element.BOOLEAN(mRS) != null);
+ assertTrue(Element.ELEMENT(mRS) != null);
+ }
+
+ public void testElementBuilder() {
+ for (int arraySize = 1; arraySize <= 3; arraySize++) {
+ // Now test array size
+ Element.Builder eb = new Element.Builder(mRS);
+ eb.add(Element.A_8(mRS), "A_8", arraySize);
+ eb.add(Element.RGBA_4444(mRS), "RGBA_4444", arraySize);
+ eb.add(Element.RGBA_5551(mRS), "RGBA_5551", arraySize);
+ eb.add(Element.RGB_565(mRS), "RGB_565", arraySize);
+ eb.add(Element.RGB_888(mRS), "RGB_888", arraySize);
+ eb.add(Element.RGBA_8888(mRS), "RGBA_8888", arraySize);
+ eb.add(Element.F32(mRS), "F32", arraySize);
+ eb.add(Element.F32_2(mRS), "F32_2", arraySize);
+ eb.add(Element.F32_3(mRS), "F32_3", arraySize);
+ eb.add(Element.F32_4(mRS), "F32_4", arraySize);
+ eb.add(Element.F64(mRS), "F64", arraySize);
+ eb.add(Element.I8(mRS), "I8", arraySize);
+ eb.add(Element.I16(mRS), "I16", arraySize);
+ eb.add(Element.I32(mRS), "I32", arraySize);
+ eb.add(Element.I64(mRS), "I64", arraySize);
+ eb.add(Element.U8(mRS), "U8", arraySize);
+ eb.add(Element.U8_4(mRS), "U8_4", arraySize);
+ eb.add(Element.U16(mRS), "U16", arraySize);
+ eb.add(Element.U32(mRS), "U32", arraySize);
+ eb.add(Element.U64(mRS), "U64", arraySize);
+ eb.add(Element.MATRIX_2X2(mRS), "MATRIX_2X2", arraySize);
+ eb.add(Element.MATRIX_3X3(mRS), "MATRIX_3X3", arraySize);
+ eb.add(Element.MATRIX_4X4(mRS), "MATRIX_4X4", arraySize);
+ eb.add(Element.MESH(mRS), "MESH", arraySize);
+ eb.add(Element.PROGRAM_FRAGMENT(mRS), "PROGRAM_FRAGMENT", arraySize);
+ eb.add(Element.PROGRAM_RASTER(mRS), "PROGRAM_RASTER", arraySize);
+ eb.add(Element.PROGRAM_STORE(mRS), "PROGRAM_STORE", arraySize);
+ eb.add(Element.PROGRAM_VERTEX(mRS), "PROGRAM_VERTEX", arraySize);
+ eb.add(Element.ALLOCATION(mRS), "ALLOCATION", arraySize);
+ eb.add(Element.SAMPLER(mRS), "SAMPLER", arraySize);
+ eb.add(Element.SCRIPT(mRS), "SCRIPT", arraySize);
+ eb.add(Element.TYPE(mRS), "TYPE", arraySize);
+ eb.add(Element.BOOLEAN(mRS), "BOOLEAN", arraySize);
+ eb.add(Element.ELEMENT(mRS), "ELEMENT", arraySize);
+ assertTrue(eb.create() != null);
+ }
+ }
+
+ public void testIsComplex() {
+ assertFalse(Element.A_8(mRS).isComplex());
+ assertFalse(Element.RGBA_4444(mRS).isComplex());
+ assertFalse(Element.RGBA_5551(mRS).isComplex());
+ assertFalse(Element.RGB_565(mRS).isComplex());
+ assertFalse(Element.RGB_888(mRS).isComplex());
+ assertFalse(Element.RGBA_8888(mRS).isComplex());
+ assertFalse(Element.F32(mRS).isComplex());
+ assertFalse(Element.F32_2(mRS).isComplex());
+ assertFalse(Element.F32_3(mRS).isComplex());
+ assertFalse(Element.F32_4(mRS).isComplex());
+ assertFalse(Element.F64(mRS).isComplex());
+ assertFalse(Element.I8(mRS).isComplex());
+ assertFalse(Element.I16(mRS).isComplex());
+ assertFalse(Element.I32(mRS).isComplex());
+ assertFalse(Element.I64(mRS).isComplex());
+ assertFalse(Element.U8(mRS).isComplex());
+ assertFalse(Element.U8_4(mRS).isComplex());
+ assertFalse(Element.U16(mRS).isComplex());
+ assertFalse(Element.U32(mRS).isComplex());
+ assertFalse(Element.U64(mRS).isComplex());
+ assertFalse(Element.MATRIX_2X2(mRS).isComplex());
+ assertFalse(Element.MATRIX_3X3(mRS).isComplex());
+ assertFalse(Element.MATRIX_4X4(mRS).isComplex());
+ assertFalse(Element.MESH(mRS).isComplex());
+ assertFalse(Element.PROGRAM_FRAGMENT(mRS).isComplex());
+ assertFalse(Element.PROGRAM_RASTER(mRS).isComplex());
+ assertFalse(Element.PROGRAM_STORE(mRS).isComplex());
+ assertFalse(Element.PROGRAM_VERTEX(mRS).isComplex());
+ assertFalse(Element.ALLOCATION(mRS).isComplex());
+ assertFalse(Element.SAMPLER(mRS).isComplex());
+ assertFalse(Element.SCRIPT(mRS).isComplex());
+ assertFalse(Element.TYPE(mRS).isComplex());
+ assertFalse(Element.BOOLEAN(mRS).isComplex());
+ assertFalse(Element.ELEMENT(mRS).isComplex());
+
+ Element.Builder eb = new Element.Builder(mRS);
+ eb.add(Element.F32(mRS), "FLOAT");
+ eb.add(Element.SAMPLER(mRS), "SAMPLER");
+ Element e1 = eb.create();
+ assertFalse(e1.isComplex());
+
+ eb = new Element.Builder(mRS);
+ eb.add(Element.A_8(mRS), "A_8");
+ eb.add(Element.RGBA_4444(mRS), "RGBA_4444");
+ Element e2 = eb.create();
+ assertFalse(e2.isComplex());
+
+ eb = new Element.Builder(mRS);
+ eb.add(e1, "e1");
+ eb.add(e2, "e2");
+ assertTrue(eb.create().isComplex());
+ }
+}
+
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramRasterTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramRasterTest.java
new file mode 100644
index 0000000..bebb8b0
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/ProgramRasterTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.ProgramRaster;
+import android.renderscript.ProgramRaster.Builder;
+import android.renderscript.ProgramRaster.CullMode;
+
+public class ProgramRasterTest extends RSBaseGraphics {
+
+ public void testProgramRasterBuilder() {
+ ProgramRaster.Builder b = new ProgramRaster.Builder(mRS);
+ for (int p = 0; p <= 1; p++) {
+ boolean pSprite = (p == 1);
+ b.setPointSpriteEnabled(pSprite);
+ for (CullMode cull : CullMode.values()) {
+ b.setCullMode(cull);
+ b.create();
+ }
+ }
+ }
+
+ public void testPrebuiltProgramRaster() {
+ assertTrue(ProgramRaster.CULL_BACK(mRS) != null);
+ assertTrue(ProgramRaster.CULL_FRONT(mRS) != null);
+ }
+}
+
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramStoreTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramStoreTest.java
new file mode 100644
index 0000000..54c5672
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/ProgramStoreTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.ProgramStore;
+import android.renderscript.ProgramStore.Builder;
+import android.renderscript.ProgramStore.DepthFunc;
+import android.renderscript.ProgramStore.BlendSrcFunc;
+import android.renderscript.ProgramStore.BlendDstFunc;
+
+public class ProgramStoreTest extends RSBaseGraphics {
+
+ void varyBuilderColorAndDither(ProgramStore.Builder pb) {
+ for (int r = 0; r <= 1; r++) {
+ boolean isR = (r == 1);
+ for (int g = 0; g <= 1; g++) {
+ boolean isG = (g == 1);
+ for (int b = 0; b <= 1; b++) {
+ boolean isB = (b == 1);
+ for (int a = 0; a <= 1; a++) {
+ boolean isA = (a == 1);
+ for (int dither = 0; dither <= 1; dither++) {
+ boolean isDither = (dither == 1);
+ pb.setDepthMaskEnabled(isDither);
+ pb.setColorMaskEnabled(isR, isG, isB, isA);
+ pb.create();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ public void testProgramStoreBuilder() {
+ for (int depth = 0; depth <= 1; depth++) {
+ boolean depthMask = (depth == 1);
+ for (DepthFunc df : DepthFunc.values()) {
+ for (BlendSrcFunc bsf : BlendSrcFunc.values()) {
+ for (BlendDstFunc bdf : BlendDstFunc.values()) {
+ ProgramStore.Builder b = new ProgramStore.Builder(mRS);
+ b.setDepthFunc(df);
+ b.setDepthMaskEnabled(depthMask);
+ b.setBlendFunc(bsf, bdf);
+ varyBuilderColorAndDither(b);
+ }
+ }
+ }
+ }
+ }
+
+ public void testPrebuiltProgramStore() {
+ assertTrue(ProgramStore.BLEND_ALPHA_DEPTH_NONE(mRS) != null);
+ assertTrue(ProgramStore.BLEND_ALPHA_DEPTH_TEST(mRS) != null);
+ assertTrue(ProgramStore.BLEND_NONE_DEPTH_NONE(mRS) != null);
+ assertTrue(ProgramStore.BLEND_NONE_DEPTH_TEST(mRS) != null);
+ }
+}
+
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java b/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
new file mode 100644
index 0000000..10aa8e6
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.RenderScript.RSMessageHandler;
+import android.test.AndroidTestCase;
+import com.android.cts.stub.R;
+
+/**
+ * Base RenderScript test class. This class provides a message handler and a
+ * convenient way to wait for compute scripts to complete their execution.
+ */
+class RSBase extends AndroidTestCase {
+
+ Context mCtx;
+ Resources mRes;
+
+ public int result;
+ private boolean msgHandled;
+
+ public static final int RS_MSG_TEST_PASSED = 100;
+ public static final int RS_MSG_TEST_FAILED = 101;
+
+ RSMessageHandler mRsMessage = new RSMessageHandler() {
+ public void run() {
+ if (result == 0) {
+ switch (mID) {
+ case RS_MSG_TEST_PASSED:
+ case RS_MSG_TEST_FAILED:
+ result = mID;
+ break;
+ default:
+ fail("Got unexpected RS message");
+ return;
+ }
+ }
+ msgHandled = true;
+ }
+ };
+
+ protected void waitForMessage() {
+ while (!msgHandled) {
+ Thread.yield();
+ }
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ result = 0;
+ msgHandled = false;
+ mCtx = getContext();
+ mRes = mCtx.getResources();
+ }
+}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RSBaseCompute.java b/tests/tests/renderscript/src/android/renderscript/cts/RSBaseCompute.java
new file mode 100644
index 0000000..84616ca
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/RSBaseCompute.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.RenderScript;
+import android.renderscript.RenderScript.RSMessageHandler;
+import android.test.AndroidTestCase;
+import com.android.cts.stub.R;
+
+/**
+ * Base RenderScript test class. This class provides a message handler and a
+ * convenient way to wait for compute scripts to complete their execution.
+ */
+class RSBaseCompute extends RSBase {
+ RenderScript mRS;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mRS = RenderScript.create(mCtx);
+ mRS.setMessageHandler(mRsMessage);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ if (mRS != null) {
+ mRS.destroy();
+ mRS = null;
+ }
+ super.tearDown();
+ }
+
+}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RSBaseGraphics.java b/tests/tests/renderscript/src/android/renderscript/cts/RSBaseGraphics.java
new file mode 100644
index 0000000..83a2744
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/RSBaseGraphics.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.RenderScript;
+import android.renderscript.RenderScript.RSMessageHandler;
+import android.renderscript.RenderScriptGL;
+import android.renderscript.RenderScriptGL.SurfaceConfig;
+import android.test.AndroidTestCase;
+import com.android.cts.stub.R;
+
+/**
+ * Base RenderScript test class. This class provides a message handler and a
+ * convenient way to wait for compute scripts to complete their execution.
+ */
+class RSBaseGraphics extends RSBase {
+ RenderScriptGL mRS;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mRS = new RenderScriptGL(mCtx, new SurfaceConfig());
+ mRS.setMessageHandler(mRsMessage);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ if (mRS != null) {
+ mRS.destroy();
+ mRS = null;
+ }
+ super.tearDown();
+ }
+
+}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RenderScriptTest.java b/tests/tests/renderscript/src/android/renderscript/cts/RenderScriptTest.java
new file mode 100644
index 0000000..e2d7968
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/RenderScriptTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.RenderScript;
+import android.test.AndroidTestCase;
+
+public class RenderScriptTest extends AndroidTestCase {
+
+ /**
+ * Simple test for Renderscript that executes a passthrough function
+ * from cts/tests/src/android/renderscript/cts/passthrough.rs.
+ */
+ public void testRenderScript() {
+ RenderScript mRS = RenderScript.create(getContext());
+ ScriptC_passthrough t = new ScriptC_passthrough(mRS,
+ getContext().getResources(), R.raw.passthrough);
+ t.invoke_passthrough(5);
+ mRS.destroy();
+ }
+
+ /**
+ * Excercise all API calls in the basic RenderScript class.
+ */
+ public void testAPI() {
+ try {
+ RenderScript mRS = RenderScript.create(null);
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ }
+
+ RenderScript mRS = RenderScript.create(getContext());
+ mRS.contextDump();
+ mRS.finish();
+ assertEquals(mRS.getApplicationContext(),
+ getContext().getApplicationContext());
+ RenderScript.RSErrorHandler mEH = mRS.getErrorHandler();
+ RenderScript.RSMessageHandler mMH = mRS.getMessageHandler();
+ mRS.setErrorHandler(mEH);
+ mRS.setMessageHandler(mMH);
+ mRS.setPriority(RenderScript.Priority.LOW);
+ mRS.setPriority(RenderScript.Priority.NORMAL);
+ mRS.destroy();
+ }
+
+}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/SamplerTest.java b/tests/tests/renderscript/src/android/renderscript/cts/SamplerTest.java
new file mode 100644
index 0000000..7f2b052
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/SamplerTest.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.Sampler;
+import android.renderscript.Sampler.Builder;
+import android.renderscript.Sampler.Value;
+
+public class SamplerTest extends RSBaseGraphics {
+
+ Sampler.Value[] mMinValues;
+ Sampler.Value[] mMagValues;
+ Sampler.Value[] mWrapValues;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ mMinValues = new Sampler.Value[4];
+ mMinValues[0] = Sampler.Value.NEAREST;
+ mMinValues[1] = Sampler.Value.LINEAR;
+ mMinValues[2] = Sampler.Value.LINEAR_MIP_LINEAR;
+ mMinValues[3] = Sampler.Value.LINEAR_MIP_NEAREST;
+
+ mMagValues = new Sampler.Value[2];
+ mMagValues[0] = Sampler.Value.NEAREST;
+ mMagValues[1] = Sampler.Value.LINEAR;
+
+ mWrapValues = new Sampler.Value[2];
+ mWrapValues[0] = Sampler.Value.CLAMP;
+ mWrapValues[1] = Sampler.Value.WRAP;
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ mMinValues = null;
+ mMagValues = null;
+ mWrapValues = null;
+ super.tearDown();
+ }
+
+ boolean contains(Sampler.Value[] array, Sampler.Value val) {
+ for (int i = 0; i < array.length; i ++) {
+ if (array[i] == val) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void testSamplerBuilder() {
+ for (int aniso = 1; aniso <= 4; aniso++) {
+ for (Sampler.Value minV : Sampler.Value.values()) {
+ for (Sampler.Value magV : Sampler.Value.values()) {
+ for (Sampler.Value wrapSV : Sampler.Value.values()) {
+ for (Sampler.Value wrapTV : Sampler.Value.values()) {
+ Sampler.Builder b = new Sampler.Builder(mRS);
+ b.setAnisotropy(aniso);
+
+ // Some value combinations are illegal
+ boolean validMin = contains(mMinValues, minV);
+ boolean validMag = contains(mMagValues, magV);
+ boolean validS = contains(mWrapValues, wrapSV);
+ boolean validT = contains(mWrapValues, wrapTV);
+
+ try {
+ b.setMinification(minV);
+ } catch (IllegalArgumentException e) {
+ assertFalse(validMin);
+ }
+ try {
+ b.setMagnification(magV);
+ } catch (IllegalArgumentException e) {
+ assertFalse(validMag);
+ }
+ try {
+ b.setWrapS(wrapSV);
+ } catch (IllegalArgumentException e) {
+ assertFalse(validS);
+ }
+ try {
+ b.setWrapT(wrapTV);
+ } catch (IllegalArgumentException e) {
+ assertFalse(validT);
+ }
+
+ if (validMin && validMag && validS && validT) {
+ b.create();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ public void testPrebuiltSamplers() {
+ assertTrue(Sampler.CLAMP_LINEAR(mRS) != null);
+ assertTrue(Sampler.CLAMP_LINEAR_MIP_LINEAR(mRS) != null);
+ assertTrue(Sampler.CLAMP_NEAREST(mRS) != null);
+ assertTrue(Sampler.WRAP_LINEAR(mRS) != null);
+ assertTrue(Sampler.WRAP_LINEAR_MIP_LINEAR(mRS) != null);
+ assertTrue(Sampler.WRAP_NEAREST(mRS) != null);
+ }
+}
+
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/TypeTest.java b/tests/tests/renderscript/src/android/renderscript/cts/TypeTest.java
new file mode 100644
index 0000000..82c7a79
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/TypeTest.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.renderscript.cts;
+
+import com.android.cts.stub.R;
+
+import android.renderscript.Element;
+import android.renderscript.Element.DataType;
+import android.renderscript.Element.DataKind;
+import android.renderscript.Type;
+import android.renderscript.Type.Builder;
+
+public class TypeTest extends RSBaseCompute {
+
+ void testBuilderSizes(Type.Builder b, int min, int max) {
+ for (int x = min; x < max; x ++) {
+ for (int y = min; y < max; y ++) {
+ b.setX(x).setY(y);
+ b.create();
+ }
+ }
+ }
+
+ void testTypeBuilderHelper(Element e) {
+ Type.Builder b = new Type.Builder(mRS, e);
+ for (int mips = 0; mips <= 1; mips ++) {
+ boolean useMips = (mips == 1);
+
+ for (int faces = 0; faces <= 1; faces++) {
+ boolean useFaces = (faces == 1);
+
+ b.setMipmaps(useMips);
+ b.setFaces(useFaces);
+ testBuilderSizes(b, 1, 8);
+ }
+ }
+ }
+
+ public void testTypeBuilder() {
+ testTypeBuilderHelper(Element.A_8(mRS));
+ testTypeBuilderHelper(Element.RGB_565(mRS));
+ testTypeBuilderHelper(Element.RGB_888(mRS));
+ testTypeBuilderHelper(Element.RGBA_8888(mRS));
+ testTypeBuilderHelper(Element.F32(mRS));
+ testTypeBuilderHelper(Element.F32_2(mRS));
+ testTypeBuilderHelper(Element.F32_3(mRS));
+ testTypeBuilderHelper(Element.F32_4(mRS));
+ testTypeBuilderHelper(Element.BOOLEAN(mRS));
+ testTypeBuilderHelper(Element.F64(mRS));
+ testTypeBuilderHelper(Element.I8(mRS));
+ testTypeBuilderHelper(Element.I16(mRS));
+ testTypeBuilderHelper(Element.I32(mRS));
+ testTypeBuilderHelper(Element.I64(mRS));
+ testTypeBuilderHelper(Element.U8(mRS));
+ testTypeBuilderHelper(Element.U8_4(mRS));
+ testTypeBuilderHelper(Element.U16(mRS));
+ testTypeBuilderHelper(Element.U32(mRS));
+ testTypeBuilderHelper(Element.U64(mRS));
+ testTypeBuilderHelper(Element.MATRIX_2X2(mRS));
+ testTypeBuilderHelper(Element.MATRIX_3X3(mRS));
+ testTypeBuilderHelper(Element.MATRIX_4X4(mRS));
+ testTypeBuilderHelper(Element.MESH(mRS));
+ testTypeBuilderHelper(Element.PROGRAM_FRAGMENT(mRS));
+ testTypeBuilderHelper(Element.PROGRAM_RASTER(mRS));
+ testTypeBuilderHelper(Element.PROGRAM_STORE(mRS));
+ testTypeBuilderHelper(Element.PROGRAM_VERTEX(mRS));
+ testTypeBuilderHelper(Element.ALLOCATION(mRS));
+ testTypeBuilderHelper(Element.SAMPLER(mRS));
+ testTypeBuilderHelper(Element.SCRIPT(mRS));
+ testTypeBuilderHelper(Element.TYPE(mRS));
+
+ // Add some complex and struct types to test here
+ }
+
+ public void testGetCount() {
+ Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
+ for (int faces = 0; faces <= 1; faces++) {
+ boolean useFaces = faces == 1;
+ int faceMultiplier = useFaces ? 6 : 1;
+ for (int x = 1; x < 8; x ++) {
+ for (int y = 1; y < 8; y ++) {
+ b.setFaces(useFaces);
+ b.setX(x).setY(y);
+ Type t = b.create();
+ assertTrue(t.getCount() == x * y * faceMultiplier);
+ }
+ }
+ }
+
+ // Test mipmaps
+ b.setFaces(false);
+ b.setMipmaps(true);
+ Type t = b.setX(8).setY(1).create();
+ int expectedCount = 8 + 4 + 2 + 1;
+ assertTrue(t.getCount() == expectedCount);
+
+ t = b.setX(8).setY(8).create();
+ expectedCount = 8*8 + 4*4 + 2*2 + 1;
+ assertTrue(t.getCount() == expectedCount);
+
+ t = b.setX(8).setY(4).create();
+ expectedCount = 8*4 + 4*2 + 2*1 + 1;
+ assertTrue(t.getCount() == expectedCount);
+
+ t = b.setX(4).setY(8).create();
+ assertTrue(t.getCount() == expectedCount);
+
+ t = b.setX(7).setY(1).create();
+ expectedCount = 7 + 3 + 1;
+ assertTrue(t.getCount() == expectedCount);
+
+ t = b.setX(7).setY(3).create();
+ expectedCount = 7*3 + 3*1 + 1;
+ assertTrue(t.getCount() == expectedCount);
+ }
+}
+
+
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
index 2a0bcbe..d7233d5 100755
--- a/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
@@ -99,7 +99,7 @@
super.setUp();
mTelephonyManager =
(TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
- mPackageManager = mContext.getPackageManager();
+ mPackageManager = getContext().getPackageManager();
mDestAddr = mTelephonyManager.getLine1Number();
mText = "This is a test message";
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
index 515f8b5..8c6ad01 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
@@ -22,6 +22,7 @@
import dalvik.annotation.TestTargets;
import android.content.Context;
+import android.content.pm.PackageManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
@@ -30,6 +31,7 @@
public class SmsMessageTest extends AndroidTestCase{
private TelephonyManager mTelephonyManager;
+ private PackageManager mPackageManager;
private static final String DISPLAY_MESSAGE_BODY = "test subject /test body";
private static final String DMB = "{ testBody[^~\\] }";
@@ -69,7 +71,7 @@
super.setUp();
mTelephonyManager =
(TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
- assertNotNull(mTelephonyManager);
+ mPackageManager = getContext().getPackageManager();
}
@SuppressWarnings("deprecation")
@@ -171,10 +173,12 @@
)
})
public void testCreateFromPdu() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+ if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+ || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
// TODO: temp workaround, need to adjust test to use CDMA pdus
return;
}
+
String pdu = "07916164260220F0040B914151245584F600006060605130308A04D4F29C0E";
SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
assertEquals(SCA1, sms.getServiceCenterAddress());
@@ -254,7 +258,8 @@
)
})
public void testCPHSVoiceMail() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+ if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+ || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
// TODO: temp workaround, need to adjust test to use CDMA pdus
return;
}
@@ -302,7 +307,8 @@
)
})
public void testGetUserData() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+ if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+ || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
// TODO: temp workaround, need to adjust test to use CDMA pdus
return;
}
@@ -331,6 +337,10 @@
)
})
public void testGetSubmitPdu() throws Exception {
+ if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+ return;
+ }
+
String scAddress = null, destinationAddress = null;
String message = null;
boolean statusReportRequested = false;
@@ -403,10 +413,12 @@
)
})
public void testEmailGateway() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+ if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+ || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
// TODO: temp workaround, need to adjust test to use CDMA pdus
return;
}
+
String pdu = "07914151551512f204038105f300007011103164638a28e6f71b50c687db" +
"7076d9357eb7412f7a794e07cdeb6275794c07bde8e5391d247e93f3";
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index 6e8aa27..645eb81 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -296,7 +296,6 @@
break;
case TelephonyManager.PHONE_TYPE_NONE:
- assertNull(deviceId);
assertSerialNumber();
assertMacAddressReported();
break;
diff --git a/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java b/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java
deleted file mode 100644
index 8b26880..0000000
--- a/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java
+++ /dev/null
@@ -1,468 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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 android.telephony.gsm.cts;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import android.content.Context;
-import android.telephony.TelephonyManager;
-import android.telephony.gsm.SmsMessage;
-import android.test.AndroidTestCase;
-
-@SuppressWarnings("deprecation")
-@TestTargetClass(SmsMessage.class)
-public class SmsMessageTest extends AndroidTestCase{
-
- private TelephonyManager mTelephonyManager;
-
- private static final String DISPLAY_MESSAGE_BODY = "test subject /test body";
- private static final String DMB = "{ testBody[^~\\] }";
- private static final String EMAIL_ADD = "foo@example.com";
- private static final String EMAIL_FROM = "foo@example.com";
- private static final String MB = DMB;
- private static final String MESSAGE_BODY1 = "Test";
- private static final String MESSAGE_BODY2 = "(Subject)Test";
- private static final String MESSAGE_BODY3 = "\u2122\u00a9\u00aehello";
- private static final String MESSAGE_BODY4 = " ";
- private static final String MESSAGE_BODY5 = " ";
- private static final String OA = "foo@example.com";
- private static final String OA1 = "+14154255486";
- private static final String OA2 = "+15122977683";
- private static final String OA3 = "_@";
- private static final String OA4 = "\u0394@";
- // pseudo subject will always be empty
- private static final String PSEUDO_SUBJECT = "";
- private static final String SCA1 = "+16466220020";
- private static final String SCA2 = "+12063130012";
- private static final String SCA3 = "+14155551212";
- private static final String SCA4 = "+14155551212";
- private static final int NOT_CREATE_FROM_SIM = -1;
- private static final int PROTOCOL_IDENTIFIER = 0;
- private static final int SMS_NUMBER1 = 1;
- private static final int SMS_NUMBER2 = 1;
- private static final int SMS_NUMBER3 = 1;
- private static final int STATUS = 0;
- private static final int STATUS_ON_SIM_DEF = -1;
- private static final int TPLAYER_LENGTH_FOR_PDU = 23;
- private static final long TIMESTAMP_MILLIS = 1149631383000l;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mTelephonyManager =
- (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
- assertNotNull(mTelephonyManager);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "createFromPdu",
- args = {byte[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getServiceCenterAddress",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getOriginatingAddress",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getTPLayerLengthForPDU",
- args = {String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getMessageBody",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "calculateLength",
- args = {CharSequence.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "calculateLength",
- args = {String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getPdu",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isEmail",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isCphsMwiMessage",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isMwiDontStore",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isReplyPathPresent",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isStatusReportMessage",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getProtocolIdentifier",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getIndexOnSim",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getMessageClass",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getStatus",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getStatusOnSim",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getTimestampMillis",
- args = {}
- )
- })
- public void testCreateFromPdu() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
- // TODO: temp workaround, need to adjust test to use CDMA pdus
- return;
- }
-
- String pdu = "07916164260220F0040B914151245584F600006060605130308A04D4F29C0E";
- SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertEquals(SCA1, sms.getServiceCenterAddress());
- assertEquals(OA1, sms.getOriginatingAddress());
- assertEquals(MESSAGE_BODY1, sms.getMessageBody());
- assertEquals(TPLAYER_LENGTH_FOR_PDU, SmsMessage.getTPLayerLengthForPDU(pdu));
- int[] result = SmsMessage.calculateLength(sms.getMessageBody(), true);
- assertEquals(SMS_NUMBER1, result[0]);
- assertEquals(sms.getMessageBody().length(), result[1]);
- assertEquals(SmsMessage.MAX_USER_DATA_SEPTETS - sms.getMessageBody().length(), result[2]);
- assertEquals(SmsMessage.ENCODING_7BIT, result[3]);
- assertEquals(pdu, toHexString(sms.getPdu()));
-
- assertEquals(NOT_CREATE_FROM_SIM, sms.getIndexOnSim());
- assertEquals(PROTOCOL_IDENTIFIER, sms.getProtocolIdentifier());
- assertFalse(sms.isEmail());
- assertFalse(sms.isReplyPathPresent());
- assertFalse(sms.isStatusReportMessage());
- assertFalse(sms.isCphsMwiMessage());
- assertEquals(SmsMessage.MessageClass.UNKNOWN, sms.getMessageClass());
- assertEquals(STATUS, sms.getStatus());
- assertEquals(STATUS_ON_SIM_DEF, sms.getStatusOnSim());
- assertEquals(TIMESTAMP_MILLIS, sms.getTimestampMillis());
-
- // Test create from null Pdu
- sms = SmsMessage.createFromPdu(null);
- assertNotNull(sms);
-
- //Test create from long Pdu
- pdu = "07912160130310F2040B915121927786F300036060924180008A0DA"
- + "8695DAC2E8FE9296A794E07";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertEquals(SCA2, sms.getServiceCenterAddress());
- assertEquals(OA2, sms.getOriginatingAddress());
- assertEquals(MESSAGE_BODY2, sms.getMessageBody());
- CharSequence msgBody = (CharSequence) sms.getMessageBody();
- result = SmsMessage.calculateLength(msgBody, false);
- assertEquals(SMS_NUMBER2, result[0]);
- assertEquals(sms.getMessageBody().length(), result[1]);
- assertEquals(SmsMessage.MAX_USER_DATA_SEPTETS - sms.getMessageBody().length(), result[2]);
- assertEquals(SmsMessage.ENCODING_7BIT, result[3]);
-
- // Test createFromPdu Ucs to Sms
- pdu = "07912160130300F4040B914151245584"
- + "F600087010807121352B10212200A900AE00680065006C006C006F";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertEquals(MESSAGE_BODY3, sms.getMessageBody());
- result = SmsMessage.calculateLength(sms.getMessageBody(), true);
- assertEquals(SMS_NUMBER3, result[0]);
- assertEquals(sms.getMessageBody().length(), result[1]);
- assertEquals(SmsMessage.MAX_USER_DATA_SEPTETS - sms.getMessageBody().length(), result[2]);
- assertEquals(SmsMessage.ENCODING_7BIT, result[3]);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isReplace",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isMWISetMessage",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isMWIClearMessage",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isMwiDontStore",
- args = {}
- )
- })
- public void testCPHSVoiceMail() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
- // TODO: temp workaround, need to adjust test to use CDMA pdus
- return;
- }
-
- // "set MWI flag"
- String pdu = "07912160130310F20404D0110041006060627171118A0120";
- SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertTrue(sms.isReplace());
- assertEquals(OA3, sms.getOriginatingAddress());
- assertEquals(MESSAGE_BODY4, sms.getMessageBody());
- assertTrue(sms.isMWISetMessage());
-
- // "clear mwi flag"
- pdu = "07912160130310F20404D0100041006021924193352B0120";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertTrue(sms.isMWIClearMessage());
-
- // "clear MWI flag"
- pdu = "07912160130310F20404D0100041006060627161058A0120";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertTrue(sms.isReplace());
- assertEquals(OA4, sms.getOriginatingAddress());
- assertEquals(MESSAGE_BODY5, sms.getMessageBody());
- assertTrue(sms.isMWIClearMessage());
-
- // "set MWI flag"
- pdu = "07912180958750F84401800500C87020026195702B06040102000200";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertTrue(sms.isMWISetMessage());
- assertTrue(sms.isMwiDontStore());
-
- // "clear mwi flag"
- pdu = "07912180958750F84401800500C07020027160112B06040102000000";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-
- assertTrue(sms.isMWIClearMessage());
- assertTrue(sms.isMwiDontStore());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getUserData",
- args = {}
- )
- })
- public void testGetUserData() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
- // TODO: temp workaround, need to adjust test to use CDMA pdus
- return;
- }
-
- String pdu = "07914140279510F6440A8111110301003BF56080207130138A8C0B05040B8423F"
- + "000032A02010106276170706C69636174696F6E2F766E642E7761702E6D6D732D"
- + "6D65737361676500AF848D0185B4848C8298524E453955304A6D7135514141426"
- + "66C414141414D7741414236514141414141008D908918802B3135313232393737"
- + "3638332F545950453D504C4D4E008A808E022B918805810306977F83687474703"
- + "A2F2F36";
- SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- byte[] userData = sms.getUserData();
- assertNotNull(userData);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getSubmitPdu",
- args = {String.class, String.class, String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getSubmitPdu",
- args = {String.class, String.class, short.class, byte[].class, boolean.class}
- )
- })
- public void testGetSubmitPdu() throws Exception {
- String scAddress = null, destinationAddress = null;
- String message = null;
- boolean statusReportRequested = false;
-
- try {
- // null message, null destination
- SmsMessage.getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested);
- fail("Should throw NullPointerException");
- } catch (NullPointerException expected) {
- // expected
- }
-
- message = "This is a test message";
- try {
- // non-null message
- SmsMessage.getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested);
- fail("Should throw NullPointerException");
- } catch (NullPointerException expected) {
- // expected
- }
-
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
- // TODO: temp workaround, OCTET encoding for EMS not properly supported
- return;
- }
-
- scAddress = "1650253000";
- destinationAddress = "18004664411";
- message = "This is a test message";
- statusReportRequested = false;
- SmsMessage.SubmitPdu smsPdu =
- SmsMessage.getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested);
- assertNotNull(smsPdu);
-
- smsPdu = SmsMessage.getSubmitPdu(scAddress, destinationAddress, (short)80,
- message.getBytes(), statusReportRequested);
- assertNotNull(smsPdu);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getEmailBody",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getEmailFrom",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getDisplayMessageBody",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getPseudoSubject",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getDisplayOriginatingAddress",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isEmail",
- args = {}
- )
- })
- public void testEmailGateway() throws Exception {
- if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
- // TODO: temp workaround, need to adjust test to use CDMA pdus
- return;
- }
- String pdu = "07914151551512f204038105f300007011103164638a28e6f71b50c687db" +
- "7076d9357eb7412f7a794e07cdeb6275794c07bde8e5391d247e93f3";
-
- SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertEquals(SCA4, sms.getServiceCenterAddress());
- assertTrue(sms.isEmail());
- assertEquals(EMAIL_ADD, sms.getEmailFrom());
- assertEquals(EMAIL_ADD, sms.getDisplayOriginatingAddress());
- assertEquals(PSEUDO_SUBJECT, sms.getPseudoSubject());
-
- assertEquals(DISPLAY_MESSAGE_BODY, sms.getDisplayMessageBody());
- assertEquals(DISPLAY_MESSAGE_BODY, sms.getEmailBody());
-
- pdu = "07914151551512f204038105f400007011103105458a29e6f71b50c687db" +
- "7076d9357eb741af0d0a442fcfe9c23739bfe16d289bdee6b5f1813629";
- sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
- assertEquals(SCA3, sms.getServiceCenterAddress());
- assertTrue(sms.isEmail());
- assertEquals(OA, sms.getDisplayOriginatingAddress());
- assertEquals(EMAIL_FROM, sms.getEmailFrom());
- assertEquals(DMB, sms.getDisplayMessageBody());
- assertEquals(MB, sms.getEmailBody());
- }
-
- private final static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'A', 'B', 'C', 'D', 'E', 'F' };
-
- public static String toHexString(byte[] array) {
- int length = array.length;
- char[] buf = new char[length * 2];
-
- int bufIndex = 0;
- for (int i = 0 ; i < length; i++)
- {
- byte b = array[i];
- buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
- buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
- }
-
- return new String(buf);
- }
-
- private static int toByte(char c) {
- if (c >= '0' && c <= '9') return (c - '0');
- if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
- if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
-
- throw new RuntimeException ("Invalid hex char '" + c + "'");
- }
-
- private static byte[] hexStringToByteArray(String hexString) {
- int length = hexString.length();
- byte[] buffer = new byte[length / 2];
-
- for (int i = 0 ; i < length ; i += 2) {
- buffer[i / 2] =
- (byte)((toByte(hexString.charAt(i)) << 4) | toByte(hexString.charAt(i+1)));
- }
-
- return buffer;
- }
-}
diff --git a/tests/tests/text/src/android/text/cts/LayoutTest.java b/tests/tests/text/src/android/text/cts/LayoutTest.java
index 4c305bb..60bac35 100644
--- a/tests/tests/text/src/android/text/cts/LayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/LayoutTest.java
@@ -21,12 +21,7 @@
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.ToBeFixed;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.graphics.Path;
import android.graphics.Rect;
-import android.graphics.Bitmap.Config;
import android.test.AndroidTestCase;
import android.text.Layout;
import android.text.Spannable;
@@ -82,53 +77,6 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "draw",
- args = {android.graphics.Canvas.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testDraw1() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- layout.draw(new Canvas());
-
- try {
- layout.draw(new Canvas(Bitmap.createBitmap(200, 200, Config.ARGB_4444)));
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "draw",
- args = {android.graphics.Canvas.class, android.graphics.Path.class,
- android.graphics.Paint.class, int.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testDraw2() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- layout.draw(new Canvas(), null, null, 0);
-
- try {
- Bitmap bitmap = Bitmap.createBitmap(200, 200,Config.ARGB_4444);
- layout.draw(new Canvas(bitmap), null, null, 0);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
-
- try {
- Bitmap bitmap = Bitmap.createBitmap(200, 200, null);
- layout.draw(new Canvas(bitmap), new Path(), new Paint(), 2);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getText",
args = {}
)
@@ -280,66 +228,6 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "getPrimaryHorizontal",
- args = {int.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetPrimaryHorizontal() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- try {
- layout.getPrimaryHorizontal(0);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getSecondaryHorizontal",
- args = {int.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetSecondaryHorizontal() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- try {
- layout.getSecondaryHorizontal(0);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getLineLeft",
- args = {int.class}
- )
- public void testGetLineLeft() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- assertEquals(2.0f, layout.getLineLeft(0));
- assertEquals(4.0f, layout.getLineLeft(1));
- assertEquals(1.0f, layout.getLineLeft(2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getLineRight",
- args = {int.class}
- )
- public void testGetLineRight() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- assertEquals(9.0f, layout.getLineRight(0));
- assertEquals(7.0f, layout.getLineRight(1));
- assertEquals(10.0f, layout.getLineRight(2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getLineForVertical",
args = {int.class}
)
@@ -368,23 +256,6 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "getOffsetForHorizontal",
- args = {int.class, float.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetOffsetForHorizontal() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- try {
- layout.getOffsetForHorizontal(0, 0);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getLineEnd",
args = {int.class}
)
@@ -450,84 +321,6 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "getOffsetToLeftOf",
- args = {int.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetOffsetToLeftOf() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- try {
- layout.getOffsetToLeftOf(0);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getOffsetToRightOf",
- args = {int.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetOffsetToRightOf() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- try {
- layout.getOffsetToRightOf(0);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getCursorPath",
- args = {int.class, android.graphics.Path.class, java.lang.CharSequence.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetCursorPath() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- try {
- layout.getCursorPath(0, new Path(), "test");
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getSelectionPath",
- args = {int.class, int.class, android.graphics.Path.class}
- )
- @ToBeFixed(bug = "1386429", explanation = "can not get the" +
- " package protected class Directions")
- public void testGetSelectionPath() {
- Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
- mAlign, mSpacingmult, mSpacingadd);
- Path path = new Path();
-
- layout.getSelectionPath(0, 0, path);
-
- try {
- layout.getSelectionPath(1, 0, path);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
-
- try {
- layout.getSelectionPath(0, 1, path);
- fail("should throw NullPointerException here");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getParagraphAlignment",
args = {int.class}
)
diff --git a/tests/tests/text/src/android/text/cts/SelectionTest.java b/tests/tests/text/src/android/text/cts/SelectionTest.java
index 11ba854..4fc3386 100644
--- a/tests/tests/text/src/android/text/cts/SelectionTest.java
+++ b/tests/tests/text/src/android/text/cts/SelectionTest.java
@@ -16,15 +16,16 @@
package android.text.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.ToBeFixed;
+
import android.test.AndroidTestCase;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.ToBeFixed;
@TestTargetClass(Selection.class)
public class SelectionTest extends AndroidTestCase {
@@ -106,12 +107,6 @@
fail("should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
}
-
- try {
- Selection.setSelection(null, 3, 6);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
}
@TestTargetNew(
@@ -145,12 +140,6 @@
fail("should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
}
-
- try {
- Selection.setSelection(null, 3);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
}
@TestTargetNew(
@@ -158,7 +147,6 @@
method = "removeSelection",
args = {android.text.Spannable.class}
)
- @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
public void testRemoveSelection() {
CharSequence text = "hello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -176,12 +164,6 @@
Selection.removeSelection(builder);
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
-
- try {
- Selection.removeSelection(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
}
@TestTargetNew(
@@ -189,7 +171,6 @@
method = "selectAll",
args = {android.text.Spannable.class}
)
- @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
public void testSelectAll() {
CharSequence text = "hello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -214,12 +195,6 @@
Selection.selectAll(empty);
assertEquals(0, Selection.getSelectionStart(empty));
assertEquals(0, Selection.getSelectionEnd(empty));
-
- try {
- Selection.selectAll(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
}
@TestTargetNew(
@@ -227,8 +202,6 @@
method = "moveLeft",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testMoveLeft() {
CharSequence text = "hello\nworld";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -236,12 +209,6 @@
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
- try {
- Selection.moveLeft(builder, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
Selection.setSelection(builder, 6, 8);
assertTrue(Selection.moveLeft(builder, layout));
assertEquals(6, Selection.getSelectionStart(builder));
@@ -260,24 +227,6 @@
assertTrue(Selection.moveLeft(builder, layout));
assertEquals(0, Selection.getSelectionStart(builder));
assertEquals(0, Selection.getSelectionEnd(builder));
-
- try {
- Selection.moveLeft(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.moveLeft(null, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.moveLeft(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
}
@TestTargetNew(
@@ -285,8 +234,6 @@
method = "moveRight",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testMoveRight() {
CharSequence text = "hello\nworld";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -294,12 +241,6 @@
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
- try {
- Selection.moveRight(builder, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
Selection.setSelection(builder,1, 5);
assertTrue(Selection.moveRight(builder, layout));
assertEquals(5, Selection.getSelectionStart(builder));
@@ -322,24 +263,6 @@
assertTrue(Selection.moveRight(builder, layout));
assertEquals(text.length(), Selection.getSelectionStart(builder));
assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
- try {
- Selection.moveRight(null, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.moveRight(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.moveRight(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
}
@TestTargetNew(
@@ -347,7 +270,6 @@
method = "moveUp",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
public void testMoveUp() {
CharSequence text = "Google\nhello,world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -380,14 +302,6 @@
assertFalse(Selection.moveUp(builder, layout));
assertEquals(5, Selection.getSelectionStart(builder));
assertEquals(5, Selection.getSelectionEnd(builder));
-
- try {
- Selection.moveUp(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- Selection.moveUp(null, layout);
}
@TestTargetNew(
@@ -395,8 +309,6 @@
method = "moveDown",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testMoveDown() {
CharSequence text = "hello,world\nGoogle";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -404,12 +316,6 @@
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
- try {
- Selection.moveDown(builder, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
Selection.setSelection(builder, 1, 3);
assertTrue(Selection.moveDown(builder, layout));
assertEquals(3, Selection.getSelectionStart(builder));
@@ -433,18 +339,6 @@
Selection.moveDown(builder, layout);
assertEquals(18, Selection.getSelectionStart(builder));
assertEquals(18, Selection.getSelectionEnd(builder));
-
- try {
- Selection.moveDown(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.moveDown(null, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
}
@TestTargetNew(
@@ -452,8 +346,6 @@
method = "extendSelection",
args = {android.text.Spannable.class, int.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testExtendSelection() {
CharSequence text = "hello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -505,8 +397,6 @@
method = "extendLeft",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testExtendLeft() {
CharSequence text = "Google\nhello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -514,12 +404,6 @@
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
- try {
- Selection.extendLeft(builder, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
Selection.setSelection(builder, 7, 8);
assertTrue(Selection.extendLeft(builder, layout));
assertEquals(7, Selection.getSelectionStart(builder));
@@ -537,24 +421,6 @@
assertTrue(Selection.extendLeft(builder, layout));
assertEquals(0, Selection.getSelectionStart(builder));
assertEquals(0, Selection.getSelectionEnd(builder));
-
- try {
- Selection.extendLeft(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.extendLeft(null, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.extendLeft(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
}
@TestTargetNew(
@@ -562,8 +428,6 @@
method = "extendRight",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testExtendRight() {
CharSequence text = "Google\nhello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -571,12 +435,6 @@
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
- try {
- Selection.extendRight(builder, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
Selection.setSelection(builder, 1, 6);
assertTrue(Selection.extendRight(builder, layout));
assertEquals(1, Selection.getSelectionStart(builder));
@@ -590,24 +448,6 @@
assertTrue(Selection.extendRight(builder, layout));
assertEquals(12, Selection.getSelectionStart(builder));
assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
- try {
- Selection.extendRight(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.extendRight(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.extendRight(null, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
}
@TestTargetNew(
@@ -615,7 +455,6 @@
method = "extendUp",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
public void testExtendUp() {
CharSequence text = "Google\nhello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -640,18 +479,6 @@
assertEquals(8, Selection.getSelectionStart(builder));
assertEquals(0, Selection.getSelectionEnd(builder));
- try {
- Selection.extendUp(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.extendUp(null, layout);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
builder = new SpannableStringBuilder();
assertTrue(Selection.extendUp(builder, layout));
assertEquals(-1, Selection.getSelectionStart(builder));
@@ -663,8 +490,6 @@
method = "extendDown",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testExtendDown() {
CharSequence text = "Google\nhello, world";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -672,12 +497,6 @@
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
- try {
- Selection.extendDown(builder, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
Selection.setSelection(builder, 1, 3);
assertTrue(Selection.extendDown(builder, layout));
assertEquals(1, Selection.getSelectionStart(builder));
@@ -690,24 +509,6 @@
assertTrue(Selection.extendDown(builder, layout));
assertEquals(1, Selection.getSelectionStart(builder));
assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
- try {
- Selection.extendDown(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.extendDown(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.extendDown(null, layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
}
@TestTargetNew(
@@ -715,7 +516,6 @@
method = "extendToLeftEdge",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
public void testExtendToLeftEdge() {
CharSequence text = "hello\nworld";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -742,18 +542,6 @@
assertEquals(2, Selection.getSelectionStart(builder));
assertEquals(0, Selection.getSelectionEnd(builder));
- try {
- Selection.extendToLeftEdge(new SpannableStringBuilder(), null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.extendToLeftEdge(null, layout);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
builder = new SpannableStringBuilder();
assertEquals(-1, Selection.getSelectionStart(builder));
assertEquals(-1, Selection.getSelectionEnd(builder));
@@ -768,8 +556,6 @@
method = "extendToRightEdge",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testExtendToRightEdge() {
CharSequence text = "hello\nworld";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -794,24 +580,6 @@
assertTrue(Selection.extendToRightEdge(builder, layout));
assertEquals(1, Selection.getSelectionStart(builder));
assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
- try {
- Selection.extendToRightEdge(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Selection.extendToRightEdge(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.extendToRightEdge(null, layout);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
}
@TestTargetNew(
@@ -819,7 +587,6 @@
method = "moveToLeftEdge",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
public void testMoveToLeftEdge() {
CharSequence text = "hello\nworld";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -845,18 +612,6 @@
assertEquals(0, Selection.getSelectionStart(builder));
assertEquals(0, Selection.getSelectionEnd(builder));
- try {
- Selection.moveToLeftEdge(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.moveToLeftEdge(null, layout);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
builder = new SpannableStringBuilder();
assertTrue(Selection.moveToLeftEdge(builder, layout));
assertEquals(0, Selection.getSelectionStart(builder));
@@ -868,8 +623,6 @@
method = "moveToRightEdge",
args = {android.text.Spannable.class, android.text.Layout.class}
)
- @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
- "and NullPointerException")
public void testMoveToRightEdge() {
CharSequence text = "hello\nworld";
SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -894,23 +647,5 @@
assertTrue(Selection.moveToRightEdge(builder, layout));
assertEquals(text.length(), Selection.getSelectionStart(builder));
assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
- try {
- Selection.moveToRightEdge(builder, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.moveToRightEdge(null, layout);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- }
-
- try {
- Selection.moveToRightEdge(new SpannableStringBuilder(), layout);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
}
}
diff --git a/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java b/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
index 26ebfb5..f8b4336 100644
--- a/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
+++ b/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
@@ -16,6 +16,12 @@
package android.text.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
import android.test.AndroidTestCase;
import android.text.InputFilter;
import android.text.SpannableString;
@@ -24,11 +30,6 @@
import android.text.style.StrikethroughSpan;
import android.text.style.TabStopSpan;
import android.text.style.UnderlineSpan;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
/**
* Test {@link SpannableStringBuilder}.
@@ -250,6 +251,28 @@
builder.replace(0, 5, text, 0, text.length());
assertEquals("ahiabc, world", builder.toString());
+ // Replacing by an empty string (identical target indexes)
+ builder = new SpannableStringBuilder("hello, world");
+ builder.replace(4, 6, "", 0, 0);
+ assertEquals("hell world", builder.toString());
+
+ builder = new SpannableStringBuilder("hello, world");
+ builder.replace(4, 6, "any string", 5, 5);
+ assertEquals("hell world", builder.toString());
+
+ // Inserting in place (no deletion)
+ builder = new SpannableStringBuilder("hello, world");
+ builder.replace(3, 3, "any string", 0, 0);
+ assertEquals("hello, world", builder.toString());
+
+ builder = new SpannableStringBuilder("hello, world");
+ builder.replace(7, 7, "nice ", 0, 5);
+ assertEquals("hello, nice world", builder.toString());
+
+ builder = new SpannableStringBuilder("hello, world");
+ builder.replace(0, 0, "say ", 1, 4);
+ assertEquals("ay hello, world", builder.toString());
+
try {
builder.replace(0, 5, text, 10, 3);
fail("should throw IndexOutOfBoundsException here");
diff --git a/tests/tests/text/src/android/text/cts/TextUtilsTest.java b/tests/tests/text/src/android/text/cts/TextUtilsTest.java
index 0b274f5..99f4f40 100755
--- a/tests/tests/text/src/android/text/cts/TextUtilsTest.java
+++ b/tests/tests/text/src/android/text/cts/TextUtilsTest.java
@@ -139,14 +139,6 @@
} catch (NullPointerException e) {
// issue 1688347, not clear what is supposed to happen if TextPaint is null.
}
-
- try {
- TextUtils.commaEllipsize(text, p, textWidth, "plus 1", null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // issue 1688347, not clear what is supposed to happen
- // if the string for "%d more" in the current locale is null.
- }
}
@TestTargetNew(
@@ -365,11 +357,11 @@
" In other methods, MARQUEE is equivalent to END, except for the first line.")
public void testEllipsize() {
TextPaint p = new TextPaint();
-
+
// turn off kerning. with kerning enabled, different methods of measuring the same text
// produce different results.
p.setFlags(p.getFlags() & ~p.DEV_KERN_TEXT_FLAG);
-
+
CharSequence text = "long string to truncate";
float textWidth = p.measureText(mEllipsis + "uncate");
@@ -391,16 +383,14 @@
TextUtils.ellipsize(text, p, textWidth, TruncateAt.MARQUEE).toString());
textWidth = p.measureText(mEllipsis);
- assertEquals(mEllipsis, TextUtils.ellipsize(text, p, textWidth, TruncateAt.END).toString());
+ assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.END).toString());
assertEquals("", TextUtils.ellipsize(text, p, textWidth - 1, TruncateAt.END).toString());
assertEquals("", TextUtils.ellipsize(text, p, -1f, TruncateAt.END).toString());
assertEquals(text,
TextUtils.ellipsize(text, p, Float.MAX_VALUE, TruncateAt.END).toString());
- assertEquals(mEllipsis,
- TextUtils.ellipsize(text, p, textWidth, TruncateAt.START).toString());
- assertEquals(mEllipsis,
- TextUtils.ellipsize(text, p, textWidth, TruncateAt.MIDDLE).toString());
+ assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.START).toString());
+ assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.MIDDLE).toString());
try {
TextUtils.ellipsize(text, null, textWidth, TruncateAt.MIDDLE);
@@ -436,7 +426,7 @@
// turn off kerning. with kerning enabled, different methods of measuring the same text
// produce different results.
p.setFlags(p.getFlags() & ~p.DEV_KERN_TEXT_FLAG);
-
+
TextUtils.EllipsizeCallback callback = new TextUtils.EllipsizeCallback() {
public void ellipsized(final int start, final int end) {
mStart = start;
@@ -523,14 +513,14 @@
// avail is long enough for ELLIPSIS, and preserveLength is specified.
resetRange();
- assertEquals(getBlankString(true, text.length()),
+ assertEquals(getBlankString(false, text.length()),
TextUtils.ellipsize(text, p, textWidth, TruncateAt.END, true, callback).toString());
assertEquals(0, mStart);
assertEquals(text.length(), mEnd);
// avail is long enough for ELLIPSIS, and preserveLength doesn't be specified.
resetRange();
- assertEquals(mEllipsis,
+ assertEquals("",
TextUtils.ellipsize(text, p, textWidth, TruncateAt.END, false,
callback).toString());
assertEquals(0, mStart);
diff --git a/tests/tests/text/src/android/text/format/cts/DateFormatTest.java b/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
index 37b337f..f24117e 100644
--- a/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
+++ b/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
@@ -32,6 +32,7 @@
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
+import java.util.TimeZone;
@TestTargetClass(DateFormat.class)
public class DateFormatTest extends AndroidTestCase {
@@ -174,4 +175,29 @@
actual = DateFormat.format(format, formatDate.getTime());
assertEquals(expectedString, actual.toString());
}
+
+ @TestTargetNew(level = TestLevel.ADDITIONAL)
+ public void test2038() {
+ Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+
+ calendar.setTimeInMillis(((long) Integer.MIN_VALUE + Integer.MIN_VALUE) * 1000L);
+ assertEquals("Sun Nov 24 17:31:44 GMT+00:00 1833",
+ DateFormat.format("EEE MMM dd kk:mm:ss zzz yyyy", calendar));
+
+ calendar.setTimeInMillis(Integer.MIN_VALUE * 1000L);
+ assertEquals("Fri Dec 13 20:45:52 GMT+00:00 1901",
+ DateFormat.format("EEE MMM dd kk:mm:ss zzz yyyy", calendar));
+
+ calendar.setTimeInMillis(0L);
+ assertEquals("Thu Jan 01 00:00:00 GMT+00:00 1970",
+ DateFormat.format("EEE MMM dd kk:mm:ss zzz yyyy", calendar));
+
+ calendar.setTimeInMillis(Integer.MAX_VALUE * 1000L);
+ assertEquals("Tue Jan 19 03:14:07 GMT+00:00 2038",
+ DateFormat.format("EEE MMM dd kk:mm:ss zzz yyyy", calendar));
+
+ calendar.setTimeInMillis((2L + Integer.MAX_VALUE + Integer.MAX_VALUE) * 1000L);
+ assertEquals("Sun Feb 07 06:28:16 GMT+00:00 2106",
+ DateFormat.format("EEE MMM dd kk:mm:ss zzz yyyy", calendar));
+ }
}
diff --git a/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java b/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java
index 6d034b9..9e773cb 100644
--- a/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java
+++ b/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java
@@ -16,17 +16,17 @@
package android.text.format.cts;
+import android.content.Context;
+import android.test.AndroidTestCase;
+import android.text.format.DateUtils;
+import dalvik.annotation.KnownFailure;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
-
-import android.content.Context;
-import android.test.AndroidTestCase;
-import android.text.format.DateUtils;
-
import java.util.Calendar;
import java.util.Date;
+import java.util.Formatter;
import java.util.Locale;
@TestTargetClass(DateUtils.class)
@@ -302,4 +302,32 @@
assertTrue(DateUtils.isToday(mBaseTime));
assertFalse(DateUtils.isToday(mBaseTime - DAY_DURATION));
}
+
+ /**
+ * DateUtils is broken beyond Integer.MAX_VALUE seconds of 1970.
+ * http://code.google.com/p/android/issues/detail?id=13050
+ */
+ @TestTargetNew(level = TestLevel.ADDITIONAL)
+ @KnownFailure("http://b/2519073")
+ public void test2038() {
+ assertEquals("00:00, Thursday, January 1, 1970", formatFull(0L));
+
+ // these tests all fail in Honeycomb
+ assertEquals("17:31, Sunday, November 24, 1833",
+ formatFull(((long) Integer.MIN_VALUE + Integer.MIN_VALUE) * 1000L));
+ assertEquals("20:45, Friday, December 13, 1901", formatFull(Integer.MIN_VALUE * 1000L));
+ assertEquals("03:14, Tuesday, January 19, 2038", formatFull(Integer.MAX_VALUE * 1000L));
+ assertEquals("06:28, Sunday, February 7, 2106",
+ formatFull((2L + Integer.MAX_VALUE + Integer.MAX_VALUE) * 1000L));
+ }
+
+ private String formatFull(long millis) {
+ Formatter formatter = new Formatter();
+ int flags = DateUtils.FORMAT_SHOW_DATE
+ | DateUtils.FORMAT_SHOW_WEEKDAY
+ | DateUtils.FORMAT_SHOW_TIME
+ | DateUtils.FORMAT_24HOUR;
+ DateUtils.formatDateRange(null, formatter, millis, millis, flags, "UTC");
+ return formatter.toString();
+ }
}
diff --git a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
index 1d6c109..a92f323 100644
--- a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
@@ -247,7 +247,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, null));
+ KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_UP)));
// |first line
// second |line
// last line
@@ -256,7 +257,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, null));
+ KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_UP)));
// first lin|e
// second |line
// last line
@@ -267,7 +269,8 @@
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, null));
+ KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_UP)));
// |first line
// second |line
// last line
@@ -276,7 +279,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, null));
+ KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_UP)));
// |first line
// second line
// last line
@@ -285,14 +289,16 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, null));
+ KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_UP)));
// first lin|e
// second line
// last line
assertSelection(correspondingIn1stLine);
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, null));
+ KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_UP)));
// first lin|e
// second line
// last line
@@ -316,7 +322,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, null));
+ KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_DOWN)));
// first line
// second |line
// last line|
@@ -325,7 +332,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, null));
+ KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_DOWN)));
// first line
// second |line
// last lin|e
@@ -336,7 +344,8 @@
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, null));
+ KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_DOWN)));
// first line
// second |line
// last line|
@@ -345,7 +354,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, null));
+ KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_DOWN)));
// first line
// second line
// last line|
@@ -354,14 +364,16 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, null));
+ KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_DOWN)));
// first line
// second line
// last lin|e
assertSelection(correspondingIn3rdLine);
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, null));
+ KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_DOWN)));
// first line
// second line
// last lin|e
@@ -385,7 +397,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// |second |line
// last line
@@ -393,7 +406,8 @@
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// |second |line
// last line
@@ -402,7 +416,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// second| |line
// last line
@@ -410,7 +425,8 @@
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// secon|d |line
// last line
@@ -419,7 +435,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// |second line
// last line
@@ -427,7 +444,8 @@
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// |second line
// last line
@@ -436,7 +454,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line
// second| line
// last line
@@ -447,7 +466,8 @@
// |second line
// last line
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, null));
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT)));
// first line|
// second line
// last line
@@ -471,7 +491,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second |line|
// last line
@@ -479,7 +500,8 @@
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second |line|
// last line
@@ -488,7 +510,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second |l|ine
// last line
@@ -496,7 +519,8 @@
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second |li|ne
// last line
@@ -505,7 +529,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second line|
// last line
@@ -513,7 +538,8 @@
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second line|
// last line
@@ -522,7 +548,8 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second l|ine
// last line
@@ -533,7 +560,8 @@
// second line|
// last line
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, null));
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT)));
// first line
// second line
// |last line
@@ -624,43 +652,15 @@
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_CENTER, null));
+ KeyEvent.KEYCODE_DPAD_CENTER, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_CENTER)));
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_0, null));
+ KeyEvent.KEYCODE_0, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_0)));
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_E, null));
+ KeyEvent.KEYCODE_E, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E)));
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_UNKNOWN, null));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test {@link ArrowKeyMovementMethod#onKeyDown(TextView, Spannable, int, "
- + "KeyEvent)}. Test the method with null parameters.",
- method = "onKeyDown",
- args = {TextView.class, Spannable.class, int.class, KeyEvent.class}
- )
- @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete. @throws clause "
- + "should be added into javadoc of ArrowKeyMovementMethod#onKeyDown(TextView, "
- + "Spannable, int, KeyEvent)} when the params view or buffer is null")
- public void testOnKeyDownWithNullParameters() {
- initTextViewWithNullLayout();
- mEditable = (Editable) mTextView.getText();
- try {
- mArrowKeyMovementMethod.onKeyDown(null, mEditable, KeyEvent.KEYCODE_DPAD_RIGHT,
- new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
- fail("The method did not throw NullPointerException when param textView is null.");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- mArrowKeyMovementMethod.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_RIGHT,
- new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
- fail("The method did not throw NullPointerException when param spannable is null.");
- } catch (NullPointerException e) {
- // expected
- }
+ KeyEvent.KEYCODE_UNKNOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_UNKNOWN)));
}
@TestTargetNew(
diff --git a/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java b/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
index 2f8cbfd..0383463 100644
--- a/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
@@ -62,117 +62,89 @@
mTextView = (TextView) mActivity.findViewById(R.id.keylistener_textview);
}
- /**
- * Check point:
- * 1. Set the cursor and press DEL key, the character before cursor is deleted.
- * 2. Set a selection and press DEL key, the selection is deleted.
- * 3. Press ALT+DEL key, the whole content of TextView is deleted.
- * 4. when there is no any selections and press DEL key, an IndexOutOfBoundsException occurs
- * 5. ALT+DEL does not delete everything where there is a selection
- * 6. DEL key does not take effect when text view does not have BaseKeyListener.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "backspace",
- args = {View.class, Editable.class, int.class, KeyEvent.class}
- )
- @ToBeFixed(bug = "1695243", explanation = "1. when there is no any selections, " +
- "an IndexOutOfBoundsException occurs. " +
- "2. ALT+DEL does not delete everything where there is a selection, " +
- "javadoc does not explain this situation")
public void testBackspace() {
- Editable content;
+ final Editable content = Editable.Factory.getInstance().newEditable(TEST_STRING);
+ setTextViewText(content);
+
+ // Nothing to delete when the cursor is at the beginning.
final MockBaseKeyListener baseKeyListener = new MockBaseKeyListener();
KeyEvent delKeyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
-
- content = Editable.Factory.getInstance().newEditable(TEST_STRING);
Selection.setSelection(content, 0, 0);
baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, delKeyEvent);
assertEquals("123456", content.toString());
- content = Editable.Factory.getInstance().newEditable(TEST_STRING);
+ // Delete the first three letters using a selection.
+ setTextViewText(content);
Selection.setSelection(content, 0, 3);
baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, delKeyEvent);
assertEquals("456", content.toString());
- content = Editable.Factory.getInstance().newEditable(TEST_STRING);
- try {
- baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL,delKeyEvent);
- fail("did not throw IndexOutOfBoundsException when there is no selections");
- } catch (IndexOutOfBoundsException e) {
- // expected.
- }
+ // Delete the entire line wit ALT + DEL
+ setTextViewText(content);
+ KeyEvent altDelKeyEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL,
+ 0, KeyEvent.META_ALT_ON);
+ Selection.setSelection(content, 0, 0);
+ baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, altDelKeyEvent);
+ assertEquals("", content.toString());
+ }
- final String str = "123456";
+ private void setTextViewText(final CharSequence content) {
mActivity.runOnUiThread(new Runnable() {
public void run() {
- mTextView.setText(str, BufferType.EDITABLE);
- mTextView.setKeyListener(baseKeyListener);
- mTextView.requestFocus();
- Selection.setSelection((Editable) mTextView.getText(), 1, 1);
+ mTextView.setText(content, BufferType.EDITABLE);
}
});
mInstrumentation.waitForIdleSync();
- assertEquals(str, mTextView.getText().toString());
- // delete the first character '1'
+ }
+
+ public void testBackspace_withSendKeys() {
+ final MockBaseKeyListener baseKeyListener = new MockBaseKeyListener();
+ final String str = "123456";
+
+ // Delete the first character '1'
+ prepareTextView(str, baseKeyListener, 1, 1);
sendKeys(KeyEvent.KEYCODE_DEL);
assertEquals("23456", mTextView.getText().toString());
- mActivity.runOnUiThread(new Runnable() {
- public void run() {
- mTextView.setText(str, BufferType.EDITABLE);
- mTextView.requestFocus();
- Selection.setSelection((Editable) mTextView.getText(), 1, 3);
- }
- });
- mInstrumentation.waitForIdleSync();
- assertEquals(str, mTextView.getText().toString());
- // delete character '2' and '3'
+ // Delete character '2' and '3'
+ prepareTextView(str, baseKeyListener, 1, 3);
sendKeys(KeyEvent.KEYCODE_DEL);
assertEquals("1456", mTextView.getText().toString());
- mActivity.runOnUiThread(new Runnable() {
- public void run() {
- mTextView.setText(str, BufferType.EDITABLE);
- mTextView.requestFocus();
- Selection.setSelection((Editable) mTextView.getText(), 0, 0);
- }
- });
- mInstrumentation.waitForIdleSync();
- assertEquals(str, mTextView.getText().toString());
- // delete everything on the line the cursor is on.
- sendKeys(KeyEvent.KEYCODE_ALT_LEFT);
- sendKeys(KeyEvent.KEYCODE_DEL);
+ // Delete everything on the line the cursor is on.
+ prepareTextView(str, baseKeyListener, 0, 0);
+ sendAltDelete();
assertEquals("", mTextView.getText().toString());
- mActivity.runOnUiThread(new Runnable() {
- public void run() {
- mTextView.setText(str, BufferType.EDITABLE);
- mTextView.requestFocus();
- Selection.setSelection((Editable) mTextView.getText(), 2, 4);
- }
- });
- mInstrumentation.waitForIdleSync();
- assertEquals(str, mTextView.getText().toString());
// ALT+DEL deletes the selection only.
- sendKeys(KeyEvent.KEYCODE_ALT_LEFT);
- sendKeys(KeyEvent.KEYCODE_DEL);
+ prepareTextView(str, baseKeyListener, 2, 4);
+ sendAltDelete();
assertEquals("1256", mTextView.getText().toString());
- // text view does not have BaseKeyListener
+ // DEL key does not take effect when TextView does not have BaseKeyListener.
+ prepareTextView(str, null, 1, 1);
+ sendKeys(KeyEvent.KEYCODE_DEL);
+ assertEquals(str, mTextView.getText().toString());
+ }
+
+ private void prepareTextView(final CharSequence content, final BaseKeyListener keyListener,
+ final int selectionStart, final int selectionEnd) {
mActivity.runOnUiThread(new Runnable() {
public void run() {
- mTextView.setText(str, BufferType.EDITABLE);
- mTextView.setKeyListener(null);
+ mTextView.setText(content, BufferType.EDITABLE);
+ mTextView.setKeyListener(keyListener);
mTextView.requestFocus();
- Selection.setSelection((Editable) mTextView.getText(), 1, 1);
+ Selection.setSelection((Editable) mTextView.getText(), selectionStart,
+ selectionEnd);
}
});
mInstrumentation.waitForIdleSync();
- assertEquals(str, mTextView.getText().toString());
- // DEL key does not take effect
+ }
+
+ private void sendAltDelete() {
+ mInstrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ALT_LEFT));
sendKeys(KeyEvent.KEYCODE_DEL);
- assertEquals(str, mTextView.getText().toString());
+ mInstrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ALT_LEFT));
}
/**
diff --git a/tests/tests/text/src/android/text/method/cts/DateTimeKeyListenerTest.java b/tests/tests/text/src/android/text/method/cts/DateTimeKeyListenerTest.java
index b3d3a39..daaedf4 100644
--- a/tests/tests/text/src/android/text/method/cts/DateTimeKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/DateTimeKeyListenerTest.java
@@ -138,7 +138,7 @@
assertEquals(expectedText, mTextView.getText().toString());
// press 'a' key if producible
- KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
if ('a' == kcm.getMatch(KeyEvent.KEYCODE_A, DateTimeKeyListener.CHARACTERS)) {
expectedText += "a";
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_A);
diff --git a/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java b/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
index 32a98e9..6a67a5c 100644
--- a/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
@@ -29,6 +29,7 @@
import android.text.Spanned;
import android.text.method.DateKeyListener;
import android.text.method.MetaKeyKeyListener;
+import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
@@ -426,9 +427,10 @@
args = {long.class, int.class, KeyEvent.class}
)
public void testHandleKeyDown() {
+ KeyEvent fullEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT,
+ 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
long state = MetaKeyKeyListener.handleKeyDown(MetaKeyKeyListener.META_CAP_LOCKED,
- KeyEvent.KEYCODE_SHIFT_LEFT,
- new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT));
+ KeyEvent.KEYCODE_SHIFT_LEFT, fullEvent);
assertEquals(0, state);
}
@@ -438,10 +440,11 @@
args = {long.class, int.class, KeyEvent.class}
)
public void testHandleKeyUp() {
+ KeyEvent fullEvent = new KeyEvent(0, 0, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT,
+ 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
long state = MetaKeyKeyListener.handleKeyUp(MetaKeyKeyListener.META_CAP_LOCKED,
- KeyEvent.KEYCODE_SHIFT_LEFT,
- new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT));
- assertEquals(MetaKeyKeyListener.META_CAP_LOCKED, state);
+ KeyEvent.KEYCODE_SHIFT_LEFT, fullEvent);
+ assertEquals(0, state);
}
private class MockMetaKeyKeyListener extends MetaKeyKeyListener {
diff --git a/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java b/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
index ed7be70..6dde08d 100755
--- a/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
@@ -147,8 +147,7 @@
mMethod.reset();
// 12-key support
- KeyCharacterMap keymap
- = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
if (keymap.getKeyboardType() == KeyCharacterMap.NUMERIC) {
// "HELLO" in case of 12-key(NUMERIC) keyboard
sendKeys("6*4 6*3 7*5 DPAD_RIGHT 7*5 7*6 DPAD_RIGHT");
diff --git a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
index be2eede..78ebfa4 100755
--- a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
@@ -486,8 +486,9 @@
int previousScrollX = mTextView.getScrollX();
runActionOnUiThread(new Runnable() {
public void run() {
- method.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_RIGHT,
- new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
+ method.onKeyDown(mTextView, (Spannable) mTextView.getText(),
+ KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_RIGHT));
}
});
assertTrue(mTextView.getScrollX() > previousScrollX);
@@ -495,8 +496,9 @@
previousScrollX = mTextView.getScrollX();
runActionOnUiThread(new Runnable() {
public void run() {
- method.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_LEFT,
- new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
+ method.onKeyDown(mTextView, (Spannable) mTextView.getText(),
+ KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_DPAD_LEFT));
}
});
assertTrue(mTextView.getScrollX() < previousScrollX);
@@ -505,7 +507,8 @@
assertVisibleLineInTextView(0);
runActionOnUiThread(new Runnable() {
public void run() {
- assertFalse(method.onKeyDown(mTextView, mSpannable, 0, null));
+ assertFalse(method.onKeyDown(mTextView, mSpannable, 0,
+ new KeyEvent(KeyEvent.ACTION_DOWN, 0)));
}
});
assertEquals(previousScrollX, mTextView.getScrollX());
diff --git a/tests/tests/text/src/android/text/method/cts/TimeKeyListenerTest.java b/tests/tests/text/src/android/text/method/cts/TimeKeyListenerTest.java
index d087fc4..8062adf 100644
--- a/tests/tests/text/src/android/text/method/cts/TimeKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/TimeKeyListenerTest.java
@@ -131,7 +131,7 @@
assertEquals("12", mTextView.getText().toString());
// press 'a' key if producible
- KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
if ('a' == kcm.getMatch(KeyEvent.KEYCODE_A, TimeKeyListener.CHARACTERS)) {
expectedText += "a";
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_A);
diff --git a/tests/tests/text/src/android/text/method/cts/TouchTest.java b/tests/tests/text/src/android/text/method/cts/TouchTest.java
index 6b53f1d..03e5835 100755
--- a/tests/tests/text/src/android/text/method/cts/TouchTest.java
+++ b/tests/tests/text/src/android/text/method/cts/TouchTest.java
@@ -39,6 +39,9 @@
private Activity mActivity;
private static final String LONG_TEXT = "Scrolls the specified widget to the specified " +
"coordinates, except constrains the X scrolling position to the horizontal regions " +
+ "of the text that will be visible after scrolling to the specified Y position." +
+ "Scrolls the specified widget to the specified " +
+ "coordinates, except constrains the X scrolling position to the horizontal regions " +
"of the text that will be visible after scrolling to the specified Y position.";
private boolean mReturnFromTouchEvent;
diff --git a/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java b/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
index 731784a..f7c1e7a 100644
--- a/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
+++ b/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
@@ -202,8 +202,7 @@
TestCase.assertEquals("fromIndex not properly recycled", 0, event.getFromIndex());
TestCase.assertEquals("itemCount not properly recycled", 0, event.getItemCount());
TestCase.assertNull("packageName not properly recycled", event.getPackageName());
- // This will fail and is fixed in Gingerbread Bug: 2593810
- // TestCase.assertNull("parcelableData not properly recycled", event.getParcelableData());
+ TestCase.assertNull("parcelableData not properly recycled", event.getParcelableData());
TestCase.assertEquals("removedCount not properly recycled", 0, event.getRemovedCount());
TestCase.assertTrue("text not properly recycled", event.getText().isEmpty());
}
diff --git a/tests/tests/view/src/android/view/cts/GestureDetector_SimpleOnGestureListenerTest.java b/tests/tests/view/src/android/view/cts/GestureDetector_SimpleOnGestureListenerTest.java
deleted file mode 100644
index b16f894..0000000
--- a/tests/tests/view/src/android/view/cts/GestureDetector_SimpleOnGestureListenerTest.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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 android.view.cts;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.view.MotionEvent;
-import android.view.GestureDetector.SimpleOnGestureListener;
-
-@TestTargetClass(SimpleOnGestureListener.class)
-public class GestureDetector_SimpleOnGestureListenerTest extends
- ActivityInstrumentationTestCase2<GestureDetectorStubActivity> {
-
- private GestureDetectorStubActivity mActivity;
-
- public GestureDetector_SimpleOnGestureListenerTest() {
- super("com.android.cts.stub", GestureDetectorStubActivity.class);
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mActivity = getActivity();
- mActivity.isDown = false;
- mActivity.isScroll = false;
- mActivity.isFling = false;
- mActivity.isSingleTapUp = false;
- mActivity.onShowPress = false;
- mActivity.onLongPress = false;
- mActivity.onDoubleTap = false;
- mActivity.onDoubleTapEvent = false;
- mActivity.onSingleTapConfirmed = false;
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test Constructor ",
- method = "GestureDetector.SimpleOnGestureListener",
- args = {}
- )
- public void testConstructor() {
- new SimpleOnGestureListener();
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onSingleTapUp",
- args = {MotionEvent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onLongPress",
- args = {MotionEvent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDown",
- args = {MotionEvent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onScroll",
- args = {MotionEvent.class, MotionEvent.class, float.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onShowPress",
- args = {MotionEvent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onFling",
- args = {MotionEvent.class, MotionEvent.class, float.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDoubleTap",
- args = {MotionEvent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onDoubleTapEvent",
- args = {MotionEvent.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onSingleTapConfirmed",
- args = {MotionEvent.class}
- )
- })
- public void testSimpleOnGestureListener() {
- GestureDetectorTestUtil.testGestureDetector(this, mActivity);
- }
-
-}
diff --git a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
index 4ab38df..156dc49 100644
--- a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
+++ b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
@@ -16,17 +16,17 @@
package android.view.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
import android.test.AndroidTestCase;
import android.text.TextUtils;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.KeyCharacterMap.KeyData;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
@TestTargetClass(KeyCharacterMap.class)
public class KeyCharacterMapTest extends AndroidTestCase {
@@ -36,7 +36,7 @@
@Override
protected void setUp() throws Exception {
super.setUp();
- mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
}
@TestTargetNew(
@@ -113,6 +113,7 @@
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TAB));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SPACE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SYM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EXPLORER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENVELOPE));
@@ -133,11 +134,131 @@
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HEADSETHOOK));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FOCUS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PLUS));
-
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MENU));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NOTIFICATION));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEARCH));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_STOP));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_NEXT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_REWIND));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MUTE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PAGE_UP));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PAGE_DOWN));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PICTSYMBOLS));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SWITCH_CHARSET));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_A));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_B));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_C));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_X));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_Y));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_Z));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_L1));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_R1));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_L2));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_R2));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_THUMBL));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_THUMBR));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_START));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_SELECT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_MODE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ESCAPE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FORWARD_DEL));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CTRL_LEFT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CTRL_RIGHT));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAPS_LOCK));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SCROLL_LOCK));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_META_LEFT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_META_RIGHT));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FUNCTION));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SYSRQ));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BREAK));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MOVE_HOME));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MOVE_END));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_INSERT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FORWARD));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PLAY));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PAUSE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_CLOSE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_EJECT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_RECORD));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F1));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F2));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F3));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F4));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F5));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F6));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F7));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F8));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F9));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F10));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F11));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F12));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM_LOCK));
+
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_0));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_1));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_2));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_3));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_4));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_5));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_6));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_7));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_8));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_9));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_DIVIDE));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_MULTIPLY));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_SUBTRACT));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_ADD));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_DOT));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_COMMA));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_ENTER));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_EQUALS));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_LEFT_PAREN));
+ assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_RIGHT_PAREN));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_MUTE));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_INFO));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CHANNEL_UP));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CHANNEL_DOWN));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ZOOM_IN));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ZOOM_OUT));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TV));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_WINDOW));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_GUIDE));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DVR));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BOOKMARK));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAPTIONS));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SETTINGS));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TV_POWER));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TV_INPUT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STB_POWER));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STB_INPUT));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AVR_POWER));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AVR_INPUT));
+
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_RED));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_GREEN));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_YELLOW));
+ assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_BLUE));
}
@TestTargetNew(
diff --git a/tests/tests/view/src/android/view/cts/KeyEventTest.java b/tests/tests/view/src/android/view/cts/KeyEventTest.java
index dc1696c..6689ca4 100644
--- a/tests/tests/view/src/android/view/cts/KeyEventTest.java
+++ b/tests/tests/view/src/android/view/cts/KeyEventTest.java
@@ -31,6 +31,8 @@
import android.view.KeyCharacterMap.KeyData;
import android.view.KeyEvent.Callback;
+import junit.framework.Assert;
+
/**
* Test {@link KeyEvent}.
*/
@@ -183,23 +185,16 @@
args = {android.view.KeyCharacterMap.KeyData.class}
)
public void testGetKeyData() {
+ KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_Z);
KeyData keyData = new KeyData();
- char origDisplayLabel = keyData.displayLabel;
- char origNumber = keyData.number;
- char[] origMeta = new char[KeyData.META_LENGTH];
- origMeta[0] = keyData.meta[0];
- origMeta[1] = keyData.meta[1];
- origMeta[2] = keyData.meta[2];
- origMeta[3] = keyData.meta[3];
+ assertTrue(keyEvent.getKeyData(keyData));
- assertTrue(mKeyEvent.getKeyData(keyData));
- // check whether KeyData has been updated.
- assertTrue(keyData.displayLabel != origDisplayLabel);
- assertTrue(keyData.number != origNumber);
- assertTrue(keyData.meta[0] != origMeta[0]);
- assertTrue(keyData.meta[1] != origMeta[1]);
- assertTrue(keyData.meta[2] != origMeta[2]);
- assertTrue(keyData.meta[3] != origMeta[3]);
+ assertEquals('Z', keyData.displayLabel);
+ assertEquals(0, keyData.number);
+ assertEquals('z', keyData.meta[0]);
+ assertEquals('Z', keyData.meta[1]);
+ assertEquals(0, keyData.meta[2]);
+ assertEquals(0, keyData.meta[3]);
}
@TestTargetNew(
@@ -295,6 +290,7 @@
public void testGetUnicodeChar1() {
// 48 is Unicode character of '0'
assertEquals(48, mKeyEvent.getUnicodeChar());
+
mKeyEvent = new KeyEvent(mDownTime, mEventTime, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_9, 5, 0);
// 57 is Unicode character of '9'
@@ -317,6 +313,7 @@
assertEquals(48, mKeyEvent.getUnicodeChar(MetaKeyKeyListener.META_CAP_LOCKED));
mKeyEvent = new KeyEvent(mDownTime, mEventTime, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_9, 5, 0);
+
// 57 is Unicode character of '9'
assertEquals(57, mKeyEvent.getUnicodeChar(0));
@@ -397,21 +394,205 @@
assertFalse(mKeyEvent.isAltPressed());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test {@link KeyEvent#isModifierKey(int)}",
- method = "isModifierKey",
- args = {int.class}
- )
+ public void testGetModifierMetaStateMask() {
+ int mask = KeyEvent.getModifierMetaStateMask();
+ assertTrue((mask & KeyEvent.META_SHIFT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_SHIFT_LEFT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_SHIFT_RIGHT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_ALT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_ALT_LEFT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_ALT_RIGHT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_CTRL_ON) != 0);
+ assertTrue((mask & KeyEvent.META_CTRL_LEFT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_CTRL_RIGHT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_META_ON) != 0);
+ assertTrue((mask & KeyEvent.META_META_LEFT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_META_RIGHT_ON) != 0);
+ assertTrue((mask & KeyEvent.META_SYM_ON) != 0);
+ assertTrue((mask & KeyEvent.META_FUNCTION_ON) != 0);
+
+ assertFalse((mask & KeyEvent.META_CAPS_LOCK_ON) != 0);
+ assertFalse((mask & KeyEvent.META_NUM_LOCK_ON) != 0);
+ assertFalse((mask & KeyEvent.META_SCROLL_LOCK_ON) != 0);
+ }
+
public void testIsModifierKey() {
assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_SHIFT_LEFT));
assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_ALT_LEFT));
assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_ALT_RIGHT));
+ assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_CTRL_LEFT));
+ assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_CTRL_RIGHT));
+ assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_META_LEFT));
+ assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_META_RIGHT));
assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_SYM));
+ assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_NUM));
+ assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_FUNCTION));
+
assertFalse(KeyEvent.isModifierKey(KeyEvent.KEYCODE_0));
}
+ private static final int UNDEFINED_META_STATE = 0x80000000;
+
+ public void testNormalizeMetaState() {
+ // Already normalized values.
+ assertEquals(0, KeyEvent.normalizeMetaState(0));
+ assertEquals(KeyEvent.getModifierMetaStateMask(),
+ KeyEvent.normalizeMetaState(KeyEvent.getModifierMetaStateMask()));
+
+ // Values that require normalization.
+ assertEquals(KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_SHIFT_LEFT_ON));
+ assertEquals(KeyEvent.META_SHIFT_RIGHT_ON | KeyEvent.META_SHIFT_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_SHIFT_RIGHT_ON));
+ assertEquals(KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_ALT_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_ALT_LEFT_ON));
+ assertEquals(KeyEvent.META_ALT_RIGHT_ON | KeyEvent.META_ALT_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_ALT_RIGHT_ON));
+ assertEquals(KeyEvent.META_CTRL_LEFT_ON | KeyEvent.META_CTRL_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_CTRL_LEFT_ON));
+ assertEquals(KeyEvent.META_CTRL_RIGHT_ON | KeyEvent.META_CTRL_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_CTRL_RIGHT_ON));
+ assertEquals(KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_META_LEFT_ON));
+ assertEquals(KeyEvent.META_META_RIGHT_ON | KeyEvent.META_META_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_META_RIGHT_ON));
+ assertEquals(KeyEvent.META_CAPS_LOCK_ON,
+ KeyEvent.normalizeMetaState(MetaKeyKeyListener.META_CAP_LOCKED));
+ assertEquals(KeyEvent.META_ALT_ON,
+ KeyEvent.normalizeMetaState(MetaKeyKeyListener.META_ALT_LOCKED));
+ assertEquals(KeyEvent.META_SYM_ON,
+ KeyEvent.normalizeMetaState(MetaKeyKeyListener.META_SYM_LOCKED));
+ assertEquals(KeyEvent.META_SHIFT_ON,
+ KeyEvent.normalizeMetaState(KeyEvent.META_SHIFT_ON | UNDEFINED_META_STATE));
+ }
+
+ public void testMetaStateHasNoModifiers() {
+ assertTrue(KeyEvent.metaStateHasNoModifiers(0));
+ assertTrue(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CAPS_LOCK_ON));
+ assertTrue(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_NUM_LOCK_ON));
+ assertTrue(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SCROLL_LOCK_ON));
+
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SHIFT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SHIFT_LEFT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SHIFT_RIGHT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_ALT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_ALT_LEFT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_ALT_RIGHT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CTRL_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CTRL_LEFT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CTRL_RIGHT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_META_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_META_LEFT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_META_RIGHT_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SYM_ON));
+ assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_FUNCTION_ON));
+ }
+
+ public void testMetaStateHasModifiers() {
+ assertTrue(KeyEvent.metaStateHasModifiers(0, 0));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_NUM_LOCK_ON | KeyEvent.META_CAPS_LOCK_ON
+ | KeyEvent.META_SCROLL_LOCK_ON, 0));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_LEFT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_RIGHT_ON,
+ KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_RIGHT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_LEFT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_NUM_LOCK_ON | KeyEvent.META_CAPS_LOCK_ON
+ | KeyEvent.META_SCROLL_LOCK_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_LEFT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_ALT_ON | KeyEvent.META_ALT_RIGHT_ON,
+ KeyEvent.META_ALT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_CTRL_RIGHT_ON | KeyEvent.META_META_LEFT_ON,
+ KeyEvent.META_CTRL_RIGHT_ON | KeyEvent.META_META_ON));
+ assertTrue(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_SYM_ON | KeyEvent.META_FUNCTION_ON | KeyEvent.META_CAPS_LOCK_ON,
+ KeyEvent.META_SYM_ON | KeyEvent.META_FUNCTION_ON));
+
+ assertFalse(KeyEvent.metaStateHasModifiers(0, KeyEvent.META_SHIFT_ON));
+ assertFalse(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_ON));
+ assertFalse(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_ON));
+ assertFalse(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_ALT_LEFT_ON,
+ KeyEvent.META_ALT_RIGHT_ON));
+ assertFalse(KeyEvent.metaStateHasModifiers(
+ KeyEvent.META_ALT_LEFT_ON,
+ KeyEvent.META_CTRL_LEFT_ON));
+
+ final int[] invalidModifiers = new int[] {
+ KeyEvent.META_CAPS_LOCK_ON,
+ KeyEvent.META_NUM_LOCK_ON,
+ KeyEvent.META_SCROLL_LOCK_ON,
+ MetaKeyKeyListener.META_CAP_LOCKED,
+ MetaKeyKeyListener.META_ALT_LOCKED,
+ MetaKeyKeyListener.META_SYM_LOCKED,
+ KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_RIGHT_ON,
+ KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON| KeyEvent.META_SHIFT_RIGHT_ON,
+ KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON,
+ KeyEvent.META_ALT_ON | KeyEvent.META_ALT_RIGHT_ON,
+ KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON| KeyEvent.META_ALT_RIGHT_ON,
+ KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON,
+ KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_RIGHT_ON,
+ KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON| KeyEvent.META_CTRL_RIGHT_ON,
+ KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON,
+ KeyEvent.META_META_ON | KeyEvent.META_META_RIGHT_ON,
+ KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON| KeyEvent.META_META_RIGHT_ON,
+ };
+ for (int modifiers : invalidModifiers) {
+ try {
+ KeyEvent.metaStateHasModifiers(0, modifiers);
+ Assert.fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException ex) {
+ }
+ }
+
+ assertFalse(KeyEvent.metaStateHasModifiers(0, UNDEFINED_META_STATE));
+ }
+
+ public void testHasNoModifiers() {
+ KeyEvent ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON);
+ assertTrue(ev.hasNoModifiers());
+
+ ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON | KeyEvent.META_SHIFT_ON);
+ assertFalse(ev.hasNoModifiers());
+ }
+
+ public void testHasModifiers() {
+ KeyEvent ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON);
+ assertTrue(ev.hasModifiers(0));
+
+ ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON | KeyEvent.META_SHIFT_ON);
+ assertTrue(ev.hasModifiers(KeyEvent.META_SHIFT_ON));
+
+ ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_A, 0,
+ KeyEvent.META_CAPS_LOCK_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_RIGHT_ON);
+ assertFalse(ev.hasModifiers(KeyEvent.META_SHIFT_LEFT_ON));
+ }
+
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "Test {@link KeyEvent#getDisplayLabel()}",
@@ -509,8 +690,6 @@
method = "getMatch",
args = {char[].class}
)
- @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete, " +
- "should add NPE description in javadoc.")
public void testGetMatch1() {
char[] codes1 = new char[] { '0', '1', '2' };
assertEquals('0', mKeyEvent.getMatch(codes1));
@@ -521,13 +700,6 @@
char[] codes3 = { '2', 'S' };
mKeyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_S);
assertEquals('S', mKeyEvent.getMatch(codes3));
-
- try {
- mKeyEvent.getMatch(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // empty
- }
}
@TestTargetNew(
@@ -742,7 +914,7 @@
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
return false;
}
-
+
public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
mIsMultiple = true;
mKeyCode = keyCode;
diff --git a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
index 6f637fc..f5bd8f4 100644
--- a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
+++ b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
@@ -16,6 +16,14 @@
package android.view.cts;
+import com.android.cts.stub.R;
+import com.android.internal.util.XmlUtils;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
import org.xmlpull.v1.XmlPullParser;
import android.app.cts.MockActivity;
@@ -23,6 +31,7 @@
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
+import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
@@ -35,21 +44,13 @@
import android.view.LayoutInflater.Factory;
import android.view.LayoutInflater.Filter;
import android.widget.LinearLayout;
-import com.android.cts.stub.R;
-
-import com.android.internal.util.XmlUtils;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
@TestTargetClass(LayoutInflater.class)
public class LayoutInflaterTest extends AndroidTestCase {
private LayoutInflater mLayoutInflater;
private Context mContext;
- private Factory mFactory = new Factory() {
+ private final Factory mFactory = new Factory() {
public View onCreateView(String name, Context context,
AttributeSet attrs) {
@@ -57,7 +58,7 @@
}
};
private boolean isOnLoadClass;
- private Filter mFilter = new Filter() {
+ private final Filter mFilter = new Filter() {
@SuppressWarnings("unchecked")
public boolean onLoadClass(Class clazz) {
@@ -172,7 +173,7 @@
}
String nodeName = parser.getName();
if (!"alias".equals(nodeName)) {
- throw new RuntimeException();
+ throw new InflateException();
}
int outerDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
@@ -296,8 +297,7 @@
try {
view = mLayoutInflater.inflate(-1, null);
fail("should throw exception");
- } catch (RuntimeException e) {
-
+ } catch (Resources.NotFoundException e) {
}
LinearLayout mLayout;
mLayout = new LinearLayout(mContext);
@@ -335,7 +335,7 @@
try {
view = mLayoutInflater.inflate(-1, null, false);
fail("should throw exception");
- } catch (RuntimeException e) {
+ } catch (Resources.NotFoundException e) {
}
LinearLayout mLayout;
@@ -381,7 +381,7 @@
try {
view = mLayoutInflater.inflate(null, null);
fail("should throw exception");
- } catch (RuntimeException e) {
+ } catch (NullPointerException e) {
}
LinearLayout mLayout;
mLayout = new LinearLayout(mContext);
@@ -395,7 +395,7 @@
try {
view = mLayoutInflater.inflate(parser, mLayout);
fail("should throw exception");
- } catch (RuntimeException e) {
+ } catch (NullPointerException e) {
}
parser = getContext().getResources().getLayout(
R.layout.inflater_layout);
@@ -440,7 +440,7 @@
try {
view = mLayoutInflater.inflate(null, null, false);
fail("should throw exception");
- } catch (RuntimeException e) {
+ } catch (NullPointerException e) {
}
LinearLayout mLayout;
mLayout = new LinearLayout(mContext);
@@ -454,7 +454,7 @@
try {
view = mLayoutInflater.inflate(parser, mLayout, false);
fail("should throw exception");
- } catch (RuntimeException e) {
+ } catch (NullPointerException e) {
}
parser = getContext().getResources().getLayout(
R.layout.inflater_layout);
@@ -475,7 +475,7 @@
try {
view = mLayoutInflater.inflate(parser, mLayout, false);
fail("should throw exception");
- } catch (RuntimeException e) {
+ } catch (InflateException e) {
}
parser = null;
@@ -497,6 +497,7 @@
super(original, newContext);
}
+ @Override
public View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return super.onCreateView(name, attrs);
diff --git a/tests/tests/view/src/android/view/cts/MotionEventTest.java b/tests/tests/view/src/android/view/cts/MotionEventTest.java
index e4df594..f8a14e6 100644
--- a/tests/tests/view/src/android/view/cts/MotionEventTest.java
+++ b/tests/tests/view/src/android/view/cts/MotionEventTest.java
@@ -22,12 +22,15 @@
import dalvik.annotation.TestTargets;
import dalvik.annotation.ToBeFixed;
+import android.graphics.Matrix;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.test.AndroidTestCase;
+import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
+import android.view.MotionEvent.PointerCoords;
/**
* Test {@link MotionEvent}.
@@ -497,4 +500,103 @@
mMotionEvent2 = null; // since it was recycled, don't try to recycle again in tear down
}
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "transform",
+ args = {}
+ )
+ public void testTransformShouldThrowWhenMatrixIsNull() {
+ try {
+ mMotionEvent1.transform(null);
+ fail("transform() should throw an exception when matrix is null.");
+ } catch (IllegalArgumentException ex) {
+ }
+ }
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "transform",
+ args = {}
+ )
+ public void testTransformShouldApplyMatrixToPointsAndPreserveRawPosition() {
+ // Generate some points on a circle.
+ // Each point 'i' is a point on a circle of radius ROTATION centered at (3,2) at an angle
+ // of ARC * i degrees clockwise relative to the Y axis.
+ // The geometrical representation is irrelevant to the test, it's just easy to generate
+ // and check rotation. We set the orientation to the same angle.
+ // Coordinate system: down is increasing Y, right is increasing X.
+ final float PI_180 = (float) (Math.PI / 180);
+ final float RADIUS = 10;
+ final float ARC = 36;
+ final float ROTATION = ARC * 2;
+
+ final int pointerCount = 11;
+ final int[] pointerIds = new int[pointerCount];
+ final PointerCoords[] pointerCoords = new PointerCoords[pointerCount];
+ for (int i = 0; i < pointerCount; i++) {
+ final PointerCoords c = new PointerCoords();
+ final float angle = (float) (i * ARC * PI_180);
+ pointerIds[i] = i;
+ pointerCoords[i] = c;
+ c.x = (float) (Math.sin(angle) * RADIUS + 3);
+ c.y = (float) (- Math.cos(angle) * RADIUS + 2);
+ c.orientation = angle;
+ }
+ final MotionEvent event = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE,
+ pointerCount, pointerIds, pointerCoords, 0, 0, 0, 0, 0, 0, 0);
+ final float originalRawX = 0 + 3;
+ final float originalRawY = - RADIUS + 2;
+ dump("Original points.", event);
+
+ // Check original raw X and Y assumption.
+ assertEquals(originalRawX, event.getRawX(), 0.001);
+ assertEquals(originalRawY, event.getRawY(), 0.001);
+
+ // Now translate the motion event so the circle's origin is at (0,0).
+ event.offsetLocation(-3, -2);
+ dump("Translated points.", event);
+
+ // Offsetting the location should preserve the raw X and Y of the first point.
+ assertEquals(originalRawX, event.getRawX(), 0.001);
+ assertEquals(originalRawY, event.getRawY(), 0.001);
+
+ // Apply a rotation about the origin by ROTATION degrees clockwise.
+ Matrix matrix = new Matrix();
+ matrix.setRotate(ROTATION);
+ event.transform(matrix);
+ dump("Rotated points.", event);
+
+ // Check the points.
+ for (int i = 0; i < pointerCount; i++) {
+ final PointerCoords c = pointerCoords[i];
+ event.getPointerCoords(i, c);
+
+ final float angle = (float) ((i * ARC + ROTATION) * PI_180);
+ assertEquals(Math.sin(angle) * RADIUS, c.x, 0.001);
+ assertEquals(- Math.cos(angle) * RADIUS, c.y, 0.001);
+ assertEquals(Math.tan(angle), Math.tan(c.orientation), 0.1);
+ }
+
+ // Applying the transformation should preserve the raw X and Y of the first point.
+ assertEquals(originalRawX, event.getRawX(), 0.001);
+ assertEquals(originalRawY, event.getRawY(), 0.001);
+ }
+
+ private void dump(String label, MotionEvent ev) {
+ if (false) {
+ StringBuilder msg = new StringBuilder();
+ msg.append(label).append("\n");
+
+ msg.append(" Raw: (").append(ev.getRawX()).append(",").append(ev.getRawY()).append(")\n");
+ int pointerCount = ev.getPointerCount();
+ for (int i = 0; i < pointerCount; i++) {
+ msg.append(" Pointer[").append(i).append("]: (")
+ .append(ev.getX(i)).append(",").append(ev.getY(i)).append("), orientation=")
+ .append(ev.getOrientation(i) * 180 / Math.PI).append(" deg\n");
+ }
+
+ android.util.Log.i("TEST", msg.toString());
+ }
+ }
}
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupTest.java b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
index ebcee54..2498700 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
@@ -16,7 +16,13 @@
package android.view.cts;
-import java.util.ArrayList;
+import com.android.internal.util.XmlUtils;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
import android.app.cts.CTSResult;
import android.content.Context;
@@ -55,13 +61,7 @@
import android.widget.TextView;
import android.widget.cts.ViewGroupStubActivity;
-import com.android.internal.util.XmlUtils;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
+import java.util.ArrayList;
@TestTargetClass(ViewGroup.class)
public class ViewGroupTest extends InstrumentationTestCase implements CTSResult{
@@ -1557,20 +1557,6 @@
assertTrue(vg.isOnRequestFocusInDescendantsCalled);
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "recomputeViewAttributes",
- args = {android.view.View.class}
- )
- public void testRecomputeViewAttributes() {
- MockViewGroup father = new MockViewGroup(mContext);
- MockViewGroup son = new MockViewGroup(mContext);
- father.addView(son);
-
- son.recomputeViewAttributes(null);
- assertTrue(father.isRecomputeViewAttributesCalled);
- }
-
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -1948,6 +1934,7 @@
public int mBottom;
public MockCanvas() {
+ super(Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888));
}
public MockCanvas(Bitmap bitmap) {
diff --git a/tests/tests/view/src/android/view/cts/ViewTest.java b/tests/tests/view/src/android/view/cts/ViewTest.java
index 87b3eae..6b5c0a1 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -46,6 +46,7 @@
import android.util.Log;
import android.util.SparseArray;
import android.util.Xml;
+import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.Display;
import android.view.HapticFeedbackConstants;
@@ -2028,10 +2029,6 @@
view.setMeasuredDimensionWrapper(20, 30);
assertEquals(20, view.getMeasuredWidth());
assertEquals(30, view.getMeasuredHeight());
-
- view.setMeasuredDimensionWrapper(-20, -30);
- assertEquals(-20, view.getMeasuredWidth());
- assertEquals(-30, view.getMeasuredHeight());
}
@TestTargets({
@@ -2686,8 +2683,11 @@
runTestOnUiThread(new Runnable() {
public void run() {
view.setFocusable(true);
+ view.requestFocus();
}
});
+ getInstrumentation().waitForIdleSync();
+ assertTrue(view.isFocused());
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
getInstrumentation().sendKeySync(event);
@@ -3087,8 +3087,11 @@
runTestOnUiThread(new Runnable() {
public void run() {
view.setFocusable(true);
+ view.requestFocus();
}
});
+ getInstrumentation().waitForIdleSync();
+ assertTrue(view.isFocused());
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_0);
getInstrumentation().sendKeySync(event);
@@ -4020,8 +4023,6 @@
args = {}
)
})
- @ToBeFixed(bug = "", explanation = "when scrollbar is with INSET style, the bottom padding" +
- "should be increased.")
@UiThreadTest
public void testScrollbarStyle() {
MockView view = (MockView) mActivity.findViewById(R.id.mock_view);
@@ -4046,8 +4047,7 @@
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
assertEquals(View.SCROLLBARS_INSIDE_INSET, view.getScrollBarStyle());
assertEquals(verticalScrollBarWidth, view.getPaddingRight());
- // issue, mockView.getPaddingBottom() is expected to equal horizontalScrollBarHeight.
- assertEquals(0, view.getPaddingBottom());
+ assertEquals(horizontalScrollBarHeight, view.getPaddingBottom());
view.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
assertEquals(View.SCROLLBARS_OUTSIDE_OVERLAY, view.getScrollBarStyle());
@@ -4057,8 +4057,7 @@
view.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
assertEquals(View.SCROLLBARS_OUTSIDE_INSET, view.getScrollBarStyle());
assertEquals(verticalScrollBarWidth, view.getPaddingRight());
- // issue, mockView.getPaddingBottom() is expected to equal horizontalScrollBarHeight.
- assertEquals(0, view.getPaddingBottom());
+ assertEquals(horizontalScrollBarHeight, view.getPaddingBottom());
// TODO: how to get the position of the Scrollbar to assert it is inside or outside.
}
@@ -4155,30 +4154,25 @@
@UiThreadTest
public void testScrolling() {
MockView view = (MockView) mActivity.findViewById(R.id.mock_view);
-
view.reset();
assertEquals(0, view.getScrollX());
assertEquals(0, view.getScrollY());
assertFalse(view.hasCalledOnScrollChanged());
- assertFalse(view.hasCalledInvalidate());
view.scrollTo(0, 0);
assertEquals(0, view.getScrollX());
assertEquals(0, view.getScrollY());
assertFalse(view.hasCalledOnScrollChanged());
- assertFalse(view.hasCalledInvalidate());
view.scrollBy(0, 0);
assertEquals(0, view.getScrollX());
assertEquals(0, view.getScrollY());
assertFalse(view.hasCalledOnScrollChanged());
- assertFalse(view.hasCalledInvalidate());
view.scrollTo(10, 100);
assertEquals(10, view.getScrollX());
assertEquals(100, view.getScrollY());
assertTrue(view.hasCalledOnScrollChanged());
- assertTrue(view.hasCalledInvalidate());
view.reset();
assertFalse(view.hasCalledOnScrollChanged());
@@ -4186,7 +4180,6 @@
assertEquals(0, view.getScrollX());
assertEquals(0, view.getScrollY());
assertTrue(view.hasCalledOnScrollChanged());
- assertTrue(view.hasCalledInvalidate());
view.reset();
assertFalse(view.hasCalledOnScrollChanged());
@@ -4194,7 +4187,6 @@
assertEquals(-1, view.getScrollX());
assertEquals(-2, view.getScrollY());
assertTrue(view.hasCalledOnScrollChanged());
- assertTrue(view.hasCalledInvalidate());
}
@TestTargets({
@@ -4624,6 +4616,11 @@
return false;
}
+ public ActionMode startActionModeForChild(View originalView,
+ ActionMode.Callback callback) {
+ return null;
+ }
+
public boolean hasShowContextMenuForChild() {
return mHasShowContextMenuForChild;
}
diff --git a/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java b/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
index 2ea05c4..7bdcfd2 100644
--- a/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
+++ b/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
@@ -344,6 +344,8 @@
* setDuplicateParentStateEnabled
*/
TextView v = new TextView(mActivity);
+ v.setSingleLine(); // otherwise the multiline state interferes with theses tests
+ v.setEnabled(false);
v.setText("Test setDuplicateParentStateEnabled");
v.setDuplicateParentStateEnabled(false);
@@ -482,13 +484,14 @@
mSymbolTextView.setText(ARGENTINA_SYMBOL);
mWarningTextView.setVisibility(View.VISIBLE);
+ assertTrue(mEditText.requestFocus());
assertTrue(mEditText.hasFocus());
assertFalse(mButtonOk.hasFocus());
assertFalse(mButtonCancel.hasFocus());
assertFalse(mSymbolTextView.hasFocus());
assertFalse(mWarningTextView.hasFocus());
- assertFalse(editListener.hasFocus());
+ assertTrue(editListener.hasFocus());
assertFalse(okListener.hasFocus());
assertFalse(cancelListener.hasFocus());
assertFalse(symbolListener.hasFocus());
diff --git a/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java b/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java
index 00b18c1..e2775d0 100644
--- a/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java
+++ b/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java
@@ -16,6 +16,11 @@
package android.view.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.IBinder;
@@ -24,10 +29,6 @@
import android.text.SpannedString;
import android.view.Gravity;
import android.view.WindowManager;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
@TestTargetClass(WindowManager.LayoutParams.class)
public class WindowManager_LayoutParamsTest extends AndroidTestCase {
@@ -167,18 +168,15 @@
params.setTitle(PARAMS_TITLE);
params.alpha = ALPHA - 0.5f;
params.windowAnimations = WINDOW_ANIMATIONS;
- params.memoryType = WindowManager.LayoutParams.MEMORY_TYPE_HARDWARE;
params.dimAmount = DIM_AMOUNT - 1.0f;
mLayoutParams = new WindowManager.LayoutParams();
assertEquals(WindowManager.LayoutParams.TITLE_CHANGED
| WindowManager.LayoutParams.ALPHA_CHANGED
- | WindowManager.LayoutParams.MEMORY_TYPE_CHANGED
| WindowManager.LayoutParams.ANIMATION_CHANGED
| WindowManager.LayoutParams.DIM_AMOUNT_CHANGED,
mLayoutParams.copyFrom(params));
assertEquals(params.getTitle(), mLayoutParams.getTitle());
assertEquals(params.alpha, mLayoutParams.alpha);
- assertEquals(params.memoryType, mLayoutParams.memoryType);
assertEquals(params.dimAmount, mLayoutParams.dimAmount);
params = new WindowManager.LayoutParams();
diff --git a/tests/tests/view/src/android/view/cts/WindowTest.java b/tests/tests/view/src/android/view/cts/WindowTest.java
index 88edecf..4b9e282 100755
--- a/tests/tests/view/src/android/view/cts/WindowTest.java
+++ b/tests/tests/view/src/android/view/cts/WindowTest.java
@@ -37,10 +37,9 @@
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
import android.util.DisplayMetrics;
-import android.view.accessibility.AccessibilityEvent;
+import android.view.ActionMode;
import android.view.Gravity;
import android.view.InputQueue;
-import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
@@ -51,6 +50,7 @@
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
+import android.view.accessibility.AccessibilityEvent;
import android.widget.TextView;
@TestTargetClass(Window.class)
@@ -313,69 +313,6 @@
public void testCloseAllPanels() throws Throwable {
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "closePanel",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "openPanel",
- args = {int.class, android.view.KeyEvent.class}
- )
- })
- public void testOpPanel() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
- assertTrue(mActivity.isOnCreateOptionsMenuCalled());
- mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
- assertTrue(mActivity.isOnOptionsMenuClosedCalled());
- }
- });
- mInstrumentation.waitForIdleSync();
- }
-
- /**
- * togglePanel: When the panel is closing, open it; when open, close it.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "togglePanel",
- args = {int.class, android.view.KeyEvent.class}
- )
- public void testTogglePanelClose() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
- assertTrue(mActivity.isOnCreateOptionsMenuCalled());
- // close panel
- mWindow.togglePanel(Window.FEATURE_OPTIONS_PANEL, null);
- assertTrue(mActivity.isOnOptionsMenuClosedCalled());
- }
- });
- mInstrumentation.waitForIdleSync();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "togglePanel",
- args = {int.class, android.view.KeyEvent.class}
- )
- public void testTogglePanelOpen() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- // open panel
- mWindow.togglePanel(Window.FEATURE_OPTIONS_PANEL, null);
- assertTrue(mActivity.isOnCreateOptionsMenuCalled());
- mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
- assertTrue(mActivity.isOnOptionsMenuClosedCalled());
- }
- });
- mInstrumentation.waitForIdleSync();
- }
-
/**
* getCurrentFocus: Return the view in this Window that currently has focus, or null if
* there are none.
@@ -444,7 +381,7 @@
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
assertEquals(screenWidth, decor.getWidth());
- assertEquals(screenHeight, decor.getHeight());
+ assertTrue(screenHeight > decor.getHeight());
assertSame(mWindow.getContext(), decor.getContext());
}
@@ -564,38 +501,6 @@
assertFalse(mWindow.isFloating());
}
- /**
- * isShortcutKey: check if a key is the shortcut key for this window
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "We set 'q' & 'a' key as shortcut key in WindowStubActivity.java,"
- + " other keys are not shortcut key",
- method = "isShortcutKey",
- args = {int.class, android.view.KeyEvent.class}
- )
- public void testIsShortcutKey() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mActivity.openOptionsMenu();
- }
- });
- mInstrumentation.waitForIdleSync();
- KeyCharacterMap keymap
- = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
- if (keymap.getKeyboardType() == KeyCharacterMap.NUMERIC) {
- assertTrue(mWindow.isShortcutKey(KeyEvent.KEYCODE_1, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_1)));
- assertFalse(mWindow.isShortcutKey(KeyEvent.KEYCODE_5, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_5)));
- } else {
- assertTrue(mWindow.isShortcutKey(KeyEvent.KEYCODE_Q, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_Q)));
- assertFalse(mWindow.isShortcutKey(KeyEvent.KEYCODE_F, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_F)));
- }
- }
-
@TestTargets({
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
@@ -1158,6 +1063,9 @@
public void togglePanel(int featureId, KeyEvent event) {
}
+ public void invalidatePanelMenu(int featureId) {
+ }
+
public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) {
return true;
}
@@ -1202,6 +1110,10 @@
return true;
}
+ public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
+ return false;
+ }
+
public boolean superDispatchTouchEvent(MotionEvent event) {
return true;
}
@@ -1210,10 +1122,17 @@
return true;
}
+ public boolean superDispatchGenericMotionEvent(MotionEvent event) {
+ return true;
+ }
+
public View getDecorView() {
return null;
}
+ public void alwaysReadCloseOnTouchAttr() {
+ }
+
public View peekDecorView() {
return null;
}
@@ -1255,11 +1174,11 @@
public void setDefaultWindowFormat(int format) {
super.setDefaultWindowFormat(format);
}
-
+
@Override
public void takeSurface(SurfaceHolder.Callback2 callback) {
}
-
+
@Override
public void takeInputQueue(InputQueue.Callback callback) {
}
@@ -1273,6 +1192,10 @@
return true;
}
+ public boolean dispatchKeyShortcutEvent(KeyEvent event) {
+ return false;
+ }
+
public boolean dispatchTouchEvent(MotionEvent event) {
return true;
}
@@ -1280,7 +1203,11 @@
public boolean dispatchTrackballEvent(MotionEvent event) {
return true;
}
-
+
+ public boolean dispatchGenericMotionEvent(MotionEvent event) {
+ return true;
+ }
+
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return true;
}
@@ -1336,5 +1263,15 @@
public boolean onSearchRequested() {
return false;
}
+
+ public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
+ return null;
+ }
+
+ public void onActionModeStarted(ActionMode mode) {
+ }
+
+ public void onActionModeFinished(ActionMode mode) {
+ }
}
}
diff --git a/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java b/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java
index 1ec2003..830e91f 100755
--- a/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java
+++ b/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java
@@ -225,7 +225,7 @@
args = {int.class, int.class}
)
})
- public void testOpTextMethods() {
+ public void testOpTextMethods() throws Throwable {
// return is an default Editable instance with empty source
final Editable text = mConnection.getEditable();
assertNotNull(text);
@@ -250,6 +250,13 @@
assertEquals(expected.toString(), mConnection.getTextAfterCursor(offLength,
BaseInputConnection.GET_TEXT_WITH_STYLES).toString());
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ assertTrue(mView.requestFocus());
+ assertTrue(mView.isFocused());
+ }
+ });
+
// dummy mode
BaseInputConnection dummyConnection = new BaseInputConnection(mView, false);
dummyConnection.commitText(inputText, inputText.length());
@@ -292,7 +299,7 @@
args = {CharSequence.class, int.class}
)
})
- public void testFinishComposingText() {
+ public void testFinishComposingText() throws Throwable {
CharSequence str = "TestFinish";
Editable inputText = Editable.Factory.getInstance().newEditable(str);
mConnection.commitText(inputText, inputText.length());
@@ -304,6 +311,14 @@
mConnection.finishComposingText();
assertTrue(BaseInputConnection.getComposingSpanStart(text) == -1);
assertTrue(BaseInputConnection.getComposingSpanEnd(text) == -1);
+
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ assertTrue(mView.requestFocus());
+ assertTrue(mView.isFocused());
+ }
+ });
+
// dummy mode
BaseInputConnection dummyConnection = new BaseInputConnection(mView, false);
dummyConnection.setComposingText(str, str.length());
@@ -325,10 +340,16 @@
method = "sendKeyEvent",
args = {KeyEvent.class}
)
- public void testSendKeyEvent() {
+ public void testSendKeyEvent() throws Throwable {
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ assertTrue(mView.requestFocus());
+ assertTrue(mView.isFocused());
+ }
+ });
+
// 12-key support
- KeyCharacterMap keymap
- = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
if (keymap.getKeyboardType() == KeyCharacterMap.NUMERIC) {
// 'Q' in case of 12-key(NUMERIC) keyboard
mConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_7));
diff --git a/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java b/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java
index bdee05a..10abe4a 100644
--- a/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java
+++ b/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java
@@ -26,6 +26,7 @@
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.CompletionInfo;
+import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
@@ -164,6 +165,8 @@
assertTrue(inputConnection.isClearMetaKeyStatesCalled);
wrapper.commitCompletion(new CompletionInfo(1, 1, "testText"));
assertTrue(inputConnection.isCommitCompletionCalled);
+ wrapper.commitCorrection(new CorrectionInfo(0, "oldText", "newText"));
+ assertTrue(inputConnection.isCommitCorrectionCalled);
wrapper.commitText("Text", 1);
assertTrue(inputConnection.isCommitTextCalled);
wrapper.deleteSurroundingText(10, 100);
@@ -204,6 +207,7 @@
public boolean isBeginBatchEditCalled;
public boolean isClearMetaKeyStatesCalled;
public boolean isCommitCompletionCalled;
+ public boolean isCommitCorrectionCalled;
public boolean isCommitTextCalled;
public boolean isDeleteSurroundingTextCalled;
public boolean isEndBatchEditCalled;
@@ -237,6 +241,11 @@
return false;
}
+ public boolean commitCorrection(CorrectionInfo info) {
+ isCommitCorrectionCalled = true;
+ return false;
+ }
+
public boolean commitText(CharSequence text, int newCursorPosition) {
isCommitTextCalled = true;
return false;
diff --git a/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java b/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java
index 5b7940f..92ef3fe 100755
--- a/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java
+++ b/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java
@@ -150,6 +150,8 @@
public void testInputMethodManager() {
Window window = mActivity.getWindow();
EditText view = (EditText) window.findViewById(R.id.entry);
+ assertTrue(view.requestFocus());
+ assertTrue(view.isFocused());
BaseInputConnection connection = new BaseInputConnection(view, false);
Context context = mInstrumentation.getTargetContext();
diff --git a/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java
index 5a62c9b..bebb1fa 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java
@@ -134,10 +134,8 @@
args = {}
)
public void testCacheDisabled() {
+ // The cache should always be enabled.
assertFalse(CacheManager.cacheDisabled());
-
- // Because setCacheDisabled is package private, we can not call it.
- // cacheDisabled() always return false. How to let it return true?
}
private void loadUrl(String url){
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
index ca1b76f..712d641 100755
--- a/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
@@ -107,6 +107,7 @@
)
})
public void testAcceptCookie() throws Exception {
+ mCookieManager.removeAllCookie();
mCookieManager.setAcceptCookie(false);
assertFalse(mCookieManager.acceptCookie());
assertFalse(mCookieManager.hasCookies());
@@ -286,4 +287,14 @@
}
}.run();
}
+
+ public void testb3167208() throws Exception {
+ String uri = "http://host.android.com/path/";
+ // note the space after the domain=
+ String problemCookie = "foo=bar; domain= .android.com; path=/";
+ mCookieManager.setCookie(uri, problemCookie);
+ String cookie = mCookieManager.getCookie(uri);
+ assertNotNull(cookie);
+ assertTrue(cookie.contains("foo=bar"));
+ }
}
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
index 2f4c35a..3b7d340 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
@@ -62,21 +62,28 @@
assertSame(csm1, csm2);
final CookieManager cookieManager = CookieManager.getInstance();
- assertFalse(cookieManager.hasCookies());
+ cookieManager.setAcceptFileSchemeCookies(true);
+
+ // Remove all cookies from the database.
+ cookieManager.removeAllCookie();
+ new DelayedCheck(30000) {
+ @Override
+ protected boolean check() {
+ return !cookieManager.hasCookies();
+ }
+ }.run();
cookieManager.setAcceptCookie(true);
assertTrue(cookieManager.acceptCookie());
- String cookieValue = "a = b";
- cookieManager.setCookie(TestHtmlConstants.HELLO_WORLD_URL, cookieValue);
- assertEquals(cookieValue, cookieManager.getCookie(TestHtmlConstants.HELLO_WORLD_URL));
-
- // Cookie is stored in RAM but not in the database.
- assertFalse(cookieManager.hasCookies());
+ String url = TestHtmlConstants.getFileUrl(TestHtmlConstants.HELLO_WORLD_URL);
+ String cookieValue = "a=b";
+ cookieManager.setCookie(url, cookieValue);
+ assertEquals(cookieValue, cookieManager.getCookie(url));
// Store the cookie to the database.
csm1.sync();
- new DelayedCheck(10000) {
+ new DelayedCheck(30000) {
@Override
protected boolean check() {
return cookieManager.hasCookies();
@@ -85,7 +92,7 @@
// Remove all cookies from the database.
cookieManager.removeAllCookie();
- new DelayedCheck(10000) {
+ new DelayedCheck(30000) {
@Override
protected boolean check() {
return !cookieManager.hasCookies();
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
index a95cd90..14a14d0 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
@@ -211,24 +211,16 @@
public void testEmptyValue() {
String url = "http://www.foobar.com";
- mCookieManager.setCookie(url, "foo;");
- String cookie = mCookieManager.getCookie(url);
- assertTrue(cookie.equals("foo"));
-
- mCookieManager.setCookie(url, "bar");
- cookie = mCookieManager.getCookie(url);
- assertTrue(cookie.equals("bar; foo"));
-
mCookieManager.setCookie(url, "bar=");
- cookie = mCookieManager.getCookie(url);
- assertTrue(cookie.equals("bar=; bar; foo"));
+ String cookie = mCookieManager.getCookie(url);
+ assertTrue(cookie.equals("bar="));
mCookieManager.setCookie(url, "foobar=;");
cookie = mCookieManager.getCookie(url);
- assertTrue(cookie.equals("bar=; foobar=; bar; foo"));
+ assertTrue(cookie.equals("bar=; foobar="));
mCookieManager.setCookie(url, "baz=; path=/wee");
cookie = mCookieManager.getCookie(url + "/wee");
- assertTrue(cookie.equals("baz=; bar=; foobar=; bar; foo"));
+ assertTrue(cookie.equals("baz=; bar=; foobar="));
}
}
diff --git a/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java b/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
index e51f574..8721326 100644
--- a/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
@@ -90,7 +90,7 @@
assertLoadUrlSuccessfully(url);
assertEquals(CtsTestServer.AUTH_REALM, client.realm);
- assertEquals(CtsTestServer.getReasonString(HttpStatus.SC_FORBIDDEN), mWebView.getTitle());
+ assertEquals(CtsTestServer.getReasonString(HttpStatus.SC_UNAUTHORIZED), mWebView.getTitle());
assertTrue(client.useHttpAuthUsernamePassword);
// missing credentials
@@ -148,6 +148,7 @@
private boolean mProceed;
private String mUser;
private String mPassword;
+ private int mAuthCount;
MyWebViewClient(boolean proceed, String user, String password) {
mProceed = proceed;
@@ -157,6 +158,11 @@
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
+ ++mAuthCount;
+ if (mAuthCount > 1) {
+ handler.cancel();
+ return;
+ }
this.realm = realm;
this.useHttpAuthUsernamePassword = handler.useHttpAuthUsernamePassword();
if (mProceed) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index 18301e7..c526a1f 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
@@ -90,9 +90,9 @@
public void testUserAgentString_default() {
final String actualUserAgentString = mSettings.getUserAgentString();
Log.i(LOG_TAG, String.format("Checking user agent string %s", actualUserAgentString));
- final String patternString = "Mozilla/5\\.0 \\(Linux; U; Android (.+); (\\w+)-(\\w+);" +
- " (.+) Build/(.+)\\) AppleWebKit/533\\.1 \\(KHTML, like Gecko\\) Version/4\\.0" +
- " Mobile Safari/533\\.1";
+ final String patternString = "Mozilla/5\\.0 \\(Linux; U; Android (.+); (\\w+)-(\\w+);\\s?" +
+ "(.*)\\sBuild/(.+)\\) AppleWebKit/(\\d+)\\.(\\d+) \\(KHTML, like Gecko\\) Version/4\\.0" +
+ "( Mobile)? Safari/(\\d+)\\.(\\d+)";
Log.i(LOG_TAG, String.format("Trying to match pattern %s", patternString));
final Pattern userAgentExpr = Pattern.compile(patternString);
Matcher patternMatcher = userAgentExpr.matcher(actualUserAgentString);
@@ -103,7 +103,9 @@
Locale currentLocale = Locale.getDefault();
assertEquals(currentLocale.getLanguage().toLowerCase(), patternMatcher.group(2));
assertEquals(currentLocale.getCountry().toLowerCase(), patternMatcher.group(3));
- assertEquals(Build.MODEL, patternMatcher.group(4));
+ // Model is only added in release builds
+ if ("REL".equals(Build.VERSION.CODENAME))
+ assertEquals(Build.MODEL, patternMatcher.group(4));
assertEquals(Build.ID, patternMatcher.group(5));
}
@@ -242,7 +244,6 @@
args = {boolean.class}
)
})
- @ToBeFixed(explanation = "Implementation does not work as expected.")
public void testAccessBlockNetworkImage() throws Exception {
String url = TestHtmlConstants.EMBEDDED_IMG_URL;
final String ext = MimeTypeMap.getFileExtensionFromUrl(url);
@@ -258,13 +259,11 @@
}
}.run();
- /* ToBeFixed: Uncomment after fixing the framework
mWebView.clearCache(true);
mSettings.setBlockNetworkImage(true);
assertTrue(mSettings.getBlockNetworkImage());
- loadUrl(url);
+ loadAssetUrl(url);
assertTrue(mWebServer.getLastRequestUrl().endsWith(ext));
- */
}
@TestTargets({
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 0de14e7..2cd2deb 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -195,7 +195,7 @@
mWebServer = new CtsTestServer(getActivity());
assertFalse(webViewClient.hasOnReceivedHttpAuthRequestCalled());
- String url = mWebServer.getAuthAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+ String url = mWebServer.getAuthAssetUrl(TestHtmlConstants.EMBEDDED_IMG_URL);
assertLoadUrlSuccessfully(mWebView, url);
assertTrue(webViewClient.hasOnReceivedHttpAuthRequestCalled());
}
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index 05ff747..608a85f 100755
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -38,6 +38,7 @@
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
+import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.util.AttributeSet;
@@ -47,6 +48,7 @@
import android.view.View;
import android.view.animation.cts.DelayedCheck;
import android.webkit.CacheManager;
+import android.webkit.CacheManager.CacheResult;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebBackForwardList;
@@ -336,56 +338,15 @@
)
})
public void testScrollBarOverlay() throws Throwable {
- DisplayMetrics metrics = mWebView.getContext().getResources().getDisplayMetrics();
- int dimension = 2 * Math.max(metrics.widthPixels, metrics.heightPixels);
-
- String p = "<p style=\"height:" + dimension + "px;" +
- "width:" + dimension + "px;margin:0px auto;\">Test scroll bar overlay.</p>";
- mWebView.loadData("<html><body>" + p + "</body></html>", "text/html", "UTF-8");
- waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ mWebView.setHorizontalScrollbarOverlay(true);
+ mWebView.setVerticalScrollbarOverlay(false);
assertTrue(mWebView.overlayHorizontalScrollbar());
assertFalse(mWebView.overlayVerticalScrollbar());
- int startX = mWebView.getScrollX();
- int startY = mWebView.getScrollY();
-
- final int bigVelocity = 10000;
- // fling to the max and wait for ending scroll
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWebView.flingScroll(bigVelocity, bigVelocity);
- }
- });
- getInstrumentation().waitForIdleSync();
-
- int overlayOffsetX = mWebView.getScrollX() - startX;
- int insetOffsetY = mWebView.getScrollY() - startY;
-
- // scroll back
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWebView.flingScroll(-bigVelocity, -bigVelocity);
- }
- });
- getInstrumentation().waitForIdleSync();
mWebView.setHorizontalScrollbarOverlay(false);
mWebView.setVerticalScrollbarOverlay(true);
assertFalse(mWebView.overlayHorizontalScrollbar());
assertTrue(mWebView.overlayVerticalScrollbar());
-
- // fling to the max and wait for ending scroll
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWebView.flingScroll(bigVelocity, bigVelocity);
- }
- });
- getInstrumentation().waitForIdleSync();
-
- int insetOffsetX = mWebView.getScrollX() - startX;
- int overlayOffsetY = mWebView.getScrollY() - startY;
-
- assertTrue(overlayOffsetY > insetOffsetY);
- assertTrue(overlayOffsetX > insetOffsetX);
}
@TestTargets({
@@ -577,6 +538,108 @@
}.run();
}
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "addJavascriptInterface",
+ args = {Object.class, String.class}
+ )
+ public void testAddJavascriptInterfaceNullObject() throws Exception {
+ WebSettings settings = mWebView.getSettings();
+ settings.setJavaScriptEnabled(true);
+ String setTitleToPropertyTypeHtml = "<html><head></head>" +
+ "<body onload=\"document.title = typeof window.injectedObject;\"></body></html>";
+
+ // Test that the property is initially undefined.
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("undefined", mWebView.getTitle());
+
+ // Test that adding a null object has no effect.
+ mWebView.addJavascriptInterface(null, "injectedObject");
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("undefined", mWebView.getTitle());
+
+ // Test that adding an object gives an object type.
+ final DummyJavaScriptInterface obj = new DummyJavaScriptInterface();
+ mWebView.addJavascriptInterface(obj, "injectedObject");
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("object", mWebView.getTitle());
+
+ // Test that trying to replace with a null object has no effect.
+ mWebView.addJavascriptInterface(null, "injectedObject");
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("object", mWebView.getTitle());
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "addJavascriptInterface",
+ args = {Object.class, String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "removeJavascriptInterface",
+ args = {String.class}
+ )
+ })
+ public void testAddJavascriptInterfaceOddName() throws Exception {
+ WebSettings settings = mWebView.getSettings();
+ settings.setJavaScriptEnabled(true);
+ final DummyJavaScriptInterface obj = new DummyJavaScriptInterface();
+
+ // We should be able to use any character other than a single quote.
+ // TODO: We currently fail when the name contains '#', '\', '\n' or '\r'.
+ // See b/3279426
+ //String oddNames[] = {" x y ", "`!\"$%^&*()-=_+[]{};#:@~\\|,./<>?\n\r ", " ", "\n", ""};
+ String oddNames[] = {" x y ", "`!\"$%^&*()-=_+[]{};:@~|,./<>? ", " ", ""};
+ for (String name : oddNames) {
+ String setTitleToPropertyTypeHtml = "<html><head>" +
+ "<script>function updateTitle() { document.title = typeof window['" +
+ name +
+ "']; }</script>" +
+ "</head><body onload=\"updateTitle();\"></body></html>";
+
+ mWebView.addJavascriptInterface(obj, name);
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("object", mWebView.getTitle());
+
+ mWebView.removeJavascriptInterface(name);
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("undefined", mWebView.getTitle());
+ }
+ }
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "removeJavascriptInterface",
+ args = {String.class}
+ )
+ public void testRemoveJavascriptInterface() throws Exception {
+ WebSettings settings = mWebView.getSettings();
+ settings.setJavaScriptEnabled(true);
+ String setTitleToPropertyTypeHtml = "<html><head></head>" +
+ "<body onload=\"document.title = typeof window.injectedObject;\"></body></html>";
+
+ // Test that adding an object gives an object type.
+ final DummyJavaScriptInterface obj = new DummyJavaScriptInterface();
+ mWebView.addJavascriptInterface(obj, "injectedObject");
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("object", mWebView.getTitle());
+
+ // Test that removing the object leaves the property undefined.
+ mWebView.removeJavascriptInterface("injectedObject");
+ mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("undefined", mWebView.getTitle());
+ }
+
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -1149,8 +1212,16 @@
assertEquals(0, cacheFileBaseDir.list().length);
startWebServer(false);
- mWebView.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL));
+ final String url = mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+ mWebView.loadUrl(url);
waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ new DelayedCheck(TEST_TIMEOUT) {
+ @Override
+ protected boolean check() {
+ CacheResult result = CacheManager.getCacheFile(url, null);
+ return result != null;
+ }
+ }.run();
int cacheFileCount = cacheFileBaseDir.list().length;
assertTrue(cacheFileCount > 0);
@@ -1327,8 +1398,9 @@
handler.reset();
int[] location = new int[2];
mWebView.getLocationOnScreen(location);
+ long time = SystemClock.uptimeMillis();
getInstrumentation().sendPointerSync(
- MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN,
+ MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN,
location[0] + imgWidth / 2,
location[1] + imgHeight / 2, 0));
mWebView.requestImageRef(msg);
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
index 4bf19d2..0995f28 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
@@ -199,6 +199,55 @@
});
mInstrumentation.waitForIdleSync();
}
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnScrollListener",
+ args = {android.widget.AbsListView.OnScrollListener.class}
+ )
+ public void testSetOnScrollListener() throws Throwable {
+ MockOnScrollListener onScrollListener = new MockOnScrollListener();
+
+ assertNull(onScrollListener.getView());
+ assertEquals(0, onScrollListener.getFirstVisibleItem());
+ assertEquals(0, onScrollListener.getVisibleItemCount());
+ assertEquals(0, onScrollListener.getTotalItemCount());
+ assertEquals(-1, onScrollListener.getScrollState());
+
+ assertFalse(onScrollListener.isOnScrollCalled());
+ assertFalse(onScrollListener.isOnScrollStateChangedCalled());
+
+ mListView.setOnScrollListener(onScrollListener);
+ assertSame(mListView, onScrollListener.getView());
+ assertEquals(0, onScrollListener.getFirstVisibleItem());
+ assertEquals(0, onScrollListener.getVisibleItemCount());
+ assertEquals(0, onScrollListener.getTotalItemCount());
+ assertEquals(-1, onScrollListener.getScrollState());
+
+ assertTrue(onScrollListener.isOnScrollCalled());
+ assertFalse(onScrollListener.isOnScrollStateChangedCalled());
+ onScrollListener.reset();
+
+ setAdapter();
+
+ assertSame(mListView, onScrollListener.getView());
+ assertEquals(0, onScrollListener.getFirstVisibleItem());
+ assertEquals(mListView.getChildCount(), onScrollListener.getVisibleItemCount());
+ assertEquals(mCountryList.length, onScrollListener.getTotalItemCount());
+ assertEquals(-1, onScrollListener.getScrollState());
+
+ assertTrue(onScrollListener.isOnScrollCalled());
+ assertFalse(onScrollListener.isOnScrollStateChangedCalled());
+ onScrollListener.reset();
+
+ TouchUtils.scrollToBottom(this, mActivity, mListView);
+ assertSame(mListView, onScrollListener.getView());
+ assertEquals(mListView.getChildCount(), onScrollListener.getVisibleItemCount());
+ assertEquals(mCountryList.length, onScrollListener.getTotalItemCount());
+ assertEquals(OnScrollListener.SCROLL_STATE_IDLE, onScrollListener.getScrollState());
+
+ assertTrue(onScrollListener.isOnScrollCalled());
+ assertTrue(onScrollListener.isOnScrollStateChangedCalled());
+ }
@TestTargetNew(
level = TestLevel.COMPLETE,
diff --git a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
index 40e1c74..76bf39b 100755
--- a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
@@ -16,7 +16,13 @@
package android.widget.cts;
-import java.io.IOException;
+import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
@@ -40,13 +46,7 @@
import android.widget.Filterable;
import android.widget.AutoCompleteTextView.Validator;
-import com.android.cts.stub.R;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+import java.io.IOException;
@TestTargetClass(AutoCompleteTextView.class)
public class AutoCompleteTextViewTest extends
@@ -97,8 +97,7 @@
.findViewById(R.id.autocompletetv_edit);
mAdapter = new ArrayAdapter<String>(mActivity,
android.R.layout.simple_dropdown_item_1line, WORDS);
- KeyCharacterMap keymap
- = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
if (keymap.getKeyboardType() == KeyCharacterMap.NUMERIC) {
mNumeric = true;
}
@@ -506,8 +505,6 @@
// Set Threshold to 4 characters
mAutoCompleteTextView.setThreshold(4);
- inflatePopup();
- assertTrue(mAutoCompleteTextView.isPopupShowing());
String testString = "";
if (mNumeric) {
// "tes" in case of 12-key(NUMERIC) keyboard
@@ -515,6 +512,7 @@
} else {
testString = "tes";
}
+
// Test the filter if the input string is not long enough to threshold
runTestOnUiThread(new Runnable() {
public void run() {
@@ -528,8 +526,6 @@
// onFilterComplete will close the popup.
assertFalse(mAutoCompleteTextView.isPopupShowing());
- inflatePopup();
- assertTrue(mAutoCompleteTextView.isPopupShowing());
if (mNumeric) {
// "that" in case of 12-key(NUMERIC) keyboard
testString = "84428";
@@ -578,11 +574,16 @@
public void run() {
mAutoCompleteTextView.setAdapter(mAdapter);
mAutoCompleteTextView.setValidator(mValidator);
- mAutoCompleteTextView.setAdapter(mAdapter);
+
+ mAutoCompleteTextView.setText("test");
+ mAutoCompleteTextView.setFocusable(true);
+ mAutoCompleteTextView.requestFocus();
+ mAutoCompleteTextView.showDropDown();
}
});
- inflatePopup();
+ mInstrumentation.waitForIdleSync();
assertTrue(mAutoCompleteTextView.isPopupShowing());
+
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
// KeyBack will close the popup.
assertFalse(mAutoCompleteTextView.isPopupShowing());
@@ -1005,18 +1006,6 @@
}
}
- private void inflatePopup() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mAutoCompleteTextView.setText("");
- mAutoCompleteTextView.setFocusable(true);
- mAutoCompleteTextView.requestFocus();
- mAutoCompleteTextView.showDropDown();
- }
- });
- mInstrumentation.waitForIdleSync();
- }
-
private static class MockFilter extends Filter {
private String mFilterResult;
diff --git a/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java b/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java
index 27c967d..cf15efd 100644
--- a/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java
@@ -317,9 +317,9 @@
// compoundButton is checked, append R.attr.state_checked to state array.
compoundButton.setChecked(true);
int[] checkedState = compoundButton.onCreateDrawableState(0);
- assertEquals(2, checkedState.length);
assertEquals(state[0], checkedState[0]);
- assertEquals(com.android.internal.R.attr.state_checked, checkedState[1]);
+ assertEquals(com.android.internal.R.attr.state_checked,
+ checkedState[checkedState.length - 1]);
// compoundButton is not checked again.
compoundButton.setChecked(false);
@@ -339,7 +339,8 @@
int drawableHeight;
Rect bounds;
Drawable drawable;
- Canvas canvas = new Canvas();
+ Canvas canvas = new Canvas(android.graphics.Bitmap.createBitmap(100, 100,
+ android.graphics.Bitmap.Config.ARGB_8888));
MockCompoundButton compoundButton;
// onDraw when there is no drawable
diff --git a/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java b/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
index 661d257..ec2a250 100755
--- a/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
@@ -114,10 +114,13 @@
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mDialerFilter.setMode(DialerFilter.DIGITS_ONLY);
+ mDialerFilter.requestFocus();
}
});
mInstrumentation.waitForIdleSync();
+ assertTrue(mDialerFilter.hasFocus());
+
mInstrumentation.sendStringSync("123");
assertEquals("", mDialerFilter.getLetters().toString());
assertEquals("123", mDialerFilter.getDigits().toString());
@@ -132,7 +135,7 @@
// 12-key support
KeyCharacterMap keymap
- = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+ = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
if (keymap.getKeyboardType() == KeyCharacterMap.NUMERIC) {
// "adg" in case of 12-key(NUMERIC) keyboard
mInstrumentation.sendStringSync("234");
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListTester.java b/tests/tests/widget/src/android/widget/cts/ExpandableListTester.java
new file mode 100644
index 0000000..8175807
--- /dev/null
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListTester.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.widget.cts;
+
+import android.app.Instrumentation;
+import android.test.ActivityInstrumentationTestCase2;
+import android.view.KeyEvent;
+import android.view.View;
+import android.widget.ExpandableListAdapter;
+import android.widget.ExpandableListView;
+import android.widget.cts.util.ExpandableListScenario;
+import android.widget.cts.util.ListUtil;
+
+import junit.framework.Assert;
+
+public class ExpandableListTester {
+ private final ExpandableListView mExpandableListView;
+ private final ExpandableListAdapter mAdapter;
+ private final ListUtil mListUtil;
+
+ private final ActivityInstrumentationTestCase2<? extends ExpandableListScenario>
+ mActivityInstrumentation;
+
+ Instrumentation mInstrumentation;
+
+ public ExpandableListTester(
+ ExpandableListView expandableListView,
+ ActivityInstrumentationTestCase2<? extends ExpandableListScenario>
+ activityInstrumentation) {
+ mExpandableListView = expandableListView;
+ Instrumentation instrumentation = activityInstrumentation.getInstrumentation();
+ mListUtil = new ListUtil(mExpandableListView, instrumentation);
+ mAdapter = mExpandableListView.getExpandableListAdapter();
+ mActivityInstrumentation = activityInstrumentation;
+ mInstrumentation = mActivityInstrumentation.getInstrumentation();
+ }
+
+ private void expandGroup(final int groupIndex, int flatPosition) {
+ Assert.assertFalse("Group is already expanded", mExpandableListView
+ .isGroupExpanded(groupIndex));
+ mListUtil.arrowScrollToSelectedPosition(flatPosition);
+ mInstrumentation.waitForIdleSync();
+ mActivityInstrumentation.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+ mActivityInstrumentation.getInstrumentation().waitForIdleSync();
+ Assert.assertTrue("Group did not expand " + groupIndex,
+ mExpandableListView.isGroupExpanded(groupIndex));
+ }
+
+ void testContextMenus() {
+ // Add a position tester ContextMenu listener to the ExpandableListView
+ PositionTesterContextMenuListener menuListener = new PositionTesterContextMenuListener();
+ mExpandableListView.setOnCreateContextMenuListener(menuListener);
+
+ int index = 0;
+
+ // Scrolling on header elements should trigger an AdapterContextMenu
+ for (int i=0; i<mExpandableListView.getHeaderViewsCount(); i++) {
+ // Check group index in context menu
+ menuListener.expectAdapterContextMenu(i);
+ // Make sure the group is visible so that getChild finds it
+ mListUtil.arrowScrollToSelectedPosition(index);
+ View headerChild = mExpandableListView.getChildAt(index
+ - mExpandableListView.getFirstVisiblePosition());
+ mExpandableListView.showContextMenuForChild(headerChild);
+ mInstrumentation.waitForIdleSync();
+ Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+ index++;
+ }
+
+ int groupCount = mAdapter.getGroupCount();
+ for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
+
+ // Expand group
+ expandGroup(groupIndex, index);
+
+ // Check group index in context menu
+ menuListener.expectGroupContextMenu(groupIndex);
+ // Make sure the group is visible so that getChild finds it
+ mListUtil.arrowScrollToSelectedPosition(index);
+ View groupChild = mExpandableListView.getChildAt(index
+ - mExpandableListView.getFirstVisiblePosition());
+ mExpandableListView.showContextMenuForChild(groupChild);
+ mInstrumentation.waitForIdleSync();
+ Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+ index++;
+
+ final int childrenCount = mAdapter.getChildrenCount(groupIndex);
+ for (int childIndex = 0; childIndex < childrenCount; childIndex++) {
+ // Check child index in context menu
+ mListUtil.arrowScrollToSelectedPosition(index);
+ menuListener.expectChildContextMenu(groupIndex, childIndex);
+ View child = mExpandableListView.getChildAt(index
+ - mExpandableListView.getFirstVisiblePosition());
+ mExpandableListView.showContextMenuForChild(child);
+ mInstrumentation.waitForIdleSync();
+ Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+ index++;
+ }
+ }
+
+ // Scrolling on footer elements should trigger an AdapterContextMenu
+ for (int i=0; i<mExpandableListView.getFooterViewsCount(); i++) {
+ // Check group index in context menu
+ menuListener.expectAdapterContextMenu(index);
+ // Make sure the group is visible so that getChild finds it
+ mListUtil.arrowScrollToSelectedPosition(index);
+ View footerChild = mExpandableListView.getChildAt(index
+ - mExpandableListView.getFirstVisiblePosition());
+ mExpandableListView.showContextMenuForChild(footerChild);
+ mInstrumentation.waitForIdleSync();
+ Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+ index++;
+ }
+
+ // Cleanup: remove the listener we added.
+ mExpandableListView.setOnCreateContextMenuListener(null);
+ }
+
+ private int expandAGroup() {
+ final int groupIndex = 2;
+ final int headerCount = mExpandableListView.getHeaderViewsCount();
+ Assert.assertTrue("Not enough groups", groupIndex < mAdapter.getGroupCount());
+ expandGroup(groupIndex, groupIndex + headerCount);
+ return groupIndex;
+ }
+
+ // This method assumes that NO group is expanded when called
+ void testConvertionBetweenFlatAndPackedOnGroups() {
+ final int headerCount = mExpandableListView.getHeaderViewsCount();
+
+ for (int i=0; i<headerCount; i++) {
+ Assert.assertEquals("Non NULL position for header item",
+ ExpandableListView.PACKED_POSITION_VALUE_NULL,
+ mExpandableListView.getExpandableListPosition(i));
+ }
+
+ // Test all (non expanded) groups
+ final int groupCount = mAdapter.getGroupCount();
+ for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
+ int expectedFlatPosition = headerCount + groupIndex;
+ long packedPositionForGroup = ExpandableListView.getPackedPositionForGroup(groupIndex);
+ Assert.assertEquals("Group not found at flat position " + expectedFlatPosition,
+ packedPositionForGroup,
+ mExpandableListView.getExpandableListPosition(expectedFlatPosition));
+
+ Assert.assertEquals("Wrong flat position for group " + groupIndex,
+ expectedFlatPosition,
+ mExpandableListView.getFlatListPosition(packedPositionForGroup));
+ }
+
+ for (int i=0; i<mExpandableListView.getFooterViewsCount(); i++) {
+ Assert.assertEquals("Non NULL position for header item",
+ ExpandableListView.PACKED_POSITION_VALUE_NULL,
+ mExpandableListView.getExpandableListPosition(headerCount + groupCount + i));
+ }
+ }
+
+ // This method assumes that NO group is expanded when called
+ void testConvertionBetweenFlatAndPackedOnChildren() {
+ // Test with an expanded group
+ final int headerCount = mExpandableListView.getHeaderViewsCount();
+ final int groupIndex = expandAGroup();
+
+ final int childrenCount = mAdapter.getChildrenCount(groupIndex);
+ for (int childIndex = 0; childIndex < childrenCount; childIndex++) {
+ int expectedFlatPosition = headerCount + groupIndex + 1 + childIndex;
+ long childPos = ExpandableListView.getPackedPositionForChild(groupIndex, childIndex);
+
+ Assert.assertEquals("Wrong flat position for child ",
+ childPos,
+ mExpandableListView.getExpandableListPosition(expectedFlatPosition));
+
+ Assert.assertEquals("Wrong flat position for child ",
+ expectedFlatPosition,
+ mExpandableListView.getFlatListPosition(childPos));
+ }
+ }
+
+ // This method assumes that NO group is expanded when called
+ void testSelectedPositionOnGroups() {
+ int index = 0;
+
+ // Scrolling on header elements should not give a valid selected position.
+ for (int i=0; i<mExpandableListView.getHeaderViewsCount(); i++) {
+ mListUtil.arrowScrollToSelectedPosition(index);
+ Assert.assertEquals("Header item is selected",
+ ExpandableListView.PACKED_POSITION_VALUE_NULL,
+ mExpandableListView.getSelectedPosition());
+ index++;
+ }
+
+ // Check selection on group items
+ final int groupCount = mAdapter.getGroupCount();
+ for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
+ mListUtil.arrowScrollToSelectedPosition(index);
+ Assert.assertEquals("Group item is not selected",
+ ExpandableListView.getPackedPositionForGroup(groupIndex),
+ mExpandableListView.getSelectedPosition());
+ index++;
+ }
+
+ // Scrolling on footer elements should not give a valid selected position.
+ for (int i=0; i<mExpandableListView.getFooterViewsCount(); i++) {
+ mListUtil.arrowScrollToSelectedPosition(index);
+ Assert.assertEquals("Footer item is selected",
+ ExpandableListView.PACKED_POSITION_VALUE_NULL,
+ mExpandableListView.getSelectedPosition());
+ index++;
+ }
+ }
+
+ // This method assumes that NO group is expanded when called
+ void testSelectedPositionOnChildren() {
+ // Test with an expanded group
+ final int headerCount = mExpandableListView.getHeaderViewsCount();
+ final int groupIndex = expandAGroup();
+
+ final int childrenCount = mAdapter.getChildrenCount(groupIndex);
+ for (int childIndex = 0; childIndex < childrenCount; childIndex++) {
+ int childFlatPosition = headerCount + groupIndex + 1 + childIndex;
+ mListUtil.arrowScrollToSelectedPosition(childFlatPosition);
+ Assert.assertEquals("Group item is not selected",
+ ExpandableListView.getPackedPositionForChild(groupIndex, childIndex),
+ mExpandableListView.getSelectedPosition());
+ }
+ }
+}
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java b/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java
index c6c0b35..fc39364 100644
--- a/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java
@@ -16,7 +16,10 @@
package android.widget.cts;
-import java.util.List;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.MediumTest;
@@ -27,21 +30,19 @@
import android.widget.cts.util.ExpandableListScenario;
import android.widget.cts.util.ListUtil;
import android.widget.cts.util.ExpandableListScenario.MyGroup;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
+
+import java.util.List;
@TestTargetClass(ExpandableListView.class)
public class ExpandableListViewBasicTest extends
ActivityInstrumentationTestCase2<ExpandableListSimple> {
private ExpandableListScenario mActivity;
- private ExpandableListView mListView;
+ private ExpandableListView mExpandableListView;
private ExpandableListAdapter mAdapter;
private ListUtil mListUtil;
public ExpandableListViewBasicTest() {
- super("com.android.cts.stub", ExpandableListSimple.class);
+ super(ExpandableListSimple.class);
}
@Override
@@ -49,27 +50,27 @@
super.setUp();
mActivity = getActivity();
- mListView = mActivity.getExpandableListView();
- mAdapter = mListView.getExpandableListAdapter();
- mListUtil = new ListUtil(mListView, getInstrumentation());
+ mExpandableListView = mActivity.getExpandableListView();
+ mAdapter = mExpandableListView.getExpandableListAdapter();
+ mListUtil = new ListUtil(mExpandableListView, getInstrumentation());
}
@MediumTest
public void testPreconditions() {
assertNotNull(mActivity);
- assertNotNull(mListView);
+ assertNotNull(mExpandableListView);
}
private int expandGroup(int numChildren, boolean atLeastOneChild) {
final int groupPos = mActivity.findGroupWithNumChildren(numChildren, atLeastOneChild);
assertTrue("Could not find group to expand", groupPos >= 0);
- assertFalse("Group is already expanded", mListView.isGroupExpanded(groupPos));
+ assertFalse("Group is already expanded", mExpandableListView.isGroupExpanded(groupPos));
mListUtil.arrowScrollToSelectedPosition(groupPos);
getInstrumentation().waitForIdleSync();
sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
getInstrumentation().waitForIdleSync();
- assertTrue("Group did not expand", mListView.isGroupExpanded(groupPos));
+ assertTrue("Group did not expand", mExpandableListView.isGroupExpanded(groupPos));
return groupPos;
}
@@ -97,7 +98,7 @@
sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
getInstrumentation().waitForIdleSync();
- assertFalse("Group did not collapse", mListView.isGroupExpanded(groupPos));
+ assertFalse("Group did not collapse", mExpandableListView.isGroupExpanded(groupPos));
}
@TestTargets({
@@ -122,13 +123,13 @@
getInstrumentation().waitForIdleSync();
// Ensure it expanded
- assertTrue("Group did not expand", mListView.isGroupExpanded(0));
+ assertTrue("Group did not expand", mExpandableListView.isGroupExpanded(0));
// Wait until that's all good
getInstrumentation().waitForIdleSync();
// Make sure it expanded
- assertTrue("Group did not expand", mListView.isGroupExpanded(0));
+ assertTrue("Group did not expand", mExpandableListView.isGroupExpanded(0));
// Insert a collapsed group in front of the one just expanded
List<MyGroup> groups = mActivity.getGroups();
@@ -149,8 +150,28 @@
// Make sure the right group is expanded
assertTrue("The expanded state didn't stay with the proper group",
- mListView.isGroupExpanded(1));
+ mExpandableListView.isGroupExpanded(1));
assertFalse("The expanded state was given to the inserted group",
- mListView.isGroupExpanded(0));
+ mExpandableListView.isGroupExpanded(0));
+ }
+
+ @MediumTest
+ public void testContextMenus() {
+ ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+ tester.testContextMenus();
+ }
+
+ @MediumTest
+ public void testConvertionBetweenFlatAndPacked() {
+ ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+ tester.testConvertionBetweenFlatAndPackedOnGroups();
+ tester.testConvertionBetweenFlatAndPackedOnChildren();
+ }
+
+ @MediumTest
+ public void testSelectedPosition() {
+ ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+ tester.testSelectedPositionOnGroups();
+ tester.testSelectedPositionOnChildren();
}
}
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java b/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java
index af420b4..5ab7f4d 100644
--- a/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java
@@ -519,10 +519,10 @@
args = {int.class, int.class}
)
public void testGetPackedPositionForChild() {
- assertEquals((long) 0x8000000000000000L,
+ assertEquals(0x8000000000000000L,
ExpandableListView.getPackedPositionForChild(0, 0));
- assertEquals((long) 0xffffffffffffffffL,
+ assertEquals(0xffffffffffffffffL,
ExpandableListView.getPackedPositionForChild(Integer.MAX_VALUE, 0xffffffff));
}
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java b/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java
index 57776a0..fe65f98 100644
--- a/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java
@@ -16,16 +16,16 @@
package android.widget.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.KeyEvent;
import android.widget.ExpandableListView;
import android.widget.cts.util.ListUtil;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
@TestTargetClass(ExpandableListView.class)
public class ExpandableListViewWithHeadersTest extends
@@ -34,7 +34,7 @@
private ListUtil mListUtil;
public ExpandableListViewWithHeadersTest() {
- super("com.android.cts.stub", ExpandableListWithHeaders.class);
+ super(ExpandableListWithHeaders.class);
}
@Override
@@ -78,4 +78,24 @@
getInstrumentation().waitForIdleSync();
assertTrue(mExpandableListView.isGroupExpanded(0));
}
+
+ @MediumTest
+ public void testContextMenus() {
+ ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+ tester.testContextMenus();
+ }
+
+ @MediumTest
+ public void testConvertionBetweenFlatAndPacked() {
+ ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+ tester.testConvertionBetweenFlatAndPackedOnGroups();
+ tester.testConvertionBetweenFlatAndPackedOnChildren();
+ }
+
+ @MediumTest
+ public void testSelectedPosition() {
+ ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+ tester.testSelectedPositionOnGroups();
+ tester.testSelectedPositionOnChildren();
+ }
}
diff --git a/tests/tests/widget/src/android/widget/cts/GridViewTest.java b/tests/tests/widget/src/android/widget/cts/GridViewTest.java
index 57b5804..802aa96 100644
--- a/tests/tests/widget/src/android/widget/cts/GridViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/GridViewTest.java
@@ -16,6 +16,14 @@
package android.widget.cts;
+import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
import org.xmlpull.v1.XmlPullParser;
import android.app.Activity;
@@ -44,14 +52,6 @@
import android.widget.ListAdapter;
import android.widget.AdapterView.OnItemClickListener;
-import com.android.cts.stub.R;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
-
/**
* Test {@link GridView}.
*/
@@ -72,7 +72,6 @@
@Override
protected void setUp() throws Exception {
super.setUp();
-
mGridView = null;
mActivity = getActivity();
mInstrumentation = getInstrumentation();
@@ -310,6 +309,7 @@
)
public void testSetHorizontalSpacing() {
mGridView = findGridViewById(R.id.gridview);
+ mGridView.setStretchMode(GridView.NO_STRETCH);
// Number of columns should be big enough, otherwise the
// horizontal spacing cannot be correctly verified.
mGridView.setNumColumns(20);
@@ -534,6 +534,48 @@
@TestTargetNew(
level = TestLevel.COMPLETE,
+ notes = "Test {@link GridView#getNumColumns()}",
+ method = "getNumColumns"
+ )
+ public void testGetNumColumns() {
+ mGridView = new GridView(mActivity);
+
+ assertEquals(mGridView.getNumColumns(), GridView.AUTO_FIT);
+
+ mGridView = findGridViewById(R.id.gridview);
+
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mGridView.setAdapter(new MockGridViewAdapter(10));
+ mGridView.setNumColumns(10);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
+
+ assertEquals(mGridView.getNumColumns(), 10);
+
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mGridView.setNumColumns(1);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
+
+ assertEquals(mGridView.getNumColumns(), 1);
+
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mGridView.setNumColumns(0);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
+
+ //although setNumColumns(0) was called, the number of columns should be 1
+ assertEquals(mGridView.getNumColumns(), 1);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
method = "attachLayoutAnimationParameters",
args = {android.view.View.class, android.view.ViewGroup.LayoutParams.class, int.class,
int.class}
diff --git a/tests/tests/widget/src/android/widget/cts/ListViewTest.java b/tests/tests/widget/src/android/widget/cts/ListViewTest.java
index e7b872a..ba597c1 100644
--- a/tests/tests/widget/src/android/widget/cts/ListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ListViewTest.java
@@ -16,9 +16,14 @@
package android.widget.cts;
-import java.util.List;
+import com.android.cts.stub.R;
+import com.google.android.collect.Lists;
-import junit.framework.Assert;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
import org.xmlpull.v1.XmlPullParser;
@@ -44,14 +49,9 @@
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
-import com.android.cts.stub.R;
-import com.google.android.collect.Lists;
+import java.util.List;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+import junit.framework.Assert;
@TestTargetClass(ListView.class)
public class ListViewTest extends ActivityInstrumentationTestCase2<ListViewStubActivity> {
@@ -721,9 +721,11 @@
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
+ mListView.requestFocus();
}
});
mInstrumentation.waitForIdleSync();
+ assertTrue(mListView.hasFocus());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
diff --git a/tests/tests/widget/src/android/widget/cts/PositionTesterContextMenuListener.java b/tests/tests/widget/src/android/widget/cts/PositionTesterContextMenuListener.java
new file mode 100644
index 0000000..a1c9bc4
--- /dev/null
+++ b/tests/tests/widget/src/android/widget/cts/PositionTesterContextMenuListener.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.widget.cts;
+
+import android.view.ContextMenu;
+import android.view.View;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.View.OnCreateContextMenuListener;
+import android.widget.ExpandableListView;
+import android.widget.AdapterView.AdapterContextMenuInfo;
+
+public class PositionTesterContextMenuListener implements OnCreateContextMenuListener {
+
+ private int groupPosition, childPosition;
+
+ // Fake constant to store in testType a test type specific to headers and footers
+ private static final int ADAPTER_TYPE = -1;
+ private int testType; // as returned by getPackedPositionType
+
+ // Will be set to null by each call to onCreateContextMenu, unless an error occurred.
+ private String errorMessage;
+
+ public void expectGroupContextMenu(int groupPosition) {
+ this.groupPosition = groupPosition;
+ testType = ExpandableListView.PACKED_POSITION_TYPE_GROUP;
+ }
+
+ public void expectChildContextMenu(int groupPosition, int childPosition) {
+ this.groupPosition = groupPosition;
+ this.childPosition = childPosition;
+ testType = ExpandableListView.PACKED_POSITION_TYPE_CHILD;
+ }
+
+ public void expectAdapterContextMenu(int flatPosition) {
+ this.groupPosition = flatPosition;
+ testType = ADAPTER_TYPE;
+ }
+
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
+ errorMessage = null;
+ if (testType == ADAPTER_TYPE) {
+ if (!isTrue("MenuInfo is not an AdapterContextMenuInfo",
+ menuInfo instanceof AdapterContextMenuInfo)) {
+ return;
+ }
+ AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
+ if (!areEqual("Wrong flat position", groupPosition, adapterContextMenuInfo.position)) {
+ return;
+ }
+ } else {
+ if (!isTrue("MenuInfo is not an ExpandableListContextMenuInfo",
+ menuInfo instanceof ExpandableListView.ExpandableListContextMenuInfo)) {
+ return;
+ }
+ ExpandableListView.ExpandableListContextMenuInfo elvMenuInfo =
+ (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
+ long packedPosition = elvMenuInfo.packedPosition;
+
+ int packedPositionType = ExpandableListView.getPackedPositionType(packedPosition);
+ if (!areEqual("Wrong packed position type", testType, packedPositionType)) {
+ return;
+ }
+
+ int packedPositionGroup = ExpandableListView.getPackedPositionGroup(packedPosition);
+ if (!areEqual("Wrong group position", groupPosition, packedPositionGroup)) {
+ return;
+ }
+
+ if (testType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
+ int packedPositionChild = ExpandableListView.getPackedPositionChild(packedPosition);
+ if (!areEqual("Wrong child position", childPosition, packedPositionChild)) {
+ return;
+ }
+ }
+ }
+ }
+
+ private boolean areEqual(String message, int expected, int actual) {
+ if (expected != actual) {
+ errorMessage = String.format(message + " (%d vs %d", expected, actual);
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isTrue(String message, boolean value) {
+ if (!value) {
+ errorMessage = message;
+ return false;
+ }
+ return true;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+}
diff --git a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
index 9331ff9..ddbe90d 100644
--- a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
@@ -40,6 +40,7 @@
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Chronometer;
+import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
@@ -359,13 +360,6 @@
.getResources().getDrawable(R.drawable.testimage);
WidgetTestUtils.assertEquals(d.getBitmap(),
((BitmapDrawable) image.getDrawable()).getBitmap());
-
- try {
- mRemoteViews.reapply(mActivity, text);
- fail("Should throw ActionException");
- } catch (ActionException e) {
- // expected
- }
}
@TestTargetNew(
@@ -384,10 +378,11 @@
assertTrue(mRemoteViews.onLoadClass(ImageView.class));
assertTrue(mRemoteViews.onLoadClass(ProgressBar.class));
assertTrue(mRemoteViews.onLoadClass(Chronometer.class));
+ assertTrue(mRemoteViews.onLoadClass(ListView.class));
+ assertTrue(mRemoteViews.onLoadClass(GridView.class));
// those classes without annotation @RemoteView
- assertFalse(mRemoteViews.onLoadClass(ListView.class));
- assertFalse(mRemoteViews.onLoadClass(GridView.class));
+ assertFalse(mRemoteViews.onLoadClass(EditText.class));
}
@TestTargetNew(
diff --git a/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java b/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java
index cff8142..681e641 100644
--- a/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java
@@ -658,6 +658,7 @@
@UiThreadTest
public void testRequestChildRectangleOnScreen() {
mScrollView.setSmoothScrollingEnabled(false);
+ mScrollView.setVerticalFadingEdgeEnabled(true);
int edge = mScrollView.getVerticalFadingEdgeLength();
View child = mScrollView.findViewById(R.id.first_child);
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index dc8e8b7..71b2dba 100755
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -44,6 +44,7 @@
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
+import android.os.Debug;
import android.test.ActivityInstrumentationTestCase2;
import android.test.TouchUtils;
import android.test.UiThreadTest;
@@ -108,7 +109,10 @@
private Activity mActivity;
private Instrumentation mInstrumentation;
private static final String LONG_TEXT = "This is a really long string which exceeds "
- + "the width of the view.";
+ + "the width of the view. New devices have a much larger screen which "
+ + "actually enables long strings to be displayed with no fading. "
+ + "I have made this string longer to fix this case. If you are correcting "
+ + "this text, I would love to see the kind of devices you guys now use!";
private static final long TIMEOUT = 5000;
private CharSequence mTransformedText;
@@ -1190,8 +1194,14 @@
}
});
- newActivity = am.waitForActivityWithTimeout(TIMEOUT);
- assertNotNull(newActivity);
+ Activity oldActivity = newActivity;
+ while (true) {
+ newActivity = am.waitForActivityWithTimeout(TIMEOUT);
+ assertNotNull(newActivity);
+ if (newActivity != oldActivity) {
+ break;
+ }
+ }
newActivity.finish();
instrumentation.removeMonitor(am);
// the text of TextView is still there.
@@ -1773,7 +1783,7 @@
// a key event that will not change the TextView's text
assertEquals("", mTextView.getText().toString());
// The icon and error message will not be reset to null
- assertNotNull(mTextView.getError());
+ assertNull(mTextView.getError());
mActivity.runOnUiThread(new Runnable() {
public void run() {
diff --git a/tests/tests/widget/src/android/widget/cts/TimePickerTest.java b/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
index 881693f..8287ae6 100644
--- a/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
@@ -136,20 +136,19 @@
int initialHour = 13;
int initialMinute = 50;
mTimePicker = new TimePicker(mContext);
- mTimePicker.setCurrentHour(Integer.valueOf(initialHour));
- mTimePicker.setCurrentMinute(Integer.valueOf(initialMinute));
+
MockOnTimeChangeListener listener = new MockOnTimeChangeListener();
mTimePicker.setOnTimeChangedListener(listener);
+ mTimePicker.setCurrentHour(Integer.valueOf(initialHour));
+ mTimePicker.setCurrentMinute(Integer.valueOf(initialMinute));
+ assertEquals(initialHour, listener.getNotifiedHourOfDay());
+ assertEquals(initialMinute, listener.getNotifiedMinute());
// set the same hour as current
listener.reset();
mTimePicker.setCurrentHour(Integer.valueOf(initialHour));
- assertTrue(listener.hasCalledOnTimeChanged());
- assertEquals(initialHour, listener.getNotifiedHourOfDay());
- assertEquals(initialMinute, listener.getNotifiedMinute());
- assertSame(mTimePicker, listener.getNotifiedView());
+ assertFalse(listener.hasCalledOnTimeChanged());
- listener.reset();
mTimePicker.setCurrentHour(Integer.valueOf(initialHour + 1));
assertTrue(listener.hasCalledOnTimeChanged());
assertEquals(initialHour + 1, listener.getNotifiedHourOfDay());
@@ -159,10 +158,7 @@
// set the same minute as current
listener.reset();
mTimePicker.setCurrentMinute(initialMinute);
- assertTrue(listener.hasCalledOnTimeChanged());
- assertEquals(initialHour + 1, listener.getNotifiedHourOfDay());
- assertEquals(initialMinute, listener.getNotifiedMinute());
- assertSame(mTimePicker, listener.getNotifiedView());
+ assertFalse(listener.hasCalledOnTimeChanged());
listener.reset();
mTimePicker.setCurrentMinute(initialMinute + 1);
@@ -174,10 +170,7 @@
// change time picker mode
listener.reset();
mTimePicker.setIs24HourView( !mTimePicker.is24HourView() );
- assertTrue(listener.hasCalledOnTimeChanged());
- assertEquals(initialHour + 1, listener.getNotifiedHourOfDay());
- assertEquals(initialMinute + 1, listener.getNotifiedMinute());
- assertSame(mTimePicker, listener.getNotifiedView());
+ assertFalse(listener.hasCalledOnTimeChanged());
}
@TestTargets({
diff --git a/tests/tests/widget/src/android/widget/cts/VideoViewTest.java b/tests/tests/widget/src/android/widget/cts/VideoViewTest.java
index 44d48a5..57ea598 100644
--- a/tests/tests/widget/src/android/widget/cts/VideoViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/VideoViewTest.java
@@ -46,7 +46,7 @@
@TestTargetClass(VideoView.class)
public class VideoViewTest extends ActivityInstrumentationTestCase2<VideoViewStubActivity> {
/** The maximum time to wait for an operation. */
- private static final long TIME_OUT = 10000L;
+ private static final long TIME_OUT = 15000L;
/** The interval time to wait for completing an operation. */
private static final long OPERATION_INTERVAL = 1500L;
/** The duration of R.raw.testvideo. */
diff --git a/tools/device-setup/TestDeviceSetup/Android.mk b/tools/device-setup/TestDeviceSetup/Android.mk
index 3704be5..413f50b 100644
--- a/tools/device-setup/TestDeviceSetup/Android.mk
+++ b/tools/device-setup/TestDeviceSetup/Android.mk
@@ -30,3 +30,14 @@
include $(BUILD_PACKAGE)
+# ======================================================
+# also build a static host library for the device info constants
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := src/android/tests/getinfo/DeviceInfoConstants.java
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE := ctsdeviceinfolib
+
+include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
index e6c0e14..bcba1cb 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
@@ -64,7 +64,7 @@
touchScreen = "finger";
}
if (touchScreen != null) {
- DeviceInfoInstrument.addResult(DeviceInfoInstrument.TOUCH_SCREEN,
+ DeviceInfoInstrument.addResult(DeviceInfoConstants.TOUCH_SCREEN,
touchScreen);
}
@@ -82,7 +82,7 @@
}
if (navigation != null) {
- DeviceInfoInstrument.addResult(DeviceInfoInstrument.NAVIGATION,
+ DeviceInfoInstrument.addResult(DeviceInfoConstants.NAVIGATION,
navigation);
}
@@ -97,7 +97,7 @@
keypad = "12key";
}
if (keypad != null) {
- DeviceInfoInstrument.addResult(DeviceInfoInstrument.KEYPAD, keypad);
+ DeviceInfoInstrument.addResult(DeviceInfoConstants.KEYPAD, keypad);
}
String[] locales = getAssets().getLocales();
@@ -110,7 +110,7 @@
}
localeList.append(";");
}
- DeviceInfoInstrument.addResult(DeviceInfoInstrument.LOCALES,
+ DeviceInfoInstrument.addResult(DeviceInfoConstants.LOCALES,
localeList.toString());
synchronized (sync) {
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
new file mode 100644
index 0000000..bfe5aaa
--- /dev/null
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.tests.getinfo;
+
+/**
+ * Constants for device info attributes to be sent as instrumentation keys.
+ * <p/>
+ * These values should correspond to attributes defined in cts_result.xsd.
+ */
+public interface DeviceInfoConstants {
+
+ public static final String PARTITIONS = "partitions";
+ public static final String OPEN_GL_ES_VERSION = "openGlEsVersion";
+ public static final String PROCESSES = "processes";
+ public static final String FEATURES = "features";
+ public static final String PHONE_NUMBER = "phoneNumber";
+ public static final String LOCALES = "locales";
+ public static final String IMSI = "imsi";
+ public static final String IMEI = "imei";
+ public static final String NETWORK = "network";
+ public static final String KEYPAD = "keypad";
+ public static final String NAVIGATION = "navigation";
+ public static final String TOUCH_SCREEN = "touch";
+ public static final String SCREEN_Y_DENSITY = "Ydpi";
+ public static final String SCREEN_X_DENSITY = "Xdpi";
+ public static final String SCREEN_SIZE = "screen_size";
+ public static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
+ public static final String SCREEN_DENSITY = "screen_density";
+ public static final String SCREEN_HEIGHT = "screen_height";
+ public static final String SCREEN_WIDTH = "screen_width";
+ public static final String VERSION_SDK = "androidPlatformVersion";
+ public static final String VERSION_RELEASE = "buildVersion";
+ public static final String BUILD_ABI = "build_abi";
+ public static final String BUILD_ABI2 = "build_abi2";
+ public static final String BUILD_FINGERPRINT = "build_fingerprint";
+ public static final String BUILD_TYPE = "build_type";
+ public static final String BUILD_MODEL = "build_model";
+ public static final String BUILD_BRAND = "build_brand";
+ public static final String BUILD_MANUFACTURER = "build_manufacturer";
+ public static final String BUILD_BOARD = "build_board";
+ public static final String BUILD_DEVICE = "build_device";
+ public static final String PRODUCT_NAME = "buildName";
+ public static final String BUILD_ID = "buildID";
+ public static final String BUILD_VERSION = "buildVersion";
+ public static final String BUILD_TAGS = "build_tags";
+ public static final String SERIAL_NUMBER = "serialNumber";
+}
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
index 8b00ddf..606adfd 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
@@ -39,44 +39,10 @@
import java.util.Scanner;
import java.util.Set;
-public class DeviceInfoInstrument extends Instrumentation {
+public class DeviceInfoInstrument extends Instrumentation implements DeviceInfoConstants {
private static final String TAG = "DeviceInfoInstrument";
- // constants for device info attributes to be sent as instrumentation keys
- // these values should correspond to attributes defined in cts_result.xsd
- private static final String PARTITIONS = "partitions";
- private static final String OPEN_GL_ES_VERSION = "openGlEsVersion";
- private static final String PROCESSES = "processes";
- private static final String FEATURES = "features";
- private static final String PHONE_NUMBER = "phoneNumber";
- public static final String LOCALES = "locales";
- private static final String IMSI = "imsi";
- private static final String IMEI = "imei";
- private static final String NETWORK = "network";
- public static final String KEYPAD = "keypad";
- public static final String NAVIGATION = "navigation";
- public static final String TOUCH_SCREEN = "touch";
- private static final String SCREEN_Y_DENSITY = "Ydpi";
- private static final String SCREEN_X_DENSITY = "Xdpi";
- private static final String SCREEN_SIZE = "screen_size";
- private static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
- private static final String SCREEN_DENSITY = "screen_density";
- private static final String SCREEN_HEIGHT = "screen_height";
- private static final String SCREEN_WIDTH = "screen_width";
- private static final String VERSION_SDK = "androidPlatformVersion";
- private static final String VERSION_RELEASE = "buildVersion";
- private static final String BUILD_ABI = "build_abi";
- private static final String BUILD_ABI2 = "build_abi2";
- private static final String BUILD_FINGERPRINT = "build_fingerprint";
- private static final String BUILD_TYPE = "build_type";
- private static final String BUILD_MODEL = "build_model";
- private static final String BUILD_BRAND = "build_brand";
- private static final String BUILD_MANUFACTURER = "build_manufacturer";
- private static final String BUILD_BOARD = "build_board";
- private static final String BUILD_DEVICE = "build_device";
- private static final String PRODUCT_NAME = "buildName";
- private static final String BUILD_ID = "buildID";
private static Bundle mResults = new Bundle();
public DeviceInfoInstrument() {
diff --git a/tools/dx-tests/Android.mk b/tools/dx-tests/Android.mk
index 9bdef58..d249cea 100644
--- a/tools/dx-tests/Android.mk
+++ b/tools/dx-tests/Android.mk
@@ -38,7 +38,7 @@
@echo "Copy: $(PRIVATE_MODULE) ($@)"
$(copy-file-to-new-target)
$(hide) chmod 755 $@
- @$(PRIVATE_CURRENT_MODULE_SCRIPT) "$(PRIVATE_BASE)" "$(HOST_JAVAC)" "$(PRIVATE_INTERMEDIATES)" "$(HOST_OUT_JAVA_LIBRARIES)/dx.jar:$(HOST_OUT_JAVA_LIBRARIES)/cfassembler.jar" "$(HOST_OUT)"
+ $(hide) PATH=$(HOST_OUT_EXECUTABLES):$$PATH $(PRIVATE_CURRENT_MODULE_SCRIPT) "$(PRIVATE_BASE)" "$(HOST_JAVAC)" "$(PRIVATE_INTERMEDIATES)" "$(HOST_OUT_JAVA_LIBRARIES)/dx.jar:$(HOST_OUT_JAVA_LIBRARIES)/cfassembler.jar" "$(HOST_OUT)"
# cfassembler host module
#============================================================
diff --git a/tools/host/src/Android.mk b/tools/host/src/Android.mk
index 47a9cb8..dabee3d 100644
--- a/tools/host/src/Android.mk
+++ b/tools/host/src/Android.mk
@@ -23,6 +23,8 @@
LOCAL_JAVA_LIBRARIES := \
ddmlib-prebuilt junit hosttestlib
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceinfolib
+
LOCAL_MODULE := cts
include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/host/src/com/android/cts/TestDevice.java b/tools/host/src/com/android/cts/TestDevice.java
index 672ed37..6ac56a1 100644
--- a/tools/host/src/com/android/cts/TestDevice.java
+++ b/tools/host/src/com/android/cts/TestDevice.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008 The Android Open Source Project
+* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@
import com.android.ddmlib.log.LogReceiver;
import com.android.ddmlib.log.LogReceiver.ILogListener;
+import android.tests.getinfo.DeviceInfoConstants;
+
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -400,43 +402,7 @@
/**
* Store the build information of a device
*/
- public static final class DeviceParameterCollector{
- // the device info keys expected to be sent from device info instrumentation
- // these constants should match exactly with those defined in DeviceInfoInstrument.jaa
- public static final String PRODUCT_NAME = "buildName";
- public static final String BUILD_VERSION = "buildVersion";
- public static final String BUILD_ID = "buildID";
- public static final String BUILD_FINGERPRINT = "build_fingerprint";
- public static final String BUILD_TAGS = "build_tags";
- public static final String BUILD_TYPE = "build_type";
- public static final String BUILD_MANUFACTURER = "build_manufacturer";
- public static final String BUILD_MODEL = "build_model";
- public static final String BUILD_BRAND = "build_brand";
- public static final String BUILD_BOARD = "build_board";
- public static final String BUILD_DEVICE = "build_device";
- public static final String BUILD_ABI = "build_abi";
- public static final String BUILD_ABI2 = "build_abi2";
- public static final String SCREEN_SIZE = "screen_size";
- public static final String SCREEN_HEIGHT = "screen_height";
- public static final String SCREEN_WIDTH = "screen_width";
- public static final String SCREEN_DENSITY = "screen_density";
- public static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
- public static final String SERIAL_NUMBER = "serialNumber";
- public static final String VERSION_SDK = "androidPlatformVersion";
- public static final String LOCALES = "locales";
- public static final String SCREEN_Y_DENSITY = "Ydpi";
- public static final String SCREEN_X_DENSITY = "Xdpi";
- public static final String TOUCH_SCREEN = "touch";
- public static final String NAVIGATION = "navigation";
- public static final String KEYPAD = "keypad";
- public static final String NETWORK = "network";
- public static final String IMEI = "imei";
- public static final String IMSI = "imsi";
- public static final String PHONE_NUMBER = "phoneNumber";
- public static final String FEATURES = "features";
- public static final String PROCESSES = "processes";
- public static final String OPEN_GL_ES_VERSION = "openGlEsVersion";
- public static final String PARTITIONS = "partitions";
+ public static final class DeviceParameterCollector implements DeviceInfoConstants {
private HashMap<String, String> mInfoMap;
diff --git a/tools/host/src/com/android/cts/Version.java b/tools/host/src/com/android/cts/Version.java
index fb91d92..2d46d45 100644
--- a/tools/host/src/com/android/cts/Version.java
+++ b/tools/host/src/com/android/cts/Version.java
@@ -18,7 +18,7 @@
public class Version {
// The CTS version string
- private static final String version = "2.3_r2";
+ private static final String version = "3.0_r2";
private Version() {
// no instances allowed
diff --git a/tools/host/src/res/cts_result.xsd b/tools/host/src/res/cts_result.xsd
index ad8205c..665795f 100644
--- a/tools/host/src/res/cts_result.xsd
+++ b/tools/host/src/res/cts_result.xsd
@@ -149,11 +149,12 @@
<xs:complexType name="testPackageType">
<xs:sequence>
- <xs:element name="TestSuite" type="testSuiteType"/>
+ <xs:element name="TestSuite" type="testSuiteType" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="appPackageName" type="xs:string"/>
<xs:attribute name="digest" type="xs:hexBinary"/>
<xs:attribute name="name" type="xs:string" use="required"/>
+ <xs:attribute name="signatureCheck" type="xs:boolean" />
</xs:complexType>
<xs:complexType name="testSuiteType">
diff --git a/tools/tradefed-host/Android.mk b/tools/tradefed-host/Android.mk
index c1e5c54..ceec5db 100644
--- a/tools/tradefed-host/Android.mk
+++ b/tools/tradefed-host/Android.mk
@@ -18,7 +18,7 @@
# Only compile source java files in this lib.
LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_JAVA_RESOURCE_DIRS := res
+LOCAL_JAVA_RESOURCE_DIRS := res ../host/src/res
LOCAL_MODULE := cts-tradefed
LOCAL_MODULE_TAGS := optional
diff --git a/tools/tradefed-host/README b/tools/tradefed-host/README
new file mode 100644
index 0000000..602ddd5
--- /dev/null
+++ b/tools/tradefed-host/README
@@ -0,0 +1,91 @@
+CTS Trade Federation
+---------------------
+
+CTS Trade Federation, cts-tradefed for short, is an early look of the next
+generation test harness for CTS.
+
+cts-tradefed is built on top of the Android Trade Federation test harness.
+
+It works in a similar manner to the existing CTS harness, but supports some
+advanced features such as:
+
+ - modular, flexible extensible design. cts-tradefed can be extended to
+support running CTS in a continuous test environment.
+ - supports sharding a CTS test run across multiple devices in parallel
+ - automatically continue a CTS test run on another device if connection
+is lost
+
+However, note the cts-tradefed is currently experimental, and should not
+be used to generate official CTS compatibility reports. Please see
+'Known issues' section for more details.
+
+Configuring cts-tradefed
+------------------------
+
+1. Ensure 'adb' is in your current PATH. adb can be found in the
+Android SDK available from http://developer.android.com
+
+Example:
+ PATH=$PATH:/home/myuser/android-sdk-linux_x86/platform-tools
+
+2. Follow the 'Setting up your device' steps documented in the
+CTS User Manual. The CTS User Manual can be downloaded at
+http://source.android.com/compatibility/downloads.html
+
+3. Connect the device to the host machine.
+
+4. Ensure device is visible via 'adb devices'
+
+Using cts-tradefed
+-------------------
+
+To run a test plan on a single device:
+
+1. Make sure you have at least one device connected
+2. Launch the cts-tradefed console by running the 'cts-tradefed' script at
+android-cts/tools/cts-tradefed
+3. Type:
+'run command --plan CTS cts' to run the default CTS plan
+
+Some other useful commands are
+
+To run a test package:
+'run command --package <packagename> cts'
+
+To run a test class:
+'run command --class <full test class name> cts'
+
+To shard a plan test run on multiple devices
+'run command --plan CTS --shards <number of shards> cts
+note: all connected devices must be running the same build
+
+For more options:
+'run command --help cts'
+
+Known issues and missing features
+----------------------------------
+- missing support for listing packages and plans (coming soon)
+- missing support for reporting incomplete tests
+- missing support for resuming previous test runs
+- logging to be improved
+
+CTS Tradefed Development
+------------------------
+See http://source.android.com for instructions on obtaining the Android
+platform source code and setting up a build environment.
+
+The source for the CTS extensions for tradefed can be found at
+<android source root>/cts/tools/tradefed-host
+
+The source for the tradefed framework itself can be found at
+<android source root>/tools/tradefederation
+
+Perform these steps to build and run cts-tradefed from the development
+environment:
+cd <path to android source root>
+make cts
+cts-tradefed
+
+More documentation and details on using and extending trade federation will
+be forthcoming in the near future.
+
diff --git a/tools/tradefed-host/etc/Android.mk b/tools/tradefed-host/etc/Android.mk
new file mode 100644
index 0000000..f3bee3f
--- /dev/null
+++ b/tools/tradefed-host/etc/Android.mk
@@ -0,0 +1,22 @@
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_PREBUILT_EXECUTABLES := cts-tradefed
+include $(BUILD_HOST_PREBUILT)
+
diff --git a/tools/tradefed-host/etc/cts-tradefed b/tools/tradefed-host/etc/cts-tradefed
new file mode 100755
index 0000000..0ca361a
--- /dev/null
+++ b/tools/tradefed-host/etc/cts-tradefed
@@ -0,0 +1,76 @@
+#!/bin/bash
+
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# launcher script for cts-tradefed harness
+# can be used from an Android build environment, or a standalone cts zip
+
+checkFile() {
+ if [ ! -f "$1" ]; then
+ echo "Unable to locate $1"
+ exit
+ fi;
+}
+
+checkPath() {
+ if ! type -P $1 &> /dev/null; then
+ echo "Unable to find $1 in path."
+ exit
+ fi;
+}
+
+checkPath adb
+checkPath java
+
+# check java version
+JAVA_VERSION=$(java -version 2>&1 | head -n 1 | grep '[ "]1\.6[\. "$$]')
+if [ "${JAVA_VERSION}" == "" ]; then
+ echo "Wrong java version. 1.6 is required."
+ exit
+fi
+
+# check if in Android build env
+if [ ! -z ${ANDROID_BUILD_TOP} ]; then
+ HOST=`uname`
+ if [ "$HOST" == "Linux" ]; then
+ OS="linux-x86"
+ elif [ "$HOST" == "Darwin" ]; then
+ OS="darwin-x86"
+ else
+ echo "Unrecognized OS"
+ exit
+ fi;
+ CTS_ROOT=${ANDROID_BUILD_TOP}/out/host/${OS}/cts
+ if [ ! -d ${CTS_ROOT} ]; then
+ echo "Could not find $CTS_ROOT in Android build environment. Try 'make cts'"
+ exit
+ fi;
+fi;
+
+if [ -z ${CTS_ROOT} ]; then
+ # assume we're in an extracted cts install
+ CTS_ROOT="$(dirname $0)/../.."
+fi;
+
+JAR_DIR=${CTS_ROOT}/android-cts/tools
+JARS="ddmlib-prebuilt.jar tradefed-prebuilt.jar hosttestlib.jar cts-tradefed.jar"
+
+for JAR in $JARS; do
+ checkFile ${JAR_DIR}/${JAR}
+ JAR_PATH=${JAR_PATH}:${JAR_DIR}/${JAR}
+done
+
+java -cp ${JAR_PATH} -DCTS_ROOT=${CTS_ROOT} com.android.cts.tradefed.command.CtsConsole "$@"
+
diff --git a/tools/tradefed-host/res/config/cts.xml b/tools/tradefed-host/res/config/cts.xml
index d98c7fb..8c9ef7d 100644
--- a/tools/tradefed-host/res/config/cts.xml
+++ b/tools/tradefed-host/res/config/cts.xml
@@ -16,10 +16,10 @@
<configuration
description="Runs a CTS plan from a pre-existing CTS installation">
- <build_provider class="com.android.cts.tradefed.targetsetup.CtsBuildProvider" />
+ <build_provider class="com.android.cts.tradefed.build.CtsBuildProvider" />
<device_recovery class="com.android.tradefed.device.WaitDeviceRecovery" />
- <target_preparer class="com.android.cts.tradefed.targetsetup.CtsSetup" />
- <test class="com.android.cts.tradefed.testtype.PlanTest" />
+ <target_preparer class="com.android.cts.tradefed.targetprep.CtsSetup" />
+ <test class="com.android.cts.tradefed.testtype.CtsTest" />
<logger class="com.android.tradefed.log.FileLogger" />
<result_reporter class="com.android.cts.tradefed.result.CtsXmlResultReporter" />
diff --git a/tools/tradefed-host/res/result/cts_result.css b/tools/tradefed-host/res/result/cts_result.css
deleted file mode 100644
index d7ce510..0000000
--- a/tools/tradefed-host/res/result/cts_result.css
+++ /dev/null
@@ -1,234 +0,0 @@
-/* Copyright (C) 2008 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- 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.
-*/
-
-body {
- font-family:arial,sans-serif;
- color:#000;
- font-size:13px;
- color:#333;
- padding:10;
- margin:10;
-}
-
-table {
- font-size:1em;
- margin:0 0 1em;
- padding:0;
- border-collapse:collapse;
- border-width:0;
- empty-cells:show;
- width: 95%;
-}
-
-/* Report logo and device name */
-#title table {
- padding:5px;
- border-width: 0px;
- margin-left:auto;
- margin-right:auto;
- vertical-align:middle;
-}
-
-/* Device and test plan summary below the title */
-#summary table {
- background-color: rgb(212, 233, 169);
- -moz-border-radius:5px;
- border-radius:5px;
- padding:5px;
- border-color: #A5C639 #A5C639 #A5C639 #A5C639;
- border-width: 0px 0px 0px 0px;
- margin-left:auto;
- margin-right:auto;
- width:80%;
-}
-
-#summary th {
- background-color: #A5C639;
- font-size:1.2em;
- height: 2em;
- width: 50%;
-}
-
-#summary td {
- border-width: 0px 0px 0px 0px;
- border-color: gray;
- border-style: inset;
- font-size:1em;
- vertical-align: top;
-}
-
-#summaryinfo table {
- background-color: rgb(212, 233, 169);
- padding:5px;
- border-width:0;
- margin-left:auto;
- margin-right:auto;
-}
-
-#summaryinfo td {
- padding:1px;
- border-width: 0px 0px 0px 0px;
- vertical-align: top;
-}
-
-/* The test summary */
-#testsummary table {
- background-color: rgb(212, 233, 169);
- padding:5px;
- border-width:1;
- border-color: #A5C639;
- margin-left:auto;
- margin-right:auto;
- width: 40%;
-}
-
-#testsummary th {
- background-color: #A5C639;
- border-width: 1px;
- border-color: gray;
- border-style: outset;
- height: 2em;
-}
-
-#testsummary td {
- border-width: 1px;
- border-color: #A5C639;
- border-style: outset;
- text-align: center;
-}
-
-/* The test details */
-#testdetail table {
- background-color: rgb(212, 233, 169);
- padding:5px;
- border-width:1;
- border-color: #A5C639;
- margin-left:auto;
- margin-right:auto;
- width: 95%;
- table-layout:fixed;
- vertical-align: top;
-}
-
-#testdetail th {
- background-color: #A5C639;
- border-width: 1px;
- border-color: gray;
- border-style: outset;
- height: 2em;
-}
-
-#testdetail td {
- border-width: 1px;
- border-color: #A5C639;
- border-style: outset;
- text-align: left;
- vertical-align: top;
- padding:1;
-}
-
-/* The test package name */
-#none table {
- border-width:0;
- border-color: white;
- background-color: white;
- text-align:left;
- border-collapse:collapse;
-}
-
-#none td {
- border-width:0;
- border-color: white;
- background-color: white;
- text-align:left;
- border-collapse:collapse;
- font-weight:bold;
-}
-
-/* Test cell details */
-td.failed {
- background-color: #FA5858;
- font-weight:bold;
- vertical-align: top;
- text-align: center;
-}
-
-td.failuredetails {
- text-align: left;
-}
-
-td.pass {
- text-align: center;
- margin-left:auto;
- margin-right:auto;
-}
-
-td.timeout, td.omitted, td.notExecuted {
- background-color: #A5C639;
- vertical-align: top;
- text-align: center;
-}
-
-td.testname {
- border-width: 1px;
- border-color: #A5C639;
- border-style: outset;
- text-align: left;
- vertical-align: top;
- padding:1;
- overflow:hidden;
-}
-
-td.testcase {
- border-width: 1px;
- border-color: #A5C639;
- border-style: outset;
- text-align: left;
- vertical-align: top;
- padding:1;
- overflow:hidden;
- font-weight:bold;
-}
-
-td.testcasespacer {
- border-width: 1px;
- border-color: #A5C639;
- border-style: outset;
- text-align: left;
- vertical-align: top;
- padding:1;
- overflow:hidden;
- font-weight:bold;
-}
-
-td.testsuite {
- border-width: 1px;
- border-color: #A5C639;
- border-style: outset;
- text-align: left;
- vertical-align: top;
- padding:1;
- overflow:hidden;
- font-weight:bold;
-}
-
-#details {
- white-space: pre-wrap; /* css-3 */
- white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
- white-space: -pre-wrap; /* Opera 4-6 */
- white-space: -o-pre-wrap; /* Opera 7 */
- word-wrap: break-word; /* Internet Explorer 5.5+ */
- overflow:auto;
-}
diff --git a/tools/tradefed-host/res/result/cts_result.xsd b/tools/tradefed-host/res/result/cts_result.xsd
deleted file mode 100644
index f2fc3a8..0000000
--- a/tools/tradefed-host/res/result/cts_result.xsd
+++ /dev/null
@@ -1,192 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
- targetNamespace="http://compatibility.android.com/cts_result/2.0"
- xmlns="http://compatibility.android.com/cts_result/2.0"
- elementFormDefault="qualified">
-
-<xs:element name="TestResult">
- <xs:complexType>
- <xs:sequence>
- <xs:element name="DeviceInfo" type="deviceInfoType"/>
- <xs:element name="HostInfo" type="hostInfoType"/>
- <xs:element name="Summary" type="summaryType"/>
- <xs:element name="TestPackage" type="testPackageType" maxOccurs="unbounded" minOccurs="1"/>
- </xs:sequence>
- <xs:attribute name="starttime" type="xs:string"/>
- <xs:attribute name="endtime" type="xs:string"/>
- <xs:attribute name="testPlan" type="xs:string"/>
- <xs:attribute name="version" type="xs:string"/>
- <xs:attribute name="profile" type="xs:string"/>
- </xs:complexType>
-</xs:element>
-
-<xs:complexType name="deviceInfoType">
- <xs:sequence>
- <xs:element name="Screen">
- <xs:complexType>
- <xs:attribute name="resolution" type="xs:string"/>
- </xs:complexType>
- </xs:element>
- <xs:element name="PhoneSubInfo">
- <xs:complexType>
- <xs:attribute name="subscriberId" type="xs:string"/>
- </xs:complexType>
- </xs:element>
- <xs:element name="BuildInfo">
- <xs:complexType>
- <xs:attribute name="Xdpi" type="xs:decimal"/>
- <xs:attribute name="Ydpi" type="xs:decimal"/>
- <xs:attribute name="androidPlatformVersion" type="xs:integer"/>
- <xs:attribute name="buildID" type="xs:string"/>
- <xs:attribute name="buildName" type="xs:string"/>
- <xs:attribute name="buildVersion" type="xs:string"/>
- <xs:attribute name="build_board" type="xs:string"/>
- <xs:attribute name="build_brand" type="xs:string"/>
- <xs:attribute name="build_device" type="xs:string"/>
- <xs:attribute name="build_fingerprint" type="xs:string"/>
- <xs:attribute name="build_model" type="xs:string"/>
- <xs:attribute name="build_type" type="xs:string"/>
- <xs:attribute name="deviceID" type="xs:string"/>
- <xs:attribute name="imei" type="xs:integer"/>
- <xs:attribute name="imsi" type="xs:integer"/>
- <xs:attribute name="keypad" type="xs:string"/>
- <xs:attribute name="locales" type="xs:string"/>
- <xs:attribute name="navigation" type="xs:string"/>
- <xs:attribute name="network" type="xs:string"/>
- <xs:attribute name="touch" type="xs:string"/>
- <xs:attribute name="openGlEsVersion" type="xs:string"/>
- <xs:attribute name="build_abi" type="xs:string"/>
- <xs:attribute name="build_abi2" type="xs:string"/>
- </xs:complexType>
- </xs:element>
- <xs:element name="FeatureInfo" type="featureInfoType"/>
- <xs:element name="ProcessInfo" type="processInfoType"/>
- </xs:sequence>
-</xs:complexType>
-
-<xs:complexType name="hostInfoType">
- <xs:sequence>
- <xs:element name="Os">
- <xs:complexType>
- <xs:attribute name="arch" type="xs:string"/>
- <xs:attribute name="name" type="xs:string"/>
- <xs:attribute name="version" type="xs:string"/>
- </xs:complexType>
- </xs:element>
- <xs:element name="Java">
- <xs:complexType>
- <xs:attribute name="name" type="xs:string"/>
- <xs:attribute name="version" type="xs:string"/>
- </xs:complexType>
- </xs:element>
- <xs:element name="Cts">
- <xs:complexType>
- <xs:sequence>
- <xs:element name="IntValue" minOccurs="0" maxOccurs="unbounded">
- <xs:complexType>
- <xs:attribute name="name" type="xs:string"/>
- <xs:attribute name="value" type="xs:integer"/>
- </xs:complexType>
- </xs:element>
- </xs:sequence>
- <xs:attribute name="version" type="xs:string"/>
- </xs:complexType>
- </xs:element>
- </xs:sequence>
- <xs:attribute name="name" type="xs:string"/>
-</xs:complexType>
-
-<xs:complexType name="featureInfoType">
- <xs:sequence>
- <xs:element name="Feature" minOccurs="0" maxOccurs="unbounded">
- <xs:complexType>
- <xs:attribute name="name" type="xs:string" />
- <xs:attribute name="type" type="xs:string" />
- <xs:attribute name="available" type="xs:string" />
- </xs:complexType>
- </xs:element>
- </xs:sequence>
-</xs:complexType>
-
-<xs:complexType name="processInfoType">
- <xs:sequence>
- <xs:element name="Process" minOccurs="0" maxOccurs="unbounded">
- <xs:complexType>
- <xs:attribute name="name" type="xs:string" />
- <xs:attribute name="uid" type="xs:integer" />
- </xs:complexType>
- </xs:element>
- </xs:sequence>
-</xs:complexType>
-
-<xs:complexType name="summaryType">
- <xs:attribute name="failed" type="xs:integer"/>
- <xs:attribute name="notExecuted" type="xs:integer"/>
- <xs:attribute name="pass" type="xs:integer"/>
- <xs:attribute name="timeout" type="xs:integer"/>
- <xs:attribute name="omitted" type="xs:integer"/>
- <xs:attribute name="total" type="xs:integer"/>
-</xs:complexType>
-
-<xs:complexType name="testPackageType">
- <xs:complexContent>
- <xs:extension base="summaryType">
- <xs:sequence>
- <xs:element name="TestCase" type="testCaseType" />
- </xs:sequence>
- <xs:attribute name="digest" type="xs:hexBinary" />
- <xs:attribute name="name" type="xs:string" use="required" />
- <xs:attribute name="runtime" type="xs:string" />
- </xs:extension>
- </xs:complexContent>
-</xs:complexType>
-
-<xs:complexType name="testCaseType">
- <xs:sequence>
- <xs:element name="Test" type="testType" minOccurs="0" maxOccurs="unbounded"/>
- </xs:sequence>
- <xs:attribute name="name" type="xs:string" use="required"/>
-</xs:complexType>
-
-<xs:complexType name="testType">
- <xs:sequence>
- <xs:element name="FailedScene" minOccurs="0" maxOccurs="1">
- <xs:complexType>
- <xs:simpleContent>
- <xs:extension base="xs:string">
- <xs:attribute name="message" type="xs:string" />
- </xs:extension>
- </xs:simpleContent>
- </xs:complexType>
- </xs:element>
- </xs:sequence>
- <xs:attribute name="name" type="xs:string" use="required"/>
- <xs:attribute name="result" type="resultType" use="required"/>
-</xs:complexType>
-
-<xs:simpleType name="resultType">
- <xs:restriction base="xs:string">
- <xs:enumeration value="pass"/>
- <xs:enumeration value="fail"/>
- <xs:enumeration value="timeout"/>
- <xs:enumeration value="notExecuted"/>
- <xs:enumeration value="omitted"/>
- </xs:restriction>
-</xs:simpleType>
-</xs:schema>
diff --git a/tools/tradefed-host/res/result/cts_result.xsl b/tools/tradefed-host/res/result/cts_result.xsl
deleted file mode 100644
index cb220e1..0000000
--- a/tools/tradefed-host/res/result/cts_result.xsl
+++ /dev/null
@@ -1,513 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2008 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- 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.
--->
-
-<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]>
-<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
-
- <xsl:template match="/">
-
- <html>
- <STYLE type="text/css">
- @import "cts_result.css";
- </STYLE>
-
- <body>
- <!-- Title of the Report -->
- <DIV id="title">
- <TABLE>
- <TR>
- <TD width="40%" align="left"><img src="logo.gif"></img></TD>
- <TD width="60%" align="left">
- <h1>Test Report for <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@build_model"/> -
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@deviceID"/>
- </h1>
- </TD>
- </TR>
- </TABLE>
- </DIV>
- <img src="newrule-green.png" align="left"></img>
-
- <br></br>
- <br></br>
-
- <!-- Header with phone and plan information -->
- <DIV id="summary">
- <TABLE width="90%" frame="none">
- <TR>
- <TH>Device Information</TH>
- <TH>Test Summary</TH>
- </TR>
-
- <TR>
- <TD>
- <!-- Device information -->
- <div id="summaryinfo">
- <TABLE width="75%">
- <TR>
- <TD class="rowtitle">Build Model</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@build_model"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Build Name</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@buildName"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Device ID</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@deviceID"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Firmware Version</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@buildVersion"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Firmware Build Number</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@buildID"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Build Fingerprint</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@build_fingerprint"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Build ABI</TD>
- <TD>
- <xsl:value-of
- select="TestResult/DeviceInfo/BuildInfo/@build_abi"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Build ABI2</TD>
- <TD>
- <xsl:value-of
- select="TestResult/DeviceInfo/BuildInfo/@build_abi2"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Android Platform Version</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@androidPlatformVersion"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Supported Locales</TD>
- <TD>
- <xsl:call-template name="formatDelimitedString">
- <xsl:with-param name="string" select="TestResult/DeviceInfo/BuildInfo/@locales"/>
- </xsl:call-template>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Screen size</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/Screen/@resolution"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Phone number</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/PhoneSubInfo/@subscriberId"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">x dpi</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@Xdpi"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">y dpi</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@Ydpi"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Touch</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@touch"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Navigation</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@navigation"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Keypad</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@keypad"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Network</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@network"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">IMEI</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@imei"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">IMSI</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@imsi"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Open GL ES Version</TD>
- <TD>
- <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@openGlEsVersion"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Features</TD>
- <TD>
- <xsl:for-each select="TestResult/DeviceInfo/FeatureInfo/Feature[@type='sdk']">
- <xsl:text>[</xsl:text>
- <xsl:choose>
- <xsl:when test="@available = 'true'">
- <xsl:text>X</xsl:text>
- </xsl:when>
- <xsl:otherwise>
- <xsl:text>_</xsl:text>
- </xsl:otherwise>
- </xsl:choose>
- <xsl:text>] </xsl:text>
-
- <xsl:value-of select="@name" />
- <br />
- </xsl:for-each>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Other Features</TD>
- <TD>
- <UL>
- <xsl:for-each select="TestResult/DeviceInfo/FeatureInfo/Feature[@type='other']">
- <LI><xsl:value-of select="@name" /></LI>
- </xsl:for-each>
- </UL>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Root Processes</TD>
- <TD>
- <UL>
- <xsl:for-each select="TestResult/DeviceInfo/ProcessInfo/Process[@uid='0']">
- <LI><xsl:value-of select="@name" /></LI>
- </xsl:for-each>
- </UL>
- </TD>
- </TR>
- </TABLE>
- </div>
- </TD>
-
- <!-- plan information -->
- <TD>
- <div id="summaryinfo">
- <TABLE width="75%">
- <TR>
- <TD class="rowtitle">CTS version</TD>
- <TD>
- <xsl:value-of select="TestResult/HostInfo/Cts/@version"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Test timeout</TD>
- <TD>
- <xsl:value-of select="TestResult/HostInfo/Cts/IntValue[@name='testStatusTimeoutMs']/@value" /> ms
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Host Info</TD>
- <TD>
- <xsl:value-of select="TestResult/HostInfo/@name"/>
- (<xsl:value-of select="TestResult/HostInfo/Os/@name"/> -
- <xsl:value-of select="TestResult/HostInfo/Os/@version"/>)
- </TD>
- </TR>
- <TR><TD><BR></BR></TD><TD></TD></TR>
- <TR>
- <TD class="rowtitle">Plan name</TD>
- <TD>
- <xsl:value-of select="TestResult/@testPlan"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Profile</TD>
- <TD>
- <xsl:value-of select="TestResult/@profile"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Start time</TD>
- <TD>
- <xsl:value-of select="TestResult/@starttime"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">End time</TD>
- <TD>
- <xsl:value-of select="TestResult/@endtime"/>
- </TD>
- </TR>
-
- <!-- Test Summary -->
- <TR><TD><BR></BR></TD><TD></TD></TR>
- <TR>
- <TD class="rowtitle">Tests Passed</TD>
- <TD>
- <xsl:value-of select="TestResult/Summary/@pass"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Tests Failed</TD>
- <TD>
- <xsl:value-of select="TestResult/Summary/@failed"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Tests Timed out</TD>
- <TD>
- <xsl:value-of select="TestResult/Summary/@timeout"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Tests Omitted</TD>
- <TD>
- <xsl:value-of select="TestResult/Summary/@omitted"/>
- </TD>
- </TR>
- <TR>
- <TD class="rowtitle">Tests Not Executed</TD>
- <TD>
- <xsl:value-of select="TestResult/Summary/@notExecuted"/>
- </TD>
- </TR>
- </TABLE>
- </div>
- </TD>
- </TR>
- </TABLE>
- </DIV>
-
- <!-- High level summary of test execution -->
- <h2 align="center">Test Summary by Package</h2>
- <DIV id="testsummary">
- <TABLE>
- <TR>
- <TH>Test Package</TH>
- <TH>Passed</TH>
- <TH>Failed</TH>
- <TH>Timed Out</TH>
- <TH>Total Tests</TH>
- </TR>
- <xsl:for-each select="TestResult/TestPackage">
- <TR>
- <TD>
- <xsl:variable name="href"><xsl:value-of select="@name"/></xsl:variable>
- <a href="#{$href}"><xsl:value-of select="@name"/></a>
- </TD>
- <TD>
- <xsl:value-of select="@pass"/>
- </TD>
- <TD>
- <xsl:value-of select="@failed"/>
- </TD>
- <TD>
- <xsl:value-of select="@timeout"/>
- </TD>
- <TD>
- <xsl:value-of select="@total"/>
- </TD>
- </TR>
- </xsl:for-each> <!-- end package -->
- </TABLE>
- </DIV>
-
- <!-- Details of all the executed tests -->
- <h2 align="center">Detailed Test Report</h2>
-
- <!-- test package -->
- <DIV id="testdetail">
- <xsl:for-each select="TestResult/TestPackage">
- <DIV id="none">
- <TABLE>
- <TR>
- <TD class="none" align="left">
- <xsl:variable name="href"><xsl:value-of select="@name"/></xsl:variable>
- <a name="{$href}">Compatibility Test Package: <xsl:value-of select="@name"/></a>
- </TD>
- </TR>
- </TABLE>
- </DIV>
-
- <TABLE>
- <TR>
- <TH width="25%">Test</TH>
- <TH width="7%">Result</TH>
- <TH width="68%">Failure Details</TH>
- </TR>
-
- <!-- test case -->
- <xsl:for-each select="TestCase">
-
- <!-- emit a blank row before every test suite name -->
- <xsl:if test="position()!=1">
- <TR> <TD class="testcasespacer" colspan="3"></TD> </TR>
- </xsl:if>
-
-
- <TR>
- <TD class="testcase" colspan="3">
- <xsl:value-of select="@name"/>
- </TD>
- </TR>
-
- <!-- test -->
- <xsl:for-each select="Test">
- <TR>
- <TD class="testname"> -- <xsl:value-of select="@name"/></TD>
-
- <!-- test results -->
- <xsl:choose>
- <xsl:when test="string(@KnownFailure)">
- <!-- "pass" indicates the that test actually passed (results have been inverted already) -->
- <xsl:if test="@result='pass'">
- <TD class="pass">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- known problem
- </div>
- </TD>
- <TD class="failuredetails"></TD>
- </xsl:if>
-
- <!-- "fail" indicates that a known failure actually passed (results have been inverted already) -->
- <xsl:if test="@result='fail'">
- <TD class="failed">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- <xsl:value-of select="@result"/>
- </div>
- </TD>
- <TD class="failuredetails">
- <div id="details">
- A test that was a known failure actually passed. Please check.
- </div>
- </TD>
- </xsl:if>
- </xsl:when>
-
- <xsl:otherwise>
- <xsl:if test="@result='pass'">
- <TD class="pass">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- <xsl:value-of select="@result"/>
- </div>
- </TD>
- <TD class="failuredetails"></TD>
- </xsl:if>
-
- <xsl:if test="@result='fail'">
- <TD class="failed">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- <xsl:value-of select="@result"/>
- </div>
- </TD>
- <TD class="failuredetails">
- <div id="details">
- <xsl:value-of select="FailedScene/@message"/>
- </div>
- </TD>
- </xsl:if>
-
- <xsl:if test="@result='timeout'">
- <TD class="timeout">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- <xsl:value-of select="@result"/>
- </div>
- <TD class="failuredetails"></TD>
- </TD>
- </xsl:if>
-
- <xsl:if test="@result='omitted'">
- <TD class="omitted">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- <xsl:value-of select="@result"/>
- </div>
- </TD>
- <TD class="failuredetails"></TD>
- </xsl:if>
-
- <xsl:if test="@result='notExecuted'">
- <TD class="notExecuted">
- <div style="text-align: center; margin-left:auto; margin-right:auto;">
- <xsl:value-of select="@result"/>
- </div>
- </TD>
- <TD class="failuredetails"></TD>
- </xsl:if>
- </xsl:otherwise>
- </xsl:choose>
- </TR> <!-- finished with a row -->
- </xsl:for-each> <!-- end test -->
- </xsl:for-each> <!-- end test case -->
- </TABLE>
- </xsl:for-each> <!-- end test package -->
- </DIV>
- </body>
- </html>
- </xsl:template>
-
- <!-- Take a delimited string and insert line breaks after a some number of elements. -->
- <xsl:template name="formatDelimitedString">
- <xsl:param name="string" />
- <xsl:param name="numTokensPerRow" select="10" />
- <xsl:param name="tokenIndex" select="1" />
- <xsl:if test="$string">
- <!-- Requires the last element to also have a delimiter after it. -->
- <xsl:variable name="token" select="substring-before($string, ';')" />
- <xsl:value-of select="$token" />
- <xsl:text> </xsl:text>
-
- <xsl:if test="$tokenIndex mod $numTokensPerRow = 0">
- <br />
- </xsl:if>
-
- <xsl:call-template name="formatDelimitedString">
- <xsl:with-param name="string" select="substring-after($string, ';')" />
- <xsl:with-param name="numTokensPerRow" select="$numTokensPerRow" />
- <xsl:with-param name="tokenIndex" select="$tokenIndex + 1" />
- </xsl:call-template>
- </xsl:if>
- </xsl:template>
-
-</xsl:stylesheet>
diff --git a/tools/tradefed-host/res/result/logo.gif b/tools/tradefed-host/res/result/logo.gif
deleted file mode 100644
index 61970b3..0000000
--- a/tools/tradefed-host/res/result/logo.gif
+++ /dev/null
Binary files differ
diff --git a/tools/tradefed-host/res/result/newrule-green.png b/tools/tradefed-host/res/result/newrule-green.png
deleted file mode 100644
index 10a4194..0000000
--- a/tools/tradefed-host/res/result/newrule-green.png
+++ /dev/null
Binary files differ
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildHelper.java b/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildHelper.java
similarity index 68%
rename from tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildHelper.java
rename to tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildHelper.java
index 9597109..4a2d56c 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildHelper.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildHelper.java
@@ -14,7 +14,9 @@
* limitations under the License.
*/
-package com.android.cts.tradefed.targetsetup;
+package com.android.cts.tradefed.build;
+
+import com.android.tradefed.build.IFolderBuildInfo;
import java.io.File;
import java.io.FileNotFoundException;
@@ -37,15 +39,21 @@
*
* @param rootDir the parent folder that contains the "android-cts" directory and all its
* contents.
- * @throws FileNotFoundException if file does not exist
*/
- public CtsBuildHelper(File rootDir) throws FileNotFoundException {
+ public CtsBuildHelper(File rootDir) {
mRootDir = rootDir;
mCtsDir = new File(mRootDir, CTS_DIR_NAME);
- if (!mCtsDir.exists()) {
- throw new FileNotFoundException(String.format(
- "CTS install folder %s does not exist", mCtsDir.getAbsolutePath()));
- }
+ }
+
+ /**
+ * Alternate {@link CtsBuildHelper} constructor that takes the {@link IFolderBuildInfo}
+ * representation of a CTS build.
+ *
+ * @param build the {@link IFolderBuildInfo}
+ * @throws FileNotFoundException
+ */
+ public CtsBuildHelper(IFolderBuildInfo build) throws FileNotFoundException {
+ this(build.getRootDir());
}
/**
@@ -88,27 +96,36 @@
/**
* @return a {@link File} representing the test cases directory
- * @throws FileNotFoundException if dir does not exist
*/
- public File getTestCasesDir() throws FileNotFoundException {
- File dir = new File(getRepositoryDir(), "testcases");
- if (!dir.exists()) {
- throw new FileNotFoundException(String.format(
- "CTS test cases directory %s does not exist", dir.getAbsolutePath()));
- }
- return dir;
+ public File getTestCasesDir() {
+ return new File(getRepositoryDir(), "testcases");
}
/**
* @return a {@link File} representing the test plan directory
- * @throws FileNotFoundException if dir does not exist
*/
public File getTestPlansDir() throws FileNotFoundException {
- File dir = new File(getRepositoryDir(), "plans");
- if (!dir.exists()) {
+ return new File(getRepositoryDir(), "plans");
+ }
+
+ /**
+ * Check the validity of the CTS build file system structure.
+ * @throws FileNotFoundException if any major directories are missing
+ */
+ public void validateStructure() throws FileNotFoundException {
+ if (!getCtsDir().exists()) {
throw new FileNotFoundException(String.format(
- "CTS test plans directory %s does not exist", dir.getAbsolutePath()));
+ "CTS install folder %s does not exist", getCtsDir().getAbsolutePath()));
}
- return dir;
+ if (!getTestCasesDir().exists()) {
+ throw new FileNotFoundException(String.format(
+ "CTS test cases folder %s does not exist",
+ getTestCasesDir().getAbsolutePath()));
+ }
+ if (!getTestPlansDir().exists()) {
+ throw new FileNotFoundException(String.format(
+ "CTS test plans folder %s does not exist",
+ getTestPlansDir().getAbsolutePath()));
+ }
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java b/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java
similarity index 66%
rename from tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java
rename to tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java
index 90fb8ba..8d72cb5 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java
@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.cts.tradefed.targetsetup;
+package com.android.cts.tradefed.build;
+import com.android.tradefed.build.BuildRetrievalError;
+import com.android.tradefed.build.FolderBuildInfo;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.IBuildProvider;
+import com.android.tradefed.build.IFolderBuildInfo;
import com.android.tradefed.config.Option;
-import com.android.tradefed.targetsetup.FolderBuildInfo;
-import com.android.tradefed.targetsetup.IBuildInfo;
-import com.android.tradefed.targetsetup.IBuildProvider;
-import com.android.tradefed.targetsetup.IFolderBuildInfo;
-import com.android.tradefed.targetsetup.TargetSetupError;
import java.io.File;
@@ -30,17 +30,17 @@
public class CtsBuildProvider implements IBuildProvider {
@Option(name="cts-install-path", description="the path to the cts installation to use")
- private File mCtsRootDir;
+ private String mCtsRootDirPath = System.getProperty("CTS_ROOT");
/**
* {@inheritDoc}
*/
- public IBuildInfo getBuild() throws TargetSetupError {
- if (mCtsRootDir == null) {
+ public IBuildInfo getBuild() throws BuildRetrievalError {
+ if (mCtsRootDirPath == null) {
throw new IllegalArgumentException("Missing --cts-install-path");
}
IFolderBuildInfo ctsBuild = new FolderBuildInfo(0, "cts", "cts");
- ctsBuild.setRootDir(mCtsRootDir);
+ ctsBuild.setRootDir(new File(mCtsRootDirPath));
return ctsBuild;
}
@@ -50,4 +50,11 @@
public void buildNotTested(IBuildInfo info) {
// ignore
}
+
+ /**
+ * {@inheritDoc}
+ */
+ public void cleanUp(IBuildInfo info) {
+ // ignore
+ }
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java b/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java
new file mode 100644
index 0000000..9c647a2
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.command;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.tradefed.testtype.ITestCaseRepo;
+import com.android.cts.tradefed.testtype.TestCaseRepo;
+import com.android.tradefed.command.Console;
+import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.RegexTrie;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Specialization of trade federation console that adds CTS commands to list plans and packages.
+ */
+public class CtsConsole extends Console {
+
+ private CtsBuildHelper mCtsBuild = null;
+
+
+ CtsConsole() {
+ super();
+ }
+
+ /**
+ * Adds the 'list packages' and 'list plans' commands
+ */
+ @Override
+ protected void setCustomCommands(RegexTrie<Runnable> trie, List<String> genericHelp,
+ Map<String, String> commandHelp) {
+ trie.put(new Runnable() {
+ @Override
+ public void run() {
+ CtsBuildHelper ctsBuild = getCtsBuild();
+ if (ctsBuild != null) {
+ listPlans(ctsBuild);
+ }
+ }
+ }, LIST_PATTERN, "p(?:lans)?");
+ trie.put(new Runnable() {
+ @Override
+ public void run() {
+ CtsBuildHelper ctsBuild = getCtsBuild();
+ if (ctsBuild != null) {
+ listPackages(ctsBuild);
+ }
+ }
+ }, LIST_PATTERN, "packages");
+
+ // find existing help for 'LIST_PATTERN' commands, and append these commands help
+ String listHelp = commandHelp.get(LIST_PATTERN);
+ if (listHelp == null) {
+ // no help? Unexpected, but soldier on
+ listHelp = new String();
+ }
+ String combinedHelp = String.format("%s" + LINE_SEPARATOR +
+ "\tp[lans] List all CTS test plans" + LINE_SEPARATOR +
+ "\tpackages List all CTS packages" + LINE_SEPARATOR, listHelp);
+ commandHelp.put(LIST_PATTERN, combinedHelp);
+ }
+
+ private void listPlans(CtsBuildHelper ctsBuild) {
+ FilenameFilter xmlFilter = new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".xml");
+ }
+ };
+ try {
+ for (File planFile : ctsBuild.getTestPlansDir().listFiles(xmlFilter)) {
+ printLine(FileUtil.getBaseName(planFile.getName()));
+ }
+ }
+ catch (FileNotFoundException e) {
+ printLine("Could not find CTS plan folder");
+ }
+ }
+
+ private void listPackages(CtsBuildHelper ctsBuild) {
+ ITestCaseRepo testCaseRepo = new TestCaseRepo(ctsBuild.getTestCasesDir());
+ for (String packageUri : testCaseRepo.getPackageNames()) {
+ printLine(packageUri);
+ }
+ }
+
+ private CtsBuildHelper getCtsBuild() {
+ if (mCtsBuild == null) {
+ String ctsInstallPath = System.getProperty("CTS_ROOT");
+ if (ctsInstallPath != null) {
+ mCtsBuild = new CtsBuildHelper(new File(ctsInstallPath));
+ try {
+ mCtsBuild.validateStructure();
+ } catch (FileNotFoundException e) {
+ printLine(String.format("Invalid cts install: %s", e.getMessage()));
+ mCtsBuild = null;
+ }
+ } else {
+ printLine("Could not find CTS install location: CTS_ROOT env variable not set");
+ }
+ }
+ return mCtsBuild;
+ }
+
+ public static void main(String[] args) {
+ CtsConsole console = new CtsConsole();
+ console.run(args);
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java b/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java
index b914f2e..61804e0 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java
@@ -22,7 +22,6 @@
import com.android.tradefed.testtype.InstrumentationTest;
import java.io.File;
-import java.util.List;
/**
* Collects info from device under test.
@@ -48,14 +47,14 @@
/**
* Installs and runs the device info collector instrumentation, and forwards results
- * to the <var>listeners</var>
+ * to the <var>listener</var>
*
* @param device
- * @param listeners
+ * @param listener
* @throws DeviceNotAvailableException
*/
public static void collectDeviceInfo(ITestDevice device, File testApkDir,
- List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
+ ITestInvocationListener listener) throws DeviceNotAvailableException {
File apkFile = new File(testApkDir, String.format("%s.apk", APK_NAME));
if (!apkFile.exists()) {
Log.e(LOG_TAG, String.format("Could not find %s", apkFile.getAbsolutePath()));
@@ -69,6 +68,6 @@
instrTest.setRerunMode(false);
instrTest.setPackageName(APP_PACKAGE_NAME);
instrTest.setRunnerName(INSTRUMENTATION_NAME);
- instrTest.run(listeners);
+ instrTest.run(listener);
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
index 4c29b01..1c90d83 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
@@ -16,19 +16,19 @@
package com.android.cts.tradefed.result;
+import com.android.cts.tradefed.build.CtsBuildHelper;
import com.android.cts.tradefed.device.DeviceInfoCollector;
-import com.android.cts.tradefed.targetsetup.CtsBuildHelper;
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.IFolderBuildInfo;
import com.android.tradefed.config.Option;
import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.result.InputStreamSource;
import com.android.tradefed.result.LogDataType;
import com.android.tradefed.result.TestResult;
import com.android.tradefed.result.TestRunResult;
-import com.android.tradefed.result.TestResult.TestStatus;
-import com.android.tradefed.targetsetup.IBuildInfo;
-import com.android.tradefed.targetsetup.IFolderBuildInfo;
import com.android.tradefed.util.FileUtil;
import org.kxml2.io.KXmlSerializer;
@@ -44,7 +44,6 @@
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -60,15 +59,14 @@
private static final String LOG_TAG = "CtsXmlResultReporter";
private static final String TEST_RESULT_FILE_NAME = "testResult.xml";
- private static final String CTS_RESULT_FILE_VERSION = "2.0";
+ private static final String CTS_RESULT_FILE_VERSION = "1.10";
private static final String CTS_VERSION = "99";
-
private static final String[] CTS_RESULT_RESOURCES = {"cts_result.xsl", "cts_result.css",
"logo.gif", "newrule-green.png"};
/** the XML namespace */
- private static final String ns = null;
+ static final String ns = null;
private static final String REPORT_DIR_NAME = "output-file-path";
@Option(name=REPORT_DIR_NAME, description="root file system path to directory to store xml " +
@@ -80,6 +78,8 @@
private String mStartTime;
+ private String mReportPath = "";
+
public void setReportDir(File reportDir) {
mReportDir = reportDir;
}
@@ -94,13 +94,14 @@
if (!(buildInfo instanceof IFolderBuildInfo)) {
throw new IllegalArgumentException("build info is not a IFolderBuildInfo");
}
+
IFolderBuildInfo ctsBuild = (IFolderBuildInfo)buildInfo;
try {
CtsBuildHelper buildHelper = new CtsBuildHelper(ctsBuild.getRootDir());
+ buildHelper.validateStructure();
mReportDir = buildHelper.getResultsDir();
-
} catch (FileNotFoundException e) {
- throw new IllegalArgumentException("unrecognized cts structure", e);
+ throw new IllegalArgumentException("Invalid CTS build", e);
}
}
// create a unique directory for saving results, using old cts host convention
@@ -108,14 +109,26 @@
mReportDir = new File(mReportDir, getResultTimestamp());
mReportDir.mkdirs();
mStartTime = getTimestamp();
+ Log.logAndDisplay(LogLevel.INFO, LOG_TAG, String.format("Using ctsbuild %s",
+ mReportDir.getAbsolutePath()));
}
/**
* {@inheritDoc}
*/
@Override
- public void testLog(String dataName, LogDataType dataType, InputStream dataStream) {
- // TODO: implement this
+ public void testLog(String dataName, LogDataType dataType, InputStreamSource dataStream) {
+ // save as zip file in report dir
+ // TODO: ensure uniqueness of file name
+ // TODO: use dataType.getFileExt() when its made public
+ String fileName = String.format("%s.%s", dataName, dataType.name().toLowerCase());
+ // TODO: consider compressing large files
+ File logFile = new File(mReportDir, fileName);
+ try {
+ FileUtil.writeToFile(dataStream.createInputStream(), logFile);
+ } catch (IOException e) {
+ Log.e(LOG_TAG, String.format("Failed to write log %s", logFile.getAbsolutePath()));
+ }
}
/**
@@ -171,7 +184,7 @@
serializer.endDocument();
// TODO: output not executed timeout omitted counts
String msg = String.format("XML test result file generated at %s. Total tests %d, " +
- "Failed %d, Error %d", reportDir.getAbsolutePath(), getNumTotalTests(),
+ "Failed %d, Error %d", getReportPath(), getNumTotalTests(),
getNumFailedTests(), getNumErrorTests());
Log.logAndDisplay(LogLevel.INFO, LOG_TAG, msg);
Log.logAndDisplay(LogLevel.INFO, LOG_TAG, String.format("Time: %s",
@@ -188,6 +201,10 @@
}
}
+ private String getReportPath() {
+ return mReportPath;
+ }
+
/**
* Output the results XML.
*
@@ -201,7 +218,6 @@
serializer.startTag(ns, "TestResult");
// TODO: output test plan and profile values
serializer.attribute(ns, "testPlan", "unknown");
- serializer.attribute(ns, "profile", "unknown");
serializer.attribute(ns, "starttime", startTime);
serializer.attribute(ns, "endtime", endTime);
serializer.attribute(ns, "version", CTS_RESULT_FILE_VERSION);
@@ -387,12 +403,10 @@
serializer.startTag(ns, "Summary");
serializer.attribute(ns, "failed", Integer.toString(getNumErrorTests() +
getNumFailedTests()));
- // TODO: output notExecuted, timeout, and omitted count
+ // TODO: output notExecuted, timeout count
serializer.attribute(ns, "notExecuted", "0");
serializer.attribute(ns, "timeout", "0");
- serializer.attribute(ns, "omitted", "0");
serializer.attribute(ns, "pass", Integer.toString(getNumPassedTests()));
- serializer.attribute(ns, "total", Integer.toString(getNumTotalTests()));
serializer.endTag(ns, "Summary");
}
@@ -423,130 +437,34 @@
}
serializer.startTag(ns, "TestPackage");
serializer.attribute(ns, "name", runResult.getName());
- serializer.attribute(ns, "runTime", formatElapsedTime(runResult.getElapsedTime()));
- // TODO: generate digest
- serializer.attribute(ns, "digest", "");
- serializer.attribute(ns, "failed", Integer.toString(runResult.getNumErrorTests() +
- runResult.getNumFailedTests()));
- // TODO: output notExecuted, timeout, and omitted count
- serializer.attribute(ns, "notExecuted", "0");
- serializer.attribute(ns, "timeout", "0");
- serializer.attribute(ns, "omitted", "0");
- serializer.attribute(ns, "pass", Integer.toString(runResult.getNumPassedTests()));
- serializer.attribute(ns, "total", Integer.toString(runResult.getNumTests()));
+ serializer.attribute(ns, "appPackageName", runResult.getName());
+ serializer.attribute(ns, "digest", getMetric(runResult, "digest"));
- // the results XML needs to organize test's by class. Build a nested data structure that
- // group's the results by class name
- Map<String, Map<TestIdentifier, TestResult>> classResultsMap = buildClassNameMap(
- runResult.getTestResults());
+ // Dump the results.
- for (Map.Entry<String, Map<TestIdentifier, TestResult>> resultsEntry :
- classResultsMap.entrySet()) {
- serializer.startTag(ns, "TestCase");
- serializer.attribute(ns, "name", resultsEntry.getKey());
- serializeTests(serializer, resultsEntry.getValue());
- serializer.endTag(ns, "TestCase");
+ // organize the tests into data structures that mirror the expected xml output.
+ TestSuiteRoot suiteRoot = new TestSuiteRoot();
+ for (Map.Entry<TestIdentifier, TestResult> testEntry : runResult.getTestResults()
+ .entrySet()) {
+ suiteRoot.insertTest(testEntry.getKey(), testEntry.getValue());
}
+ suiteRoot.serialize(serializer);
serializer.endTag(ns, "TestPackage");
}
/**
- * Organizes the test run results into a format organized by class name.
- */
- private Map<String, Map<TestIdentifier, TestResult>> buildClassNameMap(
- Map<TestIdentifier, TestResult> results) {
- // use a linked hashmap to have predictable iteration order
- Map<String, Map<TestIdentifier, TestResult>> classResultMap =
- new LinkedHashMap<String, Map<TestIdentifier, TestResult>>();
- for (Map.Entry<TestIdentifier, TestResult> resultEntry : results.entrySet()) {
- String className = resultEntry.getKey().getClassName();
- Map<TestIdentifier, TestResult> resultsForClass = classResultMap.get(className);
- if (resultsForClass == null) {
- resultsForClass = new LinkedHashMap<TestIdentifier, TestResult>();
- classResultMap.put(className, resultsForClass);
- }
- resultsForClass.put(resultEntry.getKey(), resultEntry.getValue());
- }
- return classResultMap;
- }
-
- /**
- * Output XML for given map of tests their results
+ * Helper method to retrieve the metric value with given name, or blank if not found
*
- * @param serializer
- * @param results
- * @throws IOException
- */
- private void serializeTests(KXmlSerializer serializer, Map<TestIdentifier, TestResult> results)
- throws IOException {
- for (Map.Entry<TestIdentifier, TestResult> resultEntry : results.entrySet()) {
- serializeTest(serializer, resultEntry.getKey(), resultEntry.getValue());
- }
- }
-
- /**
- * Output the XML for given test and result.
- *
- * @param serializer
- * @param testId
- * @param result
- * @throws IOException
- */
- private void serializeTest(KXmlSerializer serializer, TestIdentifier testId, TestResult result)
- throws IOException {
- serializer.startTag(ns, "Test");
- serializer.attribute(ns, "name", testId.getTestName());
- serializer.attribute(ns, "result", convertStatus(result.getStatus()));
-
- if (result.getStackTrace() != null) {
- String sanitizedStack = sanitizeStackTrace(result.getStackTrace());
- serializer.startTag(ns, "FailedScene");
- serializer.attribute(ns, "message", getFailureMessageFromStackTrace(sanitizedStack));
- serializer.text(sanitizedStack);
- serializer.endTag(ns, "FailedScene");
- }
- serializer.endTag(ns, "Test");
- }
-
- /**
- * Convert a {@link TestStatus} to the result text to output in XML
- *
- * @param status the {@link TestStatus}
+ * @param runResult
+ * @param string
* @return
*/
- private String convertStatus(TestStatus status) {
- switch (status) {
- case ERROR:
- return "fail";
- case FAILURE:
- return "fail";
- case PASSED:
- return "pass";
- // TODO add notExecuted, omitted timeout
+ private String getMetric(TestRunResult runResult, String keyName) {
+ String value = runResult.getRunMetrics().get(keyName);
+ if (value == null) {
+ return "";
}
- return "omitted";
- }
-
- /**
- * Strip out any invalid XML characters that might cause the report to be unviewable.
- * http://www.w3.org/TR/REC-xml/#dt-character
- */
- private static String sanitizeStackTrace(String trace) {
- if (trace != null) {
- return trace.replaceAll("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD]", "");
- } else {
- return null;
- }
- }
-
- private static String getFailureMessageFromStackTrace(String stack) {
- // This is probably too simplistic to work in all cases, but for now, just return first
- // line of stack as failure message
- int firstNewLine = stack.indexOf('\n');
- if (firstNewLine != -1) {
- return stack.substring(0, firstNewLine);
- }
- return stack;
+ return value;
}
/**
@@ -594,11 +512,14 @@
/**
* Creates the output stream to use for test results. Exposed for mocking.
+ * @param mReportPath
*/
OutputStream createOutputResultStream(File reportDir) throws IOException {
File reportFile = new File(reportDir, TEST_RESULT_FILE_NAME);
Log.i(LOG_TAG, String.format("Created xml report file at %s",
reportFile.getAbsolutePath()));
+ // TODO: convert to path relative to cts root
+ mReportPath = reportFile.getAbsolutePath();
return new FileOutputStream(reportFile);
}
@@ -610,7 +531,7 @@
private void copyFormattingFiles(File resultsDir) {
for (String resultFileName : CTS_RESULT_RESOURCES) {
InputStream configStream = getClass().getResourceAsStream(
- String.format("/result/%s", resultFileName));
+ String.format("%s", resultFileName));
if (configStream != null) {
File resultFile = new File(resultsDir, resultFileName);
try {
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestCase.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestCase.java
new file mode 100644
index 0000000..3fce8c4
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestCase.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.result;
+
+import com.android.tradefed.result.TestResult;
+import com.android.tradefed.result.TestResult.TestStatus;
+
+import org.kxml2.io.KXmlSerializer;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Data structure that represents a "TestCase" XML element and its children.
+ */
+class TestCase {
+
+ private final String mName;
+
+ Map<String, TestResult> mChildTestMap = new LinkedHashMap<String, TestResult>();
+
+ /**
+ * Create a {@link TestCase}
+ * @param testCaseName
+ */
+ public TestCase(String testCaseName) {
+ mName = testCaseName;
+ }
+
+ /**
+ * Inserts given test result
+ *
+ * @param testName
+ * @param testResult
+ */
+ public void insertTest(String testName, TestResult testResult) {
+ mChildTestMap.put(testName, testResult);
+ }
+
+ /**
+ * Serialize this object and all its contents to XML.
+ *
+ * @param serializer
+ * @throws IOException
+ */
+ public void serialize(KXmlSerializer serializer) throws IOException {
+ serializer.startTag(CtsXmlResultReporter.ns, "TestCase");
+ serializer.attribute(CtsXmlResultReporter.ns, "name", mName);
+ // unused
+ serializer.attribute(CtsXmlResultReporter.ns, "priority", "");
+ for (Map.Entry<String, TestResult> resultEntry: mChildTestMap.entrySet()) {
+ serializeTestResult(serializer, resultEntry.getKey(), resultEntry.getValue());
+ }
+ serializer.endTag(CtsXmlResultReporter.ns, "TestCase");
+ }
+
+ private void serializeTestResult(KXmlSerializer serializer, String name, TestResult result)
+ throws IOException {
+ serializer.startTag(CtsXmlResultReporter.ns, "Test");
+ serializer.attribute(CtsXmlResultReporter.ns, "name", name);
+ serializer.attribute(CtsXmlResultReporter.ns, "result", convertStatus(result.getStatus()));
+
+ if (result.getStackTrace() != null) {
+ String sanitizedStack = sanitizeStackTrace(result.getStackTrace());
+ serializer.startTag(CtsXmlResultReporter.ns, "FailedScene");
+ serializer.attribute(CtsXmlResultReporter.ns, "message",
+ getFailureMessageFromStackTrace(sanitizedStack));
+ serializer.text(sanitizedStack);
+ serializer.endTag(CtsXmlResultReporter.ns, "FailedScene");
+ }
+
+ serializer.endTag(CtsXmlResultReporter.ns, "Test");
+
+ }
+
+ /**
+ * Convert a {@link TestStatus} to the result text to output in XML
+ *
+ * @param status the {@link TestStatus}
+ * @return
+ */
+ private String convertStatus(TestStatus status) {
+ switch (status) {
+ case ERROR:
+ return "fail";
+ case FAILURE:
+ return "fail";
+ case PASSED:
+ return "pass";
+ // TODO add notExecuted
+ }
+ return "omitted";
+ }
+
+ /**
+ * Strip out any invalid XML characters that might cause the report to be unviewable.
+ * http://www.w3.org/TR/REC-xml/#dt-character
+ */
+ private static String sanitizeStackTrace(String trace) {
+ if (trace != null) {
+ return trace.replaceAll("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD]", "");
+ } else {
+ return null;
+ }
+ }
+
+ private static String getFailureMessageFromStackTrace(String stack) {
+ // This is probably too simplistic to work in all cases, but for now, just return first
+ // line of stack as failure message
+ int firstNewLine = stack.indexOf('\n');
+ if (firstNewLine != -1) {
+ return stack.substring(0, firstNewLine);
+ }
+ return stack;
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuite.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuite.java
new file mode 100644
index 0000000..7711740
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuite.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.result;
+
+import com.android.tradefed.result.TestResult;
+
+import org.kxml2.io.KXmlSerializer;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Data structure that represents a "TestSuite" XML element and its children.
+ */
+class TestSuite {
+
+ private final String mName;
+
+ // use linked hash map for predictable iteration order
+ Map<String, TestSuite> mChildSuiteMap = new LinkedHashMap<String, TestSuite>();
+ Map<String, TestCase> mChildTestCaseMap = new LinkedHashMap<String, TestCase>();
+
+ /**
+ * @param testSuite
+ */
+ public TestSuite(String suiteName) {
+ mName = suiteName;
+ }
+
+ /**
+ * Insert the given test result into this suite.
+ *
+ * @param suiteNames list of remaining suite names for this test
+ * @param testClassName the test class name
+ * @param testName the test method name
+ * @param testResult the {@link TestResult}
+ */
+ public void insertTest(List<String> suiteNames, String testClassName, String testName,
+ TestResult testResult) {
+ if (suiteNames.size() <= 0) {
+ // no more package segments
+ TestCase testCase = getTestCase(testClassName);
+ testCase.insertTest(testName, testResult);
+ } else {
+ String rootName = suiteNames.remove(0);
+ TestSuite suite = getTestSuite(rootName);
+ suite.insertTest(suiteNames, testClassName, testName, testResult);
+ }
+ }
+
+ /**
+ * Get the child {@link TestSuite} with given name, creating if necessary.
+ *
+ * @param suiteName
+ * @return the {@link TestSuite}
+ */
+ private TestSuite getTestSuite(String suiteName) {
+ TestSuite testSuite = mChildSuiteMap.get(suiteName);
+ if (testSuite == null) {
+ testSuite = new TestSuite(suiteName);
+ mChildSuiteMap.put(suiteName, testSuite);
+ }
+ return testSuite;
+ }
+
+ /**
+ * Get the child {@link TestCase} with given name, creating if necessary.
+ * @param testCaseName
+ * @return
+ */
+ private TestCase getTestCase(String testCaseName) {
+ TestCase testCase = mChildTestCaseMap.get(testCaseName);
+ if (testCase == null) {
+ testCase = new TestCase(testCaseName);
+ mChildTestCaseMap.put(testCaseName, testCase);
+ }
+ return testCase;
+ }
+
+ /**
+ * Serialize this object and all its contents to XML.
+ *
+ * @param serializer
+ * @throws IOException
+ */
+ public void serialize(KXmlSerializer serializer) throws IOException {
+ if (mName != null) {
+ serializer.startTag(CtsXmlResultReporter.ns, "TestSuite");
+ serializer.attribute(CtsXmlResultReporter.ns, "name", mName);
+ }
+ for (TestSuite childSuite : mChildSuiteMap.values()) {
+ childSuite.serialize(serializer);
+ }
+ for (TestCase childCase : mChildTestCaseMap.values()) {
+ childCase.serialize(serializer);
+ }
+ if (mName != null) {
+ serializer.endTag(CtsXmlResultReporter.ns, "TestSuite");
+ }
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuiteRoot.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuiteRoot.java
new file mode 100644
index 0000000..bb0b0fb
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuiteRoot.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.result;
+
+import com.android.ddmlib.Log;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.result.TestResult;
+
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Helper class for converting test results into the CTS XML serialization format.
+ * <p/>
+ * A TestIdentifier with name "com.example.ExampleTest#testExample will get serialized as the
+ * following XML
+ * <pre>
+ * TestSuite name="com"
+ * TestSuite name ="example"
+ * TestCase name = "ExampleTest"
+ * Test name="testExample"
+ * </pre>
+ */
+class TestSuiteRoot extends TestSuite {
+
+ private static final String LOG_TAG = "TestSuiteRoot";
+
+ public TestSuiteRoot() {
+ super(null);
+ }
+
+ /**
+ * Insert the given test result.
+ *
+ * @param testId
+ * @param testResult
+ */
+ public void insertTest(TestIdentifier testId, TestResult testResult) {
+ List<String> classNameSegments = new LinkedList<String>();
+ classNameSegments.addAll(Arrays.asList(testId.getClassName().split("\\.")));
+ if (classNameSegments.size() <= 0) {
+ Log.e(LOG_TAG, String.format("Unrecognized package name format for test class '%s'",
+ testId.getClassName()));
+ } else {
+ String testCaseName = classNameSegments.remove(classNameSegments.size()-1);
+ insertTest(classNameSegments, testCaseName, testId.getTestName(), testResult);
+ }
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsRootDeviceSetup.java b/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/CtsRootDeviceSetup.java
similarity index 89%
rename from tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsRootDeviceSetup.java
rename to tools/tradefed-host/src/com/android/cts/tradefed/targetprep/CtsRootDeviceSetup.java
index 589bed3..fe7dd4a 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsRootDeviceSetup.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/CtsRootDeviceSetup.java
@@ -13,17 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.cts.tradefed.targetsetup;
+package com.android.cts.tradefed.targetprep;
+import com.android.cts.tradefed.build.CtsBuildHelper;
import com.android.ddmlib.Log;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.IFolderBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.targetsetup.BuildError;
-import com.android.tradefed.targetsetup.DeviceSetup;
-import com.android.tradefed.targetsetup.IBuildInfo;
-import com.android.tradefed.targetsetup.IFolderBuildInfo;
-import com.android.tradefed.targetsetup.ITargetPreparer;
-import com.android.tradefed.targetsetup.TargetSetupError;
+import com.android.tradefed.targetprep.BuildError;
+import com.android.tradefed.targetprep.DeviceSetup;
+import com.android.tradefed.targetprep.ITargetPreparer;
+import com.android.tradefed.targetprep.TargetSetupError;
import java.io.FileNotFoundException;
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java b/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/CtsSetup.java
similarity index 69%
rename from tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java
rename to tools/tradefed-host/src/com/android/cts/tradefed/targetprep/CtsSetup.java
index 77b4656..7d952a3 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/CtsSetup.java
@@ -13,19 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.cts.tradefed.targetsetup;
+package com.android.cts.tradefed.targetprep;
-import com.android.cts.tradefed.testtype.PlanTest;
-import com.android.tradefed.config.ConfigurationException;
-import com.android.tradefed.config.IConfiguration;
-import com.android.tradefed.config.IConfigurationReceiver;
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.IFolderBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.targetsetup.BuildError;
-import com.android.tradefed.targetsetup.IBuildInfo;
-import com.android.tradefed.targetsetup.IFolderBuildInfo;
-import com.android.tradefed.targetsetup.ITargetPreparer;
-import com.android.tradefed.targetsetup.TargetSetupError;
+import com.android.tradefed.targetprep.BuildError;
+import com.android.tradefed.targetprep.ITargetPreparer;
+import com.android.tradefed.targetprep.TargetSetupError;
import java.io.File;
import java.io.FileNotFoundException;
@@ -35,14 +32,12 @@
* <p/>
* All the actions performed in this class must work on a production device.
*/
-public class CtsSetup implements ITargetPreparer, IConfigurationReceiver {
+public class CtsSetup implements ITargetPreparer {
private static final String RUNNER_APK_NAME = "android.core.tests.runner.apk";
// TODO: read this from configuration file rather than hardcoding
private static final String TEST_STUBS_APK = "CtsTestStubs.apk";
- private IConfiguration mConfiguration = null;
-
/**
* Factory method to create a {@link CtsBuildHelper}.
* <p/>
@@ -55,34 +50,17 @@
/**
* {@inheritDoc}
*/
- public void setConfiguration(IConfiguration configuration) {
- mConfiguration = configuration;
- }
-
- /**
- * {@inheritDoc}
- */
public void setUp(ITestDevice device, IBuildInfo buildInfo) throws TargetSetupError,
BuildError, DeviceNotAvailableException {
if (!(buildInfo instanceof IFolderBuildInfo)) {
throw new IllegalArgumentException("Provided buildInfo is not a IFolderBuildInfo");
}
- if (mConfiguration == null) {
- throw new IllegalStateException("setConfiguration() was not called before setUp");
- }
IFolderBuildInfo ctsBuildInfo = (IFolderBuildInfo)buildInfo;
try {
CtsBuildHelper buildHelper = createBuildHelper(ctsBuildInfo.getRootDir());
- // pass necessary build information to the other config objects
- mConfiguration.injectOptionValue(PlanTest.TEST_CASES_DIR_OPTION,
- buildHelper.getTestCasesDir().getAbsolutePath());
- mConfiguration.injectOptionValue(PlanTest.TEST_PLANS_DIR_OPTION,
- buildHelper.getTestPlansDir().getAbsolutePath());
installCtsPrereqs(device, buildHelper);
} catch (FileNotFoundException e) {
throw new TargetSetupError("Invalid CTS installation", e);
- } catch (ConfigurationException e) {
- throw new TargetSetupError("Failed to set repository directory options", e);
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
new file mode 100644
index 0000000..2834793
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
@@ -0,0 +1,465 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.tradefed.testtype;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.tradefed.device.DeviceInfoCollector;
+import com.android.ddmlib.Log;
+import com.android.ddmlib.Log.LogLevel;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.IFolderBuildInfo;
+import com.android.tradefed.config.Option;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.testtype.IDeviceTest;
+import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.testtype.IResumableTest;
+import com.android.tradefed.testtype.IShardableTest;
+import com.android.tradefed.testtype.InstrumentationTest;
+import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+import java.util.Set;
+
+import junit.framework.Test;
+
+/**
+ * A {@link Test} for running CTS tests.
+ * <p/>
+ * Supports running all the tests contained in a CTS plan, or individual test packages.
+ */
+public class CtsTest implements IDeviceTest, IResumableTest, IShardableTest, IBuildReceiver {
+
+ private static final String LOG_TAG = "CtsTest";
+
+ private static final String PLAN_OPTION = "plan";
+ private static final String PACKAGE_OPTION = "package";
+ private static final String CLASS_OPTION = "class";
+ private static final String METHOD_OPTION = "method";
+
+ private ITestDevice mDevice;
+
+ @Option(name = PLAN_OPTION, description = "the test plan to run")
+ private String mPlanName = null;
+
+ @Option(name = PACKAGE_OPTION, description = "the test packages(s) to run")
+ private Collection<String> mPackageNames = new ArrayList<String>();
+
+ @Option(name = "exclude-package", description = "the test packages(s) to exclude from the run")
+ private Collection<String> mExcludedPackageNames = new ArrayList<String>();
+
+ @Option(name = CLASS_OPTION, shortName = 'c', description = "run a specific test class")
+ private String mClassName = null;
+
+ @Option(name = METHOD_OPTION, shortName = 'm',
+ description = "run a specific test method, from given --class")
+ private String mMethodName = null;
+
+ @Option(name = "collect-device-info", description =
+ "flag to control whether to collect info from device. Default true")
+ private boolean mCollectDeviceInfo = true;
+
+ @Option(name = "resume", description =
+ "flag to attempt to automatically resume aborted test run on another connected device. " +
+ "Default false.")
+ private boolean mResume = false;
+
+ @Option(name = "shards", description =
+ "shard the tests to run into separately runnable chunks to execute on multiple devices " +
+ "concurrently")
+ private int mShards = 1;
+
+ /** data structure for a {@link IRemoteTest} and its known tests */
+ private class KnownTests {
+ private final IRemoteTest mTestForPackage;
+ private final Collection<TestIdentifier> mKnownTests;
+
+ KnownTests(IRemoteTest testForPackage, Collection<TestIdentifier> knownTests) {
+ mTestForPackage = testForPackage;
+ mKnownTests = knownTests;
+ }
+
+ IRemoteTest getTestForPackage() {
+ return mTestForPackage;
+ }
+
+ Collection<TestIdentifier> getKnownTests() {
+ return mKnownTests;
+ }
+ }
+
+ /** list of remaining tests to execute */
+ private List<KnownTests> mRemainingTests = null;
+
+ private CtsBuildHelper mCtsBuild = null;
+
+ /**
+ * {@inheritDoc}
+ */
+ public ITestDevice getDevice() {
+ return mDevice;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void setDevice(ITestDevice device) {
+ mDevice = device;
+ }
+
+ /**
+ * Set the plan name to run.
+ * <p/>
+ * Exposed for unit testing
+ */
+ void setPlanName(String planName) {
+ mPlanName = planName;
+ }
+
+ /**
+ * Set the collect device info flag.
+ * <p/>
+ * Exposed for unit testing
+ */
+ void setCollectDeviceInfo(boolean collectDeviceInfo) {
+ mCollectDeviceInfo = collectDeviceInfo;
+ }
+
+ /**
+ * Adds a package name to the list of test packages to run.
+ * <p/>
+ * Exposed for unit testing
+ */
+ void addPackageName(String packageName) {
+ mPackageNames.add(packageName);
+ }
+
+ /**
+ * Adds a package name to the list of test packages to exclude.
+ * <p/>
+ * Exposed for unit testing
+ */
+ void addExcludedPackageName(String packageName) {
+ mExcludedPackageNames.add(packageName);
+ }
+
+ /**
+ * Set the test class name to run.
+ * <p/>
+ * Exposed for unit testing
+ */
+ void setClassName(String className) {
+ mClassName = className;
+ }
+
+ /**
+ * Set the test method name to run.
+ * <p/>
+ * Exposed for unit testing
+ */
+ void setMethodName(String methodName) {
+ mMethodName = methodName;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isResumable() {
+ return mResume;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setBuild(IBuildInfo build) {
+ if (!(build instanceof IFolderBuildInfo)) {
+ throw new IllegalArgumentException(String.format(
+ "Wrong build type. Expected %s, received %s", IFolderBuildInfo.class.getName(),
+ build.getClass().getName()));
+ }
+ try {
+ mCtsBuild = new CtsBuildHelper((IFolderBuildInfo)build);
+ mCtsBuild.validateStructure();
+ } catch (FileNotFoundException e) {
+ throw new IllegalArgumentException("Invalid CTS build provided.", e);
+ }
+ }
+
+ /**
+ * Set the CTS build container.
+ * <p/>
+ * Exposed so unit tests can mock the provided build.
+ *
+ * @param buildHelper
+ */
+ void setBuildHelper(CtsBuildHelper buildHelper) {
+ mCtsBuild = buildHelper;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
+ if (getDevice() == null) {
+ throw new IllegalArgumentException("missing device");
+ }
+
+ if (mRemainingTests == null) {
+ checkFields();
+ mRemainingTests = buildTestsToRun();
+ }
+ // always collect the device info, even for resumed runs, since test will likely be running
+ // on a different device
+ collectDeviceInfo(getDevice(), mCtsBuild, listener);
+
+ while (!mRemainingTests.isEmpty()) {
+ KnownTests testPair = mRemainingTests.get(0);
+
+ IRemoteTest test = testPair.getTestForPackage();
+ if (test instanceof IDeviceTest) {
+ ((IDeviceTest)test).setDevice(getDevice());
+ }
+ // Increment the timeout for collecting the tests.
+ // TODO: move this to testPackage.createTest() instead and only increase timeout when
+ // tests number is large.
+ if (test instanceof InstrumentationTest) {
+ ((InstrumentationTest)test).setCollectsTestsShellTimeout(10*60*1000);
+ }
+ ResultFilter filter = new ResultFilter(listener, testPair.getKnownTests());
+ test.run(filter);
+ mRemainingTests.remove(0);
+ }
+ }
+
+ /**
+ * Build the list of test packages to run
+ *
+ * @return
+ */
+ private List<KnownTests> buildTestsToRun() {
+ List<KnownTests> testList = new LinkedList<KnownTests>();
+ try {
+ ITestCaseRepo testRepo = createTestCaseRepo();
+ Collection<String> testUris = getTestPackageUrisToRun(testRepo);
+
+ for (String testUri : testUris) {
+ ITestPackageDef testPackage = testRepo.getTestPackage(testUri);
+ addTestPackage(testList, testUri, testPackage);
+ }
+ if (testList.isEmpty()) {
+ Log.logAndDisplay(LogLevel.WARN, LOG_TAG, "No tests to run");
+ }
+ } catch (FileNotFoundException e) {
+ throw new IllegalArgumentException("failed to find CTS plan file", e);
+ } catch (ParseException e) {
+ throw new IllegalArgumentException("failed to parse CTS plan file", e);
+ }
+ return testList;
+ }
+
+ /**
+ * Adds a test package to the list of packages to test
+ *
+ * @param testList
+ * @param testUri
+ * @param testPackage
+ */
+ private void addTestPackage(List<KnownTests> testList, String testUri,
+ ITestPackageDef testPackage) {
+ if (testPackage != null) {
+ IRemoteTest testForPackage = testPackage.createTest(mCtsBuild.getTestCasesDir(),
+ mClassName, mMethodName);
+ if (testForPackage != null) {
+ Collection<TestIdentifier> knownTests = testPackage.getTests();
+ testList.add(new KnownTests(testForPackage, knownTests));
+ }
+ } else {
+ Log.e(LOG_TAG, String.format("Could not find test package uri %s", testUri));
+ }
+ }
+
+ /**
+ * Return the list of test package uris to run
+ *
+ * @return the list of test package uris to run
+ * @throws ParseException
+ * @throws FileNotFoundException
+ */
+ private Collection<String> getTestPackageUrisToRun(ITestCaseRepo testRepo)
+ throws ParseException, FileNotFoundException {
+ // use LinkedHashSet to have predictable iteration order
+ Set<String> testUris = new LinkedHashSet<String>();
+ if (mPlanName != null) {
+ Log.i(LOG_TAG, String.format("Executing CTS test plan %s", mPlanName));
+ String ctsPlanRelativePath = String.format("%s.xml", mPlanName);
+ File ctsPlanFile = new File(mCtsBuild.getTestPlansDir(), ctsPlanRelativePath);
+ IPlanXmlParser parser = createXmlParser();
+ parser.parse(createXmlStream(ctsPlanFile));
+ testUris.addAll(parser.getTestUris());
+ } else if (mPackageNames.size() > 0){
+ Log.i(LOG_TAG, String.format("Executing CTS test packages %s", mPackageNames));
+ testUris.addAll(mPackageNames);
+ } else if (mClassName != null) {
+ Log.i(LOG_TAG, String.format("Executing CTS test class %s", mClassName));
+ // try to find package to run from class name
+ String packageUri = testRepo.findPackageForTest(mClassName);
+ if (packageUri != null) {
+ testUris.add(packageUri);
+ } else {
+ Log.logAndDisplay(LogLevel.WARN, LOG_TAG, String.format(
+ "Could not find package for test class %s", mClassName));
+ }
+ } else {
+ // should never get here - was checkFields() not called?
+ throw new IllegalStateException("nothing to run?");
+ }
+ testUris.removeAll(mExcludedPackageNames);
+ return testUris;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Collection<IRemoteTest> split() {
+ if (mShards <= 1) {
+ return null;
+ }
+ checkFields();
+ List<KnownTests> allTests = buildTestsToRun();
+
+ if (allTests.size() <= 1) {
+ Log.w(LOG_TAG, "no tests to shard!");
+ return null;
+ }
+
+ // treat shardQueue as a circular queue, to sequentially distribute tests among shards
+ Queue<IRemoteTest> shardQueue = new LinkedList<IRemoteTest>();
+ // don't create more shards than the number of tests we have!
+ for (int i = 0; i < mShards && i < allTests.size(); i++) {
+ CtsTest shard = new CtsTest();
+ shard.mRemainingTests = new LinkedList<KnownTests>();
+ shardQueue.add(shard);
+ }
+ while (!allTests.isEmpty()) {
+ KnownTests testPair = allTests.remove(0);
+ CtsTest shard = (CtsTest)shardQueue.poll();
+ shard.mRemainingTests.add(testPair);
+ shardQueue.add(shard);
+ }
+ return shardQueue;
+ }
+
+ /**
+ * Runs the device info collector instrumentation on device, and forwards it to test listeners
+ * as run metrics.
+ * <p/>
+ * Exposed so unit tests can mock.
+ *
+ * @param listeners
+ * @throws DeviceNotAvailableException
+ * @throws FileNotFoundException
+ */
+ void collectDeviceInfo(ITestDevice device, CtsBuildHelper ctsBuild,
+ ITestInvocationListener listener) throws DeviceNotAvailableException {
+ if (mCollectDeviceInfo) {
+ DeviceInfoCollector.collectDeviceInfo(device, ctsBuild.getTestCasesDir(), listener);
+ }
+ }
+
+ /**
+ * Factory method for creating a {@link ITestCaseRepo}.
+ * <p/>
+ * Exposed for unit testing
+ */
+ ITestCaseRepo createTestCaseRepo() {
+ return new TestCaseRepo(mCtsBuild.getTestCasesDir());
+ }
+
+ /**
+ * Factory method for creating a {@link PlanXmlParser}.
+ * <p/>
+ * Exposed for unit testing
+ */
+ IPlanXmlParser createXmlParser() {
+ return new PlanXmlParser();
+ }
+
+ /**
+ * Factory method for creating a {@link InputStream} from a plan xml file.
+ * <p/>
+ * Exposed for unit testing
+ */
+ InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
+ return new BufferedInputStream(new FileInputStream(xmlFile));
+ }
+
+ private void checkFields() {
+ // for simplicity of command line usage, make --plan, --package, and --class mutually
+ // exclusive
+ boolean mutualExclusiveArgs = xor(mPlanName != null, mPackageNames.size() > 0,
+ mClassName != null);
+
+ if (!mutualExclusiveArgs) {
+ throw new IllegalArgumentException(String.format(
+ "Ambiguous or missing arguments. " +
+ "One and only of --%s --%s(s) or --%s to run can be specified",
+ PLAN_OPTION, PACKAGE_OPTION, CLASS_OPTION));
+ }
+ if (mMethodName != null && mClassName == null) {
+ throw new IllegalArgumentException(String.format(
+ "Must specify --%s when --%s is used", CLASS_OPTION, METHOD_OPTION));
+ }
+ if (mCtsBuild == null) {
+ throw new IllegalArgumentException("missing CTS build");
+ }
+ }
+
+ /**
+ * Helper method to perform exclusive or on list of boolean arguments
+ *
+ * @param args set of booleans on which to perform exclusive or
+ * @return <code>true</code> if one and only one of <var>args</code> is <code>true</code>.
+ * Otherwise return <code>false</code>.
+ */
+ private boolean xor(boolean... args) {
+ boolean currentVal = args[0];
+ for (int i=1; i < args.length; i++) {
+ if (currentVal && args[i]) {
+ return false;
+ }
+ currentVal |= args[i];
+ }
+ return currentVal;
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java
index 18ea7cf..f3930c9 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java
@@ -16,21 +16,33 @@
package com.android.cts.tradefed.testtype;
-import com.android.tradefed.testtype.IRemoteTest;
-
import java.util.Collection;
+
/**
* Interface for accessing tests from the CTS repository.
*/
-interface ITestCaseRepo {
+public interface ITestCaseRepo {
/**
- * Gets a list of tests identified by given list of uris
+ * Get a {@link TestPackageDef} given a uri
*
- * @param testUris the string uris
- * @return a {@link Collection} of {@link IRemoteTest}
+ * @param testUri the string uris
+ * @return a {@link TestPackageDef} or <code>null</code> if the uri cannot be found in repo
*/
- public Collection<IRemoteTest> getTests(Collection<String> testUris);
+ public ITestPackageDef getTestPackage(String testUri);
+
+ /**
+ * Attempt to find the package uri for a given test class name
+ *
+ * @param testClassName the test class name
+ * @return the package uri or <code>null</code> if the package cannot be found
+ */
+ public String findPackageForTest(String testClassName);
+
+ /**
+ * Return a sorted {@link Collection} of all package names found in repo.
+ */
+ public Collection<String> getPackageNames();
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
new file mode 100644
index 0000000..e4f13b5
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.tradefed.testtype;
+
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.testtype.IRemoteTest;
+
+import java.io.File;
+import java.util.Collection;
+
+/**
+ * Container for CTS test info.
+ * <p/>
+ * Knows how to translate this info into a runnable {@link IRemoteTest}.
+ */
+interface ITestPackageDef {
+
+ /**
+ * Get the unique URI of the test package.
+ * @return the {@link String} uri
+ */
+ public String getUri();
+
+ /**
+ * Creates a runnable {@link IRemoteTest} from info stored in this definition.
+ *
+ * @param testCaseDir {@link File} representing directory of test case data
+ * @param className the test class to restrict this run to or <code>null</code> to run all tests
+ * in package
+ * @param methodName the optional test method to restrict this run to, or <code>null</code> to
+ * run all tests in class/package
+ * @return a {@link IRemoteTest} with all necessary data populated to run the test or
+ * <code>null</code> if test could not be created
+ */
+ public IRemoteTest createTest(File testCaseDir, String className, String methodName);
+
+ /**
+ * Determine if given test is defined in this package.
+ *
+ * @param testDef the {@link TestIdentifier}
+ * @return <code>true</code> if test is defined
+ */
+ public boolean isKnownTest(TestIdentifier testDef);
+
+ /**
+ * Determine if given test class is defined in this package.
+ *
+ * @param testClassName the fully qualified test class name
+ * @return <code>true</code> if test class is defined
+ */
+ public boolean isKnownTestClass(String testClassName);
+
+ /**
+ * Get the collection of tests in this test package.
+ */
+ public Collection<TestIdentifier> getTests();
+
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationAppTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationAppTest.java
new file mode 100644
index 0000000..47fc14a
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationAppTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.testtype;
+
+import com.android.ddmlib.Log;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.InstrumentationTest;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * A {@link InstrumentationTest] that will install other dependent apks before test execution,
+ * and uninstall apps on execution completion.
+ */
+public class InstrumentationAppTest extends InstrumentationTest {
+
+ private static final String LOG_TAG = "InstrumentationAppTest";
+
+ // TODO: consider moving this class to tradefed proper
+
+ private Collection<File> mInstallFiles = new ArrayList<File>();
+ private Collection<String> mInstallPackages = new ArrayList<String>();
+
+ /**
+ * Add a dependent apk to install.
+ *
+ * @param apkFile the apk file
+ * @param packageName the apk's Android package name
+ */
+ public void addInstallApp(File apkFile, String packageName) {
+ mInstallFiles.add(apkFile);
+ mInstallPackages.add(packageName);
+ }
+
+ @Override
+ public void run(final ITestInvocationListener listener)
+ throws DeviceNotAvailableException {
+ if (getDevice() == null) {
+ throw new IllegalStateException("missing device");
+ }
+ try {
+ for (File apkFile : mInstallFiles) {
+ Log.d(LOG_TAG, String.format("Installing %s on %s", apkFile.getName(),
+ getDevice().getSerialNumber()));
+ getDevice().installPackage(apkFile, true);
+ }
+ super.run(listener);
+ } finally {
+ for (String packageName : mInstallPackages) {
+ Log.d(LOG_TAG, String.format("Uninstalling %s on %s", packageName,
+ getDevice().getSerialNumber()));
+ getDevice().uninstallPackage(packageName);
+ }
+ }
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java
index 70b8432..041079d 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java
@@ -21,12 +21,11 @@
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
import com.android.tradefed.result.JUnitToInvocationResultForwarder;
-import com.android.tradefed.testtype.AbstractRemoteTest;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.util.CommandStatus;
-import com.android.tradefed.util.RunUtil;
import com.android.tradefed.util.IRunUtil.IRunnableResult;
+import com.android.tradefed.util.RunUtil;
import java.io.File;
import java.io.IOException;
@@ -34,7 +33,6 @@
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.Collections;
-import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
@@ -43,7 +41,7 @@
/**
* A {@link IRemoteTest} that can run a set of JUnit tests from a jar.
*/
-public class JarHostTest extends AbstractRemoteTest implements IDeviceTest {
+public class JarHostTest implements IDeviceTest, IRemoteTest {
private static final String LOG_TAG = "JarHostTest";
@@ -121,48 +119,27 @@
/**
* {@inheritDoc}
*/
+ @SuppressWarnings("unchecked")
@Override
- public int countTestCases() {
- if (mTests == null) {
- throw new IllegalStateException();
- }
- return mTests.size();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void run(List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
+ public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
checkFields();
Log.i(LOG_TAG, String.format("Running %s test package from jar, contains %d tests.",
- mRunName, countTestCases()));
+ mRunName, mTests.size()));
// create a junit listener to forward the JUnit test results to the
// {@link ITestInvocationListener}s
JUnitToInvocationResultForwarder resultForwarder =
- new JUnitToInvocationResultForwarder(listeners);
+ new JUnitToInvocationResultForwarder(listener);
TestResult junitResult = new TestResult();
junitResult.addListener(resultForwarder);
long startTime = System.currentTimeMillis();
- reportRunStarted(listeners);
+ listener.testRunStarted(mRunName, mTests.size());
for (TestIdentifier testId : mTests) {
Test junitTest = loadTest(testId.getClassName(), testId.getTestName());
if (junitTest != null) {
runTest(testId, junitTest, junitResult);
}
}
- reportRunEnded(System.currentTimeMillis() - startTime, listeners);
- }
-
- /**
- * Report the start of the test run.
- *
- * @param listeners
- */
- private void reportRunStarted(List<ITestInvocationListener> listeners) {
- for (ITestInvocationListener listener : listeners) {
- listener.testRunStarted(mRunName, countTestCases());
- }
+ listener.testRunEnded(System.currentTimeMillis() - startTime, Collections.EMPTY_MAP);
}
/**
@@ -198,19 +175,6 @@
}
/**
- * Report the end of the test run.
- *
- * @param elapsedTime
- * @param listeners
- */
- @SuppressWarnings("unchecked")
- private void reportRunEnded(long elapsedTime, List<ITestInvocationListener> listeners) {
- for (ITestInvocationListener listener : listeners) {
- listener.testRunEnded(elapsedTime, Collections.EMPTY_MAP);
- }
- }
-
- /**
* Load the test with given names from the jar.
*
* @param className
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PlanTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PlanTest.java
deleted file mode 100644
index 212eb66..0000000
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PlanTest.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.tradefed.testtype;
-
-import com.android.cts.tradefed.device.DeviceInfoCollector;
-import com.android.ddmlib.Log;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.testtype.AbstractRemoteTest;
-import com.android.tradefed.testtype.IDeviceTest;
-import com.android.tradefed.testtype.IRemoteTest;
-import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.List;
-
-import junit.framework.Test;
-
-/**
- * A {@link Test} that runs all the tests in the CTS test plan with given name
- */
-public class PlanTest extends AbstractRemoteTest implements IDeviceTest, IRemoteTest {
-
- private static final String LOG_TAG = "PlanTest";
-
- public static final String TEST_CASES_DIR_OPTION = "test-cases-path";
- public static final String TEST_PLANS_DIR_OPTION = "test-plans-path";
-
- private ITestDevice mDevice;
-
- @Option(name = "plan", description = "the test plan to run")
- private String mPlanName = null;
-
- @Option(name = TEST_CASES_DIR_OPTION, description =
- "file path to directory containing CTS test cases")
- private File mTestCaseDir = null;
-
- @Option(name = TEST_PLANS_DIR_OPTION, description =
- "file path to directory containing CTS test plans")
- private File mTestPlanDir = null;
-
- /**
- * {@inheritDoc}
- */
- public ITestDevice getDevice() {
- return mDevice;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDevice(ITestDevice device) {
- mDevice = device;
- }
-
- /**
- * Set the test plan directory.
- * <p/>
- * Exposed for unit testing
- */
- void setTestPlanDir(File planDir) {
- mTestPlanDir = planDir;
- }
-
- /**
- * Set the test case directory.
- * <p/>
- * Exposed for unit testing
- */
- void setTestCaseDir(File testCaseDir) {
- mTestCaseDir = testCaseDir;
- }
-
- /**
- * Set the plan name to run.
- * <p/>
- * Exposed for unit testing
- */
- void setPlanName(String planName) {
- mPlanName = planName;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
- if (mPlanName == null) {
- throw new IllegalArgumentException("missing --plan option");
- }
- if (getDevice() == null) {
- throw new IllegalArgumentException("missing device");
- }
- if (mTestCaseDir == null) {
- throw new IllegalArgumentException(String.format("missing %s option",
- TEST_CASES_DIR_OPTION));
- }
- if (mTestPlanDir == null) {
- throw new IllegalArgumentException(String.format("missing %s", TEST_PLANS_DIR_OPTION));
- }
-
- Log.i(LOG_TAG, String.format("Executing CTS test plan %s", mPlanName));
-
- try {
- String ctsPlanRelativePath = String.format("%s.xml", mPlanName);
- File ctsPlanFile = new File(mTestPlanDir, ctsPlanRelativePath);
- IPlanXmlParser parser = createXmlParser();
- parser.parse(createXmlStream(ctsPlanFile));
- Collection<String> testUris = parser.getTestUris();
- ITestCaseRepo testRepo = createTestCaseRepo();
- Collection<IRemoteTest> tests = testRepo.getTests(testUris);
- collectDeviceInfo(getDevice(), mTestCaseDir, listeners);
- for (IRemoteTest test : tests) {
- if (test instanceof IDeviceTest) {
- ((IDeviceTest)test).setDevice(getDevice());
- }
- test.run(listeners);
- }
- } catch (FileNotFoundException e) {
- throw new IllegalArgumentException("failed to find CTS plan file", e);
- } catch (ParseException e) {
- throw new IllegalArgumentException("failed to parse CTS plan file", e);
- }
- }
-
- /**
- * Runs the device info collector instrumentation on device, and forwards it to test listeners
- * as run metrics.
- *
- * @param listeners
- * @throws DeviceNotAvailableException
- */
- private void collectDeviceInfo(ITestDevice device, File testApkDir,
- List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
- DeviceInfoCollector.collectDeviceInfo(device, testApkDir, listeners);
- }
-
- /**
- * Factory method for creating a {@link ITestCaseRepo}.
- * <p/>
- * Exposed for unit testing
- */
- ITestCaseRepo createTestCaseRepo() {
- return new TestCaseRepo(mTestCaseDir);
- }
-
- /**
- * Factory method for creating a {@link PlanXmlParser}.
- * <p/>
- * Exposed for unit testing
- */
- IPlanXmlParser createXmlParser() {
- return new PlanXmlParser();
- }
-
- /**
- * Factory method for creating a {@link InputStream} from a plan xml file.
- * <p/>
- * Exposed for unit testing
- */
- InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
- return new BufferedInputStream(new FileInputStream(xmlFile));
- }
-}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
new file mode 100644
index 0000000..02595c0
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.testtype;
+
+import com.android.ddmlib.Log;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.result.ResultForwarder;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * A {@link ITestInvocationListener} that filters test results based on the set of expected tests
+ * in CTS test package xml files.
+ */
+class ResultFilter extends ResultForwarder {
+
+ private final Collection<TestIdentifier> mKnownTests;
+
+ /**
+ * Create a {@link ResultFilter}.
+ *
+ * @param listener the real {@link ITestInvocationListener} to forward results to
+ * @param expectedTests the full collection of known tests to expect
+ */
+ ResultFilter(ITestInvocationListener listener, Collection<TestIdentifier> knownTests) {
+ super(listener);
+ mKnownTests = knownTests;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {
+ super.testRunEnded(elapsedTime, runMetrics);
+ // TODO: report all remaining tests in mTestPackage as failed tests with
+ // notExecuted result
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void testStarted(TestIdentifier test) {
+ if (isKnownTest(test)) {
+ super.testStarted(test);
+ } else {
+ Log.d("ResultFilter", String.format("Skipping reporting unknown test %s", test));
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void testFailed(TestFailure status, TestIdentifier test, String trace) {
+ if (isKnownTest(test)) {
+ super.testFailed(status, test, trace);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
+ if (isKnownTest(test)) {
+ super.testEnded(test, testMetrics);
+ }
+ }
+
+ /**
+ * @param test
+ * @return
+ */
+ private boolean isKnownTest(TestIdentifier test) {
+ return mKnownTests.contains(test);
+ }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java
index 8392762..6b2a00d 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java
@@ -16,7 +16,6 @@
package com.android.cts.tradefed.testtype;
import com.android.ddmlib.Log;
-import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
import java.io.BufferedInputStream;
@@ -27,13 +26,15 @@
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.Hashtable;
+import java.util.List;
import java.util.Map;
/**
* Retrieves CTS test case definitions from the repository.
*/
-class TestCaseRepo implements ITestCaseRepo {
+public class TestCaseRepo implements ITestCaseRepo {
private static final String LOG_TAG = "TestCaseRepo";
@@ -115,21 +116,32 @@
/**
* {@inheritDoc}
*/
- public Collection<IRemoteTest> getTests(Collection<String> testUris) {
- Collection<IRemoteTest> tests = new ArrayList<IRemoteTest>(testUris.size());
- for (String uri : testUris) {
- TestPackageDef def = mTestMap.get(uri);
- if (def != null) {
- IRemoteTest test = def.createTest(mTestCaseDir);
- if (test != null) {
- tests.add(test);
- } else {
- Log.w(LOG_TAG, String.format("Failed to create test from package uri %s", uri));
- }
- } else {
- Log.w(LOG_TAG, String.format("Could not find test with uri %s", uri));
+ @Override
+ public ITestPackageDef getTestPackage(String testUri) {
+ return mTestMap.get(testUri);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String findPackageForTest(String testClassName) {
+ for (Map.Entry<String, TestPackageDef> entry : mTestMap.entrySet()) {
+ if (entry.getValue().isKnownTestClass(testClassName)) {
+ return entry.getKey();
}
}
- return tests;
+ return null;
+ }
+
+ /**
+ * Return a list of all package names found in repo.
+ * @return
+ */
+ public Collection<String> getPackageNames() {
+ List<String> packageNames = new ArrayList<String>();
+ packageNames.addAll(mTestMap.keySet());
+ Collections.sort(packageNames);
+ return packageNames;
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
index a75295e..fd896f2 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
@@ -23,15 +23,18 @@
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.LinkedHashSet;
/**
* Container for CTS test info.
* <p/>
* Knows how to translate this info into a runnable {@link IRemoteTest}.
*/
-public class TestPackageDef {
+class TestPackageDef implements ITestPackageDef {
private static final String LOG_TAG = "TestPackageDef";
+ private static final String SIGNATURE_TEST_METHOD = "testSignature";
+ private static final String SIGNATURE_TEST_CLASS = "android.tests.sigtest.SimpleSignatureTest";
private String mUri = null;
private String mAppNameSpace = null;
@@ -41,16 +44,20 @@
private String mJarPath = null;
private boolean mIsSignatureTest = false;
private boolean mIsReferenceAppTest = false;
+ private String mPackageToTest = null;
+ private String mApkToTestName = null;
- private Collection<TestIdentifier> mTests = new ArrayList<TestIdentifier>();
+ // use a LinkedHashSet for predictable iteration insertion-order, and fast lookups
+ private Collection<TestIdentifier> mTests = new LinkedHashSet<TestIdentifier>();
+ // also maintain an index of known test classes
+ private Collection<String> mTestClasses = new LinkedHashSet<String>();
void setUri(String uri) {
mUri = uri;
}
/**
- * Get the unique URI of the test package.
- * @return the {@link String} uri
+ * {@inheritDoc}
*/
public String getUri() {
return mUri;
@@ -113,37 +120,38 @@
return mIsReferenceAppTest;
}
+ void setPackageToTest(String packageName) {
+ mPackageToTest = packageName;
+ }
+
+ void setApkToTest(String apkName) {
+ mApkToTestName = apkName;
+ }
+
/**
- * Creates a runnable {@link IRemoteTest} from info stored in this definition.
- *
- * @param testCaseDir {@link File} representing directory of test case data
- * @return a {@link IRemoteTest} with all necessary data populated to run the test or
- * <code>null</code> if test could not be created
+ * {@inheritDoc}
*/
- public IRemoteTest createTest(File testCaseDir) {
+ public IRemoteTest createTest(File testCaseDir, String className, String methodName) {
if (mIsHostSideTest) {
Log.d(LOG_TAG, String.format("Creating host test for %s", mName));
JarHostTest hostTest = new JarHostTest();
hostTest.setRunName(mName);
hostTest.setJarFile(new File(testCaseDir, mJarPath));
hostTest.setTestAppPath(testCaseDir.getAbsolutePath());
- hostTest.setTests(mTests);
+ hostTest.setTests(filterTests(mTests, className, methodName));
return hostTest;
} else if (mIsSignatureTest) {
- // TODO: implement this
- Log.w(LOG_TAG, String.format("Skipping currently unsupported signature test %s",
- mName));
- return null;
- } else if (mIsReferenceAppTest) {
- // TODO: implement this
- Log.w(LOG_TAG, String.format("Skipping currently unsupported reference app test %s",
- mName));
- return null;
- } else {
- Log.d(LOG_TAG, String.format("Creating instrumentation test for %s", mName));
+ // TODO: hardcode the runner/class/method for now, since current package xml
+ // points to specialized instrumentation. Eventually this special case for signatureTest
+ // can be removed, and it can be treated just like a normal InstrumentationTest
+ Log.d(LOG_TAG, String.format("Creating signature test %s", mName));
InstrumentationTest instrTest = new InstrumentationTest();
instrTest.setPackageName(mAppNameSpace);
- instrTest.setRunnerName(mRunner);
+ instrTest.setRunnerName("android.test.InstrumentationTestRunner");
+ instrTest.setClassName(SIGNATURE_TEST_CLASS);
+ instrTest.setMethodName(SIGNATURE_TEST_METHOD);
+ // add signature test to list of known tests
+ addTest(new TestIdentifier(SIGNATURE_TEST_CLASS, SIGNATURE_TEST_METHOD));
// mName means 'apk file name' for instrumentation tests
File apkFile = new File(testCaseDir, String.format("%s.apk", mName));
if (!apkFile.exists()) {
@@ -153,24 +161,100 @@
}
instrTest.setInstallFile(apkFile);
return instrTest;
+ } else if (mIsReferenceAppTest) {
+ // a reference app test is just a InstrumentationTest with one extra apk to install
+ InstrumentationAppTest instrTest = new InstrumentationAppTest();
+ File apkFile = new File(testCaseDir, String.format("%s.apk", mApkToTestName));
+ if (!apkFile.exists()) {
+ Log.w(LOG_TAG, String.format("Could not find apk file %s",
+ apkFile.getAbsolutePath()));
+ return null;
+ }
+ instrTest.addInstallApp(apkFile, mPackageToTest);
+ return setInstrumentationTest(testCaseDir, className, methodName, instrTest);
+ } else {
+ Log.d(LOG_TAG, String.format("Creating instrumentation test for %s", mName));
+ InstrumentationTest instrTest = new InstrumentationTest();
+ return setInstrumentationTest(testCaseDir, className, methodName, instrTest);
}
}
/**
+ * Populates given {@link InstrumentationTest} with data from the package xml
+ *
+ * @param testCaseDir
+ * @param className
+ * @param methodName
+ * @param instrTest
+ * @return the populated {@link InstrumentationTest} or <code>null</code>
+ */
+ private InstrumentationTest setInstrumentationTest(File testCaseDir, String className,
+ String methodName, InstrumentationTest instrTest) {
+ instrTest.setPackageName(mAppNameSpace);
+ instrTest.setRunnerName(mRunner);
+ instrTest.setClassName(className);
+ instrTest.setMethodName(methodName);
+ // mName means 'apk file name' for instrumentation tests
+ File apkFile = new File(testCaseDir, String.format("%s.apk", mName));
+ if (!apkFile.exists()) {
+ Log.w(LOG_TAG, String.format("Could not find apk file %s",
+ apkFile.getAbsolutePath()));
+ return null;
+ }
+ instrTest.setInstallFile(apkFile);
+ return instrTest;
+ }
+
+ /**
+ * Filter the tests to run based on class and method name
+ *
+ * @param tests the full set of tests in package
+ * @param className the test class name filter. <code>null</code> to run all test classes
+ * @param methodName the test method name. <code>null</code> to run all test methods
+ * @return the filtered collection of tests
+ */
+ private Collection<TestIdentifier> filterTests(Collection<TestIdentifier> tests,
+ String className, String methodName) {
+ Collection<TestIdentifier> filteredTests = new ArrayList<TestIdentifier>(tests.size());
+ for (TestIdentifier test : tests) {
+ if (className == null || test.getClassName().equals(className)) {
+ if (methodName == null || test.getTestName().equals(methodName)) {
+ filteredTests.add(test);
+ }
+ }
+ }
+ return filteredTests;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isKnownTest(TestIdentifier testDef) {
+ return mTests.contains(testDef);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isKnownTestClass(String className) {
+ return mTestClasses.contains(className);
+ }
+
+ /**
* Add a {@link TestDef} to the list of tests in this package.
*
* @param testdef
*/
void addTest(TestIdentifier testDef) {
mTests.add(testDef);
+ mTestClasses.add(testDef.getClassName());
}
/**
* Get the collection of tests in this test package.
- * <p/>
- * Exposed for unit testing.
*/
- Collection<TestIdentifier> getTests() {
+ @Override
+ public Collection<TestIdentifier> getTests() {
return mTests;
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
index 9bf6968..d12fb9d 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
@@ -70,6 +70,8 @@
final String jarPath = attributes.getValue("jarPath");
final String signatureCheck = attributes.getValue("signatureCheck");
final String referenceApp = attributes.getValue("referenceAppTest");
+ final String apkToTest = attributes.getValue("apkToTestName");
+ final String packageToTest = attributes.getValue("packageToTest");
mPackageDef = new TestPackageDef();
mPackageDef.setUri(entryUriValue);
@@ -80,6 +82,8 @@
mPackageDef.setJarPath(jarPath);
mPackageDef.setIsSignatureCheck(parseBoolean(signatureCheck));
mPackageDef.setIsReferenceApp(parseBoolean(referenceApp));
+ mPackageDef.setApkToTest(apkToTest);
+ mPackageDef.setPackageToTest(packageToTest);
// reset the class name
mClassNameStack = new Stack<String>();
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
new file mode 100644
index 0000000..2ff00d3
--- /dev/null
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed;
+
+import com.android.cts.tradefed.result.CtsXmlResultReporterTest;
+import com.android.cts.tradefed.targetprep.CtsSetupTest;
+import com.android.cts.tradefed.testtype.JarHostTestTest;
+import com.android.cts.tradefed.testtype.CtsTestTest;
+import com.android.cts.tradefed.testtype.PlanXmlParserTest;
+import com.android.cts.tradefed.testtype.TestPackageXmlParserTest;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * A test suite for all cts-tradefed unit tests.
+ * <p/>
+ * All tests listed here should be self-contained, and do not require any external dependencies
+ * (such as a full CTS build with XML etc).
+ */
+public class UnitTests extends TestSuite {
+
+ public UnitTests() {
+ super();
+ addTestSuite(CtsXmlResultReporterTest.class);
+ addTestSuite(CtsSetupTest.class);
+ addTestSuite(JarHostTestTest.class);
+ addTestSuite(CtsTestTest.class);
+ addTestSuite(PlanXmlParserTest.class);
+ addTestSuite(TestPackageXmlParserTest.class);
+ }
+
+ public static Test suite() {
+ return new UnitTests();
+ }
+}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/build/StubCtsBuildHelper.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/build/StubCtsBuildHelper.java
new file mode 100644
index 0000000..0fe2f7a
--- /dev/null
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/build/StubCtsBuildHelper.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.build;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * Stub implementation of CtsBuildHelper that returns empty files for all methods
+ */
+public class StubCtsBuildHelper extends CtsBuildHelper {
+
+ public StubCtsBuildHelper() {
+ super(new File("tmp"));
+ }
+
+ @Override
+ public void validateStructure() {
+ // ignore
+ }
+
+ @Override
+ public File getTestApp(String appFileName) throws FileNotFoundException {
+ return new File("tmp");
+ }
+}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java
index 54f8f98..b0c9e6d 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java
@@ -15,15 +15,12 @@
*/
package com.android.cts.tradefed.device;
+import com.android.tradefed.build.BuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.result.CollectingTestListener;
-import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.targetsetup.BuildInfo;
import com.android.tradefed.testtype.DeviceTestCase;
import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Map;
/**
@@ -37,11 +34,8 @@
CollectingTestListener testListener = new CollectingTestListener();
testListener.invocationStarted(new BuildInfo());
- List<ITestInvocationListener> listeners = new ArrayList<ITestInvocationListener>(1);
- listeners.add(testListener);
DeviceInfoCollector.collectDeviceInfo(getDevice(), new File(
- System.getProperty("java.io.tmpdir")),
- listeners);
+ System.getProperty("java.io.tmpdir")), testListener);
assertNotNull(testListener.getCurrentRunResults());
assertTrue(testListener.getCurrentRunResults().getRunMetrics().size() > 0);
for (Map.Entry<String, String> metricEntry : testListener.getCurrentRunResults().getRunMetrics().entrySet()) {
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
index 113496c..212128d 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
@@ -17,8 +17,8 @@
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.ddmlib.testrunner.ITestRunListener.TestFailure;
+import com.android.tradefed.build.BuildInfo;
import com.android.tradefed.result.XmlResultReporter;
-import com.android.tradefed.targetsetup.BuildInfo;
import com.android.tradefed.util.FileUtil;
import java.io.ByteArrayOutputStream;
@@ -75,14 +75,23 @@
* A simple test to ensure expected output is generated for test run with no tests.
*/
public void testEmptyGeneration() {
- final String expectedOutput = "<?xml version='1.0' encoding='UTF-8' standalone='no' ?>" +
- "<?xml-stylesheet type=\"text/xsl\" href=\"cts_result.xsl\"?>" +
- "<TestResult testPlan=\"unknown\" profile=\"unknown\" starttime=\"ignore\" endtime=\"ignore\" version=\"2.0\"> " +
- "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"0\" total=\"0\" />" +
- "</TestResult>";
+ final String expectedHeaderOutput = "<?xml version='1.0' encoding='UTF-8' standalone='no' ?>" +
+ "<?xml-stylesheet type=\"text/xsl\" href=\"cts_result.xsl\"?>";
+ final String expectedTestOutput =
+ "<TestResult testPlan=\"unknown\" starttime=\"ignore\" endtime=\"ignore\" version=\"1.10\"> ";
+ final String expectedSummaryOutput =
+ "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"0\" total=\"0\" />";
+ final String expectedEndTag = "</TestResult>";
mResultReporter.invocationStarted(new BuildInfo(1, "test", "test"));
mResultReporter.invocationEnded(1);
- assertEquals(expectedOutput, getOutput());
+ String actualOutput = getOutput();
+ assertTrue(actualOutput.startsWith(expectedHeaderOutput));
+ assertTrue(String.format("test output did not contain expected test result. Got %s",
+ actualOutput), actualOutput.contains(expectedTestOutput));
+ assertTrue(String.format("test output did not contain expected test summary. Got %s",
+ actualOutput), actualOutput.contains(expectedSummaryOutput));
+ assertTrue(String.format("test output did not contain expected TestResult end tag. Got %s",
+ actualOutput), actualOutput.endsWith(expectedEndTag));
}
/**
@@ -101,8 +110,8 @@
// TODO: consider doing xml based compare
assertTrue(output.contains(
"<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"1\" total=\"1\" />"));
- assertTrue(output.contains("<TestPackage name=\"run\" runTime=\"3s\" digest=\"\" " +
- "failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"1\" total=\"1\">"));
+ assertTrue(output.contains("<TestPackage name=\"run\" digest=\"\" " +
+ "failed=\"0\" notExecuted=\"0\" timeout=\"0\" pass=\"1\" >"));
assertTrue(output.contains(String.format("<TestCase name=\"%s\">", testId.getClassName())));
final String testCaseTag = String.format(
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetprep/CtsSetupTest.java
similarity index 79%
rename from tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java
rename to tools/tradefed-host/tests/src/com/android/cts/tradefed/targetprep/CtsSetupTest.java
index 932f3dc..4385215 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetprep/CtsSetupTest.java
@@ -13,20 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.cts.tradefed.targetsetup;
+package com.android.cts.tradefed.targetprep;
-import com.android.ddmlib.Log;
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.tradefed.build.StubCtsBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.IFolderBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.targetsetup.BuildError;
-import com.android.tradefed.targetsetup.IBuildInfo;
-import com.android.tradefed.targetsetup.IFolderBuildInfo;
-import com.android.tradefed.targetsetup.TargetSetupError;
+import com.android.tradefed.targetprep.BuildError;
+import com.android.tradefed.targetprep.TargetSetupError;
import org.easymock.EasyMock;
import java.io.File;
-import java.io.IOException;
import junit.framework.TestCase;
@@ -35,8 +35,6 @@
*/
public class CtsSetupTest extends TestCase {
- private static final String LOG_TAG = "CtsSetupTest";
-
private CtsSetup mSetup;
private ITestDevice mMockDevice;
@@ -49,13 +47,7 @@
mSetup = new CtsSetup() {
@Override
CtsBuildHelper createBuildHelper(File rootDir) {
- try {
- return StubCtsBuildHelper.createStubHelper();
- } catch (IOException e) {
- Log.e(LOG_TAG, e);
- fail("failed to create stub helper");
- return null;
- }
+ return new StubCtsBuildHelper();
}
};
mMockDevice = EasyMock.createMock(ITestDevice.class);
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/StubCtsBuildHelper.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/StubCtsBuildHelper.java
deleted file mode 100644
index 53a79be..0000000
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/StubCtsBuildHelper.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.cts.tradefed.targetsetup;
-
-import com.android.tradefed.util.FileUtil;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-/**
- * Stub implementation of CtsBuildHelper that returns empty files for all methods
- */
-public class StubCtsBuildHelper extends CtsBuildHelper {
-
- public static StubCtsBuildHelper createStubHelper() throws IOException {
- File tmpFolder= FileUtil.createTempDir("ctstmp");
- File ctsinstall = new File(tmpFolder, CtsBuildHelper.CTS_DIR_NAME);
- ctsinstall.mkdirs();
- return new StubCtsBuildHelper(tmpFolder);
- }
-
- private StubCtsBuildHelper(File rootDir) throws FileNotFoundException {
- super(rootDir);
- }
-
- @Override
- public File getTestApp(String appFileName) throws FileNotFoundException {
- return new File("tmp");
- }
-
- @Override
- public File getTestPlansDir() throws FileNotFoundException {
- return new File("tmp");
- }
-
- @Override
- public File getTestCasesDir() {
- return new File("tmp");
- }
-}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
new file mode 100644
index 0000000..157e85e
--- /dev/null
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
@@ -0,0 +1,292 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.tradefed.testtype;
+
+import com.android.cts.tradefed.build.StubCtsBuildHelper;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
+
+import org.easymock.EasyMock;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for {@link CtsTest}.
+ */
+public class CtsTestTest extends TestCase {
+
+ private static final String PACKAGE_NAME = "test-uri";
+ /** the test fixture under test, with all external dependencies mocked out */
+ private CtsTest mCtsTest;
+ private ITestCaseRepo mMockRepo;
+ private IPlanXmlParser mMockPlanParser;
+ private ITestDevice mMockDevice;
+ private ITestInvocationListener mMockListener;
+ private StubCtsBuildHelper mStubBuildHelper;
+
+ private static final String PLAN_NAME = "CTS";
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mMockRepo = EasyMock.createMock(ITestCaseRepo.class);
+ mMockPlanParser = EasyMock.createMock(IPlanXmlParser.class);
+ mMockDevice = EasyMock.createMock(ITestDevice.class);
+ mMockListener = EasyMock.createNiceMock(ITestInvocationListener.class);
+ mStubBuildHelper = new StubCtsBuildHelper();
+
+ mCtsTest = new CtsTest() {
+ @Override
+ ITestCaseRepo createTestCaseRepo() {
+ return mMockRepo;
+ }
+
+ @Override
+ IPlanXmlParser createXmlParser() {
+ return mMockPlanParser;
+ }
+
+ @Override
+ InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
+ // return empty stream, not used
+ return new ByteArrayInputStream(new byte[0]);
+ }
+ };
+ mCtsTest.setDevice(mMockDevice);
+ mCtsTest.setBuildHelper(mStubBuildHelper);
+ // turn off device collection for simplicity
+ mCtsTest.setCollectDeviceInfo(false);
+ }
+
+ /**
+ * Test normal case {@link CtsTest#run(java.util.List)} when running a plan.
+ */
+ @SuppressWarnings("unchecked")
+ public void testRun_plan() throws DeviceNotAvailableException, ParseException {
+ setParsePlanExceptations();
+
+ ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+ IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+ EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+ EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+ (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(mockTest);
+ EasyMock.expect(mockPackageDef.getTests()).andReturn(new ArrayList<TestIdentifier>());
+ mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+ replayMocks(mockTest, mockPackageDef);
+ mCtsTest.run(mMockListener);
+ verifyMocks(mockTest, mockPackageDef);
+ }
+
+ /**
+ * Test normal case {@link CtsTest#run(java.util.List)} when running a package.
+ */
+ @SuppressWarnings("unchecked")
+ public void testRun_package() throws DeviceNotAvailableException {
+ mCtsTest.addPackageName(PACKAGE_NAME);
+ ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+ IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+ EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+ EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+ (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(mockTest);
+ EasyMock.expect(mockPackageDef.getTests()).andReturn(new ArrayList<TestIdentifier>());
+ mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+ replayMocks(mockTest, mockPackageDef);
+ mCtsTest.run(mMockListener);
+ verifyMocks(mockTest, mockPackageDef);
+ }
+
+ /**
+ * Test a resumed run
+ */
+ @SuppressWarnings("unchecked")
+ public void testRun_resume() throws DeviceNotAvailableException {
+ mCtsTest.addPackageName(PACKAGE_NAME);
+ ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+ IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+ EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+ EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+ (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(mockTest);
+ EasyMock.expect(mockPackageDef.getTests()).andReturn(new ArrayList<TestIdentifier>());
+
+ mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+ // abort the first run
+ EasyMock.expectLastCall().andThrow(new DeviceNotAvailableException());
+
+ // now expect test to be resumed
+ mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+ replayMocks(mockTest, mockPackageDef);
+ try {
+ mCtsTest.run(mMockListener);
+ fail("Did not throw DeviceNotAvailableException");
+ } catch (DeviceNotAvailableException e) {
+ // expected
+ }
+ // now resume, and expect same test's run method to be called again
+ mCtsTest.run(mMockListener);
+ verifyMocks(mockTest, mockPackageDef);
+ }
+
+ /**
+ * Test normal case {@link CtsTest#run(java.util.List)} when running a class.
+ */
+ @SuppressWarnings("unchecked")
+ public void testRun_class() throws DeviceNotAvailableException {
+ final String className = "className";
+ final String methodName = "methodName";
+ mCtsTest.setClassName(className);
+ mCtsTest.setMethodName(methodName);
+
+
+ EasyMock.expect(mMockRepo.findPackageForTest(className)).andReturn(PACKAGE_NAME);
+ ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+ EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+ IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+ EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+ EasyMock.eq(className), EasyMock.eq(methodName))).andReturn(mockTest);
+ EasyMock.expect(mockPackageDef.getTests()).andReturn(new ArrayList<TestIdentifier>());
+ mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+ replayMocks(mockTest, mockPackageDef);
+ mCtsTest.run(mMockListener);
+ verifyMocks(mockTest, mockPackageDef);
+ }
+
+ /**
+ * Test {@link CtsTest#run(java.util.List)} when --excluded-package is specified
+ */
+ public void testRun_excludedPackage() throws DeviceNotAvailableException, ParseException {
+ setParsePlanExceptations();
+
+ mCtsTest.addExcludedPackageName(PACKAGE_NAME);
+
+ // PACKAGE_NAME would normally be run, but it has been excluded. Expect nothing to happen
+ replayMocks();
+ mCtsTest.run(mMockListener);
+ verifyMocks();
+ }
+
+ /**
+ * Set EasyMock expectations for parsing {@link #PLAN_NAME}
+ */
+ private void setParsePlanExceptations() throws ParseException {
+ mCtsTest.setPlanName(PLAN_NAME);
+ mMockPlanParser.parse((InputStream)EasyMock.anyObject());
+ Collection<String> uris = new ArrayList<String>(1);
+ uris.add(PACKAGE_NAME);
+ EasyMock.expect(mMockPlanParser.getTestUris()).andReturn(uris);
+ }
+
+ /**
+ * Test {@link CtsTest#run(java.util.List)} when --plan and --package options have not been
+ * specified
+ */
+ public void testRun_nothingToRun() throws DeviceNotAvailableException {
+ try {
+ mCtsTest.run(mMockListener);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Test {@link CtsTest#run(ITestInvocationListener))} when --plan and --package options have
+ * been specified.
+ */
+ public void testRun_packagePlan() throws DeviceNotAvailableException {
+ mCtsTest.setPlanName(PLAN_NAME);
+ mCtsTest.addPackageName(PACKAGE_NAME);
+ try {
+ mCtsTest.run(mMockListener);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Test {@link CtsTest#run(java.util.List)} when --plan and --class options have been
+ * specified
+ */
+ public void testRun_planClass() throws DeviceNotAvailableException {
+ mCtsTest.setPlanName(PLAN_NAME);
+ mCtsTest.setClassName("class");
+ try {
+ mCtsTest.run(mMockListener);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Test {@link CtsTest#run(java.util.List)} when --package and --class options have been
+ * specified
+ */
+ public void testRun_packageClass() throws DeviceNotAvailableException {
+ mCtsTest.addPackageName(PACKAGE_NAME);
+ mCtsTest.setClassName("class");
+ try {
+ mCtsTest.run(mMockListener);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Test {@link CtsTest#run(java.util.List)} when --plan, --package and --class options have been
+ * specified
+ */
+ public void testRun_planPackageClass() throws DeviceNotAvailableException {
+ mCtsTest.setPlanName(PLAN_NAME);
+ mCtsTest.addPackageName(PACKAGE_NAME);
+ mCtsTest.setClassName("class");
+ try {
+ mCtsTest.run(mMockListener);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ private void replayMocks(Object... mocks) {
+ EasyMock.replay(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
+ EasyMock.replay(mocks);
+ }
+
+ private void verifyMocks(Object... mocks) {
+ EasyMock.verify(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
+ EasyMock.verify(mocks);
+ }
+}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java
index fcd9563..9a49b77 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java
@@ -17,11 +17,15 @@
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
import org.easymock.EasyMock;
+import java.io.File;
import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import junit.framework.TestCase;
@@ -51,6 +55,10 @@
super(name);
}
+ public MockTest() {
+ super();
+ }
+
public void testFoo() {
}
}
@@ -64,15 +72,19 @@
ITestInvocationListener listener = EasyMock.createMock(ITestInvocationListener.class);
TestIdentifier expectedTest = new TestIdentifier(MockTest.class.getName(), "testFoo");
+ Collection<TestIdentifier> tests = new ArrayList<TestIdentifier>(1);
+ tests.add(expectedTest);
listener.testRunStarted(RUN_NAME, 1);
listener.testStarted(expectedTest);
listener.testEnded(expectedTest, Collections.EMPTY_MAP);
listener.testRunEnded(EasyMock.anyLong(), EasyMock.eq(Collections.EMPTY_MAP));
+ mJarTest.setTests(tests);
+ mJarTest.setDevice(EasyMock.createMock(ITestDevice.class));
+ mJarTest.setJarFile(new File("fakefile"));
+ mJarTest.setRunName(RUN_NAME);
EasyMock.replay(listener);
-
- mJarTest.setRunName(RUN_NAME);
mJarTest.run(listener);
+ EasyMock.verify(listener);
}
-
}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/PlanTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/PlanTestTest.java
deleted file mode 100644
index 1c2b4b6..0000000
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/PlanTestTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.cts.tradefed.testtype;
-
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.testtype.IRemoteTest;
-import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
-
-import org.easymock.EasyMock;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-/**
- * Unit tests for {@link PlanTest}.
- */
-public class PlanTestTest extends TestCase {
-
- /** the test fixture under test, with all external dependencies mocked out */
- private PlanTest mPlanTest;
- private ITestCaseRepo mMockRepo;
- private IPlanXmlParser mMockPlanParser;
- private ITestDevice mMockDevice;
- private ITestInvocationListener mMockListener;
-
- private static final String PLAN_NAME = "CTS";
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mMockRepo = EasyMock.createMock(ITestCaseRepo.class);
- mMockPlanParser = EasyMock.createMock(IPlanXmlParser.class);
- mMockDevice = EasyMock.createMock(ITestDevice.class);
- mMockListener = EasyMock.createNiceMock(ITestInvocationListener.class);
-
- mPlanTest = new PlanTest() {
- @Override
- ITestCaseRepo createTestCaseRepo() {
- return mMockRepo;
- }
-
- @Override
- IPlanXmlParser createXmlParser() {
- return mMockPlanParser;
- }
-
- @Override
- InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
- // return empty stream, not used
- return new ByteArrayInputStream(new byte[0]);
- }
- };
- mPlanTest.setDevice(mMockDevice);
- // not used, but needs to be non-null
- mPlanTest.setTestCaseDir(new File("tmp"));
- mPlanTest.setTestPlanDir(new File("tmp"));
- mPlanTest.setPlanName(PLAN_NAME);
- }
-
- /**
- * Test normal case {@link PlanTest#run(java.util.List)}.
- * <p/>
- * Not that interesting of a test in its current form, but sets the stage for testing more
- * complicated scenarios.
- */
- @SuppressWarnings("unchecked")
- public void testRun() throws DeviceNotAvailableException, ParseException {
- // expect
- mMockPlanParser.parse((InputStream)EasyMock.anyObject());
- Collection<String> uris = new ArrayList<String>(1);
- uris.add("test-uri");
- EasyMock.expect(mMockPlanParser.getTestUris()).andReturn(uris);
-
- IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
- Collection<IRemoteTest> tests = new ArrayList<IRemoteTest>(1);
- tests.add(mockTest);
- EasyMock.expect(mMockRepo.getTests(uris)).andReturn(tests);
-
- // expect
- mockTest.run((List<ITestInvocationListener>)EasyMock.anyObject());
-
- replayMocks();
- EasyMock.replay(mockTest);
- mPlanTest.run(mMockListener);
- verifyMocks();
- }
-
- private void replayMocks() {
- EasyMock.replay(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
- }
-
- private void verifyMocks() {
- EasyMock.verify(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
- }
-}
diff --git a/tools/vm-tests/src/util/build/DeviceUtil.java.template b/tools/vm-tests/src/util/build/DeviceUtil.java.template
index 4d634d1..a8461cf 100644
--- a/tools/vm-tests/src/util/build/DeviceUtil.java.template
+++ b/tools/vm-tests/src/util/build/DeviceUtil.java.template
@@ -17,7 +17,7 @@
/**
* Executes the command and its arguments in a native process.
- *
+ *
* @param commandAndArgs a string array to be passed containing the
* executable and its arguments
* @param okIndicator if not null, this String must occur in the stdout of
@@ -93,8 +93,20 @@
public static void adbPush(IDevice device, String source, String target)
throws IOException {
- DeviceUtil.digestCommand(new String[] {"adb", "-s", device.getSerialNumber(), "push",
- DeviceUtil.createFilePath(source), target}, null);
+ String tmp_source = null;
+ try {
+ tmp_source = DeviceUtil.createFilePath(source);
+ DeviceUtil.digestCommand(new String[] {"adb", "-s", device.getSerialNumber(), "push",
+ tmp_source, target}, null);
+ } finally {
+ // Clean up local temp file after pushing it to device.
+ if (tmp_source != null) {
+ File f = new File(tmp_source);
+ if (f.exists()) {
+ f.delete();
+ }
+ }
+ }
}
public static void adbExec(IDevice device, String classpath, String mainclass) {