diff --git a/CleanSpec.mk b/CleanSpec.mk
index b2474c2..b84e1b6 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -44,7 +44,6 @@
#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
-$(call add-clean-step, rm -rf $(HOST_OUT_INTERMEDIATES)/EXECUTABLES/vm-tests-tf_intermediates)
# ************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
# ************************************************
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index df7b03d..1d60713 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -12,6 +12,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+CTS_APPS_LIST := \
+ CtsVerifier
+
CTS_SECURITY_APPS_LIST := \
CtsAppAccessData \
CtsAppWithData \
@@ -26,18 +29,14 @@ CTS_SECURITY_APPS_LIST := \
# These test cases will be analyzed by the CTS API coverage tools.
CTS_COVERAGE_TEST_CASE_LIST := \
- CtsAccelerationTestCases \
- CtsAccelerationTestStubs \
CtsAccessibilityServiceTestCases \
CtsAccountManagerTestCases \
- CtsAdminTestCases \
CtsAppTestCases \
CtsBluetoothTestCases \
CtsContentTestCases \
CtsDatabaseTestCases \
CtsDpiTestCases \
CtsDpiTestCases2 \
- CtsDrmTestCases \
CtsExampleTestCases \
CtsGestureTestCases \
CtsGraphicsTestCases \
@@ -46,34 +45,34 @@ CTS_COVERAGE_TEST_CASE_LIST := \
CtsLocationTestCases \
CtsMediaTestCases \
CtsNdefTestCases \
- CtsNetTestCases \
CtsOsTestCases \
CtsPermissionTestCases \
CtsPermission2TestCases \
CtsPreferenceTestCases \
CtsProviderTestCases \
- CtsRenderscriptTestCases \
CtsSaxTestCases \
CtsSecurityTestCases \
CtsSpeechTestCases \
CtsTelephonyTestCases \
CtsTestStubs \
CtsTextTestCases \
- CtsThemeTestCases \
CtsUtilTestCases \
CtsViewTestCases \
CtsWebkitTestCases \
- CtsWidgetTestCases
+ CtsWidgetTestCases \
+ CtsNetTestCases \
+ CtsPerformanceTestCases \
+ CtsPerformance2TestCases \
+ CtsPerformance3TestCases \
+ CtsPerformance4TestCases \
+ CtsPerformance5TestCases
CTS_TEST_CASE_LIST := \
TestDeviceSetup \
CtsDelegatingAccessibilityService \
- CtsDeviceAdmin \
SignatureTest \
ApiDemos \
ApiDemosReferenceTest \
+ $(CTS_APPS_LIST) \
$(CTS_COVERAGE_TEST_CASE_LIST) \
$(CTS_SECURITY_APPS_LIST)
-
-# The following files will be placed in the tools directory of the CTS distribution
-CTS_TOOLS_LIST :=
diff --git a/CtsTestCoverage.mk b/CtsTestCoverage.mk
index 8e00913..7053fea 100644
--- a/CtsTestCoverage.mk
+++ b/CtsTestCoverage.mk
@@ -19,30 +19,22 @@
include cts/CtsTestCaseList.mk
-cts_api_coverage_exe := $(HOST_OUT_EXECUTABLES)/cts-api-coverage
-dexdeps_exe := $(HOST_OUT_EXECUTABLES)/dexdeps
+CTS_API_COVERAGE_EXE := $(HOST_OUT_EXECUTABLES)/cts-api-coverage
+DEXDEPS_EXE := $(HOST_OUT_EXECUTABLES)/dexdeps
-coverage_out := $(HOST_OUT)/cts-api-coverage
+COVERAGE_OUT := $(HOST_OUT)/cts-api-coverage
+cts-test-coverage-report := $(COVERAGE_OUT)/test-coverage.html
+cts-verifier-coverage-report := $(COVERAGE_OUT)/verifier-coverage.html
-api_text_description := $(SRC_API_DIR)/current.txt
-api_xml_description := $(coverage_out)/api.xml
-$(api_xml_description) : $(api_text_description) $(APICHECK)
- $(hide) echo "Converting API file to XML: $@"
- $(hide) mkdir -p $(coverage_out)
- $(hide) $(APICHECK_COMMAND) -convert2xml $(api_text_description) $(api_xml_description)
+CTS_API_COVERAGE_DEPENDENCIES := $(CTS_API_COVERAGE_EXE) $(DEXDEPS_EXE) $(ACP)
-cts-test-coverage-report := $(coverage_out)/test-coverage.html
-cts-verifier-coverage-report := $(coverage_out)/verifier-coverage.html
-
-cts_api_coverage_dependencies := $(cts_api_coverage_exe) $(dexdeps_exe) $(api_xml_description) $(ACP)
-
-$(cts-test-coverage-report) : $(CTS_COVERAGE_TEST_CASE_LIST) $(cts_api_coverage_dependencies)
+$(cts-test-coverage-report) : $(CTS_COVERAGE_TEST_CASE_LIST) $(CTS_API_COVERAGE_DEPENDENCIES)
$(call generate-coverage-report,"CTS Tests API Coverage Report",\
- $(CTS_COVERAGE_TEST_CASE_LIST),cts-test-apks,html,test-coverage.html)
+ $(CTS_COVERAGE_TEST_CASE_LIST),html,test-coverage.html)
-$(cts-verifier-coverage-report) : CtsVerifier $(cts_api_coverage_dependencies)
+$(cts-verifier-coverage-report) : CtsVerifier $(CTS_API_COVERAGE_DEPENDENCIES)
$(call generate-coverage-report,"CTS Verifier API Coverage Report",\
- CtsVerifier,cts-verifier-apks,html,verifier-coverage.html)
+ CtsVerifier,html,verifier-coverage.html)
.PHONY: cts-test-coverage
cts-test-coverage : $(cts-test-coverage-report)
@@ -59,18 +51,15 @@ endif
# Arguments;
# 1 - Name of the report printed out on the screen
# 2 - Name of APK packages that will be scanned to generate the report
-# 3 - Name of variable to hold the calculated paths of the APKs
-# 4 - Format of the report
-# 5 - Output file name of the report
+# 3 - Format of the report
+# 4 - Output file name of the report
define generate-coverage-report
- $(foreach testcase,$(2),$(eval $(call add-testcase-apk,$(3),$(testcase))))
- $(hide) mkdir -p $(coverage_out)
- $(hide) $(cts_api_coverage_exe) -d $(dexdeps_exe) -a $(api_xml_description) -f $(4) -o $(coverage_out)/$(5) $($(3))
- $(hide) echo $(1): file://$(ANDROID_BUILD_TOP)/$(coverage_out)/$(5)
+ $(foreach testcase,$(2),$(eval $(call add-testcase-apk,$(testcase))))
+ $(hide) mkdir -p $(COVERAGE_OUT)
+ $(hide) $(CTS_API_COVERAGE_EXE) -d $(DEXDEPS_EXE) -f $(3) -o $(COVERAGE_OUT)/$(4) $(TEST_APKS)
+ $(hide) echo $(1): file://$(ANDROID_BUILD_TOP)/$(COVERAGE_OUT)/$(4)
endef
-# classes.dex is stripped from package.apk if dex-preopt is enabled,
-# so we use the copy that definitely includes classes.dex.
define add-testcase-apk
- $(1) += $(call intermediates-dir-for,APPS,$(2))/package.apk.unaligned
+ TEST_APKS += $(call intermediates-dir-for,APPS,$(1))/package.apk
endef
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index 16d3de1..bbf7eaf 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -25,9 +25,7 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := CtsVerifier
-LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni libaudioquality libcameraanalyzer
-
-LOCAL_PROGUARD_FLAG_FILES := proguard.flags
+LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni libaudioquality
LOCAL_SDK_VERSION := current
@@ -39,31 +37,4 @@ cts-verifier: CtsVerifier adb
adb install -r $(ANDROID_PRODUCT_OUT)/data/app/CtsVerifier.apk \
&& adb shell "am start -n com.android.cts.verifier/.CtsVerifierActivity"
-#
-# Creates a "cts-verifier" directory that will contain:
-#
-# 1. Out directory with a "android-cts-verifier" containing the CTS Verifier
-# and other binaries it needs.
-#
-# 2. Zipped version of the android-cts-verifier directory to be included with
-# the build distribution.
-#
-cts-dir := $(HOST_OUT)/cts-verifier
-verifier-dir-name := android-cts-verifier
-verifier-dir := $(cts-dir)/$(verifier-dir-name)
-verifier-zip-name := $(verifier-dir-name).zip
-verifier-zip := $(cts-dir)/$(verifier-zip-name)
-
-cts : $(verifier-zip)
-$(verifier-zip) : CtsVerifier $(ACP) $(HOST_OUT)/bin/cts-usb-accessory
- $(hide) mkdir -p $(verifier-dir)
- $(hide) $(ACP) -fp $(call intermediates-dir-for,APPS,CtsVerifier)/package.apk \
- $(verifier-dir)/CtsVerifier.apk
- $(hide) $(ACP) -fp $(HOST_OUT)/bin/cts-usb-accessory $(verifier-dir)/cts-usb-accessory
- $(hide) cd $(cts-dir) && zip -rq $(verifier-dir-name) $(verifier-dir-name)
-
-ifneq ($(filter cts, $(MAKECMDGOALS)),)
- $(call dist-for-goals, cts, $(verifier-zip):$(verifier-zip-name))
-endif
-
include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 1da4cb9..9bdb37a 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -18,26 +18,19 @@
-
+ android:versionName="1.0">
+
-
-
+
-
-
-
+
@@ -46,64 +39,11 @@
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -112,90 +52,19 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ android:configChanges="keyboardHidden|orientation" />
+
+
@@ -206,21 +75,6 @@
-
-
-
-
-
-
-
-
-
-
@@ -236,17 +90,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/include/colorchecker/colorchecker.h b/apps/CtsVerifier/include/colorchecker/colorchecker.h
deleted file mode 100644
index 5409b04..0000000
--- a/apps/CtsVerifier/include/colorchecker/colorchecker.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.
- */
-
-#ifndef COLORCHECKER_H
-#define COLORCHECKER_H
-
-/** Detects the 6x4 Xrite ColorChecker Classic pattern in the input image,
- * and calculates the average color value per patch.
- *
- * All squares in the colorchecker pattern have to be fully visible,
- * and the whole pattern should fill at least 1/3 of the image
- * width. The pattern cannot be facing away from the camera at a very
- * large angle (>45 degrees). If multiple 6x4 grids can be found, the
- * one that is most front-facing will be returned.
- *
- * The average color is returned as a floating-point value per
- * channel, linearized by an inverse gamma transform and normalized
- * to 0-1 (255 = 1). The linearization is only approximate.
- *
- * @param inputImage Source image to detect the pattern in. Assumed
- * to be a 3-channel interleaved image. Row-major
- * @param width Width of input image
- * @param height Height of input image
- * @param patchColors Output 6x4 3-channel image of average patch
- * values. Allocated by caller. Pass in NULL if
- * the average values aren't needed.
- * @param outputImage Resized inputImage with overlaid grid detection
- * diagnostics. Image width is approximately 160
- * pixels. Pass in NULL if the diagnostic image
- * isn't needed.
- * @param outputWidth Actual width of outputImage.
- * @param outputHeight Actual height of outputImage.
- *
- * @return true if a grid was found, false otherwise. If false, the
- * input variables are unchanged.
- */
-bool findColorChecker(const unsigned char *image,
- int width,
- int rowSpan,
- int height,
- float *patchColors,
- unsigned char **outputImage,
- int *outputWidth,
- int *outputHeight);
-
-
-#endif
diff --git a/apps/CtsVerifier/jni/audioquality/Android.mk b/apps/CtsVerifier/jni/audioquality/Android.mk
index 8e827f7..565cec2 100644
--- a/apps/CtsVerifier/jni/audioquality/Android.mk
+++ b/apps/CtsVerifier/jni/audioquality/Android.mk
@@ -20,7 +20,7 @@ LOCAL_CPP_EXTENSION := .cpp
LOCAL_MODULE_TAGS := optional
-
+LOCAL_PRELINK_MODULE := false
LOCAL_MODULE := libaudioquality
LOCAL_SRC_FILES := Fft.cpp Window.cpp GlitchTest.cpp MeasureRms.cpp \
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/Android.mk b/apps/CtsVerifier/jni/cameraanalyzer/Android.mk
deleted file mode 100644
index ccc0998..0000000
--- a/apps/CtsVerifier/jni/cameraanalyzer/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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 := libcameraanalyzer
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := com_android_cts_verifier_camera_analyzer_ColorChecker.cpp
-
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../include/colorchecker $(JNI_H_INCLUDE)
-
-LOCAL_STATIC_LIBRARIES := libcolorchecker
-LOCAL_SHARED_LIBRARIES := libjnigraphics \
- libstlport \
- libcutils \
- libutils
-
-include $(BUILD_SHARED_LIBRARY)
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorChecker.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorChecker.cpp
deleted file mode 100644
index 4d247ab..0000000
--- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorChecker.cpp
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * 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.
- */
-
-#include "com_android_cts_verifier_camera_analyzer_ColorChecker.h"
-
-#include "utils/Log.h"
-#include "android/bitmap.h"
-#include "colorchecker.h"
-
-jboolean Java_com_android_cts_verifier_camera_analyzer_ColorChecker_findNative(
- JNIEnv* env,
- jobject thiz,
- jobject inputBitmap) {
-
- // Verify that we can handle the input bitmap
- AndroidBitmapInfo inputInfo;
- AndroidBitmap_getInfo(env, inputBitmap, &inputInfo);
- if (inputInfo.format != ANDROID_BITMAP_FORMAT_RGBA_8888 &&
- inputInfo.format != ANDROID_BITMAP_FORMAT_RGB_565) {
- LOGE("Only RGBA_8888 and RGB_565 bitmaps are supported, was given type %d.", inputInfo.format);
- return JNI_FALSE;
- }
-
- // Get some references to the fields and class type of ColorChecker
- jclass thizCls = env->GetObjectClass(thiz);
- jfieldID patchId = env->GetFieldID(thizCls, "mPatchValues", "[F");
- jfieldID outputId = env->GetFieldID(thizCls, "mDebugOutput", "Landroid/graphics/Bitmap;");
- jfloatArray patchValues = (jfloatArray)env->GetObjectField(thiz, patchId);
-
- // Get raw inputs and outputs ready
-
- uint8_t *inputBuffer;
- int result = AndroidBitmap_lockPixels(
- env,
- inputBitmap,
- reinterpret_cast(&inputBuffer) );
-
- if (result != ANDROID_BITMAP_RESUT_SUCCESS) {
- LOGE("Unable to lock input bitmap");
- return JNI_FALSE;
- }
-
- float *patchRawArray = env->GetFloatArrayElements(patchValues,
- NULL);
-
- uint8_t *outputImage = NULL;
- int outputWidth, outputHeight;
-
- // Find the color checker
- bool success;
- uint8_t *inputBufferRGBA = NULL;
- int inputStride;
- bool freeInputRGBA = false;
- switch (inputInfo.format) {
- case ANDROID_BITMAP_FORMAT_RGB_565: {
- // First convert to RGBA_8888
- inputBufferRGBA = new uint8_t[inputInfo.width *
- inputInfo.height *
- 4];
- inputStride = inputInfo.width * 4;
- uint8_t *outP = inputBufferRGBA;
- for (int y = 0; y < inputInfo.height; y++ ) {
- uint16_t *inP = (uint16_t*)(&inputBuffer[y * inputInfo.stride]);
- for (int x = 0; x < inputInfo.width; x++) {
- *(outP++) = ( ((*inP) >> 0) & 0x001F) << 3;
- *(outP++) = ( ((*inP) >> 5) & 0x003F) << 2;
- *(outP++) = ( ((*inP) >> 11) & 0x001F) << 3;
- outP++;
- inP++;
- }
- }
- freeInputRGBA = true;
- break;
- }
- case ANDROID_BITMAP_FORMAT_RGBA_8888:
- // Already in RGBA
- inputBufferRGBA = inputBuffer;
- inputStride = inputInfo.stride;
- break;
- }
-
- success = findColorChecker(inputBufferRGBA,
- inputInfo.width,
- inputStride,
- inputInfo.height,
- patchRawArray,
- &outputImage,
- &outputWidth,
- &outputHeight);
-
- // Clean up raw inputs/outputs
- env->ReleaseFloatArrayElements(patchValues, patchRawArray, 0);
- result = AndroidBitmap_unlockPixels(env, inputBitmap);
- if (result != ANDROID_BITMAP_RESUT_SUCCESS) {
- LOGE("Unable to unlock input bitmap");
- return JNI_FALSE;
- }
-
- if (freeInputRGBA) {
- delete inputBufferRGBA;
- }
-
- // Create debug bitmap from output image data
- if (outputImage != NULL) {
- // Get method handles, create inputs to createBitmap
- jclass bitmapClass =
- env->FindClass("android/graphics/Bitmap");
- jclass bitmapConfigClass =
- env->FindClass("android/graphics/Bitmap$Config");
-
- jmethodID createBitmap = env->GetStaticMethodID(
- bitmapClass, "createBitmap",
- "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
-
- jmethodID getConfig = env->GetStaticMethodID(
- bitmapConfigClass, "valueOf",
- "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
-
- // Create bitmap config and bitmap
- jstring bitmapConfigValue = env->NewStringUTF("ARGB_8888");
- jobject rgbaConfig = env->CallStaticObjectMethod(bitmapConfigClass,
- getConfig,
- bitmapConfigValue);
- jobject outputBitmap = env->CallStaticObjectMethod(bitmapClass,
- createBitmap,
- outputWidth,
- outputHeight,
- rgbaConfig);
- // Copy output image into it
- uint8_t *outputBuffer;
- int result = AndroidBitmap_lockPixels(
- env,
- outputBitmap,
- reinterpret_cast(&outputBuffer) );
-
- if (result != ANDROID_BITMAP_RESUT_SUCCESS) {
- LOGE("Unable to lock output bitmap");
- return JNI_FALSE;
- }
-
- memcpy(outputBuffer, outputImage, outputWidth * outputHeight * 4);
-
- result = AndroidBitmap_unlockPixels(env, outputBitmap);
- if (result != ANDROID_BITMAP_RESUT_SUCCESS) {
- LOGE("Unable to unlock output bitmap");
- return JNI_FALSE;
- }
-
- // Write new Bitmap reference into mDebugOutput class member
- env->SetObjectField(thiz, outputId, outputBitmap);
-
- delete outputImage;
- }
- if (!success) return JNI_FALSE;
-
- return JNI_TRUE;
-}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorChecker.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorChecker.h
deleted file mode 100644
index a9b4487..0000000
--- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorChecker.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-#ifndef JNI_CAMERAANALYZER_COLORCHECKER_H
-#define JNI_CAMERAANALYZER_COLORCHECKER_H
-
-#include
-#include
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jboolean JNICALL
-Java_com_android_cts_verifier_camera_analyzer_ColorChecker_findNative(
- JNIEnv *env,
- jobject thiz,
- jobject inputBitmap);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* JNI_CAMERAANALYZER_COLORCHECKER_H */
diff --git a/apps/CtsVerifier/jni/verifier/Android.mk b/apps/CtsVerifier/jni/verifier/Android.mk
index da4687d..98a4678 100644
--- a/apps/CtsVerifier/jni/verifier/Android.mk
+++ b/apps/CtsVerifier/jni/verifier/Android.mk
@@ -21,7 +21,7 @@ LOCAL_MODULE := libctsverifier_jni
LOCAL_MODULE_TAGS := optional
-
+LOCAL_PRELINK_MODULE := false
LOCAL_SRC_FILES := \
CtsVerifierJniOnLoad.cpp \
diff --git a/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_os_FileUtils.cpp b/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_os_FileUtils.cpp
index 9c69f1a..14e58eb 100644
--- a/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_os_FileUtils.cpp
+++ b/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_os_FileUtils.cpp
@@ -21,6 +21,7 @@
#include
#include
+static jclass gFileStatusClass;
static jfieldID gFileStatusDevFieldID;
static jfieldID gFileStatusInoFieldID;
static jfieldID gFileStatusModeFieldID;
@@ -94,19 +95,19 @@ int register_com_android_cts_verifier_os_FileUtils(JNIEnv* env)
{
jclass clazz = env->FindClass("com/android/cts/verifier/os/FileUtils");
- jclass fileStatusClass = env->FindClass("com/android/cts/verifier/os/FileUtils$FileStatus");
- gFileStatusDevFieldID = env->GetFieldID(fileStatusClass, "dev", "I");
- gFileStatusInoFieldID = env->GetFieldID(fileStatusClass, "ino", "I");
- gFileStatusModeFieldID = env->GetFieldID(fileStatusClass, "mode", "I");
- gFileStatusNlinkFieldID = env->GetFieldID(fileStatusClass, "nlink", "I");
- gFileStatusUidFieldID = env->GetFieldID(fileStatusClass, "uid", "I");
- gFileStatusGidFieldID = env->GetFieldID(fileStatusClass, "gid", "I");
- gFileStatusSizeFieldID = env->GetFieldID(fileStatusClass, "size", "J");
- gFileStatusBlksizeFieldID = env->GetFieldID(fileStatusClass, "blksize", "I");
- gFileStatusBlocksFieldID = env->GetFieldID(fileStatusClass, "blocks", "J");
- gFileStatusAtimeFieldID = env->GetFieldID(fileStatusClass, "atime", "J");
- gFileStatusMtimeFieldID = env->GetFieldID(fileStatusClass, "mtime", "J");
- gFileStatusCtimeFieldID = env->GetFieldID(fileStatusClass, "ctime", "J");
+ gFileStatusClass = env->FindClass("com/android/cts/verifier/os/FileUtils$FileStatus");
+ gFileStatusDevFieldID = env->GetFieldID(gFileStatusClass, "dev", "I");
+ gFileStatusInoFieldID = env->GetFieldID(gFileStatusClass, "ino", "I");
+ gFileStatusModeFieldID = env->GetFieldID(gFileStatusClass, "mode", "I");
+ gFileStatusNlinkFieldID = env->GetFieldID(gFileStatusClass, "nlink", "I");
+ gFileStatusUidFieldID = env->GetFieldID(gFileStatusClass, "uid", "I");
+ gFileStatusGidFieldID = env->GetFieldID(gFileStatusClass, "gid", "I");
+ gFileStatusSizeFieldID = env->GetFieldID(gFileStatusClass, "size", "J");
+ gFileStatusBlksizeFieldID = env->GetFieldID(gFileStatusClass, "blksize", "I");
+ gFileStatusBlocksFieldID = env->GetFieldID(gFileStatusClass, "blocks", "J");
+ gFileStatusAtimeFieldID = env->GetFieldID(gFileStatusClass, "atime", "J");
+ gFileStatusMtimeFieldID = env->GetFieldID(gFileStatusClass, "mtime", "J");
+ gFileStatusCtimeFieldID = env->GetFieldID(gFileStatusClass, "ctime", "J");
return env->RegisterNatives(clazz, gMethods,
sizeof(gMethods) / sizeof(JNINativeMethod));
diff --git a/apps/CtsVerifier/lib/Android.mk b/apps/CtsVerifier/lib/Android.mk
deleted file mode 100644
index 56a3fa8..0000000
--- a/apps/CtsVerifier/lib/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# 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.
-#
-
-include $(call all-subdir-makefiles)
diff --git a/apps/CtsVerifier/lib/colorchecker/Android.mk b/apps/CtsVerifier/lib/colorchecker/Android.mk
deleted file mode 100644
index 97f0089..0000000
--- a/apps/CtsVerifier/lib/colorchecker/Android.mk
+++ /dev/null
@@ -1,33 +0,0 @@
-# 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)
-
-#####################
-# Build image analysis library
-
-include $(CLEAR_VARS)
-include external/stlport/libstlport.mk
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE := libcolorchecker
-
-LOCAL_SRC_FILES += colorchecker.cpp
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../include/colorchecker
-LOCAL_SHARED_LIBRARIES := libstlport \
- libcutils \
- libutils
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/apps/CtsVerifier/lib/colorchecker/colorchecker.cpp b/apps/CtsVerifier/lib/colorchecker/colorchecker.cpp
deleted file mode 100644
index 1e0ae97..0000000
--- a/apps/CtsVerifier/lib/colorchecker/colorchecker.cpp
+++ /dev/null
@@ -1,714 +0,0 @@
-/*
- * 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.
- */
-
-//#define LOG_NDEBUG 0
-#include
-#include
-
-#include "colorchecker.h"
-#include "grouping.h"
-#include
-#include
-#include
-#include
-#include
-
-const int totalChannels = 4; // Input image channel count
-const int colorChannels = 3; // Input image color channel count
-const float gammaCorrection = 2.2; // Assumed gamma curve on input
-const int thresholdSq = 675; // Threshold on pixel difference to be considered
- // part of the same patch
-
-class PixelId {
- public:
- int id;
- const unsigned char *p;
-
- PixelId(): id(0), p(NULL) {}
-
- bool operator!=(const PixelId &other) const {
- int dR = ((int)p[0] - other.p[0]) * ((int)p[0] - other.p[0]);
- int dG = ((int)p[1] - other.p[1]) * ((int)p[1] - other.p[1]);
- int dB = ((int)p[2] - other.p[2]) * ((int)p[2] - other.p[2]);
- int distSq = dR + dG + dB;
- if (distSq > thresholdSq) return true;
- else return false;
- }
-};
-
-class ImageField: public Field {
- public:
- ImageField(int width, int height, const unsigned char *data):
- mWidth(width), mHeight(height), pData(data) {
- }
-
- PixelId operator() (int y, int x) const {
- PixelId pId;
- pId.p = pData + (y * mWidth + x ) * totalChannels;
- if (mask.size() != 0) {
- pId.id = mask[y][x];
- }
- return pId;
- }
-
- int getWidth() const { return mWidth; }
- int getHeight() const { return mHeight; }
- private:
- int mWidth;
- int mHeight;
- const unsigned char *pData;
-};
-
-class PixelGroup {
- public:
- PixelGroup(int id, const ImageField *src):
- mId(id),
- mMinX(1e7),
- mMinY(1e7),
- mMaxX(0),
- mMaxY(0),
- mArea(0),
- mSrc(src),
- mRNeighbor(NULL),
- mDNeighbor(NULL),
- mLNeighbor(NULL),
- mUNeighbor(NULL) {
- mSum[0] = 0;
- mSum[1] = 0;
- mSum[2] = 0;
- }
-
- struct IdCompare {
- bool operator() (const PixelGroup* l, const PixelGroup* r) const {
- return l->getId() < r->getId();
- }
- };
-
- void growGroup(int x, int y) {
- if (x < mMinX) mMinX = x;
- if (x > mMaxX) mMaxX = x;
- if (y < mMinY) mMinY = y;
- if (y > mMaxY) mMaxY = y;
- mArea++;
- const unsigned char *p = (*mSrc)(y,x).p;
- mSum[0] += p[0];
- mSum[1] += p[1];
- mSum[2] += p[2];
- }
-
- int getId() const {
- return mId;
- }
-
- int getArea() const {
- return mArea;
- }
-
- int getBoundArea() const {
- return (mMaxX - mMinX) * (mMaxY - mMinY);
- }
-
- float getApproxAspectRatio() const {
- return ((float)(mMaxY - mMinY)) / (mMaxX - mMinX);
- }
-
- void getApproxCenter(int *x, int *y) const {
- *x = (mMaxX + mMinX)/2;
- *y = (mMaxY + mMinY)/2;
- }
-
- void getBoundingBox(int *x1, int *y1, int *x2, int *y2) const {
- *x1 = mMinX;
- *x2 = mMaxX;
- *y1 = mMinY;
- *y2 = mMaxY;
- }
-
- void getAvgValue(unsigned char *p) const {
- p[0] = mSum[0] / mArea;
- p[1] = mSum[1] / mArea;
- p[2] = mSum[2] / mArea;
- }
-
- bool operator<(const PixelGroup &other) const {
- return mArea < other.getArea();
- }
-
- typedef std::set IdSet;
- typedef std::set::iterator IdSetIter;
-
- void findNeighbors(IdSet &candidates) {
- int cX, cY;
- getApproxCenter(&cX, &cY);
- int rDistSq = 1e9; // Larger than any reasonable image distance
- int dDistSq = rDistSq;
-
- for (IdSetIter neighbor = candidates.begin();
- neighbor != candidates.end();
- neighbor++) {
- if (*neighbor == this) continue;
- int nX, nY;
- (*neighbor)->getApproxCenter(&nX, &nY);
- // 'right' means slope between (-1/3, 1/3), positive X change
- if ( (nX - cX) > 0 ) {
- float slope = ((float)(nY - cY)) / (nX - cX);
- if (slope > -0.33 && slope < 0.33) {
- int distSq = (nX - cX) * (nX - cX) + (nY - cY) * (nY - cY);
- if (distSq < rDistSq) {
- setRNeighbor(*neighbor);
- rDistSq = distSq;
- }
- }
- }
- // 'down' means inv slope between (-1/3, 1/3), positive Y change
- if ( (nY - cY) > 0) {
- float invSlope = ((float)(nX - cX)) / (nY - cY);
- if (invSlope > -0.33 && invSlope < 0.33) {
- int distSq = (nX - cX) * (nX - cX) + (nY - cY) * (nY - cY);
- if (distSq < dDistSq) {
- setDNeighbor(*neighbor);
- dDistSq = distSq;
- }
- }
- }
- }
- // Do reverse links if possible
- if (getRNeighbor() != NULL) {
- getRNeighbor()->setLNeighbor(this);
- }
- if (getDNeighbor() != NULL) {
- getDNeighbor()->setUNeighbor(this);
- }
-
- }
-
- void setRNeighbor(PixelGroup *rNeighbor) {
- mRNeighbor = rNeighbor;
- }
-
- PixelGroup* getRNeighbor(int distance = 1) {
- PixelGroup *current = this;
- for (int i=0; i < distance; i++) {
- if (current != NULL) {
- current = current->mRNeighbor;
- } else break;
- }
- return current;
- }
-
- void setDNeighbor(PixelGroup *dNeighbor) {
- mDNeighbor = dNeighbor;
- }
-
- PixelGroup* getDNeighbor(int distance = 1) {
- PixelGroup *current = this;
- for (int i=0; i < distance; i++) {
- if (current != NULL) {
- current = current->mDNeighbor;
- } else break;
- }
- return current;
- }
-
- void setLNeighbor(PixelGroup *lNeighbor) {
- mLNeighbor = lNeighbor;
- }
-
- PixelGroup* getLNeighbor(int distance = 1) {
- PixelGroup *current = this;
- for (int i=0; i < distance; i++) {
- if (current != NULL) {
- current = current->mLNeighbor;
- } else break;
- }
- return current;
- }
-
- void setUNeighbor(PixelGroup *uNeighbor) {
- mUNeighbor = uNeighbor;
- }
-
- PixelGroup* getUNeighbor(int distance = 1) {
- PixelGroup *current = this;
- for (int i=0; i < distance; i++) {
- if (current != NULL) {
- current = current->mUNeighbor;
- } else break;
- }
- return current;
- }
-
- float distanceSqTo(const PixelGroup* other) {
- int mX, mY;
- getApproxCenter(&mX, &mY);
- int oX, oY;
- other->getApproxCenter(&oX, &oY);
- int dx = (oX - mX);
- int dy = (oY - mY);
- return dx * dx + dy * dy;
- }
-
- float distanceTo(const PixelGroup* other) {
- return sqrt( distanceSqTo(other) );
- }
-
- private:
- int mId;
- int mMinX, mMinY;
- int mMaxX, mMaxY;
- int mArea;
- int mSum[3];
- const ImageField *mSrc;
-
- PixelGroup *mRNeighbor;
- PixelGroup *mDNeighbor;
- PixelGroup *mLNeighbor;
- PixelGroup *mUNeighbor;
-};
-
-/* Scales input down by factor of outScale to output. Assumes input size is
- * exactly output size times scale */
-void downsample(const unsigned char *input,
- unsigned char *output,
- int rowSpan,
- int outWidth,
- int outHeight,
- int outScale) {
- for (int oY = 0, iY = 0; oY < outHeight; oY++, iY += outScale) {
- for (int oX = 0, iX = 0; oX < outWidth; oX++, iX += outScale) {
- short out[3] = {0,0,0};
- const unsigned char *in = input + iY * rowSpan + iX * totalChannels;
- for (int j = 0; j < outScale; j++) {
- for (int k = 0; k < outScale; k++) {
- for (int i = 0; i < colorChannels; i++) {
- out[i] += in[i];
- }
- in += totalChannels;
- }
- in += rowSpan - outScale * totalChannels;
- }
- output[0] = out[0] / (outScale * outScale);
- output[1] = out[1] / (outScale * outScale);
- output[2] = out[2] / (outScale * outScale);
- output += totalChannels;
- }
- }
-}
-
-void drawLine(unsigned char *image,
- int rowSpan,
- int x0, int y0,
- int x1, int y1,
- int r, int g, int b) {
- if ((x0 == x1) && (y0 == y1)) {
- unsigned char *p = &image[(y0 * rowSpan + x0) * totalChannels];
- if (r != -1) p[0] = r;
- if (g != -1) p[1] = g;
- if (b != -1) p[2] = b;
- return;
- }
- if ( std::abs(x1-x0) > std::abs(y1-y0) ) {
- if (x0 > x1) {
- std::swap(x0, x1);
- std::swap(y0, y1);
- }
- float slope = (float)(y1 - y0) / (x1 - x0);
- for (int x = x0; x <= x1; x++) {
- int y = y0 + slope * (x - x0);
- unsigned char *p = &image[(y * rowSpan + x) * totalChannels];
- if (r != -1) p[0] = r;
- if (g != -1) p[1] = g;
- if (b != -1) p[2] = b;
- }
- } else {
- if (y0 > y1) {
- std::swap(x0, x1);
- std::swap(y0, y1);
- }
- float invSlope = (float)(x1 - x0) / (y1 - y0);
- for (int y = y0; y <= y1; y++) {
- int x = x0 + invSlope * (y - y0);
- unsigned char *p = &image[(y*rowSpan + x) * totalChannels];
- if (r != -1) p[0] = r;
- if (g != -1) p[1] = g;
- if (b != -1) p[2] = b;
- }
- }
-
-}
-bool findColorChecker(const unsigned char *image,
- int width,
- int rowSpan,
- int height,
- float *patchColors,
- unsigned char **outputImage,
- int *outputWidth,
- int *outputHeight) {
- int64_t startTime = systemTime();
-
- const int outTargetWidth = 160;
- const int outScale = width / outTargetWidth;
- const int outWidth = width / outScale;
- const int outHeight = height / outScale;
- LOGV("Debug image dimensions: %d, %d", outWidth, outHeight);
-
- unsigned char *output = new unsigned char[outWidth * outHeight * totalChannels];
-
- unsigned char *outP;
- unsigned char *inP;
-
- // First step, downsample for speed/noise reduction
- downsample(image, output, rowSpan, outWidth, outHeight, outScale);
-
- // Find connected components (groups)
- ImageField outField(outWidth, outHeight, output);
- Grouping(&outField);
-
- // Calculate component bounds and areas
- std::vector groups;
- groups.reserve(outField.id_no);
- for (int i = 0; i < outField.id_no; i++) {
- groups.push_back(PixelGroup(i + 1, &outField));
- }
-
- inP = output;
- for (int y = 0; y < outHeight; y++) {
- for (int x = 0; x < outWidth; x++) {
- groups[ outField(y, x).id - 1].growGroup(x, y);
- }
- }
-
- // Filter out groups that are too small, too large, or have too
- // non-square aspect ratio
- PixelGroup::IdSet candidateGroups;
-
- // Maximum/minimum width assuming pattern is fully visible and >
- // 1/3 the image in width
- const int maxPatchWidth = outWidth / 6;
- const int minPatchWidth = outWidth / 3 / 7;
- const int maxPatchArea = maxPatchWidth * maxPatchWidth;
- const int minPatchArea = minPatchWidth * minPatchWidth;
- // Assuming nearly front-on view of target, so aspect ratio should
- // be quite close to square
- const float maxAspectRatio = 5.f / 4.f;
- const float minAspectRatio = 4.f / 5.f;
- for (int i = 0; i < (int)groups.size(); i++) {
- float aspect = groups[i].getApproxAspectRatio();
- if (aspect < minAspectRatio || aspect > maxAspectRatio) continue;
- // Check both boundary box area, and actual pixel count - they
- // should both be within bounds for a roughly square patch.
- int boundArea = groups[i].getBoundArea();
- if (boundArea < minPatchArea || boundArea > maxPatchArea) continue;
- int area = groups[i].getArea();
- if (area < minPatchArea || area > maxPatchArea) continue;
- candidateGroups.insert(&groups[i]);
- }
-
- // Find neighbors for candidate groups. O(n^2), but not many
- // candidates to go through
- for (PixelGroup::IdSetIter group = candidateGroups.begin();
- group != candidateGroups.end();
- group++) {
- (*group)->findNeighbors(candidateGroups);
- }
-
- // Try to find a plausible 6x4 grid by taking each pixel group as
- // the candidate top-left corner and try to build a grid from
- // it. Assumes no missing patches.
- float bestError = -1;
- std::vector bestGrid(6 * 4,0);
- for (PixelGroup::IdSetIter group = candidateGroups.begin();
- group != candidateGroups.end();
- group++) {
- int dex, dey; (*group)->getApproxCenter(&dex, &dey);
- std::vector grid(6 * 4, 0);
- PixelGroup *tl = *group;
- PixelGroup *bl, *tr, *br;
-
- // Find the bottom-left and top-right corners
- if ( (bl = tl->getDNeighbor(3)) == NULL ||
- (tr = tl->getRNeighbor(5)) == NULL ) continue;
- LOGV("Candidate at %d, %d", dex, dey);
- LOGV(" Got BL and TR");
-
- // Find the bottom-right corner
- if ( tr->getDNeighbor(3) == NULL ) {
- LOGV(" No BR from TR");
- continue;
- }
- br = tr->getDNeighbor(3);
- if ( br != bl->getRNeighbor(5) ) {
- LOGV(" BR from TR and from BL don't agree");
- continue;
- }
- br->getApproxCenter(&dex, &dey);
- LOGV(" Got BR corner at %d, %d", dex, dey);
-
- // Check that matching grid edge lengths are about the same
- float gridTopWidth = tl->distanceTo(tr);
- float gridBotWidth = bl->distanceTo(br);
-
- if (gridTopWidth / gridBotWidth < minAspectRatio ||
- gridTopWidth / gridBotWidth > maxAspectRatio) continue;
- LOGV(" Got reasonable widths: %f %f", gridTopWidth, gridBotWidth);
-
- float gridLeftWidth = tl->distanceTo(bl);
- float gridRightWidth = tr->distanceTo(br);
-
- if (gridLeftWidth / gridRightWidth < minAspectRatio ||
- gridLeftWidth / gridRightWidth > maxAspectRatio) continue;
- LOGV(" Got reasonable heights: %f %f", gridLeftWidth, gridRightWidth);
-
- // Calculate average grid spacing
- float gridAvgXGap = (gridTopWidth + gridBotWidth) / 2 / 5;
- float gridAvgYGap = (gridLeftWidth + gridRightWidth) / 2 / 3;
-
- // Calculate total error between average grid spacing and
- // actual spacing Uses difference in expected squared distance
- // and actual squared distance
- float error = 0;
- for (int x = 0; x < 6; x++) {
- for (int y = 0; y < 4; y++) {
- PixelGroup *node;
- node = tl->getRNeighbor(x)->getDNeighbor(y);
- if (node == NULL) {
- error += outWidth * outWidth;
- grid[y * 6 + x] = 0;
- } else {
- grid[y * 6 + x] = node->getId();
- if (node == tl) continue;
- float dist = tl->distanceSqTo(node);
- float expXDist = (gridAvgXGap * x);
- float expYDist = (gridAvgYGap * y);
- float expDist = expXDist * expXDist + expYDist * expYDist;
- error += fabs(dist - expDist);
- }
- }
- }
- if (bestError == -1 ||
- bestError > error) {
- bestGrid = grid;
- bestError = error;
- LOGV(" Best candidate, error %f", error);
- }
- }
-
- // Check if a grid wasn't found
- if (bestError == -1) {
- LOGV("No color checker found!");
- }
-
- // Make sure black square is in bottom-right corner
- if (bestError != -1) {
- unsigned char tlValues[3];
- unsigned char brValues[3];
- int tlId = bestGrid[0];
- int brId = bestGrid[23];
-
- groups[tlId - 1].getAvgValue(tlValues);
- groups[brId - 1].getAvgValue(brValues);
-
- int tlSum = tlValues[0] + tlValues[1] + tlValues[2];
- int brSum = brValues[0] + brValues[1] + brValues[2];
- if (brSum > tlSum) {
- // Grid is upside down, need to flip!
- LOGV("Flipping grid to put grayscale ramp at bottom");
- bestGrid = std::vector(bestGrid.rbegin(), bestGrid.rend());
- }
- }
-
- // Output average patch colors if requested
- if (bestError != -1 && patchColors != NULL) {
- for (int n = 0; n < 6 * 4 * colorChannels; n++) patchColors[n] = -1.f;
-
- // Scan over original input image for grid regions, degamma, average
- for (int px = 0; px < 6; px++) {
- for (int py = 0; py < 4; py++) {
- int id = bestGrid[py * 6 + px];
- if (id == 0) continue;
-
- PixelGroup &patch = groups[id - 1];
- int startX, startY;
- int endX, endY;
- patch.getBoundingBox(&startX, &startY, &endX, &endY);
-
- float sum[colorChannels] = {0.f};
- int count = 0;
- for (int y = startY; y <= endY; y++) {
- for (int x = startX; x < endX; x++) {
- if (outField(y,x).id != id) continue;
- for (int iY = y * outScale;
- iY < (y + 1) * outScale;
- iY++) {
- const unsigned char *inP = image +
- (iY * rowSpan)
- + (x * outScale * totalChannels);
- for (int iX = 0; iX < outScale; iX++) {
- for (int c = 0; c < colorChannels; c++) {
- // Convert to float and normalize
- float v = inP[c] / 255.f;
- // Gamma correct to get back to
- // roughly linear data
- v = pow(v, gammaCorrection);
- // Sum it up
- sum[c] += v;
- }
- count++;
- inP += totalChannels;
- }
- }
- }
- }
- for (int c = 0 ; c < colorChannels; c++) {
- patchColors[ (py * 6 + px) * colorChannels + c ] =
- sum[c] / count;
- }
- }
- }
- // Print out patch colors
- IF_LOGV() {
- for (int y = 0; y < 4; y++) {
- char tmpMsg[256];
- int cnt = 0;
- cnt = snprintf(tmpMsg, 256, "%02d:", y + 1);
- for (int x = 0; x < 6; x++) {
- int id = bestGrid[y * 6 + x];
- if (id != 0) {
- float *p = &patchColors[ (y * 6 + x) * colorChannels];
- cnt += snprintf(tmpMsg + cnt, 256 - cnt,
- "\t(%.3f,%.3f,%.3f)", p[0], p[1], p[2]);
- } else {
- cnt += snprintf(tmpMsg + cnt, 256 - cnt,
- "\t(xxx,xxx,xxx)");
- }
- }
- LOGV("%s", tmpMsg);
- }
- }
- }
-
- // Draw output if requested
- if (outputImage != NULL) {
- *outputImage = output;
- *outputWidth = outWidth;
- *outputHeight = outHeight;
-
- // Draw all candidate group bounds
- for (PixelGroup::IdSetIter group = candidateGroups.begin();
- group != candidateGroups.end();
- group++) {
-
- int x,y;
- (*group)->getApproxCenter(&x, &y);
-
- // Draw candidate bounding box
- int x0, y0, x1, y1;
- (*group)->getBoundingBox(&x0, &y0, &x1, &y1);
- drawLine(output, outWidth,
- x0, y0, x1, y0,
- 255, 0, 0);
- drawLine(output, outWidth,
- x1, y0, x1, y1,
- 255, 0, 0);
- drawLine(output, outWidth,
- x1, y1, x0, y1,
- 255, 0, 0);
- drawLine(output, outWidth,
- x0, y1, x0, y0,
- 255, 0, 0);
-
- // Draw lines between neighbors
- // Red for to-right and to-below of me connections
- const PixelGroup *neighbor;
- if ( (neighbor = (*group)->getRNeighbor()) != NULL) {
- int nX, nY;
- neighbor->getApproxCenter(&nX, &nY);
- drawLine(output,
- outWidth,
- x, y, nX, nY,
- 255, -1, -1);
- }
- if ( (neighbor = (*group)->getDNeighbor()) != NULL) {
- int nX, nY;
- neighbor->getApproxCenter(&nX, &nY);
- drawLine(output,
- outWidth,
- x, y, nX, nY,
- 255, -1, -1);
- }
- // Blue for to-left or to-above of me connections
- if ( (neighbor = (*group)->getLNeighbor()) != NULL) {
- int nX, nY;
- neighbor->getApproxCenter(&nX, &nY);
- drawLine(output,
- outWidth,
- x, y, nX, nY,
- -1, -1, 255);
- }
- if ( (neighbor = (*group)->getUNeighbor()) != NULL) {
- int nX, nY;
- neighbor->getApproxCenter(&nX, &nY);
- drawLine(output,
- outWidth,
- x, y, nX, nY,
- -1, -1, 255);
- }
- }
-
- // Mark found grid patch pixels
- if (bestError != -1) {
- for (int x=0; x < 6; x++) {
- for (int y =0; y < 4; y++) {
- int id = bestGrid[y * 6 + x];
- if (id != 0) {
- int x0, y0, x1, y1;
- groups[id - 1].getBoundingBox(&x0, &y0, &x1, &y1);
- // Fill patch pixels with blue
- for (int px = x0; px < x1; px++) {
- for (int py = y0; py < y1; py++) {
- if (outField(py,px).id != id) continue;
- unsigned char *p =
- &output[(py * outWidth + px)
- * totalChannels];
- p[0] = 0;
- p[1] = 0;
- p[2] = 255;
-
- }
- }
- drawLine(output, outWidth,
- x0, y0, x1, y1,
- 0, 255, 0);
- drawLine(output, outWidth,
- x0, y1, x0, y1,
- 0, 255, 0);
- }
- }
- }
- }
-
- } else {
- delete output;
- }
-
- int64_t endTime = systemTime();
- LOGV("Process time: %f ms",
- (endTime - startTime) / 1000000.);
-
- if (bestError == -1) return false;
-
- return true;
-}
diff --git a/apps/CtsVerifier/lib/colorchecker/grouping.h b/apps/CtsVerifier/lib/colorchecker/grouping.h
deleted file mode 100755
index 3125f55..0000000
--- a/apps/CtsVerifier/lib/colorchecker/grouping.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * 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.
- */
-
-#include
-#include
-
-#ifndef FILTERPACK_CALIBRATION_GROUPING_H
-#define FILTERPACK_CALIBRATION_GROUPING_H
-
-// To use the Grouping function, derive one class from Field.
-// Field class provides the interface for the Grouping function.
-// FF_ID is the pixel class used to compare values,
-// != operator must be defined in this class
-// region number of the pixel
-
-typedef std::vector > MASK;
-typedef std::pair POS;
-// FF_ID needs to implement the operator !=
-// bool operator != (const FF_ID &id)
-template
-class Field {
- public:
- int id_no;
- MASK mask;
- virtual FF_ID operator () (int y, int x) const =0 ;
- virtual int getWidth() const = 0;
- virtual int getHeight() const= 0;
- virtual ~Field() {}
-};
-
-template < class FF_ID>
-void FloodFill(int sx,
- int sy,
- int id_no,
- const FF_ID &id,
- Field *pField,
- POS *new_pos) {
- std::vector stack;
- stack.push_back(POS(sx,sy));
- while (stack.size() > 0) {
- sx = stack.back().first;
- sy = stack.back().second;
- stack.pop_back();
-
- // fill the current line
- int x;
- for (x = sx-1; x >= 0; x--)
- {
- if (pField->mask[sy][x]!=0) break;
- if (id != (*pField)(sy,x)) {
- new_pos->first = x;
- new_pos->second =sy;
- break;
- }
- pField->mask[sy][x] = id_no;
- }
- int startx = x;
- for (x = sx;x < pField->getWidth(); x++) {
- if (pField->mask[sy][x]!=0) break;
- if (id != (*pField)(sy,x)) {
- new_pos->first = x;
- new_pos->second =sy;
- break;
- }
- pField->mask[sy][x] = id_no;
- }
- int endx = x;
- if (endx >= pField->getWidth()) endx = pField->getWidth() - 1;
- if (startx < 0) startx = 0;
- // push the adjacent spans to the stack
- if (sy>0) {
- int bNew = true;
- for (x = endx; x >= startx; x--) {
- if (pField->mask[sy-1][x] != 0 || id != (*pField)(sy-1,x) ) {
- bNew = true;
- continue;
- }
- if (bNew) {
- stack.push_back( POS(x, sy-1));
- bNew = false;
- }
- }
- }
- if (sy < (pField->getHeight() - 1)) {
- int bNew = true;
- for (x = endx; x >= startx; x--) {
- if (pField->mask[sy+1][x]!=0 || id != (*pField)(sy+1,x)) {
- bNew = true;
- continue;
- }
- if (bNew) {
- stack.push_back( POS(x, sy+1));
- bNew = false;
- }
- }
- }
- }
-}
-
-// Group the pixels in Field based on the FF_ID != operator.
-// All pixels will be labeled from 1. The total number of unique groups(regions)
-// is (pField->id_no - 1) after the call
-// The labeasl of the pixels are stored in the mask member of Field.
-
-template
-void Grouping(Field *pField) {
- int width = pField->getWidth();
- int height = pField->getHeight();
- pField->mask = MASK(height, std::vector (width, 0) );
-
- FF_ID id;
- pField->id_no = 1;
- int sx = width / 2, sy = height / 2;
- POS new_pos(-1,-1);
- while (1) {
- id = (*pField)(sy,sx);
- int id_no = pField->id_no;
- new_pos.first = -1;
- new_pos.second = -1;
- FloodFill(sx, sy, id_no, id, pField, &new_pos);
- if (new_pos.first < 0) // no new position found, during the flood fill
- {
- const int kNumOfRetries = 10;
- // try 10 times for the new unfilled position
- for (int i = 0; i < kNumOfRetries; i++) {
- sx = rand() % width;
- sy = rand() % height;
- if (pField->mask[sy][sx] == 0) {
- new_pos.first = sx;
- new_pos.second = sy;
- break;
- }
- }
- if (new_pos.first < 0) { // still failed, search the whole image
- for (int y = 0; y < height && new_pos.first < 0; y++)
- for (int x = 0; x < width; x++) {
- if (pField->mask[y][x] == 0) {
- new_pos.first = x;
- new_pos.second = y;
- break;
- }
- }
- }
- if (new_pos.first < 0) break; // finished
- }
- sx = new_pos.first;
- sy = new_pos.second;
- pField->id_no++;
- }
-}
-
-#endif
diff --git a/apps/CtsVerifier/proguard.flags b/apps/CtsVerifier/proguard.flags
deleted file mode 100644
index ddaf962..0000000
--- a/apps/CtsVerifier/proguard.flags
+++ /dev/null
@@ -1,8 +0,0 @@
--keepclasseswithmembernames class * {
- native ;
-}
-
--keepclassmembers class com.android.cts.verifier.os.FileUtils$FileStatus {
- private ;
-}
-
diff --git a/apps/CtsVerifier/res/drawable/gray_bubble.xml b/apps/CtsVerifier/res/drawable/gray_bubble.xml
deleted file mode 100644
index 66eda76..0000000
--- a/apps/CtsVerifier/res/drawable/gray_bubble.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout-land/usb_main.xml b/apps/CtsVerifier/res/layout-land/usb_main.xml
deleted file mode 100644
index 139b54b..0000000
--- a/apps/CtsVerifier/res/layout-land/usb_main.xml
+++ /dev/null
@@ -1,87 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/bt_connection_access.xml b/apps/CtsVerifier/res/layout/bt_connection_access.xml
deleted file mode 100644
index ae373f4..0000000
--- a/apps/CtsVerifier/res/layout/bt_connection_access.xml
+++ /dev/null
@@ -1,64 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/bt_main.xml b/apps/CtsVerifier/res/layout/bt_main.xml
new file mode 100644
index 0000000..cb65412
--- /dev/null
+++ b/apps/CtsVerifier/res/layout/bt_main.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
diff --git a/apps/CtsVerifier/res/layout/bt_message_row.xml b/apps/CtsVerifier/res/layout/bt_message_row.xml
index 3bb228a..c37eece 100644
--- a/apps/CtsVerifier/res/layout/bt_message_row.xml
+++ b/apps/CtsVerifier/res/layout/bt_message_row.xml
@@ -16,5 +16,6 @@
diff --git a/apps/CtsVerifier/res/layout/bt_toggle.xml b/apps/CtsVerifier/res/layout/bt_toggle.xml
index 71def84..3a07514 100644
--- a/apps/CtsVerifier/res/layout/bt_toggle.xml
+++ b/apps/CtsVerifier/res/layout/bt_toggle.xml
@@ -24,7 +24,7 @@
android:layout_alignParentTop="true"
android:gravity="center"
android:text="@string/bt_toggle_instructions"
- style="@style/InstructionsFont"
+ android:textSize="24dip"
/>
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/bu_preference_row.xml b/apps/CtsVerifier/res/layout/bu_preference_row.xml
deleted file mode 100644
index c37eece..0000000
--- a/apps/CtsVerifier/res/layout/bu_preference_row.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
diff --git a/apps/CtsVerifier/res/layout/ca_main.xml b/apps/CtsVerifier/res/layout/ca_main.xml
deleted file mode 100644
index 98ec049..0000000
--- a/apps/CtsVerifier/res/layout/ca_main.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/da_policy_main.xml b/apps/CtsVerifier/res/layout/da_policy_main.xml
deleted file mode 100644
index b80649e..0000000
--- a/apps/CtsVerifier/res/layout/da_policy_main.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/da_screen_lock_main.xml b/apps/CtsVerifier/res/layout/da_screen_lock_main.xml
deleted file mode 100644
index eaca05f..0000000
--- a/apps/CtsVerifier/res/layout/da_screen_lock_main.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/main.xml b/apps/CtsVerifier/res/layout/main.xml
index cdfb8f4..d6cb6cd 100644
--- a/apps/CtsVerifier/res/layout/main.xml
+++ b/apps/CtsVerifier/res/layout/main.xml
@@ -26,21 +26,12 @@
android:text="@string/continue_button_text"
/>
-
diff --git a/apps/CtsVerifier/res/layout/pass_fail_list.xml b/apps/CtsVerifier/res/layout/pass_fail_list.xml
deleted file mode 100644
index 3c1f9d0..0000000
--- a/apps/CtsVerifier/res/layout/pass_fail_list.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/report_viewer.xml b/apps/CtsVerifier/res/layout/report_viewer.xml
deleted file mode 100644
index c397582..0000000
--- a/apps/CtsVerifier/res/layout/report_viewer.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
diff --git a/apps/CtsVerifier/res/layout/snsr_gyro.xml b/apps/CtsVerifier/res/layout/snsr_gyro.xml
deleted file mode 100644
index d4d7000..0000000
--- a/apps/CtsVerifier/res/layout/snsr_gyro.xml
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/sv_play.xml b/apps/CtsVerifier/res/layout/sv_play.xml
deleted file mode 100644
index be68868..0000000
--- a/apps/CtsVerifier/res/layout/sv_play.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/usb_main.xml b/apps/CtsVerifier/res/layout/usb_main.xml
deleted file mode 100644
index 5c16612..0000000
--- a/apps/CtsVerifier/res/layout/usb_main.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/res/layout/usb_message_row.xml b/apps/CtsVerifier/res/layout/usb_message_row.xml
deleted file mode 100644
index 3bb228a..0000000
--- a/apps/CtsVerifier/res/layout/usb_message_row.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
diff --git a/apps/CtsVerifier/res/layout/vertical_divider.xml b/apps/CtsVerifier/res/layout/vertical_divider.xml
deleted file mode 100644
index 068ff8e..0000000
--- a/apps/CtsVerifier/res/layout/vertical_divider.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
diff --git a/apps/CtsVerifier/res/menu/test_list_menu.xml b/apps/CtsVerifier/res/menu/test_list_menu.xml
index e777791..67c626c 100644
--- a/apps/CtsVerifier/res/menu/test_list_menu.xml
+++ b/apps/CtsVerifier/res/menu/test_list_menu.xml
@@ -3,10 +3,10 @@
-
-
+
+
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 9770ce0..08bd98b 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -4,9 +4,9 @@
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.
@@ -16,106 +16,45 @@
CTS VerifierWelcome to the CTS Verifier!
- %1$sContinuePassInfoFail
+
+ [CTS Verifier %1$s]
+ CTS Verifier %1$s Test Results
+ PASS
+ FAIL
+ NOT_EXECUTED
+
Manual Test ListAudio
- Camera
- Device Administration
- HardwareNetworkingSensorsSecurity
- StreamingFeaturesOtherClearTest results cleared.
- View
- Couldn\'t create test results report.
- Export
- Cannot save report to external storage, see log for details.
- Report saved to: %s
-
-
- Report Viewer
-
-
- Data Backup Test
- This test checks that data backup and automatic restore works
- properly. The test activity lists some preferences and files that are backed up and
- restored by the CTS Verifier. If backup and restore is working properly, these values
- should be restored after running the backup manager, uninstalling the app, and reinstalling
- the CTS Verifier.
- \n\nPress the \"Generate Test Data\" to populate these values
- and then follow the on screen instructions to finish the test.
-
- Preferences
- Files
- Loading...
- Generate Test Data
- Error occurred while generating test data...
- Random values for the preferences and files have been saved.
- \n\nFollow the instructions below to check that the data backup and restore works:
- \n\n1. Make sure backup and automatic restore are enabled in settings. Depending on the
- backup transport supported by the device you may need to do additional steps. For instance
- you may need to set a Google account as the backup account for the device.
- \n\n2. Run the backup manager: adb shell bmgr run
- \n\n3. Uninstall the program: adb uninstall com.android.cts.verifier
- \n\n4. Reinstall the CTS Verifier and verify that the values are still the same.
-
- Settings
-
-
- Policy Serialization Test
- This test checks that a device policy is properly
- saved and loaded across reboots.\n\nPress the \"Generate Policy\" button to create
- a random policy. Then press the \"Apply Policy\" button to apply the policy. Reboot the
- device and verify that all rows in the policy list are green. Red items indicate policy
- settings that were not loaded properly.
-
- 1. Press the \"Generate Policy\" to create a random device
- policy\n\n2. Press \"Apply Policy\" to put the policy into effect.\n\n3. Reboot your
- device and return to this test in the CTS Verifier.
-
- Generate Policy
- Apply Policy
- Random policy generated.
- Reboot your device and return to this CTS Verifier test.
- Password Quality
- Alphabetic
- Alphanumeric
- Numeric
- Something
- Minimum Password Length
- Maximum Failed Passwords for Wipe
- Maximum Time to Lock
- Expected value: %1$s\nActual value: %2$s
-
- Screen Lock Test
- This test checks that the DevicePolicyManager\'s lockNow
- method immediately locks the screen. It should lock the screen immediately despite any
- settings that may specify a timeout.\n\nClick the \"Force Lock\" button to lock the screen.
- Your screen should be locked and require the password to be entered.
-
- Force Lock
- It appears the screen was locked successfully!
- It does not look like the screen was locked...
+ Copy
+ Test results copied to clipboard.
+ Share
+ Share Test ResultsBluetooth Test
- The Bluetooth Control tests check whether or not the device
+ The Bluetooth Control tests check whether or not the device
can disable and enable Bluetooth properly.\n\nThe Device Communication tests require two
devices to pair and exchange messages. The two devices must be:
\n\n1. a candidate device implementation running the software build to be tested
\n\n2. a separate device implementation already known to be compatible
+ Bluetooth is not available?
+ If your device is supposed to have Bluetooth, your API implementation is not behaving correctly!
+
Bluetooth ControlDevice Communication
@@ -126,43 +65,16 @@
Disabling Bluetooth...Could not disable Bluetooth...
- Connection Access Server
- Connection Access Client
-
- Start the CTS Verifier on another device, start the Bluetooth test, and choose
- \"Connection Access Client\" to setup the test.
- \n\nFirst, unpair the devices via Bluetooth settings. Then connect the devices together
- using the \"Make Discoverable\" and \"Pick Server\" buttons.
- \n\nA connection access request should appear on the server and enable the pass button.
-
-
- Start the CTS Verifier on another device, start the Bluetooth test, and choose
- \"Connection Access Server\" to complete the test.
- \n\nMake the device acting as the server discoverable and connect to it via the
- \"Pick Server\" button. Check that the server displays the connection access request
- dialog. The client device does not need to do anything else.
-
- Was the connection access request dialog shown?
-
- Tap the \"Bluetooth Settings\" button and check that both devices are not paired
- before running the test.
- \n\nUse the \"Make Discoverable\" and \"Pick Server\" buttons to connect the two Bluetooth
- devices together and start the test.
-
-
Secure ServerStart the CTS Verifier on another device, start the Bluetooth test, and choose \"Secure Client\" to complete the test.Insecure ServerStart the CTS Verifier on another device, start the Bluetooth test, and choose \"Insecure Client\" to complete the test.Waiting for client...
- Listening...Connecting...
- ConnectedReceived MessagesSent MessagesNo messagesMake Discoverable
- Pick ServerPairing dialog shown?Insecure connections should not show the pairing dialog!
@@ -191,17 +103,11 @@
-
+
Accelerometer TestThis test verifies that the accelerometer is working properly. As you move the device around through space, the triangle should always point down (i.e. in the direction of gravity.) If it does not, the accelerometer is improperly configured.
-
- Gyroscope Test
- This test verifies that the gyroscope is working properly.\n\nRotate your device as shown by the 3D block. A green background or a check mark indicates that the gyroscope\'s value is correct. A red background or a X mark indicates that the gyroscope\'s value is not right.\n\nThere are 6 parts of the test corresponding to each rotation. Press Pass for all the stages to complete this test.
- Test %1$d of %2$d
- No gyroscope?
- It doesn\'t seem like you have a gyroscope, so you don\'t need to run this test.
- Wrong units?
- These values looks like degrees per second. These should be radians per second!
+ Magnetometer Test
+ This test verifies that the magnetometer (compass) is working properly. As you move the device around through space, the triangle should always point toward the north pole (which may point through the ground.) If it does not, the magnetometer is improperly configured. Be sure not to run this test with the device near any strong magnetic field generators.SUID File Scanner
@@ -213,7 +119,7 @@
No unauthorized suid files detected!
-
+
Audio Quality Verifier
@@ -232,7 +138,7 @@
made are also attached as raw 16 bit, 16 kHz audio files to
help you diagnose any failed tests.
-
+
CalibrateRun All
@@ -240,14 +146,14 @@
ResultsSend by emailClear
-
+
Audio Quality ResultsDismissAndroid Audio Quality Verifier Test Results
-
+
Calibrate Volume
@@ -259,7 +165,7 @@
Volume too lowVolume too highVolume OK
-
+
Unnamed experimentSound level check
@@ -270,12 +176,12 @@
Bias measurementCold recording latencyWarm recording latency
-
+
FailPassComplete
-
+
Experiment ran successfully.Mean = %1$.3g, tolerance = +/- %2$.0f\nRMS = %3$.0f, duration = %4$.1fs
@@ -291,12 +197,11 @@
RMS = %1$.0f, target = %2$.0f\nTolerance = %3$.1f%%\nDuration = %4$.1fsCannot perform test.\nCheck volume is sufficiently high?RMS deviation = %1$.2f\nMax allowed deviation = %2$.1f
-
Latency = %1$dms, maximum allowed = %2$dmsRMS = %1$.0f, target = %2$.0fLatency = %1$dms
-
-
+
+
Error getting minimum AudioRecord buffer size: %1$dError getting minimum AudioTrack buffer size: %1$dError initializing AudioRecord instance
@@ -304,38 +209,4 @@
Error reading data from AudioRecord instanceException thrown during test: %1$s
-
- Camera Analyzer
- Find color checker
- Patch values will be here
-
-
- USB Accessory Test
-
- 1. Connect your Android device to a computer and run the \'cts-usb-accessory\' program
- included with the CTS Verifier bundle.
- \n\n2. If you have not started the CTS Verifier, press \'OK\' when asked to open the CTS
- Verifier when the accessory is connected. \n\nIf you are already in this test,
- then you can press \'Cancel\' but press \'OK\' in the next dialog asking whether to allow
- CTS Verifier to access the accessory.
- \n\n3. You should see the accessory and the CTS Verifier display a series of messages
- which indicates that the accessory support is working properly.
-
- USB accessory feature is not available?
- If your device is supposed to support USB accessories, your API implementation is not behaving correctly!
- Received Messages
- Sent Messages
- No messages
- Starting message processing...
- Exception occurred while processing a message...
- Stopping message processing...
- Received all expected messages. Pass button enabled!
- Could not open file descriptor for USB accessory... try reconnecting and restarting the accessory?
-
-
- Streaming Video Quality Verifier
- This is a test for assessing the quality of streaming videos. Play each stream and verify that the video is smooth and in sync with the audio, and that there are no quality problems.
- No videos.
- Test Failed
- Unable to play stream. See log for details.
diff --git a/apps/CtsVerifier/res/values/styles.xml b/apps/CtsVerifier/res/values/styles.xml
index 51f996d..c5b05cb 100644
--- a/apps/CtsVerifier/res/values/styles.xml
+++ b/apps/CtsVerifier/res/values/styles.xml
@@ -3,15 +3,4 @@
-
-
-
-
+
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/xml/accessory_filter.xml b/apps/CtsVerifier/res/xml/accessory_filter.xml
deleted file mode 100644
index 21caaa4..0000000
--- a/apps/CtsVerifier/res/xml/accessory_filter.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/xml/device_admin.xml b/apps/CtsVerifier/res/xml/device_admin.xml
deleted file mode 100644
index 49d705a..0000000
--- a/apps/CtsVerifier/res/xml/device_admin.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java
deleted file mode 100644
index 9b53bfd..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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.verifier;
-
-import com.android.cts.verifier.TestListAdapter.TestListItem;
-
-import android.app.ListActivity;
-import android.content.Intent;
-import android.view.View;
-import android.widget.ListView;
-
-/** {@link ListActivity} that displays a list of manual tests. */
-public abstract class AbstractTestListActivity extends ListActivity {
- private static final int LAUNCH_TEST_REQUEST_CODE = 9001;
-
- protected TestListAdapter mAdapter;
-
- protected void setTestListAdapter(TestListAdapter adapter) {
- mAdapter = adapter;
- setListAdapter(mAdapter);
- mAdapter.loadTestResults();
- }
-
- private Intent getIntent(int position) {
- TestListItem item = mAdapter.getItem(position);
- return item.intent;
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case LAUNCH_TEST_REQUEST_CODE:
- handleLaunchTestResult(resultCode, data);
- break;
-
- default:
- throw new IllegalArgumentException("Unknown request code: " + requestCode);
- }
- }
-
- private void handleLaunchTestResult(int resultCode, Intent data) {
- if (resultCode == RESULT_OK) {
- TestResult testResult = TestResult.fromActivityResult(resultCode, data);
- mAdapter.setTestResult(testResult);
- }
- }
-
- /** Launch the activity when its {@link ListView} item is clicked. */
- @Override
- protected void onListItemClick(ListView listView, View view, int position, long id) {
- super.onListItemClick(listView, view, position, id);
- Intent intent = getIntent(position);
- startActivityForResult(intent, LAUNCH_TEST_REQUEST_CODE);
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ArrayTestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ArrayTestListAdapter.java
deleted file mode 100644
index 29440f0..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ArrayTestListAdapter.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.verifier;
-
-import android.content.Context;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * {@link TestListAdapter} that works like {@link android.widget.ArrayAdapter}
- * where items can be added by calling {@link #add(TestListItem)} repeatedly.
- */
-public class ArrayTestListAdapter extends TestListAdapter {
-
- private final List mRows = new ArrayList();
-
- public ArrayTestListAdapter(Context context) {
- super(context);
- }
-
- public void add(TestListItem item) {
- mRows.add(item);
- notifyDataSetChanged();
- }
-
- @Override
- protected List getRows() {
- return mRows;
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/CtsVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/CtsVerifierActivity.java
index ee3184b..e35674c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/CtsVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/CtsVerifierActivity.java
@@ -20,9 +20,8 @@ import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
-import android.view.View.OnClickListener;
import android.view.Window;
-import android.widget.TextView;
+import android.view.View.OnClickListener;
/** {@link Activity} that displays an introduction to the verifier. */
public class CtsVerifierActivity extends Activity {
@@ -41,9 +40,6 @@ public class CtsVerifierActivity extends Activity {
}
};
- TextView versionText = (TextView) findViewById(R.id.version_text);
- versionText.setText(getString(R.string.version_text, Version.getVersionName(this)));
-
findViewById(R.id.detective_logo).setOnClickListener(clickListener);
findViewById(R.id.continue_button).setOnClickListener(clickListener);
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
deleted file mode 100644
index 1f19cbe..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * 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.verifier;
-
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ActivityInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.os.Bundle;
-import android.widget.ListView;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * {@link TestListAdapter} that populates the {@link TestListActivity}'s {@link ListView} by
- * reading data from the CTS Verifier's AndroidManifest.xml.
- *
- * Making a new test activity to appear in the list requires the following steps:
- *
- *
- *
REQUIRED: Add an activity to the AndroidManifest.xml with an intent filter with a
- * main action and the MANUAL_TEST category.
- *
- *
- *
- *
- *
- *
- *
- *
OPTIONAL: Add a meta data attribute to indicate what category of tests the activity
- * should belong to. If you don't add this attribute, your test will show up in the
- * "Other" tests category.
- *
- *
- *
- *
- *
OPTIONAL: Add a meta data attribute to indicate whether this test has a parent test.
- *
- *
- *
- *
- *
OPTIONAL: Add a meta data attribute to indicate what features are required to run the
- * test. If the device does not have all of the required features then it will not appear
- * in the test list. Use a colon (:) to specify multiple required features.
- *
- *
- *
- *
- *
- *
- */
-public class ManifestTestListAdapter extends TestListAdapter {
-
- private static final String TEST_CATEGORY_META_DATA = "test_category";
-
- private static final String TEST_PARENT_META_DATA = "test_parent";
-
- private static final String TEST_REQUIRED_FEATURES_META_DATA = "test_required_features";
-
- private Context mContext;
-
- private String mTestParent;
-
- public ManifestTestListAdapter(Context context, String testParent) {
- super(context);
- mContext = context;
- mTestParent = testParent;
- }
-
- @Override
- protected List getRows() {
-
- /*
- * 1. Get all the tests belonging to the test parent.
- * 2. Get all the tests keyed by their category.
- * 3. Flatten the tests and categories into one giant list for the list view.
- */
-
- List infos = getResolveInfosForParent();
- Map> testsByCategory = getTestsByCategory(infos);
-
- List testCategories = new ArrayList(testsByCategory.keySet());
- Collections.sort(testCategories);
-
- List allRows = new ArrayList();
- for (String testCategory : testCategories) {
- List tests = filterTests(testsByCategory.get(testCategory));
- if (!tests.isEmpty()) {
- allRows.add(TestListItem.newCategory(testCategory));
- Collections.sort(tests, new Comparator() {
- @Override
- public int compare(TestListItem item, TestListItem otherItem) {
- return item.title.compareTo(otherItem.title);
- }
- });
- allRows.addAll(tests);
- }
- }
- return allRows;
- }
-
- List getResolveInfosForParent() {
- Intent mainIntent = new Intent(Intent.ACTION_MAIN);
- mainIntent.addCategory(CATEGORY_MANUAL_TEST);
-
- PackageManager packageManager = mContext.getPackageManager();
- List list = packageManager.queryIntentActivities(mainIntent,
- PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
- int size = list.size();
-
- List matchingList = new ArrayList();
- for (int i = 0; i < size; i++) {
- ResolveInfo info = list.get(i);
- String parent = getTestParent(info.activityInfo.metaData);
- if ((mTestParent == null && parent == null)
- || (mTestParent != null && mTestParent.equals(parent))) {
- matchingList.add(info);
- }
- }
- return matchingList;
- }
-
- Map> getTestsByCategory(List list) {
- Map> testsByCategory =
- new HashMap>();
-
- int size = list.size();
- for (int i = 0; i < size; i++) {
- ResolveInfo info = list.get(i);
- String title = getTitle(mContext, info.activityInfo);
- String testName = info.activityInfo.name;
- Intent intent = getActivityIntent(info.activityInfo);
- String[] requiredFeatures = getRequiredFeatures(info.activityInfo.metaData);
- TestListItem item = TestListItem.newTest(title, testName, intent, requiredFeatures);
-
- String testCategory = getTestCategory(mContext, info.activityInfo.metaData);
- addTestToCategory(testsByCategory, testCategory, item);
- }
-
- return testsByCategory;
- }
-
- static String getTestCategory(Context context, Bundle metaData) {
- String testCategory = null;
- if (metaData != null) {
- testCategory = metaData.getString(TEST_CATEGORY_META_DATA);
- }
- if (testCategory != null) {
- return testCategory;
- } else {
- return context.getString(R.string.test_category_other);
- }
- }
-
- static String getTestParent(Bundle metaData) {
- return metaData != null ? metaData.getString(TEST_PARENT_META_DATA) : null;
- }
-
- static String[] getRequiredFeatures(Bundle metaData) {
- if (metaData == null) {
- return null;
- } else {
- String value = metaData.getString(TEST_REQUIRED_FEATURES_META_DATA);
- if (value == null) {
- return null;
- } else {
- return value.split(":");
- }
- }
- }
-
- static String getTitle(Context context, ActivityInfo activityInfo) {
- if (activityInfo.labelRes != 0) {
- return context.getString(activityInfo.labelRes);
- } else {
- return activityInfo.name;
- }
- }
-
- static Intent getActivityIntent(ActivityInfo activityInfo) {
- Intent intent = new Intent();
- intent.setClassName(activityInfo.packageName, activityInfo.name);
- return intent;
- }
-
- static void addTestToCategory(Map> testsByCategory,
- String testCategory, TestListItem item) {
- List tests;
- if (testsByCategory.containsKey(testCategory)) {
- tests = testsByCategory.get(testCategory);
- } else {
- tests = new ArrayList();
- }
- testsByCategory.put(testCategory, tests);
- tests.add(item);
- }
-
- List filterTests(List tests) {
- List filteredTests = new ArrayList(tests);
- PackageManager packageManager = mContext.getPackageManager();
- Iterator iterator = filteredTests.iterator();
- while (iterator.hasNext()) {
- TestListItem item = iterator.next();
- String[] requiredFeatures = item.requiredFeatures;
- if (requiredFeatures != null) {
- for (int i = 0; i < requiredFeatures.length; i++) {
- if (!packageManager.hasSystemFeature(requiredFeatures[i])) {
- iterator.remove();
- break;
- }
- }
- }
- }
- return filteredTests;
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java b/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
index 9991b9d..b629fc5 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
@@ -17,14 +17,12 @@
package com.android.cts.verifier;
import android.app.AlertDialog;
-import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
-import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
@@ -46,12 +44,6 @@ import android.widget.Button;
*/
public class PassFailButtons {
- private static final int INFO_DIALOG_ID = 1337;
-
- private static final String INFO_DIALOG_VIEW_ID = "infoDialogViewId";
- private static final String INFO_DIALOG_TITLE_ID = "infoDialogTitleId";
- private static final String INFO_DIALOG_MESSAGE_ID = "infoDialogMessageId";
-
// Interface mostly for making documentation and refactoring easier...
private interface PassFailActivity {
@@ -75,126 +67,43 @@ public class PassFailButtons {
void setInfoResources(int titleId, int messageId, int viewId);
Button getPassButton();
-
- /* Added to the interface just to make sure it isn't forgotten in the implementations. */
- Dialog onCreateDialog(int id, Bundle args);
-
- /**
- * Returns a unique identifier for the test. Usually, this is just the class name.
- */
- String getTestId();
-
- /** @return null or details about the test run. */
- String getTestDetails();
}
public static class Activity extends android.app.Activity implements PassFailActivity {
- @Override
public void setPassFailButtonClickListeners() {
setPassFailClickListeners(this);
}
- @Override
public void setInfoResources(int titleId, int messageId, int viewId) {
setInfo(this, titleId, messageId, viewId);
}
- @Override
public Button getPassButton() {
return getPassButtonView(this);
}
-
- @Override
- public Dialog onCreateDialog(int id, Bundle args) {
- return createDialog(this, id, args);
- }
-
- @Override
- public String getTestId() {
- return getClass().getName();
- }
-
- @Override
- public String getTestDetails() {
- return null;
- }
}
public static class ListActivity extends android.app.ListActivity implements PassFailActivity {
- @Override
- public void setPassFailButtonClickListeners() {
- setPassFailClickListeners(this);
- }
-
- @Override
- public void setInfoResources(int titleId, int messageId, int viewId) {
- setInfo(this, titleId, messageId, viewId);
- }
-
- @Override
- public Button getPassButton() {
- return getPassButtonView(this);
- }
-
- @Override
- public Dialog onCreateDialog(int id, Bundle args) {
- return createDialog(this, id, args);
- }
-
- @Override
- public String getTestId() {
- return getClass().getName();
- }
-
- @Override
- public String getTestDetails() {
- return null;
- }
- }
-
- public static class TestListActivity extends AbstractTestListActivity
- implements PassFailActivity {
-
- @Override
public void setPassFailButtonClickListeners() {
setPassFailClickListeners(this);
}
- @Override
public void setInfoResources(int titleId, int messageId, int viewId) {
setInfo(this, titleId, messageId, viewId);
}
- @Override
public Button getPassButton() {
return getPassButtonView(this);
}
-
- @Override
- public Dialog onCreateDialog(int id, Bundle args) {
- return createDialog(this, id, args);
- }
-
- @Override
- public String getTestId() {
- return getClass().getName();
- }
-
- @Override
- public String getTestDetails() {
- return null;
- }
}
- private static
- void setPassFailClickListeners(final T activity) {
+ private static void setPassFailClickListeners(final android.app.Activity activity) {
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View target) {
- setTestResultAndFinish(activity, activity.getTestId(), activity.getTestDetails(),
- target);
+ setTestResultAndFinish(activity, target);
}
};
@@ -208,7 +117,6 @@ public class PassFailButtons {
View infoButton = activity.findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
infoButton.setOnClickListener(new OnClickListener() {
- @Override
public void onClick(View view) {
showInfoDialog(activity, titleId, messageId, viewId);
}
@@ -237,28 +145,6 @@ public class PassFailButtons {
private static void showInfoDialog(final android.app.Activity activity, int titleId,
int messageId, int viewId) {
- Bundle args = new Bundle();
- args.putInt(INFO_DIALOG_TITLE_ID, titleId);
- args.putInt(INFO_DIALOG_MESSAGE_ID, messageId);
- args.putInt(INFO_DIALOG_VIEW_ID, viewId);
- activity.showDialog(INFO_DIALOG_ID, args);
- }
-
- private static Dialog createDialog(final android.app.Activity activity, int id, Bundle args) {
- switch (id) {
- case INFO_DIALOG_ID:
- return createInfoDialog(activity, id, args);
- default:
- throw new IllegalArgumentException("Bad dialog id: " + id);
- }
- }
-
- private static Dialog createInfoDialog(final android.app.Activity activity, int id,
- Bundle args) {
- int viewId = args.getInt(INFO_DIALOG_VIEW_ID);
- int titleId = args.getInt(INFO_DIALOG_TITLE_ID);
- int messageId = args.getInt(INFO_DIALOG_MESSAGE_ID);
-
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setIcon(
android.R.drawable.ic_dialog_info).setTitle(titleId);
if (viewId > 0) {
@@ -269,17 +155,15 @@ public class PassFailButtons {
builder.setMessage(messageId);
}
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
public void onClick(DialogInterface dialog, int which) {
markSeenInfoDialog(activity);
}
}).setOnCancelListener(new OnCancelListener() {
- @Override
public void onCancel(DialogInterface dialog) {
markSeenInfoDialog(activity);
}
- });
- return builder.create();
+ })
+ .show();
}
private static void markSeenInfoDialog(android.app.Activity activity) {
@@ -296,30 +180,19 @@ public class PassFailButtons {
}
/** Set the test result corresponding to the button clicked and finish the activity. */
- private static void setTestResultAndFinish(android.app.Activity activity, String testId,
- String testDetails, View target) {
- boolean passed;
+ private static void setTestResultAndFinish(android.app.Activity activity, View target) {
switch (target.getId()) {
case R.id.pass_button:
- passed = true;
+ TestResult.setPassedResult(activity);
break;
+
case R.id.fail_button:
- passed = false;
+ TestResult.setFailedResult(activity);
break;
+
default:
throw new IllegalArgumentException("Unknown id: " + target.getId());
}
- setTestResultAndFinish(activity, testId, testDetails, passed);
- }
-
- /** Set the test result and finish the activity. */
- public static void setTestResultAndFinish(android.app.Activity activity, String testId,
- String testDetails, boolean passed) {
- if (passed) {
- TestResult.setPassedResult(activity, testId, testDetails);
- } else {
- TestResult.setFailedResult(activity, testId, testDetails);
- }
activity.finish();
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java
deleted file mode 100644
index 33c9b62..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.verifier;
-
-import android.app.AlertDialog;
-import android.content.Context;
-import android.os.AsyncTask;
-import android.os.Build;
-import android.os.Environment;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-/**
- * Background task to generate a report and save it to external storage.
- */
-class ReportExporter extends AsyncTask {
- protected static final Logger LOG = Logger.getLogger(ReportExporter.class.getName());
-
- private final Context mContext;
- private final TestListAdapter mAdapter;
-
- ReportExporter(Context context, TestListAdapter adapter) {
- this.mContext = context;
- this.mAdapter = adapter;
- }
-
- @Override
- protected String doInBackground(Void... params) {
- if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
- LOG.log(Level.WARNING, "External storage is not writable.");
- return mContext.getString(R.string.no_storage);
- }
- byte[] contents;
- try {
- TestResultsReport report = new TestResultsReport(mContext, mAdapter);
- contents = report.getContents().getBytes();
- } catch (Exception e) {
- LOG.log(Level.WARNING, "Couldn't create test results report", e);
- return mContext.getString(R.string.test_results_error);
- }
- File reportPath = new File(Environment.getExternalStorageDirectory(), "ctsVerifierReports");
- reportPath.mkdirs();
-
- String baseName = getReportBaseName();
- File reportFile = new File(reportPath, baseName + ".zip");
- ZipOutputStream out = null;
- try {
- out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(reportFile)));
- ZipEntry entry = new ZipEntry(baseName + ".xml");
- out.putNextEntry(entry);
- out.write(contents);
- } catch (IOException e) {
- LOG.log(Level.WARNING, "I/O exception writing report to storage.", e);
- return mContext.getString(R.string.no_storage);
- } finally {
- try {
- if (out != null) {
- out.close();
- }
- } catch (IOException e) {
- LOG.log(Level.WARNING, "I/O exception closing report.", e);
- }
- }
-
- return mContext.getString(R.string.report_saved, reportFile.getPath());
- }
-
- private String getReportBaseName() {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss", Locale.ENGLISH);
- String date = dateFormat.format(new Date());
- return "ctsVerifierReport"
- + "-" + date
- + "-" + Build.MANUFACTURER
- + "-" + Build.PRODUCT
- + "-" + Build.DEVICE
- + "-" + Build.ID;
- }
-
- @Override
- protected void onPostExecute(String result) {
- new AlertDialog.Builder(mContext)
- .setMessage(result)
- .setPositiveButton(android.R.string.ok, null)
- .show();
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ReportViewerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/ReportViewerActivity.java
deleted file mode 100644
index 36ec213..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ReportViewerActivity.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.verifier;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.widget.TextView;
-
-public class ReportViewerActivity extends Activity {
-
- public static final String EXTRA_REPORT_CONTENTS = "reportContents";
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.report_viewer);
-
- Intent intent = getIntent();
- if (intent != null) {
- String reportContents = intent.getStringExtra(EXTRA_REPORT_CONTENTS);
- if (reportContents != null) {
- TextView reportText = (TextView) findViewById(R.id.report_text);
- reportText.setText(reportContents);
- }
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
index c510653..c563e13 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
@@ -16,26 +16,88 @@
package com.android.cts.verifier;
+import com.android.cts.verifier.TestListAdapter.TestListItem;
+
import android.app.ListActivity;
+import android.content.ContentResolver;
+import android.content.ContentValues;
import android.content.Intent;
+import android.database.ContentObserver;
import android.os.Bundle;
-import android.util.Log;
+import android.os.Handler;
+import android.text.ClipboardManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
+import android.view.View;
+import android.widget.ListView;
import android.widget.Toast;
-import java.io.IOException;
-
-/** Top-level {@link ListActivity} for launching tests and managing results. */
-public class TestListActivity extends AbstractTestListActivity {
+/** {@link ListActivity} that displays a list of manual tests. */
+public class TestListActivity extends ListActivity {
- private static final String TAG = TestListActivity.class.getSimpleName();
+ private static final int LAUNCH_TEST_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setTestListAdapter(new ManifestTestListAdapter(this, null));
+
+ TestListAdapter adapter = new TestListAdapter(this);
+ setListAdapter(adapter);
+
+ TestResultContentObserver observer = new TestResultContentObserver(adapter);
+ ContentResolver resolver = getContentResolver();
+ resolver.registerContentObserver(TestResultsProvider.RESULTS_CONTENT_URI, true, observer);
+ }
+
+ /** Launch the activity when its {@link ListView} item is clicked. */
+ @Override
+ protected void onListItemClick(ListView listView, View view, int position, long id) {
+ super.onListItemClick(listView, view, position, id);
+ Intent intent = getIntent(position);
+ startActivityForResult(intent, LAUNCH_TEST_REQUEST_CODE);
+ }
+
+ private Intent getIntent(int position) {
+ TestListAdapter adapter = getListAdapter();
+ TestListItem item = adapter.getItem(position);
+ return item.intent;
+ }
+
+ @Override
+ public TestListAdapter getListAdapter() {
+ return (TestListAdapter) super.getListAdapter();
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ switch (requestCode) {
+ case LAUNCH_TEST_REQUEST_CODE:
+ handleLaunchTestResult(resultCode, data);
+ break;
+
+ default:
+ throw new IllegalArgumentException("Unknown request code: " + requestCode);
+ }
+ }
+
+ private void handleLaunchTestResult(int resultCode, Intent data) {
+ if (resultCode == RESULT_OK) {
+ TestResult testResult = TestResult.fromActivityResult(resultCode, data);
+ ContentValues values = new ContentValues(2);
+ values.put(TestResultsProvider.COLUMN_TEST_RESULT, testResult.getResult());
+ values.put(TestResultsProvider.COLUMN_TEST_NAME, testResult.getName());
+
+ ContentResolver resolver = getContentResolver();
+ int numUpdated = resolver.update(TestResultsProvider.RESULTS_CONTENT_URI, values,
+ TestResultsProvider.COLUMN_TEST_NAME + " = ?",
+ new String[] {testResult.getName()});
+
+ if (numUpdated == 0) {
+ resolver.insert(TestResultsProvider.RESULTS_CONTENT_URI, values);
+ }
+ }
}
@Override
@@ -52,12 +114,12 @@ public class TestListActivity extends AbstractTestListActivity {
handleClearItemSelected();
return true;
- case R.id.view:
- handleViewItemSelected();
+ case R.id.copy:
+ handleCopyItemSelected();
return true;
- case R.id.export:
- handleExportItemSelected();
+ case R.id.share:
+ handleShareItemSelected();
return true;
default:
@@ -66,23 +128,47 @@ public class TestListActivity extends AbstractTestListActivity {
}
private void handleClearItemSelected() {
- mAdapter.clearTestResults();
+ ContentResolver resolver = getContentResolver();
+ resolver.delete(TestResultsProvider.RESULTS_CONTENT_URI, "1", null);
Toast.makeText(this, R.string.test_results_cleared, Toast.LENGTH_SHORT).show();
}
- private void handleViewItemSelected() {
- try {
- TestResultsReport report = new TestResultsReport(this, mAdapter);
- Intent intent = new Intent(this, ReportViewerActivity.class);
- intent.putExtra(ReportViewerActivity.EXTRA_REPORT_CONTENTS, report.getContents());
- startActivity(intent);
- } catch (IOException e) {
- Toast.makeText(this, R.string.test_results_error, Toast.LENGTH_SHORT).show();
- Log.e(TAG, "Couldn't copy test results report", e);
- }
+ private void handleCopyItemSelected() {
+ TestResultsReport report = new TestResultsReport(this, getListAdapter());
+ ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
+ clipboardManager.setText(report.getBody());
+ Toast.makeText(this, R.string.test_results_copied, Toast.LENGTH_SHORT).show();
+ }
+
+ private void handleShareItemSelected() {
+ Intent target = new Intent(Intent.ACTION_SEND);
+ target.setType("text/plain");
+
+ TestResultsReport report = new TestResultsReport(this, getListAdapter());
+ target.putExtra(Intent.EXTRA_SUBJECT, report.getSubject());
+ target.putExtra(Intent.EXTRA_TEXT, report.getBody());
+ startActivity(Intent.createChooser(target, getString(R.string.share_test_results)));
}
- private void handleExportItemSelected() {
- new ReportExporter(this, mAdapter).execute();
+ /**
+ * {@link ContentResolver} that refreshes the {@link TestListAdapter} and thus
+ * the {@link ListView} when the test results change.
+ */
+ private static class TestResultContentObserver extends ContentObserver {
+
+ private final TestListAdapter mAdapter;
+
+ public TestResultContentObserver(TestListAdapter adapter) {
+ super(new Handler());
+ this.mAdapter = adapter;
+ }
+
+ @Override
+ public void onChange(boolean selfChange) {
+ super.onChange(selfChange);
+
+ // TODO: Could be improved by just refreshing the particular test result.
+ mAdapter.refreshTestResults();
+ }
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
index 52d9b32..420408e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
@@ -19,10 +19,11 @@ package com.android.cts.verifier;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
-import android.database.ContentObserver;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
import android.database.Cursor;
-import android.os.AsyncTask;
-import android.os.Handler;
+import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -31,21 +32,42 @@ import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
- * {@link BaseAdapter} that handles loading, refreshing, and setting test
- * results. What tests are shown can be customized by overriding
- * {@link #getRows()}. See {@link ArrayTestListAdapter} and
- * {@link ManifestTestListAdapter} for examples.
+ * {@link BaseAdapter} that populates the {@link TestListActivity}'s {@link ListView}.
+ * Making a new test activity to appear in the list requires the following steps:
+ *
+ *
+ *
REQUIRED: Add an activity to the AndroidManifest.xml with an intent filter with a
+ * main action and the MANUAL_TEST category.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
OPTIONAL: Add a meta data attribute to indicate what category of tests the activity
+ * should belong to. If you don't add this attribute, your test will show up in the
+ * "Other" tests category.
+ *
+ *
+ *
+ *
+ *
*/
-public abstract class TestListAdapter extends BaseAdapter {
+class TestListAdapter extends BaseAdapter {
/** Activities implementing {@link Intent#ACTION_MAIN} and this will appear in the list. */
public static final String CATEGORY_MANUAL_TEST = "android.cts.intent.category.MANUAL_TEST";
+ private static final String TEST_CATEGORY_META_DATA = "test_category";
+
/** View type for a category of tests like "Sensors" or "Features" */
private static final int CATEGORY_HEADER_VIEW_TYPE = 0;
@@ -58,46 +80,37 @@ public abstract class TestListAdapter extends BaseAdapter {
private final Context mContext;
/** Immutable data of tests like the test's title and launch intent. */
- private final List mRows = new ArrayList();
+ private final List mRows;
/** Mutable test results that will change as each test activity finishes. */
private final Map mTestResults = new HashMap();
- /** Map from test name to test details. */
- private final Map mTestDetails = new HashMap();
-
private final LayoutInflater mLayoutInflater;
/** {@link ListView} row that is either a test category header or a test. */
- public static class TestListItem {
+ static class TestListItem {
/** Title shown in the {@link ListView}. */
final String title;
- /** Test name with class and test ID to uniquely identify the test. Null for categories. */
- final String testName;
+ /** Class name with package to uniquely identify the test. Null for categories. */
+ final String className;
/** Intent used to launch the activity from the list. Null for categories. */
final Intent intent;
- /** Features necessary to run this test. */
- final String[] requiredFeatures;
-
- public static TestListItem newTest(String title, String testName, Intent intent,
- String[] requiredFeatures) {
- return new TestListItem(title, testName, intent, requiredFeatures);
+ static TestListItem newTest(String title, String className, Intent intent) {
+ return new TestListItem(title, className, intent);
}
- public static TestListItem newCategory(String title) {
- return new TestListItem(title, null, null, null);
+ static TestListItem newCategory(String title) {
+ return new TestListItem(title, null, null);
}
- private TestListItem(String title, String testName, Intent intent,
- String[] requiredFeatures) {
+ private TestListItem(String title, String className, Intent intent) {
this.title = title;
- this.testName = testName;
+ this.className = className;
this.intent = intent;
- this.requiredFeatures = requiredFeatures;
}
boolean isTest() {
@@ -105,86 +118,114 @@ public abstract class TestListAdapter extends BaseAdapter {
}
}
- public TestListAdapter(Context context) {
+ TestListAdapter(Context context) {
this.mContext = context;
+ this.mRows = getRows(context);
this.mLayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-
- TestResultContentObserver observer = new TestResultContentObserver();
- ContentResolver resolver = context.getContentResolver();
- resolver.registerContentObserver(TestResultsProvider.RESULTS_CONTENT_URI, true, observer);
+ updateTestResults(mContext, mTestResults);
}
- public void loadTestResults() {
- new RefreshTestResultsTask().execute();
- }
+ static List getRows(Context context) {
+ /*
+ * 1. Get all the tests keyed by their category.
+ * 2. Flatten the tests and categories into one giant list for the list view.
+ */
- public void clearTestResults() {
- new ClearTestResultsTask().execute();
- }
+ Map> testsByCategory = getTestsByCategory(context);
- public void setTestResult(TestResult testResult) {
- new SetTestResultTask(testResult.getName(), testResult.getResult(),
- testResult.getDetails()).execute();
- }
+ List testCategories = new ArrayList(testsByCategory.keySet());
+ Collections.sort(testCategories);
- class RefreshTestResultsTask extends AsyncTask {
- @Override
- protected RefreshResult doInBackground(Void... params) {
- List rows = getRows();
- return getRefreshResults(rows);
+ List allRows = new ArrayList();
+ for (String testCategory : testCategories) {
+ allRows.add(TestListItem.newCategory(testCategory));
+
+ List tests = testsByCategory.get(testCategory);
+ Collections.sort(tests, new Comparator() {
+ public int compare(TestListItem item, TestListItem otherItem) {
+ return item.title.compareTo(otherItem.title);
+ }
+ });
+ allRows.addAll(tests);
}
+ return allRows;
+ }
+
+ static Map> getTestsByCategory(Context context) {
+ Map> testsByCategory =
+ new HashMap>();
+
+ Intent mainIntent = new Intent(Intent.ACTION_MAIN);
+ mainIntent.addCategory(CATEGORY_MANUAL_TEST);
+
+ PackageManager packageManager = context.getPackageManager();
+ List list = packageManager.queryIntentActivities(mainIntent,
+ PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
- @Override
- protected void onPostExecute(RefreshResult result) {
- super.onPostExecute(result);
- mRows.clear();
- mRows.addAll(result.mItems);
- mTestResults.clear();
- mTestResults.putAll(result.mResults);
- mTestDetails.clear();
- mTestDetails.putAll(result.mDetails);
- notifyDataSetChanged();
+ for (int i = 0; i < list.size(); i++) {
+ ResolveInfo info = list.get(i);
+ String testCategory = getTestCategory(context, info.activityInfo.metaData);
+ String title = getTitle(context, info.activityInfo);
+ String className = info.activityInfo.name;
+ Intent intent = getActivityIntent(info.activityInfo);
+
+ addTestToCategory(testsByCategory, testCategory, title, className, intent);
}
+
+ return testsByCategory;
}
- static class RefreshResult {
- List mItems;
- Map mResults;
- Map mDetails;
+ static String getTestCategory(Context context, Bundle metaData) {
+ String testCategory = null;
+ if (metaData != null) {
+ testCategory = metaData.getString(TEST_CATEGORY_META_DATA);
+ }
+ if (testCategory != null) {
+ return testCategory;
+ } else {
+ return context.getString(R.string.test_category_other);
+ }
+ }
- RefreshResult(List items, Map results,
- Map details) {
- mItems = items;
- mResults = results;
- mDetails = details;
+ static String getTitle(Context context, ActivityInfo activityInfo) {
+ if (activityInfo.labelRes != 0) {
+ return context.getString(activityInfo.labelRes);
+ } else {
+ return activityInfo.name;
}
}
- protected abstract List getRows();
+ static Intent getActivityIntent(ActivityInfo activityInfo) {
+ Intent intent = new Intent();
+ intent.setClassName(activityInfo.packageName, activityInfo.name);
+ return intent;
+ }
- static final String[] REFRESH_PROJECTION = {
- TestResultsProvider._ID,
- TestResultsProvider.COLUMN_TEST_NAME,
- TestResultsProvider.COLUMN_TEST_RESULT,
- TestResultsProvider.COLUMN_TEST_DETAILS,
- };
+ static void addTestToCategory(Map> testsByCategory,
+ String testCategory, String title, String className, Intent intent) {
+ List tests;
+ if (testsByCategory.containsKey(testCategory)) {
+ tests = testsByCategory.get(testCategory);
+ } else {
+ tests = new ArrayList();
+ }
+ testsByCategory.put(testCategory, tests);
+ tests.add(TestListItem.newTest(title, className, intent));
+ }
- RefreshResult getRefreshResults(List items) {
- Map results = new HashMap();
- Map details = new HashMap();
- ContentResolver resolver = mContext.getContentResolver();
+ static void updateTestResults(Context context, Map testResults) {
+ testResults.clear();
+ ContentResolver resolver = context.getContentResolver();
Cursor cursor = null;
try {
- cursor = resolver.query(TestResultsProvider.RESULTS_CONTENT_URI, REFRESH_PROJECTION,
- null, null, null);
+ cursor = resolver.query(TestResultsProvider.RESULTS_CONTENT_URI,
+ TestResultsProvider.ALL_COLUMNS, null, null, null);
if (cursor.moveToFirst()) {
do {
- String testName = cursor.getString(1);
+ String className = cursor.getString(1);
int testResult = cursor.getInt(2);
- String testDetails = cursor.getString(3);
- results.put(testName, testResult);
- details.put(testName, testDetails);
+ testResults.put(className, testResult);
} while (cursor.moveToNext());
}
} finally {
@@ -192,51 +233,11 @@ public abstract class TestListAdapter extends BaseAdapter {
cursor.close();
}
}
- return new RefreshResult(items, results, details);
- }
-
- class ClearTestResultsTask extends AsyncTask {
-
- @Override
- protected Void doInBackground(Void... params) {
- ContentResolver resolver = mContext.getContentResolver();
- resolver.delete(TestResultsProvider.RESULTS_CONTENT_URI, "1", null);
- return null;
- }
}
- class SetTestResultTask extends AsyncTask {
-
- private final String mTestName;
-
- private final int mResult;
-
- private final String mDetails;
-
- SetTestResultTask(String testName, int result, String details) {
- mTestName = testName;
- mResult = result;
- mDetails = details;
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- TestResultsProvider.setTestResult(mContext, mTestName, mResult, mDetails);
- return null;
- }
- }
-
- class TestResultContentObserver extends ContentObserver {
-
- public TestResultContentObserver() {
- super(new Handler());
- }
-
- @Override
- public void onChange(boolean selfChange) {
- super.onChange(selfChange);
- loadTestResults();
- }
+ public void refreshTestResults() {
+ updateTestResults(mContext, mTestResults);
+ notifyDataSetChanged();
}
@Override
@@ -260,46 +261,25 @@ public abstract class TestListAdapter extends BaseAdapter {
return 2;
}
- @Override
public int getCount() {
return mRows.size();
}
- @Override
public TestListItem getItem(int position) {
return mRows.get(position);
}
- @Override
public long getItemId(int position) {
return position;
}
public int getTestResult(int position) {
TestListItem item = getItem(position);
- return mTestResults.containsKey(item.testName)
- ? mTestResults.get(item.testName)
+ return mTestResults.containsKey(item.className)
+ ? mTestResults.get(item.className)
: TestResult.TEST_RESULT_NOT_EXECUTED;
}
- public String getTestDetails(int position) {
- TestListItem item = getItem(position);
- return mTestDetails.containsKey(item.testName)
- ? mTestDetails.get(item.testName)
- : null;
- }
-
- public boolean allTestsPassed() {
- for (TestListItem item : mRows) {
- if (item.isTest() && (!mTestResults.containsKey(item.testName)
- || (mTestResults.get(item.testName) != TestResult.TEST_RESULT_PASSED))) {
- return false;
- }
- }
- return true;
- }
-
- @Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView;
if (convertView == null) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
index 68513ac..6269f97 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
@@ -21,10 +21,9 @@ import android.content.Intent;
/**
* Object representing the result of a test activity like whether it succeeded or failed.
- * Use {@link #setPassedResult(Activity, String, String)} or
- * {@link #setFailedResult(Activity, String, String)} from a test activity like you would
- * {@link Activity#setResult(int)} so that {@link TestListActivity}
- * will persist the test result and update its adapter and thus the list view.
+ * Use {@link #setPassedResult(Activity)} or {@link #setFailedResult(Activity)} from a test
+ * activity like you would {@link Activity#setResult(int)} so that {@link TestListActivity} will
+ * persist the test result and update its adapter and thus the list view.
*/
public class TestResult {
@@ -34,30 +33,25 @@ public class TestResult {
private static final String TEST_NAME = "name";
private static final String TEST_RESULT = "result";
- private static final String TEST_DETAILS = "details";
private final String mName;
+
private final int mResult;
- private final String mDetails;
/** Sets the test activity's result to pass. */
- public static void setPassedResult(Activity activity, String testId, String testDetails) {
- activity.setResult(Activity.RESULT_OK, createResult(activity, TEST_RESULT_PASSED, testId,
- testDetails));
+ public static void setPassedResult(Activity activity) {
+ activity.setResult(Activity.RESULT_OK, createResult(activity, TEST_RESULT_PASSED));
}
/** Sets the test activity's result to failed. */
- public static void setFailedResult(Activity activity, String testId, String testDetails) {
- activity.setResult(Activity.RESULT_OK, createResult(activity, TEST_RESULT_FAILED, testId,
- testDetails));
+ public static void setFailedResult(Activity activity) {
+ activity.setResult(Activity.RESULT_OK, createResult(activity, TEST_RESULT_FAILED));
}
- private static Intent createResult(Activity activity, int testResult, String testName,
- String testDetails) {
+ private static Intent createResult(Activity activity, int testResult) {
Intent data = new Intent(activity, activity.getClass());
- data.putExtra(TEST_NAME, testName);
+ data.putExtra(TEST_NAME, activity.getClass().getName());
data.putExtra(TEST_RESULT, testResult);
- data.putExtra(TEST_DETAILS, testDetails);
return data;
}
@@ -65,17 +59,15 @@ public class TestResult {
* Convert the test activity's result into a {@link TestResult}. Only meant to be used by
* {@link TestListActivity}.
*/
- static TestResult fromActivityResult(int resultCode, Intent data) {
+ public static TestResult fromActivityResult(int resultCode, Intent data) {
String name = data.getStringExtra(TEST_NAME);
int result = data.getIntExtra(TEST_RESULT, TEST_RESULT_NOT_EXECUTED);
- String details = data.getStringExtra(TEST_DETAILS);
- return new TestResult(name, result, details);
+ return new TestResult(name, result);
}
- private TestResult(String name, int result, String details) {
+ private TestResult(String name, int result) {
this.mName = name;
this.mResult = result;
- this.mDetails = details;
}
/** Return the name of the test like "com.android.cts.verifier.foo.FooTest" */
@@ -87,9 +79,4 @@ public class TestResult {
public int getResult() {
return mResult;
}
-
- /** Return null or string containing test output. */
- public String getDetails() {
- return mDetails;
- }
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsBackupHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsBackupHelper.java
deleted file mode 100644
index e4cd24a..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsBackupHelper.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * 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.verifier;
-
-import com.android.cts.verifier.backup.BackupTestActivity;
-
-import android.app.backup.BackupDataInputStream;
-import android.app.backup.BackupDataOutput;
-import android.app.backup.BackupHelper;
-import android.content.ContentResolver;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.os.ParcelFileDescriptor;
-import android.util.Log;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-/** {@link BackupHelper} for the test results database. */
-class TestResultsBackupHelper implements BackupHelper {
-
- private static final String TAG = TestResultsBackupHelper.class.getSimpleName();
-
- private static final String DB_BACKUP_KEY = "db";
-
- private final Context mContext;
-
- TestResultsBackupHelper(Context context) {
- mContext = context;
- }
-
- @Override
- public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
- ParcelFileDescriptor newState) {
- ContentResolver resolver = mContext.getContentResolver();
- Cursor cursor = null;
- try {
- cursor = resolver.query(TestResultsProvider.RESULTS_CONTENT_URI,
- null, null, null, null);
- int nameIndex = cursor.getColumnIndex(TestResultsProvider.COLUMN_TEST_NAME);
- int resultIndex = cursor.getColumnIndex(TestResultsProvider.COLUMN_TEST_RESULT);
- int infoSeenIndex = cursor.getColumnIndex(TestResultsProvider.COLUMN_TEST_INFO_SEEN);
- int detailsIndex = cursor.getColumnIndex(TestResultsProvider.COLUMN_TEST_DETAILS);
-
- ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
- DataOutputStream dataOutput = new DataOutputStream(byteOutput);
-
- dataOutput.writeInt(cursor.getCount());
- while (cursor.moveToNext()) {
- String name = cursor.getString(nameIndex);
- int result = cursor.getInt(resultIndex);
- int infoSeen = cursor.getInt(infoSeenIndex);
- String details = cursor.getString(detailsIndex);
-
- dataOutput.writeUTF(name);
- dataOutput.writeInt(result);
- dataOutput.writeInt(infoSeen);
- dataOutput.writeUTF(details != null ? details : "");
- }
-
- byte[] rawBytes = byteOutput.toByteArray();
- data.writeEntityHeader(DB_BACKUP_KEY, rawBytes.length);
- data.writeEntityData(rawBytes, rawBytes.length);
- } catch (IOException e) {
- Log.e(TAG, "Couldn't backup test results...", e);
- failBackupTest();
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- }
- }
-
- @Override
- public void restoreEntity(BackupDataInputStream data) {
- try {
- if (DB_BACKUP_KEY.equals(data.getKey())) {
- byte[] rawBytes = new byte[data.size()];
- data.read(rawBytes, 0, data.size());
-
- ByteArrayInputStream byteInput = new ByteArrayInputStream(rawBytes);
- DataInputStream dataInput = new DataInputStream(byteInput);
-
- int numRows = dataInput.readInt();
- ContentValues[] values = new ContentValues[numRows];
- for (int i = 0; i < numRows; i++) {
- String name = dataInput.readUTF();
- int result = dataInput.readInt();
- int infoSeen = dataInput.readInt();
- String details = dataInput.readUTF();
-
- values[i] = new ContentValues();
- values[i].put(TestResultsProvider.COLUMN_TEST_NAME, name);
- values[i].put(TestResultsProvider.COLUMN_TEST_RESULT, result);
- values[i].put(TestResultsProvider.COLUMN_TEST_INFO_SEEN, infoSeen);
- values[i].put(TestResultsProvider.COLUMN_TEST_DETAILS, details);
- }
-
- ContentResolver resolver = mContext.getContentResolver();
- resolver.bulkInsert(TestResultsProvider.RESULTS_CONTENT_URI, values);
- } else {
- Log.e(TAG, "Skipping key: " + data.getKey());
- }
- } catch (IOException e) {
- Log.e(TAG, "Couldn't restore test results...", e);
- failBackupTest();
- }
- }
-
- private void failBackupTest() {
- TestResultsProvider.setTestResult(mContext, BackupTestActivity.class.getName(),
- TestResult.TEST_RESULT_FAILED, null);
- }
-
- @Override
- public void writeNewStateDescription(ParcelFileDescriptor newState) {
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsProvider.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsProvider.java
index df05519..a41cb43 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsProvider.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsProvider.java
@@ -16,9 +16,7 @@
package com.android.cts.verifier;
-import android.app.backup.BackupManager;
import android.content.ContentProvider;
-import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
@@ -42,19 +40,23 @@ public class TestResultsProvider extends ContentProvider {
return Uri.withAppendedPath(RESULTS_CONTENT_URI, testName);
}
- static final String _ID = "_id";
+ public static final String _ID = "_id";
/** String name of the test like "com.android.cts.verifier.foo.FooTestActivity" */
- static final String COLUMN_TEST_NAME = "testname";
+ public static final String COLUMN_TEST_NAME = "testname";
/** Integer test result corresponding to constants in {@link TestResult}. */
- static final String COLUMN_TEST_RESULT = "testresult";
+ public static final String COLUMN_TEST_RESULT = "testresult";
/** Boolean indicating whether the test info has been seen. */
- static final String COLUMN_TEST_INFO_SEEN = "testinfoseen";
+ public static final String COLUMN_TEST_INFO_SEEN = "testinfoseen";
- /** String containing the test's details. */
- static final String COLUMN_TEST_DETAILS = "testdetails";
+ public static final String[] ALL_COLUMNS = {
+ _ID,
+ COLUMN_TEST_NAME,
+ COLUMN_TEST_RESULT,
+ COLUMN_TEST_INFO_SEEN,
+ };
private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
private static final int RESULTS_ALL = 1;
@@ -70,12 +72,9 @@ public class TestResultsProvider extends ContentProvider {
private SQLiteOpenHelper mOpenHelper;
- private BackupManager mBackupManager;
-
@Override
public boolean onCreate() {
mOpenHelper = new TestResultsOpenHelper(getContext());
- mBackupManager = new BackupManager(getContext());
return false;
}
@@ -83,7 +82,7 @@ public class TestResultsProvider extends ContentProvider {
private static final String DATABASE_NAME = "results.db";
- private static final int DATABASE_VERSION = 6;
+ private static final int DATABASE_VERSION = 5;
TestResultsOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
@@ -95,8 +94,7 @@ public class TestResultsProvider extends ContentProvider {
+ _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_TEST_NAME + " TEXT, "
+ COLUMN_TEST_RESULT + " INTEGER,"
- + COLUMN_TEST_INFO_SEEN + " INTEGER DEFAULT 0,"
- + COLUMN_TEST_DETAILS + " TEXT);");
+ + COLUMN_TEST_INFO_SEEN + " INTEGER DEFAULT 0);");
}
@Override
@@ -142,12 +140,14 @@ public class TestResultsProvider extends ContentProvider {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long id = db.insert(TABLE_NAME, null, values);
getContext().getContentResolver().notifyChange(uri, null);
- mBackupManager.dataChanged();
return Uri.withAppendedPath(RESULTS_CONTENT_URI, "" + id);
+
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+
int match = URI_MATCHER.match(uri);
switch (match) {
case RESULTS_ALL:
@@ -176,11 +176,9 @@ public class TestResultsProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI: " + uri);
}
- SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int numUpdated = db.update(TABLE_NAME, values, selection, selectionArgs);
if (numUpdated > 0) {
getContext().getContentResolver().notifyChange(uri, null);
- mBackupManager.dataChanged();
}
return numUpdated;
}
@@ -191,7 +189,6 @@ public class TestResultsProvider extends ContentProvider {
int numDeleted = db.delete(TABLE_NAME, selection, selectionArgs);
if (numDeleted > 0) {
getContext().getContentResolver().notifyChange(uri, null);
- mBackupManager.dataChanged();
}
return numDeleted;
}
@@ -200,22 +197,4 @@ public class TestResultsProvider extends ContentProvider {
public String getType(Uri uri) {
return null;
}
-
- static void setTestResult(Context context, String testName, int testResult,
- String testDetails) {
- ContentValues values = new ContentValues(2);
- values.put(TestResultsProvider.COLUMN_TEST_RESULT, testResult);
- values.put(TestResultsProvider.COLUMN_TEST_NAME, testName);
- values.put(TestResultsProvider.COLUMN_TEST_DETAILS, testDetails);
-
- ContentResolver resolver = context.getContentResolver();
- int numUpdated = resolver.update(TestResultsProvider.RESULTS_CONTENT_URI, values,
- TestResultsProvider.COLUMN_TEST_NAME + " = ?",
- new String[] {testName});
-
- if (numUpdated == 0) {
- resolver.insert(TestResultsProvider.RESULTS_CONTENT_URI, values);
- }
- }
-
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java
index e40b428..18a08fe 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java
@@ -18,140 +18,90 @@ package com.android.cts.verifier;
import com.android.cts.verifier.TestListAdapter.TestListItem;
-import org.xmlpull.v1.XmlSerializer;
-
import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
-import android.text.TextUtils;
-import android.util.Xml;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-
-/**
- * XML text report of the current test results.
- *
- */
-class TestResultsReport {
-
- /** Version of the test report. Increment whenever adding new tags and attributes. */
- private static final int REPORT_VERSION = 2;
-
- /** Format of the report's creation time. Maintain the same format at CTS. */
- private static DateFormat DATE_FORMAT =
- new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
- private static final String TEST_RESULTS_REPORT_TAG = "test-results-report";
- private static final String VERIFIER_INFO_TAG = "verifier-info";
- private static final String DEVICE_INFO_TAG = "device-info";
- private static final String BUILD_INFO_TAG = "build-info";
- private static final String TEST_RESULTS_TAG = "test-results";
- private static final String TEST_TAG = "test";
- private static final String TEST_DETAILS_TAG = "details";
+/** Plain text report of the current test results. */
+class TestResultsReport {
private final Context mContext;
private final TestListAdapter mAdapter;
+ private final String mVersionName;
+
TestResultsReport(Context context, TestListAdapter adapter) {
this.mContext = context;
this.mAdapter = adapter;
+ this.mVersionName = getVersionName(context);
}
- String getContents() throws IllegalArgumentException, IllegalStateException, IOException {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-
- XmlSerializer xml = Xml.newSerializer();
- xml.setOutput(outputStream, "utf-8");
- xml.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
- xml.startDocument("utf-8", true);
-
- xml.startTag(null, TEST_RESULTS_REPORT_TAG);
- xml.attribute(null, "report-version", Integer.toString(REPORT_VERSION));
- xml.attribute(null, "creation-time", DATE_FORMAT.format(new Date()));
-
- xml.startTag(null, VERIFIER_INFO_TAG);
- xml.attribute(null, "version-name", Version.getVersionName(mContext));
- xml.attribute(null, "version-code", Integer.toString(Version.getVersionCode(mContext)));
- xml.endTag(null, VERIFIER_INFO_TAG);
-
- xml.startTag(null, DEVICE_INFO_TAG);
- xml.startTag(null, BUILD_INFO_TAG);
- xml.attribute(null, "board", Build.BOARD);
- xml.attribute(null, "brand", Build.BRAND);
- xml.attribute(null, "device", Build.DEVICE);
- xml.attribute(null, "display", Build.DISPLAY);
- xml.attribute(null, "fingerprint", Build.FINGERPRINT);
- xml.attribute(null, "id", Build.ID);
- xml.attribute(null, "model", Build.MODEL);
- xml.attribute(null, "product", Build.PRODUCT);
- xml.attribute(null, "release", Build.VERSION.RELEASE);
- xml.attribute(null, "sdk", Integer.toString(Build.VERSION.SDK_INT));
- xml.endTag(null, BUILD_INFO_TAG);
- xml.endTag(null, DEVICE_INFO_TAG);
-
- xml.startTag(null, TEST_RESULTS_TAG);
+ private static String getVersionName(Context context) {
+ try {
+ PackageManager packageManager = context.getPackageManager();
+ PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
+ return info.versionName;
+ } catch (NameNotFoundException e) {
+ throw new RuntimeException("Could not get find package information for "
+ + context.getPackageName());
+ }
+ }
+
+ String getSubject() {
+ return new StringBuilder()
+ .append(mContext.getString(R.string.subject_header, mVersionName))
+ .append(' ')
+ .append(Build.FINGERPRINT)
+ .toString();
+ }
+
+ String getBody() {
+ StringBuilder builder = new StringBuilder()
+ .append(mContext.getString(R.string.body_header, mVersionName))
+ .append("\n\n")
+ .append(Build.FINGERPRINT)
+ .append("\n\n");
+
int count = mAdapter.getCount();
for (int i = 0; i < count; i++) {
TestListItem item = mAdapter.getItem(i);
- if (item.isTest()) {
- xml.startTag(null, TEST_TAG);
- xml.attribute(null, "title", item.title);
- xml.attribute(null, "class-name", item.testName);
- xml.attribute(null, "result", getTestResultString(mAdapter.getTestResult(i)));
-
- String details = mAdapter.getTestDetails(i);
- if (!TextUtils.isEmpty(details)) {
- xml.startTag(null, TEST_DETAILS_TAG);
- xml.text(details);
- xml.endTag(null, TEST_DETAILS_TAG);
- }
-
- xml.endTag(null, TEST_TAG);
+ if (!item.isTest()) {
+ builder.append(item.title).append('\n');
+ } else {
+ builder.append(item.title)
+ .append(".....")
+ .append(getTestResultString(mAdapter.getTestResult(i)))
+ .append('\n');
}
- }
- xml.endTag(null, TEST_RESULTS_TAG);
-
- xml.endTag(null, TEST_RESULTS_REPORT_TAG);
- xml.endDocument();
- return outputStream.toString("utf-8");
+ if (i + 1 < count && !mAdapter.getItem(i + 1).isTest()) {
+ builder.append('\n');
+ }
+ }
+ return builder.toString();
}
private String getTestResultString(int testResult) {
+ int resId = 0;
switch (testResult) {
case TestResult.TEST_RESULT_PASSED:
- return "pass";
+ resId = R.string.pass_result;
+ break;
case TestResult.TEST_RESULT_FAILED:
- return "fail";
+ resId = R.string.fail_result;
+ break;
case TestResult.TEST_RESULT_NOT_EXECUTED:
- return "not-executed";
+ resId = R.string.not_executed_result;
+ break;
default:
throw new IllegalArgumentException("Unknown test result: " + testResult);
}
+ return mContext.getString(resId);
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/VerifierBackupAgent.java b/apps/CtsVerifier/src/com/android/cts/verifier/VerifierBackupAgent.java
deleted file mode 100644
index 3c980b9..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/VerifierBackupAgent.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.verifier;
-
-import com.android.cts.verifier.backup.BackupTestActivity;
-
-import android.app.backup.BackupAgentHelper;
-
-public class VerifierBackupAgent extends BackupAgentHelper {
-
- @Override
- public void onCreate() {
- super.onCreate();
- addHelper("test-results", new TestResultsBackupHelper(this));
- addHelper("backup-test-prefs", BackupTestActivity.getSharedPreferencesBackupHelper(this));
- addHelper("backup-test-files", BackupTestActivity.getFileBackupHelper(this));
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/Version.java b/apps/CtsVerifier/src/com/android/cts/verifier/Version.java
deleted file mode 100644
index e7b6121..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/Version.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.verifier;
-
-import android.content.Context;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-
-class Version {
-
- static String getVersionName(Context context) {
- return getPackageInfo(context).versionName;
- }
-
- static int getVersionCode(Context context) {
- return getPackageInfo(context).versionCode;
- }
-
- static PackageInfo getPackageInfo(Context context) {
- try {
- PackageManager packageManager = context.getPackageManager();
- return packageManager.getPackageInfo(context.getPackageName(), 0);
- } catch (NameNotFoundException e) {
- throw new RuntimeException("Could not get find package information for "
- + context.getPackageName());
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/admin/PolicySerializationTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/admin/PolicySerializationTestActivity.java
deleted file mode 100644
index 1591df3..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/admin/PolicySerializationTestActivity.java
+++ /dev/null
@@ -1,503 +0,0 @@
-/*
- * 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.verifier.admin;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.app.AlertDialog;
-import android.app.admin.DevicePolicyManager;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.os.Bundle;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.ListView;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-/**
- * Test that checks that device policies are properly saved and loaded across reboots. The user
- * clicks a button to generate a random policy and is then asked to reboot the device. When
- * returning to the test, the activity checks that the device manager is reporting the values
- * it set before the user rebooted the device.
- */
-public class PolicySerializationTestActivity extends PassFailButtons.ListActivity {
-
- /**
- * Whether or not to load the expected policy from the preferences and check against
- * what the {@link DevicePolicyManager} reports.
- */
- private static final String LOAD_EXPECTED_POLICY_PREFERENCE = "load-expected-policy";
-
- private static final int ADD_DEVICE_ADMIN_REQUEST_CODE = 1;
-
- private DevicePolicyManager mDevicePolicyManager;
- private ComponentName mAdmin;
-
- private List> mPolicyItems = new ArrayList>();
- private PolicyAdapter mAdapter;
-
- private View mGeneratePolicyButton;
- private View mApplyPolicyButton;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.da_policy_main);
- setInfoResources(R.string.da_policy_serialization_test,
- R.string.da_policy_serialization_info, -1);
- setPassFailButtonClickListeners();
-
- mDevicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
- mAdmin = TestDeviceAdminReceiver.getComponent(this);
-
- mGeneratePolicyButton = findViewById(R.id.generate_policy_button);
- mGeneratePolicyButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- generateRandomPolicy();
- updateWidgets();
- }
- });
-
- mApplyPolicyButton = findViewById(R.id.apply_policy_button);
- mApplyPolicyButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- applyPolicy();
- }
- });
-
- mPolicyItems.add(new PasswordQualityPolicy(this));
- mPolicyItems.add(new PasswordMinimumLengthPolicy(this));
- mPolicyItems.add(new MaximumFailedPasswordsForWipePolicy(this));
- mPolicyItems.add(new MaximumTimeToLockPolicy(this));
- mAdapter = new PolicyAdapter(this);
- setListAdapter(mAdapter);
-
- loadPolicy();
- updateWidgets();
- }
-
- private void loadPolicy() {
- mAdapter.clear();
- SharedPreferences prefs = getPreferences(MODE_PRIVATE);
- if (prefs.getBoolean(LOAD_EXPECTED_POLICY_PREFERENCE, false)) {
- for (PolicyItem> item : mPolicyItems) {
- item.loadExpectedValue(prefs);
- item.loadActualValue(mDevicePolicyManager, mAdmin);
- mAdapter.add(item);
- }
- }
- }
-
- private void generateRandomPolicy() {
- Random random = new Random();
- mAdapter.clear();
- for (PolicyItem> item : mPolicyItems) {
- item.setRandomExpectedValue(random);
- item.resetActualValue();
- mAdapter.add(item);
- }
-
- SharedPreferences prefs = getPreferences(MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.clear();
- editor.putBoolean(LOAD_EXPECTED_POLICY_PREFERENCE, false);
- editor.apply();
-
- Toast.makeText(this, R.string.da_random_policy, Toast.LENGTH_SHORT).show();
- }
-
- private void applyPolicy() {
- Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
- intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
- TestDeviceAdminReceiver.getComponent(this));
- startActivityForResult(intent, ADD_DEVICE_ADMIN_REQUEST_CODE);
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case ADD_DEVICE_ADMIN_REQUEST_CODE:
- handleAddDeviceAdminResult(resultCode, data);
- break;
- }
- }
-
- private void handleAddDeviceAdminResult(int resultCode, Intent data) {
- if (resultCode == RESULT_OK) {
- ComponentName admin = TestDeviceAdminReceiver.getComponent(this);
- for (PolicyItem> item : mPolicyItems) {
- item.applyExpectedValue(mDevicePolicyManager, admin);
- }
-
- SharedPreferences prefs = getPreferences(MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.clear();
- editor.putBoolean(LOAD_EXPECTED_POLICY_PREFERENCE, true);
- for (PolicyItem> item : mPolicyItems) {
- item.saveExpectedValue(editor);
- }
- editor.apply();
- showRebootDialog();
- }
- }
-
- private void showRebootDialog() {
- new AlertDialog.Builder(this)
- .setIcon(android.R.drawable.ic_dialog_info)
- .setTitle(R.string.da_policy_serialization_test)
- .setMessage(R.string.da_policy_reboot)
- .setPositiveButton(android.R.string.ok, null)
- .show();
- }
-
- private void updateWidgets() {
- mApplyPolicyButton.setEnabled(!mAdapter.isEmpty());
-
- // All items need to have been serialized properly for the pass button to activate.
- boolean enablePass = !mAdapter.isEmpty();
- int numItems = mAdapter.getCount();
- for (int i = 0; i < numItems; i++) {
- PolicyItem> item = mAdapter.getItem(i);
- if (!item.matchesExpectedValue()) {
- enablePass = false;
- }
- }
- getPassButton().setEnabled(enablePass);
- }
-
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) {
- super.onListItemClick(l, v, position, id);
- PolicyItem> item = mAdapter.getItem(position);
- new AlertDialog.Builder(this)
- .setIcon(android.R.drawable.ic_dialog_info)
- .setTitle(item.getDisplayName())
- .setMessage(getString(R.string.da_policy_info,
- item.getDisplayExpectedValue(),
- item.getDisplayActualValue()))
- .setPositiveButton(android.R.string.ok, null)
- .show();
- }
-
- static class PolicyAdapter extends ArrayAdapter> {
-
- public PolicyAdapter(Context context) {
- super(context, android.R.layout.simple_list_item_1);
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- TextView view = (TextView) super.getView(position, convertView, parent);
-
- PolicyItem> item = getItem(position);
- int backgroundResource = 0;
- int iconResource = 0;
- if (item.getExpectedValue() != null && item.getActualValue() != null) {
- if (item.matchesExpectedValue()) {
- backgroundResource = R.drawable.test_pass_gradient;
- iconResource = R.drawable.fs_good;
- } else {
- backgroundResource = R.drawable.test_fail_gradient;
- iconResource = R.drawable.fs_error;
- }
- }
- view.setBackgroundResource(backgroundResource);
- view.setPadding(10, 0, 10, 0);
- view.setCompoundDrawablePadding(10);
- view.setCompoundDrawablesWithIntrinsicBounds(0, 0, iconResource, 0);
-
- return view;
- }
- }
-
- interface PolicyItem {
-
- void setRandomExpectedValue(Random random);
-
- void applyExpectedValue(DevicePolicyManager deviceManager, ComponentName admin);
-
- void loadExpectedValue(SharedPreferences prefs);
-
- void saveExpectedValue(SharedPreferences.Editor editor);
-
- void resetActualValue();
-
- void loadActualValue(DevicePolicyManager deviceManager, ComponentName admin);
-
- String getDisplayName();
-
- T getExpectedValue();
-
- String getDisplayExpectedValue();
-
- T getActualValue();
-
- String getDisplayActualValue();
-
- boolean matchesExpectedValue();
- }
-
- static abstract class BasePolicyItem implements PolicyItem {
- private String mDisplayName;
- private T mExpectedValue;
- private T mActualValue;
-
- BasePolicyItem(Context context, int nameResId) {
- mDisplayName = context.getString(nameResId);
- }
-
- @Override
- public final void setRandomExpectedValue(Random random) {
- mExpectedValue = getRandomExpectedValue(random);
- }
-
- protected abstract T getRandomExpectedValue(Random random);
-
- @Override
- public final void loadExpectedValue(SharedPreferences prefs) {
- mExpectedValue = getPreferencesValue(prefs);
- }
-
- protected abstract T getPreferencesValue(SharedPreferences prefs);
-
- @Override
- public final void loadActualValue(DevicePolicyManager deviceManager, ComponentName admin) {
- mActualValue = getDeviceManagerValue(deviceManager, admin);
- }
-
- protected abstract T getDeviceManagerValue(DevicePolicyManager deviceManager,
- ComponentName admin);
-
- @Override
- public final void resetActualValue() {
- mActualValue = null;
- }
-
- @Override
- public final String getDisplayName() {
- return mDisplayName;
- }
-
- @Override
- public final T getExpectedValue() {
- return mExpectedValue;
- }
-
- @Override
- public final String getDisplayExpectedValue() {
- return mExpectedValue != null ? getDisplayValue(mExpectedValue) : "";
- }
-
- @Override
- public final T getActualValue() {
- return mActualValue;
- }
-
- @Override
- public final String getDisplayActualValue() {
- return mActualValue != null ? getDisplayValue(mActualValue) : "";
- }
-
- protected String getDisplayValue(T value) {
- return "" + value;
- }
-
- @Override
- public final boolean matchesExpectedValue() {
- return mExpectedValue != null && mExpectedValue.equals(mActualValue);
- }
-
- @Override
- public String toString() {
- return getDisplayName();
- }
- }
-
- static abstract class IntegerPolicyItem extends BasePolicyItem {
-
- private String mPreferenceKey;
-
- IntegerPolicyItem(Context context, int nameResId, String preferenceKey) {
- super(context, nameResId);
- mPreferenceKey = preferenceKey;
- }
-
- @Override
- protected final Integer getPreferencesValue(SharedPreferences prefs) {
- return prefs.getInt(mPreferenceKey, -1);
- }
-
- @Override
- public final void saveExpectedValue(Editor editor) {
- editor.putInt(mPreferenceKey, getExpectedValue());
- }
- }
-
- static abstract class LongPolicyItem extends BasePolicyItem {
-
- private String mPreferenceKey;
-
- LongPolicyItem(Context context, int nameResId, String preferenceKey) {
- super(context, nameResId);
- mPreferenceKey = preferenceKey;
- }
-
- @Override
- protected final Long getPreferencesValue(SharedPreferences prefs) {
- return prefs.getLong(mPreferenceKey, -1);
- }
-
- @Override
- public final void saveExpectedValue(Editor editor) {
- editor.putLong(mPreferenceKey, getExpectedValue());
- }
- }
-
- static class PasswordQualityPolicy extends IntegerPolicyItem {
-
- private final Context mContext;
-
- public PasswordQualityPolicy(Context context) {
- super(context, R.string.da_password_quality, "password-quality");
- mContext = context;
- }
-
- @Override
- protected Integer getRandomExpectedValue(Random random) {
- int[] passwordQualities = new int[] {
- DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
- DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC,
- DevicePolicyManager.PASSWORD_QUALITY_NUMERIC,
- DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
- };
-
- int index = random.nextInt(passwordQualities.length);
- return passwordQualities[index];
- }
-
- @Override
- public void applyExpectedValue(DevicePolicyManager deviceManager, ComponentName admin) {
- deviceManager.setPasswordQuality(admin, getExpectedValue());
- }
-
- @Override
- protected Integer getDeviceManagerValue(DevicePolicyManager deviceManager,
- ComponentName admin) {
- return deviceManager.getPasswordQuality(admin);
- }
-
- @Override
- protected String getDisplayValue(Integer value) {
- switch (value) {
- case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
- return mContext.getString(R.string.da_password_quality_alphabetic);
- case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
- return mContext.getString(R.string.da_password_quality_alphanumeric);
- case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
- return mContext.getString(R.string.da_password_quality_numeric);
- case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
- return mContext.getString(R.string.da_password_quality_something);
- default:
- return Integer.toString(value);
- }
- }
- }
-
- static class PasswordMinimumLengthPolicy extends IntegerPolicyItem {
-
- PasswordMinimumLengthPolicy(Context context) {
- super(context, R.string.da_password_minimum_length, "password-minimum-length");
- }
-
- @Override
- protected Integer getRandomExpectedValue(Random random) {
- return random.nextInt(50);
- }
-
- @Override
- public void applyExpectedValue(DevicePolicyManager deviceManager, ComponentName admin) {
- deviceManager.setPasswordMinimumLength(admin, getExpectedValue());
- }
-
- @Override
- protected Integer getDeviceManagerValue(DevicePolicyManager deviceManager,
- ComponentName admin) {
- return deviceManager.getPasswordMinimumLength(admin);
- }
- }
-
- static class MaximumFailedPasswordsForWipePolicy extends IntegerPolicyItem {
-
- MaximumFailedPasswordsForWipePolicy(Context context) {
- super(context, R.string.da_maximum_failed_passwords_for_wipe,
- "maximum-failed-passwords-for-wipe");
- }
-
- @Override
- protected Integer getRandomExpectedValue(Random random) {
- return random.nextInt(50);
- }
-
- @Override
- public void applyExpectedValue(DevicePolicyManager deviceManager, ComponentName admin) {
- deviceManager.setMaximumFailedPasswordsForWipe(admin, getExpectedValue());
- }
-
- @Override
- protected Integer getDeviceManagerValue(DevicePolicyManager deviceManager,
- ComponentName admin) {
- return deviceManager.getMaximumFailedPasswordsForWipe(admin);
- }
- }
-
- static class MaximumTimeToLockPolicy extends LongPolicyItem {
-
- MaximumTimeToLockPolicy(Context context) {
- super(context, R.string.da_maximum_time_to_lock, "maximum-time-to-lock");
- }
-
- @Override
- protected Long getRandomExpectedValue(Random random) {
- return (long)(1000 + random.nextInt(60 * 60 * 1000));
- }
-
- @Override
- public void applyExpectedValue(DevicePolicyManager deviceManager, ComponentName admin) {
- deviceManager.setMaximumTimeToLock(admin, getExpectedValue());
- }
-
- @Override
- protected Long getDeviceManagerValue(DevicePolicyManager deviceManager,
- ComponentName admin) {
- return deviceManager.getMaximumTimeToLock(admin);
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java
deleted file mode 100644
index 5520bb7..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 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.verifier.admin;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.app.AlertDialog;
-import android.app.KeyguardManager;
-import android.app.admin.DevicePolicyManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-
-public class ScreenLockTestActivity extends PassFailButtons.Activity {
-
- private static final int ADD_DEVICE_ADMIN_REQUEST_CODE = 1;
-
- private ScreenOffReceiver mReceiver;
-
- private Button mForceLockButton;
-
- private DevicePolicyManager mDevicePolicyManager;
-
- private KeyguardManager mKeyguardManager;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.da_screen_lock_main);
- setPassFailButtonClickListeners();
- setInfoResources(R.string.da_screen_lock_test, R.string.da_screen_lock_info, -1);
-
- mDevicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
- mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
-
- getPassButton().setEnabled(false);
-
- mForceLockButton = (Button) findViewById(R.id.da_force_lock_button);
- mForceLockButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- sendAddDeviceAdminIntent();
- }
- });
-
- mReceiver = new ScreenOffReceiver();
- IntentFilter filter = new IntentFilter();
- filter.addAction(Intent.ACTION_SCREEN_OFF);
- registerReceiver(mReceiver, filter);
- }
-
- private void sendAddDeviceAdminIntent() {
- Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
- intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
- TestDeviceAdminReceiver.getComponent(this));
- startActivityForResult(intent, ADD_DEVICE_ADMIN_REQUEST_CODE);
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case ADD_DEVICE_ADMIN_REQUEST_CODE:
- handleAddDeviceAdminResult(resultCode, data);
- break;
- }
- }
-
- private void handleAddDeviceAdminResult(int resultCode, Intent data) {
- if (resultCode == RESULT_OK) {
- mDevicePolicyManager.lockNow();
- }
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- unregisterReceiver(mReceiver);
- }
-
- private class ScreenOffReceiver extends BroadcastReceiver {
-
- private static final int LOCK_CHECK_DELAY = 1000;
-
- @Override
- public void onReceive(Context context, Intent intent) {
- mForceLockButton.postDelayed(new Runnable() {
- @Override
- public void run() {
- boolean lockSuccess = mKeyguardManager.inKeyguardRestrictedInputMode();
- getPassButton().setEnabled(lockSuccess);
-
- int iconId = lockSuccess
- ? android.R.drawable.ic_dialog_info
- : android.R.drawable.ic_dialog_alert;
- int messageId = lockSuccess
- ? R.string.da_lock_success
- : R.string.da_lock_error;
- new AlertDialog.Builder(ScreenLockTestActivity.this)
- .setTitle(R.string.da_screen_lock_test)
- .setMessage(messageId)
- .setIcon(iconId)
- .setPositiveButton(android.R.string.ok, null)
- .show();
- }
- }, LOCK_CHECK_DELAY);
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/admin/TestDeviceAdminReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/admin/TestDeviceAdminReceiver.java
deleted file mode 100644
index 5ecb36d..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/admin/TestDeviceAdminReceiver.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.verifier.admin;
-
-import android.app.admin.DeviceAdminReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-
-public class TestDeviceAdminReceiver extends DeviceAdminReceiver {
-
- public static ComponentName getComponent(Context context) {
- return new ComponentName(context, TestDeviceAdminReceiver.class);
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audioquality/AudioQualityVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audioquality/AudioQualityVerifierActivity.java
index 755b62d..7d7c16d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audioquality/AudioQualityVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audioquality/AudioQualityVerifierActivity.java
@@ -280,11 +280,6 @@ public class AudioQualityVerifierActivity extends PassFailButtons.Activity
}
@Override
- public String getTestDetails() {
- return genReport();
- }
-
- @Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/backup/BackupTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/backup/BackupTestActivity.java
deleted file mode 100644
index cccc1c2..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/backup/BackupTestActivity.java
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * 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.verifier.backup;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.backup.BackupManager;
-import android.app.backup.FileBackupHelper;
-import android.app.backup.SharedPreferencesBackupHelper;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.provider.Settings;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.view.Window;
-import android.widget.BaseAdapter;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-import java.util.Scanner;
-
-/**
- * Test for checking whether the BackupManager is working properly. It lists the values of
- * several preferences and contents of files that should get backed up and restored after
- * running the backup manager and reinstalling the CTS verifier.
- */
-public class BackupTestActivity extends PassFailButtons.ListActivity {
-
- private static final String TAG = BackupTestActivity.class.getSimpleName();
-
- private static final int INSTRUCTIONS_DIALOG_ID = 1;
-
- private static final String TEST_PREFS_1 = "test-prefs-1";
- private static final String INT_PREF = "int-pref";
- private static final String BOOL_PREF = "bool-pref";
-
- private static final String TEST_PREFS_2 = "test-prefs-2";
- private static final String FLOAT_PREF = "float-pref";
- private static final String LONG_PREF = "long-pref";
- private static final String STRING_PREF = "string-pref";
-
- private static final String TEST_FILE_1 = "test-file-1";
- private static final String TEST_FILE_2 = "test-file-2";
-
- private BackupAdapter mAdapter;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
- setContentView(R.layout.bu_main);
- setPassFailButtonClickListeners();
- setInfoResources(R.string.backup_test, R.string.backup_info, 0);
-
- mAdapter = new BackupAdapter(this);
- setListAdapter(mAdapter);
-
- new LoadBackupItemsTask().execute();
-
- findViewById(R.id.generate_button).setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- new GenerateValuesTask().execute();
- }
- });
- }
-
- public static SharedPreferencesBackupHelper getSharedPreferencesBackupHelper(Context context) {
- return new SharedPreferencesBackupHelper(context, TEST_PREFS_1, TEST_PREFS_2);
- }
-
- public static FileBackupHelper getFileBackupHelper(Context context) {
- return new FileBackupHelper(context, TEST_FILE_1, TEST_FILE_2);
- }
-
- class LoadBackupItemsTask extends AsyncTask> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- setProgressBarIndeterminateVisibility(true);
- }
-
- @Override
- protected List doInBackground(Void... params) {
- List items = new ArrayList();
-
- items.add(new CategoryBackupItem(R.string.bu_preferences));
- loadPreferenceGroup1(items);
- loadPreferenceGroup2(items);
-
- items.add(new CategoryBackupItem(R.string.bu_files));
- loadFile(TEST_FILE_1, items);
- loadFile(TEST_FILE_2, items);
-
- return items;
- }
-
- private void loadPreferenceGroup1(List items) {
- SharedPreferences prefs = getSharedPreferences(TEST_PREFS_1, MODE_PRIVATE);
-
- int intValue = prefs.getInt(INT_PREF, 0);
- items.add(new PreferenceBackupItem(TEST_PREFS_1, INT_PREF, "" + intValue));
-
- boolean boolValue = prefs.getBoolean(BOOL_PREF, false);
- items.add(new PreferenceBackupItem(TEST_PREFS_1, BOOL_PREF, "" + boolValue));
- }
-
- private void loadPreferenceGroup2(List items) {
- SharedPreferences prefs = getSharedPreferences(TEST_PREFS_2, MODE_PRIVATE);
-
- float floatValue = prefs.getFloat(FLOAT_PREF, 0.0f);
- items.add(new PreferenceBackupItem(TEST_PREFS_2, FLOAT_PREF, "" + floatValue));
-
- long longValue = prefs.getLong(LONG_PREF, 0L);
- items.add(new PreferenceBackupItem(TEST_PREFS_2, LONG_PREF, "" + longValue));
-
- String stringValue = prefs.getString(STRING_PREF, null);
- items.add(new PreferenceBackupItem(TEST_PREFS_2, STRING_PREF, stringValue));
- }
-
- private void loadFile(String fileName, List items) {
- StringBuilder contents = new StringBuilder();
- Scanner scanner = null;
- try {
- scanner = new Scanner(new File(getFilesDir(), fileName));
- while (scanner.hasNext()) {
- contents.append(scanner.nextLine());
- }
- scanner.close();
- } catch (FileNotFoundException e) {
- Log.e(TAG, "Couldn't find test file but this may be fine...", e);
- } finally {
- if (scanner != null) {
- scanner.close();
- }
- }
- items.add(new FileBackupItem(fileName, contents.toString()));
- }
-
- @Override
- protected void onPostExecute(List result) {
- super.onPostExecute(result);
- setProgressBarIndeterminateVisibility(false);
- mAdapter.clear();
- mAdapter.addAll(result);
- }
- }
-
- class GenerateValuesTask extends AsyncTask {
-
- @Override
- protected Exception doInBackground(Void... params) {
- Random random = new Random();
- generatePreferenceGroup1(random);
- generatePreferenceGroup2(random);
- try {
- generateTestFile(TEST_FILE_1, random);
- generateTestFile(TEST_FILE_2, random);
- } catch (FileNotFoundException e) {
- return e;
- }
- return null;
- }
-
- private void generatePreferenceGroup1(Random random) {
- SharedPreferences prefs = getSharedPreferences(TEST_PREFS_1, MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.putInt(INT_PREF, (random.nextInt(100) + 1));
- editor.putBoolean(BOOL_PREF, random.nextBoolean());
- editor.commit();
- }
-
- private void generatePreferenceGroup2(Random random) {
- SharedPreferences prefs = getSharedPreferences(TEST_PREFS_2, MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.putFloat(FLOAT_PREF, random.nextFloat());
- editor.putLong(LONG_PREF, random.nextLong());
- editor.putString(STRING_PREF, "Random number: " + (random.nextInt(100) + 1));
- editor.commit();
- }
-
- private void generateTestFile(String fileName, Random random)
- throws FileNotFoundException {
- File file = new File(getFilesDir(), fileName);
- PrintWriter writer = new PrintWriter(file);
- writer.write("Random number: " + (random.nextInt(100) + 1));
- writer.close();
- }
-
- @Override
- protected void onPostExecute(Exception exception) {
- super.onPostExecute(exception);
- if (exception != null) {
- Log.e(TAG, "Couldn't generate test data...", exception);
- Toast.makeText(BackupTestActivity.this, R.string.bu_generate_error,
- Toast.LENGTH_LONG).show();
- } else {
- showDialog(INSTRUCTIONS_DIALOG_ID);
-
- BackupManager backupManager = new BackupManager(BackupTestActivity.this);
- backupManager.dataChanged();
-
- new LoadBackupItemsTask().execute();
- }
- }
- }
-
- @Override
- public Dialog onCreateDialog(int id, Bundle args) {
- switch (id) {
- case INSTRUCTIONS_DIALOG_ID:
- return new AlertDialog.Builder(this)
- .setIcon(android.R.drawable.ic_dialog_info)
- .setTitle(R.string.backup_test)
- .setMessage(R.string.bu_instructions)
- .setPositiveButton(android.R.string.ok, null)
- .setNeutralButton(R.string.bu_settings, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- startActivity(new Intent(Settings.ACTION_PRIVACY_SETTINGS));
- }
- })
- .create();
-
- default:
- return super.onCreateDialog(id, args);
- }
- }
-
- interface BackupItem {
- int getViewType();
- View getView(LayoutInflater inflater, int position, View convertView, ViewGroup parent);
- }
-
- static class CategoryBackupItem implements BackupItem {
-
- private final int mTitleResId;
-
- CategoryBackupItem(int titleResId) {
- mTitleResId = titleResId;
- }
-
- @Override
- public int getViewType() {
- return 0;
- }
-
- @Override
- public View getView(LayoutInflater inflater, int position, View convertView,
- ViewGroup parent) {
- TextView view = (TextView) convertView;
- if (convertView == null) {
- view = (TextView) inflater.inflate(R.layout.test_category_row, parent, false);
- }
- view.setText(mTitleResId);
- return view;
- }
- }
-
- static class PreferenceBackupItem implements BackupItem {
-
- private final String mGroup;
-
- private final String mName;
-
- private final String mValue;
-
- PreferenceBackupItem(String group, String name, String value) {
- mGroup = group;
- mName = name;
- mValue = value;
- }
-
- @Override
- public int getViewType() {
- return 1;
- }
-
- @Override
- public View getView(LayoutInflater inflater, int position, View convertView,
- ViewGroup parent) {
- TextView view = (TextView) convertView;
- if (convertView == null) {
- view = (TextView) inflater.inflate(R.layout.bu_preference_row, parent, false);
- }
- view.setText(mGroup + "/" + mName + " : " + mValue);
- return view;
- }
- }
-
- static class FileBackupItem implements BackupItem {
-
- private final String mName;
-
- private final String mContents;
-
- FileBackupItem(String name, String contents) {
- mName = name;
- mContents = contents;
- }
-
- @Override
- public int getViewType() {
- return 2;
- }
-
- @Override
- public View getView(LayoutInflater inflater, int position, View convertView,
- ViewGroup parent) {
- TextView view = (TextView) convertView;
- if (convertView == null) {
- view = (TextView) inflater.inflate(R.layout.bu_preference_row, parent, false);
- }
- view.setText(mName + " : " + mContents);
- return view;
- }
- }
-
- class BackupAdapter extends BaseAdapter {
-
- private final LayoutInflater mLayoutInflater;
-
- private final List mItems = new ArrayList();
-
- public BackupAdapter(Context context) {
- mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
- }
-
- public void clear() {
- mItems.clear();
- }
-
- public void addAll(List items) {
- mItems.addAll(items);
- notifyDataSetChanged();
- }
-
- @Override
- public int getCount() {
- return mItems.size();
- }
-
- @Override
- public BackupItem getItem(int position) {
- return mItems.get(position);
- }
-
- @Override
- public long getItemId(int position) {
- return position;
- }
-
- @Override
- public boolean isEnabled(int position) {
- return false;
- }
-
- @Override
- public int getViewTypeCount() {
- return 3;
- }
-
- @Override
- public int getItemViewType(int position) {
- return getItem(position).getViewType();
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- return getItem(position).getView(mLayoutInflater, position, convertView, parent);
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
index 6eb587f..05c50e3 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
@@ -49,13 +49,6 @@ public class BluetoothChatService {
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
- static final UUID SECURE_UUID =
- UUID.fromString("8591d757-18ee-45e1-9b12-92875d06ba23");
- static final UUID INSECURE_UUID =
- UUID.fromString("301c214f-91a2-43bf-a795-09d1198a81a7");
- static final UUID HANDSFREE_INSECURE_UUID =
- UUID.fromString("0000111F-0000-1000-8000-00805F9B34FB");
-
// Debugging
private static final String TAG = "CtsBluetoothChatService";
private static final boolean D = true;
@@ -64,10 +57,15 @@ public class BluetoothChatService {
private static final String NAME_SECURE = "CtsBluetoothChatSecure";
private static final String NAME_INSECURE = "CtsBluetoothChatInsecure";
+ // Unique UUID for this application
+ private static final UUID MY_UUID_SECURE =
+ UUID.fromString("8591d757-18ee-45e1-9b12-92875d06ba23");
+ private static final UUID MY_UUID_INSECURE =
+ UUID.fromString("301c214f-91a2-43bf-a795-09d1198a81a7");
+
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
- private final UUID mUuid;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
@@ -85,11 +83,10 @@ public class BluetoothChatService {
* @param context The UI Activity Context
* @param handler A Handler to send messages back to the UI Activity
*/
- public BluetoothChatService(Context context, Handler handler, UUID uuid) {
+ public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
- mUuid = uuid;
}
/**
@@ -282,9 +279,11 @@ public class BluetoothChatService {
// Create a new listening server socket
try {
if (secure) {
- tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, mUuid);
+ tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
+ MY_UUID_SECURE);
} else {
- tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, mUuid);
+ tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
+ NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + " listen() failed", e);
@@ -369,9 +368,11 @@ public class BluetoothChatService {
// given BluetoothDevice
try {
if (secure) {
- tmp = device.createRfcommSocketToServiceRecord(mUuid);
+ tmp = device.createRfcommSocketToServiceRecord(
+ MY_UUID_SECURE);
} else {
- tmp = device.createInsecureRfcommSocketToServiceRecord(mUuid);
+ tmp = device.createInsecureRfcommSocketToServiceRecord(
+ MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java
index 9895f02..b617fc2 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java
@@ -16,21 +16,498 @@
package com.android.cts.verifier.bluetooth;
-import com.android.cts.verifier.ManifestTestListAdapter;
import com.android.cts.verifier.PassFailButtons;
import com.android.cts.verifier.R;
+import com.android.cts.verifier.TestResult;
+import android.app.AlertDialog;
+import android.bluetooth.BluetoothAdapter;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.os.AsyncTask;
import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
-public class BluetoothTestActivity extends PassFailButtons.TestListActivity {
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class BluetoothTestActivity extends PassFailButtons.ListActivity {
+
+ public static final int TEST_BLUETOOTH_TOGGLE = 0;
+ public static final int TEST_SECURE_SERVER = 1;
+ public static final int TEST_INSECURE_SERVER = 2;
+ public static final int TEST_SECURE_CLIENT = 3;
+ public static final int TEST_INSECURE_CLIENT = 4;
+
+ private static final int START_TOGGLE_BLUETOOTH_TEST_REQUEST = 1;
+ private static final int START_SECURE_SERVER_REQUEST = 2;
+ private static final int START_INSECURE_SERVER_REQUEST = 3;
+ private static final int START_SECURE_PICK_SERVER_REQUEST = 4;
+ private static final int START_INSECURE_PICK_SERVER_REQUEST = 5;
+ private static final int START_SECURE_CLIENT_REQUEST = 6;
+ private static final int START_INSECURE_CLIENT_REQUEST = 7;
+
+ private TestListItem mBluetoothToggleTest;
+ private TestListItem mSecureServerTest;
+ private TestListItem mInsecureServerTest;
+ private TestListItem mSecureClientTest;
+ private TestListItem mInsecureClientTest;
+
+ private static final String TABLE_NAME = "results";
+ private static final String _ID = "_id";
+ private static final String COLUMN_TEST_ID = "test_id";
+ private static final String COLUMN_TEST_RESULT = "test_result";
+ private static final String[] ALL_COLUMNS = {
+ _ID,
+ COLUMN_TEST_ID,
+ COLUMN_TEST_RESULT,
+ };
+
+ private TestListAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setContentView(R.layout.pass_fail_list);
+ setContentView(R.layout.bt_main);
setPassFailButtonClickListeners();
setInfoResources(R.string.bluetooth_test, R.string.bluetooth_test_info, -1);
- setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName()));
+ mBluetoothToggleTest = TestListItem.newTest(R.string.bt_toggle_bluetooth,
+ TEST_BLUETOOTH_TOGGLE);
+ mSecureServerTest = TestListItem.newTest(R.string.bt_secure_server,
+ TEST_SECURE_SERVER);
+ mInsecureServerTest = TestListItem.newTest(R.string.bt_insecure_server,
+ TEST_INSECURE_SERVER);
+ mSecureClientTest = TestListItem.newTest(R.string.bt_secure_client,
+ TEST_SECURE_CLIENT);
+ mInsecureClientTest = TestListItem.newTest(R.string.bt_insecure_client,
+ TEST_INSECURE_CLIENT);
+
+ mAdapter = new TestListAdapter(this);
+ mAdapter.add(TestListItem.newCategory(R.string.bt_control));
+ mAdapter.add(mBluetoothToggleTest);
+
+ mAdapter.add(TestListItem.newCategory(R.string.bt_device_communication));
+ mAdapter.add(mSecureServerTest);
+ mAdapter.add(mInsecureServerTest);
+ mAdapter.add(mSecureClientTest);
+ mAdapter.add(mInsecureClientTest);
+
+ setListAdapter(mAdapter);
+ refreshTestResults();
+
+ if (BluetoothAdapter.getDefaultAdapter() == null) {
+ showNoBluetoothDialog();
+ }
+ }
+
+ private void refreshTestResults() {
+ new RefreshTask().execute();
+ }
+
+ private void showNoBluetoothDialog() {
+ new AlertDialog.Builder(this)
+ .setIcon(android.R.drawable.ic_dialog_alert)
+ .setTitle(R.string.bt_not_available_title)
+ .setMessage(R.string.bt_not_available_message)
+ .setCancelable(false)
+ .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ finish();
+ }
+ })
+ .show();
+ }
+
+ @Override
+ protected void onListItemClick(ListView l, View v, int position, long id) {
+ super.onListItemClick(l, v, position, id);
+ TestListItem testItem = (TestListItem) l.getItemAtPosition(position);
+ switch (testItem.mId) {
+ case TEST_BLUETOOTH_TOGGLE:
+ startToggleBluetoothActivity();
+ break;
+
+ case TEST_SECURE_SERVER:
+ startServerActivity(true);
+ break;
+
+ case TEST_INSECURE_SERVER:
+ startServerActivity(false);
+ break;
+
+ case TEST_SECURE_CLIENT:
+ startDevicePickerActivity(true);
+ break;
+
+ case TEST_INSECURE_CLIENT:
+ startDevicePickerActivity(false);
+ break;
+ }
+ }
+
+ private void startToggleBluetoothActivity() {
+ Intent intent = new Intent(this, BluetoothToggleActivity.class);
+ startActivityForResult(intent, START_TOGGLE_BLUETOOTH_TEST_REQUEST);
+ }
+
+ private void startServerActivity(boolean secure) {
+ Intent intent = new Intent(this, MessageTestActivity.class)
+ .putExtra(MessageTestActivity.EXTRA_SECURE, secure);
+ startActivityForResult(intent, secure
+ ? START_SECURE_SERVER_REQUEST
+ : START_INSECURE_SERVER_REQUEST);
+ }
+
+ private void startDevicePickerActivity(boolean secure) {
+ Intent intent = new Intent(this, DevicePickerActivity.class);
+ startActivityForResult(intent, secure
+ ? START_SECURE_PICK_SERVER_REQUEST
+ : START_INSECURE_PICK_SERVER_REQUEST);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ switch (requestCode) {
+ case START_TOGGLE_BLUETOOTH_TEST_REQUEST:
+ handleEnableBluetoothResult(resultCode, data);
+ break;
+
+ case START_SECURE_SERVER_REQUEST:
+ handleServerResult(resultCode, data, true);
+ break;
+
+ case START_INSECURE_SERVER_REQUEST:
+ handleServerResult(resultCode, data, false);
+ break;
+
+ case START_SECURE_PICK_SERVER_REQUEST:
+ handleDevicePickerResult(resultCode, data, true);
+ break;
+
+ case START_INSECURE_PICK_SERVER_REQUEST:
+ handleDevicePickerResult(resultCode, data, false);
+ break;
+
+ case START_SECURE_CLIENT_REQUEST:
+ handleClientResult(resultCode, data, true);
+ break;
+
+ case START_INSECURE_CLIENT_REQUEST:
+ handleClientResult(resultCode, data, false);
+ break;
+ }
+ }
+
+ private void handleEnableBluetoothResult(int resultCode, Intent data) {
+ if (data != null) {
+ TestResult result = TestResult.fromActivityResult(resultCode, data);
+ mBluetoothToggleTest.setResult(result.getResult());
+ updateTest(mBluetoothToggleTest);
+ }
+ }
+
+ private void updateTest(TestListItem item) {
+ new UpdateTask().execute(item.mId, item.mResult);
+ }
+
+ private void handleServerResult(int resultCode, Intent data, boolean secure) {
+ if (data != null) {
+ TestResult result = TestResult.fromActivityResult(resultCode, data);
+ TestListItem test = secure ? mSecureServerTest : mInsecureServerTest;
+ test.setResult(result.getResult());
+ updateTest(test);
+ }
+ }
+
+ private void handleDevicePickerResult(int resultCode, Intent data, boolean secure) {
+ if (resultCode == RESULT_OK) {
+ String address = data.getStringExtra(DevicePickerActivity.EXTRA_DEVICE_ADDRESS);
+ startClientActivity(address, secure);
+ }
+ }
+
+ private void startClientActivity(String address, boolean secure) {
+ Intent intent = new Intent(this, MessageTestActivity.class)
+ .putExtra(MessageTestActivity.EXTRA_DEVICE_ADDRESS, address)
+ .putExtra(MessageTestActivity.EXTRA_SECURE, secure);
+ startActivityForResult(intent, secure
+ ? START_SECURE_CLIENT_REQUEST
+ : START_INSECURE_CLIENT_REQUEST);
+ }
+
+ private void handleClientResult(int resultCode, Intent data, boolean secure) {
+ if (data != null) {
+ TestResult result = TestResult.fromActivityResult(resultCode, data);
+ TestListItem test = secure ? mSecureClientTest : mInsecureClientTest;
+ test.setResult(result.getResult());
+ updateTest(test);
+ }
+ }
+
+ private class UpdateTask extends AsyncTask {
+
+ @Override
+ protected Void doInBackground(Integer[] resultPairs) {
+ TestResultsHelper openHelper = new TestResultsHelper(BluetoothTestActivity.this);
+ SQLiteDatabase db = openHelper.getWritableDatabase();
+
+ int testId = resultPairs[0];
+ int testResult = resultPairs[1];
+
+ ContentValues values = new ContentValues(2);
+ values.put(COLUMN_TEST_ID, testId);
+ values.put(COLUMN_TEST_RESULT, testResult);
+
+ try {
+ if (0 == db.update(TABLE_NAME, values, COLUMN_TEST_ID + " = ?",
+ new String[] {Integer.toString(testId)})) {
+ db.insert(TABLE_NAME, null, values);
+ }
+ } finally {
+ if (db != null) {
+ db.close();
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Void result) {
+ super.onPostExecute(result);
+ refreshTestResults();
+ }
+ }
+
+ private class RefreshTask extends AsyncTask> {
+
+ @Override
+ protected Map doInBackground(Void... params) {
+ Map results = new HashMap();
+ TestResultsHelper openHelper = new TestResultsHelper(BluetoothTestActivity.this);
+ SQLiteDatabase db = openHelper.getReadableDatabase();
+ Cursor cursor = null;
+ try {
+ cursor = db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
+ while (cursor.moveToNext()) {
+ int testId = cursor.getInt(1);
+ int testResult = cursor.getInt(2);
+ results.put(testId, testResult);
+ }
+ } finally {
+ if (cursor != null) {
+ cursor.close();
+ }
+ if (db != null) {
+ db.close();
+ }
+ }
+ return results;
+ }
+
+ @Override
+ protected void onPostExecute(Map results) {
+ super.onPostExecute(results);
+ for (Integer testId : results.keySet()) {
+ TestListItem item = mAdapter.getTest(testId);
+ if (item != null) {
+ item.setResult(results.get(testId));
+ }
+ }
+ mAdapter.notifyDataSetChanged();
+ }
+ }
+
+ static class TestListItem {
+
+ static final int NUM_VIEW_TYPES = 2;
+
+ static final int VIEW_TYPE_CATEGORY = 0;
+
+ static final int VIEW_TYPE_TEST = 1;
+
+ final int mViewType;
+
+ final int mTitle;
+
+ final int mId;
+
+ int mResult;
+
+ static TestListItem newTest(int title, int id) {
+ return new TestListItem(VIEW_TYPE_TEST, title, id);
+ }
+
+ static TestListItem newCategory(int title) {
+ return new TestListItem(VIEW_TYPE_CATEGORY, title, -1);
+ }
+
+ private TestListItem(int viewType, int title, int id) {
+ this.mViewType = viewType;
+ this.mTitle = title;
+ this.mId = id;
+ }
+
+ public boolean isTest() {
+ return mViewType == VIEW_TYPE_TEST;
+ }
+
+ public void setResult(int result) {
+ mResult = result;
+ }
+ }
+
+ static class TestListAdapter extends BaseAdapter {
+
+ private static final int PADDING = 10;
+
+ private final List mItems = new ArrayList();
+
+ private final Map mTestsById = new HashMap();
+
+ private final LayoutInflater mInflater;
+
+ public TestListAdapter(Context context) {
+ mInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
+ }
+
+ public void add(TestListItem item) {
+ mItems.add(item);
+ if (item.isTest()) {
+ mTestsById.put(item.mId, item);
+ }
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ int backgroundResource = 0;
+ int iconResource = 0;
+
+ TestListItem item = getItem(position);
+
+ TextView textView = null;
+ if (convertView == null) {
+ int layout = getLayout(position);
+ textView = (TextView) mInflater.inflate(layout, parent, false);
+ } else {
+ textView = (TextView) convertView;
+ }
+
+ textView.setText(item.mTitle);
+
+ if (item.isTest()) {
+ switch (item.mResult) {
+ case TestResult.TEST_RESULT_PASSED:
+ backgroundResource = R.drawable.test_pass_gradient;
+ iconResource = R.drawable.fs_good;
+ break;
+
+ case TestResult.TEST_RESULT_FAILED:
+ backgroundResource = R.drawable.test_fail_gradient;
+ iconResource = R.drawable.fs_error;
+ break;
+
+ case TestResult.TEST_RESULT_NOT_EXECUTED:
+ break;
+
+ default:
+ throw new IllegalArgumentException("Unknown test result: " + item.mResult);
+ }
+
+ textView.setBackgroundResource(backgroundResource);
+ textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, iconResource, 0);
+ textView.setPadding(PADDING, 0, PADDING, 0);
+ textView.setCompoundDrawablePadding(PADDING);
+ }
+
+ return textView;
+ }
+
+ private int getLayout(int position) {
+ int viewType = getItemViewType(position);
+ switch (viewType) {
+ case TestListItem.VIEW_TYPE_CATEGORY:
+ return R.layout.test_category_row;
+ case TestListItem.VIEW_TYPE_TEST:
+ return android.R.layout.simple_list_item_1;
+ default:
+ throw new IllegalArgumentException("Illegal view type: " + viewType);
+
+ }
+ }
+
+ public TestListItem getTest(int id) {
+ return mTestsById.get(id);
+ }
+
+ @Override
+ public int getCount() {
+ return mItems.size();
+ }
+
+ @Override
+ public TestListItem getItem(int position) {
+ return mItems.get(position);
+ }
+
+ @Override
+ public long getItemId(int position) {
+ return getItem(position).mId;
+ }
+
+ @Override
+ public int getViewTypeCount() {
+ return TestListItem.NUM_VIEW_TYPES;
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ return getItem(position).mViewType;
+ }
+
+ @Override
+ public boolean isEnabled(int position) {
+ return getItemViewType(position) != TestListItem.VIEW_TYPE_CATEGORY;
+ }
+ }
+
+ class TestResultsHelper extends SQLiteOpenHelper {
+
+ private static final String DATABASE_NAME = "bluetooth_results.db";
+
+ private static final int DATABASE_VERSION = 1;
+
+ TestResultsHelper(Context context) {
+ super(context, DATABASE_NAME, null, DATABASE_VERSION);
+ }
+
+ @Override
+ public void onCreate(SQLiteDatabase db) {
+ db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ + COLUMN_TEST_ID + " INTEGER, "
+ + COLUMN_TEST_RESULT + " INTEGER DEFAULT 0);");
+ }
+
+ @Override
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
+ onCreate(db);
+ }
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/ConnectionAccessClientActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/ConnectionAccessClientActivity.java
deleted file mode 100644
index 5befdaf..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/ConnectionAccessClientActivity.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * 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.verifier.bluetooth;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.provider.Settings;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.Window;
-import android.widget.Button;
-import android.widget.TextView;
-import android.widget.Toast;
-
-public class ConnectionAccessClientActivity extends PassFailButtons.Activity {
-
- private static final int ENABLE_BLUETOOTH_REQUEST = 1;
- private static final int PICK_SERVER_DEVICE_REQUEST = 2;
-
- private BluetoothAdapter mBluetoothAdapter;
- private BluetoothChatService mChatService;
- private String mDeviceAddress;
- private Button mPickServerButton;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
- setContentView(R.layout.bt_connection_access);
- setInfoResources(R.string.bt_connection_access_client,
- R.string.bt_connection_access_client_info, 0);
- setPassFailButtonClickListeners();
-
- View settings = findViewById(R.id.bt_settings);
- settings.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
- }
- });
-
- mPickServerButton = (Button) findViewById(R.id.bt_pick_server_button);
- mPickServerButton.setVisibility(View.VISIBLE);
- mPickServerButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- startDevicePickerActivity();
- }
- });
-
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (!mBluetoothAdapter.isEnabled()) {
- mPickServerButton.setEnabled(false);
- startEnableBluetoothActivity();
- }
- }
-
- private void startDevicePickerActivity() {
- Intent intent = new Intent(this, DevicePickerActivity.class);
- startActivityForResult(intent, PICK_SERVER_DEVICE_REQUEST);
- }
-
- private void startEnableBluetoothActivity() {
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(intent, ENABLE_BLUETOOTH_REQUEST);
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case ENABLE_BLUETOOTH_REQUEST:
- if (resultCode == RESULT_OK) {
- mPickServerButton.setEnabled(true);
- } else {
- setResult(RESULT_CANCELED);
- finish();
- }
- break;
-
- case PICK_SERVER_DEVICE_REQUEST:
- if (resultCode == RESULT_OK) {
- mDeviceAddress = data.getStringExtra(DevicePickerActivity.EXTRA_DEVICE_ADDRESS);
- startChartService();
- }
- break;
- }
- }
-
- private void startChartService() {
- mChatService = new BluetoothChatService(this, new ChatHandler(),
- BluetoothChatService.HANDSFREE_INSECURE_UUID);
- BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
- mChatService.connect(device, false);
- }
-
- private class ChatHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- switch (msg.what) {
- case BluetoothChatService.MESSAGE_STATE_CHANGE:
- handleStateChange(msg);
- break;
-
- case BluetoothChatService.MESSAGE_DEVICE_NAME:
- handleDeviceName(msg);
- break;
-
- case BluetoothChatService.MESSAGE_TOAST:
- handleToast(msg);
- break;
- }
- }
- }
-
- private void handleStateChange(Message msg) {
- int state = msg.arg1;
- switch (state) {
- case BluetoothChatService.STATE_CONNECTING:
- setProgressBarIndeterminateVisibility(true);
- Toast.makeText(this, R.string.bt_connecting, Toast.LENGTH_SHORT).show();
- break;
-
- case BluetoothChatService.STATE_CONNECTED:
- setProgressBarIndeterminateVisibility(false);
- Toast.makeText(this, R.string.bt_connected, Toast.LENGTH_SHORT).show();
- break;
-
- case BluetoothChatService.STATE_NONE:
- setProgressBarIndeterminateVisibility(false);
- break;
- }
- }
-
- private void handleDeviceName(Message msg) {
- mDeviceAddress = msg.getData().getString(BluetoothChatService.DEVICE_NAME);
- }
-
- private void handleToast(Message msg) {
- String toast = msg.getData().getString(BluetoothChatService.TOAST);
- Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/ConnectionAccessServerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/ConnectionAccessServerActivity.java
deleted file mode 100644
index 19c46af..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/ConnectionAccessServerActivity.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * 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.verifier.bluetooth;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.app.AlertDialog;
-import android.bluetooth.BluetoothAdapter;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.provider.Settings;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.Window;
-import android.widget.Button;
-import android.widget.TextView;
-import android.widget.Toast;
-
-public class ConnectionAccessServerActivity extends PassFailButtons.Activity {
-
- private static final String ACTION_CONNECTION_ACCESS_REQUEST =
- "android.bluetooth.device.action.CONNECTION_ACCESS_REQUEST";
-
- private static final int ENABLE_BLUETOOTH_REQUEST = 1;
-
- private BluetoothAdapter mBluetoothAdapter;
- private ConnectionAccessRequestReceiver mConnectionAccessRequestReceiver;
- private BluetoothChatService mChatService;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
- setContentView(R.layout.bt_connection_access);
- setInfoResources(R.string.bt_connection_access_server,
- R.string.bt_connection_access_server_info, 0);
- setPassFailButtonClickListeners();
- getPassButton().setEnabled(false);
-
- View settings = findViewById(R.id.bt_settings);
- settings.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
- }
- });
-
- Button makeDiscoverableButton = (Button) findViewById(R.id.bt_make_discoverable_button);
- makeDiscoverableButton.setVisibility(View.VISIBLE);
- makeDiscoverableButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- makeDiscoverable();
- }
- });
-
- mConnectionAccessRequestReceiver = new ConnectionAccessRequestReceiver();
- IntentFilter intentFilter = new IntentFilter(ACTION_CONNECTION_ACCESS_REQUEST);
- registerReceiver(mConnectionAccessRequestReceiver, intentFilter);
-
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (mBluetoothAdapter.isEnabled()) {
- startChatService();
- } else {
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(intent, ENABLE_BLUETOOTH_REQUEST);
- }
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case ENABLE_BLUETOOTH_REQUEST:
- if (resultCode == RESULT_OK) {
- startChatService();
- } else {
- setResult(RESULT_CANCELED);
- finish();
- }
- break;
- }
- }
-
- private void startChatService() {
- mChatService = new BluetoothChatService(this, new ChatHandler(),
- BluetoothChatService.HANDSFREE_INSECURE_UUID);
- boolean secure = false;
- mChatService.start(secure);
- }
-
- private void makeDiscoverable() {
- if (mBluetoothAdapter.getScanMode() !=
- BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
- startActivity(intent);
- }
- }
-
- private class ChatHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- switch (msg.what) {
- case BluetoothChatService.MESSAGE_STATE_CHANGE:
- handleStateChange(msg);
- break;
-
- case BluetoothChatService.MESSAGE_TOAST:
- handleToast(msg);
- break;
- }
- }
- }
-
- private void handleStateChange(Message msg) {
- int state = msg.arg1;
- switch (state) {
- case BluetoothChatService.STATE_LISTEN:
- setProgressBarIndeterminateVisibility(true);
- Toast.makeText(this, R.string.bt_listening, Toast.LENGTH_SHORT).show();
- break;
- }
- }
-
- private void handleToast(Message msg) {
- String toast = msg.getData().getString(BluetoothChatService.TOAST);
- Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
- }
-
- class ConnectionAccessRequestReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- new AlertDialog.Builder(ConnectionAccessServerActivity.this)
- .setMessage(R.string.bt_ca_dialog)
- .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- getPassButton().setEnabled(true);
- }
- })
- .setNegativeButton(android.R.string.cancel,
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- getPassButton().setEnabled(false);
- }
- })
- .show();
- }
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- if (mChatService != null) {
- mChatService.stop();
- }
- unregisterReceiver(mConnectionAccessRequestReceiver);
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/InsecureClientActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/InsecureClientActivity.java
deleted file mode 100644
index da1f369..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/InsecureClientActivity.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.verifier.bluetooth;
-
-public class InsecureClientActivity extends MessageTestActivity {
- public InsecureClientActivity() {
- super(false, false, BluetoothChatService.INSECURE_UUID);
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/InsecureServerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/InsecureServerActivity.java
deleted file mode 100644
index 31ae7d8..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/InsecureServerActivity.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.verifier.bluetooth;
-
-public class InsecureServerActivity extends MessageTestActivity {
- public InsecureServerActivity() {
- super(false, true, BluetoothChatService.INSECURE_UUID);
- }
-}
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/MessageTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/MessageTestActivity.java
index 2c6324b..1d6706d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/MessageTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/MessageTestActivity.java
@@ -32,26 +32,27 @@ import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
-import android.view.View.OnClickListener;
import android.view.Window;
+import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
-import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-class MessageTestActivity extends PassFailButtons.Activity {
+public class MessageTestActivity extends PassFailButtons.Activity {
+
+ static final String EXTRA_DEVICE_ADDRESS = "deviceAddress";
+ static final String EXTRA_SECURE = "secure";
/** Broadcast action that should only be fired when pairing for a secure connection. */
private static final String ACTION_PAIRING_REQUEST =
"android.bluetooth.device.action.PAIRING_REQUEST";
private static final int ENABLE_BLUETOOTH_REQUEST = 1;
- private static final int PICK_SERVER_DEVICE_REQUEST = 2;
private static final String MESSAGE_DELIMITER = "\n";
private static final Pattern MESSAGE_PATTERN = Pattern.compile("Message (\\d+) to .*");
@@ -72,20 +73,12 @@ class MessageTestActivity extends PassFailButtons.Activity {
private AlertDialog mInstructionsDialog;
private String mDeviceAddress;
-
- private final boolean mSecure;
- private final boolean mServer;
- private final UUID mUuid;
+ private boolean mSecure;
+ private boolean mServer;
private String mRemoteDeviceName = "";
private StringBuilder mMessageBuffer = new StringBuilder();
- MessageTestActivity(boolean secure, boolean server, UUID uuid) {
- mSecure = secure;
- mServer = server;
- mUuid = uuid;
- }
-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -93,6 +86,9 @@ class MessageTestActivity extends PassFailButtons.Activity {
setContentView(R.layout.bt_messages);
setPassFailButtonClickListeners();
+ mDeviceAddress = getIntent().getStringExtra(EXTRA_DEVICE_ADDRESS);
+ mSecure = getIntent().getBooleanExtra(EXTRA_SECURE, true);
+ mServer = mDeviceAddress == null || mDeviceAddress.isEmpty();
if (mServer) {
setTitle(mSecure ? R.string.bt_secure_server : R.string.bt_insecure_server);
} else {
@@ -131,46 +127,29 @@ class MessageTestActivity extends PassFailButtons.Activity {
registerReceiver(mPairingActionReceiver, intentFilter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (!mServer) {
- Intent intent = new Intent(this, DevicePickerActivity.class);
- startActivityForResult(intent, PICK_SERVER_DEVICE_REQUEST);
+ if (mBluetoothAdapter.isEnabled()) {
+ startChatService();
} else {
- if (mBluetoothAdapter.isEnabled()) {
- startChatService();
- } else {
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(intent, ENABLE_BLUETOOTH_REQUEST);
- }
+ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ startActivityForResult(intent, ENABLE_BLUETOOTH_REQUEST);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case ENABLE_BLUETOOTH_REQUEST:
- if (resultCode == RESULT_OK) {
- startChatService();
- } else {
- setResult(RESULT_CANCELED);
- finish();
- }
- break;
-
- case PICK_SERVER_DEVICE_REQUEST:
- if (resultCode == RESULT_OK) {
- mDeviceAddress = data.getStringExtra(DevicePickerActivity.EXTRA_DEVICE_ADDRESS);
- startChatService();
- } else {
- setResult(RESULT_CANCELED);
- finish();
- }
- break;
+ if (requestCode == ENABLE_BLUETOOTH_REQUEST) {
+ if (resultCode == RESULT_OK) {
+ startChatService();
+ } else {
+ setResult(RESULT_CANCELED);
+ finish();
+ }
}
}
private void startChatService() {
- mChatService = new BluetoothChatService(this, new ChatHandler(), mUuid);
+ mChatService = new BluetoothChatService(this, new ChatHandler());
if (mServer) {
mChatService.start(mSecure);
} else {
@@ -342,7 +321,7 @@ class MessageTestActivity extends PassFailButtons.Activity {
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
- TestResult.setFailedResult(MessageTestActivity.this, getTestId(), null);
+ TestResult.setFailedResult(MessageTestActivity.this);
finish();
}
})
@@ -353,9 +332,7 @@ class MessageTestActivity extends PassFailButtons.Activity {
@Override
protected void onDestroy() {
super.onDestroy();
- if (mChatService != null) {
- mChatService.stop();
- }
+ mChatService.stop();
unregisterReceiver(mPairingActionReceiver);
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/SecureClientActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/SecureClientActivity.java
deleted file mode 100644
index ad908b5..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/SecureClientActivity.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.verifier.bluetooth;
-
-public class SecureClientActivity extends MessageTestActivity {
- public SecureClientActivity() {
- super(true, false, BluetoothChatService.SECURE_UUID);
- }
-}
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/SecureServerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/SecureServerActivity.java
deleted file mode 100644
index df50026..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/SecureServerActivity.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.verifier.bluetooth;
-
-public class SecureServerActivity extends MessageTestActivity {
- public SecureServerActivity() {
- super(true, true, BluetoothChatService.SECURE_UUID);
- }
-}
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraAnalyzerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraAnalyzerActivity.java
deleted file mode 100644
index b50dd9e..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraAnalyzerActivity.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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.verifier.camera.analyzer;
-
-import com.android.cts.verifier.R;
-
-import android.app.Activity;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.ImageFormat;
-import android.hardware.Camera;
-import android.os.Bundle;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
-import android.view.View;
-import android.widget.ImageView;
-import android.widget.TextView;
-
-import java.io.IOException;
-
-public class CameraAnalyzerActivity extends Activity {
-
- Bitmap mInputImage;
- TextView mResultText;
- SurfaceView mCameraView;
- ImageView mResultView;
- Camera mCamera;
- boolean mProcessingPicture = false;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.ca_main);
-
- findViewById(R.id.runbutton).setOnClickListener(mRunListener);
-
- mCameraView = (SurfaceView)findViewById(R.id.cameraview);
- mResultView = (ImageView)findViewById(R.id.resultview);
- mResultText = (TextView)findViewById(R.id.resulttext);
- mCameraView.getHolder().addCallback(mSurfaceChangeListener);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- mCamera = Camera.open(0);
- Camera.Parameters params = mCamera.getParameters();
- params.setPictureFormat(ImageFormat.JPEG);
- mCamera.setParameters(params);
- }
-
- @Override
- public void onPause() {
- super.onPause();
- mCamera.release();
- }
-
- private View.OnClickListener mRunListener = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (!mProcessingPicture) {
- mCamera.takePicture(null, null, null, mJpegListener);
- mProcessingPicture = true;
- }
- }
- };
-
- private Camera.PictureCallback mJpegListener = new Camera.PictureCallback() {
- public void onPictureTaken(byte[] data, Camera mCamera) {
- mCamera.startPreview();
- mInputImage = BitmapFactory.decodeByteArray(data, 0, data.length);
- ColorChecker checker = new ColorChecker(mInputImage);
- mResultView.setImageBitmap(checker.getDebugOutput());
- if (checker.isValid()) {
- String patchValueTxt = new String();
- for (int y = 0; y < 4; y++) {
- for (int x = 0; x < 6; x++) {
- patchValueTxt +=
- String.format("[ %.3f, %.3f, %.3f] ",
- checker.getPatchValue(x,y,0),
- checker.getPatchValue(x,y,1),
- checker.getPatchValue(x,y,2));
- }
- patchValueTxt += "\n";
- }
- mResultText.setText(patchValueTxt);
- } else {
- mResultText.setText("Can't find color checker!");
- }
- mProcessingPicture = false;
- }
- };
-
- private SurfaceHolder.Callback mSurfaceChangeListener =
- new SurfaceHolder.Callback() {
- @Override
- public void surfaceChanged(SurfaceHolder holder,
- int format,
- int width,
- int height) {
-
- }
-
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- try {
- mCamera.setPreviewDisplay(mCameraView.getHolder());
- } catch (IOException e) {
- throw new RuntimeException("Unable to connect camera to display: " + e);
- }
- mCamera.startPreview();
- }
-
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
-
- }
-
- };
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ColorChecker.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ColorChecker.java
deleted file mode 100644
index c9df24a..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ColorChecker.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * 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.verifier.camera.analyzer;
-
-import android.graphics.Bitmap;
-
-/** The ColorChecker class is used to locate a Xrite Classic Color Checker grid
- * pattern in an image, and return the average value of each color patch.
- *
- * The pattern is a 6x4 grid of square color patches. The detection routine
- * assumes the pattern is placed roughly facing the camera, with the long size
- * roughly horizontal. It doesn't matter whether the pattern is upside down or
- * not - the returned array will have the grayscale squares of the pattern on
- * the bottom row.
- */
-class ColorChecker {
-
- private float[] mPatchValues;
- private Bitmap mDebugOutput;
- private boolean mSuccess = false;
-
- /** Construct a ColorChecker from a source Bitmap.
- *
- * @param source The source image to scan through for the 6x4 Xrite Classic
- * Color Checker pattern.
- */
- public ColorChecker(Bitmap source) {
- mPatchValues = new float[6 * 4 * 3];
- mSuccess = findNative(source);
- }
-
- /** Returns whether the ColorChecker pattern was found in the source bitmap
- *
- * @return true if the pattern was found in the source Bitmap. false
- * otherwise.
- */
- public boolean isValid() {
- return mSuccess;
- }
-
- /** Returns patch RGB triplet for patch (x, y), or null if the pattern wasn't
- * found.
- *
- * @param x Column of the patch
- * @param y Row of the patch
- * @return A 3-entry float array representing the R, G, and B values of the
- * patch in roughly linear luminance, mapped to the 0-1 range.
- */
- public float[] getPatchRGB(int x, int y) {
- if (!mSuccess) throw new RuntimeException("No color checker found!");
- float[] rgb = {
- mPatchValues[(y * 6 + x) * 3 + 0],
- mPatchValues[(y * 6 + x) * 3 + 1],
- mPatchValues[(y * 6 + x) * 3 + 2]
- };
- return rgb;
- }
-
- /** Returns patch (x, y) color channel c.
- *
- * @param x Column of the patch
- * @param y Row of the patch
- * @param c Color channel of the patch (0 = R, 1 = G, 2 = B)
- * @return The float value for that color channel in roughly linear
- * luminance, mapped to the 0-1 range.
- */
- public float getPatchValue(int x, int y, int c) {
- if (!mSuccess) throw new RuntimeException("No color checker found!");
- return mPatchValues[(y * 6 + x) * 3 + c];
- }
-
- /** Returns debug Bitmap image showing detected candidate patches and the
- * grid if it was found. Valid even if the pattern wasn't found. Candiate
- * patches will have red bounding boxes. In addition, patches that are part
- * of the color checker pattern are have a green diagonal, and all their
- * member pixels are colored in solid blue.
- *
- * @return A low-resolution version of the source Bitmap with overlaid
- * detection results.
- */
- public Bitmap getDebugOutput() {
- return mDebugOutput;
- }
-
- native boolean findNative(Bitmap input);
-
- static {
- System.loadLibrary("cameraanalyzer");
- }
-}
\ No newline at end of file
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 3ea9451..aad97ad 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
@@ -40,8 +40,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
-import java.util.LinkedHashSet;
-import java.util.Set;
public class FeatureSummaryActivity extends PassFailButtons.ListActivity {
/**
@@ -76,25 +74,11 @@ public class FeatureSummaryActivity extends PassFailButtons.ListActivity {
this.required = required;
this.present = false;
}
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- } else if (o == null || !(o instanceof Feature)) {
- return false;
- } else {
- Feature feature = (Feature) o;
- return name.equals(feature.name);
- }
- }
-
- @Override
- public int hashCode() {
- return name.hashCode();
- }
}
+ /**
+ * A list of all features added in Eclair (API=7).
+ */
public static final Feature[] ALL_ECLAIR_FEATURES = {
new Feature(PackageManager.FEATURE_CAMERA, true),
new Feature(PackageManager.FEATURE_CAMERA_AUTOFOCUS, false),
@@ -107,6 +91,15 @@ public class FeatureSummaryActivity extends PassFailButtons.ListActivity {
new Feature(PackageManager.FEATURE_TELEPHONY_GSM, false),
};
+ /**
+ * A list of all features added in FroYo (API=8) and Gingerbread (API=9).
+ * Because we want to run on Eclair devices,
+ * we can't use static references to constants added later
+ * than Eclair. We could use Reflection, but we'd still need a list of
+ * string literals (for constant names) anyway, and there's little point in
+ * using Reflection to to look up a constant String value for a constant
+ * String name.
+ */
public static final Feature[] ALL_FROYO_FEATURES = {
new Feature("android.hardware.bluetooth", true),
new Feature("android.hardware.location", true),
@@ -122,15 +115,6 @@ public class FeatureSummaryActivity extends PassFailButtons.ListActivity {
};
public static final Feature[] ALL_GINGERBREAD_FEATURES = {
- // Required features in prior releases that became optional in GB
- new Feature("android.hardware.bluetooth", false),
- new Feature("android.hardware.camera", false),
- new Feature("android.hardware.location.gps", false),
- new Feature("android.hardware.microphone", false),
- new Feature("android.hardware.sensor.accelerometer", false),
- new Feature("android.hardware.sensor.compass", false),
-
- // New features in GB
new Feature("android.hardware.audio.low_latency", false),
new Feature("android.hardware.camera.front", false),
new Feature("android.hardware.nfc", false),
@@ -141,33 +125,6 @@ public class FeatureSummaryActivity extends PassFailButtons.ListActivity {
new Feature("android.software.sip.voip", false),
};
- public static final Feature[] ALL_GINGERBREAD_MR1_FEATURES = {
- new Feature("android.hardware.usb.accessory", false),
- };
-
- public static final Feature[] ALL_HONEYCOMB_FEATURES = {
- // Required features in prior releases that became optional in HC
- new Feature("android.hardware.touchscreen", false),
-
- new Feature("android.hardware.faketouch", true),
- };
-
- public static final Feature[] ALL_HONEYCOMB_MR1_FEATURES = {
- new Feature("android.hardware.usb.host", false),
- new Feature("android.hardware.usb.accessory", true),
- };
-
- public static final Feature[] ALL_HONEYCOMB_MR2_FEATURES = {
- new Feature("android.hardware.faketouch.multitouch.distinct", false),
- new Feature("android.hardware.faketouch.multitouch.jazzhand", false),
- new Feature("android.hardware.screen.landscape", false),
- new Feature("android.hardware.screen.portrait", false),
- };
-
- public static final Feature[] ALL_ICE_CREAM_SANDWICH_FEATURES = {
- new Feature(PackageManager.FEATURE_WIFI_DIRECT, false),
- };
-
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -194,33 +151,16 @@ public class FeatureSummaryActivity extends PassFailButtons.ListActivity {
// roll over all known features & check whether device reports them
boolean present = false;
int statusIcon;
- Set features = new LinkedHashSet();
-
- // add features from latest to last so that the latest requirements are put in the set first
+ ArrayList features = new ArrayList();
int apiVersion = Build.VERSION.SDK_INT;
- if (apiVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
- Collections.addAll(features, ALL_ICE_CREAM_SANDWICH_FEATURES);
- }
- if (apiVersion >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- Collections.addAll(features, ALL_HONEYCOMB_MR2_FEATURES);
- }
- if (apiVersion >= Build.VERSION_CODES.HONEYCOMB_MR1) {
- Collections.addAll(features, ALL_HONEYCOMB_MR1_FEATURES);
- }
- if (apiVersion >= Build.VERSION_CODES.HONEYCOMB) {
- Collections.addAll(features, ALL_HONEYCOMB_FEATURES);
- }
- if (apiVersion >= Build.VERSION_CODES.GINGERBREAD_MR1) {
- Collections.addAll(features, ALL_GINGERBREAD_MR1_FEATURES);
- }
- if (apiVersion >= Build.VERSION_CODES.GINGERBREAD) {
- Collections.addAll(features, ALL_GINGERBREAD_FEATURES);
+ if (apiVersion >= Build.VERSION_CODES.ECLAIR_MR1) {
+ Collections.addAll(features, ALL_ECLAIR_FEATURES);
}
if (apiVersion >= Build.VERSION_CODES.FROYO) {
Collections.addAll(features, ALL_FROYO_FEATURES);
}
- if (apiVersion >= Build.VERSION_CODES.ECLAIR_MR1) {
- Collections.addAll(features, ALL_ECLAIR_FEATURES);
+ if (apiVersion >= Build.VERSION_CODES.GINGERBREAD) {
+ Collections.addAll(features, ALL_GINGERBREAD_FEATURES);
}
for (Feature f : features) {
HashMap row = new HashMap();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeTestActivity.java
deleted file mode 100644
index ea6ca4c..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeTestActivity.java
+++ /dev/null
@@ -1,412 +0,0 @@
-/*
- * 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.verifier.sensors;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.app.AlertDialog;
-import android.content.Intent;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.opengl.GLSurfaceView;
-import android.opengl.GLU;
-import android.os.Bundle;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.TextView;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.FloatBuffer;
-import java.nio.ShortBuffer;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.microedition.khronos.egl.EGLConfig;
-import javax.microedition.khronos.opengles.GL10;
-
-/**
- * Manual test for testing the gyroscope sensor. This test consists of 6 steps for all the
- * different ways to rotate the device along the x, y, and z axis. It also raises a warning
- * if the values seem to high and may be degrees.
- */
-public class GyroscopeTestActivity extends PassFailButtons.Activity {
-
- private static final int NUM_STAGES = 6;
- private static final String STAGE_INDEX_EXTRA = "stageIndex";
-
- private static final int BACKGROUND_BLACK = 0;
- private static final int BACKGROUND_RED = 1;
- private static final int BACKGROUND_GREEN = 2;
-
- private AtomicInteger mBackgroundColor = new AtomicInteger(BACKGROUND_BLACK);
-
- private SensorManager mSensorManager;
- private Sensor mSensor;
- private SensorListener mSensorListener;
- private GLSurfaceView mGLSurfaceView;
- private TextView mProgressText;
- private TextView mSensorText;
-
- private AlertDialog mNoGyroscopeWarningDialog;
- private AlertDialog mDegreesWarningDialog;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.snsr_gyro);
- setInfoResources(R.string.snsr_gyro_test, R.string.snsr_gyro_test_info, 0);
- setPassFailButtonClickListeners();
-
- // This activity is reused 6 times with different settings to test each rotation direction
- final int stageIndex = getIntent().getIntExtra(STAGE_INDEX_EXTRA, 0);
- Settings settings = getSettings(stageIndex);
-
- // Hitting the pass button goes to the next test activity. Only the last one ends the test.
- if (stageIndex + 1 < NUM_STAGES) {
- setPassButtonGoesToNextStage(stageIndex);
- }
-
- mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
- mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
- mSensorListener = new SensorListener(settings.mSensorEventIndex,
- settings.mExpectPositiveValue);
-
- mGLSurfaceView = (GLSurfaceView) findViewById(R.id.gl_surface_view);
- mGLSurfaceView.setRenderer(new RotationGuideRenderer(settings.mRotateX, settings.mRotateY,
- settings.mRotateZ));
-
- mProgressText = (TextView) findViewById(R.id.progress);
- mProgressText.setText(String.format(getString(R.string.snsr_gyro_test_progress),
- settings.mStageIndex + 1, settings.mTotalStages));
-
- mSensorText = (TextView) findViewById(R.id.sensor_value);
- }
-
- private Settings getSettings(int stageIndex) {
- switch (stageIndex) {
- case 0:
- return new Settings(stageIndex, NUM_STAGES, 0, 0, 1, 2, true);
- case 1:
- return new Settings(stageIndex, NUM_STAGES, 0, 0, -1, 2, false);
- case 2:
- return new Settings(stageIndex, NUM_STAGES, 0, 1, 0, 1, true);
- case 3:
- return new Settings(stageIndex, NUM_STAGES, 0, -1, 0, 1, false);
- case 4:
- return new Settings(stageIndex, NUM_STAGES, 1, 0, 0, 0, true);
- case 5:
- return new Settings(stageIndex, NUM_STAGES, -1, 0, 0, 0, false);
- default:
- throw new IllegalArgumentException("Bad stage index: " + stageIndex);
- }
- }
-
- /** Bundle of settings for testing a certain rotation direction. */
- class Settings {
- int mStageIndex;
- int mTotalStages;
- float mRotateX;
- float mRotateY;
- float mRotateZ;
- int mSensorEventIndex;
- boolean mExpectPositiveValue;
-
- Settings(int stageIndex, int totalStages, float rotateX, float rotateY, float rotateZ,
- int sensorEventIndex, boolean expectPositiveValue) {
- mStageIndex = stageIndex;
- mTotalStages = totalStages;
- mRotateX = rotateX;
- mRotateY = rotateY;
- mRotateZ = rotateZ;
- mSensorEventIndex = sensorEventIndex;
- mExpectPositiveValue = expectPositiveValue;
- }
- }
-
- private void setPassButtonGoesToNextStage(final int stageIndex) {
- findViewById(R.id.pass_button).setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(GyroscopeTestActivity.this,
- GyroscopeTestActivity.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
- | Intent.FLAG_ACTIVITY_FORWARD_RESULT);
- intent.putExtra(STAGE_INDEX_EXTRA, stageIndex + 1);
- startActivity(intent);
- }
- });
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- if (!mSensorManager.registerListener(mSensorListener, mSensor,
- SensorManager.SENSOR_DELAY_UI)) {
- showNoGyroscopeWarningDialog();
- }
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- mSensorManager.unregisterListener(mSensorListener, mSensor);
- }
-
- /** Renders a spinning block to indicate how the device should be rotated in the test. */
- class RotationGuideRenderer implements GLSurfaceView.Renderer {
-
- private static final double ANGLE_INCREMENT = 1.0;
-
- private final Monolith mMonolith = new Monolith();
-
- private float mAngle = 0.0f;
-
- private float mRotateX;
-
- private float mRotateY;
-
- private float mRotateZ;
-
- public RotationGuideRenderer(float rotateX, float rotateY, float rotateZ) {
- mRotateX = rotateX;
- mRotateY = rotateY;
- mRotateZ = rotateZ;
- }
-
- @Override
- public void onDrawFrame(GL10 gl) {
- clearBackground(gl);
- gl.glMatrixMode(GL10.GL_MODELVIEW);
- gl.glLoadIdentity();
- gl.glRotatef(mAngle, mRotateX, mRotateY, mRotateZ);
- mMonolith.draw(gl);
- mAngle += ANGLE_INCREMENT;
- }
-
- private void clearBackground(GL10 gl) {
- switch (mBackgroundColor.get()) {
- case BACKGROUND_GREEN:
- gl.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
- break;
-
- case BACKGROUND_RED:
- gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
- break;
-
- default:
- gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
- break;
- }
- gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
- }
-
- @Override
- public void onSurfaceChanged(GL10 gl, int width, int height) {
- gl.glViewport(0, 0, width, height);
- gl.glMatrixMode(GL10.GL_PROJECTION);
- gl.glLoadIdentity();
- float ratio = (float) width / height;
- gl.glFrustumf(-ratio, ratio, -1, 1, 3, 15);
- GLU.gluLookAt(gl, 0, 0, 10, 0, 0, 0, 0, 1, 0);
- }
-
- @Override
- public void onSurfaceCreated(GL10 gl, EGLConfig config) {
- gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
- gl.glEnable(GL10.GL_LIGHTING);
- gl.glEnable(GL10.GL_LIGHT0);
- gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, new float[] {0.75f, 0.75f, 0.75f, 1f}, 0);
- }
- }
-
- /** Rectangular block that is rotated by {@link RotationGuideRenderer}. */
- class Monolith {
-
- private static final int NUM_VERTICES = 8;
-
- private static final int NUM_INDICES = 36;
-
- private FloatBuffer mVertexBuffer;
-
- private ShortBuffer mIndexBuffer;
-
- public Monolith() {
- mVertexBuffer = ByteBuffer.allocateDirect(NUM_VERTICES * 3 * 4)
- .order(ByteOrder.nativeOrder())
- .asFloatBuffer();
-
- float[] coordinates = {
- -0.65f, -1, 0.2f,
- -0.65f, 1, 0.2f,
- 0.65f, 1, 0.2f,
- 0.65f, -1, 0.2f,
-
- -0.65f, -1, -0.2f,
- -0.65f, 1, -0.2f,
- 0.65f, 1, -0.2f,
- 0.65f, -1, -0.2f,
- };
-
- for (int i = 0; i < coordinates.length; i++) {
- mVertexBuffer.put(coordinates[i]);
- }
-
- mIndexBuffer = ByteBuffer.allocateDirect(NUM_INDICES * 2)
- .order(ByteOrder.nativeOrder())
- .asShortBuffer();
-
- // Front
- mIndexBuffer.put((short) 0);
- mIndexBuffer.put((short) 1);
- mIndexBuffer.put((short) 2);
- mIndexBuffer.put((short) 0);
- mIndexBuffer.put((short) 2);
- mIndexBuffer.put((short) 3);
-
- // Back
- mIndexBuffer.put((short) 7);
- mIndexBuffer.put((short) 6);
- mIndexBuffer.put((short) 5);
- mIndexBuffer.put((short) 7);
- mIndexBuffer.put((short) 5);
- mIndexBuffer.put((short) 4);
-
- // Right
- mIndexBuffer.put((short) 3);
- mIndexBuffer.put((short) 2);
- mIndexBuffer.put((short) 6);
- mIndexBuffer.put((short) 3);
- mIndexBuffer.put((short) 6);
- mIndexBuffer.put((short) 7);
-
- // Left
- mIndexBuffer.put((short) 4);
- mIndexBuffer.put((short) 5);
- mIndexBuffer.put((short) 1);
- mIndexBuffer.put((short) 4);
- mIndexBuffer.put((short) 1);
- mIndexBuffer.put((short) 0);
-
- // Top
- mIndexBuffer.put((short) 1);
- mIndexBuffer.put((short) 5);
- mIndexBuffer.put((short) 6);
- mIndexBuffer.put((short) 1);
- mIndexBuffer.put((short) 6);
- mIndexBuffer.put((short) 2);
-
- // Bottom
- mIndexBuffer.put((short) 3);
- mIndexBuffer.put((short) 7);
- mIndexBuffer.put((short) 4);
- mIndexBuffer.put((short) 3);
- mIndexBuffer.put((short) 4);
- mIndexBuffer.put((short) 0);
-
- mVertexBuffer.position(0);
- mIndexBuffer.position(0);
- }
-
- public void draw(GL10 gl) {
- gl.glColor4f(0.5f, 0.5f, 0.5f, 1f);
- gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
- gl.glDrawElements(GL10.GL_TRIANGLES, NUM_INDICES, GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
- }
- }
-
- class SensorListener implements SensorEventListener {
-
- /** Throw away other events that are smaller than this. */
- private static final double MOVING_AMOUNT = 0.1;
-
- private final int mEventIndex;
-
- private final boolean mExpectPositive;
-
- SensorListener(int eventIndex, boolean expectPositive) {
- mEventIndex = eventIndex;
- mExpectPositive = expectPositive;
- }
-
- @Override
- public void onSensorChanged(SensorEvent event) {
- float value = event.values[mEventIndex];
- if (value > MOVING_AMOUNT) {
- if (mExpectPositive) {
- updateWidgets(value, BACKGROUND_GREEN, R.drawable.fs_good);
- } else {
- updateWidgets(value, BACKGROUND_RED, R.drawable.fs_error);
- }
- } else if (value < -MOVING_AMOUNT) {
- if (mExpectPositive) {
- updateWidgets(value, BACKGROUND_RED, R.drawable.fs_error);
- } else {
- updateWidgets(value, BACKGROUND_GREEN, R.drawable.fs_good);
- }
- } else {
- updateWidgets(value, BACKGROUND_BLACK, R.drawable.fs_indeterminate);
- }
-
- if (value > 10) {
- showDegreesWarningDialog();
- }
- }
-
- void updateWidgets(float sensorValue, int backgroundColor, int icon) {
- synchronized (GyroscopeTestActivity.this) {
- mBackgroundColor.set(backgroundColor);
- }
- mSensorText.setText(String.format("%+.2f", sensorValue));
- mSensorText.setCompoundDrawablesWithIntrinsicBounds(0, 0, icon, 0);
- }
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
- }
-
- private void showNoGyroscopeWarningDialog() {
- if (mNoGyroscopeWarningDialog == null) {
- mNoGyroscopeWarningDialog = new AlertDialog.Builder(GyroscopeTestActivity.this)
- .setIcon(android.R.drawable.ic_dialog_alert)
- .setTitle(R.string.snsr_gyro_test_no_gyro_title)
- .setMessage(R.string.snsr_gyro_test_no_gyro_message)
- .setPositiveButton(android.R.string.ok, null)
- .create();
- }
- if (!mNoGyroscopeWarningDialog.isShowing()) {
- mNoGyroscopeWarningDialog.show();
- }
- }
-
- private void showDegreesWarningDialog() {
- if (mDegreesWarningDialog == null) {
- mDegreesWarningDialog = new AlertDialog.Builder(GyroscopeTestActivity.this)
- .setIcon(android.R.drawable.ic_dialog_alert)
- .setTitle(R.string.snsr_gyro_test_degrees_title)
- .setMessage(R.string.snsr_gyro_test_degrees_message)
- .setPositiveButton(android.R.string.ok, null)
- .create();
- }
- if (!mDegreesWarningDialog.isShowing()) {
- mDegreesWarningDialog.show();
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/PlayVideoActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/PlayVideoActivity.java
deleted file mode 100644
index 2b65421..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/PlayVideoActivity.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * 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.verifier.streamquality;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-import com.android.cts.verifier.streamquality.StreamingVideoActivity.Stream;
-
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.content.DialogInterface;
-import android.content.DialogInterface.OnClickListener;
-import android.graphics.Rect;
-import android.media.MediaPlayer;
-import android.media.MediaPlayer.OnErrorListener;
-import android.media.MediaPlayer.OnPreparedListener;
-import android.media.MediaPlayer.OnVideoSizeChangedListener;
-import android.os.Bundle;
-import android.os.Handler;
-import android.util.Log;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
-import android.view.ViewGroup.LayoutParams;
-import android.widget.FrameLayout;
-
-import java.io.IOException;
-
-/**
- * Activity that plays a video and allows the user to select pass/fail after 60 seconds.
- */
-public class PlayVideoActivity extends PassFailButtons.Activity
- implements SurfaceHolder.Callback, OnErrorListener, OnPreparedListener,
- OnVideoSizeChangedListener {
- /**
- * Intent extra defining the {@link Stream} information
- */
- static final String EXTRA_STREAM = "com.android.cts.verifier.streamquality.EXTRA_STREAM";
-
- private static final String TAG = PlayVideoActivity.class.getName();
- private static final long ENABLE_PASS_DELAY = 60 * 1000;
-
- private static final int FAIL_DIALOG_ID = 1;
-
- private final Runnable enablePassButton = new Runnable() {
- @Override public void run() {
- setEnablePassButton(true);
- }
- };
-
- private Stream mStream;
- private SurfaceHolder mHolder;
- private SurfaceView mSurfaceView;
- private FrameLayout mVideoFrame;
- private MediaPlayer mPlayer;
- private Handler mHandler = new Handler();
- private int mVideoWidth;
- private int mVideoHeight;
- private boolean mIsVideoSizeKnown = false;
- private boolean mIsVideoReadyToBePlayed = false;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.sv_play);
- setPassFailButtonClickListeners();
-
- setEnablePassButton(false);
-
- mSurfaceView = (SurfaceView) findViewById(R.id.surface);
- mVideoFrame = (FrameLayout) findViewById(R.id.videoframe);
- mHolder = mSurfaceView.getHolder();
- mHolder.addCallback(this);
- mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
-
- mStream = (Stream) getIntent().getSerializableExtra(EXTRA_STREAM);
- }
-
- private void setEnablePassButton(boolean enable) {
- getPassButton().setEnabled(enable);
- }
-
- private void playVideo() {
- mPlayer = new MediaPlayer();
- mPlayer.setDisplay(mHolder);
- mPlayer.setScreenOnWhilePlaying(true);
- mPlayer.setOnVideoSizeChangedListener(this);
- mPlayer.setOnErrorListener(this);
- mPlayer.setOnPreparedListener(this);
- try {
- mPlayer.setDataSource(mStream.uri);
- } catch (IOException e) {
- Log.e(TAG, "Unable to play video, setDataSource failed", e);
- showDialog(FAIL_DIALOG_ID);
- return;
- }
- mPlayer.prepareAsync();
- }
-
- @Override
- public Dialog onCreateDialog(int id, Bundle args) {
- switch (id) {
- case FAIL_DIALOG_ID:
- return new AlertDialog.Builder(this)
- .setTitle(getString(R.string.sv_failed_title))
- .setMessage(getString(R.string.sv_failed_message))
- .setNegativeButton("Close", new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- PassFailButtons.setTestResultAndFinish(PlayVideoActivity.this,
- getTestId(), null, false);
- }
- })
- .show();
- default:
- return super.onCreateDialog(id, args);
- }
- }
-
- @Override
- public String getTestId() {
- return getTestId(mStream.code);
- }
-
- public static String getTestId(String code) {
- return PlayVideoActivity.class.getName() + "_" + code;
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- // This test must be completed in one session
- mHandler.removeCallbacks(enablePassButton);
- finish();
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- if (mPlayer != null) {
- mPlayer.release();
- mPlayer = null;
- }
- }
-
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- playVideo();
- }
-
- @Override
- public boolean onError(MediaPlayer mp, int what, int extra) {
- Log.e(TAG, "Unable to play video, got onError with code " + what + ", extra " + extra);
- showDialog(FAIL_DIALOG_ID);
- return true;
- }
-
- @Override
- public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
- mVideoWidth = width;
- mVideoHeight = height;
- mIsVideoSizeKnown = true;
- if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
- startVideoPlayback();
- }
- }
-
- private void startVideoPlayback() {
- mHolder.setFixedSize(mVideoWidth, mVideoHeight);
- fillScreen();
- mPlayer.start();
-
- // Enable Pass button after 60 seconds
- mHandler.postDelayed(enablePassButton, ENABLE_PASS_DELAY);
- }
-
- @Override
- public void onPrepared(MediaPlayer mp) {
- mIsVideoReadyToBePlayed = true;
- if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
- startVideoPlayback();
- }
- }
-
- private void fillScreen() {
- Rect rect = new Rect();
- mVideoFrame.getDrawingRect(rect);
- LayoutParams lp = mSurfaceView.getLayoutParams();
- float aspectRatio = ((float) mVideoWidth) / mVideoHeight;
- if (rect.width() / aspectRatio <= rect.height()) {
- lp.width = rect.width();
- lp.height = (int) (rect.width() / aspectRatio);
- } else {
- lp.width = (int) (rect.height() * aspectRatio);
- lp.height = rect.height();
- }
- mSurfaceView.setLayoutParams(lp);
- }
-
- @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
- @Override public void surfaceDestroyed(SurfaceHolder holder) {}
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java
deleted file mode 100644
index d575e5f..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * 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.verifier.streamquality;
-
-import com.android.cts.verifier.ArrayTestListAdapter;
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-import com.android.cts.verifier.TestListAdapter;
-import com.android.cts.verifier.TestListAdapter.TestListItem;
-
-import android.content.Intent;
-import android.database.DataSetObserver;
-import android.os.Bundle;
-import android.widget.TextView;
-
-import java.io.Serializable;
-
-/**
- * Tests for verifying the quality of streaming videos. Plays streams of different formats over
- * different protocols for a short amount of time, after which users can mark Pass/Fail depending
- * on the smoothness and subjective quality of the video.
- */
-public class StreamingVideoActivity extends PassFailButtons.TestListActivity {
- /**
- * Simple storage class for stream information.
- */
- static class Stream implements Serializable {
- /**
- * Human-readable name for the stream.
- */
- public final String name;
-
- /**
- * Code name to append to the class name to identify this test.
- */
- public final String code;
-
- /**
- * URI of the stream
- */
- public final String uri;
-
- public Stream(String name, String code, String uri) {
- this.name = name;
- this.code = code;
- this.uri = uri;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- } else if (o == null || !(o instanceof Stream)) {
- return false;
- } else {
- Stream stream = (Stream) o;
- return name.equals(stream.name)
- && code.equals(stream.code)
- && uri.equals(stream.uri);
- }
- }
-
- @Override
- public int hashCode() {
- return name.hashCode() ^ uri.hashCode() ^ code.hashCode();
- }
-
- @Override
- public String toString() {
- return name;
- }
- }
-
- private static final Stream[] RTSP_STREAMS = {
- new Stream("H263 Video, AMR Audio", "rtsp_h263_amr",
- "rtsp://v2.cache7.c.youtube.com/video.3gp?"
- + "cid=0x271de9756065677e&fmt=13&user=android-device-test"),
- new Stream("MPEG4 SP Video, AAC Audio", "rtsp_mpeg4_aac",
- "rtsp://v2.cache7.c.youtube.com/video.3gp?"
- + "cid=0x271de9756065677e&fmt=13&user=android-device-test"),
- new Stream("H264 Base Video, AAC Audio", "rtsp_h264_aac",
- "rtsp://v2.cache7.c.youtube.com/video.3gp?"
- + "cid=0x271de9756065677e&fmt=13&user=android-device-test"),
- };
-
- private static final Stream[] HTTP_STREAMS = {
- new Stream("H263 Video, AMR Audio", "http_h263_amr", "http://v20.lscache8.c.youtube.com/"
- + "videoplayback?id=271de9756065677e"
- + "&itag=13&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=372FA4C532AA49D14EAF049BCDA66460EEE161E9"
- + ".6D8BF096B73B7A68A7032CA8685053CFB498D30A"
- + "&key=test_key1&user=android-device-test"),
- new Stream("MPEG4 SP Video, AAC Audio", "http_mpeg4_aac",
- "http://v20.lscache8.c.youtube.com/"
- + "videoplayback?id=271de9756065677e"
- + "&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=3DCD3F79E045F95B6AF661765F046FB0440FF016"
- + ".06A42661B3AF6BAF046F012549CC9BA34EBC80A9"
- + "&key=test_key1&user=android-device-test"),
- new Stream("H264 Base Video, AAC Audio", "http_h264_aac",
- "http://v20.lscache8.c.youtube.com/"
- + "videoplayback?id=271de9756065677e"
- + "&itag=18&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=1219C2B07AF0638C27916307A6093C0E43CB894E"
- + ".126B6B916BD57157782738AA7C03E59F21DBC168"
- + "&key=test_key1&user=android-device-test"),
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.pass_fail_list);
- setPassFailButtonClickListeners();
- setInfoResources(R.string.streaming_video, R.string.streaming_video_info, -1);
-
- TextView empty = (TextView) findViewById(android.R.id.empty);
- empty.setText(R.string.sv_no_data);
-
- getPassButton().setEnabled(false);
- setTestListAdapter(getStreamAdapter());
- }
-
- private TestListAdapter getStreamAdapter() {
- ArrayTestListAdapter adapter = new ArrayTestListAdapter(this);
-
- adapter.add(TestListItem.newCategory("RTSP"));
- for (Stream stream : RTSP_STREAMS) {
- addStreamToTests(adapter, stream);
- }
-
- adapter.add(TestListItem.newCategory("HTTP Progressive"));
- for (Stream stream : HTTP_STREAMS) {
- addStreamToTests(adapter, stream);
- }
-
- adapter.registerDataSetObserver(new DataSetObserver() {
- @Override
- public void onChanged() {
- updatePassButton();
- }
- });
-
- return adapter;
- }
-
- private void addStreamToTests(ArrayTestListAdapter streams, Stream stream) {
- Intent i = new Intent(StreamingVideoActivity.this, PlayVideoActivity.class);
- i.putExtra(PlayVideoActivity.EXTRA_STREAM, stream);
- streams.add(TestListItem.newTest(stream.name, PlayVideoActivity.getTestId(stream.code),
- i, null));
- }
-
- private void updatePassButton() {
- getPassButton().setEnabled(mAdapter.allTestsPassed());
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/suid/SuidFilesActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/suid/SuidFilesActivity.java
index 7d99c2d..4a7224b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/suid/SuidFilesActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/suid/SuidFilesActivity.java
@@ -16,7 +16,6 @@
package com.android.cts.verifier.suid;
-import com.android.cts.verifier.PassFailButtons;
import com.android.cts.verifier.R;
import com.android.cts.verifier.TestResult;
import com.android.cts.verifier.os.FileUtils;
@@ -24,6 +23,7 @@ import com.android.cts.verifier.os.FileUtils.FileStatus;
import android.app.Activity;
import android.app.AlertDialog;
+import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
@@ -45,7 +45,7 @@ import java.util.HashSet;
import java.util.Set;
/** {@link Activity} that tries to find suid files. */
-public class SuidFilesActivity extends PassFailButtons.ListActivity {
+public class SuidFilesActivity extends ListActivity {
private static final String TAG = SuidFilesActivity.class.getSimpleName();
@@ -63,9 +63,7 @@ public class SuidFilesActivity extends PassFailButtons.ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setContentView(R.layout.pass_fail_list);
- setPassFailButtonClickListeners();
- getPassButton().setEnabled(false);
+ setResult(RESULT_CANCELED);
mAdapter = new SuidFilesAdapter();
setListAdapter(mAdapter);
@@ -75,19 +73,16 @@ public class SuidFilesActivity extends PassFailButtons.ListActivity {
.setTitle(R.string.suid_files)
.setMessage(R.string.suid_files_info)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
public void onClick(DialogInterface dialog, int which) {
startScan();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
- @Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setOnCancelListener(new OnCancelListener() {
- @Override
public void onCancel(DialogInterface dialog) {
finish();
}
@@ -99,7 +94,6 @@ public class SuidFilesActivity extends PassFailButtons.ListActivity {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getString(R.string.scanning_directory));
mProgressDialog.setOnCancelListener(new OnCancelListener() {
- @Override
public void onCancel(DialogInterface dialog) {
// If the scanning dialog is cancelled, then stop the task and finish the activity
// to prevent the user from just seeing a blank listview.
@@ -211,7 +205,6 @@ public class SuidFilesActivity extends PassFailButtons.ListActivity {
private final FileStatus status = new FileStatus();
- @Override
public boolean accept(File pathname) {
// Don't follow symlinks to avoid infinite looping.
if (FileUtils.getFileStatus(pathname.getPath(), status, true)) {
@@ -228,7 +221,6 @@ public class SuidFilesActivity extends PassFailButtons.ListActivity {
private final FileStatus status = new FileStatus();
- @Override
public boolean accept(File pathname) {
if (FileUtils.getFileStatus(pathname.getPath(), status, true)) {
return !status.isDirectory()
@@ -258,17 +250,18 @@ public class SuidFilesActivity extends PassFailButtons.ListActivity {
// Alert the user that nothing was found rather than showing an empty list view.
if (passed) {
- getPassButton().setEnabled(true);
+ TestResult.setPassedResult(SuidFilesActivity.this);
new AlertDialog.Builder(SuidFilesActivity.this)
.setTitle(R.string.congratulations)
.setMessage(R.string.no_suid_files)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
- @Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
+ } else {
+ TestResult.setFailedResult(SuidFilesActivity.this);
}
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/usb/UsbAccessoryTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/usb/UsbAccessoryTestActivity.java
deleted file mode 100644
index 4132807..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/usb/UsbAccessoryTestActivity.java
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * 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.verifier.usb;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.PackageManager;
-import android.content.res.Configuration;
-import android.hardware.usb.UsbAccessory;
-import android.hardware.usb.UsbManager;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.ParcelFileDescriptor;
-import android.util.Log;
-import android.view.View;
-import android.widget.ArrayAdapter;
-import android.widget.ListView;
-import android.widget.Toast;
-
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * Test for USB accessories. The test activity interacts with a cts-usb-accessory program that
- * acts as an accessory by exchanging a series of messages.
- */
-public class UsbAccessoryTestActivity extends PassFailButtons.Activity {
-
- private static final String TAG = UsbAccessoryTestActivity.class.getSimpleName();
-
- private static final int FILE_DESCRIPTOR_PROBLEM_DIALOG_ID = 1;
-
- private static final String ACTION_USB_PERMISSION =
- "com.android.cts.verifier.usb.USB_PERMISSION";
-
- private ArrayAdapter mReceivedMessagesAdapter;
- private ArrayAdapter mSentMessagesAdapter;
- private MessageHandler mHandler;
-
- private UsbManager mUsbManager;
- private PendingIntent mPermissionIntent;
- private boolean mPermissionRequestPending;
- private UsbReceiver mUsbReceiver;
-
- private ParcelFileDescriptor mFileDescriptor;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.usb_main);
- setInfoResources(R.string.usb_accessory_test, R.string.usb_accessory_test_info, -1);
- setPassFailButtonClickListeners();
-
- // Don't allow a test pass until the accessory and the Android device exchange messages...
- getPassButton().setEnabled(false);
-
- if (!hasUsbAccessorySupport()) {
- showNoUsbAccessoryDialog();
- }
-
- mReceivedMessagesAdapter = new ArrayAdapter(this, R.layout.usb_message_row);
- mSentMessagesAdapter = new ArrayAdapter(this, R.layout.usb_message_row);
- mHandler = new MessageHandler();
-
- mUsbManager = (UsbManager) getSystemService(USB_SERVICE);
- mPermissionIntent = PendingIntent.getBroadcast(this, 0,
- new Intent(ACTION_USB_PERMISSION), 0);
-
- mUsbReceiver = new UsbReceiver();
- IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
- filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
- registerReceiver(mUsbReceiver, filter);
-
- setupListViews();
- }
-
- private boolean hasUsbAccessorySupport() {
- return getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
- }
-
- private void showNoUsbAccessoryDialog() {
- new AlertDialog.Builder(this)
- .setIcon(android.R.drawable.ic_dialog_alert)
- .setTitle(R.string.usb_not_available_title)
- .setMessage(R.string.usb_not_available_message)
- .setCancelable(false)
- .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- })
- .show();
- }
-
- private void setupListViews() {
- ListView sentMessages = (ListView) findViewById(R.id.usb_sent_messages);
- ListView receivedMessages = (ListView) findViewById(R.id.usb_received_messages);
-
- View emptySentView = findViewById(R.id.usb_empty_sent_messages);
- View emptyReceivedView = findViewById(R.id.usb_empty_received_messages);
- sentMessages.setEmptyView(emptySentView);
- receivedMessages.setEmptyView(emptyReceivedView);
-
- receivedMessages.setAdapter(mReceivedMessagesAdapter);
- sentMessages.setAdapter(mSentMessagesAdapter);
- }
-
- class UsbReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (ACTION_USB_PERMISSION.equals(intent.getAction())
- || UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(intent.getAction())) {
- UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
- if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
- openAccessory(accessory);
- } else {
- Log.i(TAG, "Permission denied...");
- }
- mPermissionRequestPending = false;
- }
- }
- }
-
- private void openAccessory(UsbAccessory accessory) {
- mFileDescriptor = mUsbManager.openAccessory(accessory);
- if (mFileDescriptor != null) {
- FileDescriptor fileDescriptor = mFileDescriptor.getFileDescriptor();
- FileInputStream inputStream = new FileInputStream(fileDescriptor);
- FileOutputStream outputStream = new FileOutputStream(fileDescriptor);
- new MessageThread(inputStream, outputStream, mHandler).start();
- } else {
- showDialog(FILE_DESCRIPTOR_PROBLEM_DIALOG_ID);
- }
- }
-
- static class MessageThread extends Thread {
-
- private final InputStream mInputStream;
-
- private final OutputStream mOutputStream;
-
- private final MessageHandler mHandler;
-
- private int mNextMessageNumber = 0;
-
- MessageThread(InputStream inputStream, OutputStream outputStream, MessageHandler handler) {
- this.mInputStream = inputStream;
- this.mOutputStream = outputStream;
- this.mHandler = handler;
- }
-
- @Override
- public void run() {
- mHandler.sendEmptyMessage(MessageHandler.MESSAGE_THREAD_STARTING);
-
- try {
- // Wait a bit or else the messages can appear to quick and be confusing...
- Thread.sleep(2000);
- sendMessage();
-
- // Wait for response and send message acks...
- int numRead = 0;
- byte[] buffer = new byte[16384];
- while (numRead >= 0) {
- numRead = mInputStream.read(buffer);
- if (numRead > 0) {
- handleReceivedMessage(buffer, numRead);
- }
- }
- } catch (IOException e) {
- Log.e(TAG, "Exception while reading from input stream", e);
- mHandler.sendEmptyMessage(MessageHandler.MESSAGE_THREAD_EXCEPTION);
- } catch (InterruptedException e) {
- Log.e(TAG, "Exception while reading from input stream", e);
- mHandler.sendEmptyMessage(MessageHandler.MESSAGE_THREAD_EXCEPTION);
- }
- mHandler.sendEmptyMessage(MessageHandler.MESSAGE_THREAD_ENDING);
- }
-
- private void handleReceivedMessage(byte[] buffer, int numRead) throws IOException {
- // TODO: Check the contents of the message?
- String text = new String(buffer, 0, numRead).trim();
- mHandler.sendReceivedMessage(text);
-
- // Send back a response..
- if (mNextMessageNumber <= 10) {
- sendMessage();
- } else {
- mHandler.sendEmptyMessage(MessageHandler.TEST_PASSED);
- }
- }
-
- private void sendMessage() throws IOException {
- String text = "Message from Android device #" + mNextMessageNumber++;
- mOutputStream.write(text.getBytes());
- mHandler.sendSentMessage(text);
- }
- }
-
- class MessageHandler extends Handler {
-
- static final int RECEIVED_MESSAGE = 1;
-
- static final int SENT_MESSAGE = 2;
-
- static final int MESSAGE_THREAD_STARTING = 3;
-
- static final int MESSAGE_THREAD_EXCEPTION = 4;
-
- static final int MESSAGE_THREAD_ENDING = 5;
-
- static final int TEST_PASSED = 6;
-
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- switch (msg.what) {
- case RECEIVED_MESSAGE:
- mReceivedMessagesAdapter.add((String) msg.obj);
- break;
-
- case SENT_MESSAGE:
- mSentMessagesAdapter.add((String) msg.obj);
- break;
-
- case MESSAGE_THREAD_STARTING:
- showToast(R.string.usb_message_thread_started);
- break;
-
- case MESSAGE_THREAD_EXCEPTION:
- showToast(R.string.usb_message_thread_exception);
- break;
-
- case MESSAGE_THREAD_ENDING:
- showToast(R.string.usb_message_thread_ended);
- break;
-
- case TEST_PASSED:
- showToast(R.string.usb_test_passed);
- getPassButton().setEnabled(true);
- break;
-
- default:
- throw new IllegalArgumentException("Bad message type: " + msg.what);
- }
- }
-
- private void showToast(int messageId) {
- Toast.makeText(UsbAccessoryTestActivity.this, messageId, Toast.LENGTH_SHORT).show();
- }
-
- void sendReceivedMessage(String text) {
- Message message = Message.obtain(this, RECEIVED_MESSAGE);
- message.obj = text;
- sendMessage(message);
- }
-
- void sendSentMessage(String text) {
- Message message = Message.obtain(this, SENT_MESSAGE);
- message.obj = text;
- sendMessage(message);
- }
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- UsbAccessory[] accessories = mUsbManager.getAccessoryList();
- UsbAccessory accessory = accessories != null && accessories.length > 0
- ? accessories[0]
- : null;
- if (accessory != null) {
- if (mUsbManager.hasPermission(accessory)) {
- openAccessory(accessory);
- } else {
- if (!mPermissionRequestPending) {
- mUsbManager.requestPermission(accessory, mPermissionIntent);
- mPermissionRequestPending = true;
- }
- }
- }
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- if (mFileDescriptor != null) {
- try {
- mFileDescriptor.close();
- } catch (IOException e) {
- Log.e(TAG, "Exception while closing file descriptor", e);
- } finally {
- mFileDescriptor = null;
- }
- }
- }
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- super.onConfigurationChanged(newConfig);
- setContentView(R.layout.usb_main);
- setupListViews();
- }
-
- @Override
- public Dialog onCreateDialog(int id, Bundle args) {
- switch (id) {
- case FILE_DESCRIPTOR_PROBLEM_DIALOG_ID:
- return new AlertDialog.Builder(this)
- .setIcon(android.R.drawable.ic_dialog_alert)
- .setTitle(R.string.usb_accessory_test)
- .setMessage(R.string.usb_file_descriptor_error)
- .create();
-
- default:
- return super.onCreateDialog(id, args);
- }
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- unregisterReceiver(mUsbReceiver);
- }
-}
diff --git a/apps/cts-usb-accessory/Android.mk b/apps/cts-usb-accessory/Android.mk
deleted file mode 100644
index c4d014f..0000000
--- a/apps/cts-usb-accessory/Android.mk
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# 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.
-#
-
-# Build for Linux (desktop) host
-ifeq ($(HOST_OS),linux)
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := cts-usb-accessory.c
-
-LOCAL_MODULE := cts-usb-accessory
-
-LOCAL_C_INCLUDES += bionic/libc/kernel/common
-LOCAL_STATIC_LIBRARIES := libusbhost libcutils
-LOCAL_LDLIBS += -lpthread
-LOCAL_CFLAGS := -g -O0
-
-include $(BUILD_HOST_EXECUTABLE)
-
-endif
diff --git a/apps/cts-usb-accessory/cts-usb-accessory.c b/apps/cts-usb-accessory/cts-usb-accessory.c
deleted file mode 100644
index 4e747bb..0000000
--- a/apps/cts-usb-accessory/cts-usb-accessory.c
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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.
- */
-
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-
-struct usb_device *sDevice = NULL;
-
-static void* message_thread(void* arg) {
- int *endpoints = (int *)arg;
- int ret = 0;
- int num = 0;
- char message[50];
-
- while (sDevice && ret >= 0) {
- char buffer[16384];
- ret = usb_device_bulk_transfer(sDevice, endpoints[0], buffer, sizeof(buffer), 1000);
- if (ret < 0 && errno == ETIMEDOUT) {
- ret = 0;
- }
- if (ret > 0) {
- printf("[RECV] ");
- fwrite(buffer, 1, ret, stdout);
- printf("\n");
-
- // Respond by sending a message back
- sprintf(message, "Message from Android accessory #%d", num++);
- printf("[SENT] %s\n", message);
- fflush(stdout);
- usb_device_bulk_transfer(sDevice, endpoints[1], message, strlen(message), 1000);
- }
- }
-
- return NULL;
-}
-
-static void milli_sleep(int millis) {
- struct timespec tm;
-
- tm.tv_sec = 0;
- tm.tv_nsec = millis * 1000000;
- nanosleep(&tm, NULL);
-}
-
-static void send_string(struct usb_device *device, int index, const char* string) {
- int ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
- ACCESSORY_SEND_STRING, 0, index, (void *)string, strlen(string) + 1, 0);
-
- // some devices can't handle back-to-back requests, so delay a bit
- milli_sleep(10);
-}
-
-static int usb_device_added(const char *devname, void* client_data) {
- struct usb_descriptor_header* desc;
- struct usb_descriptor_iter iter;
- uint16_t vendorId, productId;
- int ret;
- pthread_t th;
-
- struct usb_device *device = usb_device_open(devname);
- if (!device) {
- fprintf(stderr, "usb_device_open failed\n");
- return 0;
- }
-
- vendorId = usb_device_get_vendor_id(device);
- productId = usb_device_get_product_id(device);
-
- if (!sDevice && (vendorId == 0x18D1 && (productId == 0x2D00 || productId == 0x2D01))) {
- struct usb_descriptor_header* desc;
- struct usb_descriptor_iter iter;
- struct usb_interface_descriptor *intf = NULL;
- struct usb_endpoint_descriptor *ep1 = NULL;
- struct usb_endpoint_descriptor *ep2 = NULL;
-
- printf("Found Android device in accessory mode (%x:%x)...\n",
- vendorId, productId);
- sDevice = device;
-
- usb_descriptor_iter_init(device, &iter);
- while ((desc = usb_descriptor_iter_next(&iter)) != NULL && (!intf || !ep1 || !ep2)) {
- if (desc->bDescriptorType == USB_DT_INTERFACE) {
- intf = (struct usb_interface_descriptor *)desc;
- } else if (desc->bDescriptorType == USB_DT_ENDPOINT) {
- if (ep1)
- ep2 = (struct usb_endpoint_descriptor *)desc;
- else
- ep1 = (struct usb_endpoint_descriptor *)desc;
- }
- }
-
- if (!intf) {
- fprintf(stderr, "Interface not found\n");
- exit(1);
- }
- if (!ep1 || !ep2) {
- fprintf(stderr, "Endpoints not found\n");
- exit(1);
- }
-
- if (usb_device_claim_interface(device, intf->bInterfaceNumber)) {
- fprintf(stderr, "usb_device_claim_interface failed errno: %d\n", errno);
- exit(1);
- }
-
- int endpoints[2];
- if ((ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) {
- endpoints[0] = ep1->bEndpointAddress;
- endpoints[1] = ep2->bEndpointAddress;
- } else {
- endpoints[0] = ep2->bEndpointAddress;
- endpoints[1] = ep1->bEndpointAddress;
- }
- pthread_create(&th, NULL, message_thread, (void *)endpoints);
- } else {
- printf("Found possible Android device (%x:%x) "
- "- attempting to switch to accessory mode...\n", vendorId, productId);
-
- uint16_t protocol = 0;
- ret = usb_device_control_transfer(device, USB_DIR_IN | USB_TYPE_VENDOR,
- ACCESSORY_GET_PROTOCOL, 0, 0, &protocol, sizeof(protocol), 0);
- if (ret == 2)
- printf("Device supports protocol version %d\n", protocol);
- else
- fprintf(stderr, "Failed to read protocol version\n");
-
- send_string(device, ACCESSORY_STRING_MANUFACTURER, "Android CTS");
- send_string(device, ACCESSORY_STRING_MODEL, "CTS USB Accessory");
- send_string(device, ACCESSORY_STRING_DESCRIPTION, "CTS USB Accessory");
- send_string(device, ACCESSORY_STRING_VERSION, "1.0");
- send_string(device, ACCESSORY_STRING_URI,
- "http://source.android.com/compatibility/cts-intro.html");
- send_string(device, ACCESSORY_STRING_SERIAL, "1234567890");
-
- ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
- ACCESSORY_START, 0, 0, 0, 0, 0);
- return 0;
- }
-
- if (device != sDevice)
- usb_device_close(device);
-
- return 0;
-}
-
-static int usb_device_removed(const char *devname, void* client_data) {
- if (sDevice && !strcmp(usb_device_get_name(sDevice), devname)) {
- usb_device_close(sDevice);
- sDevice = NULL;
- // exit when we are disconnected
- return 1;
- }
- return 0;
-}
-
-
-int main(int argc, char* argv[]) {
- printf("CTS USB Accessory Tester\n");
-
- struct usb_host_context* context = usb_host_init();
- if (!context) {
- fprintf(stderr, "usb_host_init failed");
- return 1;
- }
-
- // this will never return so it is safe to pass thiz directly
- usb_host_run(context, usb_device_added, usb_device_removed, NULL, NULL);
- return 0;
-}
diff --git a/development/ide/eclipse/.classpath b/development/ide/eclipse/.classpath
index a1917b3..ac56b05 100644
--- a/development/ide/eclipse/.classpath
+++ b/development/ide/eclipse/.classpath
@@ -1,7 +1,5 @@
-
-
@@ -11,24 +9,18 @@
-
-
-
-
-
-
@@ -47,11 +39,9 @@
-
-
@@ -66,8 +56,6 @@
-
-
diff --git a/tests/Android.mk b/tests/Android.mk
index 641d053..838d01d 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -18,7 +18,6 @@ include $(CLEAR_VARS)
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 9cdb13b..7eaafb3 100644
--- a/tests/AndroidManifest.xml
+++ b/tests/AndroidManifest.xml
@@ -34,8 +34,6 @@
-
-
@@ -68,7 +66,6 @@
-
@@ -83,7 +80,6 @@
-
@@ -135,14 +131,6 @@
-
-
-
-
-
-
-
@@ -326,7 +314,6 @@
@@ -950,73 +937,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/SignatureTest/Android.mk b/tests/SignatureTest/Android.mk
index 3ebab34..18c7cea 100644
--- a/tests/SignatureTest/Android.mk
+++ b/tests/SignatureTest/Android.mk
@@ -20,7 +20,7 @@ LOCAL_MODULE_TAGS := optional
# and when built explicitly put it in the data partition
LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_JAVA_LIBRARIES := android.test.runner
@@ -31,7 +31,7 @@ LOCAL_SDK_VERSION := current
# To be passed in on command line
CTS_API_VERSION ?= current
-android_api_description := $(SRC_API_DIR)/$(CTS_API_VERSION).txt
+android_api_description := $(SRC_API_DIR)/$(CTS_API_VERSION).xml
# Can't call local-intermediates-dir directly here because we have to
# include BUILD_PACAKGE first. Can't include BUILD_PACKAGE first
@@ -67,15 +67,9 @@ api_ver_file := $(api_ver_path)/api_ver_is_$(CTS_API_VERSION)
# sure the generated resources rule depend on it, we can ensure that
# the proper version of the api resource gets generated.
$(api_ver_file):
- $(hide) rm -f $(api_ver_path)/api_ver_is_*
+ @rm -f $(api_ver_path)/api_ver_is_*
$(hide) touch $@
-android_api_xml_description := $(intermediates.COMMON)/api.xml
-$(android_api_xml_description): PRIVATE_INPUT_FILE := $(android_api_description)
-$(android_api_xml_description): $(android_api_description) $(APICHECK)
- $(hide) echo "Convert api file to xml: $@"
- $(hide) $(APICHECK_COMMAND) -convert2xml $(PRIVATE_INPUT_FILE) $@
-
static_res_deps := $(call find-subdir-assets,$(LOCAL_PATH)/res)
$(copied_res_stamp): PRIVATE_PATH := $(LOCAL_PATH)
$(copied_res_stamp): PRIVATE_MODULE := $(LOCAL_MODULE)
@@ -83,11 +77,11 @@ $(copied_res_stamp): PRIVATE_RES_DIR := $(signature_res_dir)
$(copied_res_stamp): FAKE_RESOURCE_DIR := $(dir $(fake_resource_check))
$(copied_res_stamp): FAKE_RESOURCE_CHECK := $(fake_resource_check)
$(copied_res_stamp): $(foreach res,$(static_res_deps),$(LOCAL_PATH)/res/${res}) | $(ACP)
- $(hide) echo "Copy resources: $(PRIVATE_MODULE)"
- $(hide) rm -f $@
- $(hide) rm -rf $(PRIVATE_RES_DIR)
- $(hide) mkdir -p $(PRIVATE_RES_DIR)
- $(hide) if [ ! -f $(FAKE_RESOURCE_CHECK) ]; \
+ @echo "Copy resources: $(PRIVATE_MODULE)"
+ @rm -f $@
+ @rm -rf $(PRIVATE_RES_DIR)
+ @mkdir -p $(PRIVATE_RES_DIR)
+ @if [ ! -f $(FAKE_RESOURCE_CHECK) ]; \
then mkdir -p $(FAKE_RESOURCE_DIR); \
touch $(FAKE_RESOURCE_CHECK); \
fi
@@ -100,11 +94,11 @@ $(generated_res_stamp): PRIVATE_PATH := $(LOCAL_PATH)
$(generated_res_stamp): PRIVATE_MODULE := $(LOCAL_MODULE)
$(generated_res_stamp): PRIVATE_RES_DIR := $(signature_res_dir)
$(generated_res_stamp): $(api_ver_file)
-$(generated_res_stamp): $(copied_res_stamp) $(android_api_xml_description)
- $(hide) echo "Copy generated resources: $(PRIVATE_MODULE)"
- $(hide) rm -f $@
+$(generated_res_stamp): $(copied_res_stamp) $(android_api_description)
+ @echo "Copy generated resources: $(PRIVATE_MODULE)"
+ @rm -f $@
$(hide) python cts/tools/utils/android_api_description_splitter.py \
- $(android_api_xml_description) $(PRIVATE_RES_DIR) package
+ $(android_api_description) $(PRIVATE_RES_DIR) package
$(hide) touch $@
$(R_file_stamp): $(generated_res_stamp) $(copied_res_stamp)
diff --git a/tests/SignatureTest/AndroidManifest.xml b/tests/SignatureTest/AndroidManifest.xml
index 762dfae..696dc57 100644
--- a/tests/SignatureTest/AndroidManifest.xml
+++ b/tests/SignatureTest/AndroidManifest.xml
@@ -30,16 +30,10 @@
-
-
-
-
diff --git a/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java b/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java
deleted file mode 100644
index c206c9a..0000000
--- a/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * 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.
- *
- * 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 mDebugArray = new ArrayList();
-
- private HashSet 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();
- 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.
- *
- * 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/acceleration/Android.mk b/tests/acceleration/Android.mk
deleted file mode 100644
index 6e30f59..0000000
--- a/tests/acceleration/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-# 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_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_JAVA_LIBRARIES := android.test.runner
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsAccelerationTestStubs
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_PACKAGE)
diff --git a/tests/acceleration/AndroidManifest.xml b/tests/acceleration/AndroidManifest.xml
deleted file mode 100644
index f92b736..0000000
--- a/tests/acceleration/AndroidManifest.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/acceleration/res/layout/acceleration.xml b/tests/acceleration/res/layout/acceleration.xml
deleted file mode 100644
index 8dc027a..0000000
--- a/tests/acceleration/res/layout/acceleration.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/acceleration/src/android/acceleration/cts/AcceleratedView.java b/tests/acceleration/src/android/acceleration/cts/AcceleratedView.java
deleted file mode 100644
index 7d749a1..0000000
--- a/tests/acceleration/src/android/acceleration/cts/AcceleratedView.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.acceleration.cts;
-
-import android.content.Context;
-import android.graphics.Canvas;
-import android.util.AttributeSet;
-import android.view.View;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class AcceleratedView extends View {
-
- private final CountDownLatch mDrawLatch = new CountDownLatch(1);
-
- private boolean mIsHardwareAccelerated;
-
- public AcceleratedView(Context context) {
- super(context);
- }
-
- public AcceleratedView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public AcceleratedView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- synchronized (this) {
- mIsHardwareAccelerated = canvas.isHardwareAccelerated();
- }
- mDrawLatch.countDown();
- }
-
- public boolean isCanvasHardwareAccelerated() {
- try {
- if (mDrawLatch.await(1, TimeUnit.SECONDS)) {
- synchronized (this) {
- return mIsHardwareAccelerated;
- }
- } else {
- throw new IllegalStateException("View was not drawn...");
- }
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/tests/acceleration/src/android/acceleration/cts/BaseAcceleratedActivity.java b/tests/acceleration/src/android/acceleration/cts/BaseAcceleratedActivity.java
deleted file mode 100644
index 8ef6a8e..0000000
--- a/tests/acceleration/src/android/acceleration/cts/BaseAcceleratedActivity.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.acceleration.cts;
-
-import com.android.cts.acceleration.stub.R;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.View;
-
-abstract class BaseAcceleratedActivity extends Activity {
-
- private AcceleratedView mHardwareAcceleratedView;
- private AcceleratedView mSoftwareAcceleratedView;
-
- private AcceleratedView mManualHardwareAcceleratedView;
- private AcceleratedView mManualSoftwareAcceleratedView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.acceleration);
-
- mHardwareAcceleratedView = (AcceleratedView) findViewById(R.id.hardware_accelerated_view);
- mSoftwareAcceleratedView = (AcceleratedView) findViewById(R.id.software_accelerated_view);
-
- mManualHardwareAcceleratedView =
- (AcceleratedView) findViewById(R.id.manual_hardware_accelerated_view);
- mManualSoftwareAcceleratedView =
- (AcceleratedView) findViewById(R.id.manual_software_accelerated_view);
-
- mManualHardwareAcceleratedView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
- mManualSoftwareAcceleratedView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
- }
-
- public AcceleratedView getHardwareAcceleratedView() {
- return mHardwareAcceleratedView;
- }
-
- public AcceleratedView getSoftwareAcceleratedView() {
- return mSoftwareAcceleratedView;
- }
-
- public AcceleratedView getManualHardwareAcceleratedView() {
- return mManualHardwareAcceleratedView;
- }
-
- public AcceleratedView getManualSoftwareAcceleratedView() {
- return mManualSoftwareAcceleratedView;
- }
-}
diff --git a/tests/acceleration/src/android/acceleration/cts/HardwareAcceleratedActivity.java b/tests/acceleration/src/android/acceleration/cts/HardwareAcceleratedActivity.java
deleted file mode 100644
index bb26202..0000000
--- a/tests/acceleration/src/android/acceleration/cts/HardwareAcceleratedActivity.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * 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.acceleration.cts;
-
-public class HardwareAcceleratedActivity extends BaseAcceleratedActivity {
-}
diff --git a/tests/acceleration/src/android/acceleration/cts/SoftwareAcceleratedActivity.java b/tests/acceleration/src/android/acceleration/cts/SoftwareAcceleratedActivity.java
deleted file mode 100644
index 0a6a3df..0000000
--- a/tests/acceleration/src/android/acceleration/cts/SoftwareAcceleratedActivity.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * 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.acceleration.cts;
-
-public class SoftwareAcceleratedActivity extends BaseAcceleratedActivity {
-}
diff --git a/tests/acceleration/src/android/acceleration/cts/WindowFlagHardwareAcceleratedActivity.java b/tests/acceleration/src/android/acceleration/cts/WindowFlagHardwareAcceleratedActivity.java
deleted file mode 100644
index 9def8b7..0000000
--- a/tests/acceleration/src/android/acceleration/cts/WindowFlagHardwareAcceleratedActivity.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.acceleration.cts;
-
-import android.os.Bundle;
-import android.view.WindowManager;
-
-public class WindowFlagHardwareAcceleratedActivity extends BaseAcceleratedActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
- WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
- }
-}
diff --git a/tests/accessibilityservice/AndroidManifest.xml b/tests/accessibilityservice/AndroidManifest.xml
index 81758f6..29164bc 100644
--- a/tests/accessibilityservice/AndroidManifest.xml
+++ b/tests/accessibilityservice/AndroidManifest.xml
@@ -28,8 +28,6 @@
- Delegating Accessibility Service
+
+ End-to-end test
+
+
+ Blah
+
+
+ Blah blah
+
+
+ Click me
+
+
+ First list item
+
+
+ Second list item
+
+
+ Alert title
+
+
+ Alert message
+
+
+ Notification message
+
diff --git a/tests/accessibilityservice/res/xml/accessibilityservice.xml b/tests/accessibilityservice/res/xml/accessibilityservice.xml
deleted file mode 100644
index 31a3f71..0000000
--- a/tests/accessibilityservice/res/xml/accessibilityservice.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/IAccessibilityServiceDelegate.aidl b/tests/accessibilityservice/src/android/accessibilityservice/IAccessibilityServiceDelegate.aidl
index 868bd72..b5ebf19 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/IAccessibilityServiceDelegate.aidl
+++ b/tests/accessibilityservice/src/android/accessibilityservice/IAccessibilityServiceDelegate.aidl
@@ -20,7 +20,7 @@ import android.view.accessibility.AccessibilityEvent;
/**
* Interface for interacting with the accessibility service mock.
*/
-oneway interface IAccessibilityServiceDelegate {
+interface IAccessibilityServiceDelegate {
/**
* Delegate an {@link android.view.accessibility.AccessibilityEvent}.
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/delegate/DelegatingAccessibilityService.java b/tests/accessibilityservice/src/android/accessibilityservice/delegate/DelegatingAccessibilityService.java
index 5680b7c..37a9c54 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/delegate/DelegatingAccessibilityService.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/delegate/DelegatingAccessibilityService.java
@@ -17,6 +17,7 @@
package android.accessibilityservice.delegate;
import android.accessibilityservice.AccessibilityService;
+import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.IAccessibilityServiceDelegate;
import android.accessibilityservice.IAccessibilityServiceDelegateConnection;
import android.app.Service;
@@ -63,6 +64,14 @@ public class DelegatingAccessibilityService extends AccessibilityService {
@Override
protected void onServiceConnected() {
+ AccessibilityServiceInfo info = new AccessibilityServiceInfo();
+ info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
+ info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
+ info.packageNames = new String[] {
+ "com.android.cts.accessibilityservice"
+ };
+ setServiceInfo(info);
+
// the service is ready to be used only
// after the system has bound to it
sServiceDelegate = this;
diff --git a/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java b/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java
index 106f1af..f162edc 100644
--- a/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java
+++ b/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java
@@ -323,7 +323,7 @@ public class AppSecurityTests extends DeviceTestCase {
private boolean mAllTestsPassed = true;
private String mTestRunErrorMessage = null;
- public void testEnded(TestIdentifier test, Map metrics) {
+ public void testEnded(TestIdentifier test, Map metrics) {
// ignore
}
diff --git a/tests/appsecurity-tests/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java b/tests/appsecurity-tests/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java
index 1de6464..d77a872 100644
--- a/tests/appsecurity-tests/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java
+++ b/tests/appsecurity-tests/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java
@@ -16,17 +16,12 @@
package com.android.cts.appwithdata;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.test.AndroidTestCase;
-
import java.io.FileOutputStream;
import java.io.IOException;
+import android.content.Context;
+import android.test.AndroidTestCase;
+
/**
* Test that will create private app data.
*
@@ -40,14 +35,6 @@ public class CreatePrivateDataTest extends AndroidTestCase {
*/
private static final String PRIVATE_FILE_NAME = "private_file.txt";
- private static final String PREFERENCES_FILE_NAME = "preferences";
- private static final String PREFERENCE_KEY = "preference_key";
- private static final String PREFERENCE_VALUE = "preference_value";
-
- static final String DB_TABLE_NAME = "test_table";
- static final String DB_COLUMN = "test_column";
- static final String DB_VALUE = "test_value";
-
/**
* Creates a file private to this app
* @throws IOException if any error occurred when creating the file
@@ -58,39 +45,6 @@ public class CreatePrivateDataTest extends AndroidTestCase {
outputStream.write("file contents".getBytes());
outputStream.close();
assertTrue(getContext().getFileStreamPath(PRIVATE_FILE_NAME).exists());
-
- writeToPreferences();
- writeToDatabase();
- }
-
- private void writeToPreferences() {
- SharedPreferences prefs = mContext.getSharedPreferences(PREFERENCES_FILE_NAME, 0);
- SharedPreferences.Editor editor = prefs.edit();
- editor.putString(PREFERENCE_KEY, PREFERENCE_VALUE);
- editor.commit();
- assertEquals(PREFERENCE_VALUE, prefs.getString(PREFERENCE_KEY, null));
- }
-
- private void writeToDatabase() {
- SQLiteDatabase db = null;
- Cursor cursor = null;
- try {
- db = new TestDatabaseOpenHelper(mContext).getWritableDatabase();
- ContentValues values = new ContentValues(1);
- values.put(DB_COLUMN, DB_VALUE);
- assertTrue(db.insert(DB_TABLE_NAME, null, values) != -1);
-
- cursor = db.query(DB_TABLE_NAME, new String[] {DB_COLUMN},
- null, null, null, null, null);
- assertEquals(1, cursor.getCount());
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- if (db != null) {
- db.close();
- }
- }
}
/**
@@ -99,53 +53,5 @@ public class CreatePrivateDataTest extends AndroidTestCase {
*/
public void testEnsurePrivateDataNotExist() throws IOException {
assertFalse(getContext().getFileStreamPath(PRIVATE_FILE_NAME).exists());
-
- assertPreferencesDataDoesNotExist();
- assertDatabaseDataDoesNotExist();
- }
-
- private void assertPreferencesDataDoesNotExist() {
- SharedPreferences prefs = mContext.getSharedPreferences(PREFERENCES_FILE_NAME, 0);
- assertNull(prefs.getString(PREFERENCE_KEY, null));
- }
-
- private void assertDatabaseDataDoesNotExist() {
- SQLiteDatabase db = null;
- Cursor cursor = null;
- try {
- db = new TestDatabaseOpenHelper(mContext).getWritableDatabase();
- cursor = db.query(DB_TABLE_NAME, new String[] {DB_COLUMN},
- null, null, null, null, null);
- assertEquals(0, cursor.getCount());
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- if (db != null) {
- db.close();
- }
- }
- }
-
- static class TestDatabaseOpenHelper extends SQLiteOpenHelper {
-
- static final String _ID = "_id";
-
- public TestDatabaseOpenHelper(Context context) {
- super(context, "test.db", null, 1337);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE " + DB_TABLE_NAME + " ("
- + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
- + DB_COLUMN + " TEXT);");
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_NAME);
- onCreate(db);
- }
}
}
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
index de71966..683ec9e 100644
--- a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
@@ -31,8 +31,6 @@
-
-
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 31a3f47..8c14575 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,19 +1,3 @@
-/*
- * 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
deleted file mode 100644
index ea06d8c..0000000
--- a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java
+++ /dev/null
@@ -1,41 +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.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
deleted file mode 100644
index 989e24b..0000000
--- a/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.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/noiseandchirps b/tests/assets/noiseandchirps
deleted file mode 100644
index a819efc..0000000
Binary files a/tests/assets/noiseandchirps and /dev/null differ
diff --git a/tests/assets/noiseandchirps.wrong b/tests/assets/noiseandchirps.wrong
deleted file mode 100644
index a819efc..0000000
Binary files a/tests/assets/noiseandchirps.wrong and /dev/null differ
diff --git a/tests/assets/sphere.a3d b/tests/assets/sphere.a3d
deleted file mode 100644
index 3d78b01..0000000
Binary files a/tests/assets/sphere.a3d and /dev/null differ
diff --git a/tests/assets/webkit/jsform.html b/tests/assets/webkit/jsform.html
index 1781194..ddf01f8 100644
--- a/tests/assets/webkit/jsform.html
+++ b/tests/assets/webkit/jsform.html
@@ -24,7 +24,7 @@
}
}
-
+
javascript form test
- * @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 a9a3293..89918a1 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.TestLevel;
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,6 +37,9 @@ public class SQLiteProgramTest extends AndroidTestCase {
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();
@@ -54,6 +57,79 @@ public class SQLiteProgramTest extends AndroidTestCase {
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,
@@ -119,36 +195,39 @@ public class SQLiteProgramTest extends AndroidTestCase {
}
statement.close();
- Cursor cursor = null;
+ statement = mDatabase.compileStatement("SELECT text1 FROM test;");
try {
- cursor = mDatabase.query("test", new String[]{"text1"}, "where text1='a'",
- new String[]{"foo"}, null, null, null);
+ statement.bindString(1, "foo");
fail("Should throw exception (no value to bind)");
} catch (SQLiteException expected) {
// expected
- } finally {
- if (cursor != null) {
- cursor.close();
- }
+ }
+
+ 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
+ }
+ try {
+ statement.bindLong(-1, 30);
+ fail("Should throw exception (index is negative)");
+ } catch (SQLiteException expected) {
+ // expected
}
try {
- cursor = mDatabase.query("test", new String[]{"text1"}, "where text1='a'",
- new String[]{"foo", "bar"}, null, null, null);
+ statement.bindDouble(3, 589.0);
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(
@@ -224,4 +303,64 @@ public class SQLiteProgramTest extends AndroidTestCase {
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 b568b8c..ec6b79a 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
@@ -21,35 +21,19 @@ import dalvik.annotation.TestTargetClass;
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;
@@ -76,62 +60,40 @@ public class SQLiteStatementTest extends AndroidTestCase {
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 = "executeUpdateDelete",
+ method = "execute",
args = {}
)
public void testExecute() {
- mDatabase.disableWriteAheadLogging();
populateDefaultTable();
- assertEquals(0, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
+ Cursor c = mDatabase.query("test", null, null, null, null, null, null);
+ assertEquals(0, c.getCount());
+
+ // 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));
-
- // 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));
-
- // 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");
+ c = mDatabase.query("test", null, null, null, null, null, null);
+ assertEquals(1, c.getCount());
+
+ c.moveToFirst();
+ assertEquals(STRING1, c.getString(c.getColumnIndex("data")));
+
+ // invalid SQL statement
+ statement = mDatabase.compileStatement(
+ "SELECT * FROM test WHERE data=\"" + STRING1 + "\"");
try {
- statement2.executeUpdateDelete();
- fail("exception expected");
+ statement.execute();
+ fail("There should be a SQLException thrown out.");
} catch (SQLException e) {
- // expected
- } finally {
- statement2.close();
+ // expected.
}
+
+ c.deactivate();
+ statement.close();
}
@TestTargets({
@@ -156,33 +118,25 @@ public class SQLiteStatementTest extends AndroidTestCase {
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();
- // if the sql statement is something that causes rows of data to
- // be returned, executeInsert() throws an exception
+ // invalid SQL statement
statement = mDatabase.compileStatement(
"SELECT * FROM test WHERE data=\"" + STRING2 + "\"");
try {
statement.executeInsert();
- fail("exception expected");
+ fail("There should be a SQLException thrown out.");
} catch (SQLException e) {
- // expected
- } finally {
- statement.close();
-
+ // expected.
}
+
+ c.deactivate();
+ statement.close();
}
@TestTargetNew(
@@ -242,177 +196,4 @@ public class SQLiteStatementTest extends AndroidTestCase {
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/dpi/src/android/dpi/cts/ConfigurationTest.java b/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
index 316933d..624f35a 100644
--- a/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
+++ b/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
@@ -17,15 +17,11 @@
package android.dpi.cts;
import android.content.Context;
-import android.content.res.Configuration;
import android.test.AndroidTestCase;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
-import java.util.HashSet;
-import java.util.Set;
-
/**
* Test for verifying a device's screen configuration.
*/
@@ -33,7 +29,7 @@ public class ConfigurationTest extends AndroidTestCase {
public void testScreenConfiguration() {
WindowManager windowManager =
- (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
+ (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
@@ -49,48 +45,9 @@ public class ConfigurationTest extends AndroidTestCase {
int max = Math.max(metrics.widthPixels, metrics.heightPixels);
int min = Math.min(metrics.widthPixels, metrics.heightPixels);
- double aspectRatio = (double) max / min;
- assertTrue("Aspect ratio must be between 1.333 and 1.86. It was " + aspectRatio,
- aspectRatio >= 1.333 && aspectRatio <= 1.86);
-
- Set allowedDensities = new HashSet();
- allowedDensities.add(DisplayMetrics.DENSITY_LOW);
- allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM);
- allowedDensities.add(DisplayMetrics.DENSITY_TV);
- allowedDensities.add(DisplayMetrics.DENSITY_HIGH);
- allowedDensities.add(DisplayMetrics.DENSITY_XHIGH);
- assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: "
- + allowedDensities, allowedDensities.contains(metrics.densityDpi));
-
- assertEquals(metrics.density,
- (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT,
- 0.5f / DisplayMetrics.DENSITY_DEFAULT);
-
- Configuration mConfig = mContext.getResources().getConfiguration();
- int screenLayout = mConfig.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
- int screenLayoutLong = mConfig.screenLayout & Configuration.SCREENLAYOUT_LONG_MASK;
-
- int longSize = (int) (max / metrics.density);
- int shortSize = (int) (min / metrics.density);
-
- // Logic copied from WindowManagerService...
- if (longSize < 470) {
- assertEquals(Configuration.SCREENLAYOUT_SIZE_SMALL, screenLayout);
- assertEquals(Configuration.SCREENLAYOUT_LONG_NO, screenLayoutLong);
- } else {
- if (longSize >= 960 && shortSize >= 720) {
- assertEquals(Configuration.SCREENLAYOUT_SIZE_XLARGE, screenLayout);
- } else if (longSize >= 640 && shortSize >= 480) {
- assertEquals(Configuration.SCREENLAYOUT_SIZE_LARGE, screenLayout);
- } else {
- assertEquals(Configuration.SCREENLAYOUT_SIZE_NORMAL, screenLayout);
- }
-
- if (((longSize * 3) / 5) >= (shortSize - 1)) {
- assertEquals(Configuration.SCREENLAYOUT_LONG_YES, screenLayoutLong);
- } else {
- assertEquals(Configuration.SCREENLAYOUT_LONG_NO, screenLayoutLong);
- }
- }
+ boolean format16x9 = Math.floor(max * 9.0d / 16.0d) <= min;
+ boolean format4x3 = Math.ceil(max * 3.0d / 4.0d) >= min;
+ assertTrue("Aspect ratio must be between 4:3 and 16:9. It was " + max + ":" + min,
+ format4x3 && format16x9);
}
}
diff --git a/tests/tests/drm/Android.mk b/tests/tests/drm/Android.mk
deleted file mode 100644
index 61e1f10..0000000
--- a/tests/tests/drm/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-# 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
deleted file mode 100644
index fe515f3..0000000
--- a/tests/tests/drm/AndroidManifest.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/tests/drm/README b/tests/tests/drm/README
deleted file mode 100644
index dd0ef17..0000000
--- a/tests/tests/drm/README
+++ /dev/null
@@ -1,6 +0,0 @@
-- 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
deleted file mode 100644
index 736c0ad..0000000
--- a/tests/tests/drm/src/android/drm/cts/Config.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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 getInfoOfRegistration();
- HashMap getInfoOfUnregistration();
- HashMap getInfoOfRightsAcquisition();
-}
diff --git a/tests/tests/drm/src/android/drm/cts/ConfigFactory.java b/tests/tests/drm/src/android/drm/cts/ConfigFactory.java
deleted file mode 100644
index 643bb67..0000000
--- a/tests/tests/drm/src/android/drm/cts/ConfigFactory.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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
deleted file mode 100644
index 631446c..0000000
--- a/tests/tests/drm/src/android/drm/cts/DRMTest.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * 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.io.File;
-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 mConfigs = new ArrayList();
- 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 testIsDrmDirectoryExist() {
- assertTrue("/data/drm/ does not exist", new File("/data/drm/").exists());
- }
-
- 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 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 {
- if (drmInfo == null) {
- return;
- }
-
- 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
deleted file mode 100644
index e67ff03..0000000
--- a/tests/tests/drm/src/android/drm/cts/configs/FwdLockConfig.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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 getInfoOfRegistration() {
- return sInfoOfRegistration;
- }
- public HashMap getInfoOfUnregistration() {
- return sInfoOfUnregistration;
- }
- public HashMap getInfoOfRightsAcquisition(){
- return sInfoOfRightsAcquisition;
- }
-
- private static HashMap sInfoOfRegistration = new HashMap();
- private static HashMap sInfoOfUnregistration = new HashMap();
- private static HashMap sInfoOfRightsAcquisition =
- new HashMap();
-
- 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
deleted file mode 100644
index 7310825..0000000
--- a/tests/tests/drm/src/android/drm/cts/configs/PassthruConfig.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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 getInfoOfRegistration() {
- return sInfoOfRegistration;
- }
- public HashMap getInfoOfUnregistration() {
- return sInfoOfUnregistration;
- }
- public HashMap getInfoOfRightsAcquisition(){
- return sInfoOfRightsAcquisition;
- }
-
- private static HashMap sInfoOfRegistration = new HashMap();
- private static HashMap sInfoOfUnregistration = new HashMap();
- private static HashMap sInfoOfRightsAcquisition = new HashMap();
-
- 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/BitmapFactoryTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
old mode 100755
new mode 100644
index 73a712b..4c6259c
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
@@ -25,24 +25,18 @@ import dalvik.annotation.TestTargetNew;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
-import android.graphics.Color;
import android.graphics.Rect;
-import android.graphics.Bitmap.CompressFormat;
-import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.os.ParcelFileDescriptor;
import android.test.InstrumentationTestCase;
import android.util.DisplayMetrics;
-import android.util.TypedValue;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
@TestTargetClass(BitmapFactory.class)
public class BitmapFactoryTest extends InstrumentationTestCase {
@@ -57,25 +51,6 @@ public class BitmapFactoryTest extends InstrumentationTestCase {
private int mDefaultDensity;
private int mTargetDensity;
- // The test images, including baseline JPEG, a PNG, a GIF, a BMP AND a WEBP.
- private static int[] RES_IDS = new int[] {
- R.drawable.baseline_jpeg, R.drawable.png_test, R.drawable.gif_test,
- R.drawable.bmp_test, R.drawable.webp_test
- };
- private static String[] NAMES_TEMP_FILES = new String[] {
- "baseline_temp.jpg", "png_temp.png", "gif_temp.gif",
- "bmp_temp.bmp", "webp_temp.webp"
- };
-
- // The width and height of the above image.
- private static int WIDTHS[] = new int[] { 1280, 640, 320, 320, 640 };
- private static int HEIGHTS[] = new int[] { 960, 480, 240, 240, 480 };
-
- // Configurations for BitmapFactory.Options
- private static Config[] COLOR_CONFIGS = new Config[] {Config.ARGB_8888, Config.RGB_565,
- Config.ARGB_4444};
- private static int[] COLOR_TOLS = new int[] {16, 49, 576};
-
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -132,24 +107,6 @@ public class BitmapFactoryTest extends InstrumentationTestCase {
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "decodeResourceStream",
- args = {android.content.res.Resources.class, android.util.TypedValue.class,
- java.io.InputStream.class, android.graphics.Rect.class,
- android.graphics.BitmapFactory.Options.class}
- )
- public void testDecodeResourceStream() {
- InputStream is = obtainInputStream();
- Rect r = new Rect(1, 1, 1, 1);
- TypedValue value = new TypedValue();
- Bitmap b = BitmapFactory.decodeResourceStream(mRes, value, is, r, mOpt1);
- assertNotNull(b);
- // Test the bitmap size
- assertEquals(START_HEIGHT, b.getHeight());
- assertEquals(START_WIDTH, b.getWidth());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "decodeByteArray",
args = {byte[].class, int.class, int.class, android.graphics.BitmapFactory.Options.class}
)
@@ -212,62 +169,12 @@ public class BitmapFactoryTest extends InstrumentationTestCase {
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "decodeStream",
- args = {java.io.InputStream.class}
- )
- public void testDecodeStream3() throws IOException {
- for (int i = 0; i < RES_IDS.length; ++i) {
- InputStream is = obtainInputStream(RES_IDS[i]);
- Bitmap b = BitmapFactory.decodeStream(is);
- assertNotNull(b);
- // Test the bitmap size
- assertEquals(WIDTHS[i], b.getWidth());
- assertEquals(HEIGHTS[i], b.getHeight());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "decodeStream",
- args = {java.io.InputStream.class}
- )
- public void testDecodeStream4() throws IOException {
- BitmapFactory.Options options = new BitmapFactory.Options();
- for (int k = 0; k < COLOR_CONFIGS.length; ++k) {
- options.inPreferredConfig = COLOR_CONFIGS[k];
-
- // Decode the PNG & WebP test images. The WebP test image has been encoded from PNG test
- // image and should have same similar (within some error-tolerance) Bitmap data.
- InputStream iStreamPng = obtainInputStream(R.drawable.png_test);
- Bitmap bPng = BitmapFactory.decodeStream(iStreamPng, null, options);
- assertNotNull(bPng);
- assertEquals(bPng.getConfig(), COLOR_CONFIGS[k]);
-
- InputStream iStreamWebp1 = obtainInputStream(R.drawable.webp_test);
- Bitmap bWebp1 = BitmapFactory.decodeStream(iStreamWebp1, null, options);
- assertNotNull(bWebp1);
- compareBitmaps(bPng, bWebp1, COLOR_TOLS[k], true);
-
- // Compress the PNG image to WebP format (Quality=90) and decode it back.
- // This will test end-to-end WebP encoding and decoding.
- ByteArrayOutputStream oStreamWebp = new ByteArrayOutputStream();
- assertTrue(bPng.compress(CompressFormat.WEBP, 90, oStreamWebp));
- InputStream iStreamWebp2 = new ByteArrayInputStream(oStreamWebp.toByteArray());
- Bitmap bWebp2 = BitmapFactory.decodeStream(iStreamWebp2, null, options);
- assertNotNull(bWebp2);
- compareBitmaps(bPng, bWebp2, COLOR_TOLS[k], true);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "decodeFileDescriptor",
args = {java.io.FileDescriptor.class, android.graphics.Rect.class,
android.graphics.BitmapFactory.Options.class}
)
public void testDecodeFileDescriptor1() throws IOException {
- ParcelFileDescriptor pfd = obtainParcelDescriptor(obtainPath());
- FileDescriptor input = pfd.getFileDescriptor();
+ FileDescriptor input = obtainDescriptor(obtainPath());
Rect r = new Rect(1, 1, 1, 1);
Bitmap b = BitmapFactory.decodeFileDescriptor(input, r, mOpt1);
assertNotNull(b);
@@ -284,8 +191,7 @@ public class BitmapFactoryTest extends InstrumentationTestCase {
args = {java.io.FileDescriptor.class}
)
public void testDecodeFileDescriptor2() throws IOException {
- ParcelFileDescriptor pfd = obtainParcelDescriptor(obtainPath());
- FileDescriptor input = pfd.getFileDescriptor();
+ FileDescriptor input = obtainDescriptor(obtainPath());
Bitmap b = BitmapFactory.decodeFileDescriptor(input);
assertNotNull(b);
// Test the bitmap size
@@ -334,15 +240,10 @@ public class BitmapFactoryTest extends InstrumentationTestCase {
return mRes.openRawResource(R.drawable.start);
}
- private InputStream obtainInputStream(int resId) {
- return mRes.openRawResource(resId);
- }
-
- private ParcelFileDescriptor obtainParcelDescriptor(String path)
- throws IOException {
- File file = new File(path);
- return(ParcelFileDescriptor.open(file,
- ParcelFileDescriptor.MODE_READ_ONLY));
+ private FileDescriptor obtainDescriptor(String path) throws IOException {
+ File file = new File(path);
+ return(ParcelFileDescriptor.open(file,
+ ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor());
}
private String obtainPath() throws IOException {
@@ -365,48 +266,4 @@ public class BitmapFactoryTest extends InstrumentationTestCase {
fOutput.close();
return (file.getPath());
}
-
- // Compare expected to actual to see if their diff is less then mseMargin.
- // lessThanMargin is to indicate whether we expect the mean square error
- // to be "less than" or "no less than".
- private void compareBitmaps(Bitmap expected, Bitmap actual,
- int mseMargin, boolean lessThanMargin) {
- final int width = expected.getWidth();
- final int height = expected.getHeight();
-
- assertEquals("mismatching widths", width, actual.getWidth());
- assertEquals("mismatching heights", height, actual.getHeight());
- assertEquals("mismatching configs", expected.getConfig(),
- actual.getConfig());
-
- double mse = 0;
- int[] expectedColors = new int [width * height];
- int[] actualColors = new int [width * height];
-
- expected.getPixels(expectedColors, 0, width, 0, 0, width, height);
- actual.getPixels(actualColors, 0, width, 0, 0, width, height);
-
- for (int row = 0; row < height; ++row) {
- for (int col = 0; col < width; ++col) {
- int idx = row * width + col;
- mse += distance(expectedColors[idx], actualColors[idx]);
- }
- }
- mse /= width * height;
-
- if (lessThanMargin) {
- assertTrue("MSE too large for normal case: " + mse,
- mse <= mseMargin);
- } else {
- assertFalse("MSE too small for abnormal case: " + mse,
- mse <= mseMargin);
- }
- }
-
- private double distance(int expect, int actual) {
- final int r = Color.red(actual) - Color.red(expect);
- final int g = Color.green(actual) - Color.green(expect);
- final int b = Color.blue(actual) - Color.blue(expect);
- return r * r + g * g + b * b;
- }
}
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
old mode 100755
new mode 100644
index 93d8bd6..e1ba12a
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
@@ -34,7 +34,6 @@ import com.android.cts.stub.R;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -53,28 +52,27 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
private Resources mRes;
// The test images, including baseline JPEGs and progressive JPEGs, a PNG,
- // a WEBP, a GIF and a BMP.
+ // a GIF and a BMP.
private static int[] RES_IDS = new int[] {
R.drawable.baseline_jpeg, R.drawable.progressive_jpeg,
R.drawable.baseline_restart_jpeg,
R.drawable.progressive_restart_jpeg,
- R.drawable.png_test, R.drawable.webp_test,
- R.drawable.gif_test, R.drawable.bmp_test
+ R.drawable.png_test, R.drawable.gif_test, R.drawable.bmp_test
};
private static String[] NAMES_TEMP_FILES = new String[] {
- "baseline_temp.jpg", "progressive_temp.jpg", "baseline_restart_temp.jpg",
- "progressive_restart_temp.jpg", "png_temp.png", "webp_temp.webp",
- "gif_temp.gif", "bmp_temp.bmp"
+ "baseline_temp.jpg", "progressive_temp.jpg", "baseline_restart_temp.jpg"
+ , "progressive_restart_temp.jpg", "png_temp.png", "gif_temp.gif",
+ "bmp_temp.bmp"
};
// The width and height of the above image.
// -1 denotes that the image format is not supported by BitmapRegionDecoder
private static int WIDTHS[] = new int[] {
- 1280, 1280, 1280, 1280, 640, 640, -1, -1};
- private static int HEIGHTS[] = new int[] {960, 960, 960, 960, 480, 480, -1, -1};
+ 1280, 1280, 1280, 1280, 640, -1, -1};
+ private static int HEIGHTS[] = new int[] {960, 960, 960, 960, 480, -1, -1};
// The number of test images, format of which is supported by BitmapRegionDecoder
- private static int NUM_TEST_IMAGES = 6;
+ private static int NUM_TEST_IMAGES = 5;
private static int TILE_SIZE = 256;
@@ -92,9 +90,6 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
// square error of 3 * (1 * 1) among the RGB values.
private int mMseMargin = 3 * (1 * 1);
- // MSE margin for WebP Region-Decoding for 'Config.RGB_565' is little bigger.
- private int mMseMarginWebPConfigRgb565 = 5;
-
@Override
protected void setUp() throws Exception {
@@ -162,8 +157,7 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
public void testNewInstanceStringAndFileDescriptor() throws IOException {
for (int i = 0; i < RES_IDS.length; ++i) {
String filepath = obtainPath(i);
- ParcelFileDescriptor pfd = obtainParcelDescriptor(filepath);
- FileDescriptor fd = pfd.getFileDescriptor();
+ FileDescriptor fd = obtainDescriptor(filepath);
try {
BitmapRegionDecoder decoder1 =
BitmapRegionDecoder.newInstance(filepath, false);
@@ -199,12 +193,7 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
InputStream is2 = obtainInputStream(RES_IDS[i]);
Bitmap wholeImage = BitmapFactory.decodeStream(is2, null, opts);
- if (RES_IDS[i] == R.drawable.webp_test && COLOR_CONFIGS[k] == Config.RGB_565) {
- compareRegionByRegion(decoder, opts, mMseMarginWebPConfigRgb565,
- wholeImage);
- } else {
- compareRegionByRegion(decoder, opts, mMseMargin, wholeImage);
- }
+ compareRegionByRegion(decoder, opts, wholeImage);
wholeImage.recycle();
}
}
@@ -230,12 +219,7 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
Bitmap wholeImage = BitmapFactory.decodeByteArray(imageData,
0, imageData.length, opts);
- if (RES_IDS[i] == R.drawable.webp_test && COLOR_CONFIGS[k] == Config.RGB_565) {
- compareRegionByRegion(decoder, opts, mMseMarginWebPConfigRgb565,
- wholeImage);
- } else {
- compareRegionByRegion(decoder, opts, mMseMargin, wholeImage);
- }
+ compareRegionByRegion(decoder, opts, wholeImage);
wholeImage.recycle();
}
}
@@ -259,47 +243,27 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
BitmapRegionDecoder decoder =
BitmapRegionDecoder.newInstance(filepath, false);
Bitmap wholeImage = BitmapFactory.decodeFile(filepath, opts);
- if (RES_IDS[i] == R.drawable.webp_test && COLOR_CONFIGS[k] == Config.RGB_565) {
- compareRegionByRegion(decoder, opts, mMseMarginWebPConfigRgb565,
- wholeImage);
- } else {
- compareRegionByRegion(decoder, opts, mMseMargin, wholeImage);
- }
-
- ParcelFileDescriptor pfd1 = obtainParcelDescriptor(filepath);
- FileDescriptor fd1 = pfd1.getFileDescriptor();
+ compareRegionByRegion(decoder, opts, wholeImage);
+
+ FileDescriptor fd1 = obtainDescriptor(filepath);
decoder = BitmapRegionDecoder.newInstance(fd1, false);
- ParcelFileDescriptor pfd2 = obtainParcelDescriptor(filepath);
- FileDescriptor fd2 = pfd2.getFileDescriptor();
- if (RES_IDS[i] == R.drawable.webp_test && COLOR_CONFIGS[k] == Config.RGB_565) {
- compareRegionByRegion(decoder, opts, mMseMarginWebPConfigRgb565,
- wholeImage);
- } else {
- compareRegionByRegion(decoder, opts, mMseMargin, wholeImage);
- }
+ FileDescriptor fd2 = obtainDescriptor(filepath);
+ compareRegionByRegion(decoder, opts, wholeImage);
wholeImage.recycle();
}
}
}
}
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "recycle",
- args = {}
- ),
- @TestTargetNew(
+ @TestTargetNew(
level = TestLevel.COMPLETE,
- method = "isRecycled",
+ method = "recycle",
args = {}
- )
- })
+ )
public void testRecycle() throws IOException {
InputStream is = obtainInputStream(RES_IDS[0]);
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
decoder.recycle();
- assertTrue(decoder.isRecycled());
try {
decoder.getWidth();
fail("Should throw an exception!");
@@ -322,7 +286,7 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
}
private void compareRegionByRegion(BitmapRegionDecoder decoder,
- Options opts, int mseMargin, Bitmap wholeImage) {
+ Options opts, Bitmap wholeImage) {
int width = decoder.getWidth();
int height = decoder.getHeight();
Rect rect = new Rect(0, 0, width, height);
@@ -342,7 +306,7 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
Rect rect2 = new Rect(left, top, left + actual.getWidth(),
top + actual.getHeight());
expected = cropBitmap(wholeImage, rect2);
- compareBitmaps(expected, actual, mseMargin, true);
+ compareBitmaps(expected, actual, mMseMargin, true);
actual.recycle();
expected.recycle();
}
@@ -393,14 +357,12 @@ public class BitmapRegionDecoderTest extends InstrumentationTestCase {
return (file.getPath());
}
- private ParcelFileDescriptor obtainParcelDescriptor(String path)
- throws IOException {
+ private FileDescriptor obtainDescriptor(String path) throws IOException {
File file = new File(path);
return(ParcelFileDescriptor.open(file,
- ParcelFileDescriptor.MODE_READ_ONLY));
+ ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor());
}
-
// Compare expected to actual to see if their diff is less then mseMargin.
// lessThanMargin is to indicate whether we expect the diff to be
// "less than" or "no less than".
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
index f8d3ee9..7287834 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
@@ -25,7 +25,6 @@ import dalvik.annotation.TestTargets;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
@@ -33,7 +32,6 @@ import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.os.Parcel;
import android.test.AndroidTestCase;
-import android.util.DisplayMetrics;
import android.widget.cts.WidgetTestUtils;
import java.io.ByteArrayOutputStream;
@@ -790,98 +788,6 @@ public class BitmapTest extends AndroidTestCase {
mBitmap.equals(Bitmap.CREATOR.createFromParcel(p));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getScaledHeight",
- args = {int.class}
- )
- public void testGetScaledHeight1() {
- int dummyDensity = 5;
- Bitmap ret = Bitmap.createBitmap(100, 200, Config.RGB_565);
- int scaledHeight = scaleFromDensity(ret.getHeight(), ret.getDensity(), dummyDensity);
- assertNotNull(ret);
- assertEquals(scaledHeight, ret.getScaledHeight(dummyDensity));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getScaledHeight",
- args = {android.util.DisplayMetrics.class}
- )
- public void testGetScaledHeight2() {
- Bitmap ret = Bitmap.createBitmap(100, 200, Config.RGB_565);
- DisplayMetrics metrics = new DisplayMetrics();
- metrics = getContext().getResources().getDisplayMetrics();
- int scaledHeight = scaleFromDensity(ret.getHeight(), ret.getDensity(), metrics.densityDpi);
- assertEquals(scaledHeight, ret.getScaledHeight(metrics));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getScaledHeight",
- args = {android.graphics.Canvas.class}
- )
- public void testGetScaledHeight3() {
- Bitmap ret = Bitmap.createBitmap(100, 200, Config.RGB_565);
- Bitmap mMutableBitmap = Bitmap.createBitmap(100, 200, Config.ARGB_8888);
- Canvas mCanvas = new Canvas(mMutableBitmap);
- // set Density
- mCanvas.setDensity(DisplayMetrics.DENSITY_HIGH);
- int scaledHeight = scaleFromDensity(
- ret.getHeight(), ret.getDensity(), mCanvas.getDensity());
- assertEquals(scaledHeight, ret.getScaledHeight(mCanvas));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getScaledWidth",
- args = {android.graphics.Canvas.class}
- )
- public void testGetScaledWidth1() {
- int dummyDensity = 5;
- Bitmap ret = Bitmap.createBitmap(100, 200, Config.RGB_565);
- int scaledWidth = scaleFromDensity(ret.getWidth(), ret.getDensity(), dummyDensity);
- assertNotNull(ret);
- assertEquals(scaledWidth, ret.getScaledWidth(dummyDensity));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getScaledWidth",
- args = {android.util.DisplayMetrics.class}
- )
- public void testGetScaledWidth2() {
- Bitmap ret = Bitmap.createBitmap(100, 200, Config.RGB_565);
- DisplayMetrics metrics = new DisplayMetrics();
- metrics = getContext().getResources().getDisplayMetrics();
- int scaledWidth = scaleFromDensity(ret.getWidth(), ret.getDensity(), metrics.densityDpi);
- assertEquals(scaledWidth, ret.getScaledWidth(metrics));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getScaledWidth",
- args = {android.graphics.Canvas.class}
- )
- public void testGetScaledWidth3() {
- Bitmap ret = Bitmap.createBitmap(100, 200, Config.RGB_565);
- Bitmap mMutableBitmap = Bitmap.createBitmap(100, 200, Config.ARGB_8888);
- Canvas mCanvas = new Canvas(mMutableBitmap);
- // set Density
- mCanvas.setDensity(DisplayMetrics.DENSITY_HIGH);
- int scaledWidth = scaleFromDensity(ret.getWidth(), ret.getDensity(), mCanvas.getDensity());
- assertEquals(scaledWidth, ret.getScaledWidth(mCanvas));
- }
-
- private int scaleFromDensity(int size, int sdensity, int tdensity) {
- if (sdensity == Bitmap.DENSITY_NONE || sdensity == tdensity) {
- return size;
- }
-
- // Scale by tdensity / sdensity, rounding up.
- return ((size * tdensity) + (sdensity >> 1)) / sdensity;
- }
-
private int[] createColors(int size){
int[] colors = new int[size];
diff --git a/tests/tests/graphics/src/android/graphics/cts/Bitmap_CompressFormatTest.java b/tests/tests/graphics/src/android/graphics/cts/Bitmap_CompressFormatTest.java
index afe3409..44c91e3 100644
--- a/tests/tests/graphics/src/android/graphics/cts/Bitmap_CompressFormatTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/Bitmap_CompressFormatTest.java
@@ -37,7 +37,6 @@ public class Bitmap_CompressFormatTest extends AndroidTestCase{
public void testValueOf(){
assertEquals(CompressFormat.JPEG, CompressFormat.valueOf("JPEG"));
assertEquals(CompressFormat.PNG, CompressFormat.valueOf("PNG"));
- assertEquals(CompressFormat.WEBP, CompressFormat.valueOf("WEBP"));
}
@TestTargets({
@@ -56,15 +55,13 @@ public class Bitmap_CompressFormatTest extends AndroidTestCase{
public void testValues(){
CompressFormat[] comFormat = CompressFormat.values();
- assertEquals(3, comFormat.length);
+ assertEquals(2, comFormat.length);
assertEquals(CompressFormat.JPEG, comFormat[0]);
assertEquals(CompressFormat.PNG, comFormat[1]);
- assertEquals(CompressFormat.WEBP, comFormat[2]);
//CompressFormat is used as a argument here for all the methods that use it
Bitmap b = Bitmap.createBitmap(10, 24, Config.ARGB_8888);
assertTrue(b.compress(CompressFormat.JPEG, 24, new ByteArrayOutputStream()));
assertTrue(b.compress(CompressFormat.PNG, 24, new ByteArrayOutputStream()));
- assertTrue(b.compress(CompressFormat.WEBP, 24, new ByteArrayOutputStream()));
}
}
diff --git a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
index 5f20ae6..07612d4 100644
--- a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
@@ -21,7 +21,6 @@ import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
-import android.util.DisplayMetrics;
import android.graphics.DrawFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
@@ -97,6 +96,7 @@ public class CanvasTest extends InstrumentationTestCase {
)
public void testCanvas1() {
final Canvas c = new Canvas();
+ assertNull(c.getGL());
}
@TestTargetNew(
@@ -128,6 +128,36 @@ public class CanvasTest extends InstrumentationTestCase {
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",
@@ -143,6 +173,16 @@ public class CanvasTest extends InstrumentationTestCase {
// 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 {
@@ -159,6 +199,39 @@ public class CanvasTest extends InstrumentationTestCase {
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",
@@ -1071,7 +1144,7 @@ public class CanvasTest extends InstrumentationTestCase {
args = {float.class, float.class, float.class, float.class}
)
public void testClipRect6() {
- assertTrue(mCanvas.clipRect(0.5f, 0.5f, 10.5f, 31.5f));
+ assertTrue(mCanvas.clipRect(0, 0, 10, 31));
}
@TestTargetNew(
@@ -2180,28 +2253,6 @@ public class CanvasTest extends InstrumentationTestCase {
mCanvas.drawPicture(p, dst);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "setDensity",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getDensity",
- args = {android.util.DisplayMetrics.class}
- )
- })
- public void testDensity() {
- // set Density
- mCanvas.setDensity(DisplayMetrics.DENSITY_DEFAULT);
- assertEquals(DisplayMetrics.DENSITY_DEFAULT, mCanvas.getDensity());
-
- // set Density
- mCanvas.setDensity(DisplayMetrics.DENSITY_HIGH);
- assertEquals(DisplayMetrics.DENSITY_HIGH, mCanvas.getDensity());
- }
-
private void preCompare() {
final float[] values = new float[FLOAT_ARRAY_LEN];
mCanvas.getMatrix().getValues(values);
@@ -2215,4 +2266,8 @@ public class CanvasTest extends InstrumentationTestCase {
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/Interpolator_ResultTest.java b/tests/tests/graphics/src/android/graphics/cts/Interpolator_ResultTest.java
index 82419db..3c79581 100644
--- a/tests/tests/graphics/src/android/graphics/cts/Interpolator_ResultTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/Interpolator_ResultTest.java
@@ -18,8 +18,6 @@ package android.graphics.cts;
import junit.framework.TestCase;
import android.graphics.Interpolator.Result;
-import android.graphics.Shader.TileMode;
-
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
@@ -33,9 +31,8 @@ public class Interpolator_ResultTest extends TestCase {
args = {java.lang.String.class}
)
public void testValueOf() {
- assertEquals(Result.FREEZE_START, Result.valueOf("FREEZE_START"));
- assertEquals(Result.FREEZE_END, Result.valueOf("FREEZE_END"));
- assertEquals(Result.NORMAL, Result.valueOf("NORMAL"));
+ // this enum type is tested in
+ // android.graphics.InterpolatorTest#testTimeToValues1()
}
@TestTargetNew(
@@ -44,10 +41,8 @@ public class Interpolator_ResultTest extends TestCase {
args = {}
)
public void testValues() {
- Result[] result = Result.values();
- assertEquals(3, result.length);
- assertEquals(Result.NORMAL, result[0]);
- assertEquals(Result.FREEZE_START, result[1]);
- assertEquals(Result.FREEZE_END, result[2]);
+ // this enum type is tested in
+ // android.graphics.InterpolatorTest#testTimeToValues1()
}
-}
\ No newline at end of file
+
+}
diff --git a/tests/tests/graphics/src/android/graphics/cts/NinePatchTest.java b/tests/tests/graphics/src/android/graphics/cts/NinePatchTest.java
index d2b9af0..041de94 100644
--- a/tests/tests/graphics/src/android/graphics/cts/NinePatchTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/NinePatchTest.java
@@ -207,18 +207,6 @@ public class NinePatchTest extends AndroidTestCase {
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "getDensity",
- args = {}
- )
- public void testGetDensity() {
- mBitmap.setDensity(11);
- assertEquals(11, mNinePatch.getDensity());
- mNinePatch = new NinePatch(mBitmap, mChunk, NAME);
- assertEquals(mNinePatch.getDensity(), mBitmap.getDensity());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getTransparentRegion",
args = {android.graphics.Rect.class}
)
diff --git a/tests/tests/graphics/src/android/graphics/cts/PaintTest.java b/tests/tests/graphics/src/android/graphics/cts/PaintTest.java
index 42c5f58..20701cb 100644
--- a/tests/tests/graphics/src/android/graphics/cts/PaintTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/PaintTest.java
@@ -24,30 +24,22 @@ import dalvik.annotation.TestTargets;
import android.graphics.ColorFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
-import android.graphics.Paint.Align;
-import android.graphics.Paint.Cap;
-import android.graphics.Paint.Join;
-import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rasterizer;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.graphics.Xfermode;
+import android.graphics.Paint.Align;
+import android.graphics.Paint.Cap;
+import android.graphics.Paint.Join;
+import android.graphics.Paint.Style;
import android.test.AndroidTestCase;
import android.text.SpannedString;
@TestTargetClass(Paint.class)
public class PaintTest extends AndroidTestCase {
- private static final Typeface[] TYPEFACES = new Typeface[] {
- Typeface.DEFAULT,
- Typeface.DEFAULT_BOLD,
- Typeface.MONOSPACE,
- Typeface.SANS_SERIF,
- Typeface.SERIF,
- };
-
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -80,10 +72,6 @@ public class PaintTest extends AndroidTestCase {
SpannedString textSpan = new SpannedString(text);
Paint p = new Paint();
-
- // We need to turn off kerning in order to get accurate comparisons
- p.setFlags(p.getFlags() & ~Paint.DEV_KERN_TEXT_FLAG);
-
float[] widths = new float[text.length()];
assertEquals(text.length(), p.getTextWidths(text, widths));
@@ -109,7 +97,7 @@ public class PaintTest extends AndroidTestCase {
3, widths[0] + widths[1] + widths[2]);
// Measure substring from back: "MN"
- assertBreakText(text, textChars, textSpan, 5, 7, true, totalWidth,
+ assertBreakText(text, textChars, textSpan, 5, 7, false, totalWidth,
2, widths[5] + widths[6]);
// Reverse measure substring from back: "MN"
@@ -138,9 +126,6 @@ public class PaintTest extends AndroidTestCase {
float expectedWidth) {
Paint p = new Paint();
- // We need to turn off kerning in order to get accurate comparisons
- p.setFlags(p.getFlags() & ~Paint.DEV_KERN_TEXT_FLAG);
-
int count = end - start;
if (!measureForwards) {
count = -count;
@@ -476,17 +461,13 @@ public class PaintTest extends AndroidTestCase {
public void testGetFontSpacing() {
Paint p = new Paint();
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
+ assertEquals(13.96875f, p.getFontSpacing());
- p.setTextSize(10);
- float spacing10 = p.getFontSpacing();
- assertTrue(spacing10 > 0);
+ p.setTextSize(24.0f);
+ assertEquals(27.9375f, p.getFontSpacing());
- p.setTextSize(20);
- float spacing20 = p.getFontSpacing();
- assertTrue(spacing20 > spacing10);
- }
+ p.setTypeface(Typeface.MONOSPACE);
+ assertEquals(27.9375f, p.getFontSpacing());
}
@TestTargets({
@@ -630,17 +611,25 @@ public class PaintTest extends AndroidTestCase {
public void testAscent() {
Paint p = new Paint();
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
+ assertEquals(-11.138672f, p.ascent());
- p.setTextSize(10);
- float ascent10 = p.ascent();
- assertTrue(ascent10 < 0);
+ p.setTextSize(10.0f);
+ assertEquals(-9.282227f, p.ascent());
- p.setTextSize(20);
- float ascent20 = p.ascent();
- assertTrue(ascent20 < ascent10);
- }
+ p.setTypeface(Typeface.DEFAULT_BOLD);
+ assertEquals(-9.282227f, p.ascent());
+
+ p.setTextSize(20.0f);
+ assertEquals(-18.564453f, p.ascent());
+
+ p.setTypeface(Typeface.DEFAULT_BOLD);
+ assertEquals(-18.564453f, p.ascent());
+
+ p.setTypeface(Typeface.MONOSPACE);
+ assertEquals(-18.564453f, p.ascent());
+
+ p.setTypeface(Typeface.SANS_SERIF);
+ assertEquals(-18.564453f, p.ascent());
}
@TestTargets({
@@ -912,19 +901,36 @@ public class PaintTest extends AndroidTestCase {
Paint p = new Paint();
Paint.FontMetrics fm = new Paint.FontMetrics();
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
+ assertEquals(13.96875f, p.getFontMetrics(fm));
+ assertEquals(-11.138672f, fm.ascent);
+ assertEquals(3.2519531f, fm.bottom);
+ assertEquals(2.8300781f, fm.descent);
+ assertEquals(0.0f, fm.leading);
+ assertEquals(-12.574219f, fm.top);
- p.setTextSize(10);
- float spacing10 = p.getFontMetrics(fm);
- assertEquals(p.ascent(), fm.ascent);
- assertEquals(p.descent(), fm.descent);
+ assertEquals(13.96875f, p.getFontMetrics(null));
+
+ p.setTextSize(24.0f);
+
+ assertEquals(27.9375f, p.getFontMetrics(fm));
+ assertEquals(-22.277344f, fm.ascent);
+ assertEquals(6.5039062f, fm.bottom);
+ assertEquals(5.6601562f, fm.descent);
+ assertEquals(0.0f, fm.leading);
+ assertEquals(-25.148438f, fm.top);
+
+ assertEquals(27.9375f, p.getFontMetrics(null));
+
+ p.setTypeface(Typeface.MONOSPACE);
+ assertEquals(27.9375f, p.getFontMetrics(fm));
+ assertEquals(-22.277344f, fm.ascent);
+ assertEquals(6.5039062f, fm.bottom);
+ assertEquals(5.6601562f, fm.descent);
+ assertEquals(0.0f, fm.leading);
+ assertEquals(-25.347656f, fm.top);
+
+ assertEquals(27.9375f, p.getFontMetrics(null));
- p.setTextSize(20);
- float spacing20 = p.getFontMetrics(fm);
- assertEquals(p.ascent(), fm.ascent);
- assertEquals(p.descent(), fm.descent);
- }
}
@TestTargetNew(
@@ -934,22 +940,34 @@ public class PaintTest extends AndroidTestCase {
)
public void testGetFontMetrics2() {
Paint p = new Paint();
+ Paint.FontMetrics fm;
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
+ fm = p.getFontMetrics();
+ assertEquals(-11.138672f, fm.ascent);
+ assertEquals(3.2519531f, fm.bottom);
+ assertEquals(2.8300781f, fm.descent);
+ assertEquals(0.0f, fm.leading);
+ assertEquals(-12.574219f, fm.top);
- p.setTextSize(10);
- Paint.FontMetrics fm = p.getFontMetrics();
- assertEquals(p.ascent(), fm.ascent);
- assertEquals(p.descent(), fm.descent);
+ p.setTextSize(24.0f);
- p.setTextSize(20);
- fm = p.getFontMetrics();
- assertEquals(p.ascent(), fm.ascent);
- assertEquals(p.descent(), fm.descent);
- }
- }
+ fm = p.getFontMetrics();
+ assertEquals(-22.277344f, fm.ascent);
+ assertEquals(6.5039062f, fm.bottom);
+ assertEquals(5.6601562f, fm.descent);
+ assertEquals(0.0f, fm.leading);
+ assertEquals(-25.148438f, fm.top);
+ p.setTypeface(Typeface.MONOSPACE);
+
+ fm = p.getFontMetrics();
+ assertEquals(-22.277344f, fm.ascent);
+ assertEquals(6.5039062f, fm.bottom);
+ assertEquals(5.6601562f, fm.descent);
+ assertEquals(0.0f, fm.leading);
+ assertEquals(-25.347656f, fm.top);
+
+ }
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -1037,17 +1055,25 @@ public class PaintTest extends AndroidTestCase {
public void testDescent() {
Paint p = new Paint();
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
+ assertEquals(2.8300781f, p.descent());
- p.setTextSize(10);
- float descent10 = p.descent();
- assertTrue(descent10 > 0);
+ p.setTextSize(10.0f);
+ assertEquals(2.3583984f, p.descent());
- p.setTextSize(20);
- float descent20 = p.descent();
- assertTrue(descent20 > descent10);
- }
+ p.setTypeface(Typeface.DEFAULT_BOLD);
+ assertEquals(2.3583984f, p.descent());
+
+ p.setTextSize(20.0f);
+ assertEquals(4.716797f, p.descent());
+
+ p.setTypeface(Typeface.DEFAULT_BOLD);
+ assertEquals(4.716797f, p.descent());
+
+ p.setTypeface(Typeface.MONOSPACE);
+ assertEquals(4.716797f, p.descent());
+
+ p.setTypeface(Typeface.SANS_SERIF);
+ assertEquals(4.716797f, p.descent());
}
@TestTargets({
@@ -1174,19 +1200,36 @@ public class PaintTest extends AndroidTestCase {
Paint p = new Paint();
Paint.FontMetricsInt fmi = new Paint.FontMetricsInt();
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
+ assertEquals(14, p.getFontMetricsInt(fmi));
+ assertEquals(-11, fmi.ascent);
+ assertEquals(4, fmi.bottom);
+ assertEquals(3, fmi.descent);
+ assertEquals(0, fmi.leading);
+ assertEquals(-13, fmi.top);
- p.setTextSize(10);
- p.getFontMetricsInt(fmi);
- assertEquals(Math.round(p.ascent()), fmi.ascent);
- assertEquals(Math.round(p.descent()), fmi.descent);
+ assertEquals(14, p.getFontMetricsInt(null));
+
+ p.setTextSize(24);
+
+ assertEquals(28, p.getFontMetricsInt(fmi));
+ assertEquals(-22, fmi.ascent);
+ assertEquals(7, fmi.bottom);
+ assertEquals(6, fmi.descent);
+ assertEquals(0, fmi.leading);
+ assertEquals(-26, fmi.top);
+
+ assertEquals(28, p.getFontMetricsInt(null));
+
+ p.setTypeface(Typeface.MONOSPACE);
+ assertEquals(28, p.getFontMetricsInt(fmi));
+ assertEquals(-22, fmi.ascent);
+ assertEquals(7, fmi.bottom);
+ assertEquals(6, fmi.descent);
+ assertEquals(0, fmi.leading);
+ assertEquals(-26, fmi.top);
+
+ assertEquals(28, p.getFontMetricsInt(null));
- p.setTextSize(20);
- p.getFontMetricsInt(fmi);
- assertEquals(Math.round(p.ascent()), fmi.ascent);
- assertEquals(Math.round(p.descent()), fmi.descent);
- }
}
@TestTargetNew(
@@ -1198,19 +1241,29 @@ public class PaintTest extends AndroidTestCase {
Paint p = new Paint();
Paint.FontMetricsInt fmi;
- for (Typeface typeface : TYPEFACES) {
- p.setTypeface(typeface);
-
- p.setTextSize(10);
- fmi = p.getFontMetricsInt();
- assertEquals(Math.round(p.ascent()), fmi.ascent);
- assertEquals(Math.round(p.descent()), fmi.descent);
-
- p.setTextSize(20);
- fmi = p.getFontMetricsInt();
- assertEquals(Math.round(p.ascent()), fmi.ascent);
- assertEquals(Math.round(p.descent()), fmi.descent);
- }
+ fmi = p.getFontMetricsInt();
+ assertEquals(-11, fmi.ascent);
+ assertEquals(4, fmi.bottom);
+ assertEquals(3, fmi.descent);
+ assertEquals(0, fmi.leading);
+ assertEquals(-13, fmi.top);
+
+ p.setTextSize(24);
+
+ fmi = p.getFontMetricsInt();
+ assertEquals(-22, fmi.ascent);
+ assertEquals(7, fmi.bottom);
+ assertEquals(6, fmi.descent);
+ assertEquals(0, fmi.leading);
+ assertEquals(-26, fmi.top);
+
+ p.setTypeface(Typeface.MONOSPACE);
+ fmi = p.getFontMetricsInt();
+ assertEquals(-22, fmi.ascent);
+ assertEquals(7, fmi.bottom);
+ assertEquals(6, fmi.descent);
+ assertEquals(0, fmi.leading);
+ assertEquals(-26, fmi.top);
}
public void testMeasureText() {
@@ -1219,10 +1272,6 @@ public class PaintTest extends AndroidTestCase {
SpannedString textSpan = new SpannedString(text);
Paint p = new Paint();
-
- // We need to turn off kerning in order to get accurate comparisons
- p.setFlags(p.getFlags() & ~Paint.DEV_KERN_TEXT_FLAG);
-
float[] widths = new float[text.length()];
for (int i = 0; i < widths.length; i++) {
widths[i] = p.measureText(text, i, i + 1);
@@ -1251,10 +1300,6 @@ public class PaintTest extends AndroidTestCase {
private void assertMeasureText(String text, char[] textChars, SpannedString textSpan,
int start, int end, float expectedWidth) {
Paint p = new Paint();
-
- // We need to turn off kerning in order to get accurate comparisons
- p.setFlags(p.getFlags() & ~Paint.DEV_KERN_TEXT_FLAG);
-
int count = end - start;
float[] widths = new float[] {-1, -1, -1, -1};
diff --git a/tests/tests/graphics/src/android/graphics/cts/PathMeasureTest.java b/tests/tests/graphics/src/android/graphics/cts/PathMeasureTest.java
index 94e352a..614a44e 100644
--- a/tests/tests/graphics/src/android/graphics/cts/PathMeasureTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/PathMeasureTest.java
@@ -157,9 +157,6 @@ public class PathMeasureTest extends AndroidTestCase {
mPath.addRect(1, 2, 3, 4, Path.Direction.CW);
mPathMeasure.setPath(mPath, true);
assertEquals(8f, mPathMeasure.getLength());
- Path dst = new Path();
- assertTrue(mPathMeasure.getSegment(0, mPathMeasure.getLength(), dst, true));
- assertFalse(mPathMeasure.getSegment(mPathMeasure.getLength(), 0, dst, true));
}
@TestTargetNew(
diff --git a/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java b/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java
new file mode 100644
index 0000000..170992d
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java
@@ -0,0 +1,85 @@
+/*
+ * 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
new file mode 100644
index 0000000..3db864b
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/cts/RadialGradientTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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/cts/RectTest.java b/tests/tests/graphics/src/android/graphics/cts/RectTest.java
index 5eb788f..2176987 100644
--- a/tests/tests/graphics/src/android/graphics/cts/RectTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/RectTest.java
@@ -677,30 +677,6 @@ public class RectTest extends AndroidTestCase {
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "flattenToString",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "unflattenFromString",
- args = {java.lang.String.class}
- )
- })
- public void testFlattenToString() {
- Rect mRect = new Rect(1, 2, 3, 4);
- String flattenString = mRect.flattenToString();
- assertNotNull(flattenString);
- String unDefinedFormat = "TOPLEFT";
- Rect rect = Rect.unflattenFromString(flattenString);
- assertEquals(mRect, rect);
- rect = null;
- rect = Rect.unflattenFromString(unDefinedFormat);
- assertNull(rect);
- }
-
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "describeContents",
diff --git a/tests/tests/graphics/src/android/graphics/cts/Shader_TileModeTest.java b/tests/tests/graphics/src/android/graphics/cts/Shader_TileModeTest.java
index 4389032..135bf36 100644
--- a/tests/tests/graphics/src/android/graphics/cts/Shader_TileModeTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/Shader_TileModeTest.java
@@ -18,7 +18,6 @@ package android.graphics.cts;
import junit.framework.TestCase;
import android.graphics.Shader;
-import android.graphics.Shader.TileMode;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
@@ -27,27 +26,18 @@ import dalvik.annotation.TestTargets;
@TestTargetClass(Shader.TileMode.class)
public class Shader_TileModeTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void testValueOf() {
- assertEquals(TileMode.CLAMP, TileMode.valueOf("CLAMP"));
- assertEquals(TileMode.MIRROR, TileMode.valueOf("MIRROR"));
- assertEquals(TileMode.REPEAT, TileMode.valueOf("REPEAT"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "values",
- args = {}
- )
- public void testValues() {
- TileMode[] tileMode = TileMode.values();
- assertEquals(3, tileMode.length);
- assertEquals(TileMode.CLAMP, tileMode[0]);
- assertEquals(TileMode.REPEAT, tileMode[1]);
- assertEquals(TileMode.MIRROR, tileMode[2]);
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.NOT_NECESSARY,
+ method = "values",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_NECESSARY,
+ method = "valueOf",
+ args = {java.lang.String.class}
+ )
+ })
+ public void testTileMode() {
}
}
diff --git a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
index 19f3f46..c861b3e 100755
--- a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
@@ -22,19 +22,8 @@ import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
import android.graphics.Typeface;
-import android.content.res.AssetFileDescriptor;
-import android.content.res.AssetManager;
-import android.content.res.Resources;
-import android.graphics.Typeface;
-import android.os.ParcelFileDescriptor;
import android.test.AndroidTestCase;
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
@TestTargetClass(android.graphics.Typeface.class)
public class TypefaceTest extends AndroidTestCase {
@@ -177,61 +166,4 @@ public class TypefaceTest extends AndroidTestCase {
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "samplefont.ttf");
assertNotNull(typeface);
}
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "createFromFile",
- args = {java.io.File.class}
- )
- public void testCreateFromFile1() throws IOException {
- // input abnormal params.
- try {
- Typeface.createFromFile((File)null);
- fail("Should throw a NullPointerException.");
- } catch (NullPointerException e) {
- // except here
- }
- File file = new File(obtainPath());
- Typeface typeface = Typeface.createFromFile(file);
- assertNotNull(typeface);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "createFromFile",
- args = {java.lang.String.class}
- )
- public void testCreateFromFile2() throws IOException {
- // input abnormal params.
- try {
- Typeface.createFromFile((String)null);
- fail("Should throw a NullPointerException.");
- } catch (NullPointerException e) {
- // except here
- }
-
- Typeface typeface = Typeface.createFromFile(obtainPath());
- assertNotNull(typeface);
- }
-
- private String obtainPath() throws IOException {
- File dir = getContext().getFilesDir();
- dir.mkdirs();
- File file = new File(dir, "test.jpg");
- if (!file.createNewFile()) {
- if (!file.exists()) {
- fail("Failed to create new File!");
- }
- }
- InputStream is = getContext().getAssets().open("samplefont.ttf");
- FileOutputStream fOutput = new FileOutputStream(file);
- byte[] dataBuffer = new byte[1024];
- int readLength = 0;
- while ((readLength = is.read(dataBuffer)) != -1) {
- fOutput.write(dataBuffer, 0, readLength);
- }
- is.close();
- fOutput.close();
- return (file.getPath());
- }
}
diff --git a/tests/tests/graphics/src/android/graphics/cts/YuvImageTest.java b/tests/tests/graphics/src/android/graphics/cts/YuvImageTest.java
index eb0b21f..6613e92 100755
--- a/tests/tests/graphics/src/android/graphics/cts/YuvImageTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/YuvImageTest.java
@@ -203,56 +203,6 @@ public class YuvImageTest extends AndroidTestCase {
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getHeight",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getWidth",
- args = {}
- )
- })
- public void testGetHeight() {
- generateTestBitmaps(WIDTH, HEIGHT);
- YuvImage image = generateYuvImage(ImageFormat.YUY2, mTestBitmaps[0], 0);
- assertEquals(mTestBitmaps[0].getHeight(), image.getHeight());
- assertEquals(mTestBitmaps[0].getWidth(), image.getWidth());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getYuvData",
- args = {}
- )
- public void testGetYuvData() {
- generateTestBitmaps(WIDTH, HEIGHT);
- int width = mTestBitmaps[0].getWidth();
- int height = mTestBitmaps[0].getHeight();
- int stride = width;
- int[] argb = new int[stride * height];
- mTestBitmaps[0].getPixels(argb, 0, stride, 0, 0, width, height);
- byte[] yuv = convertArgbsToYuvs(argb, stride, height, ImageFormat.NV21);
- int[] strides = new int[] {
- stride, stride
- };
- YuvImage image = new YuvImage(yuv, ImageFormat.NV21, width, height, strides);
- assertEquals(yuv, image.getYuvData());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getYuvFormat",
- args = {}
- )
- public void testGetYuvFormat() {
- generateTestBitmaps(WIDTH, HEIGHT);
- YuvImage image = generateYuvImage(ImageFormat.YUY2, mTestBitmaps[0], 0);
- assertEquals(ImageFormat.YUY2, image.getYuvFormat());
- }
-
private void generateTestBitmaps(int width, int height) {
Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(dst);
@@ -270,7 +220,7 @@ public class YuvImageTest extends AndroidTestCase {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
- int stride = width + paddings;
+ int stride = width + paddings;;
YuvImage image = null;
int[] argb = new int [stride * height];
@@ -301,6 +251,7 @@ public class YuvImageTest extends AndroidTestCase {
Rect expectedRect = sameRect ? actualRect : rect1;
expected = Bitmap.createBitmap(testBitmap, expectedRect.left, expectedRect.top, expectedRect.width(), expectedRect.height());
+
compareBitmaps(expected, actual, mMseMargin, sameRect);
}
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java
index 5e9e88d..a27aa9d 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java
@@ -41,7 +41,6 @@ import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable.ConstantState;
import android.test.InstrumentationTestCase;
import android.util.AttributeSet;
-import android.util.DisplayMetrics;
import android.view.Gravity;
import java.io.ByteArrayInputStream;
@@ -68,40 +67,20 @@ public class BitmapDrawableTest extends InstrumentationTestCase {
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "BitmapDrawable",
- args = {android.content.res.Resources.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BitmapDrawable",
args = {android.graphics.Bitmap.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "BitmapDrawable",
- args = {android.content.res.Resources.class, android.graphics.Bitmap.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BitmapDrawable",
args = {java.lang.String.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "BitmapDrawable",
- args = {android.content.res.Resources.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BitmapDrawable",
args = {java.io.InputStream.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "BitmapDrawable",
- args = {android.content.res.Resources.class, java.io.InputStream.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "getPaint",
args = {}
),
@@ -129,10 +108,6 @@ public class BitmapDrawableTest extends InstrumentationTestCase {
bitmapDrawable.getPaint().getFlags());
assertEquals(bitmap, bitmapDrawable.getBitmap());
- new BitmapDrawable(mContext.getResources());
-
- new BitmapDrawable(mContext.getResources(), bitmap);
-
new BitmapDrawable(mContext.getFilesDir().getPath());
new BitmapDrawable(new ByteArrayInputStream("test constructor".getBytes()));
@@ -140,12 +115,8 @@ public class BitmapDrawableTest extends InstrumentationTestCase {
// exceptional test
new BitmapDrawable((Bitmap) null);
- new BitmapDrawable(mContext.getResources(), (String) null);
-
new BitmapDrawable((String) null);
- new BitmapDrawable(mContext.getResources(), (InputStream) null);
-
new BitmapDrawable((InputStream) null);
}
@@ -445,38 +416,6 @@ public class BitmapDrawableTest extends InstrumentationTestCase {
assertEquals(48, bitmapDrawable.getIntrinsicHeight());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "setTargetDensity",
- args = {android.graphics.Canvas.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "setTargetDensity",
- args = {android.util.DisplayMetrics.class}
- )
- })
- @SuppressWarnings("deprecation")
- public void testSetTargetDensity() {
- BitmapDrawable bitmapDrawable = new BitmapDrawable();
-
- Bitmap bitmap = Bitmap.createBitmap(200, 300, Config.RGB_565);
- Canvas canvas = new Canvas(bitmap);
- bitmapDrawable = new BitmapDrawable(bitmap);
- bitmapDrawable.setTargetDensity(canvas.getDensity());
- assertEquals(200, bitmapDrawable.getIntrinsicWidth());
- assertEquals(300, bitmapDrawable.getIntrinsicHeight());
-
- DisplayMetrics disMetrics = new DisplayMetrics();
- disMetrics = getInstrumentation().getTargetContext().getResources().getDisplayMetrics();
- InputStream source = mContext.getResources().openRawResource(R.drawable.size_48x48);
- bitmapDrawable = new BitmapDrawable(source);
- bitmapDrawable.setTargetDensity(disMetrics.densityDpi);
- assertEquals(48, bitmapDrawable.getIntrinsicWidth());
- assertEquals(48, bitmapDrawable.getIntrinsicHeight());
- }
-
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "inflate",
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/ClipDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/ClipDrawableTest.java
index 8a5d7aa..d503938 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/ClipDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/ClipDrawableTest.java
@@ -18,30 +18,32 @@ package android.graphics.drawable.cts;
import com.android.cts.stub.R;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.ToBeFixed;
+
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
-import java.io.IOException;
-
import android.graphics.Bitmap;
-import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
+import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
+import android.graphics.drawable.Drawable.Callback;
import android.graphics.drawable.Drawable.ConstantState;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.StateSet;
import android.util.Xml;
import android.view.Gravity;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.ToBeFixed;
+
+import java.io.IOException;
@TestTargetClass(android.graphics.drawable.ClipDrawable.class)
public class ClipDrawableTest extends AndroidTestCase {
@@ -521,7 +523,7 @@ public class ClipDrawableTest extends AndroidTestCase {
}
}
- private class MockCallback implements Drawable.Callback2 {
+ private class MockCallback implements Callback {
private Drawable mInvalidateDrawable;
private Drawable mScheduleDrawable;
private Runnable mRunnable;
@@ -557,9 +559,5 @@ public class ClipDrawableTest extends AndroidTestCase {
mScheduleDrawable = who;
mRunnable = what;
}
-
- public int getResolvedLayoutDirection(Drawable who) {
- return 0;
- }
}
}
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 bfe3ec7..15ae0b6 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 class DrawableContainerStateTest extends TestCase{
})
public void testConstantHeightsAndWidths() {
assertEquals(0, mDrawableContainerState.getChildCount());
- assertEquals(-1, mDrawableContainerState.getConstantHeight());
- assertEquals(-1, mDrawableContainerState.getConstantWidth());
+ assertEquals(0, mDrawableContainerState.getConstantHeight());
+ assertEquals(0, mDrawableContainerState.getConstantWidth());
assertEquals(0, mDrawableContainerState.getConstantMinimumHeight());
assertEquals(0, mDrawableContainerState.getConstantMinimumWidth());
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerTest.java
index 9191cac..c9107ab 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerTest.java
@@ -16,9 +16,11 @@
package android.graphics.drawable.cts;
-import junit.framework.TestCase;
-
-import java.util.Arrays;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
@@ -26,13 +28,13 @@ import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
-import android.graphics.drawable.DrawableContainer.DrawableContainerState;
import android.graphics.drawable.LevelListDrawable;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+import android.graphics.drawable.Drawable.Callback;
+import android.graphics.drawable.DrawableContainer.DrawableContainerState;
+
+import java.util.Arrays;
+
+import junit.framework.TestCase;
@TestTargetClass(DrawableContainer.class)
public class DrawableContainerTest extends TestCase {
@@ -1096,7 +1098,7 @@ public class DrawableContainerTest extends TestCase {
}
}
- private class MockCallBack implements Drawable.Callback2 {
+ private class MockCallBack implements Callback {
private boolean mCalledInvalidateDrawable;
private boolean mCalledScheduleDrawable;
@@ -1132,9 +1134,5 @@ public class DrawableContainerTest extends TestCase {
public void unscheduleDrawable(Drawable who, Runnable what) {
mCalledUnscheduleDrawable = true;
}
-
- public int getResolvedLayoutDirection(Drawable who) {
- return 0;
- }
}
}
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTest.java
index 97f160f..9d586d9 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTest.java
@@ -18,37 +18,37 @@ package android.graphics.drawable.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 org.xmlpull.v1.XmlPullParserException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
import android.content.ContentResolver;
import android.content.res.Resources;
-import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
+import android.graphics.drawable.Drawable.Callback;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.StateSet;
-import android.util.TypedValue;
import android.util.Xml;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
@TestTargetClass(Drawable.class)
public class DrawableTest extends AndroidTestCase {
@@ -236,116 +236,6 @@ public class DrawableTest extends AndroidTestCase {
@TestTargetNew(
level = TestLevel.COMPLETE,
- method = "createFromResourceStream",
- args = {android.content.res.Resources.class, android.util.TypedValue.class,
- java.io.InputStream.class, java.lang.String.class}
- )
- public void testCreateFromResourceStream1() throws FileNotFoundException, IOException {
- FileInputStream inputEmptyStream = null;
- FileInputStream inputStream = null;
- File imageFile = null;
- OutputStream outputEmptyStream = null;
-
- assertNull(Drawable.createFromResourceStream(null, null, inputStream, "test.bmp"));
-
- File emptyFile = new File(mContext.getFilesDir(), "tempemptyimage.jpg");
-
- // write some random data.
- try {
- outputEmptyStream = new FileOutputStream(emptyFile);
- outputEmptyStream.write(10);
-
- inputEmptyStream = new FileInputStream(emptyFile);
- assertNull(Drawable.createFromResourceStream(mResources, null, inputEmptyStream,
- "Sample"));
-
- imageFile = new File(mContext.getFilesDir(), "tempimage.jpg");
-
- writeSampleImage(imageFile);
-
- inputStream = new FileInputStream(imageFile);
- final TypedValue value = new TypedValue();
- assertNotNull(Drawable.createFromResourceStream(mResources, value, inputStream,
- "Sample"));
- } finally {
-
- if (null != outputEmptyStream) {
- outputEmptyStream.close();
- }
- if (null != inputEmptyStream) {
- inputEmptyStream.close();
- }
- if (null != inputStream) {
- inputStream.close();
- }
- if (emptyFile.exists()) {
- assertTrue(emptyFile.delete());
- }
- if (imageFile.exists()) {
- assertTrue(imageFile.delete());
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "createFromResourceStream",
- args = {android.content.res.Resources.class, android.util.TypedValue.class,
- java.io.InputStream.class, java.lang.String.class,
- android.graphics.BitmapFactory.Options.class}
- )
- public void testCreateFromResourceStream2() throws FileNotFoundException, IOException {
- FileInputStream inputEmptyStream = null;
- FileInputStream inputStream = null;
- File imageFile = null;
- OutputStream outputEmptyStream = null;
-
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inScaled = false;
-
- assertNull(Drawable.createFromResourceStream(null, null, inputStream, "test.bmp", opt));
-
- File emptyFile = new File(mContext.getFilesDir(), "tempemptyimage.jpg");
-
- // write some random data.
- try {
- outputEmptyStream = new FileOutputStream(emptyFile);
- outputEmptyStream.write(10);
-
- inputEmptyStream = new FileInputStream(emptyFile);
- assertNull(Drawable.createFromResourceStream(mResources, null, inputEmptyStream,
- "Sample", opt));
-
- imageFile = new File(mContext.getFilesDir(), "tempimage.jpg");
-
- writeSampleImage(imageFile);
-
- inputStream = new FileInputStream(imageFile);
- final TypedValue value = new TypedValue();
- assertNotNull(Drawable.createFromResourceStream(mResources, value, inputStream,
- "Sample", opt));
- } finally {
-
- if (null != outputEmptyStream) {
- outputEmptyStream.close();
- }
- if (null != inputEmptyStream) {
- inputEmptyStream.close();
- }
- if (null != inputStream) {
- inputStream.close();
- }
- if (emptyFile.exists()) {
- assertTrue(emptyFile.delete());
- }
- if (imageFile.exists()) {
- assertTrue(imageFile.delete());
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
method = "createFromXml",
args = {android.content.res.Resources.class, org.xmlpull.v1.XmlPullParser.class}
)
@@ -806,22 +696,6 @@ public class DrawableTest extends AndroidTestCase {
assertSame(mockDrawable, mockDrawable.mutate());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "isLayoutRtlSelf",
- args = {java.lang.Runnable.class}
- )
- public void getResolvedLayoutDirectionSelf() {
- MockDrawable mockDrawable = new MockDrawable();
- MockCallback mockCallback = new MockCallback(1);
- mockDrawable.setCallback(mockCallback);
- assertEquals(1, mockDrawable.getResolvedLayoutDirectionSelf());
-
- mockCallback = new MockCallback(0);
- mockDrawable.setCallback(mockCallback);
- assertEquals(0, mockDrawable.getResolvedLayoutDirectionSelf());
- }
-
private static class MockDrawable extends Drawable {
private ColorFilter mColorFilter;
@@ -856,21 +730,11 @@ public class DrawableTest extends AndroidTestCase {
}
}
- private static class MockCallback implements Drawable.Callback2 {
+ private static class MockCallback implements Callback {
private Drawable mInvalidateDrawable;
private Drawable mScheduleDrawable;
private Runnable mRunnable;
private long mWhen;
- private int mLayoutDirection;
-
- public MockCallback() {
- // 0 for LTR layout direction
- this(0);
- }
-
- public MockCallback(int direction) {
- mLayoutDirection = direction;
- }
public Drawable getInvalidateDrawable() {
return mInvalidateDrawable;
@@ -902,9 +766,5 @@ public class DrawableTest extends AndroidTestCase {
mScheduleDrawable = who;
mRunnable = what;
}
-
- public int getResolvedLayoutDirection(Drawable who) {
- return mLayoutDirection;
- }
}
}
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 cb9b7b6..b47d906 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
@@ -18,9 +18,13 @@ package android.graphics.drawable.cts;
import com.android.cts.stub.R;
-import org.xmlpull.v1.XmlPullParserException;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
-import java.io.IOException;
+import org.xmlpull.v1.XmlPullParserException;
import android.R.attr;
import android.content.res.Resources;
@@ -33,21 +37,19 @@ import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
-import android.graphics.drawable.Drawable.ConstantState;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.RotateDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
+import android.graphics.drawable.Drawable.Callback;
+import android.graphics.drawable.Drawable.ConstantState;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.StateSet;
import android.view.View;
-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(android.graphics.drawable.LayerDrawable.class)
public class LayerDrawableTest extends AndroidTestCase {
@@ -281,6 +283,9 @@ public class LayerDrawableTest extends AndroidTestCase {
assertFalse(layerDrawable.setDrawableByLayerId(30, d1));
+ layerDrawable.setDrawableByLayerId(20, null);
+ assertEquals(null, layerDrawable.getDrawable(1));
+
try {
layerDrawable.getDrawable(layerDrawable.getNumberOfLayers());
fail("Should throw IndexOutOfBoundsException");
@@ -416,7 +421,7 @@ public class LayerDrawableTest extends AndroidTestCase {
assertFalse(cb.hasCalledUnschedule());
}
- private static class MockCallback implements Drawable.Callback2 {
+ private static class MockCallback implements Callback {
private boolean mCalledInvalidate;
private boolean mCalledSchedule;
private boolean mCalledUnschedule;
@@ -445,10 +450,6 @@ public class LayerDrawableTest extends AndroidTestCase {
return mCalledUnschedule;
}
- public int getResolvedLayoutDirection(Drawable who) {
- return 0;
- }
-
public void reset() {
mCalledInvalidate = false;
mCalledSchedule = false;
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/RotateDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/RotateDrawableTest.java
index 8dde6a3..97bc210 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/RotateDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/RotateDrawableTest.java
@@ -18,11 +18,15 @@ package android.graphics.drawable.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 org.xmlpull.v1.XmlPullParserException;
-import java.io.IOException;
-
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
@@ -31,16 +35,14 @@ import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
-import android.graphics.drawable.Drawable.ConstantState;
import android.graphics.drawable.RotateDrawable;
+import android.graphics.drawable.Drawable.Callback;
+import android.graphics.drawable.Drawable.ConstantState;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.Xml;
-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(android.graphics.drawable.RotateDrawable.class)
public class RotateDrawableTest extends AndroidTestCase {
@@ -350,7 +352,7 @@ public class RotateDrawableTest extends AndroidTestCase {
assertEquals(50, ((BitmapDrawable) d3.getDrawable()).getPaint().getAlpha());
}
- private static class MockCallback implements Drawable.Callback2 {
+ private static class MockCallback implements Callback {
private boolean mCalledInvalidate;
private boolean mCalledSchedule;
private boolean mCalledUnschedule;
@@ -379,10 +381,6 @@ public class RotateDrawableTest extends AndroidTestCase {
return mCalledUnschedule;
}
- public int getResolvedLayoutDirection(Drawable who) {
- return 0;
- }
-
public void reset() {
mCalledInvalidate = false;
mCalledSchedule = false;
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/ScaleDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/ScaleDrawableTest.java
index c9d9d0a..23e8745 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/ScaleDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/ScaleDrawableTest.java
@@ -18,9 +18,13 @@ package android.graphics.drawable.cts;
import com.android.cts.stub.R;
-import org.xmlpull.v1.XmlPullParserException;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
-import java.io.IOException;
+import org.xmlpull.v1.XmlPullParserException;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
@@ -29,18 +33,16 @@ import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
-import android.graphics.drawable.Drawable.ConstantState;
import android.graphics.drawable.ScaleDrawable;
+import android.graphics.drawable.Drawable.Callback;
+import android.graphics.drawable.Drawable.ConstantState;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.StateSet;
import android.view.Gravity;
-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(android.graphics.drawable.ScaleDrawable.class)
public class ScaleDrawableTest extends AndroidTestCase {
@@ -147,7 +149,7 @@ public class ScaleDrawableTest extends AndroidTestCase {
assertFalse(cb.hasCalledUnschedule());
}
- private static class MockCallback implements Drawable.Callback2 {
+ private static class MockCallback implements Callback {
private boolean mCalledInvalidate;
private boolean mCalledSchedule;
private boolean mCalledUnschedule;
@@ -176,10 +178,6 @@ public class ScaleDrawableTest extends AndroidTestCase {
return mCalledUnschedule;
}
- public int getResolvedLayoutDirection(Drawable who) {
- return 0;
- }
-
public void reset() {
mCalledInvalidate = false;
mCalledSchedule = false;
@@ -517,8 +515,7 @@ public class ScaleDrawableTest extends AndroidTestCase {
XmlResourceParser parser = res.getXml(R.xml.scaledrawable);
AttributeSet attrs = DrawableTestUtils.getAttributeSet(parser, "scale_allattrs");
scaleDrawable.inflate(res, parser, attrs);
- int bitmapSize = (int) Math.ceil(48.0 *
- res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
+ int bitmapSize = 48 * res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT;
assertEquals(bitmapSize, scaleDrawable.getIntrinsicWidth());
assertEquals(bitmapSize, scaleDrawable.getIntrinsicHeight());
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/TransitionDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/TransitionDrawableTest.java
index a60bfe9..c02593f 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/TransitionDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/TransitionDrawableTest.java
@@ -18,18 +18,20 @@ package android.graphics.drawable.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 android.content.res.Resources;
import android.graphics.Bitmap;
-import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
+import android.graphics.Bitmap.Config;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
+import android.graphics.drawable.Drawable.Callback;
import android.test.InstrumentationTestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
@TestTargetClass(TransitionDrawable.class)
public class TransitionDrawableTest extends InstrumentationTestCase {
@@ -312,7 +314,7 @@ public class TransitionDrawableTest extends InstrumentationTestCase {
}
}
- private class MockCallBack implements Drawable.Callback2 {
+ private class MockCallBack implements Callback {
private boolean mHasCalledInvalidateDrawable;
public boolean hasCalledInvalidateDrawable() {
@@ -331,9 +333,5 @@ public class TransitionDrawableTest extends InstrumentationTestCase {
public void unscheduleDrawable(Drawable who, Runnable what) {
}
-
- public int getResolvedLayoutDirection(Drawable who) {
- return 0;
- }
}
}
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 ada9d69..fa164e3 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,7 +62,11 @@ public class RoundRectShapeTest extends TestCase {
} catch (ArrayIndexOutOfBoundsException e) {
}
- new RoundRectShape(null, new RectF(), new float[8]);
+ try {
+ new RoundRectShape(null, new RectF(), new float[8]);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
try {
new RoundRectShape(new float[8], new RectF(), new float[7]);
diff --git a/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/ShapeTest.java b/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/ShapeTest.java
index 99bde2f..10c4022 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/ShapeTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/ShapeTest.java
@@ -21,25 +21,14 @@ import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
-import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
-import android.graphics.RectF;
-import android.graphics.Bitmap.Config;
-import android.graphics.Paint.Style;
-import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import junit.framework.TestCase;
@TestTargetClass(android.graphics.drawable.shapes.Shape.class)
public class ShapeTest extends TestCase {
- private static final int TEST_WIDTH = 100;
- private static final int TEST_HEIGHT = 200;
-
- private static final int TEST_COLOR_1 = 0xFF00FF00;
- private static final int TEST_COLOR_2 = 0xFFFF0000;
-
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -125,30 +114,7 @@ public class ShapeTest extends TestCase {
args = {}
)
public void testHasAlpha() {
- Shape shape = new MockShape();
- assertTrue(shape.hasAlpha());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "draw",
- args = {android.graphics.Canvas.class, android.graphics.Paint.class}
- )
- public void testDraw() {
- Shape shape = new MockShape();
- Bitmap bitmap = Bitmap.createBitmap(TEST_WIDTH, TEST_HEIGHT, Config.ARGB_8888);
- Canvas canvas = new Canvas(bitmap);
- Paint paint = new Paint();
- paint.setStyle(Style.FILL);
- paint.setColor(TEST_COLOR_1);
- shape.resize(TEST_WIDTH, TEST_HEIGHT);
-
- shape.draw(canvas, paint);
- assertEquals(0, bitmap.getPixel(0, 0));
-
- paint.setColor(TEST_COLOR_2);
- shape.draw(canvas, paint);
- assertEquals(0, bitmap.getPixel(0, 0));
+ assertTrue(new MockShape().hasAlpha());
}
private static class MockShape extends Shape {
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java
deleted file mode 100644
index 816ffaa..0000000
--- a/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java
+++ /dev/null
@@ -1,882 +0,0 @@
-/*
- * 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.hardware.cts;
-
-import android.content.Context;
-import android.graphics.SurfaceTexture;
-import android.hardware.Camera;
-import android.hardware.Camera.Parameters;
-import android.hardware.Camera.Size;
-
-import android.opengl.GLES20;
-import android.opengl.GLSurfaceView;
-import android.opengl.Matrix;
-import android.opengl.cts.GLSurfaceViewStubActivity;
-
-import android.os.ConditionVariable;
-import android.os.Environment;
-import android.os.Looper;
-import android.os.PowerManager;
-import android.os.PowerManager.WakeLock;
-
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.MoreAsserts;
-import android.test.UiThreadTest;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.FloatBuffer;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.microedition.khronos.egl.EGL10;
-import javax.microedition.khronos.egl.EGLConfig;
-import javax.microedition.khronos.egl.EGLContext;
-import javax.microedition.khronos.egl.EGLDisplay;
-import javax.microedition.khronos.opengles.GL10;
-
-/**
- * This test case must run with hardware. It can't be tested in emulator
- */
-@LargeTest
-@TestTargetClass(Camera.class)
-public class CameraGLTest extends ActivityInstrumentationTestCase2 {
- private static final String TAG = "CameraGLTest";
- private static final String PACKAGE = "com.android.cts.stub";
- private static final boolean LOGV = false;
- private static final boolean LOGVV = false;
- private static final int EGL_OPENGL_ES2_BIT = 0x0004;
-
- private boolean mSurfaceTextureCallbackResult = false;
-
- private static final int WAIT_FOR_COMMAND_TO_COMPLETE = 1500; // Milliseconds.
- private static final int WAIT_FOR_FOCUS_TO_COMPLETE = 3000;
- private static final int WAIT_FOR_SNAPSHOT_TO_COMPLETE = 5000;
-
- private SurfaceTextureCallback mSurfaceTextureCallback = new SurfaceTextureCallback();
- private SurfaceTextureBurstCallback mSurfaceTextureBurstCallback = new SurfaceTextureBurstCallback();
- private PreviewCallback mPreviewCallback = new PreviewCallback();
-
- private Looper mLooper = null;
- private final ConditionVariable mSurfaceTextureDone = new ConditionVariable();
- private final ConditionVariable mPreviewDone = new ConditionVariable();
-
- Camera mCamera;
- SurfaceTexture mSurfaceTexture;
- Renderer mRenderer;
- GLSurfaceView mGLView;
-
- public CameraGLTest() {
- super(PACKAGE, GLSurfaceViewStubActivity.class);
- if (LOGV) Log.v(TAG, "CameraGLTest Constructor");
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- // Set up renderer instance
- mRenderer = this.new Renderer();
- GLSurfaceViewStubActivity.setRenderer(mRenderer);
- GLSurfaceViewStubActivity.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
- GLSurfaceViewStubActivity.setGlVersion(2);
- // Start CameraStubActivity.
- GLSurfaceViewStubActivity stubActivity = getActivity();
- // Store a link to the view so we can redraw it when needed
- mGLView = stubActivity.getView();
- }
-
- @Override
- protected void tearDown() throws Exception {
- if (mCamera != null) {
- terminateMessageLooper();
- }
- // Clean up static values in stub so it can be reused
- GLSurfaceViewStubActivity.resetRenderMode();
- GLSurfaceViewStubActivity.resetRenderer();
- GLSurfaceViewStubActivity.resetGlVersion();
-
- super.tearDown();
- }
-
- /**
- * Initializes the message looper so that the Camera object can
- * receive the callback messages.
- */
- private void initializeMessageLooper(final int cameraId) {
- final ConditionVariable startDone = new ConditionVariable();
- new Thread() {
- @Override
- public void run() {
- Log.v(TAG, "Start camera/surfacetexture thread");
- // Set up a looper to be used by camera.
- Looper.prepare();
- // Save the looper so that we can terminate this thread
- // after we are done with it.
- mLooper = Looper.myLooper();
- // These must be instantiated outside the UI thread, since the
- // UI thread will be doing a lot of waiting, stopping callbacks.
- mCamera = Camera.open(cameraId);
- mSurfaceTexture = new SurfaceTexture(mRenderer.getTextureID());
- Log.v(TAG, "Camera " + cameraId + " is opened.");
- startDone.open();
- Looper.loop(); // Blocks forever until Looper.quit() is called.
- Log.v(TAG, "Stop camera/surfacetexture thread");
- }
- }.start();
-
- Log.v(TAG, "start waiting for looper");
- if (!startDone.block(WAIT_FOR_COMMAND_TO_COMPLETE)) {
- fail("initializeMessageLooper: start timeout");
- }
- }
-
- /**
- * Terminates the message looper thread.
- */
- private void terminateMessageLooper() throws Exception {
- if (LOGV) Log.v(TAG, "Shutting down camera");
- mCamera.release();
- mLooper.quit();
- // Looper.quit() is asynchronous. The looper may still has some
- // preview callbacks in the queue after quit is called. The preview
- // callback still uses the camera object (setHasPreviewCallback).
- // After camera is released, RuntimeException will be thrown from
- // the method. So we need to join the looper thread here.
- mLooper.getThread().join();
- mCamera = null;
- mSurfaceTexture = null;
- if (LOGV) Log.v(TAG, "Shutdown of camera complete.");
- }
-
- /** The camera preview callback. Stops capture after the first callback */
- private final class PreviewCallback
- implements android.hardware.Camera.PreviewCallback {
- public void onPreviewFrame(byte [] data, Camera camera) {
- if (LOGV) Log.v(TAG, "PreviewCallback");
- assertNotNull(data);
- Size size = camera.getParameters().getPreviewSize();
- assertEquals(size.width * size.height * 3 / 2, data.length);
- mCamera.stopPreview();
- mPreviewDone.open();
- }
- }
-
- /** A simple SurfaceTexture listener callback, meant to be used together with the camera preview
- * callback */
- private final class SurfaceTextureCallback
- implements android.graphics.SurfaceTexture.OnFrameAvailableListener {
- public void onFrameAvailable(SurfaceTexture surfaceTexture) {
- if (LOGV) Log.v(TAG, "SurfaceTextureCallback");
- mSurfaceTextureDone.open();
- // Assumes preview is stopped elsewhere
- }
- }
-
- /** A burst SurfaceTexture listener callback, used for multiple-frame capture */
- private final class SurfaceTextureBurstCallback
- implements android.graphics.SurfaceTexture.OnFrameAvailableListener {
-
- public void setBurstCount(int burstCount) {
- mBurstCount = burstCount;
- }
-
- public int getBurstCount() {
- return mBurstCount;
- }
-
- public void onFrameAvailable(SurfaceTexture surfaceTexture) {
- if (LOGVV) Log.v(TAG, "SurfaceTextureBurstCallback, frame #" + mBurstCount);
- mBurstCount--;
- if (!mSurfaceTextureCallbackResult) {
- if (mBurstCount <= 0) {
- if (LOGV) Log.v(TAG, "SurfaceTextureBurstCallback stopping preview.");
- mCamera.stopPreview();
- if (LOGVV) Log.v(TAG, "SurfaceTextureBurstCallback preview stopped.");
- mSurfaceTextureCallbackResult = true;
- }
- mSurfaceTextureDone.open();
- }
- }
-
- private int mBurstCount = 0;
- }
-
- /** Waits until surface texture callbacks have fired */
- private boolean waitForSurfaceTextureDone() {
- if (LOGVV) Log.v(TAG, "Wait for surface texture callback");
- if (!mSurfaceTextureDone.block(WAIT_FOR_COMMAND_TO_COMPLETE)) {
- // timeout could be expected or unexpected. The caller will decide.
- Log.v(TAG, "waitForSurfaceTextureDone: timeout");
- return false;
- }
- mSurfaceTextureDone.close();
- return true;
- }
-
- /** Waits until the camera preview callback has fired */
- private boolean waitForPreviewDone() {
- if (LOGVV) Log.v(TAG, "Wait for preview callback");
- if (!mPreviewDone.block(WAIT_FOR_COMMAND_TO_COMPLETE)) {
- // timeout could be expected or unexpected. The caller will decide.
- Log.v(TAG, "waitForPreviewDone: timeout");
- return false;
- }
- mPreviewDone.close();
- return true;
- }
-
- /** @return OpenGL ES major version 1 or 2 or some negative number for error */
- private static int getDetectedVersion() {
- /*
- * Get all the device configurations and check if any of the attributes specify the
- * the EGL_OPENGL_ES2_BIT to determine whether the device supports 2.0.
- */
- EGL10 egl = (EGL10) EGLContext.getEGL();
- EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
- int[] numConfigs = new int[1];
-
- if (egl.eglInitialize(display, null)) {
- try {
- if (egl.eglGetConfigs(display, null, 0, numConfigs)) {
- EGLConfig[] configs = new EGLConfig[numConfigs[0]];
- if (egl.eglGetConfigs(display, configs, numConfigs[0], numConfigs)) {
- int[] value = new int[1];
- for (int i = 0; i < numConfigs[0]; i++) {
- if (egl.eglGetConfigAttrib(display, configs[i],
- EGL10.EGL_RENDERABLE_TYPE, value)) {
- if ((value[0] & EGL_OPENGL_ES2_BIT) == EGL_OPENGL_ES2_BIT) {
- return 2;
- }
- } else {
- Log.w(TAG, "Getting config attribute with "
- + "EGL10#eglGetConfigAttrib failed "
- + "(" + i + "/" + numConfigs[0] + "): "
- + egl.eglGetError());
- }
- }
- return 1;
- } else {
- Log.e(TAG, "Getting configs with EGL10#eglGetConfigs failed: "
- + egl.eglGetError());
- return -1;
- }
- } else {
- Log.e(TAG, "Getting number of configs with EGL10#eglGetConfigs failed: "
- + egl.eglGetError());
- return -2;
- }
- } finally {
- egl.eglTerminate(display);
- }
- } else {
- Log.e(TAG, "Couldn't initialize EGL.");
- return -3;
- }
- }
-
- /** Generic per-camera test interface */
- private interface RunPerCamera {
- void run(int cameraId) throws Exception;
- }
-
- /** Generic camera test runner, to minimize boilerplace duplication */
- private void runForAllCameras(RunPerCamera test) throws Exception {
- /* Currently OpenGL ES 2.0 is supported for this test, so just skip it
- if only 1.0 is available. */
- int glVersion = getDetectedVersion();
- assertTrue(glVersion > 0);
- if (glVersion != 2) {
- Log.w(TAG, "Skipping test because OpenGL ES 2 is not supported");
- return;
- }
-
- /* Make sure the screen stays on while testing - otherwise the OpenGL context may disappear */
- PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
- PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "CameraGLTest");
- wl.acquire();
- try {
- /* Run the requested test per camera */
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- test.run(id);
- }
- } finally {
- wl.release();
- // If an assert failed, camera might still be active. Clean up before next test.
- if (mCamera != null) {
- terminateMessageLooper();
- }
- }
- }
-
- /** Test Camera.setPreviewTexture in conjunction with the standard Camera preview callback */
- @UiThreadTest
- public void testSetPreviewTexturePreviewCallback() throws Exception {
- runForAllCameras(testSetPreviewTexturePreviewCallbackByCamera);
- }
-
- private RunPerCamera testSetPreviewTexturePreviewCallbackByCamera = new RunPerCamera() {
- public void run(int cameraId) throws Exception {
- boolean noTimeout;
- // Check the order: startPreview->setPreviewTexture, with a PreviewCallback as well
- mPreviewDone.close();
- initializeMessageLooper(cameraId);
- mCamera.setPreviewCallback(mPreviewCallback);
- mCamera.startPreview();
- mCamera.setPreviewTexture(mSurfaceTexture);
- noTimeout = waitForPreviewDone();
- assertTrue("Timeout waiting for new preview callback!", noTimeout);
- terminateMessageLooper();
-
- // Check the order: setPreviewTexture->startPreview.
- initializeMessageLooper(cameraId);
- mCamera.setPreviewCallback(mPreviewCallback);
- mCamera.setPreviewTexture(mSurfaceTexture);
- mCamera.startPreview();
- noTimeout = waitForPreviewDone();
- assertTrue("Timeout waiting for new preview callback!", noTimeout);
-
- // Check the order: setting preview display to null->startPreview->
- // setPreviewTexture.
- mCamera.setPreviewCallback(mPreviewCallback);
- mCamera.setPreviewTexture(null);
- mCamera.startPreview();
- mCamera.setPreviewTexture(mSurfaceTexture);
- noTimeout = waitForPreviewDone();
- assertTrue("Timeout waiting for new preview callback!", noTimeout);
- terminateMessageLooper();
- }
- };
-
- /** Test Camera.setPreviewTexture in conjunction with both the standard Camera preview callback,
- and the SurfaceTexture onFrameAvailable callback */
- @UiThreadTest
- public void testSetPreviewTextureBothCallbacks() throws Exception {
- runForAllCameras(testSetPreviewTextureBothCallbacksByCamera);
- }
-
- private RunPerCamera testSetPreviewTextureBothCallbacksByCamera = new RunPerCamera() {
- public void run(int cameraId) throws Exception {
- boolean noTimeout;
- // Check SurfaceTexture callback together with preview callback
- // Check the order: setPreviewTexture->startPreview
- mSurfaceTextureDone.close();
- initializeMessageLooper(cameraId);
- mRenderer.setCameraSizing(mCamera.getParameters().getPreviewSize());
- mCamera.setPreviewCallback(mPreviewCallback);
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureCallback);
- mCamera.setPreviewTexture(mSurfaceTexture);
- mCamera.startPreview();
-
- noTimeout = waitForSurfaceTextureDone();
- assertTrue("Timeout waiting for new frame from SurfaceTexture!", noTimeout);
- noTimeout = waitForPreviewDone();
- assertTrue("Timeout waiting for new preview callback!",noTimeout);
-
- mGLView.requestRender();
- terminateMessageLooper();
-
- // Check the order: startPreview->setPreviewTexture
- mSurfaceTextureDone.close();
- initializeMessageLooper(cameraId);
- mRenderer.setCameraSizing(mCamera.getParameters().getPreviewSize());
- mCamera.setPreviewCallback(mPreviewCallback);
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureCallback);
- mCamera.startPreview();
- mCamera.setPreviewTexture(mSurfaceTexture);
-
- noTimeout = waitForSurfaceTextureDone();
- assertTrue("Timeout waiting for new frame from SurfaceTexture!", noTimeout);
- noTimeout = waitForPreviewDone();
- assertTrue("Timeout waiting for new preview callback!", noTimeout);
-
- mGLView.requestRender();
-
- // Check the order: setting preview to null->startPreview->setPreviewTexture
- mCamera.setPreviewCallback(mPreviewCallback);
- mCamera.setPreviewTexture(null);
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureCallback);
- mCamera.startPreview();
- mCamera.setPreviewTexture(mSurfaceTexture);
- noTimeout = waitForPreviewDone();
- assertTrue(noTimeout);
- terminateMessageLooper();
- }
- };
-
- /** Test Camera.setPreviewTexture in conjunction with just the SurfaceTexture onFrameAvailable callback */
- @UiThreadTest
- public void testSetPreviewTextureTextureCallback() throws Exception {
- runForAllCameras(testSetPreviewTextureTextureCallbackByCamera);
- }
-
- private RunPerCamera testSetPreviewTextureTextureCallbackByCamera = new RunPerCamera() {
- public void run(int cameraId) throws Exception {
- boolean noTimeout;
- // Check that SurfaceTexture callbacks work with no standard
- // preview callback
- mSurfaceTextureCallbackResult = false;
- mSurfaceTextureDone.close();
- initializeMessageLooper(cameraId);
- mSurfaceTextureBurstCallback.setBurstCount(1);
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureBurstCallback);
- mCamera.setPreviewTexture(mSurfaceTexture);
- mRenderer.setCameraSizing(mCamera.getParameters().getPreviewSize());
- mCamera.startPreview();
-
- noTimeout = waitForSurfaceTextureDone();
- mGLView.requestRender();
- assertTrue(noTimeout);
-
- terminateMessageLooper();
- assertTrue(mSurfaceTextureCallbackResult);
-
- // Check that SurfaceTexture callbacks also work with
- // startPreview->setPreviewTexture
- mSurfaceTextureCallbackResult = false;
- mSurfaceTextureDone.close();
- initializeMessageLooper(cameraId);
- mSurfaceTextureBurstCallback.setBurstCount(1);
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureBurstCallback);
- mRenderer.setCameraSizing(mCamera.getParameters().getPreviewSize());
- mCamera.startPreview();
- mCamera.setPreviewTexture(mSurfaceTexture);
-
- noTimeout = waitForSurfaceTextureDone();
- assertTrue(noTimeout);
-
- terminateMessageLooper();
- assertTrue(mSurfaceTextureCallbackResult);
-
- // Check that SurfaceTexture callbacks also work with
- // null->startPreview->setPreviewTexture
- mSurfaceTextureCallbackResult = false;
- mSurfaceTextureDone.close();
- initializeMessageLooper(cameraId);
- mSurfaceTextureBurstCallback.setBurstCount(1);
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureBurstCallback);
- mRenderer.setCameraSizing(mCamera.getParameters().getPreviewSize());
- mCamera.setPreviewTexture(null);
- mCamera.startPreview();
- mCamera.setPreviewTexture(mSurfaceTexture);
-
- noTimeout = waitForSurfaceTextureDone();
- assertTrue(noTimeout);
-
- terminateMessageLooper();
- assertTrue(mSurfaceTextureCallbackResult);
- }
- };
-
- /** Test all preview sizes and framerates along with SurfaceTexture-provided metadata (texture
- * transforms and timestamps) */
- @UiThreadTest
- public void testCameraToSurfaceTextureMetadata() throws Exception {
- runForAllCameras(testCameraToSurfaceTextureMetadataByCamera);
- }
-
- private RunPerCamera testCameraToSurfaceTextureMetadataByCamera = new RunPerCamera() {
- public void run(int cameraId) throws Exception {
- // Number of frames to test over
- int kLoopCount = 100;
- // Ignore timestamp issues before this frame
- int kFirstTestedFrame = 10;
- // Slop in timestamp testing, needed because timestamps are not
- // currently being set by driver-level code so are subject to
- // lots of variability
- float kTestSlopMargin = 30; // ms
-
- boolean noTimeout;
- initializeMessageLooper(cameraId);
- Parameters parameters = mCamera.getParameters();
-
- mSurfaceTexture.setOnFrameAvailableListener(mSurfaceTextureBurstCallback);
- mCamera.setPreviewTexture(mSurfaceTexture);
-
- for (Size size: parameters.getSupportedPreviewSizes()) {
- for (int[] fps: parameters.getSupportedPreviewFpsRange()) {
- if (LOGV) {
- Log.v(TAG, "Testing camera #" + cameraId +
- ", preview size:" + size.width + "x" + size.height +
- ", frame rate range: [" +
- (fps[Parameters.PREVIEW_FPS_MIN_INDEX] / 1000.) + "," +
- (fps[Parameters.PREVIEW_FPS_MAX_INDEX] / 1000.) + "]");
- }
- parameters.setPreviewSize(size.width, size.height);
- parameters.setPreviewFpsRange(fps[Parameters.PREVIEW_FPS_MIN_INDEX],
- fps[Parameters.PREVIEW_FPS_MAX_INDEX]);
- mCamera.setParameters(parameters);
-
- assertEquals(size, mCamera.getParameters().getPreviewSize());
-
- int[] actualFps = new int[2];
- mCamera.getParameters().getPreviewFpsRange(actualFps);
- assertEquals(fps[Parameters.PREVIEW_FPS_MIN_INDEX],
- actualFps[Parameters.PREVIEW_FPS_MIN_INDEX]);
- assertEquals(fps[Parameters.PREVIEW_FPS_MAX_INDEX],
- actualFps[Parameters.PREVIEW_FPS_MAX_INDEX]);
-
- mSurfaceTextureBurstCallback.setBurstCount(kLoopCount);
- mSurfaceTextureCallbackResult = false;
- mSurfaceTextureDone.close();
-
- mRenderer.setCameraSizing(mCamera.getParameters().getPreviewSize());
- if (LOGV) Log.v(TAG, "Starting preview");
- mCamera.startPreview();
- if (LOGVV) Log.v(TAG, "Preview started");
-
- long[] timestamps = new long[kLoopCount];
- for (int i = 0; i < kLoopCount; i++) {
- noTimeout = waitForSurfaceTextureDone();
- assertTrue("Timeout waiting for frame " + i +
- " (burst callback thinks " +
- (kLoopCount - mSurfaceTextureBurstCallback.getBurstCount()) +
- ")! (Size " + size.width + "x" + size.height + ", fps [" +
- (fps[Parameters.PREVIEW_FPS_MIN_INDEX] / 1000.) + ", " +
- (fps[Parameters.PREVIEW_FPS_MAX_INDEX] / 1000.) + "])",
- noTimeout);
-
- if (LOGVV) Log.v(TAG, "Frame #" + i + " completed");
- // Draw the frame (and update the SurfaceTexture)
- mGLView.requestRender();
- // Wait until frame is drawn, so that the SurfaceTexture has new
- // metadata
- noTimeout = mRenderer.waitForDrawDone();
- assertTrue(noTimeout);
-
- // Store timestamps for later
- timestamps[i] = mSurfaceTexture.getTimestamp();
- // Verify that the surfaceTexture transform has at least one non-zero
- // entry
- float[] transform = new float[16];
- mSurfaceTexture.getTransformMatrix(transform);
- boolean nonZero = false;
- for (int k = 0; k < 16; k++) {
- if (transform[k] != 0.f) {
- nonZero = true;
- break;
- }
- }
- assertTrue(nonZero);
- }
- assertTrue(mSurfaceTextureCallbackResult);
-
- float expectedMaxFrameDurationMs = 1000.f * 1000.f /
- fps[Parameters.PREVIEW_FPS_MIN_INDEX];
- float slopMaxFrameDurationMs = expectedMaxFrameDurationMs +
- kTestSlopMargin;
- float expectedMinFrameDurationMs = 1000.f * 1000.f /
- fps[Parameters.PREVIEW_FPS_MAX_INDEX];
- float slopMinFrameDurationMs = expectedMinFrameDurationMs -
- kTestSlopMargin;
-
- for (int i = kFirstTestedFrame; i < kLoopCount; i++) {
- float frameDurationMs = (timestamps[i] - timestamps[i - 1]) / 1000000.f;
- if (LOGVV) {
- Log.v(TAG, "Frame " + i + " duration: " + frameDurationMs +
- " ms, expecting [" + expectedMinFrameDurationMs + "," +
- expectedMaxFrameDurationMs + "], slop range [" +
- slopMinFrameDurationMs + "," + slopMaxFrameDurationMs + "].");
- }
- assertTrue("Frame " + i + " duration out of bounds! ("+
- frameDurationMs + " ms, expecting [" +
- slopMinFrameDurationMs + "," +
- slopMaxFrameDurationMs + "] ms)",
- (frameDurationMs > slopMinFrameDurationMs) &&
- (frameDurationMs < slopMaxFrameDurationMs) );
- }
- }
- }
- terminateMessageLooper();
- } // void run(int cameraId)
- };
-
- /** Basic OpenGL ES 2.0 renderer to draw SurfaceTexture-sourced frames to the screen */
- private class Renderer implements GLSurfaceView.Renderer {
- public Renderer() {
- mTriangleVertices =
- ByteBuffer.allocateDirect(mTriangleVerticesData.length * FLOAT_SIZE_BYTES).
- order(ByteOrder.nativeOrder()).asFloatBuffer();
- mTriangleVertices.put(mTriangleVerticesData).position(0);
-
- Matrix.setIdentityM(mSTMatrix, 0);
- Matrix.setIdentityM(mMMatrix, 0);
-
- mTextureID = 0;
- }
-
- public void setCameraSizing(Camera.Size previewSize) {
- mCameraRatio = (float)previewSize.width/previewSize.height;
- }
-
- public boolean waitForDrawDone() {
- if (!mDrawDone.block(WAIT_FOR_COMMAND_TO_COMPLETE) ) {
- // timeout could be expected or unexpected. The caller will decide.
- Log.e(TAG, "waitForDrawDone: timeout");
- return false;
- }
- mDrawDone.close();
- return true;
- }
-
- private final ConditionVariable mDrawDone = new ConditionVariable();
-
- public void onDrawFrame(GL10 glUnused) {
- if (LOGVV) Log.v(TAG, "onDrawFrame()");
- if (CameraGLTest.this.mSurfaceTexture != null) {
- CameraGLTest.this.mSurfaceTexture.updateTexImage();
- CameraGLTest.this.mSurfaceTexture.getTransformMatrix(mSTMatrix);
- mDrawDone.open();
- }
-
- // Ignore the passed-in GL10 interface, and use the GLES20
- // class's static methods instead.
- GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
- GLES20.glUseProgram(mProgram);
- checkGlError("glUseProgram");
-
- GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
- GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
-
- mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
- GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
- TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
- checkGlError("glVertexAttribPointer maPosition");
- GLES20.glEnableVertexAttribArray(maPositionHandle);
- checkGlError("glEnableVertexAttribArray maPositionHandle");
-
- mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
- GLES20.glVertexAttribPointer(maTextureHandle, 3, GLES20.GL_FLOAT, false,
- TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
- checkGlError("glVertexAttribPointer maTextureHandle");
- GLES20.glEnableVertexAttribArray(maTextureHandle);
- checkGlError("glEnableVertexAttribArray maTextureHandle");
-
- Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0);
- Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
-
- GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
- GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);
- GLES20.glUniform1f(muCRatioHandle, mCameraRatio);
-
- GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
- checkGlError("glDrawArrays");
- }
-
- public void onSurfaceChanged(GL10 glUnused, int width, int height) {
- if (LOGV) Log.v(TAG, "onSurfaceChanged()");
- // Ignore the passed-in GL10 interface, and use the GLES20
- // class's static methods instead.
- GLES20.glViewport(0, 0, width, height);
- mRatio = (float) width / height;
- Matrix.frustumM(mProjMatrix, 0, -mRatio, mRatio, -1, 1, 3, 7);
- }
-
- public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
- if (LOGV) Log.v(TAG, "onSurfaceCreated()");
- // Ignore the passed-in GL10 interface, and use the GLES20
- // class's static methods instead.
-
- /* Set up shaders and handles to their variables */
- mProgram = createProgram(mVertexShader, mFragmentShader);
- if (mProgram == 0) {
- return;
- }
- maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
- checkGlError("glGetAttribLocation aPosition");
- if (maPositionHandle == -1) {
- throw new RuntimeException("Could not get attrib location for aPosition");
- }
- maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
- checkGlError("glGetAttribLocation aTextureCoord");
- if (maTextureHandle == -1) {
- throw new RuntimeException("Could not get attrib location for aTextureCoord");
- }
-
- muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
- checkGlError("glGetUniformLocation uMVPMatrix");
- if (muMVPMatrixHandle == -1) {
- throw new RuntimeException("Could not get attrib location for uMVPMatrix");
- }
-
- muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
- checkGlError("glGetUniformLocation uSTMatrix");
- if (muMVPMatrixHandle == -1) {
- throw new RuntimeException("Could not get attrib location for uSTMatrix");
- }
-
- muCRatioHandle = GLES20.glGetUniformLocation(mProgram, "uCRatio");
- checkGlError("glGetUniformLocation uCRatio");
- if (muMVPMatrixHandle == -1) {
- throw new RuntimeException("Could not get attrib location for uCRatio");
- }
-
- /*
- * Create our texture. This has to be done each time the
- * surface is created.
- */
-
- int[] textures = new int[1];
- GLES20.glGenTextures(1, textures, 0);
-
- mTextureID = textures[0];
- GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
- checkGlError("glBindTexture mTextureID");
-
- // Can't do mipmapping with camera source
- GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
- GLES20.GL_NEAREST);
- GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
- GLES20.GL_LINEAR);
- // Clamp to edge is the only option
- GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
- GLES20.GL_CLAMP_TO_EDGE);
- GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
- GLES20.GL_CLAMP_TO_EDGE);
- checkGlError("glTexParameteri mTextureID");
-
- Matrix.setLookAtM(mVMatrix, 0, 0, 0, 4f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
- }
-
- public int getTextureID() {
- return mTextureID;
- }
-
- private int loadShader(int shaderType, String source) {
- int shader = GLES20.glCreateShader(shaderType);
- if (shader != 0) {
- GLES20.glShaderSource(shader, source);
- GLES20.glCompileShader(shader);
- int[] compiled = new int[1];
- GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
- if (compiled[0] == 0) {
- Log.e(TAG, "Could not compile shader " + shaderType + ":");
- Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
- GLES20.glDeleteShader(shader);
- shader = 0;
- }
- }
- return shader;
- }
-
- private int createProgram(String vertexSource, String fragmentSource) {
- int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
- if (vertexShader == 0) {
- return 0;
- }
- int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
- if (pixelShader == 0) {
- return 0;
- }
-
- int program = GLES20.glCreateProgram();
- if (program != 0) {
- GLES20.glAttachShader(program, vertexShader);
- checkGlError("glAttachShader");
- GLES20.glAttachShader(program, pixelShader);
- checkGlError("glAttachShader");
- GLES20.glLinkProgram(program);
- int[] linkStatus = new int[1];
- GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
- if (linkStatus[0] != GLES20.GL_TRUE) {
- Log.e(TAG, "Could not link program: ");
- Log.e(TAG, GLES20.glGetProgramInfoLog(program));
- GLES20.glDeleteProgram(program);
- program = 0;
- }
- }
- return program;
- }
-
- private void checkGlError(String op) {
- int error;
- while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
- Log.e(TAG, op + ": glError " + error);
- throw new RuntimeException(op + ": glError " + error);
- }
- }
-
- private static final int FLOAT_SIZE_BYTES = 4;
- private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
- private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
- private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
- private final float[] mTriangleVerticesData = {
- // X, Y, Z, U, V
- -1.0f, -1.0f, 0, 0.f, 0.f,
- 1.0f, -1.0f, 0, 1.f, 0.f,
- -1.0f, 1.0f, 0, 0.f, 1.f,
- 1.0f, 1.0f, 0, 1.f, 1.f,
- };
-
- private FloatBuffer mTriangleVertices;
-
- private final String mVertexShader =
- "uniform mat4 uMVPMatrix;\n" +
- "uniform mat4 uSTMatrix;\n" +
- "uniform float uCRatio;\n" +
- "attribute vec4 aPosition;\n" +
- "attribute vec4 aTextureCoord;\n" +
- "varying vec2 vTextureCoord;\n" +
- "void main() {\n" +
- " gl_Position = vec4(uCRatio,1,1,1) * uMVPMatrix * aPosition;\n" +
- " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
- "}\n";
-
- private final String mFragmentShader =
- "#extension GL_OES_EGL_image_external : require\n" +
- "precision mediump float;\n" +
- "varying vec2 vTextureCoord;\n" +
- "uniform samplerExternalOES sTexture;\n" +
- "void main() {\n" +
- " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
- "}\n";
-
- private float[] mMVPMatrix = new float[16];
- private float[] mProjMatrix = new float[16];
- private float[] mMMatrix = new float[16];
- private float[] mVMatrix = new float[16];
- private float[] mSTMatrix = new float[16];
-
- private int mProgram;
- private int mTextureID;
- private int muMVPMatrixHandle;
- private int muSTMatrixHandle;
- private int muCRatioHandle;
- private int maPositionHandle;
- private int maTextureHandle;
-
- private float mRatio = 1.0f;
- private float mCameraRatio = 1.0f;
-
- private Context mContext;
- private static final String TAG = "CameraGLTest.Renderer";
-
- // Magic key
- private static final int GL_TEXTURE_EXTERNAL_OES = 0x8D65;
- }
-
-}
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
index 309bfc7..60b8459 100644
--- a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
@@ -16,20 +16,21 @@
package android.hardware.cts;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
-import android.graphics.Rect;
import android.hardware.Camera;
-import android.hardware.Camera.Area;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.ErrorCallback;
-import android.hardware.Camera.Face;
-import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.Parameters;
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;
@@ -42,11 +43,6 @@ import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
import android.view.SurfaceHolder;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -68,29 +64,17 @@ public class CameraTest extends ActivityInstrumentationTestCase2startPreview.
initializeMessageLooper(cameraId);
- mPreviewCallbackResult = PREVIEW_CALLBACK_NOT_RECEIVED;
+ mPreviewCallbackResult = false;
mCamera.setOneShotPreviewCallback(mPreviewCallback);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
waitForPreviewDone();
mCamera.stopPreview();
- assertEquals(PREVIEW_CALLBACK_RECEIVED, mPreviewCallbackResult);
+ assertTrue(mPreviewCallbackResult);
// Check the order: setting preview display to null->startPreview->
// setPreviewDisplay.
- mPreviewCallbackResult = PREVIEW_CALLBACK_NOT_RECEIVED;
+ mPreviewCallbackResult = false;
mCamera.setOneShotPreviewCallback(mPreviewCallback);
mCamera.setPreviewDisplay(null);
mCamera.startPreview();
mCamera.setPreviewDisplay(holder);
waitForPreviewDone();
terminateMessageLooper();
- assertEquals(PREVIEW_CALLBACK_RECEIVED, mPreviewCallbackResult);
+ assertTrue(mPreviewCallbackResult);
}
@TestTargetNew(
@@ -558,13 +526,16 @@ public class CameraTest extends ActivityInstrumentationTestCase2 previewSizes = parameters.getSupportedPreviewSizes();
@@ -648,9 +616,7 @@ public class CameraTest extends ActivityInstrumentationTestCase2= 2);
- assertTrue(previewFormats.contains(ImageFormat.NV21));
- assertTrue(previewFormats.contains(ImageFormat.YV12));
+ assertTrue(previewFormats != null && previewFormats.size() != 0);
assertTrue(pictureFormats != null && pictureFormats.size() != 0);
assertTrue(frameRates != null && frameRates.size() != 0);
assertTrue(focusModes != null && focusModes.size() != 0);
@@ -728,45 +694,6 @@ public class CameraTest extends ActivityInstrumentationTestCase2 0);
checkExposureCompensation(parameters);
- checkPreferredPreviewSizeForVideo(parameters);
- }
-
- private void checkPreferredPreviewSizeForVideo(Parameters parameters) {
- List 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 previewSizes = parameters.getSupportedPreviewSizes();
- assertNotNull(previewSizes);
- assertTrue(previewSizes.size() > 0);
- assertTrue(previewSizes.contains(preferredPreviewSize));
- }
}
private void checkExposureCompensation(Parameters parameters) {
@@ -810,13 +737,12 @@ public class CameraTest extends ActivityInstrumentationTestCase2 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;
- }
- }
- }
- }
-
- private void recordVideo(CamcorderProfile profile,
- SurfaceHolder holder) throws Exception {
+ private void recordVideo(Size size, SurfaceHolder surfaceHolder) 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.setProfile(profile);
+ recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setOutputFile("/dev/null");
- recorder.setPreviewDisplay(holder.getSurface());
+ recorder.setVideoSize(size.width, size.height);
+ recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
+ recorder.setPreviewDisplay(surfaceHolder.getSurface());
recorder.prepare();
recorder.start();
-
- // Apps can use the camera after start since API level 13.
- Parameters parameters = mCamera.getParameters();
- if (parameters.isZoomSupported()) {
- if (parameters.getMaxZoom() > 0) {
- parameters.setZoom(1);
- mCamera.setParameters(parameters);
- parameters.setZoom(0);
- mCamera.setParameters(parameters);
- }
- }
- if (parameters.isSmoothZoomSupported()) {
- if (parameters.getMaxZoom() > 0) {
- ZoomListener zoomListener = new ZoomListener();
- mCamera.setZoomChangeListener(zoomListener);
- mCamera.startSmoothZoom(1);
- assertTrue(zoomListener.mZoomDone.block(1000));
- }
- }
-
- try {
- mCamera.unlock();
- fail("unlock should not succeed during recording.");
- } catch(RuntimeException e) {
- // expected
- }
-
- Thread.sleep(2000);
+ Thread.sleep(5000);
recorder.stop();
} finally {
recorder.release();
@@ -1094,11 +962,9 @@ public class CameraTest extends ActivityInstrumentationTestCase2 1) {
- zoomListener.mValues.clear();
- zoomListener.mStopped.clear();
+ zoomListener.mValues = new ArrayList();
+ zoomListener.mStopped = false;
Log.e(TAG, "zoomListener.mStopped = " + zoomListener.mStopped);
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());
- for(int i = 0; i < zoomListener.mValues.size(); i++) {
- int value = zoomListener.mValues.get(i);
- boolean stopped = zoomListener.mStopped.get(i);
- // Make sure we get all the zoom values in order.
- assertEquals(maxZoom - 1 - i, value);
- // All "stopped" except the last should be false.
- assertEquals(i == zoomListener.mValues.size() - 1, stopped);
+ int i = maxZoom - 1;
+ for(Integer value: zoomListener.mValues) {
+ assertEquals(i, value.intValue());
+ i--;
}
}
@@ -1323,8 +1151,8 @@ public class CameraTest extends ActivityInstrumentationTestCase2();
+ zoomListener.mStopped = false;
zoomListener.mZoomDone.close();
parameters.setZoom(0);
mCamera.setParameters(parameters);
@@ -1332,31 +1160,22 @@ public class CameraTest extends ActivityInstrumentationTestCase2 mValues = new ArrayList();
- public ArrayList mStopped = new ArrayList();
+ public boolean mStopped;
public final ConditionVariable mZoomDone = new ConditionVariable();
public void onZoomChange(int value, boolean stopped, Camera camera) {
mValues.add(value);
- mStopped.add(stopped);
+ assertFalse(mStopped);
+ mStopped = stopped;
if (stopped) {
mZoomDone.open();
}
@@ -1374,6 +1193,7 @@ public class CameraTest extends ActivityInstrumentationTestCase2 areas) {
- Parameters parameters = mCamera.getParameters();
- parameters.setMeteringAreas(areas);
- mCamera.setParameters(parameters);
- parameters = mCamera.getParameters();
- assertEquals(areas, parameters.getMeteringAreas());
- }
-
- private void testInvalidMeteringAreas(ArrayList areas) {
- Parameters parameters = mCamera.getParameters();
- List originalAreas = parameters.getMeteringAreas();
- try {
- parameters.setMeteringAreas(areas);
- mCamera.setParameters(parameters);
- fail("Should throw exception when metering area is invalid.");
- } catch (RuntimeException e) {
- parameters = mCamera.getParameters();
- assertEquals(originalAreas, parameters.getMeteringAreas());
- }
- }
-
- // Apps should be able to call startPreview in jpeg callback.
- @UiThreadTest
- public void testJpegCallbackStartPreview() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- testJpegCallbackStartPreviewByCamera(id);
- }
- }
-
- private void testJpegCallbackStartPreviewByCamera(int cameraId) throws Exception {
- initializeMessageLooper(cameraId);
- mCamera.startPreview();
- mCamera.takePicture(mShutterCallback, mRawPictureCallback, new JpegStartPreviewCallback());
- waitForSnapshotDone();
- terminateMessageLooper();
- assertTrue(mJpegPictureCallbackResult);
- }
-
- private final class JpegStartPreviewCallback implements PictureCallback {
- public void onPictureTaken(byte[] rawData, Camera camera) {
- try {
- camera.startPreview();
- mJpegPictureCallbackResult = true;
- } catch (Exception e) {
- }
- mSnapshotDone.open();
- }
- }
-
- @UiThreadTest
- public void testRecordingHint() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- testRecordingHintByCamera(id);
- }
- }
-
- private void testRecordingHintByCamera(int cameraId) throws Exception {
- initializeMessageLooper(cameraId);
- Parameters parameters = mCamera.getParameters();
-
- SurfaceHolder holder = getActivity().getSurfaceView().getHolder();
- CamcorderProfile profile = CamcorderProfile.get(cameraId,
- CamcorderProfile.QUALITY_LOW);
-
- setPreviewSizeByProfile(parameters, profile);
-
- // Test recording videos and taking pictures when the hint is off and on.
- for (int i = 0; i < 2; i++) {
- parameters.setRecordingHint(i == 0 ? false : true);
- mCamera.setParameters(parameters);
- mCamera.startPreview();
- recordVideoSimple(profile, holder);
- mCamera.takePicture(mShutterCallback, mRawPictureCallback, mJpegPictureCallback);
- waitForSnapshotDone();
- assertTrue(mJpegPictureCallbackResult);
- }
-
- // Can change recording hint when the preview is active.
- mCamera.startPreview();
- parameters.setRecordingHint(false);
- mCamera.setParameters(parameters);
- parameters.setRecordingHint(true);
- mCamera.setParameters(parameters);
- terminateMessageLooper();
- }
-
- private void recordVideoSimple(CamcorderProfile profile,
- SurfaceHolder holder) throws Exception {
- mCamera.unlock();
- MediaRecorder recorder = new MediaRecorder();
- try {
- recorder.setCamera(mCamera);
- recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
- recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
- recorder.setProfile(profile);
- recorder.setOutputFile("/dev/null");
- recorder.setPreviewDisplay(holder.getSurface());
- recorder.prepare();
- recorder.start();
- Thread.sleep(2000);
- recorder.stop();
- } finally {
- recorder.release();
- mCamera.lock();
- }
- }
-
- @UiThreadTest
- public void testAutoExposureLock() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- initializeMessageLooper(id);
- Parameters parameters = mCamera.getParameters();
- boolean aeLockSupported = parameters.isAutoExposureLockSupported();
- if (aeLockSupported) {
- testLockCommon(AUTOEXPOSURE_LOCK);
- testLockAdditionalAE();
- }
- terminateMessageLooper();
- }
- }
-
- @UiThreadTest
- public void testAutoWhiteBalanceLock() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- initializeMessageLooper(id);
- Parameters parameters = mCamera.getParameters();
- boolean awbLockSupported = parameters.isAutoWhiteBalanceLockSupported();
- if (awbLockSupported) {
- testLockCommon(AUTOWHITEBALANCE_LOCK);
- testLockAdditionalAWB();
- }
- terminateMessageLooper();
- }
- }
-
- @UiThreadTest
- public void test3ALockInteraction() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- initializeMessageLooper(id);
- Parameters parameters = mCamera.getParameters();
- boolean locksSupported =
- parameters.isAutoWhiteBalanceLockSupported() &&
- parameters.isAutoExposureLockSupported();
- if (locksSupported) {
- testLockInteractions();
- }
- terminateMessageLooper();
- }
- }
-
- private void testLockCommon(int type) {
- // Verify lock is not set on open()
- assert3ALockState("Lock not released after open()", type, false);
-
- // Verify lock can be set, unset before preview
- set3ALockState(true, type);
- assert3ALockState("Lock could not be set before 1st preview!",
- type, true);
-
- set3ALockState(false, type);
- assert3ALockState("Lock could not be unset before 1st preview!",
- type, false);
-
- // Verify preview start does not set lock
- mCamera.startPreview();
- assert3ALockState("Lock state changed by preview start!", type, false);
-
- // Verify lock can be set, unset during preview
- set3ALockState(true, type);
- assert3ALockState("Lock could not be set during preview!", type, true);
-
- set3ALockState(false, type);
- assert3ALockState("Lock could not be unset during preview!",
- type, false);
-
- // Verify lock is not cleared by stop preview
- set3ALockState(true, type);
- mCamera.stopPreview();
- assert3ALockState("Lock was cleared by stopPreview!", type, true);
-
- // Verify that preview start does not clear lock
- set3ALockState(true, type);
- mCamera.startPreview();
- assert3ALockState("Lock state changed by preview start!", type, true);
-
- // Verify that taking a picture does not clear the lock
- set3ALockState(true, type);
- mCamera.takePicture(mShutterCallback, mRawPictureCallback,
- mJpegPictureCallback);
- waitForSnapshotDone();
- assert3ALockState("Lock state was cleared by takePicture!", type, true);
-
- mCamera.startPreview();
- Parameters parameters = mCamera.getParameters();
- for (String focusMode: parameters.getSupportedFocusModes()) {
- // TODO: Test this for other focus modes as well, once agreement is
- // reached on which ones it should apply to
- if (!Parameters.FOCUS_MODE_AUTO.equals(focusMode) ) {
- continue;
- }
-
- parameters.setFocusMode(focusMode);
- mCamera.setParameters(parameters);
-
- // Verify that autoFocus does not change the lock
- set3ALockState(false, type);
- mCamera.autoFocus(mAutoFocusCallback);
- assert3ALockState("Lock was set by autoFocus in mode: " + focusMode, type, false);
- assertTrue(waitForFocusDone());
- assert3ALockState("Lock was set by autoFocus in mode: " + focusMode, type, false);
-
- // Verify that cancelAutoFocus does not change the lock
- mCamera.cancelAutoFocus();
- assert3ALockState("Lock was set by cancelAutoFocus!", type, false);
-
- // Verify that autoFocus does not change the lock
- set3ALockState(true, type);
- mCamera.autoFocus(mAutoFocusCallback);
- assert3ALockState("Lock was cleared by autoFocus in mode: " + focusMode, type, true);
- assertTrue(waitForFocusDone());
- assert3ALockState("Lock was cleared by autoFocus in mode: " + focusMode, type, true);
-
- // Verify that cancelAutoFocus does not change the lock
- mCamera.cancelAutoFocus();
- assert3ALockState("Lock was cleared by cancelAutoFocus!", type, true);
- }
- mCamera.stopPreview();
- }
-
- private void testLockAdditionalAE() {
- // Verify that exposure compensation can be used while
- // AE lock is active
- mCamera.startPreview();
- Parameters parameters = mCamera.getParameters();
- parameters.setAutoExposureLock(true);
- mCamera.setParameters(parameters);
- parameters.setExposureCompensation(parameters.getMaxExposureCompensation());
- mCamera.setParameters(parameters);
- parameters = mCamera.getParameters();
- assertTrue("Could not adjust exposure compensation with AE locked!",
- parameters.getExposureCompensation() ==
- parameters.getMaxExposureCompensation() );
-
- parameters.setExposureCompensation(parameters.getMinExposureCompensation());
- mCamera.setParameters(parameters);
- parameters = mCamera.getParameters();
- assertTrue("Could not adjust exposure compensation with AE locked!",
- parameters.getExposureCompensation() ==
- parameters.getMinExposureCompensation() );
- mCamera.stopPreview();
- }
-
- private void testLockAdditionalAWB() {
- // Verify that switching AWB modes clears AWB lock
- mCamera.startPreview();
- Parameters parameters = mCamera.getParameters();
- String firstWb = null;
- for ( String wbMode: parameters.getSupportedWhiteBalance() ) {
- if (firstWb == null) {
- firstWb = wbMode;
- }
- parameters.setWhiteBalance(firstWb);
- mCamera.setParameters(parameters);
- parameters.setAutoWhiteBalanceLock(true);
- mCamera.setParameters(parameters);
-
- parameters.setWhiteBalance(wbMode);
- mCamera.setParameters(parameters);
-
- assert3ALockState("Changing WB mode did not clear AWB lock!",
- AUTOWHITEBALANCE_LOCK, false);
- }
- mCamera.stopPreview();
- }
-
- private void testLockInteractions() {
- // Verify that toggling AE does not change AWB lock state
- set3ALockState(false, AUTOWHITEBALANCE_LOCK);
- set3ALockState(false, AUTOEXPOSURE_LOCK);
-
- set3ALockState(true, AUTOEXPOSURE_LOCK);
- assert3ALockState("Changing AE lock affected AWB lock!",
- AUTOWHITEBALANCE_LOCK, false);
-
- set3ALockState(false, AUTOEXPOSURE_LOCK);
- assert3ALockState("Changing AE lock affected AWB lock!",
- AUTOWHITEBALANCE_LOCK, false);
-
- set3ALockState(true, AUTOWHITEBALANCE_LOCK);
-
- set3ALockState(true, AUTOEXPOSURE_LOCK);
- assert3ALockState("Changing AE lock affected AWB lock!",
- AUTOWHITEBALANCE_LOCK, true);
-
- set3ALockState(false, AUTOEXPOSURE_LOCK);
- assert3ALockState("Changing AE lock affected AWB lock!",
- AUTOWHITEBALANCE_LOCK, true);
-
- // Verify that toggling AWB does not change AE lock state
- set3ALockState(false, AUTOWHITEBALANCE_LOCK);
- set3ALockState(false, AUTOEXPOSURE_LOCK);
-
- set3ALockState(true, AUTOWHITEBALANCE_LOCK);
- assert3ALockState("Changing AWB lock affected AE lock!",
- AUTOEXPOSURE_LOCK, false);
-
- set3ALockState(false, AUTOWHITEBALANCE_LOCK);
- assert3ALockState("Changing AWB lock affected AE lock!",
- AUTOEXPOSURE_LOCK, false);
-
- set3ALockState(true, AUTOEXPOSURE_LOCK);
-
- set3ALockState(true, AUTOWHITEBALANCE_LOCK);
- assert3ALockState("Changing AWB lock affected AE lock!",
- AUTOEXPOSURE_LOCK, true);
-
- set3ALockState(false, AUTOWHITEBALANCE_LOCK);
- assert3ALockState("Changing AWB lock affected AE lock!",
- AUTOEXPOSURE_LOCK, true);
- }
-
- private void assert3ALockState(String msg, int type, boolean state) {
- Parameters parameters = mCamera.getParameters();
- switch (type) {
- case AUTOEXPOSURE_LOCK:
- assertTrue(msg, state == parameters.getAutoExposureLock());
- break;
- case AUTOWHITEBALANCE_LOCK:
- assertTrue(msg, state == parameters.getAutoWhiteBalanceLock());
- break;
- default:
- assertTrue("Unknown lock type " + type, false);
- break;
- }
- }
-
- private void set3ALockState(boolean state, int type) {
- Parameters parameters = mCamera.getParameters();
- switch (type) {
- case AUTOEXPOSURE_LOCK:
- parameters.setAutoExposureLock(state);
- break;
- case AUTOWHITEBALANCE_LOCK:
- parameters.setAutoWhiteBalanceLock(state);
- break;
- default:
- assertTrue("Unknown lock type "+type, false);
- break;
- }
- mCamera.setParameters(parameters);
- }
-
- @UiThreadTest
- public void testFaceDetection() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- testFaceDetectionByCamera(id);
- }
- }
-
- private void testFaceDetectionByCamera(int cameraId) throws Exception {
- final int FACE_DETECTION_TEST_DURATION = 3000;
- initializeMessageLooper(cameraId);
- mCamera.startPreview();
- Parameters parameters = mCamera.getParameters();
- int maxNumOfFaces = parameters.getMaxNumDetectedFaces();
- assertTrue(maxNumOfFaces >= 0);
- if (maxNumOfFaces == 0) {
- try {
- mCamera.startFaceDetection();
- fail("Should throw an exception if face detection is not supported.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- terminateMessageLooper();
- return;
- }
-
- mCamera.startFaceDetection();
- try {
- mCamera.startFaceDetection();
- fail("Starting face detection twice should throw an exception");
- } catch (RuntimeException e) {
- // expected
- }
- FaceListener listener = new FaceListener();
- mCamera.setFaceDetectionListener(listener);
- // Sleep some time so the camera has chances to detect faces.
- Thread.sleep(FACE_DETECTION_TEST_DURATION);
- // The face callback runs in another thread. Release the camera and stop
- // the looper. So we do not access the face array from two threads at
- // the same time.
- terminateMessageLooper();
-
- // Check if the optional fields are supported.
- boolean optionalFieldSupported = false;
- Face firstFace = null;
- for (Face[] faces: listener.mFacesArray) {
- for (Face face: faces) {
- if (face != null) firstFace = face;
- }
- }
- if (firstFace != null) {
- if (firstFace.id != -1 || firstFace.leftEye != null
- || firstFace.rightEye != null || firstFace.mouth != null) {
- optionalFieldSupported = true;
- }
- }
-
- // Verify the faces array.
- for (Face[] faces: listener.mFacesArray) {
- testFaces(faces, maxNumOfFaces, optionalFieldSupported);
- }
- }
-
- private class FaceListener implements FaceDetectionListener {
- public ArrayList mFacesArray = new ArrayList();
-
- @Override
- public void onFaceDetection(Face[] faces, Camera camera) {
- mFacesArray.add(faces);
- }
- }
-
- private void testFaces(Face[] faces, int maxNumOfFaces,
- boolean optionalFieldSupported) {
- Rect bounds = new Rect(-1000, -1000, 1000, 1000);
- assertNotNull(faces);
- assertTrue(faces.length <= maxNumOfFaces);
- for (int i = 0; i < faces.length; i++) {
- Face face = faces[i];
- Rect rect = face.rect;
- // Check the bounds.
- assertNotNull(rect);
- assertTrue(rect.width() > 0);
- assertTrue(rect.height() > 0);
- assertTrue("Coordinates out of bounds. rect=" + rect,
- bounds.contains(rect) || Rect.intersects(bounds, rect));
-
- // Check the score.
- assertTrue(face.score >= 1 && face.score <= 100);
-
- // Check id, left eye, right eye, and the mouth.
- // Optional fields should be all valid or none of them.
- if (!optionalFieldSupported) {
- assertEquals(-1, face.id);
- assertNull(face.leftEye);
- assertNull(face.rightEye);
- assertNull(face.mouth);
- } else {
- assertTrue(face.id != -1);
- assertNotNull(face.leftEye);
- assertNotNull(face.rightEye);
- assertNotNull(face.mouth);
- assertTrue(bounds.contains(face.leftEye.x, face.leftEye.y));
- assertTrue(bounds.contains(face.rightEye.x, face.rightEye.y));
- assertTrue(bounds.contains(face.mouth.x, face.mouth.y));
- // ID should be unique.
- if (i != faces.length - 1) {
- assertTrue(face.id != faces[i + 1].id);
- }
- }
- }
- }
-
- @UiThreadTest
- public void testVideoSnapshot() throws Exception {
- int nCameras = Camera.getNumberOfCameras();
- for (int id = 0; id < nCameras; id++) {
- Log.v(TAG, "Camera id=" + id);
- testVideoSnapshotByCamera(id);
- }
- }
-
- private void testVideoSnapshotByCamera(int cameraId) throws Exception {
- initializeMessageLooper(cameraId);
- Camera.Parameters parameters = mCamera.getParameters();
- if (!parameters.isVideoSnapshotSupported()) return;
-
- SurfaceHolder holder = getActivity().getSurfaceView().getHolder();
-
- // Set the preview size.
- CamcorderProfile profile = CamcorderProfile.get(cameraId,
- CamcorderProfile.QUALITY_LOW);
- setPreviewSizeByProfile(parameters, profile);
-
- // Set the biggest picture size.
- Size biggestSize = mCamera.new Size(-1, -1);
- for (Size size: parameters.getSupportedPictureSizes()) {
- if (biggestSize.width < size.width) {
- biggestSize = size;
- }
- }
- parameters.setPictureSize(biggestSize.width, biggestSize.height);
-
- mCamera.setParameters(parameters);
- mCamera.startPreview();
- mCamera.unlock();
- MediaRecorder recorder = new MediaRecorder();
- try {
- recorder.setCamera(mCamera);
- recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
- recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
- recorder.setProfile(profile);
- recorder.setOutputFile("/dev/null");
- recorder.setPreviewDisplay(holder.getSurface());
- recorder.prepare();
- recorder.start();
- testTakePictureByCamera();
- testJpegExifByCamera(true);
- testJpegThumbnailSizeByCamera(true);
- recorder.stop();
- } finally {
- recorder.release();
- mCamera.lock();
- }
- terminateMessageLooper();
- }
}
diff --git a/tests/tests/jni/libjnitest/Android.mk b/tests/tests/jni/libjnitest/Android.mk
index d7d1bad..84856b3 100644
--- a/tests/tests/jni/libjnitest/Android.mk
+++ b/tests/tests/jni/libjnitest/Android.mk
@@ -25,6 +25,9 @@ LOCAL_MODULE := libjnitest
# Don't include this package in any configuration by default.
LOCAL_MODULE_TAGS := optional
+# This isn't part of the system, so don't prelink it.
+LOCAL_PRELINK_MODULE := false
+
LOCAL_SRC_FILES := \
android_jni_cts_InstanceNonce.c \
android_jni_cts_JniCTest.c \
diff --git a/tests/tests/jni/src/android/jni/cts/InstanceNonce.java b/tests/tests/jni/src/android/jni/cts/InstanceNonce.java
index e1a7dea..a5bb01d 100644
--- a/tests/tests/jni/src/android/jni/cts/InstanceNonce.java
+++ b/tests/tests/jni/src/android/jni/cts/InstanceNonce.java
@@ -22,9 +22,7 @@ package android.jni.cts;
*/
public class InstanceNonce {
static {
- if (!JniTestCase.isCpuAbiNone()) {
- System.loadLibrary("jnitest");
- }
+ System.loadLibrary("jnitest");
}
/**
diff --git a/tests/tests/jni/src/android/jni/cts/JniCTest.java b/tests/tests/jni/src/android/jni/cts/JniCTest.java
index eb14504..950b534 100644
--- a/tests/tests/jni/src/android/jni/cts/JniCTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniCTest.java
@@ -16,17 +16,16 @@
package android.jni.cts;
+import junit.framework.TestCase;
/**
* Basic tests of calling the C functions that make up the JNI. This
* class merely calls into native code and reports back if there was
* a problem.
*/
-public class JniCTest extends JniTestCase {
+public class JniCTest extends TestCase {
static {
- if (!JniTestCase.isCpuAbiNone()) {
- System.loadLibrary("jnitest");
- }
+ System.loadLibrary("jnitest");
}
/**
diff --git a/tests/tests/jni/src/android/jni/cts/JniCppTest.java b/tests/tests/jni/src/android/jni/cts/JniCppTest.java
index 6993b29..ad4f377 100644
--- a/tests/tests/jni/src/android/jni/cts/JniCppTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniCppTest.java
@@ -16,17 +16,16 @@
package android.jni.cts;
+import junit.framework.TestCase;
/**
* Basic tests of calling the C++ functions that make up the JNI. This
* class merely calls into native code and reports back if there was
* a problem.
*/
-public class JniCppTest extends JniTestCase {
+public class JniCppTest extends TestCase {
static {
- if (!JniTestCase.isCpuAbiNone()) {
- System.loadLibrary("jnitest");
- }
+ System.loadLibrary("jnitest");
}
/**
diff --git a/tests/tests/jni/src/android/jni/cts/JniInstanceTest.java b/tests/tests/jni/src/android/jni/cts/JniInstanceTest.java
index 7c16a3a..a66e072 100644
--- a/tests/tests/jni/src/android/jni/cts/JniInstanceTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniInstanceTest.java
@@ -16,13 +16,14 @@
package android.jni.cts;
+import junit.framework.TestCase;
/**
* Basic native instance method tests. The "nonce" class being tested
* by this class is a class defined in this package that declares the
* bulk of its methods as native.
*/
-public class JniInstanceTest extends JniTestCase {
+public class JniInstanceTest extends TestCase {
/** instance to use for all the tests */
private InstanceNonce target;
@@ -164,7 +165,7 @@ public class JniInstanceTest extends JniTestCase {
public void test_takeShort() {
assertTrue(target.takeShort((short) 19991));
}
-
+
/**
* Test a simple value-taking method call, that returns whether it
* got the expected value.
diff --git a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
index 3036c71..ff4411d 100644
--- a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
@@ -16,14 +16,14 @@
package android.jni.cts;
+import junit.framework.TestCase;
/**
* Basic static method tests. The "nonce" class being tested by this
* class is a class defined in this package that declares the bulk of
* its methods as native.
*/
-public class JniStaticTest extends JniTestCase {
-
+public class JniStaticTest extends TestCase {
/**
* Test a simple no-op and void-returning method call.
*/
@@ -166,7 +166,7 @@ public class JniStaticTest extends JniTestCase {
public void test_takeShort() {
assertTrue(StaticNonce.takeShort((short) 19991));
}
-
+
/**
* Test a simple value-taking method call, that returns whether it
* got the expected value.
diff --git a/tests/tests/jni/src/android/jni/cts/JniTestCase.java b/tests/tests/jni/src/android/jni/cts/JniTestCase.java
deleted file mode 100644
index a137ff7..0000000
--- a/tests/tests/jni/src/android/jni/cts/JniTestCase.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.jni.cts;
-
-import android.os.Build;
-
-import junit.framework.TestCase;
-
-class JniTestCase extends TestCase {
-
- static boolean isCpuAbiNone() {
- return "none".equalsIgnoreCase(Build.CPU_ABI);
- }
-
- @Override
- protected void runTest() throws Throwable {
- // Skip the JNI tests if ABI is none...
- if (!isCpuAbiNone()) {
- super.runTest();
- }
- }
-}
diff --git a/tests/tests/jni/src/android/jni/cts/StaticNonce.java b/tests/tests/jni/src/android/jni/cts/StaticNonce.java
index c84e899..f9b3310 100644
--- a/tests/tests/jni/src/android/jni/cts/StaticNonce.java
+++ b/tests/tests/jni/src/android/jni/cts/StaticNonce.java
@@ -22,9 +22,7 @@ package android.jni.cts;
*/
public class StaticNonce {
static {
- if (!JniTestCase.isCpuAbiNone()) {
- System.loadLibrary("jnitest");
- }
+ System.loadLibrary("jnitest");
}
/**
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index 620ee82..51623d0 100755
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -576,6 +576,9 @@ public class LocationManagerTest extends InstrumentationTestCase {
mManager.addProximityAlert(0, 0, 0, 5000, pi);
mManager.removeProximityAlert(pi);
+
+ mManager.addProximityAlert(0, 0, 0, 5000, null);
+ mManager.removeProximityAlert(null);
}
@TestTargets({
diff --git a/tests/tests/media/src/android/media/cts/AudioEffectTest.java b/tests/tests/media/src/android/media/cts/AudioEffectTest.java
index c40f169..0aaf11f 100644
--- a/tests/tests/media/src/android/media/cts/AudioEffectTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioEffectTest.java
@@ -22,13 +22,11 @@ import android.content.res.AssetFileDescriptor;
import android.media.audiofx.AudioEffect;
import android.media.AudioFormat;
import android.media.AudioManager;
-import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.audiofx.PresetReverb;
import android.media.audiofx.EnvironmentalReverb;
import android.media.audiofx.Equalizer;
import android.media.MediaPlayer;
-import android.media.MediaRecorder;
import android.os.Looper;
import android.test.AndroidTestCase;
@@ -48,8 +46,6 @@ public class AudioEffectTest extends AndroidTestCase {
private final static float DELAY_TOLERANCE = 1.05f;
// allow +/- 5% tolerance between set and get ratios
private final static float RATIO_TOLERANCE = 1.05f;
- // AudioRecord sampling rate
- private final static int SAMPLING_RATE = 44100;
private AudioEffect mEffect = null;
private AudioEffect mEffect2 = null;
@@ -119,25 +115,6 @@ public class AudioEffectTest extends AndroidTestCase {
// 1 - constructor
//----------------------------------
- private AudioRecord getAudioRecord() {
- AudioRecord ar = null;
- try {
- ar = new AudioRecord(MediaRecorder.AudioSource.DEFAULT,
- SAMPLING_RATE,
- AudioFormat.CHANNEL_CONFIGURATION_MONO,
- AudioFormat.ENCODING_PCM_16BIT,
- AudioRecord.getMinBufferSize(SAMPLING_RATE,
- AudioFormat.CHANNEL_CONFIGURATION_MONO,
- AudioFormat.ENCODING_PCM_16BIT) * 10);
- assertNotNull("Could not create AudioRecord", ar);
- assertEquals("AudioRecord not initialized",
- AudioRecord.STATE_INITIALIZED, ar.getState());
- } catch (IllegalArgumentException e) {
- fail("AudioRecord invalid parameter");
- }
- return ar;
- }
-
//Test case 1.0: test constructor from effect type and get effect ID
@TestTargets({
@TestTargetNew(
@@ -162,19 +139,10 @@ public class AudioEffectTest extends AndroidTestCase {
for (int i = 0; i < desc.length; i++) {
if (!desc[i].type.equals(AudioEffect.EFFECT_TYPE_NULL)) {
try {
- int sessionId;
- AudioRecord ar = null;
- if (AudioEffect.EFFECT_PRE_PROCESSING.equals(desc[i].connectMode)) {
- ar = getAudioRecord();
- sessionId = ar.getAudioSessionId();
- } else {
- sessionId = 0;
- }
AudioEffect effect = new AudioEffect(desc[i].type,
AudioEffect.EFFECT_TYPE_NULL,
0,
- sessionId);
-
+ 0);
assertNotNull("could not create AudioEffect", effect);
try {
assertTrue("invalid effect ID", (effect.getId() != 0));
@@ -182,9 +150,6 @@ public class AudioEffectTest extends AndroidTestCase {
fail("AudioEffect not initialized");
} finally {
effect.release();
- if (ar != null) {
- ar.release();
- }
}
} catch (IllegalArgumentException e) {
fail("Effect not found: "+desc[i].name);
@@ -218,18 +183,10 @@ public class AudioEffectTest extends AndroidTestCase {
assertTrue("no effects found", (desc.length != 0));
for (int i = 0; i < desc.length; i++) {
try {
- int sessionId;
- AudioRecord ar = null;
- if (AudioEffect.EFFECT_PRE_PROCESSING.equals(desc[i].connectMode)) {
- ar = getAudioRecord();
- sessionId = ar.getAudioSessionId();
- } else {
- sessionId = 0;
- }
AudioEffect effect = new AudioEffect(AudioEffect.EFFECT_TYPE_NULL,
desc[i].uuid,
0,
- sessionId);
+ 0);
assertNotNull("could not create AudioEffect", effect);
try {
assertTrue("invalid effect ID", (effect.getId() != 0));
@@ -237,9 +194,6 @@ public class AudioEffectTest extends AndroidTestCase {
fail("AudioEffect not initialized");
} finally {
effect.release();
- if (ar != null) {
- ar.release();
- }
}
} catch (IllegalArgumentException e) {
fail("Effect not found: "+desc[i].name);
@@ -612,7 +566,7 @@ public class AudioEffectTest extends AndroidTestCase {
byte[] param = mEffect.intToByteArray(PresetReverb.PARAM_PRESET);
byte[] value = new byte[2];
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
short preset = PresetReverb.PRESET_SMALLROOM;
if (mEffect.byteArrayToShort(value) == preset) {
preset = PresetReverb.PRESET_MEDIUMROOM;
@@ -621,7 +575,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, value);
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
assertEquals("get/set Parameter failed", preset,
mEffect.byteArrayToShort(value));
@@ -655,7 +609,7 @@ public class AudioEffectTest extends AndroidTestCase {
int param = EnvironmentalReverb.PARAM_DECAY_TIME;
int[] value = new int[1];
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
int time = 500;
if (value[0] == time) {
time = 1000;
@@ -663,7 +617,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, time);
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
assertTrue("got incorrect decay time",
((float)value[0] > (float)(time / DELAY_TOLERANCE)) &&
((float)value[0] < (float)(time * DELAY_TOLERANCE)));
@@ -698,7 +652,7 @@ public class AudioEffectTest extends AndroidTestCase {
int param = PresetReverb.PARAM_PRESET;
short[] value = new short[1];
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
short preset = PresetReverb.PRESET_SMALLROOM;
if (value[0] == preset) {
preset = PresetReverb.PRESET_MEDIUMROOM;
@@ -706,7 +660,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, preset);
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
assertEquals("get/set Parameter failed", preset, value[0]);
} catch (IllegalArgumentException e) {
@@ -739,7 +693,7 @@ public class AudioEffectTest extends AndroidTestCase {
int param = EnvironmentalReverb.PARAM_DECAY_TIME;
byte[] value = new byte[4];
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
int time = 500;
if (mEffect.byteArrayToInt(value) == time) {
time = 1000;
@@ -748,7 +702,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, value);
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
int time2 = mEffect.byteArrayToInt(value);
assertTrue("got incorrect decay time",
((float)time2 > (float)(time / DELAY_TOLERANCE)) &&
@@ -785,7 +739,7 @@ public class AudioEffectTest extends AndroidTestCase {
int[] value = new int[1];
param[0] = EnvironmentalReverb.PARAM_DECAY_TIME;
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
int[] time = new int[1];
time[0] = 500;
if (value[0] == time[0]) {
@@ -794,7 +748,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, time);
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
assertTrue("got incorrect decay time",
((float)value[0] > (float)(time[0] / DELAY_TOLERANCE)) &&
((float)value[0] < (float)(time[0] * DELAY_TOLERANCE)));
@@ -831,7 +785,7 @@ public class AudioEffectTest extends AndroidTestCase {
param[0] = PresetReverb.PARAM_PRESET;
short[] value = new short[1];
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
short[] preset = new short[1];
preset[0] = PresetReverb.PRESET_SMALLROOM;
if (value[0] == preset[0]) {
@@ -840,7 +794,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, preset);
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
assertEquals("get/set Parameter failed", preset[0], value[0]);
} catch (IllegalArgumentException e) {
@@ -874,7 +828,7 @@ public class AudioEffectTest extends AndroidTestCase {
param[0] = EnvironmentalReverb.PARAM_DECAY_TIME;
byte[] value = new byte[4];
int status = mEffect.getParameter(param, value);
- assertFalse("getParameter 1 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 1 failed", AudioEffect.SUCCESS, status);
int time = 500;
if (mEffect.byteArrayToInt(value) == time) {
time = 1000;
@@ -883,7 +837,7 @@ public class AudioEffectTest extends AndroidTestCase {
status = mEffect.setParameter(param, mEffect.intToByteArray(time));
assertEquals("setParameter failed", AudioEffect.SUCCESS, status);
status = mEffect.getParameter(param, value);
- assertFalse("getParameter 2 failed", AudioEffect.isError(status));
+ assertEquals("getParameter 2 failed", AudioEffect.SUCCESS, status);
int time2 = mEffect.byteArrayToInt(value);
assertTrue("got incorrect decay time",
((float)time2 > (float)(time / DELAY_TOLERANCE)) &&
@@ -1064,8 +1018,8 @@ public class AudioEffectTest extends AndroidTestCase {
short[] value = new short[1];
status = effect2.getParameter(PresetReverb.PARAM_PRESET, value);
- assertFalse("Effect2 getParameter failed",
- AudioEffect.isError(status));
+ assertEquals("Effect2 getParameter failed",
+ AudioEffect.SUCCESS, status);
assertEquals("Effect1 changed parameter", PresetReverb.PRESET_SMALLROOM
, value[0]);
@@ -1232,7 +1186,7 @@ public class AudioEffectTest extends AndroidTestCase {
byte[] reply = new byte[4];
// command 3 is ENABLE
int status = mEffect.command(3, cmd, reply);
- assertFalse("command failed", AudioEffect.isError(status));
+ assertEquals("command failed", AudioEffect.SUCCESS, status);
assertTrue("effect not enabled", mEffect.getEnabled());
} catch (IllegalStateException e) {
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index f4d60c8..b4053cf 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -22,7 +22,6 @@ import static android.media.AudioManager.ADJUST_SAME;
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;
@@ -45,21 +44,37 @@ import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
import dalvik.annotation.ToBeFixed;
+import android.app.cts.CTSResult;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.provider.Settings;
-import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
import android.view.SoundEffectConstants;
-
@TestTargetClass(AudioManager.class)
-public class AudioManagerTest extends AndroidTestCase {
+public class AudioManagerTest extends AndroidTestCase implements CTSResult {
private final static int MP3_TO_PLAY = R.raw.testmp3;
private final static long TIME_TO_PLAY = 2000;
private AudioManager mAudioManager;
+ private int mResultCode;
+ private Sync mSync = new Sync();
+
+ private static class Sync {
+ private boolean notified;
+
+ synchronized void notifyResult() {
+ notified = true;
+ notify();
+ }
+
+ synchronized void waitForResult() throws Exception {
+ if (!notified) {
+ wait();
+ }
+ }
+ }
@Override
protected void setUp() throws Exception {
@@ -184,8 +199,6 @@ public class AudioManagerTest extends AndroidTestCase {
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());
}
@@ -247,30 +260,25 @@ public class AudioManagerTest extends AndroidTestCase {
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({
@@ -493,12 +501,7 @@ public class AudioManagerTest extends AndroidTestCase {
AudioManager.STREAM_VOICE_CALL,
AudioManager.STREAM_RING };
- TelephonyManager tm =
- (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
- //FIXME: use TelephonyManager.isVoiceCapable() when public
- boolean voiceCapable = tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
-
- mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+ mAudioManager.adjustVolume(ADJUST_RAISE, 100);
mAudioManager.adjustSuggestedStreamVolume(
ADJUST_LOWER, USE_DEFAULT_STREAM_TYPE, FLAG_SHOW_UI);
@@ -517,17 +520,49 @@ public class AudioManagerTest extends AndroidTestCase {
// volume lower
mAudioManager.setStreamVolume(streams[i], maxVolume, FLAG_SHOW_UI);
- for (int k = maxVolume; k > 1; k--) {
+ for (int k = maxVolume; k > 0; k--) {
mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_SHOW_UI);
assertEquals(k - 1, mAudioManager.getStreamVolume(streams[i]));
}
- // on voice capable devices, ring and notification volumes cannot be set to 0
- // by continous press on volume minus key
- // simulate volume key release
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_SAME,
- FLAG_SHOW_UI | FLAG_ALLOW_RINGER_MODES);
- mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_SHOW_UI);
- assertEquals(0, mAudioManager.getStreamVolume(streams[i]));
+
+ 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());
+ }
// volume raise
mAudioManager.setStreamVolume(streams[i], 0, FLAG_SHOW_UI);
@@ -548,7 +583,7 @@ public class AudioManagerTest extends AndroidTestCase {
// adjust volume
int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
- mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+ mAudioManager.adjustVolume(ADJUST_RAISE, 100);
MediaPlayer mp = MediaPlayer.create(mContext, MP3_TO_PLAY);
mp.setAudioStreamType(STREAM_MUSIC);
@@ -582,12 +617,8 @@ public class AudioManagerTest extends AndroidTestCase {
assertFalse(mAudioManager.isMusicActive());
}
- public void testSetInvalidRingerMode() {
- int ringerMode = mAudioManager.getRingerMode();
- mAudioManager.setRingerMode(-1337);
- assertEquals(ringerMode, mAudioManager.getRingerMode());
-
- mAudioManager.setRingerMode(-3007);
- assertEquals(ringerMode, mAudioManager.getRingerMode());
+ 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 1ddcdd5..5f6fc2c 100644
--- a/tests/tests/media/src/android/media/cts/AudioRecordTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
@@ -18,7 +18,6 @@ package android.media.cts;
import java.nio.ByteBuffer;
-import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
@@ -41,7 +40,6 @@ public class AudioRecordTest extends AndroidTestCase {
private boolean mIsOnPeriodicNotificationCalled;
private boolean mIsHandleMessageCalled;
private Looper mLooper;
- private int MAX_RECORD_START_TIME_MS = 100;
@Override
protected void setUp() throws Exception {
@@ -139,9 +137,6 @@ public class AudioRecordTest extends AndroidTestCase {
)
})
public void testAudioRecordProperties() throws Exception {
- if (!hasMicrophone()) {
- return;
- }
assertEquals(AudioFormat.ENCODING_PCM_16BIT, mAudioRecord.getAudioFormat());
assertEquals(MediaRecorder.AudioSource.DEFAULT, mAudioRecord.getAudioSource());
assertEquals(1, mAudioRecord.getChannelCount());
@@ -229,16 +224,10 @@ public class AudioRecordTest extends AndroidTestCase {
)
})
public void testAudioRecordOP() throws Exception {
- if (!hasMicrophone()) {
- return;
- }
final int SLEEP_TIME = 10;
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));
@@ -264,10 +253,6 @@ public class AudioRecordTest extends AndroidTestCase {
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);
@@ -336,8 +321,4 @@ public class AudioRecordTest extends AndroidTestCase {
mAudioRecord.release();
assertEquals(AudioRecord.STATE_UNINITIALIZED, mAudioRecord.getState());
}
-
- private boolean hasMicrophone() {
- return getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
- }
}
diff --git a/tests/tests/media/src/android/media/cts/AudioRecord_BufferSizeTest.java b/tests/tests/media/src/android/media/cts/AudioRecord_BufferSizeTest.java
deleted file mode 100644
index 504a304..0000000
--- a/tests/tests/media/src/android/media/cts/AudioRecord_BufferSizeTest.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.media.cts;
-
-import android.content.pm.PackageManager;
-import android.media.AudioFormat;
-import android.media.AudioRecord;
-import android.media.MediaRecorder.AudioSource;
-import android.test.AndroidTestCase;
-import android.util.Log;
-import android.view.animation.cts.DelayedCheck;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class AudioRecord_BufferSizeTest extends AndroidTestCase {
-
- private static final String TAG = AudioRecord_BufferSizeTest.class.getSimpleName();
- private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
- private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
-
- private static final int[] SAMPLE_RATES_IN_HZ = new int[] {
- 8000,
- 11025,
- 16000,
- 44100,
- };
-
- private AudioRecord mAudioRecord;
-
- public void testGetMinBufferSize() throws Exception {
- if (!hasMicrophone()) {
- return;
- }
- List failedSampleRates = new ArrayList();
- for (int i = 0; i < SAMPLE_RATES_IN_HZ.length; i++) {
- try {
- record(SAMPLE_RATES_IN_HZ[i]);
- } catch (Throwable e) {
- Log.e(TAG, "Sample rate: " + SAMPLE_RATES_IN_HZ[i], e);
- failedSampleRates.add(SAMPLE_RATES_IN_HZ[i]);
- }
- }
- assertTrue("Failed sample rates: " + failedSampleRates + " See log for more details.",
- failedSampleRates.isEmpty());
- }
-
- private void record(int sampleRateInHz) {
- int bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, CHANNEL_CONFIG, AUDIO_FORMAT);
- byte[] buffer = new byte[bufferSize];
- assertTrue(bufferSize > 0);
-
- createAudioRecord(sampleRateInHz, bufferSize);
- checkRecordingState(AudioRecord.STATE_INITIALIZED);
-
- mAudioRecord.startRecording();
- checkRecordingState(AudioRecord.RECORDSTATE_RECORDING);
-
- assertTrue(mAudioRecord.read(buffer, 0, bufferSize) > 0);
-
- mAudioRecord.stop();
- checkRecordingState(AudioRecord.RECORDSTATE_STOPPED);
-
- mAudioRecord.release();
- }
-
- private void createAudioRecord(final int sampleRateInHz, final int bufferSize) {
- mAudioRecord = new AudioRecord(AudioSource.DEFAULT, sampleRateInHz,
- CHANNEL_CONFIG, AUDIO_FORMAT, bufferSize);
- assertNotNull(mAudioRecord);
- }
-
- private void checkRecordingState(final int state) {
- new DelayedCheck() {
- @Override
- protected boolean check() {
- return mAudioRecord.getRecordingState() == state;
- }
- }.run();
- }
-
- private boolean hasMicrophone() {
- return getContext().getPackageManager().hasSystemFeature(
- PackageManager.FEATURE_MICROPHONE);
- }
-}
diff --git a/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java b/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
index cbdf8b0..b94da11 100644
--- a/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
+++ b/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
@@ -22,8 +22,6 @@ import dalvik.annotation.TestTargetNew;
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;
@@ -35,16 +33,7 @@ public class CamcorderProfileTest extends AndroidTestCase {
private static final String TAG = "CamcorderProfileTest";
- // 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 videoSizes) {
+ private void checkProfile(CamcorderProfile profile) {
Log.v(TAG, String.format("profile: duration=%d, quality=%d, " +
"fileFormat=%d, videoCodec=%d, videoBitRate=%d, videoFrameRate=%d, " +
"videoFrameWidth=%d, videoFrameHeight=%d, audioCodec=%d, " +
@@ -63,19 +52,7 @@ public class CamcorderProfileTest extends AndroidTestCase {
profile.audioChannels));
assertTrue(profile.duration > 0);
assertTrue(profile.quality == CamcorderProfile.QUALITY_LOW ||
- 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);
+ profile.quality == CamcorderProfile.QUALITY_HIGH);
assertTrue(profile.videoBitRate > 0);
assertTrue(profile.videoFrameRate > 0);
assertTrue(profile.videoFrameWidth > 0);
@@ -83,152 +60,6 @@ public class CamcorderProfileTest extends AndroidTestCase {
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 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 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,
- // replace this with CamcorderProfile.QUALITY_QVGA
- 7,
- CamcorderProfile.QUALITY_CIF,
- CamcorderProfile.QUALITY_480P,
- CamcorderProfile.QUALITY_720P,
- CamcorderProfile.QUALITY_1080P};
-
- int[] specificTimeLapseProfileQualities = {CamcorderProfile.QUALITY_TIME_LAPSE_QCIF,
- // replace this with CamcorderProfile.QUALITY_TIME_LAPSE_QVGA
- 1007,
- 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({
@@ -239,7 +70,10 @@ public class CamcorderProfileTest extends AndroidTestCase {
)
})
public void testGet() {
- checkGet(-1);
+ CamcorderProfile lowProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
+ CamcorderProfile highProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
+ checkProfile(lowProfile);
+ checkProfile(highProfile);
}
@TestTargets({
@@ -251,31 +85,13 @@ public class CamcorderProfileTest extends AndroidTestCase {
})
public void testGetWithId() {
int nCamera = Camera.getNumberOfCameras();
- for (int cameraId = 0; cameraId < nCamera; cameraId++) {
- checkGet(cameraId);
- }
- }
-
- private List getSupportedVideoSizes(int cameraId) {
- Camera camera = (cameraId == -1)? Camera.open(): Camera.open(cameraId);
- Parameters parameters = camera.getParameters();
- List videoSizes = parameters.getSupportedVideoSizes();
- if (videoSizes == null) {
- videoSizes = parameters.getSupportedPreviewSizes();
- assertNotNull(videoSizes);
- }
- camera.release();
- return videoSizes;
- }
-
- private boolean isSizeSupported(int width, int height, List sizes) {
- if (sizes == null) return true;
-
- for (Size size: sizes) {
- if (size.width == width && size.height == height) {
- return true;
- }
+ 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);
}
- return false;
}
}
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerStreamingTest.java b/tests/tests/media/src/android/media/cts/MediaPlayerStreamingTest.java
deleted file mode 100644
index 652c5bd..0000000
--- a/tests/tests/media/src/android/media/cts/MediaPlayerStreamingTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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.media.cts;
-
-import android.media.MediaPlayer;
-import android.webkit.cts.CtsTestServer;
-
-
-/**
- * Tests of MediaPlayer streaming capabilities.
- */
-public class MediaPlayerStreamingTest extends MediaPlayerTestBase {
- private CtsTestServer mServer;
-
- // Streaming RTSP video from YouTube
- public void testRTSP_H263_AMR_Video1() throws Exception {
- playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0x271de9756065677e"
- + "&fmt=13&user=android-device-test", 176, 144);
- }
- public void testRTSP_H263_AMR_Video2() throws Exception {
- playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0xc80658495af60617"
- + "&fmt=13&user=android-device-test", 176, 144);
- }
-
- public void testRTSP_MPEG4SP_AAC_Video1() throws Exception {
- playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0x271de9756065677e"
- + "&fmt=17&user=android-device-test", 176, 144);
- }
- public void testRTSP_MPEG4SP_AAC_Video2() throws Exception {
- playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0xc80658495af60617"
- + "&fmt=17&user=android-device-test", 176, 144);
- }
-
- public void testRTSP_H264Base_AAC_Video1() throws Exception {
- playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0x271de9756065677e"
- + "&fmt=18&user=android-device-test", 480, 270);
- }
- public void testRTSP_H264Base_AAC_Video2() throws Exception {
- playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0xc80658495af60617"
- + "&fmt=18&user=android-device-test", 480, 270);
- }
-
- // Streaming HTTP video from YouTube
- public void testHTTP_H263_AMR_Video1() throws Exception {
- playVideoTest("http://v20.lscache8.c.youtube.com/videoplayback?id=271de9756065677e"
- + "&itag=13&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=372FA4C532AA49D14EAF049BCDA66460EEE161E9"
- + ".6D8BF096B73B7A68A7032CA8685053CFB498D30A"
- + "&key=test_key1&user=android-device-test", 176, 144);
- }
- public void testHTTP_H263_AMR_Video2() throws Exception {
- playVideoTest("http://v20.lscache8.c.youtube.com/videoplayback?id=c80658495af60617"
- + "&itag=13&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=191FCD5C4B7400065C20845D7AC2B437B1291F26"
- + ".66F8B8D7EFF7F144141AC67E8E35E078468CE6FB"
- + "&key=test_key1&user=android-device-test", 176, 144);
- }
-
- public void testHTTP_MPEG4SP_AAC_Video1() throws Exception {
- playVideoTest("http://v20.lscache8.c.youtube.com/videoplayback?id=271de9756065677e"
- + "&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=3DCD3F79E045F95B6AF661765F046FB0440FF016"
- + ".06A42661B3AF6BAF046F012549CC9BA34EBC80A9"
- + "&key=test_key1&user=android-device-test", 176, 144);
- }
- public void testHTTP_MPEG4SP_AAC_Video2() throws Exception {
- playVideoTest("http://v20.lscache8.c.youtube.com/videoplayback?id=c80658495af60617"
- + "&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=242B7AEF3AB38519F593203FDEF420E2A585DA6E"
- + ".4A57C03AF6859FE4694CD69C3225E386373A98B0"
- + "&key=test_key1&user=android-device-test", 176, 144);
- }
-
- public void testHTTP_H264Base_AAC_Video1() throws Exception {
- playVideoTest("http://v20.lscache8.c.youtube.com/videoplayback?id=271de9756065677e"
- + "&itag=18&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=1219C2B07AF0638C27916307A6093C0E43CB894E"
- + ".126B6B916BD57157782738AA7C03E59F21DBC168"
- + "&key=test_key1&user=android-device-test", 480, 270);
- }
- public void testHTTP_H264Base_AAC_Video2() throws Exception {
- playVideoTest("http://v20.lscache8.c.youtube.com/videoplayback?id=c80658495af60617"
- + "&itag=18&ip=0.0.0.0&ipbits=0&expire=999999999999999999"
- + "&sparams=ip,ipbits,expire,ip,ipbits,expire,id,itag"
- + "&signature=61674BC069F2C812A18C390DE785CECD296228C7"
- + ".11F5FCE823FB8FA31269A06A483C2F9B2C22F357"
- + "&key=test_key1&user=android-device-test", 480, 270);
- }
-
- // Streaming HLS video from YouTube
- public void testHLS() throws Exception {
- // Play stream for 60 seconds
- playLiveVideoTest("http://www.youtube.com/api/manifest/hls/ns/yt-live/id/UeHRu5LFHaU"
- + "?ip=0.0.0.0&ipbits=0&expire=19000000000&sparams=ip,ipbits,expire&signature"
- + "=313BE90526F2D815EB207156E1460C7E8EEC2503.799EE7B8B7CE3F2957060DB27C216077"
- + "0303EBD2&key=test_key1&user=android-device-test&m3u8=1", 60 * 1000);
- }
-
- // Streaming audio from local HTTP server
- public void testPlayMp3Stream1() throws Throwable {
- localHttpAudioStreamTest("ringer.mp3", false, false);
- }
- public void testPlayMp3Stream2() throws Throwable {
- localHttpAudioStreamTest("ringer.mp3", false, false);
- }
- public void testPlayMp3StreamRedirect() throws Throwable {
- localHttpAudioStreamTest("ringer.mp3", true, false);
- }
- public void testPlayMp3StreamNoLength() throws Throwable {
- localHttpAudioStreamTest("noiseandchirps.mp3", false, true);
- }
- public void testPlayOggStream() throws Throwable {
- localHttpAudioStreamTest("noiseandchirps.ogg", false, false);
- }
- public void testPlayOggStreamRedirect() throws Throwable {
- localHttpAudioStreamTest("noiseandchirps.ogg", true, false);
- }
- public void testPlayOggStreamNoLength() throws Throwable {
- localHttpAudioStreamTest("noiseandchirps.ogg", false, true);
- }
-
- private void localHttpAudioStreamTest(final String name, boolean redirect, boolean nolength)
- throws Throwable {
- mServer = new CtsTestServer(mContext);
- try {
- String stream_url = null;
- if (redirect) {
- // Stagefright doesn't have a limit, but we can't test support of infinite redirects
- // Up to 4 redirects seems reasonable though.
- stream_url = mServer.getRedirectingAssetUrl(name, 4);
- } else {
- stream_url = mServer.getAssetUrl(name);
- }
- if (nolength) {
- stream_url = stream_url + "?" + CtsTestServer.NOLENGTH_POSTFIX;
- }
-
- mMediaPlayer.setDataSource(stream_url);
-
- mMediaPlayer.setDisplay(getActivity().getSurfaceHolder());
- mMediaPlayer.setScreenOnWhilePlaying(true);
-
- mOnBufferingUpdateCalled.reset();
- mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
- @Override
- public void onBufferingUpdate(MediaPlayer mp, int percent) {
- mOnBufferingUpdateCalled.signal();
- }
- });
- mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
- @Override
- public boolean onError(MediaPlayer mp, int what, int extra) {
- fail("Media player had error " + what + " playing " + name);
- return true;
- }
- });
-
- assertFalse(mOnBufferingUpdateCalled.isSignalled());
- mMediaPlayer.prepare();
-
- if (nolength) {
- mMediaPlayer.start();
- Thread.sleep(LONG_SLEEP_TIME);
- assertFalse(mMediaPlayer.isPlaying());
- } else {
- mOnBufferingUpdateCalled.waitForSignal();
- mMediaPlayer.start();
- Thread.sleep(SLEEP_TIME);
- }
- mMediaPlayer.stop();
- mMediaPlayer.reset();
- } finally {
- mServer.shutdown();
- }
- }
-}
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerSurfaceTest.java b/tests/tests/media/src/android/media/cts/MediaPlayerSurfaceTest.java
deleted file mode 100644
index 196382d..0000000
--- a/tests/tests/media/src/android/media/cts/MediaPlayerSurfaceTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.media.cts;
-
-import android.os.Bundle;
-import android.test.ActivityInstrumentationTestCase2;
-
-/**
- */
-public class MediaPlayerSurfaceTest extends ActivityInstrumentationTestCase2 {
-
- public MediaPlayerSurfaceTest() {
- super("com.android.cts.stub", MediaPlayerSurfaceStubActivity.class);
- }
-
- public void testSetSurface() throws Exception {
- Bundle extras = new Bundle();
- MediaPlayerSurfaceStubActivity activity = launchActivity("com.android.cts.stub",
- MediaPlayerSurfaceStubActivity.class, extras);
- activity.playVideo();
- activity.finish();
- }
-}
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
index 9947592..d18d684 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
@@ -17,347 +17,567 @@ package android.media.cts;
import com.android.cts.stub.R;
-import android.content.pm.PackageManager;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import android.content.Context;
import android.content.res.AssetFileDescriptor;
+import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
+import android.media.MediaPlayer.OnBufferingUpdateListener;
+import android.media.MediaPlayer.OnCompletionListener;
+import android.media.MediaPlayer.OnErrorListener;
+import android.media.MediaPlayer.OnPreparedListener;
+import android.media.MediaPlayer.OnSeekCompleteListener;
+import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Environment;
+import android.os.Looper;
import android.os.PowerManager;
+import android.test.ActivityInstrumentationTestCase2;
+import android.view.SurfaceHolder;
+import android.webkit.cts.CtsTestServer;
+import android.util.Log;
import java.io.File;
+import java.io.FileDescriptor;
+
+@TestTargetClass(MediaPlayer.class)
+public class MediaPlayerTest extends ActivityInstrumentationTestCase2 {
+
+ private static String TAG = "CtsMediaPlayerTest";
+ private static final int SLEEP_TIME = 1000;
+ private static final int LONG_SLEEP_TIME = 6000;
+ private final String mSourceMediaOnSdcard;
+ private Monitor mOnVideoSizeChangedCalled = new Monitor();
+ private Monitor mOnBufferingUpdateCalled = new Monitor();
+ private Monitor mOnPrepareCalled = new Monitor();
+ private Monitor mOnSeekCompleteCalled = new Monitor();
+ private Monitor mOnCompletionCalled = new Monitor();
+ private Monitor mOnInfoCalled = new Monitor();
+ private Monitor mOnErrorCalled = new Monitor();
+ private Context mContext;
+ private Resources mResources;
+ private CtsTestServer mServer;
+ private static Object sVideoSizeChanged;
+ private static Object sLock;
+ private static Looper sLooper = null;
+ private static final int WAIT_FOR_COMMAND_TO_COMPLETE = 60000; //1 min max.
+
+ /*
+ * InstrumentationTestRunner.onStart() calls Looper.prepare(), which creates a looper
+ * for the current thread. However, since we don't actually call loop() in the test,
+ * any messages queued with that looper will never be consumed. We instantiate the player
+ * in the constructor, before setUp(), so that its constructor does not see the
+ * nonfunctional Looper.
+ */
+ private MediaPlayer mMediaPlayer = new MediaPlayer();
-/**
- * Tests for the MediaPlayer API and local video/audio playback.
- *
- * The files in res/raw used by testLocalVideo* are (c) copyright 2008,
- * Blender Foundation / www.bigbuckbunny.org, and are licensed under the Creative Commons
- * Attribution 3.0 License at http://creativecommons.org/licenses/by/3.0/us/.
- */
-public class MediaPlayerTest extends MediaPlayerTestBase {
- public void testPlayNullSource() throws Exception {
- try {
- mMediaPlayer.setDataSource((String) null);
- fail("Null URI was accepted");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- public void testPlayAudio() throws Exception {
- final int mp3Duration = 34909;
- final int tolerance = 70;
- final int seekDuration = 100;
- final int resid = R.raw.testmp3_2;
-
- MediaPlayer mp = MediaPlayer.create(mContext, resid);
- try {
- mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
- mp.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
-
- assertFalse(mp.isPlaying());
- mp.start();
- assertTrue(mp.isPlaying());
+ static MediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener =
+ new MediaPlayer.OnVideoSizeChangedListener() {
+ public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
+ synchronized (sVideoSizeChanged) {
+ Log.v(TAG, "sizechanged notification received ...");
+ sVideoSizeChanged.notify();
+ }
+ }
+ };
- assertFalse(mp.isLooping());
- mp.setLooping(true);
- assertTrue(mp.isLooping());
+ private static class Monitor {
+ private boolean signalled;
- assertEquals(mp3Duration, mp.getDuration(), tolerance);
- int pos = mp.getCurrentPosition();
- assertTrue(pos >= 0);
- assertTrue(pos < mp3Duration - seekDuration);
+ public synchronized void reset() {
+ signalled = false;
+ }
- mp.seekTo(pos + seekDuration);
- assertEquals(pos + seekDuration, mp.getCurrentPosition(), tolerance);
+ public synchronized void signal() {
+ signalled = true;
+ notifyAll();
+ }
- // test pause and restart
- mp.pause();
- Thread.sleep(SLEEP_TIME);
- assertFalse(mp.isPlaying());
- mp.start();
- assertTrue(mp.isPlaying());
-
- // test stop and restart
- mp.stop();
- mp.reset();
- AssetFileDescriptor afd = mResources.openRawResourceFd(resid);
- mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
- afd.close();
- mp.prepare();
- assertFalse(mp.isPlaying());
- mp.start();
- assertTrue(mp.isPlaying());
-
- // waiting to complete
- while(mp.isPlaying()) {
- Thread.sleep(SLEEP_TIME);
+ public synchronized void waitForSignal() throws InterruptedException {
+ while (!signalled) {
+ wait();
}
- } finally {
- mp.release();
}
}
- public void testPlayVideo() throws Exception {
- playVideoTest(R.raw.testvideo, 352, 288);
- }
-
- /**
- * Test for reseting a surface during video playback
- * After reseting, the video should continue playing
- * from the time setDisplay() was called
- */
- public void testVideoSurfaceResetting() throws Exception {
- final int tolerance = 150;
- final int seekPos = 1500;
-
- playVideoTest(R.raw.testvideo, 352, 288);
-
- mMediaPlayer.start();
- Thread.sleep(SLEEP_TIME);
-
- int posBefore = mMediaPlayer.getCurrentPosition();
- mMediaPlayer.setDisplay(getActivity().getSurfaceHolder2());
- int posAfter = mMediaPlayer.getCurrentPosition();
-
- assertEquals(posAfter, posBefore);
- assertTrue(mMediaPlayer.isPlaying());
-
- Thread.sleep(SLEEP_TIME);
-
- mMediaPlayer.seekTo(seekPos);
- Thread.sleep(SLEEP_TIME / 2);
-
- posBefore = mMediaPlayer.getCurrentPosition();
- mMediaPlayer.setDisplay(null);
- posAfter = mMediaPlayer.getCurrentPosition();
-
- assertEquals(posAfter, posBefore);
- assertEquals(seekPos + SLEEP_TIME / 2, posBefore, tolerance);
- assertTrue(mMediaPlayer.isPlaying());
-
- Thread.sleep(SLEEP_TIME);
-
- posBefore = mMediaPlayer.getCurrentPosition();
- mMediaPlayer.setDisplay(getActivity().generateSurfaceHolder());
- posAfter = mMediaPlayer.getCurrentPosition();
-
- assertEquals(posAfter, posBefore);
- assertTrue(mMediaPlayer.isPlaying());
-
- Thread.sleep(SLEEP_TIME);
- }
-
- public void testLocalVideo_MP4_H264_480x360_500kbps_25fps_AAC_Stereo_128kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_500kbps_25fps_aac_stereo_128kbps_44100hz, 480, 360);
- }
-
- public void testLocalVideo_MP4_H264_480x360_500kbps_30fps_AAC_Stereo_128kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_500kbps_30fps_aac_stereo_128kbps_44100hz, 480, 360);
- }
-
- public void testLocalVideo_MP4_H264_480x360_1000kbps_25fps_AAC_Stereo_128kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_1000kbps_25fps_aac_stereo_128kbps_44100hz, 480, 360);
- }
-
- public void testLocalVideo_MP4_H264_480x360_1000kbps_30fps_AAC_Stereo_128kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_1000kbps_30fps_aac_stereo_128kbps_44100hz, 480, 360);
- }
-
- public void testLocalVideo_MP4_H264_480x360_1350kbps_25fps_AAC_Stereo_128kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_1350kbps_25fps_aac_stereo_128kbps_44100hz, 480, 360);
- }
-
- public void testLocalVideo_MP4_H264_480x360_1350kbps_30fps_AAC_Stereo_128kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_1350kbps_30fps_aac_stereo_128kbps_44100hz, 480, 360);
- }
-
- public void testLocalVideo_MP4_H264_480x360_1350kbps_30fps_AAC_Stereo_192kbps_44110Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_480x360_mp4_h264_1350kbps_30fps_aac_stereo_192kbps_44100hz, 480, 360);
+ public MediaPlayerTest() {
+ super("com.android.cts.stub", MediaStubActivity.class);
+ mSourceMediaOnSdcard = new File(Environment.getExternalStorageDirectory(),
+ "record_and_play.3gp").getAbsolutePath();
}
- public void testLocalVideo_3gp_H263_176x144_56kbps_12fps_AAC_Mono_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_11025hz, 176, 144);
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mContext = getInstrumentation().getTargetContext();
+ mResources = mContext.getResources();
}
- public void testLocalVideo_3gp_H263_176x144_56kbps_12fps_AAC_Mono_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_22050hz, 176, 144);
- }
-
- public void testLocalVideo_3gp_H263_176x144_56kbps_12fps_AAC_Stereo_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_11025hz, 176, 144);
- }
-
- public void testLocalVideo_3gp_H263_176x144_56kbps_12fps_AAC_Stereo_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_11025hz, 176, 144);
- }
-
- public void testLocalVideo_3gp_H263_176x144_56kbps_12fps_AAC_Stereo_128kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
-
- public void testLocalVideo_3gp_H263_176x144_56kbps_12fps_AAC_Stereo_128kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
+ @Override
+ protected void tearDown() throws Exception {
+ if (mMediaPlayer != null) {
+ mMediaPlayer.release();
+ }
+ File file = new File(mSourceMediaOnSdcard);
+ if (file.exists()) {
+ file.delete();
+ }
+ if (mServer != null) {
+ mServer.shutdown();
+ }
+ super.tearDown();
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "create",
+ args = {Context.class, int.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setAudioStreamType",
+ args = {int.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setWakeMode",
+ args = {Context.class, int.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "isPlaying",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "start",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setLooping",
+ args = {boolean.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "isLooping",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "getCurrentPosition",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "seekTo",
+ args = {int.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "pause",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "stop",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "reset",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDataSource",
+ args = {FileDescriptor.class, long.class, long.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "prepare",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "getDuration",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "release",
+ args = {}
+ )
+ })
+ public void testPlayAudio() throws Exception {
+ final int mp3Duration = 34909;
+ final int tolerance = 70;
+ final int seekDuration = 100;
+ final int resid = R.raw.testmp3_2;
- public void testLocalVideo_3gp_H263_176x144_56kbps_25fps_AAC_Mono_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_11025hz, 176, 144);
- }
+ MediaPlayer mp = MediaPlayer.create(mContext, resid);
+ mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
+ mp.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
- public void testLocalVideo_3gp_H263_176x144_56kbps_25fps_AAC_Mono_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_22050hz, 176, 144);
- }
+ assertFalse(mp.isPlaying());
+ mp.start();
+ assertTrue(mp.isPlaying());
- public void testLocalVideo_3gp_H263_176x144_56kbps_25fps_AAC_Stereo_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_11025hz, 176, 144);
- }
+ assertFalse(mp.isLooping());
+ mp.setLooping(true);
+ assertTrue(mp.isLooping());
- public void testLocalVideo_3gp_H263_176x144_56kbps_25fps_AAC_Stereo_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_11025hz, 176, 144);
- }
+ assertEquals(mp3Duration, mp.getDuration(), tolerance);
+ int pos = mp.getCurrentPosition();
+ assertTrue(pos >= 0);
+ assertTrue(pos < mp3Duration - seekDuration);
- public void testLocalVideo_3gp_H263_176x144_56kbps_25fps_AAC_Stereo_128kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_25fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
+ mp.seekTo(pos + seekDuration);
+ assertEquals(pos + seekDuration, mp.getCurrentPosition(), tolerance);
- public void testLocalVideo_3gp_H263_176x144_56kbps_25fps_AAC_Stereo_128kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_56kbps_25fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
+ // test pause and restart
+ mp.pause();
+ Thread.sleep(SLEEP_TIME);
+ assertFalse(mp.isPlaying());
+ mp.start();
+ assertTrue(mp.isPlaying());
- public void testLocalVideo_3gp_H263_176x144_300kbps_12fps_AAC_Mono_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_12fps_aac_mono_24kbps_11025hz, 176, 144);
- }
+ // test stop and restart
+ mp.stop();
+ mp.reset();
+ AssetFileDescriptor afd = mResources.openRawResourceFd(resid);
+ mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+ afd.close();
+ mp.prepare();
+ assertFalse(mp.isPlaying());
+ mp.start();
+ assertTrue(mp.isPlaying());
- public void testLocalVideo_3gp_H263_176x144_300kbps_12fps_AAC_Mono_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_12fps_aac_mono_24kbps_22050hz, 176, 144);
- }
+ // waiting to complete
+ while(mp.isPlaying()) {
+ Thread.sleep(SLEEP_TIME);
+ }
- public void testLocalVideo_3gp_H263_176x144_300kbps_12fps_AAC_Stereo_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_12fps_aac_stereo_24kbps_11025hz, 176, 144);
+ mp.release();
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "MediaPlayer",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDisplay",
+ args = {SurfaceHolder.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setScreenOnWhilePlaying",
+ args = {boolean.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "getVideoHeight",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "getVideoWidth",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setVolume",
+ args = {float.class, float.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDataSource",
+ args = {FileDescriptor.class}
+ )
+ })
+
+ /*
+ * Initializes the message looper so that the mediaPlayer object can
+ * receive the callback messages.
+ */
+ private static void initializeMessageLooper() {
+ new Thread() {
+ @Override
+ public void run() {
+ // Set up a looper to be used by camera.
+ Looper.prepare();
+ // Save the looper so that we can terminate this thread
+ // after we are done with it.
+ sLooper = Looper.myLooper();
+ synchronized (sLock) {
+ sLock.notify();
+ }
+ Looper.loop(); // Blocks forever until Looper.quit() is called.
+ Log.v(TAG, "initializeMessageLooper: quit.");
+ }
+ }.start();
}
- public void testLocalVideo_3gp_H263_176x144_300kbps_12fps_AAC_Stereo_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_12fps_aac_stereo_24kbps_11025hz, 176, 144);
+ /*
+ * Terminates the message looper thread.
+ */
+ private static void terminateMessageLooper() {
+ sLooper.quit();
}
- public void testLocalVideo_3gp_H263_176x144_300kbps_12fps_AAC_Stereo_128kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_12fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
+ public void testPlayVideo() throws Exception {
+ final int expectedVideoWidth = 352; // width of R.raw.testvideo
+ final int expectedVideoHeight = 288; // height of R.raw.testvideo
+ final float leftVolume = 0.5f;
+ final float rightVolume = 0.5f;
+ final int resid = R.raw.testvideo;
+
+ sLock = new Object();
+ sVideoSizeChanged = new Object();
+ MediaPlayer mp = new MediaPlayer();
+ AssetFileDescriptor afd = mResources.openRawResourceFd(resid);
+ mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+ afd.close();
+ mp.setDisplay(getActivity().getSurfaceHolder());
+ mp.setScreenOnWhilePlaying(true);
+ mp.prepare();
+
+ int videoWidth = 0;
+ int videoHeight = 0;
+ synchronized (sLock) {
+ initializeMessageLooper();
+ try {
+ sLock.wait(WAIT_FOR_COMMAND_TO_COMPLETE);
+ } catch(Exception e) {
+ Log.v(TAG, "looper was interrupted.");
+ return;
+ }
+ }
+ try {
+ mp.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
+ synchronized (sVideoSizeChanged) {
+ try {
+ sVideoSizeChanged.wait(WAIT_FOR_COMMAND_TO_COMPLETE);
+ } catch (Exception e) {
+ Log.v(TAG, "wait was interrupted");
+ }
+ }
+ videoWidth = mp.getVideoWidth();
+ videoHeight = mp.getVideoHeight();
+ terminateMessageLooper();
+ } catch (Exception e) {
+ Log.e(TAG, e.getMessage());
+ }
+ assertEquals(expectedVideoWidth, videoWidth);
+ assertEquals(expectedVideoHeight, videoHeight);
- public void testLocalVideo_3gp_H263_176x144_300kbps_12fps_AAC_Stereo_128kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_12fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
+ mp.start();
+ mp.setVolume(leftVolume, rightVolume);
- public void testLocalVideo_3gp_H263_176x144_300kbps_25fps_AAC_Mono_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_25fps_aac_mono_24kbps_11025hz, 176, 144);
- }
+ // waiting to complete
+ while (mp.isPlaying()) {
+ Thread.sleep(SLEEP_TIME);
+ }
- public void testLocalVideo_3gp_H263_176x144_300kbps_25fps_AAC_Mono_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_25fps_aac_mono_24kbps_22050hz, 176, 144);
- }
+ mp.release();
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnBufferingUpdateListener",
+ args = {OnBufferingUpdateListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDataSource",
+ args = {String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDisplay",
+ args = {SurfaceHolder.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "start",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "stop",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "prepare",
+ args = {}
+ )
+ })
+
+ public void testPlayMp3Stream1() throws Throwable {
+ streamTest("ringer.mp3", false, false);
+ }
+ public void testPlayMp3Stream2() throws Throwable {
+ streamTest("ringer.mp3", false, false);
+ }
+ public void testPlayMp3StreamRedirect() throws Throwable {
+ streamTest("ringer.mp3", true, false);
+ }
+ public void testPlayMp3StreamNoLength() throws Throwable {
+ streamTest("noiseandchirps.mp3", false, true);
+ }
+ public void testPlayOggStream() throws Throwable {
+ streamTest("noiseandchirps.ogg", false, false);
+ }
+ public void testPlayOggStreamRedirect() throws Throwable {
+ streamTest("noiseandchirps.ogg", true, false);
+ }
+ public void testPlayOggStreamNoLength() throws Throwable {
+ streamTest("noiseandchirps.ogg", false, true);
+ }
+
+ private void streamTest(String name, boolean redirect, boolean nolength) throws Throwable {
+ mServer = new CtsTestServer(mContext);
+ String stream_url = null;
+ if (redirect) {
+ // Stagefright doesn't have a limit, but we can't test support of infinite redirects
+ // Up to 4 redirects seems reasonable though.
+ stream_url = mServer.getRedirectingAssetUrl(name, 4);
+ } else {
+ stream_url = mServer.getAssetUrl(name);
+ }
+ if (nolength) {
+ stream_url = stream_url + "?" + CtsTestServer.NOLENGTH_POSTFIX;
+ }
- public void testLocalVideo_3gp_H263_176x144_300kbps_25fps_AAC_Stereo_24kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_25fps_aac_stereo_24kbps_11025hz, 176, 144);
- }
+ mMediaPlayer.setDataSource(stream_url);
- public void testLocalVideo_3gp_H263_176x144_300kbps_25fps_AAC_Stereo_24kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_25fps_aac_stereo_24kbps_11025hz, 176, 144);
- }
+ mMediaPlayer.setDisplay(getActivity().getSurfaceHolder());
+ mMediaPlayer.setScreenOnWhilePlaying(true);
- public void testLocalVideo_3gp_H263_176x144_300kbps_25fps_AAC_Stereo_128kbps_11025Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_25fps_aac_stereo_128kbps_11025hz, 176, 144);
- }
+ mOnBufferingUpdateCalled.reset();
+ mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
+ public void onBufferingUpdate(MediaPlayer mp, int percent) {
+ mOnBufferingUpdateCalled.signal();
+ }
+ });
- public void testLocalVideo_3gp_H263_176x144_300kbps_25fps_AAC_Stereo_128kbps_22050Hz()
- throws Exception {
- playVideoTest(
- R.raw.video_176x144_3gp_h263_300kbps_25fps_aac_stereo_128kbps_22050hz, 176, 144);
- }
+ assertFalse(mOnBufferingUpdateCalled.signalled);
+ mMediaPlayer.prepare();
+ if (nolength) {
+ mMediaPlayer.start();
+ Thread.sleep(LONG_SLEEP_TIME);
+ assertFalse(mMediaPlayer.isPlaying());
+ } else {
+ mOnBufferingUpdateCalled.waitForSignal();
+ mMediaPlayer.start();
+ Thread.sleep(SLEEP_TIME);
+ }
+ mMediaPlayer.stop();
+ mMediaPlayer.reset();
+ }
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnCompletionListener",
+ args = {OnCompletionListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnErrorListener",
+ args = {OnErrorListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnPreparedListener",
+ args = {OnPreparedListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnSeekCompleteListener",
+ args = {OnSeekCompleteListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnVideoSizeChangedListener",
+ args = {OnVideoSizeChangedListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setOnInfoListener",
+ args = {MediaPlayer.OnInfoListener.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDataSource",
+ args = {FileDescriptor.class, long.class, long.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "prepare",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "start",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "stop",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "isPlaying",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "seekTo",
+ args = {int.class}
+ )
+ })
public void testCallback() throws Throwable {
final int mp4Duration = 8484;
- loadResource(R.raw.testvideo);
+ AssetFileDescriptor afd = mResources.openRawResourceFd(R.raw.testvideo);
+ try {
+ mMediaPlayer.setDataSource(
+ afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+ } finally {
+ afd.close();
+ }
+
mMediaPlayer.setDisplay(getActivity().getSurfaceHolder());
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
- @Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mOnVideoSizeChangedCalled.signal();
}
});
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
- @Override
public void onPrepared(MediaPlayer mp) {
mOnPrepareCalled.signal();
}
});
mMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
- @Override
public void onSeekComplete(MediaPlayer mp) {
mOnSeekCompleteCalled.signal();
}
@@ -365,14 +585,12 @@ public class MediaPlayerTest extends MediaPlayerTestBase {
mOnCompletionCalled.reset();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
- @Override
public void onCompletion(MediaPlayer mp) {
mOnCompletionCalled.signal();
}
});
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
- @Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mOnErrorCalled.signal();
return false;
@@ -380,84 +598,83 @@ public class MediaPlayerTest extends MediaPlayerTestBase {
});
mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
- @Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
mOnInfoCalled.signal();
return false;
}
});
- assertFalse(mOnPrepareCalled.isSignalled());
- assertFalse(mOnVideoSizeChangedCalled.isSignalled());
+ assertFalse(mOnPrepareCalled.signalled);
+ assertFalse(mOnVideoSizeChangedCalled.signalled);
mMediaPlayer.prepare();
mOnPrepareCalled.waitForSignal();
mOnVideoSizeChangedCalled.waitForSignal();
- mOnSeekCompleteCalled.reset();
+ mOnSeekCompleteCalled.signalled = false;
mMediaPlayer.seekTo(mp4Duration >> 1);
mOnSeekCompleteCalled.waitForSignal();
- assertFalse(mOnCompletionCalled.isSignalled());
+ assertFalse(mOnCompletionCalled.signalled);
mMediaPlayer.start();
while(mMediaPlayer.isPlaying()) {
Thread.sleep(SLEEP_TIME);
}
assertFalse(mMediaPlayer.isPlaying());
mOnCompletionCalled.waitForSignal();
- assertFalse(mOnErrorCalled.isSignalled());
+ assertFalse(mOnErrorCalled.signalled);
mMediaPlayer.stop();
mMediaPlayer.start();
mOnErrorCalled.waitForSignal();
}
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDataSource",
+ args = {Context.class, Uri.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "setDataSource",
+ args = {String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "create",
+ args = {Context.class, Uri.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "create",
+ args = {Context.class, Uri.class, SurfaceHolder.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL,
+ method = "prepareAsync",
+ args = {}
+ )
+ })
public void testRecordAndPlay() throws Exception {
- if (!hasMicrophone()) {
- return;
- }
- File outputFile = new File(Environment.getExternalStorageDirectory(),
- "record_and_play.3gp");
- String outputFileLocation = outputFile.getAbsolutePath();
- try {
- recordMedia(outputFileLocation);
- MediaPlayer mp = new MediaPlayer();
- try {
- mp.setDataSource(outputFileLocation);
- mp.prepareAsync();
- Thread.sleep(SLEEP_TIME);
- playAndStop(mp);
- } finally {
- mp.release();
- }
-
- Uri uri = Uri.parse(outputFileLocation);
- mp = new MediaPlayer();
- try {
- mp.setDataSource(mContext, uri);
- mp.prepareAsync();
- Thread.sleep(SLEEP_TIME);
- playAndStop(mp);
- } finally {
- mp.release();
- }
+ recordMedia();
+ MediaPlayer mp = new MediaPlayer();
+ mp.setDataSource(mSourceMediaOnSdcard);
+ mp.prepareAsync();
+ Thread.sleep(SLEEP_TIME);
+ playAndStop(mp);
+ mp.reset();
+ Uri uri = Uri.parse(mSourceMediaOnSdcard);
+ mp = new MediaPlayer();
+ mp.setDataSource(mContext, uri);
+ mp.prepareAsync();
+ Thread.sleep(SLEEP_TIME);
+ playAndStop(mp);
+ mp.release();
- try {
- mp = MediaPlayer.create(mContext, uri);
- playAndStop(mp);
- } finally {
- if (mp != null) {
- mp.release();
- }
- }
+ mp = MediaPlayer.create(mContext, uri);
+ playAndStop(mp);
+ mp.release();
- try {
- mp = MediaPlayer.create(mContext, uri, getActivity().getSurfaceHolder());
- playAndStop(mp);
- } finally {
- if (mp != null) {
- mp.release();
- }
- }
- } finally {
- outputFile.delete();
- }
+ mp = MediaPlayer.create(mContext, uri, getActivity().getSurfaceHolder());
+ playAndStop(mp);
+ mp.release();
}
private void playAndStop(MediaPlayer mp) throws Exception {
@@ -466,25 +683,18 @@ public class MediaPlayerTest extends MediaPlayerTestBase {
mp.stop();
}
- private void recordMedia(String outputFile) throws Exception {
+ private void recordMedia() throws Exception {
MediaRecorder mr = new MediaRecorder();
- try {
- mr.setAudioSource(MediaRecorder.AudioSource.MIC);
- mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
- mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- mr.setOutputFile(outputFile);
+ mr.setAudioSource(MediaRecorder.AudioSource.MIC);
+ mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
+ mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
+ mr.setOutputFile(mSourceMediaOnSdcard);
- mr.prepare();
- mr.start();
- Thread.sleep(SLEEP_TIME);
- mr.stop();
- } finally {
- mr.release();
- }
+ mr.prepare();
+ mr.start();
+ Thread.sleep(SLEEP_TIME);
+ mr.stop();
+ mr.release();
}
- private boolean hasMicrophone() {
- return getActivity().getPackageManager().hasSystemFeature(
- PackageManager.FEATURE_MICROPHONE);
- }
}
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java b/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
deleted file mode 100644
index 6b6f3d7..0000000
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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.media.cts;
-
-import android.content.Context;
-import android.content.res.AssetFileDescriptor;
-import android.content.res.Resources;
-import android.media.MediaPlayer;
-import android.test.ActivityInstrumentationTestCase2;
-
-import java.io.IOException;
-import java.util.logging.Logger;
-
-/**
- * Base class for tests which use MediaPlayer to play audio or video.
- */
-public class MediaPlayerTestBase extends ActivityInstrumentationTestCase2 {
- private static final Logger LOG = Logger.getLogger(MediaPlayerTestBase.class.getName());
-
- protected static final int SLEEP_TIME = 1000;
- protected static final int LONG_SLEEP_TIME = 6000;
- protected static final int STREAM_RETRIES = 5;
-
- public static class Monitor {
- private boolean signalled;
-
- public synchronized void reset() {
- signalled = false;
- }
-
- public synchronized void signal() {
- signalled = true;
- notifyAll();
- }
-
- public synchronized void waitForSignal() throws InterruptedException {
- while (!signalled) {
- wait();
- }
- }
-
- public synchronized boolean isSignalled() {
- return signalled;
- }
- }
-
- protected Monitor mOnVideoSizeChangedCalled = new Monitor();
- protected Monitor mOnBufferingUpdateCalled = new Monitor();
- protected Monitor mOnPrepareCalled = new Monitor();
- protected Monitor mOnSeekCompleteCalled = new Monitor();
- protected Monitor mOnCompletionCalled = new Monitor();
- protected Monitor mOnInfoCalled = new Monitor();
- protected Monitor mOnErrorCalled = new Monitor();
-
- protected Context mContext;
- protected Resources mResources;
-
- /*
- * InstrumentationTestRunner.onStart() calls Looper.prepare(), which creates a looper
- * for the current thread. However, since we don't actually call loop() in the test,
- * any messages queued with that looper will never be consumed. We instantiate the player
- * in the constructor, before setUp(), so that its constructor does not see the
- * nonfunctional Looper.
- */
- protected MediaPlayer mMediaPlayer = new MediaPlayer();
-
- public MediaPlayerTestBase() {
- super(MediaStubActivity.class);
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mContext = getInstrumentation().getTargetContext();
- mResources = mContext.getResources();
- }
-
- @Override
- protected void tearDown() throws Exception {
- if (mMediaPlayer != null) {
- mMediaPlayer.release();
- }
- super.tearDown();
- }
-
- protected void loadResource(int resid) throws Exception {
- AssetFileDescriptor afd = mResources.openRawResourceFd(resid);
- try {
- mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
- afd.getLength());
- } finally {
- afd.close();
- }
- }
-
- protected void playLiveVideoTest(String path, int playTime) throws Exception {
- playVideoWithRetries(path, null, null, playTime);
- }
-
- protected void playVideoTest(String path, int width, int height) throws Exception {
- playVideoWithRetries(path, width, height, 0);
- }
-
- protected void playVideoWithRetries(String path, Integer width, Integer height, int playTime)
- throws Exception {
- boolean playedSuccessfully = false;
- for (int i = 0; i < STREAM_RETRIES; i++) {
- try {
- mMediaPlayer.setDataSource(path);
- playLoadedVideo(width, height, playTime);
- playedSuccessfully = true;
- break;
- } catch (PrepareFailedException e) {
- // prepare() can fail because of network issues, so try again
- LOG.warning("prepare() failed on try " + i + ", trying playback again");
- }
- }
- assertTrue("Stream did not play successfully after all attempts", playedSuccessfully);
- }
-
- protected void playVideoTest(int resid, int width, int height) throws Exception {
- loadResource(resid);
- playLoadedVideo(width, height, 0);
- }
-
- /**
- * Play a video which has already been loaded with setDataSource().
- *
- * @param width width of the video to verify, or null to skip verification
- * @param height height of the video to verify, or null to skip verification
- * @param playTime length of time to play video, or 0 to play entire video
- */
- private void playLoadedVideo(final Integer width, final Integer height, int playTime)
- throws Exception {
- final float leftVolume = 0.5f;
- final float rightVolume = 0.5f;
-
- mMediaPlayer.setDisplay(getActivity().getSurfaceHolder());
- mMediaPlayer.setScreenOnWhilePlaying(true);
- mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
- @Override
- public void onVideoSizeChanged(MediaPlayer mp, int w, int h) {
- mOnVideoSizeChangedCalled.signal();
- if (width != null) {
- assertEquals(width.intValue(), w);
- }
- if (height != null) {
- assertEquals(height.intValue(), h);
- }
- }
- });
- mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
- @Override
- public boolean onError(MediaPlayer mp, int what, int extra) {
- fail("Media player had error " + what + " playing video");
- return true;
- }
- });
- try {
- mMediaPlayer.prepare();
- } catch (IOException e) {
- mMediaPlayer.reset();
- throw new PrepareFailedException();
- }
-
- mMediaPlayer.start();
- mOnVideoSizeChangedCalled.waitForSignal();
- mMediaPlayer.setVolume(leftVolume, rightVolume);
-
- // waiting to complete
- if (playTime == 0) {
- while (mMediaPlayer.isPlaying()) {
- Thread.sleep(SLEEP_TIME);
- }
- } else {
- Thread.sleep(playTime);
- }
- }
-
- private static class PrepareFailedException extends Exception {}
-}
diff --git a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
index db136f2..70b108e 100644
--- a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
@@ -20,7 +20,6 @@ import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
-import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
@@ -151,9 +150,6 @@ public class MediaRecorderTest extends ActivityInstrumentationTestCase2 0);
}
-
- private boolean hasCamera() {
- return getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
- }
-
- private boolean hasMicrophone() {
- return getActivity().getPackageManager().hasSystemFeature(
- PackageManager.FEATURE_MICROPHONE);
- }
}
diff --git a/tests/tests/media/src/android/media/cts/MediaScannerNotificationTest.java b/tests/tests/media/src/android/media/cts/MediaScannerNotificationTest.java
deleted file mode 100644
index 3c201ca..0000000
--- a/tests/tests/media/src/android/media/cts/MediaScannerNotificationTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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.media.cts;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.Uri;
-import android.os.Environment;
-import android.test.AndroidTestCase;
-
-
-public class MediaScannerNotificationTest extends AndroidTestCase {
- private static final int MEDIA_SCANNER_TIME_OUT = 2000;
-
- private ScannerNotificationReceiver mScannerStartedReceiver;
- private ScannerNotificationReceiver mScannerFinishedReceiver;
- private boolean mScannerStarted;
- private boolean mScannerFinished;
-
- public void testMediaScannerNotification() throws InterruptedException {
- mScannerStarted = false;
- mScannerFinished = false;
-
- IntentFilter scannerStartedIntentFilter = new IntentFilter(
- Intent.ACTION_MEDIA_SCANNER_STARTED);
- scannerStartedIntentFilter.addDataScheme("file");
- IntentFilter scannerFinshedIntentFilter = new IntentFilter(
- Intent.ACTION_MEDIA_SCANNER_FINISHED);
- scannerFinshedIntentFilter.addDataScheme("file");
-
- mScannerStartedReceiver = new ScannerNotificationReceiver(
- Intent.ACTION_MEDIA_SCANNER_STARTED);
- mScannerFinishedReceiver = new ScannerNotificationReceiver(
- Intent.ACTION_MEDIA_SCANNER_FINISHED);
-
- getContext().registerReceiver(mScannerStartedReceiver, scannerStartedIntentFilter);
- getContext().registerReceiver(mScannerFinishedReceiver, scannerFinshedIntentFilter);
-
- getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
- + Environment.getExternalStorageDirectory())));
- mScannerStartedReceiver.waitForCalls(1, MEDIA_SCANNER_TIME_OUT);
- mScannerFinishedReceiver.waitForCalls(1, MEDIA_SCANNER_TIME_OUT);
-
- assertTrue(mScannerStarted);
- assertTrue(mScannerFinished);
- }
-
- class ScannerNotificationReceiver extends BroadcastReceiver {
- private int mCalls;
- private int mExpectedCalls;
- private String mAction;
- private Object mLock;
-
- ScannerNotificationReceiver(String action) {
- mAction = action;
- reset();
- mLock = new Object();
- }
-
- void reset() {
- mExpectedCalls = Integer.MAX_VALUE;
- mCalls = 0;
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.getAction().equals(mAction)) {
- if (mAction.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
- mScannerStarted = true;
- } else if (mAction.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
- mScannerFinished = true;
- }
- synchronized (mLock) {
- mCalls += 1;
- if (mCalls >= mExpectedCalls) {
- mLock.notify();
- }
- }
- }
- }
-
- public void waitForCalls(int expectedCalls, long timeout) throws InterruptedException {
- synchronized(mLock) {
- mExpectedCalls = expectedCalls;
- if (mCalls < mExpectedCalls) {
- mLock.wait(timeout);
- }
- }
- }
- }
-}
diff --git a/tests/tests/nativemedia/Android.mk b/tests/tests/nativemedia/Android.mk
deleted file mode 100644
index 928ebcd..0000000
--- a/tests/tests/nativemedia/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# Build the unit tests.
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_C_INCLUDES:= \
- bionic \
- bionic/libstdc++/include \
- external/gtest/include \
- system/media/wilhelm/include \
- external/stlport/stlport \
- system/media/wilhelm/src/ut
-
-LOCAL_SRC_FILES:= \
- src/SLObjectCreationTest.cpp
-
-LOCAL_SHARED_LIBRARIES := \
- libutils \
- libOpenSLES \
- libstlport
-
-LOCAL_STATIC_LIBRARIES := \
- libOpenSLESUT \
- libgtest
-
-LOCAL_CFLAGS += -DXP_UNIX
-
-LOCAL_MODULE:= NativeMediaTest
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
-
-include $(BUILD_EXECUTABLE)
\ No newline at end of file
diff --git a/tests/tests/nativemedia/src/SLObjectCreationTest.cpp b/tests/tests/nativemedia/src/SLObjectCreationTest.cpp
deleted file mode 100644
index e63e42f..0000000
--- a/tests/tests/nativemedia/src/SLObjectCreationTest.cpp
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * 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.
- */
-
-/**
- * Test for testing the creation of OpenSL ES objects under various configurations (determined
- * by their data source and sink types) that are expected to be supported.
- * The tests verify the creation and completion of the call to Realize() for the following objects:
- * - Engine
- * - OutputMix
- * - AudioPlayer:
- * * source is URI
- * * source is FD
- * * source is BufferQueue of PCM buffers
- * * source is AndroidBufferQueue of MP2TS buffers
- * * source is URI, sink is BufferQueue of PCM buffers
- * * source is FD, sink is BufferQueue of PCM buffers
- * * source is AndroidBufferQueue of AAC ADTS buffers, sink is BufferQueue of PCM buffers
- * - AudioRecorder
- * * source is IO device, sink is BufferQueue of PCM buffers
- */
-
-#define LOG_NDEBUG 0
-#define LOG_TAG "SLObjectCreationTest"
-
-#include
-#include "SLES/OpenSLES.h"
-#include "SLES/OpenSLES_Android.h"
-#include "OpenSLESUT.h"
-#include
-
-//-----------------------------------------------------------------
-/* Checks for error and displays the error code if any */
-bool IsOk(SLresult res) {
- if (SL_RESULT_SUCCESS != res) {
- const char *str = slesutResultToString(res);
- if (NULL == str)
- str = "unknown";
- fprintf(stderr, "IsOk failure: %s (0x%x), exiting\n", str, res);
- return false;
- }
- return true;
-}
-
-//-----------------------------------------------------------------
-class SLObjectCreationTest : public ::testing::Test {
-
-protected:
- SLresult res;
- SLObjectItf engineObj, outputMixObj, audioPlayerObj;
- SLEngineItf engineItf;
-
- SLDataSource audioSource;
- SLDataSink audioSink;
- SLDataLocator_URI locatorUriSrc;
- SLDataLocator_AndroidBufferQueue locatorAbqSrc;
- SLDataLocator_AndroidFD locatorFdSrc;
- SLDataFormat_MIME formatMimeSrc;
-
- SLDataLocator_OutputMix locatorOutputmixSnk;
- SLDataLocator_AndroidSimpleBufferQueue locatorBqSnk;
- SLDataFormat_PCM formatPcmSnk;
-
- SLObjectCreationTest() { }
-
- virtual ~SLObjectCreationTest() { }
-
- /* Test setup*/
- virtual void SetUp() {
- LOGV("Test Setup()");
- res = SL_RESULT_UNKNOWN_ERROR;
- engineItf = NULL;
- engineObj = NULL;
- outputMixObj = NULL;
- audioPlayerObj = NULL;
- // Engine creation
- res = slCreateEngine(&engineObj, 0, NULL, 0, NULL, NULL);
- ASSERT_TRUE(IsOk(res));
- res = (*engineObj)->Realize(engineObj, SL_BOOLEAN_FALSE);
- ASSERT_TRUE(IsOk(res));
- res = (*engineObj)->GetInterface(engineObj, SL_IID_ENGINE, &engineItf);
- ASSERT_TRUE(IsOk(res));
- ASSERT_TRUE(NULL != engineItf);
- }
-
- virtual void TearDown() {
- LOGV("Test TearDown()");
- if (audioPlayerObj) {
- (*audioPlayerObj)->Destroy(audioPlayerObj);
- audioPlayerObj = NULL;
- }
- if (outputMixObj) {
- (*outputMixObj)->Destroy(outputMixObj);
- outputMixObj = NULL;
- }
- if (engineObj){
- (*engineObj)->Destroy(engineObj);
- engineObj = NULL;
- }
- }
-
- //---------------------------------------------------------------------------------------------
- // Test implementation convenience methods (to avoid code duplication)
-
- void AudioPlayerCreation() {
- res = (*engineItf)->CreateAudioPlayer(engineItf, &audioPlayerObj,
- &audioSource, &audioSink, 0, NULL/*iidArray*/, NULL/*required*/);
- ASSERT_TRUE(IsOk(res));
- ASSERT_TRUE(NULL != audioPlayerObj);
- res = (*audioPlayerObj)->Realize(audioPlayerObj, SL_BOOLEAN_FALSE);
- ASSERT_TRUE(IsOk(res));
- }
-
- void OutputMixSinkInitialization() {
- locatorOutputmixSnk.locatorType = SL_DATALOCATOR_OUTPUTMIX;
- locatorOutputmixSnk.outputMix = outputMixObj; // created in OutputMixCreation()
- audioSink.pLocator = &locatorOutputmixSnk;
- audioSink.pFormat = NULL;
- }
-
- void UriSourceInitialization() {
- locatorUriSrc.locatorType = SL_DATALOCATOR_URI;
- locatorUriSrc.URI = (SLchar*) "/dummyPath/dummyFile.mp3";
- formatMimeSrc.formatType = SL_DATAFORMAT_MIME;
- formatMimeSrc.mimeType = (SLchar *) NULL;
- formatMimeSrc.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
- audioSource.pLocator = &locatorUriSrc;
- audioSource.pFormat = &formatMimeSrc;
- }
-
- void FdSourceInitialization() {
- locatorFdSrc.locatorType = SL_DATALOCATOR_ANDROIDFD;
- locatorFdSrc.fd = (SLint32) 1;// a positive value to fake a valid FD
- locatorFdSrc.length = 10;
- locatorFdSrc.offset = 0;
- formatMimeSrc.formatType = SL_DATAFORMAT_MIME;
- formatMimeSrc.mimeType = (SLchar *) NULL;
- formatMimeSrc.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
- audioSource.pLocator = &locatorFdSrc;
- audioSource.pFormat = &formatMimeSrc;
- }
-
- void PcmBqSinkInitialization() {
- locatorBqSnk.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
- locatorBqSnk.numBuffers = 16;
- formatPcmSnk.formatType = SL_DATAFORMAT_PCM;
- formatPcmSnk.numChannels = 1;
- formatPcmSnk.samplesPerSec = SL_SAMPLINGRATE_8;
- formatPcmSnk.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
- formatPcmSnk.containerSize = 16;
- formatPcmSnk.channelMask = SL_SPEAKER_FRONT_LEFT;
- formatPcmSnk.endianness = SL_BYTEORDER_LITTLEENDIAN;
- audioSink.pLocator = (void *) &locatorBqSnk;
- audioSink.pFormat = (void *) &formatPcmSnk;
- }
-
- //---------------------------------------------------------------------------------------------
- // Tests
-
- /* Test case for creating an AudioPlayer object */
- void OutputMixCreation() {
- res = (*engineItf)->CreateOutputMix(engineItf, &outputMixObj,
- 0, NULL/*iidArray*/, NULL/*required*/);
- ASSERT_TRUE(IsOk(res));
- ASSERT_TRUE(NULL != outputMixObj);
- res = (*outputMixObj)->Realize(outputMixObj, SL_BOOLEAN_FALSE);
- ASSERT_TRUE(IsOk(res));
- }
-
- /* Test case for creating an AudioPlayer object that plays from a URI */
- void AudioPlayerFromUriCreation() {
- // source: URI
- UriSourceInitialization();
- // sink: OutputMix
- OutputMixSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioPlayer object that plays from a FD */
- void AudioPlayerFromFdCreation() {
- // source: FD
- FdSourceInitialization();
- // sink: OutputMix
- OutputMixSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioPlayer object that plays from a PCM BufferQueue */
- void AudioPlayerFromPcmBqCreation() {
- // source: PCM BufferQueue
- SLDataLocator_BufferQueue locatorBufferQueue;
- locatorBufferQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE;
- locatorBufferQueue.numBuffers = 16;
- SLDataFormat_PCM pcm;
- pcm.formatType = SL_DATAFORMAT_PCM;
- pcm.numChannels = 2;
- pcm.samplesPerSec = SL_SAMPLINGRATE_44_1;
- pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
- pcm.containerSize = 16;
- pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
- pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
- audioSource.pLocator = &locatorBufferQueue;
- audioSource.pFormat = &pcm;
-
- // sink: OutputMix
- OutputMixSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioPlayer object that plays from Transport Stream ABQ */
- void AudioPlayerFromTsAbqCreation() {
- // source: transport stream in an AndroidBufferQueue
- locatorAbqSrc.locatorType = SL_DATALOCATOR_ANDROIDBUFFERQUEUE;
- locatorAbqSrc.numBuffers = 16;
- formatMimeSrc.formatType = SL_DATAFORMAT_MIME;
- formatMimeSrc.mimeType = (SLchar *) "video/mp2ts";
- formatMimeSrc.containerType = SL_CONTAINERTYPE_MPEG_TS;
- audioSource.pFormat = (void *)&formatMimeSrc;
- audioSource.pLocator = (void *)&locatorAbqSrc;
-
- // sink: OutputMix
- OutputMixSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioPlayer object that decodes from a URI to a PCM BQ */
- void AudioPlayerFromUriToPcmBqCreation() {
- // source: URI
- UriSourceInitialization();
- // sink: PCM BufferQueue
- PcmBqSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioPlayer object that decodes from a FD to a PCM BQ */
- void AudioPlayerFromFdToPcmBqCreation() {
- // source: FD
- FdSourceInitialization();
- // sink: PCM BufferQueue
- PcmBqSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioPlayer object that decodes from a ADTS ABQ to a PCM BQ */
- void AudioPlayerFromAdtsAbqToPcmBqCreation() {
- // source: ADTS AndroidBufferQueue
- locatorAbqSrc.locatorType = SL_DATALOCATOR_ANDROIDBUFFERQUEUE;
- locatorAbqSrc.numBuffers = 16;
- formatMimeSrc.formatType = SL_DATAFORMAT_MIME;
- formatMimeSrc.mimeType = (SLchar *)"audio/aac-adts";
- formatMimeSrc.containerType = SL_CONTAINERTYPE_RAW;
- audioSource.pLocator = (void *) &locatorAbqSrc;
- audioSource.pFormat = (void *) &formatMimeSrc;
-
- // sink: PCM BufferQueue
- PcmBqSinkInitialization();
- // AudioPlayer creation
- AudioPlayerCreation();
- }
-
- /* Test case for creating an AudioRecorder object */
- void AudioRecorderCreation() {
- // source: IO device
- SLDataLocator_IODevice locatorIoDeviceSrc;
- locatorIoDeviceSrc.locatorType = SL_DATALOCATOR_IODEVICE;
- locatorIoDeviceSrc.deviceType = SL_IODEVICE_AUDIOINPUT;
- locatorIoDeviceSrc.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
- locatorIoDeviceSrc.device = NULL;
- audioSource.pLocator = (void *) &locatorIoDeviceSrc;
- audioSource.pFormat = NULL;
-
- // sink: PCM BufferQueue
- PcmBqSinkInitialization();
-
- // AudioRecorder creation
- SLObjectItf audioRecorderObj = NULL;
- res = (*engineItf)->CreateAudioRecorder(engineItf, &audioRecorderObj,
- &audioSource, &audioSink, 0, NULL/*iidArray*/, NULL/*required*/);
- ASSERT_TRUE(IsOk(res));
- ASSERT_TRUE(NULL != audioRecorderObj);
- res = (*audioRecorderObj)->Realize(audioRecorderObj, SL_BOOLEAN_FALSE);
- ASSERT_TRUE(IsOk(res));
-
- // AudioRecorder destruction
- (*audioRecorderObj)->Destroy(audioRecorderObj);
- }
-};
-
-//-------------------------------------------------------------------------------------------------
-TEST_F(SLObjectCreationTest, testEngineCreation) {
- LOGV("Test Fixture: EngineCreation");
- // nothing to do here that isn't done in SetUp()
-}
-
-TEST_F(SLObjectCreationTest, testOutputMixCreation) {
- LOGV("Test Fixture: OutputMixCreation");
- OutputMixCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromUriCreation) {
- LOGV("Test Fixture: AudioPlayerFromUriCreation");
- // required for AudioPlayer creation
- OutputMixCreation();
- AudioPlayerFromUriCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromFdCreation) {
- LOGV("Test Fixture: AudioPlayerFromFdCreation");
- // required for AudioPlayer creation
- OutputMixCreation();
- AudioPlayerFromFdCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromPcmBqCreation) {
- LOGV("Test Fixture: AudioPlayerFromPcmBqCreation");
- // required for AudioPlayer creation
- OutputMixCreation();
- AudioPlayerFromPcmBqCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromTsAbqCreation) {
- LOGV("Test Fixture: AudioPlayerFromTsAbqCreation");
- // required for AudioPlayer creation
- OutputMixCreation();
- AudioPlayerFromTsAbqCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromUriToPcmBqCreation) {
- LOGV("Test Fixture: AudioPlayerFromUriToPcmBqCreation");
- AudioPlayerFromUriToPcmBqCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromFdToPcmBqCreation) {
- LOGV("Test Fixture: AudioPlayerFromFdToPcmBqCreation");
- AudioPlayerFromFdToPcmBqCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioPlayerFromAdtsAbqToPcmBqCreation) {
- LOGV("Test Fixture: AudioPlayerFromAdtsAbqToPcmBqCreation");
- AudioPlayerFromAdtsAbqToPcmBqCreation();
-}
-
-TEST_F(SLObjectCreationTest, testAudioRecorderCreation) {
- LOGV("Test Fixture: AudioRecorderCreation");
- AudioRecorderCreation();
-}
-
-int main(int argc, char **argv) {
- testing::InitGoogleTest(&argc, argv);
-
- return RUN_ALL_TESTS();
-}
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index cd80be2..96a935b 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -35,8 +35,6 @@ import android.net.wifi.WifiManager;
import android.test.AndroidTestCase;
import android.util.Log;
-import java.util.HashSet;
-import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -50,14 +48,13 @@ public class ConnectivityManagerTest extends AndroidTestCase {
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;
+ // device could have only one interface: data, wifi.
+ private static final int MIN_NUM_NETWORK_TYPES = 1;
+
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -172,20 +169,12 @@ public class ConnectivityManagerTest extends AndroidTestCase {
args = {int.class, int.class}
)
public void testRequestRouteToHost() {
- Set exceptionFreeTypes = new HashSet();
- exceptionFreeTypes.add(ConnectivityManager.TYPE_BLUETOOTH);
- exceptionFreeTypes.add(ConnectivityManager.TYPE_ETHERNET);
- exceptionFreeTypes.add(ConnectivityManager.TYPE_MOBILE);
- exceptionFreeTypes.add(ConnectivityManager.TYPE_MOBILE_DUN);
- exceptionFreeTypes.add(ConnectivityManager.TYPE_MOBILE_HIPRI);
- exceptionFreeTypes.add(ConnectivityManager.TYPE_MOBILE_MMS);
- exceptionFreeTypes.add(ConnectivityManager.TYPE_MOBILE_SUPL);
NetworkInfo[] ni = mCm.getAllNetworkInfo();
for (NetworkInfo n : ni) {
- if (n.isConnected() && exceptionFreeTypes.contains(n.getType())) {
- assertTrue("Network type: " + n.getType(), mCm.requestRouteToHost(n.getType(),
- HOST_ADDRESS));
+ // make sure network is up (except WIFI due to always fail)
+ if (n.isConnected() && (n.getType() != TYPE_WIFI)) {
+ assertTrue(mCm.requestRouteToHost(n.getType(), HOST_ADDRESS));
}
}
@@ -298,7 +287,7 @@ public class ConnectivityManagerTest extends AndroidTestCase {
}
public boolean waitForConnection() throws InterruptedException {
- return mReceiveLatch.await(30, TimeUnit.SECONDS);
+ return mReceiveLatch.await(10, TimeUnit.SECONDS);
}
}
}
diff --git a/tests/tests/net/src/android/net/cts/ListeningPortsTest.java b/tests/tests/net/src/android/net/cts/ListeningPortsTest.java
index bcec0fe..b6e6efb 100644
--- a/tests/tests/net/src/android/net/cts/ListeningPortsTest.java
+++ b/tests/tests/net/src/android/net/cts/ListeningPortsTest.java
@@ -46,7 +46,7 @@ public class ListeningPortsTest extends TestCase {
EXCEPTION_PATTERNS.add("[0-9A-F]{6}7F:[0-9A-F]{4}"); // IPv4 Loopback
// IPv6 exceptions
- EXCEPTION_PATTERNS.add("[0]{25}1[0]{6}:[0-9A-F]{4}"); // IPv6 Loopback
+ EXCEPTION_PATTERNS.add("[0]{31}1:[0-9A-F]{4}"); // IPv6 Loopback
EXCEPTION_PATTERNS.add("[0]{16}[0]{4}[0]{4}[0-9A-F]{6}7F:[0-9A-F]{4}"); // IPv4-6 Conversion
EXCEPTION_PATTERNS.add("[0]{16}[F]{4}[0]{4}[0-9A-F]{6}7F:[0-9A-F]{4}"); // IPv4-6 Conversion
}
@@ -118,18 +118,13 @@ public class ListeningPortsTest extends TestCase {
String localAddress = fields[1];
String state = fields[3];
- String uid = fields[7];
assertTrue(procFilePath + " should have an IP address in the second column",
isAddress(localAddress));
- String localIp = localAddress.split(":")[0];
- int localPort = Integer.parseInt(localAddress.split(":")[1], 16);
-
if (!isException(localAddress) && isPortListening(state, isTcp)) {
throw new ListeningPortsAssertionError(
- "Found port listening on addr=" + localIp + ", port="
- + localPort + ", UID=" + uid + " in " + procFilePath);
+ "Found port listening on " + localAddress + " in " + procFilePath);
}
}
} catch (FileNotFoundException notFound) {
diff --git a/tests/tests/net/src/android/net/cts/NetworkInfo_DetailedStateTest.java b/tests/tests/net/src/android/net/cts/NetworkInfo_DetailedStateTest.java
index 6b9b985..196e102 100644
--- a/tests/tests/net/src/android/net/cts/NetworkInfo_DetailedStateTest.java
+++ b/tests/tests/net/src/android/net/cts/NetworkInfo_DetailedStateTest.java
@@ -16,13 +16,12 @@
package android.net.cts;
+import android.net.NetworkInfo.DetailedState;
+import android.test.AndroidTestCase;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
-import android.net.NetworkInfo.DetailedState;
-import android.test.AndroidTestCase;
-
@TestTargetClass(DetailedState.class)
public class NetworkInfo_DetailedStateTest extends AndroidTestCase {
@@ -53,7 +52,7 @@ public class NetworkInfo_DetailedStateTest extends AndroidTestCase {
)
public void testValues() {
DetailedState[] expected = DetailedState.values();
- assertEquals(11, expected.length);
+ assertEquals(10, expected.length);
assertEquals(DetailedState.IDLE, expected[0]);
assertEquals(DetailedState.SCANNING, expected[1]);
assertEquals(DetailedState.CONNECTING, expected[2]);
@@ -64,7 +63,6 @@ public class NetworkInfo_DetailedStateTest extends AndroidTestCase {
assertEquals(DetailedState.DISCONNECTING, expected[7]);
assertEquals(DetailedState.DISCONNECTED, expected[8]);
assertEquals(DetailedState.FAILED, expected[9]);
- assertEquals(DetailedState.BLOCKED, expected[10]);
}
}
diff --git a/tests/tests/net/src/android/net/http/cts/ApacheHttpClientTest.java b/tests/tests/net/src/android/net/http/cts/ApacheHttpClientTest.java
deleted file mode 100644
index e4846fd..0000000
--- a/tests/tests/net/src/android/net/http/cts/ApacheHttpClientTest.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * 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.net.http.cts;
-
-import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.DefaultHttpClient;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.PackageManager;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.NetworkInfo.State;
-import android.net.Uri;
-import android.net.wifi.WifiManager;
-import android.test.AndroidTestCase;
-import android.util.Log;
-import android.webkit.cts.CtsTestServer;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class ApacheHttpClientTest extends AndroidTestCase {
-
- private static final String TAG = ApacheHttpClientTest.class.getSimpleName();
-
- private static final int NUM_DOWNLOADS = 20;
-
- private static final int SMALL_DOWNLOAD_SIZE = 100 * 1024;
-
- private CtsTestServer mWebServer;
-
- private WifiManager mWifiManager;
-
- private ConnectivityManager mConnectivityManager;
-
- private boolean mHasTelephony;
-
- private boolean mHasWifi;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mWebServer = new CtsTestServer(mContext);
- mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
- mConnectivityManager = (ConnectivityManager)
- mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-
- PackageManager packageManager = mContext.getPackageManager();
- mHasTelephony = packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
- mHasWifi = packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI);
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- mWebServer.shutdown();
- }
-
- public void testExecute_withMobile() throws Exception {
- if (mHasTelephony) {
- disconnectWifiToConnectToMobile();
- }
-
- downloadMultipleFiles();
-
- if (mHasWifi) {
- connectToWifi();
- }
- }
-
- public void testExecute_withWifi() throws Exception {
- if (mHasWifi) {
- if (!mWifiManager.isWifiEnabled()) {
- connectToWifi();
- }
- downloadMultipleFiles();
- }
- }
-
- private void downloadMultipleFiles() throws ClientProtocolException, IOException {
- List responses = new ArrayList();
- for (int i = 0; i < NUM_DOWNLOADS; i++) {
- HttpClient httpClient = new DefaultHttpClient();
- HttpGet request = new HttpGet(getSmallDownloadUrl(i).toString());
- HttpResponse response = httpClient.execute(request);
- responses.add(response);
- }
-
- for (int i = 0; i < NUM_DOWNLOADS; i++) {
- assertDownloadResponse("Download " + i, SMALL_DOWNLOAD_SIZE, responses.get(i));
- }
- }
-
- private Uri getSmallDownloadUrl(int index) {
- return Uri.parse(mWebServer.getTestDownloadUrl("cts-small-download-" + index,
- SMALL_DOWNLOAD_SIZE));
- }
-
- private void assertDownloadResponse(String message, int expectedNumBytes, HttpResponse response)
- throws IllegalStateException, IOException {
- byte[] buffer = new byte[4096];
- assertEquals(200, response.getStatusLine().getStatusCode());
-
- InputStream stream = response.getEntity().getContent();
- int numBytes = 0;
- while (true) {
- int bytesRead = stream.read(buffer);
- if (bytesRead < 0) {
- break;
- } else {
- numBytes += bytesRead;
- }
- }
- assertEquals(message, SMALL_DOWNLOAD_SIZE, numBytes);
- }
-
- private void connectToWifi() throws InterruptedException {
- if (!mWifiManager.isWifiEnabled()) {
- ConnectivityActionReceiver receiver =
- new ConnectivityActionReceiver(ConnectivityManager.TYPE_WIFI, State.CONNECTED);
- IntentFilter filter = new IntentFilter();
- filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
- mContext.registerReceiver(receiver, filter);
-
- assertTrue(mWifiManager.setWifiEnabled(true));
- assertTrue("Wifi must be configured to connect to an access point for this test.",
- receiver.waitForStateChange());
-
- mContext.unregisterReceiver(receiver);
- }
- }
-
- private void disconnectWifiToConnectToMobile() throws InterruptedException {
- if (mHasWifi && mWifiManager.isWifiEnabled()) {
- ConnectivityActionReceiver connectMobileReceiver =
- new ConnectivityActionReceiver(ConnectivityManager.TYPE_MOBILE,
- State.CONNECTED);
- ConnectivityActionReceiver disconnectWifiReceiver =
- new ConnectivityActionReceiver(ConnectivityManager.TYPE_WIFI,
- State.DISCONNECTED);
- IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
- mContext.registerReceiver(connectMobileReceiver, filter);
- mContext.registerReceiver(disconnectWifiReceiver, filter);
-
- assertTrue(mWifiManager.setWifiEnabled(false));
- assertTrue(disconnectWifiReceiver.waitForStateChange());
- assertTrue(connectMobileReceiver.waitForStateChange());
-
- mContext.unregisterReceiver(connectMobileReceiver);
- mContext.unregisterReceiver(disconnectWifiReceiver);
- }
- }
-
- /** Receiver that captures the last connectivity change's network type and state. */
- private class ConnectivityActionReceiver extends BroadcastReceiver {
-
- private final CountDownLatch mReceiveLatch = new CountDownLatch(1);
-
- private final int mNetworkType;
-
- private final State mExpectedState;
-
- ConnectivityActionReceiver(int networkType, State expectedState) {
- mNetworkType = networkType;
- mExpectedState = expectedState;
- }
-
- public void onReceive(Context context, Intent intent) {
- NetworkInfo networkInfo = intent.getExtras()
- .getParcelable(ConnectivityManager.EXTRA_NETWORK_INFO);
- int networkType = networkInfo.getType();
- State networkState = networkInfo.getState();
- Log.i(TAG, "Network type: " + networkType + " State: " + networkInfo.getState());
- if (networkType == mNetworkType && networkInfo.getState() == mExpectedState) {
- mReceiveLatch.countDown();
- }
- }
-
- public boolean waitForStateChange() throws InterruptedException {
- return hasExpectedState() || mReceiveLatch.await(30, TimeUnit.SECONDS);
- }
-
- private boolean hasExpectedState() {
- return mExpectedState == mConnectivityManager.getNetworkInfo(mNetworkType).getState();
- }
- }
-}
diff --git a/tests/tests/net/src/android/net/http/cts/SslErrorTest.java b/tests/tests/net/src/android/net/http/cts/SslErrorTest.java
deleted file mode 100755
index d186f0e..0000000
--- a/tests/tests/net/src/android/net/http/cts/SslErrorTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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.net.http.cts;
-
-import android.net.http.SslCertificate;
-import android.net.http.SslError;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Date;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(SslError.class)
-public class SslErrorTest extends TestCase {
- private SslCertificate mCertificate;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mCertificate = new SslCertificate("foo", "bar", new Date(42), new Date(43));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "hasError",
- args = {int.class}
- )
- public void testHasError() {
- SslError error = new SslError(SslError.SSL_EXPIRED, mCertificate);
- assertTrue(error.hasError(SslError.SSL_EXPIRED));
- assertFalse(error.hasError(SslError.SSL_UNTRUSTED));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "addError",
- args = {int.class}
- )
- public void testAddError() {
- SslError error = new SslError(SslError.SSL_EXPIRED, mCertificate);
- assertFalse(error.hasError(SslError.SSL_UNTRUSTED));
- error.addError(SslError.SSL_UNTRUSTED);
- assertTrue(error.hasError(SslError.SSL_UNTRUSTED));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "addError",
- args = {int.class}
- )
- public void testAddErrorIgnoresInvalidValues() {
- SslError error = new SslError(SslError.SSL_EXPIRED, mCertificate);
- error.addError(42);
- assertFalse(error.hasError(42));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "SslError",
- args = {int.class, SslCertificate.class}
- )
- public void testConstructorIgnoresInvalidValues() {
- SslError error = new SslError(42, mCertificate);
- assertFalse(error.hasError(42));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getPrimaryError",
- args = {}
- )
- public void testGetPrimaryError() {
- SslError error = new SslError(SslError.SSL_EXPIRED, mCertificate);
- error.addError(SslError.SSL_UNTRUSTED);
- assertEquals(error.getPrimaryError(), SslError.SSL_UNTRUSTED);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getPrimaryError",
- args = {}
- )
- public void testGetPrimaryErrorWithEmptySet() {
- SslError error = new SslError(42, mCertificate);
- assertEquals(error.getPrimaryError(), -1);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getUrl",
- args = {}
- )
- public void testGetUrl() {
- SslError error = new SslError(SslError.SSL_EXPIRED, mCertificate, "foo");
- assertEquals(error.getUrl(), "foo");
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getUrl",
- args = {}
- )
- public void testGetUrlWithDeprecatedConstructor() {
- SslError error = new SslError(SslError.SSL_EXPIRED, mCertificate);
- assertEquals(error.getUrl(), "");
- }
-}
diff --git a/tests/tests/os/Android.mk b/tests/tests/os/Android.mk
index 35cafb9..affd97d 100644
--- a/tests/tests/os/Android.mk
+++ b/tests/tests/os/Android.mk
@@ -23,7 +23,11 @@ LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
LOCAL_JAVA_LIBRARIES := android.test.runner
+ifneq ($(TARGET_SIMULATOR),true)
LOCAL_SRC_FILES := $(call all-java-files-under, src)
+else
+LOCAL_SRC_FILES := $(filter-out %BuildTest.java,$(call all-java-files-under, src))
+endif
LOCAL_PACKAGE_NAME := CtsOsTestCases
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index 89f26f2..ec3f49a 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -114,8 +114,6 @@ public class BuildTest extends TestCase {
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 =
@@ -137,14 +135,10 @@ public class BuildTest extends TestCase {
// 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 2846cc9..cc15f6f 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 @@ public class BuildVersionTest extends TestCase {
private static final String LOG_TAG = "BuildVersionTest";
private static final Set EXPECTED_RELEASES =
- new HashSet(Arrays.asList("4.0", "4.0.1"));
- private static final int EXPECTED_SDK = 14;
+ new HashSet(Arrays.asList("2.3.3", "2.3.4"));
+ private static final int EXPECTED_SDK = 10;
public void testReleaseVersion() {
// Applications may rely on the exact release version
diff --git a/tests/tests/os/src/android/os/cts/FileObserverTest.java b/tests/tests/os/src/android/os/cts/FileObserverTest.java
index b51f804..d44e22b 100644
--- a/tests/tests/os/src/android/os/cts/FileObserverTest.java
+++ b/tests/tests/os/src/android/os/cts/FileObserverTest.java
@@ -16,15 +16,20 @@
package android.os.cts;
-import android.os.FileObserver;
-import android.test.AndroidTestCase;
-
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
+import android.os.FileObserver;
+import android.test.AndroidTestCase;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
+@TestTargetClass(FileObserver.class)
public class FileObserverTest extends AndroidTestCase {
private File mTestFile;
@@ -68,6 +73,18 @@ public class FileObserverTest extends AndroidTestCase {
}
}
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "FileObserver",
+ args = {java.lang.String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "FileObserver",
+ args = {java.lang.String.class, int.class}
+ )
+ })
public void testConstructor() {
// new the instance
new MockFileObserver(PATH);
@@ -87,6 +104,31 @@ public class FileObserverTest extends AndroidTestCase {
* moved from dir observer should get moved-from event,
* moved to dir observer should get moved-to event.
*/
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "startWatching",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "onEvent",
+ args = {int.class, java.lang.String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.PARTIAL,
+ method = "stopWatching",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ method = "finalize",
+ args = {}
+ )
+ })
+ @ToBeFixed(bug = "1725406", explanation =
+ "android.os.FileObserver#onEvent(int event, String path) still got event "
+ + "after called FileObserver#stopWatching()")
public void testFileObserver() throws Exception {
MockFileObserver fileObserver = null;
int[] expected = null;
@@ -130,7 +172,7 @@ public class FileObserverTest extends AndroidTestCase {
mTestDir.delete();
expected = new int[] {FileObserver.CREATE,
- FileObserver.OPEN, FileObserver.CLOSE_WRITE,
+ FileObserver.OPEN, FileObserver.CLOSE_NOWRITE,
FileObserver.DELETE, FileObserver.DELETE_SELF, UNDEFINED};
moveEvents = waitForEvent(fileObserver);
assertEventsEquals(expected, moveEvents);
@@ -175,15 +217,9 @@ public class FileObserverTest extends AndroidTestCase {
}
private void assertEventsEquals(final int[] expected, final FileEvent[] moveEvents) {
- List expectedEvents = new ArrayList();
+ assertEquals(expected.length, moveEvents.length);
for (int i = 0; i < expected.length; i++) {
- expectedEvents.add(expected[i]);
- }
- List actualEvents = Arrays.asList(moveEvents);
- String message = "Expected: " + expectedEvents + " Actual: " + actualEvents;
- assertEquals(message, expected.length, moveEvents.length);
- for (int i = 0; i < expected.length; i++) {
- assertEquals(message, expected[i], moveEvents[i].event);
+ assertEquals(expected[i], moveEvents[i].event);
}
}
@@ -203,11 +239,6 @@ public class FileObserverTest extends AndroidTestCase {
this.event = event;
this.path = path;
}
-
- @Override
- public String toString() {
- return Integer.toString(event);
- }
}
/*
diff --git a/tests/tests/os/src/android/os/cts/MessengerTest.java b/tests/tests/os/src/android/os/cts/MessengerTest.java
index 6b2debc..efe022d 100644
--- a/tests/tests/os/src/android/os/cts/MessengerTest.java
+++ b/tests/tests/os/src/android/os/cts/MessengerTest.java
@@ -90,9 +90,6 @@ public class MessengerTest extends AndroidTestCase {
public void dump(FileDescriptor fd, String[] args) throws RemoteException {
}
- public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException {
- }
-
};
// Create another messenger to send msg.
diff --git a/tests/tests/os/src/android/os/cts/NoExecutePermissionTest.java b/tests/tests/os/src/android/os/cts/NoExecutePermissionTest.java
deleted file mode 100644
index 6450e58..0000000
--- a/tests/tests/os/src/android/os/cts/NoExecutePermissionTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.os.cts;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.Scanner;
-
-import junit.framework.TestCase;
-
-/**
- * {@link TestCase} that checks that the NX (No Execute) feature is enabled. This feature makes it
- * harder to perform attacks against Android by marking certain data blocks as non-executable.
- */
-public class NoExecutePermissionTest extends TestCase {
-
- public void testNoExecutePermission() throws FileNotFoundException {
- if (!cpuHasNxSupport()) {
- return;
- }
-
- String heapPermissions = null;
- String stackPermissions = null;
-
- Scanner scanner = null;
- try {
- scanner = new Scanner(new File("/proc/self/maps"));
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine().trim();
- String[] fields = line.split("\\s+");
-
- // Sample line:
- // 0001d000-00024000 rw-p 00000000 00:00 0 [heap]
- if (fields != null && fields.length >= 1) {
- String permissions = fields[1];
- if (fields.length >= 6) {
- String tag = fields[5];
- if ("[heap]".equals(tag)) {
- heapPermissions = permissions;
- } else if ("[stack]".equals(tag)) {
- stackPermissions = permissions;
- }
- }
- }
- }
- } finally {
- if (scanner != null) {
- scanner.close();
- }
- }
-
- assertEquals("NX (No Execute) not enabled for heap", "rw-p", heapPermissions);
- assertEquals("NX (No Execute) not enabled for stack", "rw-p", stackPermissions);
- }
-
- private static boolean cpuHasNxSupport() {
- if (CpuFeatures.isArmCpu() && !CpuFeatures.isArm7Compatible()) {
- // ARM processors before v7 do not have NX support.
- // http://code.google.com/p/android/issues/detail?id=17328
- return false;
- }
-
- // TODO: handle other processors. For now, assume those processors
- // have NX support.
- return true;
- }
-}
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
index 3974b6c..ce6658f 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
@@ -28,14 +28,9 @@ import android.os.ParcelFileDescriptor;
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;
@@ -115,72 +110,6 @@ public class ParcelFileDescriptorTest extends AndroidTestCase {
}
@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 2493680..28d7728 100644
--- a/tests/tests/os/src/android/os/cts/ParcelTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelTest.java
@@ -563,9 +563,9 @@ public class ParcelTest extends AndroidTestCase {
p.recycle();
// test Parcelable[]
- Signature[] signatures = {new Signature("1234"),
- new Signature("ABCD"),
- new Signature("abcd")};
+ Signature[] signatures = {new Signature("123"),
+ new Signature("ABC"),
+ new Signature("abc")};
Parcelable[] signatures2;
p = Parcel.obtain();
p.writeValue(signatures);
@@ -776,30 +776,6 @@ public class ParcelTest extends AndroidTestCase {
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({
@@ -899,11 +875,12 @@ public class ParcelTest extends AndroidTestCase {
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 + 1], d[i]);
+ assertEquals(c[i], d[i]);
}
p.recycle();
}
@@ -2449,13 +2426,13 @@ public class ParcelTest extends AndroidTestCase {
public void testReadParcelableArray() {
Parcel p;
MockClassLoader mcl = new MockClassLoader();
- Signature[] s = {new Signature("1234"),
- new Signature("ABCD"),
- new Signature("abcd")};
+ Signature[] s = {new Signature("123"),
+ new Signature("ABC"),
+ new Signature("abc")};
- Signature[] s2 = {new Signature("1234"),
+ Signature[] s2 = {new Signature("123"),
null,
- new Signature("abcd")};
+ new Signature("abc")};
Parcelable[] s3;
// test write null
@@ -2498,13 +2475,13 @@ public class ParcelTest extends AndroidTestCase {
})
public void testReadTypedArray() {
Parcel p;
- Signature[] s = {new Signature("1234"),
- new Signature("ABCD"),
- new Signature("abcd")};
+ Signature[] s = {new Signature("123"),
+ new Signature("ABC"),
+ new Signature("abc")};
- Signature[] s2 = {new Signature("1234"),
+ Signature[] s2 = {new Signature("123"),
null,
- new Signature("abcd")};
+ new Signature("abc")};
Signature[] s3 = new Signature[3];
Signature[] s4 = new Signature[4];
@@ -2575,11 +2552,11 @@ public class ParcelTest extends AndroidTestCase {
public void testReadTypedArray2() {
Parcel p;
Signature[] s = {
- new Signature("1234"), new Signature("ABCD"), new Signature("abcd")
+ new Signature("123"), new Signature("ABC"), new Signature("abc")
};
Signature[] s2 = {
- new Signature("1234"), null, new Signature("abcd")
+ new Signature("123"), null, new Signature("abc")
};
Signature[] s3 = {
null, null, null
@@ -2625,13 +2602,13 @@ public class ParcelTest extends AndroidTestCase {
})
public void testCreateTypedArray() {
Parcel p;
- Signature[] s = {new Signature("1234"),
- new Signature("ABCD"),
- new Signature("abcd")};
+ Signature[] s = {new Signature("123"),
+ new Signature("ABC"),
+ new Signature("abc")};
- Signature[] s2 = {new Signature("1234"),
+ Signature[] s2 = {new Signature("123"),
null,
- new Signature("abcd")};
+ new Signature("abc")};
Signature[] s3;
// test write null
@@ -2676,12 +2653,12 @@ public class ParcelTest extends AndroidTestCase {
public void testReadTypedList() {
Parcel p;
ArrayList s = new ArrayList();
- s.add(new Signature("1234"));
- s.add(new Signature("ABCD"));
- s.add(new Signature("abcd"));
+ s.add(new Signature("123"));
+ s.add(new Signature("ABC"));
+ s.add(new Signature("abc"));
ArrayList s2 = new ArrayList();
- s2.add(new Signature("1234"));
+ s2.add(new Signature("123"));
s2.add(null);
ArrayList s3 = new ArrayList();
@@ -2728,7 +2705,7 @@ public class ParcelTest extends AndroidTestCase {
p.recycle();
s2 = new ArrayList();
- s2.add(new Signature("1234"));
+ s2.add(new Signature("123"));
s2.add(null);
p = Parcel.obtain();
p.writeTypedList(s2);
@@ -2756,12 +2733,12 @@ public class ParcelTest extends AndroidTestCase {
public void testCreateTypedArrayList() {
Parcel p;
ArrayList s = new ArrayList();
- s.add(new Signature("1234"));
- s.add(new Signature("ABCD"));
- s.add(new Signature("abcd"));
+ s.add(new Signature("123"));
+ s.add(new Signature("ABC"));
+ s.add(new Signature("abc"));
ArrayList s2 = new ArrayList();
- s2.add(new Signature("1234"));
+ s2.add(new Signature("123"));
s2.add(null);
ArrayList s3;
diff --git a/tests/tests/os/src/android/os/cts/ProcessTest.java b/tests/tests/os/src/android/os/cts/ProcessTest.java
index 4f61688..6216f06 100644
--- a/tests/tests/os/src/android/os/cts/ProcessTest.java
+++ b/tests/tests/os/src/android/os/cts/ProcessTest.java
@@ -26,6 +26,7 @@ import android.os.Process;
import android.test.AndroidTestCase;
import android.util.Log;
import dalvik.annotation.TestTargets;
+import dalvik.annotation.TestStatus;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
@@ -234,7 +235,13 @@ public class ProcessTest extends AndroidTestCase {
}
assertTrue(time > 0);
- assertTrue(servicePid != Process.myPid());
+
+ if(servicePid == Process.myPid()) {
+ assertFalse(Process.supportsProcesses());
+ return;
+ } else {
+ assertTrue(Process.supportsProcesses());
+ }
Process.killProcess(servicePid);
synchronized (mSync) {
diff --git a/tests/tests/performance/Android.mk b/tests/tests/performance/Android.mk
new file mode 100644
index 0000000..6025c7f
--- /dev/null
+++ b/tests/tests/performance/Android.mk
@@ -0,0 +1,32 @@
+# 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.
+
+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 := CtsPerformanceTestCases
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/performance/AndroidManifest.xml b/tests/tests/performance/AndroidManifest.xml
new file mode 100644
index 0000000..375311f
--- /dev/null
+++ b/tests/tests/performance/AndroidManifest.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/tests/performance/src/android/performance/cts/MultiAppStartupTest.java b/tests/tests/performance/src/android/performance/cts/MultiAppStartupTest.java
new file mode 100644
index 0000000..a736d89
--- /dev/null
+++ b/tests/tests/performance/src/android/performance/cts/MultiAppStartupTest.java
@@ -0,0 +1,90 @@
+/*
+ * 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.performance.cts;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.test.InstrumentationTestCase;
+
+public class MultiAppStartupTest extends InstrumentationTestCase {
+ private static final String PACKAGE_UNDER_TEST = "com.android.calculator2";
+ private static final String ACTIVITY_UNDER_TEST = "Calculator";
+ private static final int ACTIVITY_STARTUP_WAIT_TIME = 1000;
+
+ private Intent buildIntent(final String pkgName, String className, boolean isMain) {
+ final String fullClassName = pkgName + "." + className;
+ Intent intent = new Intent();
+ intent.setClassName(pkgName, fullClassName);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ if (isMain) {
+ intent.setAction(Intent.ACTION_MAIN);
+ intent.addCategory(Intent.CATEGORY_LAUNCHER);
+ }
+ return intent;
+ }
+
+ private void launchActivity(final String pkgName, String className, boolean isMain) {
+ Context ctx = getInstrumentation().getContext();
+ ctx.startActivity(buildIntent(pkgName, className, isMain));
+ }
+
+ private long launchActivityUnderTest() {
+ long start = System.currentTimeMillis();
+ Intent i = buildIntent(PACKAGE_UNDER_TEST,
+ ACTIVITY_UNDER_TEST,
+ true);
+ Activity a = getInstrumentation().startActivitySync(i);
+ long end = System.currentTimeMillis();
+ long diff = end - start;
+ a.finish();
+ return diff;
+ }
+
+ public void testMultipleApps() throws InterruptedException {
+ // Measure how long the initial startup of the application takes
+ long initialStartDuration = launchActivityUnderTest();
+
+ // Re-launch the activity. It was finished in
+ // launchActivityUnderTest, so this ensures that it is around
+ // for the ActivityManager to possibly kill it.
+ launchActivity(PACKAGE_UNDER_TEST,
+ ACTIVITY_UNDER_TEST,
+ true);
+
+ // Then launch a few more
+ launchActivity("com.android.browser", "BrowserActivity", true);
+ Thread.sleep(ACTIVITY_STARTUP_WAIT_TIME);
+ launchActivity("com.android.mms", "ui.ConversationList", true);
+ Thread.sleep(ACTIVITY_STARTUP_WAIT_TIME);
+ launchActivity("com.android.contacts", "TwelveKeyDialer", false);
+ Thread.sleep(ACTIVITY_STARTUP_WAIT_TIME);
+ launchActivity("com.android.contacts", "RecentCallsListActivity", false);
+ Thread.sleep(ACTIVITY_STARTUP_WAIT_TIME);
+
+ long finalStartDuration = launchActivityUnderTest();
+
+ // assure that the time to re-start the application is less
+ // than the original start time.
+ assertTrue("Restart of inital app took to long: " +
+ finalStartDuration + " " + initialStartDuration,
+ finalStartDuration < initialStartDuration);
+
+ // TODO: Change this check to use RunningProcesses from
+ // ActivityManager which should provide better results.
+ }
+}
diff --git a/tests/tests/performance2/Android.mk b/tests/tests/performance2/Android.mk
new file mode 100644
index 0000000..9264559
--- /dev/null
+++ b/tests/tests/performance2/Android.mk
@@ -0,0 +1,32 @@
+# 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.
+
+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 := CtsPerformance2TestCases
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/performance2/AndroidManifest.xml b/tests/tests/performance2/AndroidManifest.xml
new file mode 100644
index 0000000..0d439e7
--- /dev/null
+++ b/tests/tests/performance2/AndroidManifest.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/tests/performance2/src/android/performance2/cts/AppStartup.java b/tests/tests/performance2/src/android/performance2/cts/AppStartup.java
new file mode 100644
index 0000000..fdbddfe
--- /dev/null
+++ b/tests/tests/performance2/src/android/performance2/cts/AppStartup.java
@@ -0,0 +1,71 @@
+/*
+ * 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.performance2.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.test.InstrumentationTestCase;
+
+public class AppStartup extends InstrumentationTestCase {
+ private static final long MAX_AVG_STARTUP_TIME = 500;
+ private static final String PACKAGE_UNDER_TEST = "com.android.music";
+ private static final String ACTIVITY_UNDER_TEST = "MusicBrowserActivity";
+ private static final int NUMBER_OF_ITERS = 10;
+
+ private Intent buildIntent(final String pkgName, String className) {
+ final String fullClassName = pkgName + "." + className;
+ Intent intent = new Intent();
+ intent.setClassName(pkgName, fullClassName);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ intent.setAction(Intent.ACTION_MAIN);
+ intent.addCategory(Intent.CATEGORY_LAUNCHER);
+ return intent;
+ }
+
+ public void testStartup() throws InterruptedException {
+ long totalTime = 0;
+ Intent i = buildIntent(PACKAGE_UNDER_TEST, ACTIVITY_UNDER_TEST);
+
+ // Warm up
+ for (int x = 0; x < 3; x++) {
+ Activity a = getInstrumentation().startActivitySync(i);
+ a.finish();
+ }
+
+ // Actually test.
+ for (int x = 0; x < NUMBER_OF_ITERS; x++) {
+ long start = System.currentTimeMillis();
+ Activity a = getInstrumentation().startActivitySync(i);
+ long end = System.currentTimeMillis();
+
+ long diff = end - start;
+ totalTime += diff;
+
+ a.finish();
+ }
+ long avgStartupTime = totalTime / NUMBER_OF_ITERS;
+
+ android.util.Log.d("AppStartup", "AppStartup for " +
+ PACKAGE_UNDER_TEST + "/" +
+ ACTIVITY_UNDER_TEST + " took " +
+ avgStartupTime + "ms.");
+
+ assertTrue("App Took too long to startup: " + avgStartupTime +
+ " " + MAX_AVG_STARTUP_TIME,
+ avgStartupTime < MAX_AVG_STARTUP_TIME);
+ }
+}
diff --git a/tests/tests/performance3/Android.mk b/tests/tests/performance3/Android.mk
new file mode 100644
index 0000000..d24d2bd
--- /dev/null
+++ b/tests/tests/performance3/Android.mk
@@ -0,0 +1,32 @@
+# 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.
+
+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 := CtsPerformance3TestCases
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/performance3/AndroidManifest.xml b/tests/tests/performance3/AndroidManifest.xml
new file mode 100644
index 0000000..b774447
--- /dev/null
+++ b/tests/tests/performance3/AndroidManifest.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/tests/performance3/src/android/performance3/cts/AppStartup.java b/tests/tests/performance3/src/android/performance3/cts/AppStartup.java
new file mode 100644
index 0000000..34ca91c
--- /dev/null
+++ b/tests/tests/performance3/src/android/performance3/cts/AppStartup.java
@@ -0,0 +1,72 @@
+/*
+ * 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.performance3.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.net.Uri;
+import android.test.InstrumentationTestCase;
+
+public class AppStartup extends InstrumentationTestCase {
+ private static final long MAX_AVG_STARTUP_TIME = 1300;
+ private static final String PACKAGE_UNDER_TEST = "com.android.browser";
+ private static final String ACTIVITY_UNDER_TEST = "BrowserActivity";
+ private static final int NUMBER_OF_ITERS = 10;
+
+ private Intent buildIntent(final String pkgName, String className) {
+ final String fullClassName = pkgName + "." + className;
+ Intent intent = new Intent();
+ intent.setClassName(pkgName, fullClassName);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ intent.setAction(Intent.ACTION_VIEW);
+ intent.setData(Uri.parse("http://www.google.com/m"));
+ return intent;
+ }
+
+ public void testStartup() throws InterruptedException {
+ long totalTime = 0;
+ Intent i = buildIntent(PACKAGE_UNDER_TEST, ACTIVITY_UNDER_TEST);
+
+ // Warm up
+ for (int x = 0; x < 3; x++) {
+ Activity a = getInstrumentation().startActivitySync(i);
+ a.finish();
+ }
+
+ // Actually test.
+ for (int x = 0; x < NUMBER_OF_ITERS; x++) {
+ long start = System.currentTimeMillis();
+ Activity a = getInstrumentation().startActivitySync(i);
+ long end = System.currentTimeMillis();
+
+ long diff = end - start;
+ totalTime += diff;
+
+ a.finish();
+ }
+ long avgStartupTime = totalTime / NUMBER_OF_ITERS;
+
+ android.util.Log.d("AppStartup", "AppStartup for " +
+ PACKAGE_UNDER_TEST + "/" +
+ ACTIVITY_UNDER_TEST + " took " +
+ avgStartupTime + "ms.");
+
+ assertTrue("App Took too long to startup: " + avgStartupTime +
+ " " + MAX_AVG_STARTUP_TIME,
+ avgStartupTime < MAX_AVG_STARTUP_TIME);
+ }
+}
diff --git a/tests/tests/performance4/Android.mk b/tests/tests/performance4/Android.mk
new file mode 100644
index 0000000..8aabbfb
--- /dev/null
+++ b/tests/tests/performance4/Android.mk
@@ -0,0 +1,32 @@
+# 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.
+
+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 := CtsPerformance4TestCases
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/performance4/AndroidManifest.xml b/tests/tests/performance4/AndroidManifest.xml
new file mode 100644
index 0000000..d47c8a2
--- /dev/null
+++ b/tests/tests/performance4/AndroidManifest.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/tests/performance4/src/android/performance4/cts/AppStartup.java b/tests/tests/performance4/src/android/performance4/cts/AppStartup.java
new file mode 100644
index 0000000..5b0f447
--- /dev/null
+++ b/tests/tests/performance4/src/android/performance4/cts/AppStartup.java
@@ -0,0 +1,71 @@
+/*
+ * 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.performance4.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.test.InstrumentationTestCase;
+
+public class AppStartup extends InstrumentationTestCase {
+ private static final long MAX_AVG_STARTUP_TIME = 700;
+ private static final String PACKAGE_UNDER_TEST = "com.android.mms";
+ private static final String ACTIVITY_UNDER_TEST = "ui.ConversationList";
+ private static final int NUMBER_OF_ITERS = 10;
+
+ private Intent buildIntent(final String pkgName, String className) {
+ final String fullClassName = pkgName + "." + className;
+ Intent intent = new Intent();
+ intent.setClassName(pkgName, fullClassName);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ intent.setAction(Intent.ACTION_MAIN);
+ intent.addCategory(Intent.CATEGORY_LAUNCHER);
+ return intent;
+ }
+
+ public void testStartup() throws InterruptedException {
+ long totalTime = 0;
+ Intent i = buildIntent(PACKAGE_UNDER_TEST, ACTIVITY_UNDER_TEST);
+
+ // Warm up
+ for (int x = 0; x < 3; x++) {
+ Activity a = getInstrumentation().startActivitySync(i);
+ a.finish();
+ }
+
+ // Actually test.
+ for (int x = 0; x < NUMBER_OF_ITERS; x++) {
+ long start = System.currentTimeMillis();
+ Activity a = getInstrumentation().startActivitySync(i);
+ long end = System.currentTimeMillis();
+
+ long diff = end - start;
+ totalTime += diff;
+
+ a.finish();
+ }
+ long avgStartupTime = totalTime / NUMBER_OF_ITERS;
+
+ android.util.Log.d("AppStartup", "AppStartup for " +
+ PACKAGE_UNDER_TEST + "/" +
+ ACTIVITY_UNDER_TEST + " took " +
+ avgStartupTime + "ms.");
+
+ assertTrue("App Took too long to startup: " + avgStartupTime +
+ " " + MAX_AVG_STARTUP_TIME,
+ avgStartupTime < MAX_AVG_STARTUP_TIME);
+ }
+}
diff --git a/tests/tests/performance5/Android.mk b/tests/tests/performance5/Android.mk
new file mode 100644
index 0000000..c1f91fd
--- /dev/null
+++ b/tests/tests/performance5/Android.mk
@@ -0,0 +1,32 @@
+# 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.
+
+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 := CtsPerformance5TestCases
+
+LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+
+include $(BUILD_PACKAGE)
diff --git a/tests/tests/performance5/AndroidManifest.xml b/tests/tests/performance5/AndroidManifest.xml
new file mode 100644
index 0000000..d7db0ca
--- /dev/null
+++ b/tests/tests/performance5/AndroidManifest.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/tests/performance5/src/android/performance5/cts/AppStartup.java b/tests/tests/performance5/src/android/performance5/cts/AppStartup.java
new file mode 100644
index 0000000..dd4482c
--- /dev/null
+++ b/tests/tests/performance5/src/android/performance5/cts/AppStartup.java
@@ -0,0 +1,71 @@
+/*
+ * 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.performance5.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.test.InstrumentationTestCase;
+
+public class AppStartup extends InstrumentationTestCase {
+ private static final long MAX_AVG_STARTUP_TIME = 650;
+ private static final String PACKAGE_UNDER_TEST = "com.android.alarmclock";
+ private static final String ACTIVITY_UNDER_TEST = "AlarmClock";
+ private static final int NUMBER_OF_ITERS = 10;
+
+ private Intent buildIntent(final String pkgName, String className) {
+ final String fullClassName = pkgName + "." + className;
+ Intent intent = new Intent();
+ intent.setClassName(pkgName, fullClassName);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ intent.setAction(Intent.ACTION_MAIN);
+ intent.addCategory(Intent.CATEGORY_LAUNCHER);
+ return intent;
+ }
+
+ public void testStartup() throws InterruptedException {
+ long totalTime = 0;
+ Intent i = buildIntent(PACKAGE_UNDER_TEST, ACTIVITY_UNDER_TEST);
+
+ // Warm up
+ for (int x = 0; x < 3; x++) {
+ Activity a = getInstrumentation().startActivitySync(i);
+ a.finish();
+ }
+
+ // Actually test.
+ for (int x = 0; x < NUMBER_OF_ITERS; x++) {
+ long start = System.currentTimeMillis();
+ Activity a = getInstrumentation().startActivitySync(i);
+ long end = System.currentTimeMillis();
+
+ long diff = end - start;
+ totalTime += diff;
+
+ a.finish();
+ }
+ long avgStartupTime = totalTime / NUMBER_OF_ITERS;
+
+ android.util.Log.d("AppStartup", "AppStartup for " +
+ PACKAGE_UNDER_TEST + "/" +
+ ACTIVITY_UNDER_TEST + " took " +
+ avgStartupTime + "ms.");
+
+ assertTrue("App Took too long to startup: " + avgStartupTime +
+ " " + MAX_AVG_STARTUP_TIME,
+ avgStartupTime < MAX_AVG_STARTUP_TIME);
+ }
+}
diff --git a/tests/tests/permission/jni/Android.mk b/tests/tests/permission/jni/Android.mk
index 44e742e..0891a72 100644
--- a/tests/tests/permission/jni/Android.mk
+++ b/tests/tests/permission/jni/Android.mk
@@ -21,6 +21,9 @@ LOCAL_MODULE := libctspermission_jni
# Don't include this package in any configuration by default.
LOCAL_MODULE_TAGS := optional
+# This isn't part of the system, so don't prelink it.
+LOCAL_PRELINK_MODULE := false
+
LOCAL_SRC_FILES := \
CtsPermissionsJniOnLoad.cpp \
android_permission_cts_FileUtils.cpp
diff --git a/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp b/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp
index c658af6..1666d50 100644
--- a/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp
+++ b/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp
@@ -21,6 +21,7 @@
#include
#include
+static jclass gFileStatusClass;
static jfieldID gFileStatusDevFieldID;
static jfieldID gFileStatusInoFieldID;
static jfieldID gFileStatusModeFieldID;
@@ -100,19 +101,19 @@ int register_android_permission_cts_FileUtils(JNIEnv* env)
{
jclass clazz = env->FindClass("android/permission/cts/FileUtils");
- jclass fileStatusClass = env->FindClass("android/permission/cts/FileUtils$FileStatus");
- gFileStatusDevFieldID = env->GetFieldID(fileStatusClass, "dev", "I");
- gFileStatusInoFieldID = env->GetFieldID(fileStatusClass, "ino", "I");
- gFileStatusModeFieldID = env->GetFieldID(fileStatusClass, "mode", "I");
- gFileStatusNlinkFieldID = env->GetFieldID(fileStatusClass, "nlink", "I");
- gFileStatusUidFieldID = env->GetFieldID(fileStatusClass, "uid", "I");
- gFileStatusGidFieldID = env->GetFieldID(fileStatusClass, "gid", "I");
- gFileStatusSizeFieldID = env->GetFieldID(fileStatusClass, "size", "J");
- gFileStatusBlksizeFieldID = env->GetFieldID(fileStatusClass, "blksize", "I");
- gFileStatusBlocksFieldID = env->GetFieldID(fileStatusClass, "blocks", "J");
- gFileStatusAtimeFieldID = env->GetFieldID(fileStatusClass, "atime", "J");
- gFileStatusMtimeFieldID = env->GetFieldID(fileStatusClass, "mtime", "J");
- gFileStatusCtimeFieldID = env->GetFieldID(fileStatusClass, "ctime", "J");
+ gFileStatusClass = env->FindClass("android/permission/cts/FileUtils$FileStatus");
+ gFileStatusDevFieldID = env->GetFieldID(gFileStatusClass, "dev", "I");
+ gFileStatusInoFieldID = env->GetFieldID(gFileStatusClass, "ino", "I");
+ gFileStatusModeFieldID = env->GetFieldID(gFileStatusClass, "mode", "I");
+ gFileStatusNlinkFieldID = env->GetFieldID(gFileStatusClass, "nlink", "I");
+ gFileStatusUidFieldID = env->GetFieldID(gFileStatusClass, "uid", "I");
+ gFileStatusGidFieldID = env->GetFieldID(gFileStatusClass, "gid", "I");
+ gFileStatusSizeFieldID = env->GetFieldID(gFileStatusClass, "size", "J");
+ gFileStatusBlksizeFieldID = env->GetFieldID(gFileStatusClass, "blksize", "I");
+ gFileStatusBlocksFieldID = env->GetFieldID(gFileStatusClass, "blocks", "J");
+ gFileStatusAtimeFieldID = env->GetFieldID(gFileStatusClass, "atime", "J");
+ gFileStatusMtimeFieldID = env->GetFieldID(gFileStatusClass, "mtime", "J");
+ gFileStatusCtimeFieldID = env->GetFieldID(gFileStatusClass, "ctime", "J");
return env->RegisterNatives(clazz, gMethods,
sizeof(gMethods) / sizeof(JNINativeMethod));
diff --git a/tests/tests/permission/src/android/permission/cts/DebuggableTest.java b/tests/tests/permission/src/android/permission/cts/DebuggableTest.java
index d77e13e..fe4ed57 100644
--- a/tests/tests/permission/src/android/permission/cts/DebuggableTest.java
+++ b/tests/tests/permission/src/android/permission/cts/DebuggableTest.java
@@ -20,9 +20,7 @@ import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.test.AndroidTestCase;
-import java.util.HashSet;
import java.util.List;
-import java.util.Set;
/**
* Verify that pre-installed packages don't have the debuggable
@@ -32,16 +30,13 @@ import java.util.Set;
public class DebuggableTest extends AndroidTestCase {
public void testNoDebuggable() {
- Set debuggableApps = new HashSet();
List apps = getContext()
.getPackageManager()
.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for (ApplicationInfo app : apps) {
String appName = app.packageName;
- if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE) {
- debuggableApps.add(appName);
- }
+ assertTrue("Package " + appName + " is marked as debuggable.",
+ (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
}
- assertTrue("Packages marked debuggable: " + debuggableApps, debuggableApps.isEmpty());
}
}
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index c222e7b..3cbb362 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -21,7 +21,6 @@ import android.content.pm.PackageManager;
import android.os.Environment;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.MediumTest;
-import android.test.suitebuilder.annotation.LargeTest;
import java.io.File;
import java.io.FileFilter;
@@ -37,9 +36,9 @@ import java.util.Set;
*
* TODO: Combine this file with {@link android.os.cts.FileAccessPermissionTest}
*/
+@MediumTest
public class FileSystemPermissionTest extends AndroidTestCase {
- @MediumTest
public void testCreateFileHasSanePermissions() throws Exception {
File myFile = new File(getContext().getFilesDir(), "hello");
FileOutputStream stream = new FileOutputStream(myFile);
@@ -60,7 +59,6 @@ public class FileSystemPermissionTest extends AndroidTestCase {
}
}
- @MediumTest
public void testCreateDirectoryHasSanePermissions() throws Exception {
File myDir = new File(getContext().getFilesDir(), "helloDirectory");
assertTrue(myDir.mkdir());
@@ -81,7 +79,6 @@ public class FileSystemPermissionTest extends AndroidTestCase {
}
}
- @MediumTest
public void testOtherApplicationDirectoriesAreNotWritable() throws Exception {
List apps = getContext()
.getPackageManager()
@@ -94,44 +91,36 @@ public class FileSystemPermissionTest extends AndroidTestCase {
}
}
- @MediumTest
public void testApplicationParentDirectoryNotWritable() throws Exception {
String myDataDir = getContext().getApplicationInfo().dataDir;
File parentDir = new File(myDataDir).getParentFile();
assertDirectoryNotWritable(parentDir);
}
- @MediumTest
public void testDataDirectoryNotWritable() throws Exception {
assertDirectoryNotWritable(Environment.getDataDirectory());
}
- @MediumTest
public void testAndroidRootDirectoryNotWritable() throws Exception {
assertDirectoryNotWritable(Environment.getRootDirectory());
}
- @MediumTest
public void testDownloadCacheDirectoryNotWritable() throws Exception {
assertDirectoryNotWritable(Environment.getDownloadCacheDirectory());
}
- @MediumTest
public void testRootDirectoryNotWritable() throws Exception {
assertDirectoryNotWritable(new File("/"));
}
- @MediumTest
public void testDevDirectoryNotWritable() throws Exception {
assertDirectoryNotWritable(new File("/dev"));
}
- @MediumTest
public void testProcDirectoryNotWritable() throws Exception {
assertDirectoryNotWritable(new File("/proc"));
}
- @MediumTest
public void testDevMemSane() throws Exception {
File f = new File("/dev/mem");
assertFalse(f.canRead());
@@ -139,7 +128,6 @@ public class FileSystemPermissionTest extends AndroidTestCase {
assertFalse(f.canExecute());
}
- @MediumTest
public void testDevkmemSane() throws Exception {
File f = new File("/dev/kmem");
assertFalse(f.canRead());
@@ -147,7 +135,6 @@ public class FileSystemPermissionTest extends AndroidTestCase {
assertFalse(f.canExecute());
}
- @MediumTest
public void testDevPortSane() throws Exception {
File f = new File("/dev/port");
assertFalse(f.canRead());
@@ -170,15 +157,12 @@ public class FileSystemPermissionTest extends AndroidTestCase {
/**
* Verify that any publicly readable directories reachable from
- * the root directory are not writable. World writable directories
- * are a security hole and an application should only be able to
- * write to it's own home directory.
+ * the root directory are not writable.
*
* Note: Because not all directories are readable, this is a best-effort
* test only. Writable directories within unreadable subdirectories
* will NOT be detected by this code.
*/
- @LargeTest
public void testAllOtherDirectoriesNotWritable() throws Exception {
File start = new File("/");
assertDirectoryAndSubdirectoriesNotWritable(start);
@@ -186,57 +170,29 @@ public class FileSystemPermissionTest extends AndroidTestCase {
private static final Set OTHER_RANDOM_DIRECTORIES = new HashSet(
Arrays.asList(
- "/app-cache/ciq/socket",
- "/data/anr",
- "/data/app",
- "/data/app-private",
"/data/backup",
- "/data/btips",
- "/data/btips/TI",
- "/data/btips/TI/opp",
+ "/data/secure",
+ "/data/system",
"/data/dalvik-cache",
- "/data/data/.drm",
- "/data/data/.drm/.wmdrm",
+ "/data/property",
+ "/data/app",
+ "/data/app-private",
+ "/data/local",
+ "/data/misc",
"/data/dontpanic",
+ "/data/lost+found",
"/data/drm",
"/data/drm/rights",
- "/data/dump",
- "/data/local",
- "/data/local/tmp/com.nuance.android.vsuite.vsuiteapp",
- "/data/log",
- "/data/lost+found",
- "/data/misc",
- "/data/misc/bluetooth",
- "/data/misc/dhcp",
- "/data/misc/wifi",
- "/data/misc/wifi/sockets",
- "/data/property",
- "/data/secure",
- "/data/shared",
- "/data/system",
- "/data/wifi",
- "/data/wiper",
- "/data/wpstiles",
- "/dbdata/databases",
- "/mnt_ext",
- "/mnt_ext/badablk2",
- "/mnt_ext/badablk3",
- "/mnt_ext/cache",
- "/mnt_ext/data"
+ "/data/data/.drm",
+ "/data/data/.drm/.wmdrm"
)
);
/**
- * Verify that directories not discoverable by
- * testAllOtherDirectoriesNotWritable are not writable. World
- * writable directories are a security hole and an application
- * should only be able to write to it's own home directory.
- *
* Because /data and /data/data are not readable, we blindly try to
* poke around in there looking for bad directories. There has to be
* a better way...
*/
- @LargeTest
public void testOtherRandomDirectoriesNotWritable() throws Exception {
for (String dir : OTHER_RANDOM_DIRECTORIES) {
File start = new File(dir);
@@ -244,7 +200,6 @@ public class FileSystemPermissionTest extends AndroidTestCase {
}
}
- @LargeTest
public void testAllFilesInSysAreNotWritable() throws Exception {
assertAllFilesInDirAndSubDirAreNotWritable(new File("/sys"));
}
diff --git a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
index fab9cf6..a645424 100644
--- a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
@@ -20,13 +20,9 @@ import dalvik.annotation.TestTargetClass;
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/permission/src/android/permission/cts/NoExecutePermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoExecutePermissionTest.java
new file mode 100644
index 0000000..5c0a4c3
--- /dev/null
+++ b/tests/tests/permission/src/android/permission/cts/NoExecutePermissionTest.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.permission.cts;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.Scanner;
+
+import junit.framework.TestCase;
+
+/**
+ * {@link TestCase} that checks that the NX (No Execute) feature is enabled. This feature makes it
+ * harder to perform attacks against Android by marking certain data blocks as non-executable.
+ */
+public class NoExecutePermissionTest extends TestCase {
+
+ public void testNoExecutePermission() throws FileNotFoundException {
+ String heapPermissions = null;
+ String stackPermissions = null;
+
+ Scanner scanner = null;
+ try {
+ scanner = new Scanner(new File("/proc/self/maps"));
+ while (scanner.hasNextLine()) {
+ String line = scanner.nextLine().trim();
+ String[] fields = line.split("\\s+");
+
+ // Sample line:
+ // 0001d000-00024000 rw-p 00000000 00:00 0 [heap]
+ if (fields != null && fields.length >= 1) {
+ String permissions = fields[1];
+ if (fields.length >= 6) {
+ String tag = fields[5];
+ if ("[heap]".equals(tag)) {
+ heapPermissions = permissions;
+ } else if ("[stack]".equals(tag)) {
+ stackPermissions = permissions;
+ }
+ }
+ }
+ }
+ } finally {
+ if (scanner != null) {
+ scanner.close();
+ }
+ }
+
+ assertEquals("NX (No Execute) not enabled for heap", "rw-p", heapPermissions);
+ assertEquals("NX (No Execute) not enabled for stack", "rw-p", stackPermissions);
+ }
+}
diff --git a/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java b/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
index 6258667..f34e380 100755
--- a/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
@@ -77,7 +77,6 @@ public class NoReceiveSmsPermissionTest extends AndroidTestCase {
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/AndroidManifest.xml b/tests/tests/provider/AndroidManifest.xml
index 6811ed2..b67fcf0 100644
--- a/tests/tests/provider/AndroidManifest.xml
+++ b/tests/tests/provider/AndroidManifest.xml
@@ -26,9 +26,5 @@
android:targetPackage="com.android.cts.stub"
android:label="CTS tests of android.provider"/>
-
-
diff --git a/tests/tests/provider/src/android/provider/cts/BrowserTest.java b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
index 73db4c3..2486efa 100644
--- a/tests/tests/provider/src/android/provider/cts/BrowserTest.java
+++ b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
@@ -28,10 +28,8 @@ import android.os.RemoteException;
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;
@@ -52,7 +50,6 @@ public class BrowserTest extends ActivityInstrumentationTestCase2 mBookmarksBackup;
@@ -73,38 +70,20 @@ public class BrowserTest extends ActivityInstrumentationTestCase2();
mSearchesBackup = new ArrayList();
- // Disable sync
- mMasterSyncEnabled = ContentResolver.getMasterSyncAutomatically();
- ContentResolver.setMasterSyncAutomatically(false);
-
// backup the current contents in database
- Cursor cursor = mProvider.query(Bookmarks.CONTENT_URI, null, null, null, null);
+ Cursor cursor = mProvider.query(Browser.BOOKMARKS_URI, null, null, null, null);
if (cursor.moveToFirst()) {
- String[] colNames = cursor.getColumnNames();
while (!cursor.isAfterLast()) {
ContentValues value = new ContentValues();
- 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;
- }
- }
+ 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));
mBookmarksBackup.add(value);
cursor.moveToNext();
@@ -127,41 +106,28 @@ public class BrowserTest extends ActivityInstrumentationTestCase2= 0);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.remove(Events.SELF_ATTENDEE_STATUS);
- long eventId2 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId2 >= 0);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.remove(Events.SELF_ATTENDEE_STATUS);
- long eventId3 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId3 >= 0);
-
- /*
- * Add some attendees, reminders, and extended properties.
- */
- Uri uri, syncUri;
-
- syncUri = asSyncAdapter(Reminders.CONTENT_URI, account, CTS_TEST_TYPE);
- ContentValues remValues = new ContentValues();
- remValues.put(Reminders.EVENT_ID, eventId1);
- remValues.put(Reminders.MINUTES, 10);
- remValues.put(Reminders.METHOD, Reminders.METHOD_ALERT);
- mContentResolver.insert(syncUri, remValues);
- remValues.put(Reminders.MINUTES, 20);
- mContentResolver.insert(syncUri, remValues);
-
- syncUri = asSyncAdapter(ExtendedProperties.CONTENT_URI, account, CTS_TEST_TYPE);
- ContentValues extended = new ContentValues();
- extended.put(ExtendedProperties.NAME, "foo");
- extended.put(ExtendedProperties.VALUE, "bar");
- extended.put(ExtendedProperties.EVENT_ID, eventId2);
- mContentResolver.insert(syncUri, extended);
- extended.put(ExtendedProperties.EVENT_ID, eventId1);
- mContentResolver.insert(syncUri, extended);
- extended.put(ExtendedProperties.NAME, "foo2");
- extended.put(ExtendedProperties.VALUE, "bar2");
- mContentResolver.insert(syncUri, extended);
-
- syncUri = asSyncAdapter(Attendees.CONTENT_URI, account, CTS_TEST_TYPE);
- ContentValues attendee = new ContentValues();
- attendee.put(Attendees.ATTENDEE_NAME, "Joe");
- attendee.put(Attendees.ATTENDEE_EMAIL, CalendarHelper.generateCalendarOwnerEmail(account));
- attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_DECLINED);
- attendee.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
- attendee.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_PERFORMER);
- attendee.put(Attendees.EVENT_ID, eventId3);
- mContentResolver.insert(syncUri, attendee);
-
- /*
- * Iterate over all events on our calendar. Peek at a few values to see if they
- * look reasonable.
- */
- EntityIterator ei = EventsEntity.newEntityIterator(
- mContentResolver.query(EventsEntity.CONTENT_URI, null, Events.CALENDAR_ID + "=?",
- new String[] { String.valueOf(calendarId) }, null),
- mContentResolver);
- int count = 0;
- try {
- while (ei.hasNext()) {
- Entity entity = ei.next();
- ContentValues values = entity.getEntityValues();
- ArrayList subvalues = entity.getSubValues();
- long eventId = values.getAsLong(Events._ID);
- if (eventId == eventId1) {
- // 2 x reminder, 2 x extended properties
- assertEquals(4, subvalues.size());
- } else if (eventId == eventId2) {
- // Extended properties
- assertEquals(1, subvalues.size());
- ContentValues subContentValues = subvalues.get(0).values;
- String name = subContentValues.getAsString(
- CalendarContract.ExtendedProperties.NAME);
- String value = subContentValues.getAsString(
- CalendarContract.ExtendedProperties.VALUE);
- assertEquals("foo", name);
- assertEquals("bar", value);
- } else if (eventId == eventId3) {
- // Attendees
- assertEquals(1, subvalues.size());
- } else {
- fail("should not be here");
- }
- count++;
- }
- assertEquals(3, count);
- } finally {
- ei.close();
- }
-
- // Confirm that querying for a single event yields a single event.
- ei = EventsEntity.newEntityIterator(
- mContentResolver.query(EventsEntity.CONTENT_URI, null, SQL_WHERE_ID,
- new String[] { String.valueOf(eventId3) }, null),
- mContentResolver);
- try {
- count = 0;
- while (ei.hasNext()) {
- Entity entity = ei.next();
- count++;
- }
- assertEquals(1, count);
- } finally {
- ei.close();
- }
-
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Exercises the CalendarEntity class.
- */
- @MediumTest
- public void testCalendarEntityQuery() {
- String account1 = "ceq1_account";
- String account2 = "ceq2_account";
- String account3 = "ceq3_account";
- int seed = 0;
-
- // Clean up just in case.
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account1);
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account2);
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account3);
-
- // Create calendars.
- long calendarId1 = createAndVerifyCalendar(account1, seed++, null);
- long calendarId2 = createAndVerifyCalendar(account2, seed++, null);
- long calendarId3 = createAndVerifyCalendar(account3, seed++, null);
-
- EntityIterator ei = CalendarEntity.newEntityIterator(
- mContentResolver.query(CalendarEntity.CONTENT_URI, null,
- Calendars._ID + "=? OR " + Calendars._ID + "=? OR " + Calendars._ID + "=?",
- new String[] { String.valueOf(calendarId1), String.valueOf(calendarId2),
- String.valueOf(calendarId3) },
- null));
-
- try {
- int count = 0;
- while (ei.hasNext()) {
- Entity entity = ei.next();
- count++;
- }
- assertEquals(3, count);
- } finally {
- ei.close();
- }
-
- removeAndVerifyCalendar(account1, calendarId1);
- removeAndVerifyCalendar(account2, calendarId2);
- removeAndVerifyCalendar(account3, calendarId3);
- }
-
- /**
- * Tests creation and manipulation of Attendees.
- */
- @MediumTest
- public void testAttendees() {
- String account = "att_account";
- int seed = 0;
-
- // Clean up just in case.
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar.
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create two events, one with a value set for SELF_ATTENDEE_STATUS, one without.
- ContentValues eventValues;
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.put(Events.SELF_ATTENDEE_STATUS, Events.STATUS_TENTATIVE);
- long eventId1 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId1 >= 0);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.remove(Events.SELF_ATTENDEE_STATUS);
- long eventId2 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId2 >= 0);
-
- /*
- * Add some attendees to the first event.
- */
- long attId1 = AttendeeHelper.addAttendee(mContentResolver, eventId1,
- "Alice",
- "alice@example.com",
- Attendees.ATTENDEE_STATUS_TENTATIVE,
- Attendees.RELATIONSHIP_ATTENDEE,
- Attendees.TYPE_REQUIRED);
- long attId2 = AttendeeHelper.addAttendee(mContentResolver, eventId1,
- "Betty",
- "betty@example.com",
- Attendees.ATTENDEE_STATUS_DECLINED,
- Attendees.RELATIONSHIP_ATTENDEE,
- Attendees.TYPE_NONE);
- long attId3 = AttendeeHelper.addAttendee(mContentResolver, eventId1,
- "Carol",
- "carol@example.com",
- Attendees.ATTENDEE_STATUS_DECLINED,
- Attendees.RELATIONSHIP_ATTENDEE,
- Attendees.TYPE_OPTIONAL);
-
- /*
- * Find the event1 "self" attendee entry.
- */
- Cursor cursor = AttendeeHelper.findAttendeesByEmail(mContentResolver, eventId1,
- CalendarHelper.generateCalendarOwnerEmail(account));
- try {
- assertEquals(1, cursor.getCount());
- //DatabaseUtils.dumpCursor(cursor);
-
- cursor.moveToFirst();
- long id = cursor.getLong(AttendeeHelper.ATTENDEES_ID_INDEX);
-
- /*
- * Update the status field. The provider should automatically propagate the result.
- */
- ContentValues update = new ContentValues();
- Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, id);
-
- update.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED);
- int count = mContentResolver.update(uri, update, null, null);
- assertEquals(1, count);
-
- int status = EventHelper.lookupSelfAttendeeStatus(mContentResolver, eventId1);
- assertEquals(Attendees.ATTENDEE_STATUS_ACCEPTED, status);
-
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- }
-
- /*
- * Do a bulk update of all Attendees for this event, changing any Attendee with status
- * "declined" to "invited".
- */
- ContentValues bulkUpdate = new ContentValues();
- bulkUpdate.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_INVITED);
-
- int count = mContentResolver.update(Attendees.CONTENT_URI, bulkUpdate,
- Attendees.EVENT_ID + "=? AND " + Attendees.ATTENDEE_STATUS + "=?",
- new String[] {
- String.valueOf(eventId1), String.valueOf(Attendees.ATTENDEE_STATUS_DECLINED)
- });
- assertEquals(2, count);
-
- /*
- * Add a new, non-self attendee to the second event.
- */
- long attId4 = AttendeeHelper.addAttendee(mContentResolver, eventId2,
- "Diana",
- "diana@example.com",
- Attendees.ATTENDEE_STATUS_ACCEPTED,
- Attendees.RELATIONSHIP_ATTENDEE,
- Attendees.TYPE_REQUIRED);
-
- /*
- * Confirm that the selfAttendeeStatus on the second event has the default value.
- */
- int status = EventHelper.lookupSelfAttendeeStatus(mContentResolver, eventId2);
- assertEquals(Attendees.ATTENDEE_STATUS_NONE, status);
-
- /*
- * Create a new "self" attendee in the second event by updating the email address to
- * match that of the calendar owner.
- */
- ContentValues newSelf = new ContentValues();
- newSelf.put(Attendees.ATTENDEE_EMAIL, CalendarHelper.generateCalendarOwnerEmail(account));
- count = mContentResolver.update(ContentUris.withAppendedId(Attendees.CONTENT_URI, attId4),
- newSelf, null, null);
- assertEquals(1, count);
-
- /*
- * Confirm that the event's selfAttendeeStatus has been updated.
- */
- status = EventHelper.lookupSelfAttendeeStatus(mContentResolver, eventId2);
- assertEquals(Attendees.ATTENDEE_STATUS_ACCEPTED, status);
-
- /*
- * TODO: (these are unexpected usage patterns)
- * - Update an Attendee's status and event_id to move it to a different event, and
- * confirm that the selfAttendeeStatus in the destination event is updated (rather
- * than that of the source event).
- * - Create two Attendees with email addresses that match "self" but have different
- * values for "status". Delete one and confirm that selfAttendeeStatus is changed
- * to that of the remaining Attendee. (There is no defined behavior for
- * selfAttendeeStatus when there are multiple matching Attendees.)
- */
-
- /*
- * Test deletion, singly by ID and in bulk.
- */
- count = mContentResolver.delete(ContentUris.withAppendedId(Attendees.CONTENT_URI, attId4),
- null, null);
- assertEquals(1, count);
-
- count = mContentResolver.delete(Attendees.CONTENT_URI, Attendees.EVENT_ID + "=?",
- new String[] { String.valueOf(eventId1) });
- assertEquals(4, count); // 3 we created + 1 auto-added by the provider
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests creation and manipulation of Reminders.
- */
- @MediumTest
- public void testReminders() {
- String account = "rem_account";
- int seed = 0;
-
- // Clean up just in case.
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar.
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create events.
- ContentValues eventValues;
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- long eventId1 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId1 >= 0);
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- long eventId2 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId2 >= 0);
-
- // No reminders, hasAlarm should be zero.
- int hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId1);
- assertEquals(0, hasAlarm);
- hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId2);
- assertEquals(0, hasAlarm);
-
- /*
- * Add some reminders.
- */
- long remId1 = ReminderHelper.addReminder(mContentResolver, eventId1,
- 10, Reminders.METHOD_DEFAULT);
- long remId2 = ReminderHelper.addReminder(mContentResolver, eventId1,
- 15, Reminders.METHOD_ALERT);
- long remId3 = ReminderHelper.addReminder(mContentResolver, eventId1,
- 20, Reminders.METHOD_SMS); // SMS isn't allowed for this calendar
-
- // Should have been set to 1 by provider.
- hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId1);
- assertEquals(1, hasAlarm);
-
- // Add a reminder to event2.
- ReminderHelper.addReminder(mContentResolver, eventId2,
- 20, Reminders.METHOD_DEFAULT);
- hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId2);
- assertEquals(1, hasAlarm);
-
-
- /*
- * Check the entries.
- */
- Cursor cursor = ReminderHelper.findRemindersByEventId(mContentResolver, eventId1);
- try {
- assertEquals(3, cursor.getCount());
- //DatabaseUtils.dumpCursor(cursor);
-
- while (cursor.moveToNext()) {
- int minutes = cursor.getInt(ReminderHelper.REMINDERS_MINUTES_INDEX);
- int method = cursor.getInt(ReminderHelper.REMINDERS_METHOD_INDEX);
- switch (minutes) {
- case 10:
- assertEquals(Reminders.METHOD_DEFAULT, method);
- break;
- case 15:
- assertEquals(Reminders.METHOD_ALERT, method);
- break;
- case 20:
- assertEquals(Reminders.METHOD_SMS, method);
- break;
- default:
- fail("unexpected minutes " + minutes);
- break;
- }
- }
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- }
-
- /*
- * Use the bulk update feature to change all METHOD_DEFAULT to METHOD_EMAIL. To make
- * this more interesting we first change remId3 to METHOD_DEFAULT.
- */
- int count;
- ContentValues newValues = new ContentValues();
- newValues.put(Reminders.METHOD, Reminders.METHOD_DEFAULT);
- count = mContentResolver.update(ContentUris.withAppendedId(Reminders.CONTENT_URI, remId3),
- newValues, null, null);
- assertEquals(1, count);
-
- newValues.put(Reminders.METHOD, Reminders.METHOD_EMAIL);
- count = mContentResolver.update(Reminders.CONTENT_URI, newValues,
- Reminders.EVENT_ID + "=? AND " + Reminders.METHOD + "=?",
- new String[] {
- String.valueOf(eventId1), String.valueOf(Reminders.METHOD_DEFAULT)
- });
- assertEquals(2, count);
-
- // check it
- int method = ReminderHelper.lookupMethod(mContentResolver, remId3);
- assertEquals(Reminders.METHOD_EMAIL, method);
-
- /*
- * Delete some / all reminders and confirm that hasAlarm tracks it.
- *
- * You can also remove reminders from an event by updating the event_id column, but
- * that's defined as producing undefined behavior, so we don't do it here.
- */
- count = mContentResolver.delete(Reminders.CONTENT_URI,
- Reminders.EVENT_ID + "=? AND " + Reminders.MINUTES + ">=?",
- new String[] { String.valueOf(eventId1), "15" });
- assertEquals(2, count);
- hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId1);
- assertEquals(1, hasAlarm);
-
- // Delete all reminders from both events.
- count = mContentResolver.delete(Reminders.CONTENT_URI,
- Reminders.EVENT_ID + "=? OR " + Reminders.EVENT_ID + "=?",
- new String[] { String.valueOf(eventId1), String.valueOf(eventId2) });
- assertEquals(2, count);
- hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId1);
- assertEquals(0, hasAlarm);
- hasAlarm = EventHelper.lookupHasAlarm(mContentResolver, eventId2);
- assertEquals(0, hasAlarm);
-
- /*
- * Add a couple of reminders and then delete one with the by-ID URI.
- */
- long remId4 = ReminderHelper.addReminder(mContentResolver, eventId1,
- 10, Reminders.METHOD_EMAIL);
- long remId5 = ReminderHelper.addReminder(mContentResolver, eventId1,
- 15, Reminders.METHOD_EMAIL);
- count = mContentResolver.delete(ContentUris.withAppendedId(Reminders.CONTENT_URI, remId4),
- null, null);
- assertEquals(1, count);
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests creation and manipulation of ExtendedProperties.
- */
- @MediumTest
- public void testExtendedProperties() {
- String account = "ep_account";
- int seed = 0;
-
- // Clean up just in case.
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar.
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create events.
- ContentValues eventValues;
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- long eventId1 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId1 >= 0);
-
- /*
- * Add some extended properties.
- */
- long epId1 = ExtendedPropertiesHelper.addExtendedProperty(mContentResolver, account,
- eventId1, "first", "Jeffrey");
- long epId2 = ExtendedPropertiesHelper.addExtendedProperty(mContentResolver, account,
- eventId1, "last", "Lebowski");
- long epId3 = ExtendedPropertiesHelper.addExtendedProperty(mContentResolver, account,
- eventId1, "title", "Dude");
-
- /*
- * Spot-check a couple of entries.
- */
- Cursor cursor = ExtendedPropertiesHelper.findExtendedPropertiesByEventId(mContentResolver,
- eventId1);
- try {
- assertEquals(3, cursor.getCount());
- //DatabaseUtils.dumpCursor(cursor);
-
- while (cursor.moveToNext()) {
- String name =
- cursor.getString(ExtendedPropertiesHelper.EXTENDED_PROPERTIES_NAME_INDEX);
- String value =
- cursor.getString(ExtendedPropertiesHelper.EXTENDED_PROPERTIES_VALUE_INDEX);
-
- if (name.equals("last")) {
- assertEquals("Lebowski", value);
- }
- }
-
- String title = ExtendedPropertiesHelper.lookupValueByName(mContentResolver, eventId1,
- "title");
- assertEquals("Dude", title);
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- }
-
- // Update the title. Must be done as a sync adapter.
- ContentValues newValues = new ContentValues();
- newValues.put(ExtendedProperties.VALUE, "Big");
- Uri uri = ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI, epId3);
- uri = asSyncAdapter(uri, account, CTS_TEST_TYPE);
- int count = mContentResolver.update(uri, newValues, null, null);
- assertEquals(1, count);
-
- // check it
- String title = ExtendedPropertiesHelper.lookupValueByName(mContentResolver, eventId1,
- "title");
- assertEquals("Big", title);
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Test instance queries with search parameters.
- */
- @MediumTest
- public void testInstanceSearch() {
- String account = "cser_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create a calendar
- ContentValues values = CalendarHelper.getNewCalendarValues(account, seed);
- long calendarId = createAndVerifyCalendar(account, seed++, values);
-
- String testStart = "2009-10-01T08:00:00";
- String timeZone = TIME_ZONES[0];
- Time startTime = new Time(timeZone);
- startTime.parse3339(testStart);
- long startMillis = startTime.toMillis(false);
-
- // Create some events, with different descriptions. (Could also create a single
- // recurring event and some instance exceptions.)
- ContentValues eventValues;
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.put(Events.DESCRIPTION, "testevent event-one fiddle");
- eventValues.put(Events.DTSTART, startMillis);
- eventValues.put(Events.DTEND, startMillis + DateUtils.HOUR_IN_MILLIS);
- eventValues.put(Events.EVENT_TIMEZONE, timeZone);
- long eventId1 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId1 >= 0);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.put(Events.DESCRIPTION, "testevent event-two fuzzle");
- eventValues.put(Events.DTSTART, startMillis + DateUtils.HOUR_IN_MILLIS);
- eventValues.put(Events.DTEND, startMillis + DateUtils.HOUR_IN_MILLIS * 2);
- eventValues.put(Events.EVENT_TIMEZONE, timeZone);
- long eventId2 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId2 >= 0);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.put(Events.DESCRIPTION, "testevent event-three fiddle");
- eventValues.put(Events.DTSTART, startMillis + DateUtils.HOUR_IN_MILLIS * 2);
- eventValues.put(Events.DTEND, startMillis + DateUtils.HOUR_IN_MILLIS * 3);
- eventValues.put(Events.EVENT_TIMEZONE, timeZone);
- long eventId3 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId3 >= 0);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- eventValues.put(Events.DESCRIPTION, "nontestevent");
- eventValues.put(Events.DTSTART, startMillis + (long) (DateUtils.HOUR_IN_MILLIS * 1.5f));
- eventValues.put(Events.DTEND, startMillis + DateUtils.HOUR_IN_MILLIS * 2);
- eventValues.put(Events.EVENT_TIMEZONE, timeZone);
- long eventId4 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- assertTrue(eventId4 >= 0);
-
- String rangeStart = "2009-10-01T00:00:00";
- String rangeEnd = "2009-10-01T11:59:59";
- String[] projection = new String[] { Instances.BEGIN };
-
- if (false) {
- Cursor instances = getInstances(timeZone, rangeStart, rangeEnd, projection);
- dumpInstances(instances, timeZone, "all");
- instances.close();
- }
-
- Cursor instances;
- int count;
-
- // Find all matching "testevent". The search matches on partial strings, so this
- // will also pick up "nontestevent".
- instances = getInstancesSearch(timeZone, rangeStart, rangeEnd,
- "testevent", false, projection);
- count = instances.getCount();
- instances.close();
- assertEquals(4, count);
-
- // Find all matching "fiddle" and "event". Set the "by day" flag just to be different.
- instances = getInstancesSearch(timeZone, rangeStart, rangeEnd,
- "fiddle event", true, projection);
- count = instances.getCount();
- instances.close();
- assertEquals(2, count);
-
- // Find all matching "fiddle" and "baluchitherium".
- instances = getInstancesSearch(timeZone, rangeStart, rangeEnd,
- "baluchitherium fiddle", false, projection);
- count = instances.getCount();
- instances.close();
- assertEquals(0, count);
-
- // Find all matching "event-two".
- instances = getInstancesSearch(timeZone, rangeStart, rangeEnd,
- "event-two", false, projection);
- count = instances.getCount();
- instances.close();
- assertEquals(1, count);
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- @MediumTest
- public void testCalendarUpdateAsApp() {
- String account = "cu1_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create a calendar
- ContentValues values = CalendarHelper.getNewCalendarValues(account, seed);
- long id = createAndVerifyCalendar(account, seed++, values);
-
- Uri uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, id);
-
- // Update the calendar using the direct Uri
- ContentValues updateValues = CalendarHelper.getUpdateCalendarValuesWithOriginal(
- values, seed++);
- assertEquals(1, mContentResolver.update(uri, updateValues, null, null));
-
- verifyCalendar(account, values, id);
-
- // Update the calendar using selection + args
- String selection = Calendars._ID + "=?";
- String[] selectionArgs = new String[] { Long.toString(id) };
-
- updateValues = CalendarHelper.getUpdateCalendarValuesWithOriginal(values, seed++);
-
- assertEquals(1, mContentResolver.update(
- Calendars.CONTENT_URI, updateValues, selection, selectionArgs));
-
- verifyCalendar(account, values, id);
-
- removeAndVerifyCalendar(account, id);
- }
-
- // TODO test calendar updates as sync adapter
-
- /**
- * Test access to the "syncstate" table.
- */
- @MediumTest
- public void testSyncState() {
- String account = "ss_account";
- int seed = 0;
-
- // Clean up just in case
- SyncStateHelper.deleteSyncStateByAccount(mContentResolver, account, true);
-
- // Create a new sync state entry
- ContentValues values = SyncStateHelper.getNewSyncStateValues(account);
- long id = createAndVerifySyncState(account, values);
-
- // Look it up with the by-ID URI
- Cursor c = SyncStateHelper.getSyncStateById(mContentResolver, id);
- assertNotNull(c);
- assertEquals(1, c.getCount());
- c.close();
-
- // Try to remove it as non-sync-adapter; expected to fail.
- boolean failed;
- try {
- SyncStateHelper.deleteSyncStateByAccount(mContentResolver, account, false);
- failed = false;
- } catch (IllegalArgumentException iae) {
- failed = true;
- }
- assertTrue("deletion of sync state by app was allowed", failed);
-
- // Remove it and verify that it's gone
- removeAndVerifySyncState(account);
- }
-
-
- private void verifyEvent(ContentValues values, long eventId) {
- Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
- // Verify
- Cursor c = mContentResolver
- .query(eventUri, EventHelper.EVENTS_PROJECTION, null, null, null);
- assertEquals(1, c.getCount());
- assertTrue(c.moveToFirst());
- assertEquals(eventId, c.getLong(0));
- for (String key : values.keySet()) {
- int index = c.getColumnIndex(key);
- assertEquals(key, values.getAsString(key), c.getString(index));
- }
- c.close();
- }
-
- @MediumTest
- public void testEventCreationAndDeletion() {
- String account = "ec1_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar and event
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- ContentValues eventValues = EventHelper
- .getNewEventValues(account, seed++, calendarId, true);
- long eventId = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
-
- Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
-
- removeAndVerifyEvent(eventUri, eventValues, account);
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- @MediumTest
- public void testEventUpdateAsApp() {
- String account = "em1_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create event as sync adapter
- ContentValues eventValues = EventHelper
- .getNewEventValues(account, seed++, calendarId, true);
- long eventId = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
-
- // Update event as app
- Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
-
- ContentValues updateValues = EventHelper.getUpdateEventValuesWithOriginal(eventValues,
- seed++, false);
- assertEquals(1, mContentResolver.update(eventUri, updateValues, null, null));
- updateValues.put(Events.DIRTY, 1); // provider should have marked as dirty
- verifyEvent(updateValues, eventId);
-
- removeAndVerifyEvent(eventUri, eventValues, account);
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests update of multiple events with a single update call.
- */
- @MediumTest
- public void testBulkUpdate() {
- String account = "bup_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
- String calendarIdStr = String.valueOf(calendarId);
-
- // Create events
- ContentValues eventValues;
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- long eventId1 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
-
- eventValues = EventHelper.getNewEventValues(account, seed++, calendarId, true);
- long eventId2 = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
-
- // Update the "description" field in all events in this calendar.
- String newDescription = "bulk edit";
- ContentValues updateValues = new ContentValues();
- updateValues.put(Events.DESCRIPTION, newDescription);
-
- // Must be sync adapter to do a bulk update.
- Uri uri = asSyncAdapter(Events.CONTENT_URI, account, CTS_TEST_TYPE);
- int count = mContentResolver.update(uri, updateValues, SQL_WHERE_CALENDAR_ID,
- new String[] { calendarIdStr });
-
- // Check to see if the changes went through.
- Uri eventUri = Events.CONTENT_URI;
- Cursor c = mContentResolver.query(eventUri, new String[] { Events.DESCRIPTION },
- SQL_WHERE_CALENDAR_ID, new String[] { calendarIdStr }, null);
- assertEquals(2, c.getCount());
- while (c.moveToNext()) {
- assertEquals(newDescription, c.getString(0));
- }
- c.close();
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests the content provider's enforcement of restrictions on who is allowed to modify
- * specific columns in a Calendar.
- *
- * This attempts to create a new row in the Calendar table, specifying one restricted
- * column at a time.
- */
- @MediumTest
- public void testSyncOnlyInsertEnforcement() {
- // These operations should not succeed, so there should be nothing to clean up after.
- // TODO: this should be a new event augmented with an illegal column, not a single
- // column. Otherwise we might be tripping over a "DTSTART must exist" test.
- ContentValues vals = new ContentValues();
- for (int i = 0; i < Calendars.SYNC_WRITABLE_COLUMNS.length; i++) {
- boolean threw = false;
- try {
- vals.clear();
- vals.put(Calendars.SYNC_WRITABLE_COLUMNS[i], "1");
- mContentResolver.insert(Calendars.CONTENT_URI, vals);
- } catch (IllegalArgumentException e) {
- threw = true;
- }
- assertTrue("Only sync adapter should be allowed to insert "
- + Calendars.SYNC_WRITABLE_COLUMNS[i], threw);
- }
- }
-
- /**
- * Tests creation of a recurring event.
- *
- * This (and the other recurrence tests) uses dates well in the past to reduce the likelihood
- * of encountering non-test recurring events. (Ideally we would select events associated
- * with a specific calendar.) With dates well in the past, it's also important to have a
- * fixed maximum count or end date; otherwise, if the metadata min/max instance values are
- * large enough, the recurrence recalculation processor could get triggered on an insert or
- * update and bump up against the 2000-instance limit.
- *
- * TODO: need some allDay tests
- */
- @MediumTest
- public void testRecurrence() {
- String account = "re_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create recurring event
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, true, "2003-08-05T09:00:00", "PT1H",
- "FREQ=WEEKLY;INTERVAL=2;COUNT=4;BYDAY=TU,SU;WKST=SU");
- long eventId = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
- //Log.d(TAG, "+++ basic recurrence eventId is " + eventId);
-
- // Check to see if we have the expected number of instances
- String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
- int instanceCount = getInstanceCount(timeZone, "2003-08-05T00:00:00",
- "2003-08-31T11:59:59");
- if (false) {
- Cursor instances = getInstances(timeZone, "2003-08-05T00:00:00", "2003-08-31T11:59:59",
- new String[] { Instances.BEGIN });
- dumpInstances(instances, timeZone, "initial");
- instances.close();
- }
- assertEquals("recurrence instance count", 4, instanceCount);
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests conversion of a regular event to a recurring event.
- */
- @MediumTest
- public void testConversionToRecurring() {
- String account = "reconv_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar and event
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- ContentValues eventValues = EventHelper
- .getNewEventValues(account, seed++, calendarId, true);
- long eventId = createAndVerifyEvent(account, seed, calendarId, true, eventValues);
-
- long dtstart = eventValues.getAsLong(Events.DTSTART);
- long dtend = eventValues.getAsLong(Events.DTEND);
- long durationSecs = (dtend - dtstart) / 1000;
-
- ContentValues updateValues = new ContentValues();
- updateValues.put(Events.RRULE, "FREQ=WEEKLY"); // recurs forever
- updateValues.put(Events.DURATION, "P" + durationSecs + "S");
- updateValues.putNull(Events.DTEND);
-
- // Issue update; do it as app instead of sync adapter to exercise that path.
- updateAndVerifyEvent(account, calendarId, eventId, false, updateValues);
-
- // Make sure LAST_DATE got nulled out by our infinitely repeating sequence.
- Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
- Cursor c = mContentResolver.query(eventUri, new String[] { Events.LAST_DATE },
- null, null, null);
- assertEquals(1, c.getCount());
- assertTrue(c.moveToFirst());
- assertNull(c.getString(0));
- c.close();
-
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests creation of a recurring event with single-instance exceptions.
- */
- @MediumTest
- public void testSingleRecurrenceExceptions() {
- String account = "rex_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create recurring event.
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, true, "1999-03-28T09:00:00", "PT1H", "FREQ=WEEKLY;WKST=SU;COUNT=100");
- long eventId = createAndVerifyEvent(account, seed++, calendarId, true, eventValues);
-
- // Add some attendees and reminders.
- addAttendees(account, eventId, seed);
- addReminders(account, eventId, seed);
-
- // Select a period that gives us 5 instances. We don't want this to straddle a DST
- // transition, because we expect the startMinute field to be the same for all
- // instances, and it's stored as minutes since midnight in the device's time zone.
- // Things won't be consistent if the event and the device have different ideas about DST.
- String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
- String testStart = "1999-04-18T00:00:00";
- String testEnd = "1999-05-16T23:59:59";
- String[] projection = { Instances.BEGIN, Instances.START_MINUTE, Instances.END_MINUTE };
-
- Cursor instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "initial");
- }
-
- assertEquals("initial recurrence instance count", 5, instances.getCount());
-
- /*
- * Advance the start time of a few instances, and verify.
- */
-
- // Leave first instance alone.
- instances.moveToPosition(1);
-
- long startMillis;
- ContentValues excepValues;
-
- // Advance the start time of the 2nd instance.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.DTSTART, startMillis + 3600*1000);
- long excepEventId2 = createAndVerifyException(account, eventId, excepValues, true);
- instances.moveToNext();
-
- // Advance the start time of the 3rd instance.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.DTSTART, startMillis + 3600*1000*2);
- long excepEventId3 = createAndVerifyException(account, eventId, excepValues, true);
- instances.moveToNext();
-
- // Cancel the 4th instance.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.STATUS, Events.STATUS_CANCELED);
- long excepEventId4 = createAndVerifyException(account, eventId, excepValues, true);
- instances.moveToNext();
-
- // TODO: try to modify a non-existent instance.
-
- instances.close();
-
- // TODO: compare Reminders, Attendees, ExtendedProperties on one of the exception events
-
- // Re-query the instances and figure out if they look right.
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "with DTSTART exceptions");
- }
- assertEquals("exceptional recurrence instance count", 4, instances.getCount());
-
- long prevMinute = -1;
- while (instances.moveToNext()) {
- // expect the start times for each entry to be different from the previous entry
- long startMinute = instances.getLong(1);
- assertTrue("instance start times are different", startMinute != prevMinute);
-
- prevMinute = startMinute;
- }
- instances.close();
-
-
- // Delete all of our exceptions, and verify.
- int deleteCount = 0;
- deleteCount += deleteException(account, eventId, excepEventId2);
- deleteCount += deleteException(account, eventId, excepEventId3);
- deleteCount += deleteException(account, eventId, excepEventId4);
- assertEquals("events deleted", 3, deleteCount);
-
- // Re-query the instances and figure out if they look right.
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "post exception deletion");
- }
- assertEquals("post-exception deletion instance count", 5, instances.getCount());
-
- prevMinute = -1;
- while (instances.moveToNext()) {
- // expect the start times for each entry to be the same
- long startMinute = instances.getLong(1);
- if (prevMinute != -1) {
- assertEquals("instance start times are the same", startMinute, prevMinute);
- }
- prevMinute = startMinute;
- }
- instances.close();
-
- /*
- * Repeat the test, this time modifying DURATION.
- */
-
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "initial");
- }
-
- assertEquals("initial recurrence instance count", 5, instances.getCount());
-
- // Leave first instance alone.
- instances.moveToPosition(1);
-
- // Advance the end time of the 2nd instance.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.DURATION, "P" + 3600*2 + "S");
- excepEventId2 = createAndVerifyException(account, eventId, excepValues, true);
- instances.moveToNext();
-
- // Advance the end time of the 3rd instance, and change the self-attendee status.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.DURATION, "P" + 3600*3 + "S");
- excepValues.put(Events.SELF_ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_DECLINED);
- excepEventId3 = createAndVerifyException(account, eventId, excepValues, true);
- instances.moveToNext();
-
- // Advance the start time of the 4th instance, which will also advance the end time.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.DTSTART, startMillis + 3600*1000);
- excepEventId4 = createAndVerifyException(account, eventId, excepValues, true);
- instances.moveToNext();
-
- instances.close();
-
- // TODO: make sure the selfAttendeeStatus change took
-
- // Re-query the instances and figure out if they look right.
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "with DURATION exceptions");
- }
- assertEquals("exceptional recurrence instance count", 5, instances.getCount());
-
- prevMinute = -1;
- while (instances.moveToNext()) {
- // expect the start times for each entry to be different from the previous entry
- long endMinute = instances.getLong(2);
- assertTrue("instance end times are different", endMinute != prevMinute);
-
- prevMinute = endMinute;
- }
- instances.close();
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests creation of a simple recurrence exception when not pretending to be the sync
- * adapter. One significant consequence is that we don't set the _sync_id field in the
- * events, which affects how the provider correlates recurrences and exceptions.
- */
- @MediumTest
- public void testNonAdapterRecurrenceExceptions() {
- String account = "rena_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Generate recurring event, with "asSyncAdapter" set to false.
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, false, "1991-02-03T12:00:00", "PT1H", "FREQ=DAILY;WKST=SU;COUNT=10");
-
- // Select a period that gives us 3 instances.
- String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
- String testStart = "1991-02-03T00:00:00";
- String testEnd = "1991-02-05T23:59:59";
- String[] projection = { Instances.BEGIN, Instances.START_MINUTE };
-
- // Expand the bounds of the instances table so we expand future events as they are added.
- expandInstanceRange(account, calendarId, testStart, testEnd, timeZone);
-
- // Create the event in the database.
- long eventId = createAndVerifyEvent(account, seed++, calendarId, false, eventValues);
- assertTrue(eventId >= 0);
-
- // Add some attendees.
- addAttendees(account, eventId, seed);
-
- Cursor instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "initial");
- }
- assertEquals("initial recurrence instance count", 3, instances.getCount());
-
- /*
- * Alter the attendee status of the second event. This should cause the instances to
- * be updated, replacing the previous 2nd instance with the exception instance. If the
- * code is broken we'll see four instances (because the original instance didn't get
- * removed) or one instance (because the code correctly deleted all related events but
- * couldn't correlate the exception with its original recurrence).
- */
-
- // Leave first instance alone.
- instances.moveToPosition(1);
-
- long startMillis;
- ContentValues excepValues;
-
- // Advance the start time of the 2nd instance.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.SELF_ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_DECLINED);
- long excepEventId2 = createAndVerifyException(account, eventId, excepValues, false);
- instances.moveToNext();
-
- instances.close();
-
- // Re-query the instances and figure out if they look right.
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "with exceptions");
- }
-
- // TODO: this test currently fails due to limitations in the provider
- //assertEquals("exceptional recurrence instance count", 3, instances.getCount());
-
- instances.close();
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests insertion of event exceptions before and after a recurring event is created.
- *
- * The server may send exceptions down before the event they refer to, so the provider
- * fills in the originalId of previously-existing exceptions when a recurring event is
- * inserted. Make sure that works.
- *
- * The _sync_id column is only unique with a given calendar. We create events with
- * identical originalSyncId values in two different calendars to verify that the provider
- * doesn't update unrelated events.
- *
- * We can't use the /exception URI, because that only works if the events are created
- * in order.
- */
- @MediumTest
- public void testOutOfOrderRecurrenceExceptions() {
- String account1 = "roid1_account";
- String account2 = "roid2_account";
- String startWhen = "1987-08-09T12:00:00";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account1);
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account2);
-
- // Create calendars
- long calendarId1 = createAndVerifyCalendar(account1, seed++, null);
- long calendarId2 = createAndVerifyCalendar(account2, seed++, null);
-
-
- // Generate base event.
- ContentValues recurEventValues = EventHelper.getNewRecurringEventValues(account1, seed++,
- calendarId1, true, startWhen, "PT1H", "FREQ=DAILY;WKST=SU;COUNT=10");
-
- // Select a period that gives us 3 instances.
- String timeZone = recurEventValues.getAsString(Events.EVENT_TIMEZONE);
- String testStart = "1987-08-09T00:00:00";
- String testEnd = "1987-08-11T23:59:59";
- String[] projection = { Instances.BEGIN, Instances.START_MINUTE, Instances.EVENT_ID };
-
- /*
- * We're interested in exploring what the instance expansion code does with the events
- * as they arrive. It won't do anything at event-creation time unless the instance
- * range already covers the interesting set of dates, so we need to create and remove
- * an instance in the same time frame beforehand.
- */
- expandInstanceRange(account1, calendarId1, testStart, testEnd, timeZone);
-
- /*
- * Instances table should be expanded. Do the test.
- */
-
- final String MAGIC_SYNC_ID = "MagicSyncId";
- recurEventValues.put(Events._SYNC_ID, MAGIC_SYNC_ID);
-
- // Generate exceptions from base, removing the generated _sync_id and setting the
- // base event's _sync_id as originalSyncId.
- ContentValues beforeExcepValues, afterExcepValues, unrelatedExcepValues;
- beforeExcepValues = new ContentValues(recurEventValues);
- afterExcepValues = new ContentValues(recurEventValues);
- unrelatedExcepValues = new ContentValues(recurEventValues);
- beforeExcepValues.remove(Events._SYNC_ID);
- afterExcepValues.remove(Events._SYNC_ID);
- unrelatedExcepValues.remove(Events._SYNC_ID);
- beforeExcepValues.put(Events.ORIGINAL_SYNC_ID, MAGIC_SYNC_ID);
- afterExcepValues.put(Events.ORIGINAL_SYNC_ID, MAGIC_SYNC_ID);
- unrelatedExcepValues.put(Events.ORIGINAL_SYNC_ID, MAGIC_SYNC_ID);
-
- // Disassociate the "unrelated" exception by moving it to the other calendar.
- unrelatedExcepValues.put(Events.CALENDAR_ID, calendarId2);
-
- // We shift the start time by half an hour, and use the same _sync_id.
- final long ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;
- final long ONE_HOUR_MILLIS = 60 * 60 * 1000;
- final long HALF_HOUR_MILLIS = 30 * 60 * 1000;
- long dtstartMillis = recurEventValues.getAsLong(Events.DTSTART) + ONE_DAY_MILLIS;
- beforeExcepValues.put(Events.ORIGINAL_INSTANCE_TIME, dtstartMillis);
- beforeExcepValues.put(Events.DTSTART, dtstartMillis + HALF_HOUR_MILLIS);
- beforeExcepValues.put(Events.DTEND, dtstartMillis + ONE_HOUR_MILLIS);
- beforeExcepValues.remove(Events.DURATION);
- beforeExcepValues.remove(Events.RRULE);
- beforeExcepValues.put(Events.ORIGINAL_SYNC_ID, MAGIC_SYNC_ID);
- dtstartMillis += ONE_DAY_MILLIS;
- afterExcepValues.put(Events.ORIGINAL_INSTANCE_TIME, dtstartMillis);
- afterExcepValues.put(Events.DTSTART, dtstartMillis + HALF_HOUR_MILLIS);
- afterExcepValues.put(Events.DTEND, dtstartMillis + ONE_HOUR_MILLIS);
- afterExcepValues.remove(Events.DURATION);
- afterExcepValues.remove(Events.RRULE);
- afterExcepValues.put(Events.ORIGINAL_SYNC_ID, MAGIC_SYNC_ID);
- dtstartMillis += ONE_DAY_MILLIS;
- unrelatedExcepValues.put(Events.ORIGINAL_INSTANCE_TIME, dtstartMillis);
- unrelatedExcepValues.put(Events.DTSTART, dtstartMillis + HALF_HOUR_MILLIS);
- unrelatedExcepValues.put(Events.DTEND, dtstartMillis + ONE_HOUR_MILLIS);
- unrelatedExcepValues.remove(Events.DURATION);
- unrelatedExcepValues.remove(Events.RRULE);
- unrelatedExcepValues.put(Events.ORIGINAL_SYNC_ID, MAGIC_SYNC_ID);
-
-
- // Create "before" and "unrelated" exceptions.
- long beforeEventId = createAndVerifyEvent(account1, seed, calendarId1, true,
- beforeExcepValues);
- assertTrue(beforeEventId >= 0);
- long unrelatedEventId = createAndVerifyEvent(account2, seed, calendarId2, true,
- unrelatedExcepValues);
- assertTrue(unrelatedEventId >= 0);
-
- // Create recurring event.
- long recurEventId = createAndVerifyEvent(account1, seed, calendarId1, true,
- recurEventValues);
- assertTrue(recurEventId >= 0);
-
- // Create "after" exception.
- long afterEventId = createAndVerifyEvent(account1, seed, calendarId1, true,
- afterExcepValues);
- assertTrue(afterEventId >= 0);
-
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "before=" + beforeEventId + ", unrel=" + unrelatedEventId +
- ", recur=" + recurEventId + ", after=" + afterEventId);
- }
-
- // Check to see how many instances we get. If the recurrence and the exception don't
- // get paired up correctly, we'll see too many instances.
- Cursor instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "with exception");
- }
-
- assertEquals("initial recurrence instance count", 3, instances.getCount());
-
- instances.close();
-
-
- /*
- * Now we want to verify that:
- * - "before" and "after" have an originalId equal to our recurEventId
- * - "unrelated" has no originalId
- */
- Cursor c = null;
- try {
- final String[] PROJECTION = new String[] { Events.ORIGINAL_ID };
- Uri eventUri;
- Long originalId;
-
- eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, beforeEventId);
- c = mContentResolver.query(eventUri, PROJECTION, null, null, null);
- assertEquals(1, c.getCount());
- c.moveToNext();
- originalId = c.getLong(0);
- assertNotNull(originalId);
- assertEquals(recurEventId, (long) originalId);
- c.close();
-
- eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, afterEventId);
- c = mContentResolver.query(eventUri, PROJECTION, null, null, null);
- assertEquals(1, c.getCount());
- c.moveToNext();
- originalId = c.getLong(0);
- assertNotNull(originalId);
- assertEquals(recurEventId, (long) originalId);
- c.close();
-
- eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, unrelatedEventId);
- c = mContentResolver.query(eventUri, PROJECTION, null, null, null);
- assertEquals(1, c.getCount());
- c.moveToNext();
- assertNull(c.getString(0));
- c.close();
-
- c = null;
- } finally {
- if (c != null) {
- c.close();
- }
- }
-
- // delete the calendars
- removeAndVerifyCalendar(account1, calendarId1);
- removeAndVerifyCalendar(account2, calendarId2);
- }
-
- /**
- * Tests exceptions that modify all future instances of a recurring event.
- */
- @MediumTest
- public void testForwardRecurrenceExceptions() {
- String account = "refx_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create recurring event
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, true, "1999-01-01T06:00:00", "PT1H", "FREQ=WEEKLY;WKST=SU;COUNT=10");
- long eventId = createAndVerifyEvent(account, seed++, calendarId, true, eventValues);
-
- // Add some attendees and reminders.
- addAttendees(account, eventId, seed++);
- addReminders(account, eventId, seed++);
-
- // Get some instances.
- String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
- String testStart = "1999-01-01T00:00:00";
- String testEnd = "1999-01-29T23:59:59";
- String[] projection = { Instances.BEGIN, Instances.START_MINUTE };
-
- Cursor instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "initial");
- }
-
- assertEquals("initial recurrence instance count", 5, instances.getCount());
-
- // Modify starting from 3rd instance.
- instances.moveToPosition(2);
-
- long startMillis;
- ContentValues excepValues;
-
- // Replace with a new recurrence rule. We move the start time an hour later, and cap
- // it at two instances.
- startMillis = instances.getLong(0);
- excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.DTSTART, startMillis + 3600*1000);
- excepValues.put(Events.RRULE, "FREQ=WEEKLY;COUNT=2;WKST=SU");
- long excepEventId = createAndVerifyException(account, eventId, excepValues, true);
- instances.close();
-
-
- // Check to see if it took.
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "with new rule");
- }
-
- assertEquals("count with exception", 4, instances.getCount());
-
- long prevMinute = -1;
- for (int i = 0; i < 4; i++) {
- long startMinute;
- instances.moveToNext();
- switch (i) {
- case 0:
- startMinute = instances.getLong(1);
- break;
- case 1:
- case 3:
- startMinute = instances.getLong(1);
- assertEquals("first/last pairs match", prevMinute, startMinute);
- break;
- case 2:
- startMinute = instances.getLong(1);
- assertFalse("first two != last two", prevMinute == startMinute);
- break;
- default:
- fail();
- startMinute = -1; // make compiler happy
- break;
- }
-
- prevMinute = startMinute;
- }
- instances.close();
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Tests exceptions that modify all instances of a recurring event. This is not really an
- * exception, since it won't create a new event, but supporting it allows us to use the
- * exception URI without having to determine whether the "start from here" instance is the
- * very first instance.
- */
- @MediumTest
- public void testFullRecurrenceUpdate() {
- String account = "ref_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create recurring event
- String rrule = "FREQ=DAILY;WKST=MO;COUNT=100";
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, true, "1997-08-29T02:14:00", "PT1H", rrule);
- long eventId = createAndVerifyEvent(account, seed++, calendarId, true, eventValues);
- //Log.i(TAG, "+++ eventId is " + eventId);
-
- // Get some instances.
- String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
- String testStart = "1997-08-01T00:00:00";
- String testEnd = "1997-08-31T23:59:59";
- String[] projection = { Instances.BEGIN, Instances.EVENT_LOCATION };
- String newLocation = "NEW!";
-
- Cursor instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "initial");
- }
-
- assertEquals("initial recurrence instance count", 3, instances.getCount());
-
- instances.moveToFirst();
- long startMillis = instances.getLong(0);
- ContentValues excepValues = EventHelper.getNewExceptionValues(startMillis);
- excepValues.put(Events.RRULE, rrule); // identifies this as an "all future events" excep
- excepValues.put(Events.EVENT_LOCATION, newLocation);
- long excepEventId = createAndVerifyException(account, eventId, excepValues, true);
- instances.close();
-
- // Check results.
- assertEquals("full update does not create new ID", eventId, excepEventId);
-
- instances = getInstances(timeZone, testStart, testEnd, projection);
- assertEquals("post-update instance count", 3, instances.getCount());
- while (instances.moveToNext()) {
- assertEquals("new location", newLocation, instances.getString(1));
- }
- instances.close();
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- @MediumTest
- public void testMultiRuleRecurrence() {
- String account = "multirule_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create recurring event
- String rrule = "FREQ=DAILY;WKST=MO;COUNT=5\nFREQ=WEEKLY;WKST=SU;COUNT=5";
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, true, "1997-08-29T02:14:00", "PT1H", rrule);
- long eventId = createAndVerifyEvent(account, seed++, calendarId, true, eventValues);
-
- // TODO: once multi-rule RRULEs are fully supported, verify that they work
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Issue bad requests and expect them to get rejected.
- */
- @MediumTest
- public void testBadRequests() {
- String account = "neg_account";
- int seed = 0;
-
- // Clean up just in case
- CalendarHelper.deleteCalendarByAccount(mContentResolver, account);
-
- // Create calendar
- long calendarId = createAndVerifyCalendar(account, seed++, null);
-
- // Create recurring event
- String rrule = "FREQ=OFTEN;WKST=MO";
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed++,
- calendarId, true, "1997-08-29T02:14:00", "PT1H", rrule);
- try {
- createAndVerifyEvent(account, seed++, calendarId, true, eventValues);
- fail("Bad recurrence rule should have been rejected");
- } catch (IllegalArgumentException iae) {
- // good
- }
-
- // delete the calendar
- removeAndVerifyCalendar(account, calendarId);
- }
-
- /**
- * Acquires the set of instances that appear between the specified start and end points.
- *
- * @param timeZone Time zone to use when parsing startWhen and endWhen
- * @param startWhen Start date/time, in RFC 3339 format
- * @param endWhen End date/time, in RFC 3339 format
- * @param projection Array of desired column names
- * @return Cursor with instances (caller should close when done)
- */
- private Cursor getInstances(String timeZone, String startWhen, String endWhen,
- String[] projection) {
- Time startTime = new Time(timeZone);
- startTime.parse3339(startWhen);
- long startMillis = startTime.toMillis(false);
-
- Time endTime = new Time(timeZone);
- endTime.parse3339(endWhen);
- long endMillis = endTime.toMillis(false);
-
- // We want a list of instances that occur between the specified dates. Use the
- // "instances/when" URI.
- Uri uri = Uri.withAppendedPath(CalendarContract.Instances.CONTENT_URI,
- startMillis + "/" + endMillis);
-
- Cursor instances = mContentResolver.query(uri, projection, null, null,
- projection[0] + " ASC");
-
- return instances;
- }
-
- /**
- * Acquires the set of instances that appear between the specified start and end points
- * that match the search terms.
- *
- * @param timeZone Time zone to use when parsing startWhen and endWhen
- * @param startWhen Start date/time, in RFC 3339 format
- * @param endWhen End date/time, in RFC 3339 format
- * @param search A collection of tokens to search for. The columns searched are
- * hard-coded in the provider (currently title, description, location, attendee
- * name, attendee email).
- * @param searchByDay If set, adjust start/end to calendar day boundaries.
- * @param projection Array of desired column names
- * @return Cursor with instances (caller should close when done)
- */
- private Cursor getInstancesSearch(String timeZone, String startWhen, String endWhen,
- String search, boolean searchByDay, String[] projection) {
- Time startTime = new Time(timeZone);
- startTime.parse3339(startWhen);
- long startMillis = startTime.toMillis(false);
-
- Time endTime = new Time(timeZone);
- endTime.parse3339(endWhen);
- long endMillis = endTime.toMillis(false);
-
- Uri uri;
- if (searchByDay) {
- // start/end are Julian day numbers rather than time in milliseconds
- int julianStart = Time.getJulianDay(startMillis, startTime.gmtoff);
- int julianEnd = Time.getJulianDay(endMillis, endTime.gmtoff);
- uri = Uri.withAppendedPath(CalendarContract.Instances.CONTENT_SEARCH_BY_DAY_URI,
- julianStart + "/" + julianEnd + "/" + search);
- } else {
- uri = Uri.withAppendedPath(CalendarContract.Instances.CONTENT_SEARCH_URI,
- startMillis + "/" + endMillis + "/" + search);
- }
-
- // We want a list of instances that occur between the specified dates and that match
- // the search terms.
-
- Cursor instances = mContentResolver.query(uri, projection, null, null,
- projection[0] + " ASC");
-
- return instances;
- }
-
- /** debug -- dump instances cursor */
- private static void dumpInstances(Cursor instances, String timeZone, String msg) {
- Log.d(TAG, "Instances (" + msg + ")");
-
- int posn = instances.getPosition();
- instances.moveToPosition(-1);
-
- //Log.d(TAG, "+++ instances has " + instances.getCount() + " rows, " +
- // instances.getColumnCount() + " columns");
- while (instances.moveToNext()) {
- long beginMil = instances.getLong(0);
- Time beginT = new Time(timeZone);
- beginT.set(beginMil);
- String logMsg = "--> begin=" + beginT.format3339(false) + " (" + beginMil + ")";
- for (int i = 2; i < instances.getColumnCount(); i++) {
- logMsg += " [" + instances.getString(i) + "]";
- }
- Log.d(TAG, logMsg);
- }
- instances.moveToPosition(posn);
- }
-
-
- /**
- * Counts the number of instances that appear between the specified start and end times.
- */
- private int getInstanceCount(String timeZone, String startWhen, String endWhen) {
- Cursor instances = getInstances(timeZone, startWhen, endWhen,
- new String[] { Instances._ID });
- int count = instances.getCount();
- instances.close();
- return count;
- }
-
- /**
- * Deletes an event as app and sync adapter which removes it from the db and
- * verifies after each.
- *
- * @param eventUri The uri for the event to delete
- * @param accountName TODO
- */
- private void removeAndVerifyEvent(Uri eventUri, ContentValues eventValues, String accountName) {
- // Delete event
- EventHelper.deleteEvent(mContentResolver, eventUri, eventValues);
- // Verify
- verifyEvent(eventValues, ContentUris.parseId(eventUri));
- // Delete as sync adapter
- assertEquals(1,
- EventHelper.deleteEventAsSyncAdapter(mContentResolver, eventUri, accountName));
- // Verify
- Cursor c = EventHelper.getEventByUri(mContentResolver, eventUri);
- assertEquals(0, c.getCount());
- c.close();
- }
-
- /**
- * Creates an event on the given calendar and verifies it.
- *
- * @param account
- * @param seed
- * @param calendarId
- * @param asSyncAdapter
- * @param values optional pre created set of values; will have several new entries added
- * @return the _id for the new event
- */
- private long createAndVerifyEvent(String account, int seed, long calendarId,
- boolean asSyncAdapter, ContentValues values) {
- // Create an event
- if (values == null) {
- values = EventHelper.getNewEventValues(account, seed, calendarId, asSyncAdapter);
- }
- Uri insertUri = Events.CONTENT_URI;
- if (asSyncAdapter) {
- insertUri = asSyncAdapter(insertUri, account, CTS_TEST_TYPE);
- }
- Uri uri = mContentResolver.insert(insertUri, values);
-
- // Verify
- EventHelper.addDefaultReadOnlyValues(values, account, asSyncAdapter);
- long eventId = ContentUris.parseId(uri);
- assertTrue(eventId >= 0);
-
- verifyEvent(values, eventId);
- return eventId;
- }
-
- /**
- * Updates an event, and verifies that the updates took.
- */
- private void updateAndVerifyEvent(String account, long calendarId, long eventId,
- boolean asSyncAdapter, ContentValues updateValues) {
- Uri uri = Uri.withAppendedPath(Events.CONTENT_URI, String.valueOf(eventId));
- if (asSyncAdapter) {
- uri = asSyncAdapter(uri, account, CTS_TEST_TYPE);
- }
- int count = mContentResolver.update(uri, updateValues, null, null);
-
- // Verify
- assertEquals(1, count);
- verifyEvent(updateValues, eventId);
- }
-
- /**
- * Creates an exception to a recurring event, and verifies it.
- * @param account The account to use.
- * @param originalEventId The ID of the original event.
- * @param values Values for the exception; must include originalInstanceTime.
- * @return The _id for the new event.
- */
- private long createAndVerifyException(String account, long originalEventId,
- ContentValues values, boolean asSyncAdapter) {
- // Create the exception
- Uri uri = Uri.withAppendedPath(Events.CONTENT_EXCEPTION_URI,
- String.valueOf(originalEventId));
- if (asSyncAdapter) {
- uri = asSyncAdapter(uri, account, CTS_TEST_TYPE);
- }
- Uri resultUri = mContentResolver.insert(uri, values);
- assertNotNull(resultUri);
- long eventId = ContentUris.parseId(resultUri);
- assertTrue(eventId >= 0);
- return eventId;
- }
-
- /**
- * Deletes an exception to a recurring event.
- * @param account The account to use.
- * @param eventId The ID of the original recurring event.
- * @param excepId The ID of the exception event.
- * @return The number of rows deleted.
- */
- private int deleteException(String account, long eventId, long excepId) {
- Uri uri = Uri.withAppendedPath(Events.CONTENT_EXCEPTION_URI,
- eventId + "/" + excepId);
- uri = asSyncAdapter(uri, account, CTS_TEST_TYPE);
- return mContentResolver.delete(uri, null, null);
- }
-
- /**
- * Add some sample attendees to an event.
- */
- private void addAttendees(String account, long eventId, int seed) {
- assertTrue(eventId >= 0);
- AttendeeHelper.addAttendee(mContentResolver, eventId,
- "Attender" + seed,
- CalendarHelper.generateCalendarOwnerEmail(account),
- Attendees.ATTENDEE_STATUS_ACCEPTED,
- Attendees.RELATIONSHIP_ORGANIZER,
- Attendees.TYPE_NONE);
- seed++;
-
- AttendeeHelper.addAttendee(mContentResolver, eventId,
- "Attender" + seed,
- "attender" + seed + "@example.com",
- Attendees.ATTENDEE_STATUS_TENTATIVE,
- Attendees.RELATIONSHIP_NONE,
- Attendees.TYPE_NONE);
- }
-
- /**
- * Add some sample reminders to an event.
- */
- private void addReminders(String account, long eventId, int seed) {
- ReminderHelper.addReminder(mContentResolver, eventId, seed * 5, Reminders.METHOD_ALERT);
- }
-
- /**
- * Creates and removes an event that covers a specific range of dates. Call this to
- * cause the provider to expand the CalendarMetaData min/max values to include the range.
- * Useful when you want to see the provider expand the instances as the events are added.
- */
- private void expandInstanceRange(String account, long calendarId, String testStart,
- String testEnd, String timeZone) {
- int seed = 0;
-
- // TODO: this should use an UNTIL rule based on testEnd, not a COUNT
- ContentValues eventValues = EventHelper.getNewRecurringEventValues(account, seed,
- calendarId, true, testStart, "PT1H", "FREQ=DAILY;WKST=SU;COUNT=100");
-
- /*
- * Some of the helper functions modify "eventValues", so we want to make sure we're
- * passing a copy of anything we want to re-use.
- */
- long eventId = createAndVerifyEvent(account, seed, calendarId, true,
- new ContentValues(eventValues));
- assertTrue(eventId >= 0);
-
- String[] projection = { Instances.BEGIN, Instances.START_MINUTE };
- Cursor instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "prep-create");
- }
- assertEquals("initial recurrence instance count", 3, instances.getCount());
- instances.close();
-
- Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
- removeAndVerifyEvent(eventUri, new ContentValues(eventValues), account);
-
- instances = getInstances(timeZone, testStart, testEnd, projection);
- if (DEBUG_RECURRENCE) {
- dumpInstances(instances, timeZone, "prep-clear");
- }
- assertEquals("initial recurrence instance count", 0, instances.getCount());
- instances.close();
-
- }
-
- /**
- * Inserts a new calendar with the given account and seed and verifies it.
- *
- * @param account The account to add the calendar to
- * @param seed A number to use to generate the values
- * @return the created calendar's id
- */
- private long createAndVerifyCalendar(String account, int seed, ContentValues values) {
- // Create a calendar
- if (values == null) {
- values = CalendarHelper.getNewCalendarValues(account, seed);
- }
- Uri syncUri = asSyncAdapter(Calendars.CONTENT_URI, account, CTS_TEST_TYPE);
- Uri uri = mContentResolver.insert(syncUri, values);
- long calendarId = ContentUris.parseId(uri);
- assertTrue(calendarId >= 0);
-
- verifyCalendar(account, values, calendarId);
- return calendarId;
- }
-
- /**
- * Deletes a given calendar and verifies no calendars remain on that
- * account.
- *
- * @param account
- * @param id
- */
- private void removeAndVerifyCalendar(String account, long id) {
- // TODO Add code to delete as app and sync adapter and test both
-
- // Delete
- assertEquals(1, CalendarHelper.deleteCalendarById(mContentResolver, id));
-
- // Verify
- Cursor c = CalendarHelper.getCalendarsByAccount(mContentResolver, account);
- assertEquals(0, c.getCount());
- c.close();
- }
-
- /**
- * Check all the fields of a calendar contained in values + id. This assumes
- * a single calendar has been created on the given account.
- *
- * @param account the account of the calendar
- * @param values the values to check against the db
- * @param id the _id of the calendar
- */
- private void verifyCalendar(String account, ContentValues values, long id) {
- // Verify
- Cursor c = CalendarHelper.getCalendarsByAccount(mContentResolver, account);
- assertEquals(1, c.getCount());
- assertTrue(c.moveToFirst());
- assertEquals(id, c.getLong(0));
- for (String key : values.keySet()) {
- int index = c.getColumnIndex(key);
- assertTrue("Key " + key + " not in projection", index >= 0);
- assertEquals(key, values.getAsString(key), c.getString(index));
- }
- c.close();
- }
-
- /**
- * Creates a new _sync_state entry and verifies the contents.
- */
- private long createAndVerifySyncState(String account, ContentValues values) {
- assertNotNull(values);
- Uri syncUri = asSyncAdapter(SyncState.CONTENT_URI, account, CTS_TEST_TYPE);
- Uri uri = mContentResolver.insert(syncUri, values);
- long syncStateId = ContentUris.parseId(uri);
- assertTrue(syncStateId >= 0);
-
- verifySyncState(account, values, syncStateId);
- return syncStateId;
-
- }
-
- /**
- * Removes the _sync_state entry with the specified id, then verifies that it's gone.
- */
- private void removeAndVerifySyncState(String account) {
- assertEquals(1, SyncStateHelper.deleteSyncStateByAccount(mContentResolver, account, true));
-
- // Verify
- Cursor c = SyncStateHelper.getSyncStateByAccount(mContentResolver, account);
- try {
- assertEquals(0, c.getCount());
- } finally {
- if (c != null) {
- c.close();
- }
- }
- }
-
- /**
- * Check all the fields of a _sync_state entry contained in values + id. This assumes
- * a single _sync_state has been created on the given account.
- */
- private void verifySyncState(String account, ContentValues values, long id) {
- // Verify
- Cursor c = SyncStateHelper.getSyncStateByAccount(mContentResolver, account);
- try {
- assertEquals(1, c.getCount());
- assertTrue(c.moveToFirst());
- assertEquals(id, c.getLong(0));
- for (String key : values.keySet()) {
- int index = c.getColumnIndex(key);
- if (key.equals(SyncState.DATA)) {
- // TODO: can't compare as string, so compare as byte[]
- } else {
- assertEquals(key, values.getAsString(key), c.getString(index));
- }
- }
- } finally {
- if (c != null) {
- c.close();
- }
- }
- }
-
-
- /**
- * Special version of the test runner that does some remote Emma coverage housekeeping.
- */
- public static class CalendarEmmaTestRunner extends InstrumentationCtsTestRunner {
- private static final Uri EMMA_CONTENT_URI =
- Uri.parse("content://" + CalendarContract.AUTHORITY + "/emma");
- private ContentResolver mContentResolver;
-
- @Override
- public void onStart() {
- mContentResolver = getTargetContext().getContentResolver();
-
- ContentValues values = new ContentValues();
- values.put("cmd", "start");
- mContentResolver.insert(EMMA_CONTENT_URI, values);
-
- super.onStart();
- }
-
- @Override
- public void finish(int resultCode, Bundle results) {
- ContentValues values = new ContentValues();
- values.put("cmd", "stop");
- values.put("outputFileName",
- Environment.getExternalStorageDirectory() + "/calendar-provider.ec");
- mContentResolver.insert(EMMA_CONTENT_URI, values);
- super.finish(resultCode, results);
- }
- }
-}
diff --git a/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java b/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java
index 68ed1b8..daec382 100644
--- a/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java
+++ b/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java
@@ -16,7 +16,10 @@
package android.provider.cts;
-import com.android.cts.stub.R;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
import android.content.ContentResolver;
import android.content.IContentProvider;
@@ -26,13 +29,11 @@ import android.provider.cts.ContactsContract_TestDataBuilder.TestData;
import android.provider.cts.ContactsContract_TestDataBuilder.TestRawContact;
import android.test.InstrumentationTestCase;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
+@TestTargetClass(Photo.class)
public class ContactsContract_PhotoTest extends InstrumentationTestCase {
private ContactsContract_TestDataBuilder mBuilder;
+ private static final byte[] TEST_PHOTO_DATA = "ABCDEFG".getBytes();
private static final byte[] EMPTY_TEST_PHOTO_DATA = "".getBytes();
@Override
@@ -50,44 +51,40 @@ public class ContactsContract_PhotoTest extends InstrumentationTestCase {
mBuilder.cleanup();
}
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "Tests INSERT operation for photo"
+ )
+ })
+
public void testAddPhoto() throws Exception {
TestRawContact rawContact = mBuilder.newRawContact().insert();
TestData photoData = rawContact.newDataRow(Photo.CONTENT_ITEM_TYPE)
- .with(Photo.PHOTO, getTestPhotoData())
+ .with(Photo.PHOTO, TEST_PHOTO_DATA)
.insert();
photoData.load();
photoData.assertColumn(Photo.RAW_CONTACT_ID, rawContact.getId());
- photoData.assertBlobColumnNotNull(Photo.PHOTO);
+ photoData.assertColumn(Photo.PHOTO, TEST_PHOTO_DATA);
}
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "Tests INSERT operation for empty photo"
+ )
+ })
+
public void testAddEmptyPhoto() throws Exception {
TestRawContact rawContact = mBuilder.newRawContact().insert();
TestData photoData = rawContact.newDataRow(Photo.CONTENT_ITEM_TYPE)
.with(Photo.PHOTO, EMPTY_TEST_PHOTO_DATA)
.insert();
- assertNotNull(photoData.load());
- }
- private byte[] getTestPhotoData() {
- InputStream input = getInstrumentation().getTargetContext().getResources()
- .openRawResource(R.drawable.testimage);
- return readInputStreamFully(input);
- }
-
- protected byte[] readInputStreamFully(InputStream is) {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- byte[] buffer = new byte[10000];
- int count;
- try {
- while ((count = is.read(buffer)) != -1) {
- os.write(buffer, 0, count);
- }
- is.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return os.toByteArray();
+ photoData.load();
+ photoData.assertColumn(Photo.RAW_CONTACT_ID, rawContact.getId());
+ photoData.assertColumn(Photo.PHOTO, EMPTY_TEST_PHOTO_DATA);
}
}
diff --git a/tests/tests/provider/src/android/provider/cts/ContactsContract_TestDataBuilder.java b/tests/tests/provider/src/android/provider/cts/ContactsContract_TestDataBuilder.java
index c73830e..0c04aa6 100644
--- a/tests/tests/provider/src/android/provider/cts/ContactsContract_TestDataBuilder.java
+++ b/tests/tests/provider/src/android/provider/cts/ContactsContract_TestDataBuilder.java
@@ -33,11 +33,12 @@ import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import java.util.Arrays;
+
import junit.framework.Assert;
import junit.framework.ComparisonFailure;
@@ -154,10 +155,9 @@ public class ContactsContract_TestDataBuilder {
mCursor = mProvider.query(getUri(), null, null, null, null);
if (mCursor == null || !mCursor.moveToFirst()) {
- return null;
- } else {
- return (T) this;
+ fail("No data rows for URI: " + getUri());
}
+ return (T)this;
}
@SuppressWarnings("unchecked")
@@ -210,14 +210,6 @@ public class ContactsContract_TestDataBuilder {
assertEquals(value, mCursor.getBlob(getColumnIndex(columnName)));
}
- public void assertBlobColumnNotNull(String columnName) {
- assertNotNull(mCursor.getBlob(getColumnIndex(columnName)));
- }
-
- public void assertBlobColumnNull(String columnName) {
- assertNull(mCursor.getBlob(getColumnIndex(columnName)));
- }
-
public void assertEquals(byte[] expected, byte[] actual) {
assertEquals(null, expected, actual);
}
diff --git a/tests/tests/provider/src/android/provider/cts/ContactsTest.java b/tests/tests/provider/src/android/provider/cts/ContactsTest.java
index 1c74b7f..fa1e431 100644
--- a/tests/tests/provider/src/android/provider/cts/ContactsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/ContactsTest.java
@@ -820,20 +820,10 @@ public class ContactsTest extends InstrumentationTestCase {
GroupMembership.CONTENT_URI, GROUP_MEMBERSHIP_PROJECTION,
GroupMembership.PERSON_ID + " = " + peopleId,
null, null);
-
- // 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);
+ assertTrue(cursor.moveToNext());
+ assertEquals(peopleId, cursor.getInt(PERSON_ID_INDEX));
+ assertEquals(groupId1, cursor.getInt(GROUP_ID_INDEX));
+ int id = cursor.getInt(ID_INDEX);
cursor.close();
// Test: update
diff --git a/tests/tests/provider/src/android/provider/cts/Contacts_PeopleTest.java b/tests/tests/provider/src/android/provider/cts/Contacts_PeopleTest.java
index 0f36626..d8d6baa 100644
--- a/tests/tests/provider/src/android/provider/cts/Contacts_PeopleTest.java
+++ b/tests/tests/provider/src/android/provider/cts/Contacts_PeopleTest.java
@@ -308,8 +308,8 @@ public class Contacts_PeopleTest extends InstrumentationTestCase {
mContentResolver, mPeopleRowsAdded.get(0));
assertNotNull(photoStream);
Bitmap bitmap = BitmapFactory.decodeStream(photoStream, null, null);
- assertEquals(96, bitmap.getWidth());
- assertEquals(64, bitmap.getHeight());
+ assertEquals(212, bitmap.getWidth());
+ assertEquals(142, bitmap.getHeight());
photoStream = People.openContactPhotoInputStream(mContentResolver,
mPeopleRowsAdded.get(1));
@@ -317,8 +317,8 @@ public class Contacts_PeopleTest extends InstrumentationTestCase {
bitmap = People.loadContactPhoto(context, mPeopleRowsAdded.get(0),
com.android.cts.stub.R.drawable.size_48x48, null);
- assertEquals(96, bitmap.getWidth());
- assertEquals(64, bitmap.getHeight());
+ assertEquals(212, bitmap.getWidth());
+ assertEquals(142, bitmap.getHeight());
bitmap = People.loadContactPhoto(context, null,
com.android.cts.stub.R.drawable.size_48x48, null);
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java
index 00bb47d..98792e7 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java
@@ -96,8 +96,7 @@ public class MediaStore_Audio_AlbumsTest extends InstrumentationTestCase {
null);
assertEquals(1, c.getCount());
c.moveToFirst();
- long id = c.getLong(c.getColumnIndex(Albums._ID));
- assertTrue(id > 0);
+ assertTrue(c.getLong(c.getColumnIndex(Albums._ID)) > 0);
assertEquals(Audio1.ALBUM, c.getString(c.getColumnIndex(Albums.ALBUM)));
assertNull(c.getString(c.getColumnIndex(Albums.ALBUM_ART)));
assertNotNull(c.getString(c.getColumnIndex(Albums.ALBUM_KEY)));
@@ -141,20 +140,6 @@ public class MediaStore_Audio_AlbumsTest extends InstrumentationTestCase {
// expected
}
- // test filtering
- Uri filterUri = audioAlbumsUri.buildUpon()
- .appendQueryParameter("filter", Audio1.ARTIST).build();
- c = mContentResolver.query(filterUri, null, null, null, null);
- assertEquals(1, c.getCount());
- c.moveToFirst();
- long fid = c.getLong(c.getColumnIndex(Albums._ID));
- assertTrue(id == fid);
- c.close();
-
- filterUri = audioAlbumsUri.buildUpon().appendQueryParameter("filter", "xyzfoo").build();
- c = mContentResolver.query(filterUri, null, null, null, null);
- assertEquals(0, c.getCount());
- c.close();
} finally {
mContentResolver.delete(audioMediaUri, null, null);
}
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_ArtistsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_ArtistsTest.java
index a7ef2d1..917aa3d 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_ArtistsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_ArtistsTest.java
@@ -91,8 +91,7 @@ public class MediaStore_Audio_ArtistsTest extends InstrumentationTestCase {
c.moveToFirst();
assertEquals(Audio1.ARTIST, c.getString(c.getColumnIndex(Artists.ARTIST)));
- long id = c.getLong(c.getColumnIndex(Artists._ID));
- assertTrue(id > 0);
+ assertTrue(c.getLong(c.getColumnIndex(Artists._ID)) > 0);
assertNotNull(c.getString(c.getColumnIndex(Artists.ARTIST_KEY)));
assertEquals(1, c.getInt(c.getColumnIndex(Artists.NUMBER_OF_ALBUMS)));
assertEquals(1, c.getInt(c.getColumnIndex(Artists.NUMBER_OF_TRACKS)));
@@ -115,21 +114,6 @@ public class MediaStore_Audio_ArtistsTest extends InstrumentationTestCase {
} catch (UnsupportedOperationException e) {
// expected
}
-
- // test filtering
- Uri filterUri = artistsUri.buildUpon()
- .appendQueryParameter("filter", Audio1.ARTIST).build();
- c = mContentResolver.query(filterUri, null, null, null, null);
- assertEquals(1, c.getCount());
- c.moveToFirst();
- long fid = c.getLong(c.getColumnIndex(Artists._ID));
- assertTrue(id == fid);
- c.close();
-
- filterUri = artistsUri.buildUpon().appendQueryParameter("filter", "xyzfoo").build();
- c = mContentResolver.query(filterUri, null, null, null, null);
- assertEquals(0, c.getCount());
- c.close();
} finally {
mContentResolver.delete(uri, null, null);
}
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Genres_MembersTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Genres_MembersTest.java
index aa364b4..66ac599 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Genres_MembersTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Genres_MembersTest.java
@@ -95,6 +95,8 @@ public class MediaStore_Audio_Genres_MembersTest extends InstrumentationTestCase
null));
}
+ @ToBeFixed(bug = "", explanation = "The result cursor of query for all columns does not "
+ + "contain the column Members.ALBUM_ART, Members.GENRE_ID and Members.AUDIO_ID.")
public void testStoreAudioGenresMembersExternal() {
ContentValues values = new ContentValues();
values.put(Genres.NAME, Audio1.GENRE);
@@ -103,12 +105,8 @@ public class MediaStore_Audio_Genres_MembersTest extends InstrumentationTestCase
c.moveToFirst();
long genreId = c.getLong(c.getColumnIndex(Genres._ID));
- long genre2Id = -1; // used later
c.close();
- // verify that the Uri has the correct format and genre value
- assertEquals(uri.toString(), "content://media/external/audio/genres/" + genreId);
-
// insert audio as the member of the genre
values.clear();
values.put(Members.AUDIO_ID, mAudioIdOfJam);
@@ -117,15 +115,36 @@ public class MediaStore_Audio_Genres_MembersTest extends InstrumentationTestCase
assertNotNull(mContentResolver.insert(membersUri, values));
try {
- // query, slow path
+ // query
c = mContentResolver.query(membersUri, null, null, null, null);
+ // the ALBUM_ART column does not exist
+ try {
+ c.getColumnIndexOrThrow(Members.ALBUM_ART);
+ fail("Should throw IllegalArgumentException because there is no column with name"
+ + " \"Members.ALBUM_ART\" in the table");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ c.getColumnIndexOrThrow(Members.AUDIO_ID);
+ fail("Should throw IllegalArgumentException because there is no column with name"
+ + " \"Members.AUDIO_ID\" in the table");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ c.getColumnIndexOrThrow(Members.GENRE_ID);
+ fail("Should throw IllegalArgumentException because there is no column with name"
+ + " \"Members.GENRE_ID\" in the table");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
assertEquals(1, c.getCount());
c.moveToFirst();
-
- assertEquals(mAudioIdOfJam, c.getLong(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(genreId, c.getLong(c.getColumnIndex(Members.GENRE_ID)));
- assertEquals(mAudioIdOfJam, c.getLong(c.getColumnIndex(Members._ID)));
+ assertTrue(c.getLong(c.getColumnIndex(Members._ID)) > 0);
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)));
@@ -134,7 +153,6 @@ public class MediaStore_Audio_Genres_MembersTest extends InstrumentationTestCase
assertEquals(Audio1.SIZE, c.getInt(c.getColumnIndex(Members.SIZE)));
assertEquals(Audio1.TITLE, c.getString(c.getColumnIndex(Members.TITLE)));
assertEquals(Audio1.ALBUM, c.getString(c.getColumnIndex(Members.ALBUM)));
- assertEquals(Audio1.IS_DRM, c.getInt(c.getColumnIndex(Members.IS_DRM)));
String albumKey = c.getString(c.getColumnIndex(Members.ALBUM_KEY));
assertNotNull(albumKey);
long albumId = c.getLong(c.getColumnIndex(Members.ALBUM_ID));
@@ -157,89 +175,6 @@ public class MediaStore_Audio_Genres_MembersTest extends InstrumentationTestCase
assertNotNull(titleKey);
c.close();
- // query again, fast path
- c = mContentResolver.query(membersUri,
- new String[] { Members.AUDIO_ID, Members.GENRE_ID},
- null, null, null);
- assertEquals(1, c.getCount());
- c.moveToFirst();
- assertEquals(mAudioIdOfJam, c.getLong(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(genreId, c.getLong(c.getColumnIndex(Members.GENRE_ID)));
- c.close();
-
- // Query with a constraint on _id. Note that _id corresponds to the _id
- // column in the audio table, not the one in the audio_genres_map table.
- // We need to preserve this behavior for backward compatibility.
- c = mContentResolver.query(membersUri, null,
- Members._ID + "=?", new String[] {Long.toString(mAudioIdOfJam)}, null);
- assertEquals(1, c.getCount());
- c.moveToFirst();
- assertEquals(mAudioIdOfJam, c.getLong(c.getColumnIndex(Members._ID)));
- c.close();
-
- // Query members across all genres
- Uri allMembersUri = Uri.parse("content://media/external/audio/genres/all/members");
- c = mContentResolver.query(allMembersUri, null, null, null, null);
- int colidx = c.getColumnIndex(Members.AUDIO_ID);
- int jamcnt = 0;
- // The song should appear only once, for the genre we used when inserting it
- while(c.moveToNext()) {
- if (c.getLong(colidx) == mAudioIdOfJam) {
- jamcnt++;
- assertEquals(genreId, c.getLong(c.getColumnIndex(Members.GENRE_ID)));
- }
- }
- assertEquals(1, jamcnt);
- c.close();
-
- // Query the same Uri, but add a where clause to restrict it to the one entry we added
- c = mContentResolver.query(allMembersUri, null,
- Members.AUDIO_ID + "=?", new String[] {Long.toString(mAudioIdOfJam)}, null);
- assertEquals(1, c.getCount());
- c.moveToFirst();
- assertEquals(genreId, c.getLong(c.getColumnIndex(Members.GENRE_ID)));
- assertEquals(mAudioIdOfJam, c.getLong(c.getColumnIndex(Members.AUDIO_ID)));
- c.close();
-
- // create another genre
- values.clear();
- values.put(Genres.NAME, Audio1.GENRE + "-2");
- uri = mContentResolver.insert(Genres.EXTERNAL_CONTENT_URI, values);
- c = mContentResolver.query(uri, null, null, null, null);
- c.moveToFirst();
- genre2Id = c.getLong(c.getColumnIndex(Genres._ID));
- c.close();
-
- // insert the song into the second genre
- values.clear();
- values.put(Members.AUDIO_ID, mAudioIdOfJam);
- Uri members2Uri = Members.getContentUri(MediaStoreAudioTestHelper.EXTERNAL_VOLUME_NAME,
- genre2Id);
- assertNotNull(mContentResolver.insert(members2Uri, values));
-
- // Query members across all genres again
- c = mContentResolver.query(allMembersUri, null, null, null, null);
- colidx = c.getColumnIndex(Members.AUDIO_ID);
- int jamcnt1 = 0;
- int jamcnt2 = 0;
- // This time the song should appear twice, once for each genre
- while(c.moveToNext()) {
- if (c.getLong(colidx) == mAudioIdOfJam) {
- long g = c.getLong(c.getColumnIndex(Members.GENRE_ID));
- if (g == genreId) {
- jamcnt1++;
- } else if (g == genre2Id) {
- jamcnt2++;
- } else {
- fail("wrong genre found");
- }
- }
- }
- assertEquals(1, jamcnt1);
- assertEquals(1, jamcnt2);
- c.close();
-
-
// update the member
values.clear();
values.put(Members.AUDIO_ID, mAudioIdOfJamLive);
@@ -251,20 +186,17 @@ public class MediaStore_Audio_Genres_MembersTest extends InstrumentationTestCase
// expected
}
- // Delete the members, note that this does not delete the genre itself
- assertEquals(1, mContentResolver.delete(membersUri, null, null)); // check number of rows deleted
-
- // verify the genre is now empty
- c = mContentResolver.query(membersUri, null, null, null, null);
- assertEquals(0, c.getCount());
- c.close();
-
+ // delete the member
+ try {
+ mContentResolver.delete(membersUri, null, null);
+ fail("Should throw SQLException because there is no column with name "
+ + "\"Members.GENRE_ID\" in the table");
+ } catch (SQLException e) {
+ // expected
+ }
} finally {
// the members are deleted when deleting the genre which they belong to
mContentResolver.delete(Genres.EXTERNAL_CONTENT_URI, Genres._ID + "=" + genreId, null);
- if (genre2Id >= 0) {
- mContentResolver.delete(Genres.EXTERNAL_CONTENT_URI, Genres._ID + "=" + genre2Id, null);
- }
c = mContentResolver.query(membersUri, null, null, null, null);
assertEquals(0, c.getCount());
c.close();
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_MediaTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_MediaTest.java
index a964f64..29b270e 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_MediaTest.java
@@ -76,10 +76,12 @@ public class MediaStore_Audio_MediaTest extends InstrumentationTestCase {
null, null));
}
+ @ToBeFixed(bug = "", explanation = "The column Media.ALBUM_ART does not exist.")
public void testStoreAudioMediaInternal() {
testStoreAudioMedia(true);
}
+ @ToBeFixed(bug = "", explanation = "The column Media.ALBUM_ART does not exist.")
public void testStoreAudioMediaExternal() {
testStoreAudioMedia(false);
}
@@ -100,13 +102,11 @@ public class MediaStore_Audio_MediaTest extends InstrumentationTestCase {
Cursor c = mContentResolver.query(uri, null, null, null, null);
assertEquals(1, c.getCount());
c.moveToFirst();
- long id = c.getLong(c.getColumnIndex(Media._ID));
- assertTrue(id > 0);
+ assertTrue(c.getLong(c.getColumnIndex(Media._ID)) > 0);
String expected = isInternal ? Audio1.INTERNAL_DATA : Audio1.EXTERNAL_DATA;
assertEquals(expected, c.getString(c.getColumnIndex(Media.DATA)));
assertTrue(c.getLong(c.getColumnIndex(Media.DATE_ADDED)) > 0);
assertEquals(Audio1.DATE_MODIFIED, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
- assertEquals(Audio1.IS_DRM, c.getInt(c.getColumnIndex(Media.IS_DRM)));
assertEquals(Audio1.FILE_NAME, c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
assertEquals(Audio1.MIME_TYPE, c.getString(c.getColumnIndex(Media.MIME_TYPE)));
assertEquals(Audio1.SIZE, c.getInt(c.getColumnIndex(Media.SIZE)));
@@ -131,6 +131,14 @@ public class MediaStore_Audio_MediaTest extends InstrumentationTestCase {
assertEquals(Audio1.YEAR, c.getInt(c.getColumnIndex(Media.YEAR)));
String titleKey = c.getString(c.getColumnIndex(Media.TITLE_KEY));
assertNotNull(titleKey);
+ // the ALBUM_ART column does not exist
+ try {
+ c.getColumnIndexOrThrow(Media.ALBUM_ART);
+ fail("Should throw IllegalArgumentException because there is no column with name"
+ + " \"Media.ALBUM_ART\" in the table");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
c.close();
// update
@@ -143,12 +151,9 @@ public class MediaStore_Audio_MediaTest extends InstrumentationTestCase {
c = mContentResolver.query(uri, null, null, null, null);
assertEquals(1, c.getCount());
c.moveToFirst();
- long id2 = c.getLong(c.getColumnIndex(Media._ID));
- assertTrue(id == id2);
expected = isInternal ? Audio2.INTERNAL_DATA : Audio2.EXTERNAL_DATA;
assertEquals(expected, c.getString(c.getColumnIndex(Media.DATA)));
assertEquals(Audio2.DATE_MODIFIED, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
- assertEquals(Audio2.IS_DRM, c.getInt(c.getColumnIndex(Media.IS_DRM)));
assertEquals(Audio2.DISPLAY_NAME, c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
assertEquals(Audio2.MIME_TYPE, c.getString(c.getColumnIndex(Media.MIME_TYPE)));
assertEquals(Audio2.SIZE, c.getInt(c.getColumnIndex(Media.SIZE)));
@@ -170,22 +175,6 @@ public class MediaStore_Audio_MediaTest extends InstrumentationTestCase {
assertEquals(Audio2.YEAR, c.getInt(c.getColumnIndex(Media.YEAR)));
assertTrue(titleKey.equals(c.getString(c.getColumnIndex(Media.TITLE_KEY))));
c.close();
-
- // test filtering
- Uri baseUri = isInternal ? Media.INTERNAL_CONTENT_URI : Media.EXTERNAL_CONTENT_URI;
- Uri filterUri = baseUri.buildUpon()
- .appendQueryParameter("filter", Audio2.ARTIST).build();
- c = mContentResolver.query(filterUri, null, null, null, null);
- assertEquals(1, c.getCount());
- c.moveToFirst();
- long fid = c.getLong(c.getColumnIndex(Media._ID));
- assertTrue(id == fid);
- c.close();
-
- filterUri = baseUri.buildUpon().appendQueryParameter("filter", "xyzfoo").build();
- c = mContentResolver.query(filterUri, null, null, null, null);
- assertEquals(0, c.getCount());
- c.close();
} finally {
// delete
int result = mContentResolver.delete(uri, null, null);
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 48ae5d7..e50abf4 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,8 +30,6 @@ import android.os.Environment;
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;
@@ -76,8 +74,9 @@ public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
ContentValues values = new ContentValues();
values.put(Playlists.NAME, "My favourites");
values.put(Playlists.DATA, externalPlaylistPath);
- long dateAdded = System.currentTimeMillis() / 1000;
- long dateModified = System.currentTimeMillis() / 1000;
+ long dateAdded = System.currentTimeMillis();
+ values.put(Playlists.DATE_ADDED, dateAdded);
+ long dateModified = System.currentTimeMillis();
values.put(Playlists.DATE_MODIFIED, dateModified);
// insert
Uri uri = mContentResolver.insert(Playlists.EXTERNAL_CONTENT_URI, values);
@@ -92,8 +91,7 @@ public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
assertEquals(externalPlaylistPath,
c.getString(c.getColumnIndex(Playlists.DATA)));
- long realDateAdded = c.getLong(c.getColumnIndex(Playlists.DATE_ADDED));
- assertTrue(realDateAdded >= dateAdded);
+ assertEquals(dateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
assertEquals(dateModified, c.getLong(c.getColumnIndex(Playlists.DATE_MODIFIED)));
assertTrue(c.getLong(c.getColumnIndex(Playlists._ID)) > 0);
c.close();
@@ -110,7 +108,7 @@ public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
assertEquals(externalPlaylistPath,
c.getString(c.getColumnIndex(Playlists.DATA)));
- assertEquals(realDateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
+ assertEquals(dateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
assertEquals(dateModified, c.getLong(c.getColumnIndex(Playlists.DATE_MODIFIED)));
c.close();
} finally {
@@ -119,6 +117,7 @@ public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
}
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");
@@ -127,8 +126,6 @@ public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
long dateModified = System.currentTimeMillis();
values.put(Playlists.DATE_MODIFIED, dateModified);
Uri uri = mContentResolver.insert(Playlists.INTERNAL_CONTENT_URI, values);
- assertNotNull(uri);
- assertTrue(Pattern.matches("content://media/internal/audio/playlists/\\d+",
- uri.toString()));
+ assertNull(uri);
}
}
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 62aa208..12d080e 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
@@ -24,7 +24,6 @@ import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
-import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Audio.Playlists;
import android.provider.MediaStore.Audio.Playlists.Members;
@@ -32,8 +31,6 @@ import android.provider.cts.MediaStoreAudioTestHelper.Audio1;
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 = {
@@ -51,7 +48,6 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
Members.DISPLAY_NAME,
Members.DURATION,
Members.IS_ALARM,
- Members.IS_DRM,
Members.IS_MUSIC,
Members.IS_NOTIFICATION,
Members.IS_RINGTONE,
@@ -81,7 +77,6 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
Members.DISPLAY_NAME,
Members.DURATION,
Members.IS_ALARM,
- Members.IS_DRM,
Members.IS_MUSIC,
Members.IS_NOTIFICATION,
Members.IS_RINGTONE,
@@ -150,10 +145,6 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
Cursor c = mContentResolver.query(uri, null, null, null, null);
c.moveToFirst();
long playlistId = c.getLong(c.getColumnIndex(Playlists._ID));
- long playlist2Id = -1; // used later
-
- // verify that the Uri has the correct format and playlist value
- assertEquals(uri.toString(), "content://media/external/audio/playlists/" + playlistId);
// insert audio as the member of the playlist
values.clear();
@@ -162,9 +153,8 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
Uri membersUri = Members.getContentUri(MediaStoreAudioTestHelper.EXTERNAL_VOLUME_NAME,
playlistId);
Uri audioUri = mContentResolver.insert(membersUri, values);
-
assertNotNull(audioUri);
- assertTrue(audioUri.toString().startsWith(membersUri.toString()));
+ assertEquals(Uri.withAppendedPath(membersUri, Long.toString(mIdOfAudio1)), audioUri);
try {
// query the audio info
@@ -172,11 +162,10 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
assertEquals(1, c.getCount());
c.moveToFirst();
long memberId = c.getLong(c.getColumnIndex(Members._ID));
- assertEquals(memberId, Long.parseLong(audioUri.getPathSegments().get(5)));
+ assertTrue(memberId > 0);
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)));
- assertEquals(Audio1.IS_DRM, c.getInt(c.getColumnIndex(Members.IS_DRM)));
assertEquals(Audio1.FILE_NAME, c.getString(c.getColumnIndex(Members.DISPLAY_NAME)));
assertEquals(Audio1.MIME_TYPE, c.getString(c.getColumnIndex(Members.MIME_TYPE)));
assertEquals(Audio1.SIZE, c.getInt(c.getColumnIndex(Members.SIZE)));
@@ -225,7 +214,6 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
assertEquals(Audio2.EXTERNAL_DATA, c.getString(c.getColumnIndex(Members.DATA)));
assertTrue(c.getLong(c.getColumnIndex(Members.DATE_ADDED)) > 0);
assertEquals(Audio2.DATE_MODIFIED, c.getLong(c.getColumnIndex(Members.DATE_MODIFIED)));
- assertEquals(Audio2.IS_DRM, c.getInt(c.getColumnIndex(Members.IS_DRM)));
assertEquals(Audio2.FILE_NAME, c.getString(c.getColumnIndex(Members.DISPLAY_NAME)));
assertEquals(Audio2.MIME_TYPE, c.getString(c.getColumnIndex(Members.MIME_TYPE)));
assertEquals(Audio2.SIZE, c.getInt(c.getColumnIndex(Members.SIZE)));
@@ -248,121 +236,18 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
assertNotNull(c.getString(c.getColumnIndex(Members.TITLE_KEY)));
c.close();
- // update the member back to its original state
- values.clear();
- values.put(Members.PLAY_ORDER, 1);
- values.put(Members.AUDIO_ID, mIdOfAudio1);
- result = mContentResolver.update(membersUri, values, Members.AUDIO_ID + "="
- + mIdOfAudio2, null);
- assertEquals(1, result);
-
- // insert another member into the playlist
- values.clear();
- values.put(Members.AUDIO_ID, mIdOfAudio2);
- values.put(Members.PLAY_ORDER, 2);
- Uri audioUri2 = mContentResolver.insert(membersUri, values);
- // the playlist should now have id1 at position 1 and id2 at position2, check that
- c = mContentResolver.query(membersUri, new String[] { Members.AUDIO_ID, Members.PLAY_ORDER }, null, null, Members.PLAY_ORDER);
- assertEquals(2, c.getCount());
- c.moveToFirst();
- assertEquals(mIdOfAudio1, c.getInt(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(1, c.getInt(c.getColumnIndex(Members.PLAY_ORDER)));
- c.moveToNext();
- assertEquals(mIdOfAudio2, c.getInt(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(2, c.getInt(c.getColumnIndex(Members.PLAY_ORDER)));
- c.close();
-
- // swap the items around
- assertTrue(MediaStore.Audio.Playlists.Members.moveItem(mContentResolver, playlistId, 2, 1));
-
- // check the new positions
- c = mContentResolver.query(membersUri, new String[] { Members.AUDIO_ID, Members.PLAY_ORDER }, null, null, Members.PLAY_ORDER);
- assertEquals(2, c.getCount());
- c.moveToFirst();
- assertEquals(mIdOfAudio2, c.getInt(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(1, c.getInt(c.getColumnIndex(Members.PLAY_ORDER)));
- c.moveToNext();
- assertEquals(mIdOfAudio1, c.getInt(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(2, c.getInt(c.getColumnIndex(Members.PLAY_ORDER)));
- c.close();
-
- // swap the items around in the other direction
- assertTrue(MediaStore.Audio.Playlists.Members.moveItem(mContentResolver, playlistId, 1, 2));
-
- // check the positions again
- c = mContentResolver.query(membersUri, new String[] { Members.AUDIO_ID, Members.PLAY_ORDER }, null, null, Members.PLAY_ORDER);
- assertEquals(2, c.getCount());
- c.moveToFirst();
- assertEquals(mIdOfAudio1, c.getLong(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(1, c.getInt(c.getColumnIndex(Members.PLAY_ORDER)));
- c.moveToNext();
- assertEquals(mIdOfAudio2, c.getLong(c.getColumnIndex(Members.AUDIO_ID)));
- assertEquals(2, c.getInt(c.getColumnIndex(Members.PLAY_ORDER)));
- c.close();
-
- // create another playlist
- values.clear();
- values.put(Playlists.NAME, "My favourites 2");
- values.put(Playlists.DATA, "");
- values.put(Playlists.DATE_ADDED, dateAdded);
- values.put(Playlists.DATE_MODIFIED, dateModified);
- // insert
- uri = mContentResolver.insert(Playlists.EXTERNAL_CONTENT_URI, values);
- assertNotNull(uri);
- c = mContentResolver.query(uri, null, null, null, null);
- c.moveToFirst();
- playlist2Id = c.getLong(c.getColumnIndex(Playlists._ID));
- c.close();
-
- // insert audio into 2nd playlist
- values.clear();
- values.put(Members.AUDIO_ID, mIdOfAudio1);
- values.put(Members.PLAY_ORDER, 1);
- Uri members2Uri = Members.getContentUri(MediaStoreAudioTestHelper.EXTERNAL_VOLUME_NAME,
- playlist2Id);
- Uri audio2Uri = mContentResolver.insert(members2Uri, values);
-
- // check that the audio exists in both playlist
- c = mContentResolver.query(membersUri, null, null, null, null);
- assertEquals(2, c.getCount());
- int cnt = 0;
- int colidx = c.getColumnIndex(Members.AUDIO_ID);
- assertTrue(colidx >= 0);
- while(c.moveToNext()) {
- if (c.getLong(colidx) == mIdOfAudio1) {
- cnt++;
- }
- }
- assertEquals(1, cnt);
- c.close();
- c = mContentResolver.query(members2Uri, null, null, null, null);
- assertEquals(1, c.getCount());
- cnt = 0;
- while(c.moveToNext()) {
- if (c.getLong(colidx) == mIdOfAudio1) {
- cnt++;
- }
- }
- assertEquals(1, cnt);
- c.close();
-
- // delete the members
+ // delete the member
result = mContentResolver.delete(membersUri, null, null);
- assertEquals(2, result);
- result = mContentResolver.delete(members2Uri, null, null);
assertEquals(1, result);
} finally {
- // delete the playlists
+ // delete the playlist
mContentResolver.delete(Playlists.EXTERNAL_CONTENT_URI,
Playlists._ID + "=" + playlistId, null);
- if (playlist2Id >= 0) {
- mContentResolver.delete(Playlists.EXTERNAL_CONTENT_URI,
- Playlists._ID + "=" + playlist2Id, null);
- }
}
}
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");
@@ -371,8 +256,6 @@ public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestC
long dateModified = System.currentTimeMillis();
values.put(Playlists.DATE_MODIFIED, dateModified);
Uri uri = mContentResolver.insert(Playlists.INTERNAL_CONTENT_URI, values);
- assertNotNull(uri);
- assertTrue(Pattern.matches("content://media/internal/audio/playlists/\\d+",
- uri.toString()));
+ assertNull(uri);
}
}
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 8e8d650..2de72c8 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;
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,15 +247,11 @@ public class MediaStore_Images_MediaTest extends InstrumentationTestCase {
assertNull(mContentResolver.query(Media.getContentUri(volume), null, null, null, null));
}
- public void testStoreImagesMediaExternal() throws Exception {
+ public void testStoreImagesMediaExternal() {
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);
@@ -269,11 +265,11 @@ public class MediaStore_Images_MediaTest extends InstrumentationTestCase {
values.put(Media.DATA, externalPath);
values.put(Media.DISPLAY_NAME, "testimage");
values.put(Media.MIME_TYPE, "image/jpeg");
- values.put(Media.SIZE, numBytes);
+ values.put(Media.SIZE, 86853);
values.put(Media.TITLE, "testimage");
- long dateAdded = System.currentTimeMillis() / 1000;
+ long dateAdded = System.currentTimeMillis();
values.put(Media.DATE_ADDED, dateAdded);
- long dateModified = System.currentTimeMillis() / 1000;
+ long dateModified = System.currentTimeMillis();
values.put(Media.DATE_MODIFIED, dateModified);
// insert
@@ -300,9 +296,9 @@ public class MediaStore_Images_MediaTest extends InstrumentationTestCase {
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(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
+ assertEquals(86853, c.getInt(c.getColumnIndex(Media.SIZE)));
long realDateAdded = c.getLong(c.getColumnIndex(Media.DATE_ADDED));
- assertTrue(realDateAdded >= dateAdded);
+ assertTrue(realDateAdded > 0);
assertEquals(dateModified, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
c.close();
@@ -322,7 +318,7 @@ public class MediaStore_Images_MediaTest extends InstrumentationTestCase {
values.put(Media.MIME_TYPE, "image/jpeg");
values.put(Media.SIZE, 86854);
values.put(Media.TITLE, "testimage1");
- dateModified = System.currentTimeMillis() / 1000;
+ dateModified = System.currentTimeMillis();
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 6f7842c..9a720e5 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,8 +29,6 @@ import android.provider.MediaStore;
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;
@@ -58,15 +56,11 @@ public class MediaStore_Video_MediaTest extends InstrumentationTestCase {
assertNull(mContentResolver.query(Media.getContentUri(volume), null, null, null, null));
}
- public void testStoreVideoMediaExternal() throws Exception {
+ public void testStoreVideoMediaExternal() {
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");
@@ -85,11 +79,11 @@ public class MediaStore_Video_MediaTest extends InstrumentationTestCase {
values.put(Media.DATA, externalVideoPath);
values.put(Media.DISPLAY_NAME, "testvideo");
values.put(Media.MIME_TYPE, "video/3gpp");
- values.put(Media.SIZE, numBytes);
+ values.put(Media.SIZE, 86853);
values.put(Media.TITLE, "testvideo");
- long dateAdded = System.currentTimeMillis() / 1000;
+ long dateAdded = System.currentTimeMillis();
values.put(Media.DATE_ADDED, dateAdded);
- long dateModified = System.currentTimeMillis() / 1000;
+ long dateModified = System.currentTimeMillis();
values.put(Media.DATE_MODIFIED, dateModified);
// insert
@@ -121,9 +115,9 @@ public class MediaStore_Video_MediaTest extends InstrumentationTestCase {
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(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
+ assertEquals(86853, c.getInt(c.getColumnIndex(Media.SIZE)));
long realDateAdded = c.getLong(c.getColumnIndex(Media.DATE_ADDED));
- assertTrue(realDateAdded >= dateAdded);
+ assertTrue(realDateAdded > 0);
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
deleted file mode 100644
index 1395de1..0000000
--- a/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java
+++ /dev/null
@@ -1,244 +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.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 {
- 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 13a32d6..718b9d2 100644
--- a/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
+++ b/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
@@ -117,10 +117,11 @@ public class Settings_SecureTest extends AndroidTestCase {
} catch (SecurityException expected) {
}
+ // TODO: Should be fixed to throw SettingNotFoundException.
try {
Secure.getFloat(cr, NO_SUCH_SETTING);
- fail("SettingNotFoundException should have been thrown!");
- } catch (SettingNotFoundException expected) {
+ fail("NullPointerException should have been thrown!");
+ } catch (NullPointerException expected) {
}
try {
@@ -178,9 +179,4 @@ public class Settings_SecureTest extends AndroidTestCase {
assertNotNull(uri);
assertEquals(Uri.withAppendedPath(Secure.CONTENT_URI, name), uri);
}
-
- public void testUnknownSourcesOffByDefault() throws SettingNotFoundException {
- assertEquals("Device should not ship with 'Unknown Sources' enabled by default.",
- 0, Secure.getInt(cr, Settings.Secure.INSTALL_NON_MARKET_APPS));
- }
}
diff --git a/tests/tests/renderscript/Android.mk b/tests/tests/renderscript/Android.mk
deleted file mode 100644
index fc64614..0000000
--- a/tests/tests/renderscript/Android.mk
+++ /dev/null
@@ -1,37 +0,0 @@
-# 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
deleted file mode 100644
index 7205b3c..0000000
--- a/tests/tests/renderscript/AndroidManifest.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AllocationTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AllocationTest.java
deleted file mode 100644
index 722274d..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/AllocationTest.java
+++ /dev/null
@@ -1,689 +0,0 @@
-/*
- * 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.graphics.Bitmap;
-import android.renderscript.Allocation;
-import android.renderscript.AllocationAdapter;
-import android.renderscript.Allocation.MipmapControl;
-import android.renderscript.Element;
-import android.renderscript.RSIllegalArgumentException;
-import android.renderscript.Type;
-import android.renderscript.Type.Builder;
-import android.renderscript.Type.CubemapFace;
-
-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 A = Allocation.createSized(mRS, e, i);
- assertEquals(A.getType().getElement(), e);
- assertEquals(A.getType().getX(), 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));
- }
-
- static int bDimX = 48;
- static int bDimY = 8;
-
- void helperCreateFromBitmap(Bitmap B,
- Allocation.MipmapControl mc) {
- for (int i = 0; i < 1; i++) {
- for (int j = 0; j < 1; j++) {
- for (int k = 0; k < 1; k++) {
- for (int l = 0; l < 1; l++) {
- int u = 0;
- u |= (i * Allocation.USAGE_SCRIPT);
- u |= (j * Allocation.USAGE_GRAPHICS_TEXTURE);
- u |= (k * Allocation.USAGE_GRAPHICS_VERTEX);
- u |= (l * Allocation.USAGE_GRAPHICS_CONSTANTS);
- assertTrue(null !=
- Allocation.createFromBitmap(mRS, B, mc, u));
- assertTrue(null !=
- Allocation.createCubemapFromBitmap(mRS, B, mc, u));
- }
- }
- }
- }
- }
-
- public void testCreateFromBitmap() {
- Bitmap B = Bitmap.createBitmap(bDimX, bDimY, Bitmap.Config.ARGB_8888);
- Allocation.createFromBitmap(mRS, B);
- Allocation.createCubemapFromBitmap(mRS, B);
- for (Allocation.MipmapControl mc : Allocation.MipmapControl.values()) {
- helperCreateFromBitmap(B, mc);
- }
-
- try {
- int invalidUsage = 0x0020;
- Allocation.createFromBitmap(mRS, B,
- Allocation.MipmapControl.MIPMAP_NONE, invalidUsage);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
-
- try {
- // width % 6 != 0
- Bitmap badB = Bitmap.createBitmap(47, 8, Bitmap.Config.ARGB_8888);
- Allocation.createCubemapFromBitmap(mRS, badB,
- Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
-
- try {
- // width / 6 != height
- Bitmap badB = Bitmap.createBitmap(48, 4, Bitmap.Config.ARGB_8888);
- Allocation.createCubemapFromBitmap(mRS, badB,
- Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
-
- try {
- // height not power of 2
- Bitmap badB = Bitmap.createBitmap(36, 6, Bitmap.Config.ARGB_8888);
- Allocation.createCubemapFromBitmap(mRS, badB,
- Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- }
-
- public void testAllocationMipmapControl() {
- assertEquals(MipmapControl.MIPMAP_NONE,
- MipmapControl.valueOf("MIPMAP_NONE"));
- assertEquals(MipmapControl.MIPMAP_FULL,
- MipmapControl.valueOf("MIPMAP_FULL"));
- assertEquals(MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE,
- MipmapControl.valueOf("MIPMAP_ON_SYNC_TO_TEXTURE"));
- // Make sure no new enums are added
- assertEquals(3, Allocation.MipmapControl.values().length);
-
- for (Allocation.MipmapControl mc : Allocation.MipmapControl.values()) {
- Type.Builder b = new Type.Builder(mRS, Element.U8(mRS));
- b.setX(8).setY(8);
- Allocation.createTyped(mRS, b.create(), mc,
- Allocation.USAGE_GRAPHICS_TEXTURE);
- }
- }
-
- public void testCubemapFaces() {
- Type.Builder b = new Type.Builder(mRS, Element.U8(mRS));
- b.setX(8).setY(8).setFaces(true);
- Allocation cubemap = Allocation.createTyped(mRS, b.create(),
- MipmapControl.MIPMAP_NONE,
- Allocation.USAGE_SCRIPT);
- AllocationAdapter adapter = AllocationAdapter.create2D(mRS, cubemap);
- for (Type.CubemapFace cf : Type.CubemapFace.values()) {
- adapter.setFace(cf);
- }
- }
-
- /*
- * Test all copy from/to routines for byte/short/int/float
- */
-
- void helperFloatCopy(int nElems, int offset, int count, int copyMode) {
- Allocation A = Allocation.createSized(mRS, Element.F32(mRS), nElems);
-
- float src[], dst[];
- src = new float[nElems];
- dst = new float[nElems];
- for (int i = 0; i < count; i++) {
- src[i] = (float)i;
- dst[offset + i] = -1.0f;
- }
-
- switch (copyMode) {
- case 0: A.copyFrom(src); break;
- case 1: A.copyFromUnchecked(src); break;
- case 2: A.copy1DRangeFrom(offset, count, src); break;
- case 3: A.copy1DRangeFromUnchecked(offset, count, src); break;
- }
- A.copyTo(dst);
-
- for (int i = 0; i < count; i++) {
- assertEquals(dst[offset + i], src[i]);
- }
- }
-
- void helperByteCopy(int nElems, int offset, int count, int copyMode) {
- Allocation A = Allocation.createSized(mRS, Element.I8(mRS), nElems);
-
- byte src[], dst[];
- src = new byte[nElems];
- dst = new byte[nElems];
- for (int i = 0; i < count; i++) {
- src[i] = (byte)i;
- dst[offset + i] = -1;
- }
-
- switch (copyMode) {
- case 0: A.copyFrom(src); break;
- case 1: A.copyFromUnchecked(src); break;
- case 2: A.copy1DRangeFrom(offset, count, src); break;
- case 3: A.copy1DRangeFromUnchecked(offset, count, src); break;
- }
- A.copyTo(dst);
-
- for (int i = 0; i < count; i++) {
- assertEquals(dst[offset + i], src[i]);
- }
- }
-
- void helperShortCopy(int nElems, int offset, int count, int copyMode) {
- Allocation A = Allocation.createSized(mRS, Element.I16(mRS), nElems);
-
- short src[], dst[];
- src = new short[nElems];
- dst = new short[nElems];
- for (int i = 0; i < count; i++) {
- src[i] = (short)i;
- dst[offset + i] = -1;
- }
-
- switch (copyMode) {
- case 0: A.copyFrom(src); break;
- case 1: A.copyFromUnchecked(src); break;
- case 2: A.copy1DRangeFrom(offset, count, src); break;
- case 3: A.copy1DRangeFromUnchecked(offset, count, src); break;
- }
- A.copyTo(dst);
-
- for (int i = 0; i < count; i++) {
- assertEquals(dst[offset + i], src[i]);
- }
- }
-
- void helperIntCopy(int nElems, int offset, int count, int copyMode) {
- Allocation A = Allocation.createSized(mRS, Element.I32(mRS), nElems);
-
- int src[], dst[];
- src = new int[nElems];
- dst = new int[nElems];
- for (int i = 0; i < count; i++) {
- src[i] = i;
- dst[offset + i] = -1;
- }
-
- switch (copyMode) {
- case 0: A.copyFrom(src); break;
- case 1: A.copyFromUnchecked(src); break;
- case 2: A.copy1DRangeFrom(offset, count, src); break;
- case 3: A.copy1DRangeFromUnchecked(offset, count, src); break;
- }
- A.copyTo(dst);
-
- for (int i = 0; i < count; i++) {
- assertEquals(dst[offset + i], src[i]);
- }
- }
-
- void helperBaseObjCopy(int nElems, int offset, int count, int copyMode) {
- Allocation A =
- Allocation.createSized(mRS, Element.ELEMENT(mRS), nElems);
- Element E[] = new Element[nElems];
- for (int i = 0; i < nElems; i++) {
- E[i] = Element.BOOLEAN(mRS);
- }
-
- A.copyFrom(E);
- }
-
- void helperBitmapCopy(int x, int y) {
- Bitmap bSrc = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
- Bitmap bDst = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
-
- for (int j = 0; j < y; j++) {
- for (int i = 0; i < x; i++) {
- bSrc.setPixel(i, j, 9);
- bDst.setPixel(i, j, 0);
- }
- }
-
- Type.Builder typeBuilder =
- new Type.Builder(mRS, Element.RGBA_8888(mRS));
- typeBuilder.setMipmaps(false);
- typeBuilder.setFaces(false);
- typeBuilder.setX(x).setY(y);
- Allocation A = Allocation.createTyped(mRS, typeBuilder.create());
-
- A.copyFrom(bSrc);
- A.copyTo(bDst);
-
- for (int j = 0; j < y; j++) {
- for (int i = 0; i < x; i++) {
- assertEquals(bSrc.getPixel(i, j), bDst.getPixel(i, j));
- }
- }
- }
-
- void helperFloatAllocationCopy(int nElems, int offset, int count) {
-
- Allocation srcA = Allocation.createSized(mRS, Element.F32(mRS), nElems);
- Allocation dstA = Allocation.createSized(mRS, Element.F32(mRS), nElems);
-
- float src[], dst[];
- src = new float[nElems];
- dst = new float[nElems];
- for (int i = 0; i < nElems; i++) {
- src[i] = (float)i;
- dst[i] = -1.0f;
- }
-
- // First populate the source allocation
- srcA.copyFrom(src);
- // Now test allocation to allocation copy
- dstA.copy1DRangeFrom(offset, count, srcA, offset);
- dstA.copyTo(dst);
-
- for (int i = 0; i < count; i++) {
- assertEquals(dst[offset + i], src[offset + i]);
- }
- }
-
- void helperByteAllocationCopy(int nElems, int offset, int count) {
-
- Allocation srcA = Allocation.createSized(mRS, Element.I8(mRS), nElems);
- Allocation dstA = Allocation.createSized(mRS, Element.I8(mRS), nElems);
-
- byte src[], dst[];
- src = new byte[nElems];
- dst = new byte[nElems];
- for (int i = 0; i < nElems; i++) {
- src[i] = (byte)i;
- dst[i] = -1;
- }
-
- // First populate the source allocation
- srcA.copyFrom(src);
- // Now test allocation to allocation copy
- dstA.copy1DRangeFrom(offset, count, srcA, offset);
- dstA.copyTo(dst);
-
- for (int i = 0; i < count; i++) {
- assertEquals(dst[offset + i], src[offset + i]);
- }
- }
-
- void helperFloatCopy2D(int nElemsX, int nElemsY,
- int xOffset, int yOffset,
- int width, int height) {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- Allocation A = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
-
- float src[], dst[];
- src = new float[width * height];
- dst = new float[nElemsX * nElemsY];
- for (int i = width * height - 1; i >= 0; i--) {
- src[i] = (float)i;
- }
- for (int i = nElemsX * nElemsY - 1; i >= 0; i--) {
- dst[i] = -1.0f;
- }
-
- A.copy2DRangeFrom(xOffset, yOffset, width, height, src);
- A.copyTo(dst);
-
- int sourceCount = width * height - 1;
- for (int y = yOffset + height - 1; y >= yOffset ; y--) {
- for (int x = xOffset + width - 1; x >= xOffset ; x--) {
- assertEquals(dst[y * nElemsX + x], src[sourceCount--]);
- }
- }
- }
-
- void helperByteCopy2D(int nElemsX, int nElemsY,
- int xOffset, int yOffset,
- int width, int height) {
- Type.Builder b = new Type.Builder(mRS, Element.I8(mRS));
- Allocation A = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
-
- byte src[], dst[];
- src = new byte[width * height];
- dst = new byte[nElemsX * nElemsY];
- for (int i = width * height - 1; i >= 0; i--) {
- src[i] = (byte)i;
- }
- for (int i = nElemsX * nElemsY - 1; i >= 0; i--) {
- dst[i] = -1;
- }
-
- A.copy2DRangeFrom(xOffset, yOffset, width, height, src);
- A.copyTo(dst);
-
- int sourceCount = width * height - 1;
- for (int y = yOffset + height - 1; y >= yOffset ; y--) {
- for (int x = xOffset + width - 1; x >= xOffset ; x--) {
- assertEquals(dst[y * nElemsX + x], src[sourceCount--]);
- }
- }
- }
-
- void helperShortCopy2D(int nElemsX, int nElemsY,
- int xOffset, int yOffset,
- int width, int height) {
- Type.Builder b = new Type.Builder(mRS, Element.I16(mRS));
- Allocation A = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
-
- short src[], dst[];
- src = new short[width * height];
- dst = new short[nElemsX * nElemsY];
- for (int i = width * height - 1; i >= 0; i--) {
- src[i] = (short)i;
- }
- for (int i = nElemsX * nElemsY - 1; i >= 0; i--) {
- dst[i] = -1;
- }
-
- A.copy2DRangeFrom(xOffset, yOffset, width, height, src);
- A.copyTo(dst);
-
- int sourceCount = width * height - 1;
- for (int y = yOffset + height - 1; y >= yOffset ; y--) {
- for (int x = xOffset + width - 1; x >= xOffset ; x--) {
- assertEquals(dst[y * nElemsX + x], src[sourceCount--]);
- }
- }
- }
-
- void helperIntCopy2D(int nElemsX, int nElemsY,
- int xOffset, int yOffset,
- int width, int height) {
- Type.Builder b = new Type.Builder(mRS, Element.I32(mRS));
- Allocation A = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
-
- int src[], dst[];
- src = new int[width * height];
- dst = new int[nElemsX * nElemsY];
- for (int i = width * height - 1; i >= 0; i--) {
- src[i] = i;
- }
- for (int i = nElemsX * nElemsY - 1; i >= 0; i--) {
- dst[i] = -1;
- }
-
- A.copy2DRangeFrom(xOffset, yOffset, width, height, src);
- A.copyTo(dst);
-
- int sourceCount = width * height - 1;
- for (int y = yOffset + height - 1; y >= yOffset ; y--) {
- for (int x = xOffset + width - 1; x >= xOffset ; x--) {
- assertEquals(dst[y * nElemsX + x], src[sourceCount--]);
- }
- }
- }
-
- void helperFloatAllocationCopy2D(int nElemsX, int nElemsY,
- int xOffset, int yOffset,
- int width, int height) {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- Allocation srcA = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
- Allocation dstA = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
-
- float src[], dst[];
- src = new float[nElemsX * nElemsY];
- dst = new float[nElemsX * nElemsY];
- for (int i = nElemsX * nElemsY - 1; i >= 0; i--) {
- src[i] = (float)i;
- dst[i] = -1.0f;
- }
- srcA.copyFrom(src);
- dstA.copy2DRangeFrom(xOffset, yOffset, width, height, srcA, xOffset, yOffset);
- dstA.copyTo(dst);
-
- int sourceCount = width * height - 1;
- for (int y = yOffset + height - 1; y >= yOffset ; y--) {
- for (int x = xOffset + width - 1; x >= xOffset ; x--) {
- assertEquals(dst[y * nElemsX + x], src[y * nElemsX + x]);
- }
- }
- }
-
- void helperByteAllocationCopy2D(int nElemsX, int nElemsY,
- int xOffset, int yOffset,
- int width, int height) {
- Type.Builder b = new Type.Builder(mRS, Element.I8(mRS));
- Allocation srcA = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
- Allocation dstA = Allocation.createTyped(mRS, b.setX(nElemsX).setY(nElemsY).create());
-
- byte src[], dst[];
- src = new byte[nElemsX * nElemsY];
- dst = new byte[nElemsX * nElemsY];
- for (int i = nElemsX * nElemsY - 1; i >= 0; i--) {
- src[i] = (byte)i;
- dst[i] = -1;
- }
- srcA.copyFrom(src);
- dstA.copy2DRangeFrom(xOffset, yOffset, width, height, srcA, xOffset, yOffset);
- dstA.copyTo(dst);
-
- int sourceCount = width * height - 1;
- for (int y = yOffset + height - 1; y >= yOffset ; y--) {
- for (int x = xOffset + width - 1; x >= xOffset ; x--) {
- assertEquals(dst[y * nElemsX + x], src[y * nElemsX + x]);
- }
- }
- }
-
- static int elemsToTest = 20;
-
- public void test1DCopyOperations() {
- for (int s = 8; s <= elemsToTest; s += 2) {
- for (int mode = 0; mode <= 1; mode ++) {
- helperFloatCopy(s, 0, s, mode);
- helperByteCopy(s, 0, s, mode);
- helperShortCopy(s, 0, s, mode);
- helperIntCopy(s, 0, s, mode);
- helperBaseObjCopy(s, 0, s, mode);
- }
-
- // now test copy range
- for (int mode = 2; mode <= 3; mode ++) {
- for (int off = 0; off < s; off ++) {
- for (int count = 1; count <= s - off; count ++) {
- helperFloatCopy(s, off, count, mode);
- helperByteCopy(s, off, count, mode);
- helperShortCopy(s, off, count, mode);
- helperIntCopy(s, off, count, mode);
- helperBaseObjCopy(s, off, count, mode);
- }
- }
- }
-
- for (int off = 0; off < s; off ++) {
- for (int count = 1; count <= s - off; count ++) {
- helperFloatAllocationCopy(s, off, count);
- helperByteAllocationCopy(s, off, count);
- }
- }
- }
-
- helperBitmapCopy(bDimX, bDimY);
- }
-
- public void test2DCopyOperations() {
- for (int sX = 8; sX <= elemsToTest; sX += 5) {
- for (int sY = 8; sY <= elemsToTest; sY += 5) {
- for (int offX = 0; offX < sX; offX += 3) {
- for (int offY = 0; offY < sY; offY += 3) {
- for (int w = 1; w <= sX - offX; w += 3) {
- for (int h = 1; h <= sY - offY; h += 3) {
- helperFloatCopy2D(sX, sY, offX, offY, w, h);
- helperByteCopy2D(sX, sY, offX, offY, w, h);
- helperShortCopy2D(sX, sY, offX, offY, w, h);
- helperIntCopy2D(sX, sY, offX, offY, w, h);
- helperFloatAllocationCopy2D(sX, sY, offX, offY, w, h);
- helperByteAllocationCopy2D(sX, sY, offX, offY, w, h);
- }
- }
- }
- }
- }
- }
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/BaseObjTest.java b/tests/tests/renderscript/src/android/renderscript/cts/BaseObjTest.java
deleted file mode 100644
index a079951..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/BaseObjTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.renderscript.BaseObj;
-import android.renderscript.Font;
-import android.renderscript.Font.Style;
-import android.renderscript.RSIllegalArgumentException;
-
-public class BaseObjTest extends RSBaseGraphics {
-
- public void testBaseObj() {
- Style S = Font.Style.NORMAL;
- Font F = Font.create(mRS, mRes, "sans-serif", S, 8);
- assertTrue(F != null);
- BaseObj B = F;
- B.setName("sans-serif");
- try {
- B.setName("sans-serif");
- fail("set name twice for a BaseObj");
- } catch (RSIllegalArgumentException e) {
- }
- B.destroy();
-
- F = Font.create(mRS, mRes, "serif", S, 8);
- assertTrue(F != null);
- B = F;
- try {
- B.setName("");
- fail("set empty name for a BaseObj");
- } catch (RSIllegalArgumentException e) {
- }
- B.setName("serif");
- B.destroy();
-
- F = Font.create(mRS, mRes, "mono", S, 8);
- assertTrue(F != null);
- B = F;
- try {
- B.setName(null);
- fail("set name as null string reference for a BaseObj");
- } catch (RSIllegalArgumentException e) {
- }
- B.setName("mono");
- B.destroy();
- }
-}
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ComputeTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ComputeTest.java
deleted file mode 100644
index 59c4de4..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ComputeTest.java
+++ /dev/null
@@ -1,375 +0,0 @@
-/*
- * 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.renderscript.Allocation;
-
-import android.renderscript.Byte2;
-import android.renderscript.Byte3;
-import android.renderscript.Byte4;
-
-import android.renderscript.Double2;
-import android.renderscript.Double3;
-import android.renderscript.Double4;
-
-import android.renderscript.Element;
-
-import android.renderscript.Float2;
-import android.renderscript.Float3;
-import android.renderscript.Float4;
-
-import android.renderscript.Int2;
-import android.renderscript.Int3;
-import android.renderscript.Int4;
-
-import android.renderscript.Long2;
-import android.renderscript.Long3;
-import android.renderscript.Long4;
-
-import android.renderscript.RSRuntimeException;
-
-import android.renderscript.Short2;
-import android.renderscript.Short3;
-import android.renderscript.Short4;
-
-import android.renderscript.Type;
-
-import com.android.cts.stub.R;
-
-public class ComputeTest extends RSBaseCompute {
-
- public void testJavaVectorTypes() {
- Byte2 b2 = new Byte2();
- b2.x = 1;
- b2.y = 2;
- b2 = new Byte2((byte)1, (byte)2);
- assertTrue(b2.x == 1);
- assertTrue(b2.y == 2);
- Byte3 b3 = new Byte3();
- b3.x = 1;
- b3.y = 2;
- b3.z = 2;
- b3 = new Byte3((byte)1, (byte)2, (byte)3);
- assertTrue(b3.x == 1);
- assertTrue(b3.y == 2);
- assertTrue(b3.z == 3);
- Byte4 b4 = new Byte4();
- b4.x = 1;
- b4.y = 2;
- b4.x = 3;
- b4.w = 4;
- b4 = new Byte4((byte)1, (byte)2, (byte)3, (byte)4);
- assertTrue(b4.x == 1);
- assertTrue(b4.y == 2);
- assertTrue(b4.z == 3);
- assertTrue(b4.w == 4);
-
- Double2 d2 = new Double2();
- d2.x = 1.0;
- d2.y = 2.0;
- d2 = new Double2(1.0, 2.0);
- assertTrue(d2.x == 1.0);
- assertTrue(d2.y == 2.0);
- Double3 d3 = new Double3();
- d3.x = 1.0;
- d3.y = 2.0;
- d3.z = 3.0;
- d3 = new Double3(1.0, 2.0, 3.0);
- assertTrue(d3.x == 1.0);
- assertTrue(d3.y == 2.0);
- assertTrue(d3.z == 3.0);
- Double4 d4 = new Double4();
- d4.x = 1.0;
- d4.y = 2.0;
- d4.x = 3.0;
- d4.w = 4.0;
- d4 = new Double4(1.0, 2.0, 3.0, 4.0);
- assertTrue(d4.x == 1.0);
- assertTrue(d4.y == 2.0);
- assertTrue(d4.z == 3.0);
- assertTrue(d4.w == 4.0);
-
- Float2 f2 = new Float2();
- f2.x = 1.0f;
- f2.y = 2.0f;
- f2 = new Float2(1.0f, 2.0f);
- assertTrue(f2.x == 1.0f);
- assertTrue(f2.y == 2.0f);
- Float3 f3 = new Float3();
- f3.x = 1.0f;
- f3.y = 2.0f;
- f3.z = 3.0f;
- f3 = new Float3(1.0f, 2.0f, 3.0f);
- assertTrue(f3.x == 1.0f);
- assertTrue(f3.y == 2.0f);
- assertTrue(f3.z == 3.0f);
- Float4 f4 = new Float4();
- f4.x = 1.0f;
- f4.y = 2.0f;
- f4.x = 3.0f;
- f4.w = 4.0f;
- f4 = new Float4(1.0f, 2.0f, 3.0f, 4.0f);
- assertTrue(f4.x == 1.0f);
- assertTrue(f4.y == 2.0f);
- assertTrue(f4.z == 3.0f);
- assertTrue(f4.w == 4.0f);
-
- Int2 i2 = new Int2();
- i2.x = 1;
- i2.y = 2;
- i2 = new Int2(1, 2);
- assertTrue(i2.x == 1);
- assertTrue(i2.y == 2);
- Int3 i3 = new Int3();
- i3.x = 1;
- i3.y = 2;
- i3.z = 3;
- i3 = new Int3(1, 2, 3);
- assertTrue(i3.x == 1);
- assertTrue(i3.y == 2);
- assertTrue(i3.z == 3);
- Int4 i4 = new Int4();
- i4.x = 1;
- i4.y = 2;
- i4.x = 3;
- i4.w = 4;
- i4 = new Int4(1, 2, 3, 4);
- assertTrue(i4.x == 1);
- assertTrue(i4.y == 2);
- assertTrue(i4.z == 3);
- assertTrue(i4.w == 4);
-
- Long2 l2 = new Long2();
- l2.x = 1;
- l2.y = 2;
- l2 = new Long2(1, 2);
- assertTrue(l2.x == 1);
- assertTrue(l2.y == 2);
- Long3 l3 = new Long3();
- l3.x = 1;
- l3.y = 2;
- l3.z = 3;
- l3 = new Long3(1, 2, 3);
- assertTrue(l3.x == 1);
- assertTrue(l3.y == 2);
- assertTrue(l3.z == 3);
- Long4 l4 = new Long4();
- l4.x = 1;
- l4.y = 2;
- l4.x = 3;
- l4.w = 4;
- l4 = new Long4(1, 2, 3, 4);
- assertTrue(l4.x == 1);
- assertTrue(l4.y == 2);
- assertTrue(l4.z == 3);
- assertTrue(l4.w == 4);
-
- Short2 s2 = new Short2();
- s2.x = 1;
- s2.y = 2;
- s2 = new Short2((short)1, (short)2);
- assertTrue(s2.x == 1);
- assertTrue(s2.y == 2);
- Short3 s3 = new Short3();
- s3.x = 1;
- s3.y = 2;
- s3.z = 3;
- s3 = new Short3((short)1, (short)2, (short)3);
- assertTrue(s3.x == 1);
- assertTrue(s3.y == 2);
- assertTrue(s3.z == 3);
- Short4 s4 = new Short4();
- s4.x = 1;
- s4.y = 2;
- s4.x = 3;
- s4.w = 4;
- s4 = new Short4((short)1, (short)2, (short)3, (short)4);
- assertTrue(s4.x == 1);
- assertTrue(s4.y == 2);
- assertTrue(s4.z == 3);
- assertTrue(s4.w == 4);
- }
-
- 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);
-
- ScriptField_AllVectorTypes avt;
- avt = new ScriptField_AllVectorTypes(mRS, 1,
- Allocation.USAGE_SCRIPT);
- ScriptField_AllVectorTypes.Item avtItem;
- avtItem = new ScriptField_AllVectorTypes.Item();
- avtItem.b2.x = 1;
- avtItem.b2.y = 2;
- avtItem.b3.x = 1;
- avtItem.b3.y = 2;
- avtItem.b3.z = 3;
- avtItem.b4.x = 1;
- avtItem.b4.y = 2;
- avtItem.b4.z = 3;
- avtItem.b4.w = 4;
-
- avtItem.s2.x = 1;
- avtItem.s2.y = 2;
- avtItem.s3.x = 1;
- avtItem.s3.y = 2;
- avtItem.s3.z = 3;
- avtItem.s4.x = 1;
- avtItem.s4.y = 2;
- avtItem.s4.z = 3;
- avtItem.s4.w = 4;
-
- avtItem.i2.x = 1;
- avtItem.i2.y = 2;
- avtItem.i3.x = 1;
- avtItem.i3.y = 2;
- avtItem.i3.z = 3;
- avtItem.i4.x = 1;
- avtItem.i4.y = 2;
- avtItem.i4.z = 3;
- avtItem.i4.w = 4;
-
- avtItem.f2.x = 1.0f;
- avtItem.f2.y = 2.0f;
- avtItem.f3.x = 1.0f;
- avtItem.f3.y = 2.0f;
- avtItem.f3.z = 3.0f;
- avtItem.f4.x = 1.0f;
- avtItem.f4.y = 2.0f;
- avtItem.f4.z = 3.0f;
- avtItem.f4.w = 4.0f;
-
- avt.set(avtItem, 0, true);
- s.bind_avt(avt);
-
- 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);
- }
-
- void setUpAllocation(Allocation a, int val) {
- Type t = a.getType();
- int x = t.getX();
-
- int[] arr = new int[x];
- for (int i = 0; i < x; i++) {
- arr[i] = val;
- }
- a.copyFrom(arr);
- }
-
- void checkAllocation(Allocation a, int val) {
- Type t = a.getType();
- int x = t.getX();
-
- int[] arr = new int[x];
- a.copyTo(arr);
- for (int i = 0; i < x; i++) {
- assertTrue(arr[i] == val);
- }
- }
-
- /**
- * Test support for reflected forEach() as well as validation of parameters.
- */
- public void testForEach() {
- ScriptC_negate s = new ScriptC_negate(mRS,
- mRes,
- R.raw.negate);
-
- int x = 7;
- Type t = new Type.Builder(mRS, Element.I32(mRS)).setX(x).create();
- Allocation in = Allocation.createTyped(mRS, t);
- Allocation out = Allocation.createTyped(mRS, t);
-
- int val = 5;
- setUpAllocation(in, val);
- s.forEach_root(in, out);
- checkAllocation(out, -val);
-
- Type badT = new Type.Builder(mRS, Element.I32(mRS)).setX(x-1).create();
- Allocation badOut = Allocation.createTyped(mRS, badT);
- try {
- s.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ContextCreationTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ContextCreationTest.java
deleted file mode 100644
index 84c8ade..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ContextCreationTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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 dalvik.annotation.TestTargetClass;
-import android.renderscript.*;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.UiThreadTest;
-import android.util.Log;
-
-/**
- * Tests for the RenderScriptGL class.
- */
-@TestTargetClass(RenderScriptGL.class)
-public class ContextCreationTest extends
- ActivityInstrumentationTestCase2 {
-
- private static final int NUM_RECREATE_ITERATIONS_WITHOUT_DELAY = 50;
-
- private static final int NUM_RECREATE_ITERATIONS_WITH_DELAY = 10;
-
- private static final int RECREATE_DELAY = 100;
-
- private static final boolean LOG_RECREATE = true;
-
- private static final String TAG = "ContextCreationTest";
-
- private RenderscriptGLStubActivity mActivity;
-
- public ContextCreationTest() {
- super(RenderscriptGLStubActivity.class);
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mActivity = getActivity();
- }
-
- /**
- * Test repeated recreation of the renderscript context with a
- * delay in between to detect hangs in the graphics drivers
- */
- @UiThreadTest
- public void testCreationWithDelay() throws InterruptedException {
- for (int i = 0; i < NUM_RECREATE_ITERATIONS_WITH_DELAY; i++) {
- Thread.sleep(RECREATE_DELAY);
- if (LOG_RECREATE) {
- Log.w(TAG, "Recreate (w/ delay) step " + i + " - pause");
- }
- mActivity.recreateView();
- }
- }
-
- /**
- * Test repeated recreation of the renderscript context to
- * detect hangs in the graphics drivers
- */
- @UiThreadTest
- public void testCreationWithoutDelay() {
- for (int i = 0; i < NUM_RECREATE_ITERATIONS_WITHOUT_DELAY; i++) {
- if (LOG_RECREATE) {
- Log.w(TAG, "Recreate (no delay) step " + i + " - pause");
- }
- mActivity.recreateView();
- }
- }
-
- /**
- * Test repeated recreation of the renderscript context with two
- * created at a time to detect hangs in the graphics drivers
- */
- @UiThreadTest
- public void testMultiviewCreationWithoutDelay() {
- for (int i = 0; i < NUM_RECREATE_ITERATIONS_WITHOUT_DELAY; i++) {
- if (LOG_RECREATE) {
- Log.w(TAG, "Recreate multiview (no delay) step " + i + " - pause");
- }
- mActivity.recreateMultiView();
- }
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ElementTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ElementTest.java
deleted file mode 100644
index 4f8185a..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ElementTest.java
+++ /dev/null
@@ -1,474 +0,0 @@
-/*
- * 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.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.F64_2(mRS) != null);
- assertTrue(Element.F64_3(mRS) != null);
- assertTrue(Element.F64_4(mRS) != null);
- assertTrue(Element.I8(mRS) != null);
- assertTrue(Element.I8_2(mRS) != null);
- assertTrue(Element.I8_3(mRS) != null);
- assertTrue(Element.I8_4(mRS) != null);
- assertTrue(Element.I16(mRS) != null);
- assertTrue(Element.I16_2(mRS) != null);
- assertTrue(Element.I16_3(mRS) != null);
- assertTrue(Element.I16_4(mRS) != null);
- assertTrue(Element.I32(mRS) != null);
- assertTrue(Element.I32_2(mRS) != null);
- assertTrue(Element.I32_3(mRS) != null);
- assertTrue(Element.I32_4(mRS) != null);
- assertTrue(Element.I64(mRS) != null);
- assertTrue(Element.I64_2(mRS) != null);
- assertTrue(Element.I64_3(mRS) != null);
- assertTrue(Element.I64_4(mRS) != null);
- assertTrue(Element.U8(mRS) != null);
- assertTrue(Element.U8_2(mRS) != null);
- assertTrue(Element.U8_3(mRS) != null);
- assertTrue(Element.U8_4(mRS) != null);
- assertTrue(Element.U16(mRS) != null);
- assertTrue(Element.U16_2(mRS) != null);
- assertTrue(Element.U16_3(mRS) != null);
- assertTrue(Element.U16_4(mRS) != null);
- assertTrue(Element.U32(mRS) != null);
- assertTrue(Element.U32_2(mRS) != null);
- assertTrue(Element.U32_3(mRS) != null);
- assertTrue(Element.U32_4(mRS) != null);
- assertTrue(Element.U64(mRS) != null);
- assertTrue(Element.U64_2(mRS) != null);
- assertTrue(Element.U64_3(mRS) != null);
- assertTrue(Element.U64_4(mRS) != null);
- assertTrue(Element.MATRIX_2X2(mRS) != null);
- assertTrue(Element.MATRIX_3X3(mRS) != null);
- assertTrue(Element.MATRIX_4X4(mRS) != null);
- assertTrue(Element.MATRIX4X4(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 testEquals() {
- assertTrue(Element.A_8(mRS).equals(Element.A_8(mRS)));
- assertFalse(Element.A_8(mRS).equals(Element.U8(mRS)));
-
- // Compatible elements
- assertTrue(Element.A_8(mRS).isCompatible(Element.U8(mRS)));
- assertTrue(Element.U8(mRS).isCompatible(Element.A_8(mRS)));
-
- // Verify equivalence of user-built Elements
- Element.Builder eb1 = new Element.Builder(mRS);
- eb1.add(Element.I8(mRS), "Test");
- Element e1 = eb1.add(Element.U8(mRS), "UTest").create();
-
- assertTrue(e1.equals(e1));
-
- Element.Builder eb2 = new Element.Builder(mRS);
- eb2.add(Element.I8(mRS), "Test");
- Element e2 = eb2.add(Element.U8(mRS), "UTest").create();
-
- assertTrue(e1.equals(e2));
- assertTrue(e2.equals(e1));
- assertTrue(e1.hashCode() == e2.hashCode());
- assertTrue(e1.isCompatible(e2));
- assertTrue(e2.isCompatible(e1));
-
- // Check name differences
- Element.Builder eb3 = new Element.Builder(mRS);
- eb3.add(Element.I8(mRS), "Test");
- Element e3 = eb3.add(Element.U8(mRS), "NotUTest").create();
-
- assertFalse(e1.equals(e3));
- assertFalse(e3.equals(e1));
- assertFalse(e1.isCompatible(e3));
- assertFalse(e3.isCompatible(e1));
-
- eb1.add(Element.I8(mRS), "Another");
- assertFalse(e1.equals(eb1.create()));
- assertFalse(eb1.create().equals(e1));
-
- // Compatible sub-elements but neither equal nor compatible
- Element.Builder eb4 = new Element.Builder(mRS);
- eb4.add(Element.I8(mRS), "Test");
- Element e4 = eb4.add(Element.A_8(mRS), "UTest").create();
-
- assertFalse(e1.equals(e4));
- assertFalse(e4.equals(e1));
- assertFalse(e1.isCompatible(e4));
- assertFalse(e4.isCompatible(e1));
-
- // Check identity from same builder
- assertTrue(eb1.create().isCompatible(eb1.create()));
- }
-
- public void testIsCompatible() {
- Element[] ALLOCATION = { Element.ALLOCATION(mRS) };
- // A_8 is in U8
- Element[] BOOLEAN = { Element.BOOLEAN(mRS) };
- Element[] ELEMENT = { Element.ELEMENT(mRS) };
- Element[] F32 = { Element.F32(mRS) };
- Element[] F32_2 = { Element.F32_2(mRS),
- Element.createVector(mRS, Element.DataType.FLOAT_32, 2) };
- Element[] F32_3 = { Element.F32_3(mRS),
- Element.createVector(mRS, Element.DataType.FLOAT_32, 3) };
- Element[] F32_4 = { Element.F32_4(mRS),
- Element.createVector(mRS, Element.DataType.FLOAT_32, 4) };
- Element[] F64 = { Element.F64(mRS) };
- Element[] I16 = { Element.I16(mRS) };
- Element[] I32 = { Element.I32(mRS) };
- Element[] I64 = { Element.I64(mRS) };
- Element[] I8 = { Element.I8(mRS) };
- // MATRIX4X4 is in MATRIX_4X4
- Element[] MATRIX_2X2 = { Element.MATRIX_2X2(mRS) };
- Element[] MATRIX_3X3 = { Element.MATRIX_3X3(mRS) };
- Element[] MATRIX_4X4 = { Element.MATRIX4X4(mRS),
- Element.MATRIX_4X4(mRS) };
- Element[] MESH = { Element.MESH(mRS) };
- Element[] PROGRAM_FRAGMENT = { Element.PROGRAM_FRAGMENT(mRS) };
- Element[] PROGRAM_RASTER = { Element.PROGRAM_RASTER(mRS) };
- Element[] PROGRAM_STORE = { Element.PROGRAM_STORE(mRS) };
- Element[] PROGRAM_VERTEX = { Element.PROGRAM_VERTEX(mRS) };
- Element[] RGBA_4444 = { Element.RGBA_4444(mRS),
- Element.createPixel(mRS, Element.DataType.UNSIGNED_4_4_4_4,
- Element.DataKind.PIXEL_RGBA) };
- Element[] RGBA_5551 = { Element.RGBA_5551(mRS),
- Element.createPixel(mRS, Element.DataType.UNSIGNED_5_5_5_1,
- Element.DataKind.PIXEL_RGBA) };
- // RGBA_8888 is in U8_4
- Element[] RGB_565 = { Element.RGB_565(mRS),
- Element.createPixel(mRS, Element.DataType.UNSIGNED_5_6_5,
- Element.DataKind.PIXEL_RGB) };
- // RGB_888 is in U8_3
- Element[] SAMPLER = { Element.SAMPLER(mRS) };
- Element[] SCRIPT = { Element.SCRIPT(mRS) };
- Element[] TYPE = { Element.TYPE(mRS) };
- Element[] U16 = { Element.U16(mRS) };
- Element[] U32 = { Element.U32(mRS) };
- Element[] U64 = { Element.U64(mRS) };
- Element[] U8 = { Element.A_8(mRS),
- Element.U8(mRS),
- Element.createPixel(mRS, Element.DataType.UNSIGNED_8,
- Element.DataKind.PIXEL_A) };
- Element[] U8_3 = { Element.RGB_888(mRS),
- Element.createVector(mRS, Element.DataType.UNSIGNED_8, 3),
- Element.createPixel(mRS, Element.DataType.UNSIGNED_8,
- Element.DataKind.PIXEL_RGB) };
- Element[] U8_4 = { Element.U8_4(mRS),
- Element.RGBA_8888(mRS),
- Element.createVector(mRS, Element.DataType.UNSIGNED_8, 4),
- Element.createPixel(mRS, Element.DataType.UNSIGNED_8,
- Element.DataKind.PIXEL_RGBA) };
-
- Element[][] ElementArrs = { ALLOCATION, BOOLEAN, ELEMENT, F32, F32_2,
- F32_3, F32_4, F64, I16, I32, I64, I8,
- MATRIX_2X2, MATRIX_3X3, MATRIX_4X4, MESH,
- PROGRAM_FRAGMENT, PROGRAM_RASTER,
- PROGRAM_STORE, PROGRAM_VERTEX, RGBA_4444,
- RGBA_5551, RGB_565, SAMPLER, SCRIPT, TYPE,
- U16, U32, U64, U8, U8_3, U8_4 };
-
- int ElementArrsLen = ElementArrs.length;
- for (int i = 0; i < ElementArrsLen; i++) {
- for (int j = 0; j < ElementArrsLen; j++) {
- for (Element el : ElementArrs[i]) {
- for (Element er : ElementArrs[j]) {
- if (i == j) {
- // Elements within a group are compatible
- assertTrue(el.isCompatible(er));
- } else {
- // Elements from different groups are incompatible
- assertFalse(el.isCompatible(er));
- }
- }
- }
- }
- }
- }
-
- 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.F64_2(mRS), "F64_2", arraySize);
- eb.add(Element.F64_3(mRS), "F64_3", arraySize);
- eb.add(Element.F64_4(mRS), "F64_4", arraySize);
- eb.add(Element.I8(mRS), "I8", arraySize);
- eb.add(Element.I8_2(mRS), "I8_2", arraySize);
- eb.add(Element.I8_3(mRS), "I8_3", arraySize);
- eb.add(Element.I8_4(mRS), "I8_4", arraySize);
- eb.add(Element.I16(mRS), "I16", arraySize);
- eb.add(Element.I16_2(mRS), "I16_2", arraySize);
- eb.add(Element.I16_3(mRS), "I16_3", arraySize);
- eb.add(Element.I16_4(mRS), "I16_4", arraySize);
- eb.add(Element.I32(mRS), "I32", arraySize);
- eb.add(Element.I32_2(mRS), "I32_2", arraySize);
- eb.add(Element.I32_3(mRS), "I32_3", arraySize);
- eb.add(Element.I32_4(mRS), "I32_4", arraySize);
- eb.add(Element.I64(mRS), "I64", arraySize);
- eb.add(Element.I64_2(mRS), "I64_2", arraySize);
- eb.add(Element.I64_3(mRS), "I64_3", arraySize);
- eb.add(Element.I64_4(mRS), "I64_4", arraySize);
- eb.add(Element.U8(mRS), "U8", arraySize);
- eb.add(Element.U8_2(mRS), "U8_2", arraySize);
- eb.add(Element.U8_3(mRS), "U8_3", arraySize);
- eb.add(Element.U8_4(mRS), "U8_4", arraySize);
- eb.add(Element.U16(mRS), "U16", arraySize);
- eb.add(Element.U16_2(mRS), "U16_2", arraySize);
- eb.add(Element.U16_3(mRS), "U16_3", arraySize);
- eb.add(Element.U16_4(mRS), "U16_4", arraySize);
- eb.add(Element.U32(mRS), "U32", arraySize);
- eb.add(Element.U32_2(mRS), "U32_2", arraySize);
- eb.add(Element.U32_3(mRS), "U32_3", arraySize);
- eb.add(Element.U32_4(mRS), "U32_4", arraySize);
- eb.add(Element.U64(mRS), "U64", arraySize);
- eb.add(Element.U64_2(mRS), "U64_2", arraySize);
- eb.add(Element.U64_3(mRS), "U64_3", arraySize);
- eb.add(Element.U64_4(mRS), "U64_4", 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.MATRIX4X4(mRS), "MATRIX4X4", 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.F64_2(mRS).isComplex());
- assertFalse(Element.F64_3(mRS).isComplex());
- assertFalse(Element.F64_4(mRS).isComplex());
- assertFalse(Element.I8(mRS).isComplex());
- assertFalse(Element.I8_2(mRS).isComplex());
- assertFalse(Element.I8_3(mRS).isComplex());
- assertFalse(Element.I8_4(mRS).isComplex());
- assertFalse(Element.I16(mRS).isComplex());
- assertFalse(Element.I16_2(mRS).isComplex());
- assertFalse(Element.I16_3(mRS).isComplex());
- assertFalse(Element.I16_4(mRS).isComplex());
- assertFalse(Element.I32(mRS).isComplex());
- assertFalse(Element.I32_2(mRS).isComplex());
- assertFalse(Element.I32_3(mRS).isComplex());
- assertFalse(Element.I32_4(mRS).isComplex());
- assertFalse(Element.I64(mRS).isComplex());
- assertFalse(Element.I64_2(mRS).isComplex());
- assertFalse(Element.I64_3(mRS).isComplex());
- assertFalse(Element.I64_4(mRS).isComplex());
- assertFalse(Element.U8(mRS).isComplex());
- assertFalse(Element.U8_2(mRS).isComplex());
- assertFalse(Element.U8_3(mRS).isComplex());
- assertFalse(Element.U8_4(mRS).isComplex());
- assertFalse(Element.U16(mRS).isComplex());
- assertFalse(Element.U16_2(mRS).isComplex());
- assertFalse(Element.U16_3(mRS).isComplex());
- assertFalse(Element.U16_4(mRS).isComplex());
- assertFalse(Element.U32(mRS).isComplex());
- assertFalse(Element.U32_2(mRS).isComplex());
- assertFalse(Element.U32_3(mRS).isComplex());
- assertFalse(Element.U32_4(mRS).isComplex());
- assertFalse(Element.U64(mRS).isComplex());
- assertFalse(Element.U64_2(mRS).isComplex());
- assertFalse(Element.U64_3(mRS).isComplex());
- assertFalse(Element.U64_4(mRS).isComplex());
- assertFalse(Element.MATRIX_2X2(mRS).isComplex());
- assertFalse(Element.MATRIX_3X3(mRS).isComplex());
- assertFalse(Element.MATRIX_4X4(mRS).isComplex());
- assertFalse(Element.MATRIX4X4(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());
- }
-
- public void testDataType() {
- assertEquals(DataType.FLOAT_32, DataType.valueOf("FLOAT_32"));
- assertEquals(DataType.FLOAT_64, DataType.valueOf("FLOAT_64"));
- assertEquals(DataType.SIGNED_8, DataType.valueOf("SIGNED_8"));
- assertEquals(DataType.SIGNED_16, DataType.valueOf("SIGNED_16"));
- assertEquals(DataType.SIGNED_32, DataType.valueOf("SIGNED_32"));
- assertEquals(DataType.SIGNED_64, DataType.valueOf("SIGNED_64"));
- assertEquals(DataType.UNSIGNED_8, DataType.valueOf("UNSIGNED_8"));
- assertEquals(DataType.UNSIGNED_16, DataType.valueOf("UNSIGNED_16"));
- assertEquals(DataType.UNSIGNED_32, DataType.valueOf("UNSIGNED_32"));
- assertEquals(DataType.UNSIGNED_64, DataType.valueOf("UNSIGNED_64"));
-
- assertEquals(DataType.BOOLEAN, DataType.valueOf("BOOLEAN"));
-
- assertEquals(DataType.UNSIGNED_5_6_5, DataType.valueOf("UNSIGNED_5_6_5"));
- assertEquals(DataType.UNSIGNED_5_5_5_1, DataType.valueOf("UNSIGNED_5_5_5_1"));
- assertEquals(DataType.UNSIGNED_4_4_4_4, DataType.valueOf("UNSIGNED_4_4_4_4"));
-
- assertEquals(DataType.MATRIX_4X4, DataType.valueOf("MATRIX_4X4"));
- assertEquals(DataType.MATRIX_3X3, DataType.valueOf("MATRIX_3X3"));
- assertEquals(DataType.MATRIX_2X2, DataType.valueOf("MATRIX_2X2"));
-
- assertEquals(DataType.RS_ELEMENT, DataType.valueOf("RS_ELEMENT"));
- assertEquals(DataType.RS_TYPE, DataType.valueOf("RS_TYPE"));
- assertEquals(DataType.RS_ALLOCATION, DataType.valueOf("RS_ALLOCATION"));
- assertEquals(DataType.RS_SAMPLER, DataType.valueOf("RS_SAMPLER"));
- assertEquals(DataType.RS_SCRIPT, DataType.valueOf("RS_SCRIPT"));
- assertEquals(DataType.RS_MESH, DataType.valueOf("RS_MESH"));
- assertEquals(DataType.RS_PROGRAM_FRAGMENT, DataType.valueOf("RS_PROGRAM_FRAGMENT"));
- assertEquals(DataType.RS_PROGRAM_VERTEX, DataType.valueOf("RS_PROGRAM_VERTEX"));
- assertEquals(DataType.RS_PROGRAM_RASTER, DataType.valueOf("RS_PROGRAM_RASTER"));
- assertEquals(DataType.RS_PROGRAM_STORE, DataType.valueOf("RS_PROGRAM_STORE"));
- // Make sure no new enums are added
- assertEquals(27, DataType.values().length);
-
- for (DataType dt : DataType.values()) {
- Element.createVector(mRS, dt, 2);
- }
- }
-
- public void testDataKind() {
- assertEquals(DataKind.USER, DataKind.valueOf("USER"));
-
- assertEquals(DataKind.PIXEL_L, DataKind.valueOf("PIXEL_L"));
- assertEquals(DataKind.PIXEL_A, DataKind.valueOf("PIXEL_A"));
- assertEquals(DataKind.PIXEL_LA, DataKind.valueOf("PIXEL_LA"));
- assertEquals(DataKind.PIXEL_RGB, DataKind.valueOf("PIXEL_RGB"));
- assertEquals(DataKind.PIXEL_RGBA, DataKind.valueOf("PIXEL_RGBA"));
- assertEquals(DataKind.PIXEL_DEPTH, DataKind.valueOf("PIXEL_DEPTH"));
- // Make sure no new enums are added
- assertEquals(7, DataKind.values().length);
-
- for (DataKind dk : DataKind.values()) {
- if (dk != DataKind.USER) {
- Element.createPixel(mRS, DataType.UNSIGNED_8, dk);
- }
- }
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ExceptionTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ExceptionTest.java
deleted file mode 100644
index 3a9df46..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ExceptionTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.renderscript.RSIllegalArgumentException;
-import android.renderscript.RSInvalidStateException;
-import android.renderscript.RSRuntimeException;
-import android.renderscript.RSDriverException;
-
-import android.test.AndroidTestCase;
-
-public class ExceptionTest extends AndroidTestCase {
- public void testExceptions() {
- try {
- throw new RSIllegalArgumentException("IAE");
- } catch (RSIllegalArgumentException e) {
- assertEquals(e.getMessage(), "IAE");
- }
-
- try {
- throw new RSInvalidStateException("ISE");
- } catch (RSInvalidStateException e) {
- assertEquals(e.getMessage(), "ISE");
- }
-
- try {
- throw new RSRuntimeException("RE");
- } catch (RSRuntimeException e) {
- assertEquals(e.getMessage(), "RE");
- }
-
- try {
- throw new RSDriverException("DE");
- } catch (RSDriverException e) {
- assertEquals(e.getMessage(), "DE");
- }
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/FieldPackerTest.java b/tests/tests/renderscript/src/android/renderscript/cts/FieldPackerTest.java
deleted file mode 100644
index 8625b9f..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/FieldPackerTest.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * 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.renderscript.Byte2;
-import android.renderscript.Byte3;
-import android.renderscript.Byte4;
-import android.renderscript.FieldPacker;
-import android.renderscript.Double2;
-import android.renderscript.Double3;
-import android.renderscript.Double4;
-import android.renderscript.Float2;
-import android.renderscript.Float3;
-import android.renderscript.Float4;
-import android.renderscript.Int2;
-import android.renderscript.Int3;
-import android.renderscript.Int4;
-import android.renderscript.Long2;
-import android.renderscript.Long3;
-import android.renderscript.Long4;
-import android.renderscript.Matrix2f;
-import android.renderscript.Matrix3f;
-import android.renderscript.Matrix4f;
-import android.renderscript.RSIllegalArgumentException;
-import android.renderscript.Short2;
-import android.renderscript.Short3;
-import android.renderscript.Short4;
-
-public class FieldPackerTest extends RSBaseCompute {
-
- public void testAddAllTypes() {
- FieldPacker fp = new FieldPacker(1024);
- fp.addBoolean(true);
- fp.addF32(0.1f);
- fp.addF32(new Float3());
- fp.addF32(new Float4());
- fp.addF32(new Float2());
- fp.addF64(0.2);
- fp.addF64(new Double2());
- fp.addF64(new Double3());
- fp.addF64(new Double4());
- fp.addI16(new Short3());
- fp.addI16(new Short2());
- fp.addI16((short)-2);
- fp.addI16(new Short4());
- fp.addI32(new Int3());
- fp.addI32(-4);
- fp.addI32(new Int4());
- fp.addI32(new Int2());
- fp.addI64(-8);
- fp.addI64(new Long2());
- fp.addI64(new Long3());
- fp.addI64(new Long4());
- fp.addI8((byte)-1);
- fp.addI8(new Byte4());
- fp.addI8(new Byte2());
- fp.addI8(new Byte3());
- fp.addMatrix(new Matrix4f());
- fp.addMatrix(new Matrix3f());
- fp.addMatrix(new Matrix2f());
- fp.addObj(null);
- fp.addU16(new Int2());
- fp.addU16(new Int4());
- fp.addU16((short)2);
- fp.addU16(new Int3());
- fp.addU32(new Long4());
- fp.addU32(new Long2());
- fp.addU32(new Long3());
- fp.addU32(4);
- fp.addU64(8);
- fp.addU64(new Long2());
- fp.addU64(new Long3());
- fp.addU64(new Long4());
- fp.addU8(new Short2());
- fp.addU8(new Short4());
- fp.addU8((byte)1);
- fp.addU8(new Short3());
- }
-
- public void testAlignResetSkip() {
- for (int alignAmount = 1; alignAmount < 16; alignAmount <<= 1) {
- FieldPacker fp = new FieldPacker(256);
- for (int i = 0; i < 32; i++) {
- fp.align(alignAmount);
- fp.addI8((byte)i);
- }
-
- byte[] b = fp.getData();
- for (int i = 0; i < 32; i++) {
- assertEquals(i, b[alignAmount * i]);
- }
-
- // Check that align is zeroing out bytes in between
- fp.reset();
- fp.addI8((byte)0);
- fp.align(256);
- b = fp.getData();
- for (int i = 0; i < 256; i++) {
- assertEquals(0, b[i]);
- }
- }
-
- for (int skipAmount = 1; skipAmount < 4; skipAmount++) {
- FieldPacker fp = new FieldPacker(256);
- for (int i = 0; i < 32; i++) {
- fp.addI8((byte)i);
- fp.skip(skipAmount);
- }
- fp.reset(1);
- for (int i = 0; i < 32; i++) {
- fp.addI8((byte)i);
- fp.skip(skipAmount);
- }
-
- byte[] b = fp.getData();
- for (int i = 0; i < 32; i++) {
- // Check that skip is not altering any other bytes
- assertEquals(i, b[i * (skipAmount + 1)]);
- assertEquals(i, b[(i * (skipAmount + 1)) + 1]);
- }
- }
-
- // Error cases
- FieldPacker fp = new FieldPacker(256);
-
- int[] badAlignArgs = {-4, -3, -2, -1, 0, 3, 5, 127};
- for (int arg: badAlignArgs) {
- try {
- fp.align(arg);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- }
-
- int[] badResetArgs = {-1000, -2, -1, 256, 257, 1000};
- for (int arg: badResetArgs) {
- try {
- fp.reset(arg);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- }
-
- // Skip allows us to move 1 past the final element in the FieldPacker
- int[] badSkipArgs = {-1000, -6, -5, 253, 1000};
- for (int arg: badSkipArgs) {
- try {
- fp.reset(4);
- fp.skip(arg);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- }
- }
-}
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/FileA3DTest.java b/tests/tests/renderscript/src/android/renderscript/cts/FileA3DTest.java
deleted file mode 100644
index ca2bb38..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/FileA3DTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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 java.io.File;
-
-import com.android.cts.stub.R;
-
-import android.renderscript.RSRuntimeException;
-import android.renderscript.FileA3D;
-import android.renderscript.FileA3D.EntryType;
-import android.renderscript.FileA3D.IndexEntry;
-
-public class FileA3DTest extends RSBaseGraphics {
-
- public void testCreateFromResource() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- }
-
- public void testCreateFromAsset() {
- FileA3D model = FileA3D.createFromAsset(mRS, mRes.getAssets(), "sphere.a3d");
- assertTrue(model != null);
- }
-
- public void testGetIndexEntryCount() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- assertTrue(model.getIndexEntryCount() == 1);
- }
-
- public void testGetIndexEntry() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- assertTrue(model.getIndexEntryCount() == 1);
- assertTrue(model.getIndexEntry(0) != null);
- }
-
- public void testIndexEntryGetEntryType() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- assertTrue(model.getIndexEntryCount() == 1);
- FileA3D.IndexEntry entry = model.getIndexEntry(0);
- assertTrue(entry != null);
- assertTrue(entry.getEntryType() == FileA3D.EntryType.MESH);
- boolean isOneOfEntries = false;
- for(FileA3D.EntryType et : FileA3D.EntryType.values()) {
- if (et == entry.getEntryType()) {
- isOneOfEntries = true;
- break;
- }
- }
- assertTrue(isOneOfEntries);
- }
-
- public void testIndexEntryGetMesh() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- assertTrue(model.getIndexEntryCount() == 1);
- FileA3D.IndexEntry entry = model.getIndexEntry(0);
- assertTrue(entry != null);
- assertTrue(entry.getEntryType() == FileA3D.EntryType.MESH);
- assertTrue(entry.getMesh() != null);
- }
-
- public void testIndexEntryGetName() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- assertTrue(model.getIndexEntryCount() == 1);
- FileA3D.IndexEntry entry = model.getIndexEntry(0);
- assertTrue(entry != null);
- assertTrue(entry.getName() != null);
- }
-
- public void testIndexEntryGetObject() {
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.sphere);
- assertTrue(model != null);
- assertTrue(model.getIndexEntryCount() == 1);
- FileA3D.IndexEntry entry = model.getIndexEntry(0);
- assertTrue(entry != null);
- assertTrue(entry.getObject() != null);
- }
-
- public void testFileA3DEntryType() {
- assertEquals(FileA3D.EntryType.UNKNOWN, FileA3D.EntryType.valueOf("UNKNOWN"));
- assertEquals(FileA3D.EntryType.MESH, FileA3D.EntryType.valueOf("MESH"));
- // Make sure no new enums are added
- assertEquals(2, FileA3D.EntryType.values().length);
- }
-
- public void testCreateFromFile() {
- File fileDesc = new File("bogusFile");
- try {
- FileA3D model = FileA3D.createFromFile(mRS, fileDesc);
- fail("should throw RSRuntimeException.");
- } catch (RSRuntimeException e) {
- }
- try {
- FileA3D model = FileA3D.createFromFile(mRS, "bogus");
- fail("should throw RSRuntimeException.");
- } catch (RSRuntimeException e) {
- }
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/FontTest.java b/tests/tests/renderscript/src/android/renderscript/cts/FontTest.java
deleted file mode 100644
index a3e4da0..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/FontTest.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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 java.io.File;
-import com.android.cts.stub.R;
-
-import android.os.Environment;
-import android.renderscript.Font;
-import android.renderscript.Font.Style;
-import android.renderscript.RSIllegalArgumentException;
-
-public class FontTest extends RSBaseGraphics {
-
- public void testCreate() {
- for (int fontSize = 8; fontSize <= 12; fontSize += 2) {
- for (Font.Style style : Font.Style.values()) {
- Font F = null;
- F = Font.create(mRS, mRes, "sans-serif", style, fontSize);
- assertTrue(F != null);
- F.setName("sans-serif");
- try {
- F.setName("sans-serif");
- fail("set name twice for a font");
- } catch (RSIllegalArgumentException e) {
- }
- F.destroy();
-
- F = Font.create(mRS, mRes, "serif", style, fontSize);
- assertTrue(F != null);
- try {
- F.setName("");
- fail("set empty name for a font");
- } catch (RSIllegalArgumentException e) {
- }
- F.setName("serif");
- F.destroy();
-
- F = Font.create(mRS, mRes, "mono", style, fontSize);
- assertTrue(F != null);
- try {
- F.setName(null);
- fail("set name as null string reference for a font");
- } catch (RSIllegalArgumentException e) {
- }
- F.setName("mono");
- F.destroy();
- }
- }
- }
-
- public void testCreateFromFile() {
- String fontFile = "Roboto-Regular.ttf";
- String fontPath = Environment.getRootDirectory().getAbsolutePath();
- fontPath += "/fonts/" + fontFile;
- File fileDesc = new File(fontPath);
- assertTrue(Font.createFromFile(mRS, mRes, fontPath, 8) != null);
- assertTrue(Font.createFromFile(mRS, mRes, fileDesc, 8) != null);
- }
-
- public void testCreateFromAsset() {
- assertTrue(Font.createFromAsset(mRS, mRes, "samplefont.ttf", 8) != null);
- }
-
- public void testFontStyle() {
- assertEquals(Font.Style.NORMAL, Font.Style.valueOf("NORMAL"));
- assertEquals(Font.Style.BOLD, Font.Style.valueOf("BOLD"));
- assertEquals(Font.Style.ITALIC, Font.Style.valueOf("ITALIC"));
- assertEquals(Font.Style.BOLD_ITALIC, Font.Style.valueOf("BOLD_ITALIC"));
- // Make sure no new enums are added
- assertEquals(4, Font.Style.values().length);
- }
-
- public void testCreateFromResource() {
- assertTrue(Font.createFromResource(mRS, mRes, R.raw.samplefont, 8) != null);
- }
-}
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ForEachTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ForEachTest.java
deleted file mode 100644
index 12c8fb0..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ForEachTest.java
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
- * 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.renderscript.Allocation;
-
-import android.renderscript.Byte2;
-import android.renderscript.Byte3;
-import android.renderscript.Byte4;
-
-import android.renderscript.Double2;
-import android.renderscript.Double3;
-import android.renderscript.Double4;
-
-import android.renderscript.Element;
-
-import android.renderscript.Float2;
-import android.renderscript.Float3;
-import android.renderscript.Float4;
-
-import android.renderscript.Int2;
-import android.renderscript.Int3;
-import android.renderscript.Int4;
-
-import android.renderscript.Long2;
-import android.renderscript.Long3;
-import android.renderscript.Long4;
-
-import android.renderscript.RSRuntimeException;
-
-import android.renderscript.Short2;
-import android.renderscript.Short3;
-import android.renderscript.Short4;
-
-import android.renderscript.Type;
-
-import com.android.cts.stub.R;
-
-public class ForEachTest extends RSBaseCompute {
- /**
- * Test support for reflected forEach() as well as validation of parameters.
- */
- public void testForEach() {
- int x = 7;
-
- // badOut is always I8, so it is always an invalid type
- Type t = new Type.Builder(mRS, Element.I8(mRS)).setX(x).create();
- Allocation badOut = Allocation.createTyped(mRS, t);
-
- // I8
- ScriptC_fe_i8 fe_i8 = new ScriptC_fe_i8(mRS, mRes, R.raw.fe_i8);
- Allocation in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U8(mRS)).setX(x).create();
- Allocation out = Allocation.createTyped(mRS, t);
- fe_i8.forEach_root(in, out);
- try {
- fe_i8.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I8_2
- ScriptC_fe_i8_2 fe_i8_2 = new ScriptC_fe_i8_2(mRS,
- mRes,
- R.raw.fe_i8_2);
- t = new Type.Builder(mRS, Element.I8_2(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U8_2(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i8_2.forEach_root(in, out);
- try {
- fe_i8_2.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I8_3
- ScriptC_fe_i8_3 fe_i8_3 = new ScriptC_fe_i8_3(mRS,
- mRes,
- R.raw.fe_i8_3);
- t = new Type.Builder(mRS, Element.I8_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U8_3(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i8_3.forEach_root(in, out);
- try {
- fe_i8_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I8_4
- ScriptC_fe_i8_4 fe_i8_4 = new ScriptC_fe_i8_4(mRS,
- mRes,
- R.raw.fe_i8_4);
- t = new Type.Builder(mRS, Element.I8_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U8_4(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i8_4.forEach_root(in, out);
- try {
- fe_i8_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I16
- ScriptC_fe_i16 fe_i16 = new ScriptC_fe_i16(mRS, mRes, R.raw.fe_i16);
- t = new Type.Builder(mRS, Element.I16(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U16(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i16.forEach_root(in, out);
- try {
- fe_i16.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I16_2
- ScriptC_fe_i16_2 fe_i16_2 = new ScriptC_fe_i16_2(mRS,
- mRes,
- R.raw.fe_i16_2);
- t = new Type.Builder(mRS, Element.I16_2(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U16_2(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i16_2.forEach_root(in, out);
- try {
- fe_i16_2.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I16_3
- ScriptC_fe_i16_3 fe_i16_3 = new ScriptC_fe_i16_3(mRS,
- mRes,
- R.raw.fe_i16_3);
- t = new Type.Builder(mRS, Element.I16_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U16_3(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i16_3.forEach_root(in, out);
- try {
- fe_i16_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I16_4
- ScriptC_fe_i16_4 fe_i16_4 = new ScriptC_fe_i16_4(mRS,
- mRes,
- R.raw.fe_i16_4);
- t = new Type.Builder(mRS, Element.I16_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U16_4(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i16_4.forEach_root(in, out);
- try {
- fe_i16_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I32
- ScriptC_fe_i32 fe_i32 = new ScriptC_fe_i32(mRS, mRes, R.raw.fe_i32);
- t = new Type.Builder(mRS, Element.I32(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U32(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i32.forEach_root(in, out);
- try {
- fe_i32.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I32_2
- ScriptC_fe_i32_2 fe_i32_2 = new ScriptC_fe_i32_2(mRS,
- mRes,
- R.raw.fe_i32_2);
- t = new Type.Builder(mRS, Element.I32_2(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U32_2(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i32_2.forEach_root(in, out);
- try {
- fe_i32_2.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I32_3
- ScriptC_fe_i32_3 fe_i32_3 = new ScriptC_fe_i32_3(mRS,
- mRes,
- R.raw.fe_i32_3);
- t = new Type.Builder(mRS, Element.I32_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U32_3(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i32_3.forEach_root(in, out);
- try {
- fe_i32_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I32_4
- ScriptC_fe_i32_4 fe_i32_4 = new ScriptC_fe_i32_4(mRS,
- mRes,
- R.raw.fe_i32_4);
- t = new Type.Builder(mRS, Element.I32_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U32_4(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i32_4.forEach_root(in, out);
- try {
- fe_i32_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I64
- ScriptC_fe_i64 fe_i64 = new ScriptC_fe_i64(mRS, mRes, R.raw.fe_i64);
- t = new Type.Builder(mRS, Element.I64(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U64(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i64.forEach_root(in, out);
- try {
- fe_i64.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I64_2
- ScriptC_fe_i64_2 fe_i64_2 = new ScriptC_fe_i64_2(mRS,
- mRes,
- R.raw.fe_i64_2);
- t = new Type.Builder(mRS, Element.I64_2(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U64_2(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i64_2.forEach_root(in, out);
- try {
- fe_i64_2.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I64_3
- ScriptC_fe_i64_3 fe_i64_3 = new ScriptC_fe_i64_3(mRS,
- mRes,
- R.raw.fe_i64_3);
- t = new Type.Builder(mRS, Element.I64_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U64_3(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i64_3.forEach_root(in, out);
- try {
- fe_i64_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // I64_4
- ScriptC_fe_i64_4 fe_i64_4 = new ScriptC_fe_i64_4(mRS,
- mRes,
- R.raw.fe_i64_4);
- t = new Type.Builder(mRS, Element.I64_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.U64_4(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i64_4.forEach_root(in, out);
- try {
- fe_i64_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F32
- ScriptC_fe_f32 fe_f32 = new ScriptC_fe_f32(mRS, mRes, R.raw.fe_f32);
- t = new Type.Builder(mRS, Element.F32(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f32.forEach_root(in, out);
- try {
- fe_f32.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F32_2
- ScriptC_fe_f32_2 fe_f32_2 = new ScriptC_fe_f32_2(mRS,
- mRes,
- R.raw.fe_f32_2);
- t = new Type.Builder(mRS, Element.F32_2(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.F32_2(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_f32_2.forEach_root(in, out);
- try {
- fe_f32_2.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F32_3
- ScriptC_fe_f32_3 fe_f32_3 = new ScriptC_fe_f32_3(mRS,
- mRes,
- R.raw.fe_f32_3);
- t = new Type.Builder(mRS, Element.F32_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f32_3.forEach_root(in, out);
- try {
- fe_f32_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F32_4
- ScriptC_fe_f32_4 fe_f32_4 = new ScriptC_fe_f32_4(mRS,
- mRes,
- R.raw.fe_f32_4);
- t = new Type.Builder(mRS, Element.F32_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f32_4.forEach_root(in, out);
- try {
- fe_f32_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F64
- ScriptC_fe_f64 fe_f64 = new ScriptC_fe_f64(mRS, mRes, R.raw.fe_f64);
- t = new Type.Builder(mRS, Element.F64(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f64.forEach_root(in, out);
- try {
- fe_f64.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F64_2
- ScriptC_fe_f64_2 fe_f64_2 = new ScriptC_fe_f64_2(mRS,
- mRes,
- R.raw.fe_f64_2);
- t = new Type.Builder(mRS, Element.F64_2(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f64_2.forEach_root(in, out);
- try {
- fe_f64_2.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F64_3
- ScriptC_fe_f64_3 fe_f64_3 = new ScriptC_fe_f64_3(mRS,
- mRes,
- R.raw.fe_f64_3);
- t = new Type.Builder(mRS, Element.F64_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f64_3.forEach_root(in, out);
- try {
- fe_f64_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // F64_4
- ScriptC_fe_f64_4 fe_f64_4 = new ScriptC_fe_f64_4(mRS,
- mRes,
- R.raw.fe_f64_4);
- t = new Type.Builder(mRS, Element.F64_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_f64_4.forEach_root(in, out);
- try {
- fe_f64_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // fe_test (struct)
- ScriptC_fe_struct fe_struct = new ScriptC_fe_struct(mRS,
- mRes,
- R.raw.fe_struct);
- in = new ScriptField_fe_test(mRS, x).getAllocation();
- out = new ScriptField_fe_test(mRS, x).getAllocation();
- fe_struct.forEach_root(in, out);
- try {
- fe_struct.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // BOOLEAN
- ScriptC_fe_bool fe_bool = new ScriptC_fe_bool(mRS, mRes, R.raw.fe_bool);
- t = new Type.Builder(mRS, Element.BOOLEAN(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- out = Allocation.createTyped(mRS, t);
- fe_bool.forEach_root(in, out);
- try {
- fe_bool.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // A_8
- t = new Type.Builder(mRS, Element.I8(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.A_8(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i8.forEach_root(in, out);
- try {
- fe_i8.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // RGBA_8888
- t = new Type.Builder(mRS, Element.I8_4(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.RGBA_8888(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i8_4.forEach_root(in, out);
- try {
- fe_i8_4.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
-
- // RGB_888
- t = new Type.Builder(mRS, Element.I8_3(mRS)).setX(x).create();
- in = Allocation.createTyped(mRS, t);
- t = new Type.Builder(mRS, Element.RGB_888(mRS)).setX(x).create();
- out = Allocation.createTyped(mRS, t);
- fe_i8_3.forEach_root(in, out);
- try {
- fe_i8_3.forEach_root(in, badOut);
- fail("should throw RSRuntimeException");
- } catch (RSRuntimeException e) {
- }
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Matrix2fTest.java b/tests/tests/renderscript/src/android/renderscript/cts/Matrix2fTest.java
deleted file mode 100755
index fa7c5d5..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/Matrix2fTest.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * 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.renderscript.Matrix2f;
-
-public class Matrix2fTest extends RSBaseCompute {
-
- final float delta = 0.00001f;
- final float[] setData = {
- 1.0f, 2.0f,
- 3.0f, 4.0f
- };
-
- void checkIdentity(Matrix2f m, float delta) {
- for (int i = 0; i < 2; i ++) {
- for (int j = 0; j < 2; j ++) {
- if (i == j) {
- assertEquals(1.0f, m.getArray()[i*2 + j], delta);
- } else {
- assertEquals(0.0f, m.getArray()[i*2 + j], delta);
- }
- }
- }
- }
-
- String getString(float[] array) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < 2; i ++) {
- builder.append("[");
- for (int j = 0; j < 2; j ++) {
- builder.append(array[i*2 + j]);
- builder.append(" ");
- }
- builder.append("]");
- }
- return builder.toString();
- }
-
- void checkData(Matrix2f m, float[] data, float delta) {
- for (int i = 0; i < data.length; i ++) {
- assertEquals(data[i], m.getArray()[i], delta);
- }
- }
-
- void checkData(Matrix2f m, float[] data) {
- String s1 = getString(m.getArray());
- String s2 = getString(data);
- assertEquals(s2, s1);
- }
-
- public void testCreation() {
- Matrix2f m = new Matrix2f();
- assertTrue(m.getArray() != null);
- checkIdentity(m, 0.0f);
-
- m = new Matrix2f(setData);
- checkData(m, setData);
- }
-
- public void testGet() {
-
- Matrix2f m = new Matrix2f(setData);
-
- for (int i = 0; i < 2; i ++) {
- for (int j = 0; j < 2; j ++) {
- assertEquals(setData[i*2 + j], m.get(i, j), 0.0f);
- }
- }
- }
-
- public void testSet() {
- Matrix2f m = new Matrix2f();
- for (int i = 0; i < 2; i ++) {
- for (int j = 0; j < 2; j ++) {
- float valToSet = setData[i*2 + j];
- m.set(i, j, valToSet);
- assertEquals(valToSet, m.get(i, j), 0.0f);
- }
- }
- }
-
- public void testLoadIdentity() {
- Matrix2f m = new Matrix2f(setData);
- m.loadIdentity();
- checkIdentity(m, 0.0f);
- }
-
- public void testLoad() {
- Matrix2f m1 = new Matrix2f();
- Matrix2f m2 = new Matrix2f(setData);
-
- m1.load(m2);
- checkData(m1, setData);
- }
-
- public void testLoadScale() {
- float[] expectedData = {
- 2.0f, 0.0f,
- 0.0f, 3.0f
- };
-
- Matrix2f m = new Matrix2f(setData);
- m.loadScale(2.0f, 3.0f);
- checkData(m, expectedData);
- }
-
- public void testMultiply() {
- float[] lhsData = {
- 1.0f, 1.0f,
- 1.0f, 1.0f
- };
-
- float[] rhsData = {
- 2.0f, 2.0f,
- 3.0f, 3.0f
- };
-
- float[] expected = {
- 2.0f*2.0f, 2.0f*2.0f,
- 2.0f*3.0f, 2.0f*3.0f
- };
-
- // Due to column major nature of OpenGL,
- // left hand side and right hand side
- // are reversed. Premultiplying by row major
- // and post multiplying by column major
- // are the same. So lhs and rhs get reversed here.
- Matrix2f lhs = new Matrix2f(lhsData);
- Matrix2f rhs = new Matrix2f(rhsData);
- Matrix2f loadMul = new Matrix2f();
-
- loadMul.loadMultiply(lhs, rhs);
- checkData(loadMul, expected);
-
- lhs.multiply(rhs);
- checkData(lhs, expected);
- }
-
- public void testScale() {
- float[] expectedData = new float[setData.length];
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
- float scaleX = 2.0f;
- float scaleY = 3.0f;
- expectedData[0] *= scaleX;
- expectedData[1] *= scaleX;
- expectedData[2] *= scaleY;
- expectedData[3] *= scaleY;
-
- Matrix2f m = new Matrix2f(setData);
- m.scale(scaleX, scaleY);
- checkData(m, expectedData);
- }
-
- public void testTranspose() {
- float[] expectedData = new float[setData.length];
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
- float temp = expectedData[1];
- expectedData[1] = expectedData[2];
- expectedData[2] = temp;
-
- Matrix2f m = new Matrix2f(setData);
- m.transpose();
-
- checkData(m, expectedData);
- }
-
- public void testRotateLoadRotate() {
-
- float theta = 30.0f * (float)(java.lang.Math.PI / 180.0f);
- float cosTheta = (float)Math.cos((float)theta);
- float sinTheta = (float)Math.sin((float)theta);
- float[] rotate = new float[4];
- rotate[0] = cosTheta;
- rotate[1] = -sinTheta;
- rotate[2] = sinTheta;
- rotate[3] = cosTheta;
-
- Matrix2f m = new Matrix2f();
- m.loadRotate(30.0f);
- checkData(m, rotate);
-
- m = new Matrix2f();
- m.rotate(30.0f);
- checkData(m, rotate);
-
- float[] sourceData = {
- 2.0f, 3.0f,
- 4.0f, 5.0f
- };
- float[] rotated = new float[4];
- rotated[0] = rotate[0] * sourceData[0] + rotate[1] * sourceData[2];
- rotated[1] = rotate[0] * sourceData[1] + rotate[1] * sourceData[3];
- rotated[2] = rotate[2] * sourceData[0] + rotate[3] * sourceData[2];
- rotated[3] = rotate[2] * sourceData[1] + rotate[3] * sourceData[3];
- m = new Matrix2f(sourceData);
- m.rotate(30.0f);
-
- checkData(m, rotated);
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Matrix3fTest.java b/tests/tests/renderscript/src/android/renderscript/cts/Matrix3fTest.java
deleted file mode 100755
index f817cab..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/Matrix3fTest.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * 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.renderscript.Matrix3f;
-
-public class Matrix3fTest extends RSBaseCompute {
-
- final float delta = 0.00001f;
- final float[] setData = {
- 1.0f, 2.0f, 3.0f,
- 4.0f, 5.0f, 6.0f,
- 7.0f, 8.0f, 9.0f
- };
-
- void checkIdentity(Matrix3f m, float delta) {
- for (int i = 0; i < 3; i ++) {
- for (int j = 0; j < 3; j ++) {
- if (i == j) {
- assertEquals(1.0f, m.getArray()[i*3 + j], delta);
- } else {
- assertEquals(0.0f, m.getArray()[i*3 + j], delta);
- }
- }
- }
- }
-
- String getString(float[] array) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < 3; i ++) {
- builder.append("[");
- for (int j = 0; j < 3; j ++) {
- builder.append(array[i*3 + j]);
- builder.append(" ");
- }
- builder.append("]");
- }
- return builder.toString();
- }
-
- void checkData(Matrix3f m, float[] data, float delta) {
- for (int i = 0; i < data.length; i ++) {
- assertEquals(data[i], m.getArray()[i], delta);
- }
- }
-
- void checkData(Matrix3f m, float[] data) {
- String s1 = getString(m.getArray());
- String s2 = getString(data);
- assertEquals(s2, s1);
- }
-
- public void testCreation() {
- Matrix3f m = new Matrix3f();
- assertTrue(m.getArray() != null);
- checkIdentity(m, 0.0f);
-
- m = new Matrix3f(setData);
- checkData(m, setData);
- }
-
- public void testGet() {
-
- Matrix3f m = new Matrix3f(setData);
-
- for (int i = 0; i < 3; i ++) {
- for (int j = 0; j < 3; j ++) {
- assertEquals(setData[i*3 + j], m.get(i, j), 0.0f);
- }
- }
- }
-
- public void testSet() {
- Matrix3f m = new Matrix3f();
- for (int i = 0; i < 3; i ++) {
- for (int j = 0; j < 3; j ++) {
- float valToSet = setData[i*3 + j];
- m.set(i, j, valToSet);
- assertEquals(valToSet, m.get(i, j), 0.0f);
- }
- }
- }
-
- public void testLoadIdentity() {
- Matrix3f m = new Matrix3f(setData);
- m.loadIdentity();
- checkIdentity(m, 0.0f);
- }
-
- public void testLoad() {
- Matrix3f m1 = new Matrix3f();
- Matrix3f m2 = new Matrix3f(setData);
-
- m1.load(m2);
- checkData(m1, setData);
- }
-
- public void testLoadScale() {
- float[] expectedData = {
- 2.0f, 0.0f, 0.0f,
- 0.0f, 3.0f, 0.0f,
- 0.0f, 0.0f, 4.0f,
- };
- float[] expectedData2 = {
- 2.0f, 0.0f, 0.0f,
- 0.0f, 3.0f, 0.0f,
- 0.0f, 0.0f, 1.0f,
- };
-
- Matrix3f m = new Matrix3f(setData);
- m.loadScale(2.0f, 3.0f, 4.0f);
- checkData(m, expectedData);
-
- m = new Matrix3f(setData);
- m.loadScale(2.0f, 3.0f);
- checkData(m, expectedData2);
- }
-
- public void testLoadTranslate() {
- float[] expectedData = {
- 1.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f,
- 2.0f, 3.0f, 1.0f,
- };
-
- Matrix3f m = new Matrix3f(setData);
- m.loadTranslate(2.0f, 3.0f);
- checkData(m, expectedData);
- }
-
- public void testScale() {
- float[] expectedData = new float[setData.length];
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
- float scaleX = 2.0f;
- float scaleY = 3.0f;
- float scaleZ = 4.0f;
- expectedData[0] *= scaleX;
- expectedData[1] *= scaleX;
- expectedData[2] *= scaleX;
- expectedData[3] *= scaleY;
- expectedData[4] *= scaleY;
- expectedData[5] *= scaleY;
- expectedData[6] *= scaleZ;
- expectedData[7] *= scaleZ;
- expectedData[8] *= scaleZ;
-
- Matrix3f m = new Matrix3f(setData);
- m.scale(scaleX, scaleY, scaleZ);
- checkData(m, expectedData);
-
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
- expectedData[0] *= scaleX;
- expectedData[1] *= scaleX;
- expectedData[2] *= scaleX;
- expectedData[3] *= scaleY;
- expectedData[4] *= scaleY;
- expectedData[5] *= scaleY;
-
- m = new Matrix3f(setData);
- m.scale(scaleX, scaleY);
- checkData(m, expectedData);
- }
-
- public void testMultiply() {
- float[] lhsData = {
- 1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f
- };
-
- float[] rhsData = {
- 2.0f, 2.0f, 2.0f,
- 3.0f, 3.0f, 3.0f,
- 4.0f, 4.0f, 4.0f
- };
-
- float[] expected = {
- 3.0f*2.0f, 3.0f*2.0f, 3.0f*2.0f,
- 3.0f*3.0f, 3.0f*3.0f, 3.0f*3.0f,
- 3.0f*4.0f, 3.0f*4.0f, 3.0f*4.0f
- };
-
- // Due to column major nature of OpenGL,
- // left hand side and right hand side
- // are reversed. Premultiplying by row major
- // and post multiplying by column major
- // are the same. So lhs and rhs get reversed here.
- Matrix3f lhs = new Matrix3f(lhsData);
- Matrix3f rhs = new Matrix3f(rhsData);
- Matrix3f loadMul = new Matrix3f();
-
- loadMul.loadMultiply(lhs, rhs);
- checkData(loadMul, expected);
-
- lhs.multiply(rhs);
- checkData(lhs, expected);
- }
-
- public void testTranspose() {
- float[] expectedData = new float[setData.length];
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
-
- for(int i = 0; i < 2; i++) {
- for(int j = i + 1; j < 3; j++) {
- float temp = expectedData[i*3 + j];
- expectedData[i*3 + j] = expectedData[j*3 + i];
- expectedData[j*3 + i] = temp;
- }
- }
-
- Matrix3f m = new Matrix3f(setData);
- m.transpose();
-
- checkData(m, expectedData);
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Matrix4fTest.java b/tests/tests/renderscript/src/android/renderscript/cts/Matrix4fTest.java
deleted file mode 100755
index 8678578..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/Matrix4fTest.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * 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.renderscript.Matrix4f;
-
-public class Matrix4fTest extends RSBaseCompute {
-
- final float delta = 0.00001f;
- final float[] setData = {
- 1.0f, 2.0f, 3.0f, 4.0f,
- 5.0f, 6.0f, 7.0f, 8.0f,
- 9.0f, 10.0f, 11.0f, 12.0f,
- 13.0f, 14.0f, 15.0f, 16.0f
- };
-
- void checkIdentity(Matrix4f m, float delta) {
- for (int i = 0; i < 4; i ++) {
- for (int j = 0; j < 4; j ++) {
- if (i == j) {
- assertEquals(1.0f, m.getArray()[i*4 + j], delta);
- } else {
- assertEquals(0.0f, m.getArray()[i*4 + j], delta);
- }
- }
- }
- }
-
- String getString(float[] array) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < 4; i ++) {
- builder.append("[");
- for (int j = 0; j < 4; j ++) {
- builder.append(array[i*4 + j]);
- builder.append(" ");
- }
- builder.append("]");
- }
- return builder.toString();
- }
-
- void checkData(Matrix4f m, float[] data, float delta) {
- for (int i = 0; i < data.length; i ++) {
- assertEquals(data[i], m.getArray()[i], delta);
- }
- }
-
- void checkData(Matrix4f m, float[] data) {
- String s1 = getString(m.getArray());
- String s2 = getString(data);
- assertEquals(s2, s1);
- }
-
- public void testCreation() {
- Matrix4f m = new Matrix4f();
- assertTrue(m.getArray() != null);
- checkIdentity(m, 0.0f);
-
-
- m = new Matrix4f(setData);
- checkData(m, setData);
- }
-
- public void testGet() {
-
- Matrix4f m = new Matrix4f(setData);
-
- for (int i = 0; i < 4; i ++) {
- for (int j = 0; j < 4; j ++) {
- assertEquals(setData[i*4 + j], m.get(i, j), 0.0f);
- }
- }
- }
-
- public void testSet() {
- Matrix4f m = new Matrix4f();
- for (int i = 0; i < 4; i ++) {
- for (int j = 0; j < 4; j ++) {
- float valToSet = setData[i*4 + j];
- m.set(i, j, valToSet);
- assertEquals(valToSet, m.get(i, j), 0.0f);
- }
- }
- }
-
- public void testLoadIdentity() {
- Matrix4f m = new Matrix4f(setData);
- m.loadIdentity();
- checkIdentity(m, 0.0f);
- }
-
- public void testLoad() {
- Matrix4f m1 = new Matrix4f();
- Matrix4f m2 = new Matrix4f(setData);
-
- m1.load(m2);
- checkData(m1, setData);
- }
-
- public void testLoadScale() {
- float[] expectedData = {
- 2.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 3.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 4.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 1.0f
- };
-
- Matrix4f m = new Matrix4f(setData);
- m.loadScale(2.0f, 3.0f, 4.0f);
- checkData(m, expectedData);
- }
-
- public void testLoadTranslate() {
- float[] expectedData = {
- 1.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.0f,
- 2.0f, 3.0f, 4.0f, 1.0f
- };
-
- Matrix4f m = new Matrix4f(setData);
- m.loadTranslate(2.0f, 3.0f, 4.0f);
- checkData(m, expectedData);
- }
-
- public void testScale() {
- float[] expectedData = new float[setData.length];
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
- float scaleX = 2.0f;
- float scaleY = 3.0f;
- float scaleZ = 4.0f;
- expectedData[0] *= scaleX;
- expectedData[1] *= scaleX;
- expectedData[2] *= scaleX;
- expectedData[3] *= scaleX;
- expectedData[4] *= scaleY;
- expectedData[5] *= scaleY;
- expectedData[6] *= scaleY;
- expectedData[7] *= scaleY;
- expectedData[8] *= scaleZ;
- expectedData[9] *= scaleZ;
- expectedData[10] *= scaleZ;
- expectedData[11] *= scaleZ;
-
- Matrix4f m = new Matrix4f(setData);
- m.scale(scaleX, scaleY, scaleZ);
- checkData(m, expectedData);
- }
-
- public void testTranspose() {
- float[] expectedData = new float[setData.length];
- System.arraycopy(setData, 0, expectedData, 0, setData.length);
-
- for(int i = 0; i < 3; i++) {
- for(int j = i + 1; j < 4; j++) {
- float temp = expectedData[i*4 + j];
- expectedData[i*4 + j] = expectedData[j*4 + i];
- expectedData[j*4 + i] = temp;
- }
- }
-
- Matrix4f m = new Matrix4f(setData);
- m.transpose();
-
- checkData(m, expectedData);
- }
-
- public void testMultiply() {
- float[] lhsData = {
- 1.0f, 1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f
- };
-
- float[] rhsData = {
- 2.0f, 2.0f, 2.0f, 2.0f,
- 3.0f, 3.0f, 3.0f, 3.0f,
- 4.0f, 4.0f, 4.0f, 4.0f,
- 5.0f, 5.0f, 5.0f, 5.0f
- };
-
- float[] expected = {
- 4.0f*2.0f, 4.0f*2.0f, 4.0f*2.0f, 4.0f*2.0f,
- 4.0f*3.0f, 4.0f*3.0f, 4.0f*3.0f, 4.0f*3.0f,
- 4.0f*4.0f, 4.0f*4.0f, 4.0f*4.0f, 4.0f*4.0f,
- 4.0f*5.0f, 4.0f*5.0f, 4.0f*5.0f, 4.0f*5.0f
- };
-
- // Due to column major nature of OpenGL,
- // left hand side and right hand side
- // are reversed. Premultiplying by row major
- // and post multiplying by column major
- // are the same. So lhs and rhs get reversed here.
- Matrix4f lhs = new Matrix4f(lhsData);
- Matrix4f rhs = new Matrix4f(rhsData);
- Matrix4f loadMul = new Matrix4f();
-
- loadMul.loadMultiply(lhs, rhs);
- checkData(loadMul, expected);
-
- lhs.multiply(rhs);
- checkData(lhs, expected);
- }
-
- public void testInverse() {
- Matrix4f m = new Matrix4f();
- assertTrue(m.inverse());
- checkIdentity(m, delta);
-
- m = new Matrix4f();
- m.scale(2.0f, 2.0f, 2.0f);
- m.translate(5.0f, 6.0f, 7.0f);
-
- Matrix4f m2 = new Matrix4f(m.getArray());
- assertTrue(m2.inverse());
- m.multiply(m2);
- checkIdentity(m, delta);
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/MeshTest.java b/tests/tests/renderscript/src/android/renderscript/cts/MeshTest.java
deleted file mode 100644
index ffa733a..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/MeshTest.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * 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.renderscript.Allocation;
-import android.renderscript.Element;
-import android.renderscript.Type;
-import android.renderscript.Mesh;
-import android.renderscript.Mesh.Primitive;
-import android.renderscript.Mesh.AllocationBuilder;
-import android.renderscript.Mesh.Builder;
-import android.renderscript.Mesh.TriangleMeshBuilder;
-
-public class MeshTest extends RSBaseGraphics {
-
- Allocation mAttrAlloc;
- Allocation mIndexAlloc;
- Element mPosElem;
- Type mPosType;
- Type mIndexType;
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- Element.Builder eb = new Element.Builder(mRS);
- eb.add(Element.F32_4(mRS), "position");
- mPosElem = eb.create();
- Type.Builder typeB = new Type.Builder(mRS, mPosElem);
- mPosType = typeB.setX(3).create();
- typeB = new Type.Builder(mRS, Element.U16(mRS));
- mIndexType = typeB.setX(3).create();
-
- mAttrAlloc = Allocation.createSized(mRS, mPosElem, 3);
- mIndexAlloc = Allocation.createSized(mRS, Element.U16(mRS), 3);
- }
-
- public void testMeshAllocationBuilder() {
- Mesh.AllocationBuilder mab;
- for(Primitive prim : Primitive.values()) {
- mab = new Mesh.AllocationBuilder(mRS);
- mab.addVertexAllocation(mAttrAlloc);
- mab.getCurrentVertexTypeIndex();
- mab.addIndexSetType(prim);
- assertTrue(mab.create() != null);
-
- mab = new Mesh.AllocationBuilder(mRS);
- mab.addVertexAllocation(mAttrAlloc);
- mab.getCurrentVertexTypeIndex();
- mab.addIndexSetAllocation(mIndexAlloc, prim);
- mab.getCurrentIndexSetIndex();
- mab.addIndexSetType(prim);
-
- Mesh mesh = mab.create();
- assertTrue(mesh != null);
- assertTrue(mesh.getVertexAllocationCount() == 1);
- assertTrue(mesh.getVertexAllocation(0) == mAttrAlloc);
- assertTrue(mesh.getPrimitiveCount() == 2);
- assertTrue(mesh.getPrimitive(0) == prim);
- assertTrue(mesh.getPrimitive(1) == prim);
- assertTrue(mesh.getIndexSetAllocation(0) == mIndexAlloc);
- }
- }
-
- public void testMeshBuilder() {
- Mesh.Builder mb;
- for(Primitive prim : Primitive.values()) {
- mb = new Mesh.Builder(mRS,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_VERTEX);
- mb.addVertexType(mPosElem, 3);
- mb.getCurrentVertexTypeIndex();
- mb.addIndexSetType(prim);
- Mesh mesh = mb.create();
- assertTrue(mesh != null);
- assertTrue(mesh.getVertexAllocationCount() != 0);
-
- mb = new Mesh.Builder(mRS,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_VERTEX);
- mb.addVertexType(mPosElem, 3);
- mb.getCurrentVertexTypeIndex();
- mb.addIndexSetType(Element.U16(mRS), 3, prim);
- mb.getCurrentIndexSetIndex();
- mesh = mb.create();
- assertTrue(mesh != null);
- assertTrue(mesh.getVertexAllocationCount() != 0);
- assertTrue(mesh.getPrimitiveCount() != 0);
-
- mb = new Mesh.Builder(mRS,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_VERTEX);
- mb.addVertexType(mPosElem, 3);
- mb.getCurrentVertexTypeIndex();
- mb.addIndexSetType(mIndexType, prim);
- mb.getCurrentIndexSetIndex();
- assertTrue(mb.create() != null);
-
- mb = new Mesh.Builder(mRS,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_VERTEX);
- mb.addVertexType(mPosType);
- mb.getCurrentVertexTypeIndex();
- mb.addIndexSetType(prim);
- assertTrue(mb.create() != null);
-
- mb = new Mesh.Builder(mRS,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_VERTEX);
- mb.addVertexType(mPosType);
- mb.getCurrentVertexTypeIndex();
- mb.addIndexSetType(Element.U16(mRS), 3, prim);
- mb.getCurrentIndexSetIndex();
- assertTrue(mb.create() != null);
-
- mb = new Mesh.Builder(mRS,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_VERTEX);
- mb.addVertexType(mPosType);
- mb.getCurrentVertexTypeIndex();
- mb.addIndexSetType(mIndexType, prim);
- mb.getCurrentIndexSetIndex();
- assertTrue(mb.create() != null);
- }
- }
-
- void triangleMeshBuilderHelper(int size, int flags) {
- // Test various num vertices and triangles
- for (int numVerts = 3; numVerts < 100; numVerts += 15) {
- for (int numTries = 1; numTries < 100; numTries += 15) {
- Mesh.TriangleMeshBuilder tmb = new Mesh.TriangleMeshBuilder(mRS, size, flags);
- // Append all the vertices
- for (int numVertsI = 0; numVertsI < numVerts; numVertsI++) {
- if (size == 2) {
- tmb.addVertex(1.0f, 1.0f);
- } else {
- tmb.addVertex(1.0f, 1.0f, 1.0f);
- }
- if ((flags & TriangleMeshBuilder.COLOR) != 0) {
- tmb.setColor(1.0f, 1.0f, 1.0f, 1.0f);
- }
- if ((flags & TriangleMeshBuilder.NORMAL) != 0) {
- tmb.setNormal(1.0f, 1.0f, 1.0f);
- }
- if ((flags & TriangleMeshBuilder.TEXTURE_0) != 0) {
- tmb.setTexture(1.0f, 1.0f);
- }
- }
- // Add triangles to index them
- for (int numTriesI = 0; numTriesI < numTries; numTriesI ++) {
- tmb.addTriangle(0, 1, 2);
- }
- assertTrue(tmb.create(false) != null);
- assertTrue(tmb.create(true) != null);
- }
- }
- }
-
- public void testMeshTriangleMeshBuilder() {
- for (int size = 2; size <= 3; size ++) {
- triangleMeshBuilderHelper(size, 0);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.COLOR);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.COLOR |
- TriangleMeshBuilder.NORMAL);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.COLOR |
- TriangleMeshBuilder.TEXTURE_0);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.COLOR |
- TriangleMeshBuilder.NORMAL |
- TriangleMeshBuilder.TEXTURE_0);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.NORMAL);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.NORMAL|
- TriangleMeshBuilder.TEXTURE_0);
- triangleMeshBuilderHelper(size, TriangleMeshBuilder.TEXTURE_0);
- }
- }
-
- public void testMeshPrimitive() {
- assertEquals(Mesh.Primitive.POINT, Mesh.Primitive.valueOf("POINT"));
- assertEquals(Mesh.Primitive.LINE, Mesh.Primitive.valueOf("LINE"));
- assertEquals(Mesh.Primitive.LINE_STRIP, Mesh.Primitive.valueOf("LINE_STRIP"));
- assertEquals(Mesh.Primitive.TRIANGLE, Mesh.Primitive.valueOf("TRIANGLE"));
- assertEquals(Mesh.Primitive.TRIANGLE_STRIP, Mesh.Primitive.valueOf("TRIANGLE_STRIP"));
- assertEquals(Mesh.Primitive.TRIANGLE_FAN, Mesh.Primitive.valueOf("TRIANGLE_FAN"));
- // Make sure no new enums are added
- assertEquals(6, Mesh.Primitive.values().length);
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramFragmentFixedFunctionTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramFragmentFixedFunctionTest.java
deleted file mode 100644
index ac54b74..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ProgramFragmentFixedFunctionTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.Type;
-import android.renderscript.Allocation;
-import android.renderscript.Sampler;
-import android.renderscript.ProgramFragment;
-import android.renderscript.ProgramFragmentFixedFunction;
-import android.renderscript.ProgramFragmentFixedFunction.Builder;
-
-public class ProgramFragmentFixedFunctionTest extends RSBaseGraphics {
-
- ScriptC_graphics_runner mScript;
-
- Allocation mTex2D;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- Type.Builder typeB = new Type.Builder(mRS, Element.RGB_888(mRS));
- typeB.setX(8).setY(8);
- mTex2D = Allocation.createTyped(mRS, typeB.create(),
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_TEXTURE);
-
- mScript = new ScriptC_graphics_runner(mRS, mRes, R.raw.graphics_runner);
- mRS.bindRootScript(mScript);
- }
-
- @Override
- protected void tearDown() throws Exception {
- mRS.bindRootScript(null);
- super.tearDown();
- }
-
- void testProgramFragmentFixedFunctionBuilder(boolean testBind) {
- ProgramFragmentFixedFunction.Builder b;
- for (int tCount = 0; tCount <= Builder.MAX_TEXTURE; tCount ++) {
- for (int varC = 0; varC <= 1; varC++) {
- for (int pSprite = 0; pSprite <= 1; pSprite++) {
- for (Builder.EnvMode env : Builder.EnvMode.values()) {
- for (Builder.Format format : Builder.Format.values()) {
- b = new ProgramFragmentFixedFunction.Builder(mRS);
- b.setVaryingColor(varC == 1);
- b.setPointSpriteTexCoordinateReplacement(pSprite == 1);
- for (int t = 0; t < tCount; t++) {
- b.setTexture(env, format, t);
- }
-
- ProgramFragment pf = b.create();
- assertTrue(pf != null);
- for (int t = 0; t < tCount; t++) {
- pf.bindTexture(mTex2D, t);
- pf.bindSampler(Sampler.CLAMP_NEAREST(mRS), t);
- }
- if (testBind) {
- mScript.invoke_testProgramFragment(pf);
- }
- }
- }
- }
- }
- }
- }
-
- public void testProgramFragmentFixedFunctionBuilder() {
- testProgramFragmentFixedFunctionBuilder(false);
- testProgramFragmentFixedFunctionBuilder(true);
- }
-
- public void testBuilderEnvMode() {
- assertEquals(Builder.EnvMode.DECAL, Builder.EnvMode.valueOf("DECAL"));
- assertEquals(Builder.EnvMode.MODULATE, Builder.EnvMode.valueOf("MODULATE"));
- assertEquals(Builder.EnvMode.REPLACE, Builder.EnvMode.valueOf("REPLACE"));
-
- // Make sure no new enums are added
- assertEquals(3, Builder.EnvMode.values().length);
- }
-
- public void testBuilderFormat() {
- assertEquals(Builder.Format.ALPHA, Builder.Format.valueOf("ALPHA"));
- assertEquals(Builder.Format.LUMINANCE_ALPHA, Builder.Format.valueOf("LUMINANCE_ALPHA"));
- assertEquals(Builder.Format.RGB, Builder.Format.valueOf("RGB"));
- assertEquals(Builder.Format.RGBA, Builder.Format.valueOf("RGBA"));
-
- // Make sure no new enums are added
- assertEquals(4, Builder.Format.values().length);
- }
-
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramFragmentTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramFragmentTest.java
deleted file mode 100644
index 9a71386..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ProgramFragmentTest.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * 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.Element;
-import android.renderscript.Program;
-import android.renderscript.ProgramFragment;
-import android.renderscript.Sampler;
-import android.renderscript.Type;
-
-public class ProgramFragmentTest extends RSBaseGraphics {
-
- ScriptC_graphics_runner mScript;
-
- Allocation mConstMatrix;
- Allocation mConstComplex;
- Allocation mConstExtra;
-
- Allocation mTex2D;
- Allocation mTexCube;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- Type.Builder typeB = new Type.Builder(mRS, Element.RGB_888(mRS));
- typeB.setX(8).setY(8);
- mTex2D = Allocation.createTyped(mRS, typeB.create(),
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_TEXTURE);
- typeB.setFaces(true);
- mTexCube = Allocation.createTyped(mRS, typeB.create(),
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_TEXTURE);
-
- ScriptField_ConstMatrix c1 = new ScriptField_ConstMatrix(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- c1.set(new ScriptField_ConstMatrix.Item(), 0, true);
- mConstMatrix = c1.getAllocation();
-
- ScriptField_ConstComplex c2 = new ScriptField_ConstComplex(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- c2.set(new ScriptField_ConstComplex.Item(), 0, true);
- mConstComplex = c2.getAllocation();
-
- ScriptField_ConstExtra c3 = new ScriptField_ConstExtra(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- c3.set(new ScriptField_ConstExtra.Item(), 0, true);
- mConstExtra = c3.getAllocation();
-
- mScript = new ScriptC_graphics_runner(mRS, mRes, R.raw.graphics_runner);
- mRS.bindRootScript(mScript);
- }
-
- @Override
- protected void tearDown() throws Exception {
- mRS.bindRootScript(null);
- super.tearDown();
- }
-
- ProgramFragment buildShader(Allocation[] textures, Allocation[] constInput, String shader) {
- ProgramFragment.Builder pfb = new ProgramFragment.Builder(mRS);
- Program.BaseProgramBuilder bpb = pfb;
- if (textures != null) {
- for (int i = 0; i < textures.length; i++) {
- Program.TextureType tType = Program.TextureType.TEXTURE_2D;
- if (textures[i].getType().hasFaces()) {
- tType = Program.TextureType.TEXTURE_CUBE;
- }
- // Add textures through the base program builder
- bpb.addTexture(tType);
- bpb.getCurrentTextureIndex();
- }
- }
-
- if (constInput != null) {
- for (int i = 0; i < constInput.length; i++) {
- bpb.addConstant(constInput[i].getType());
- bpb.getCurrentConstantIndex();
- }
- }
-
- bpb.setShader(shader);
- ProgramFragment pf = pfb.create();
- if (constInput != null) {
- for (int i = 0; i < constInput.length; i++) {
- pf.bindConstants(constInput[i], i);
- // Test the base class path too
- Program p = pf;
- p.bindConstants(constInput[i], i);
- }
- }
- if (textures != null) {
- for (int i = 0; i < textures.length; i++) {
- pf.bindTexture(textures[i], i);
- pf.bindSampler(Sampler.CLAMP_NEAREST(mRS), i);
- // Test the base class path too
- Program p = pf;
- p.bindTexture(textures[i], i);
- p.bindSampler(Sampler.CLAMP_NEAREST(mRS), i);
- }
- }
- return pf;
- }
-
- void testProgramFragmentBuilderHelper(boolean testBind) {
- String simpleFrag = "void main() {\n"+
- " vec4 col = vec4(0.1, 0.2, 0.3, 0.4);"+
- " gl_FragColor = col;\n"+
- "}";
-
- String simpleUni = "void main() {\n"+
- " vec4 col = vec4(0.1, 0.2, 0.3, 0.4);\n"+
- " col = UNI_MATRIX * col;\n"+
- " gl_FragColor = col;\n"+
- "}";
-
- String simpleUniTex = "void main() {\n"+
- " vec4 col = vec4(0.1, 0.2, 0.3, 0.4);"+
- " col += texture2D(UNI_Tex0, vec2(0.1, 0.1));\n"+
- " col += textureCube(UNI_Tex1, vec3(0.1, 0.2, 0.3));\n"+
- " col = UNI_MATRIX * col;\n"+
- " gl_FragColor = col;\n"+
- "}";
-
- String multiUni = "void main() {\n"+
- " vec4 col = vec4(0.1, 0.2, 0.3, 0.4);"+
- " col = UNI_MATRIX * col;\n"+
- " col = UNI_EXTRA * col;\n"+
- " col += UNI_extra4;\n"+
- " col.xyz += UNI_extra3;\n "+
- " col.xy += UNI_extra2;\n"+
- " col.x += UNI_extra1;\n"+
- " gl_FragColor = col;\n"+
- "}";
-
- // Create a series of shaders that do nothing useful
- // but exercise creation pipeline
- ProgramFragment pf = buildShader(null, null, simpleFrag);
- if (testBind) {
- mScript.invoke_testProgramFragment(pf);
- }
-
- Allocation[] constInput = new Allocation[1];
- constInput[0] = mConstMatrix;
- pf = buildShader(null, constInput, simpleUni);
- if (testBind) {
- mScript.invoke_testProgramFragment(pf);
- mRS.bindProgramFragment(pf);
- }
-
- constInput[0] = mConstComplex;
- pf = buildShader(null, constInput, multiUni);
- if (testBind) {
- mScript.invoke_testProgramFragment(pf);
- mRS.bindProgramFragment(pf);
- }
-
- Allocation[] textures = new Allocation[2];
- textures[0] = mTex2D;
- textures[1] = mTexCube;
- pf = buildShader(textures, constInput, simpleUniTex);
- if (testBind) {
- mScript.invoke_testProgramFragment(pf);
- mRS.bindProgramFragment(pf);
- }
-
- constInput = new Allocation[2];
- constInput[0] = mConstMatrix;
- constInput[1] = mConstExtra;
- pf = buildShader(null, constInput, multiUni);
- if (testBind) {
- mScript.invoke_testProgramFragment(pf);
- mRS.bindProgramFragment(pf);
- }
- }
-
- public void testProgramFragmentBuilder() {
- testProgramFragmentBuilderHelper(false);
- }
-
- public void testProgramFragmentCreation() {
- testProgramFragmentBuilderHelper(true);
- }
-
- public void testProgramTextureType() {
- assertEquals(Program.TextureType.TEXTURE_2D,
- Program.TextureType.valueOf("TEXTURE_2D"));
- assertEquals(Program.TextureType.TEXTURE_CUBE,
- Program.TextureType.valueOf("TEXTURE_CUBE"));
- // Make sure no new enums are added
- assertEquals(2, Program.TextureType.values().length);
-
- ProgramFragment.Builder pfb = new ProgramFragment.Builder(mRS);
- for (Program.TextureType tt : Program.TextureType.values()) {
- pfb.addTexture(tt);
- }
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramRasterTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramRasterTest.java
deleted file mode 100644
index befa926..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ProgramRasterTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.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);
- ProgramRaster pr = b.create();
- assertTrue(pr != null);
- mRS.bindProgramRaster(pr);
- }
- }
- }
-
- public void testPrebuiltProgramRaster() {
- assertTrue(ProgramRaster.CULL_BACK(mRS) != null);
- assertTrue(ProgramRaster.CULL_FRONT(mRS) != null);
- assertTrue(ProgramRaster.CULL_NONE(mRS) != null);
- }
-
- public void testProgramRasterCullMode() {
- assertEquals(CullMode.BACK, CullMode.valueOf("BACK"));
- assertEquals(CullMode.FRONT, CullMode.valueOf("FRONT"));
- assertEquals(CullMode.NONE, CullMode.valueOf("NONE"));
- // Make sure no new enums are added
- assertEquals(3, CullMode.values().length);
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramStoreTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramStoreTest.java
deleted file mode 100644
index b7f5eff..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ProgramStoreTest.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * 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.renderscript.ProgramStore;
-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.setDitherEnabled(isDither);
- pb.setColorMaskEnabled(isR, isG, isB, isA);
- ProgramStore ps = pb.create();
- assertTrue(ps != null);
- mRS.bindProgramStore(ps);
- }
- }
- }
- }
- }
- }
-
- 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);
- }
-
- public void testProgramStoreBlendDstFunc() {
- assertEquals(BlendDstFunc.ZERO,
- BlendDstFunc.valueOf("ZERO"));
- assertEquals(BlendDstFunc.ONE,
- BlendDstFunc.valueOf("ONE"));
- assertEquals(BlendDstFunc.SRC_COLOR,
- BlendDstFunc.valueOf("SRC_COLOR"));
- assertEquals(BlendDstFunc.ONE_MINUS_SRC_COLOR,
- BlendDstFunc.valueOf("ONE_MINUS_SRC_COLOR"));
- assertEquals(BlendDstFunc.SRC_ALPHA,
- BlendDstFunc.valueOf("SRC_ALPHA"));
- assertEquals(BlendDstFunc.ONE_MINUS_SRC_ALPHA,
- BlendDstFunc.valueOf("ONE_MINUS_SRC_ALPHA"));
- assertEquals(BlendDstFunc.DST_ALPHA,
- BlendDstFunc.valueOf("DST_ALPHA"));
- assertEquals(BlendDstFunc.ONE_MINUS_DST_ALPHA,
- BlendDstFunc.valueOf("ONE_MINUS_DST_ALPHA"));
- // Make sure no new enums are added
- assertEquals(8, BlendDstFunc.values().length);
- }
-
- public void testProgramStoreBlendSrcFunc() {
- assertEquals(BlendSrcFunc.ZERO,
- BlendSrcFunc.valueOf("ZERO"));
- assertEquals(BlendSrcFunc.ONE,
- BlendSrcFunc.valueOf("ONE"));
- assertEquals(BlendSrcFunc.DST_COLOR,
- BlendSrcFunc.valueOf("DST_COLOR"));
- assertEquals(BlendSrcFunc.ONE_MINUS_DST_COLOR,
- BlendSrcFunc.valueOf("ONE_MINUS_DST_COLOR"));
- assertEquals(BlendSrcFunc.SRC_ALPHA,
- BlendSrcFunc.valueOf("SRC_ALPHA"));
- assertEquals(BlendSrcFunc.ONE_MINUS_SRC_ALPHA,
- BlendSrcFunc.valueOf("ONE_MINUS_SRC_ALPHA"));
- assertEquals(BlendSrcFunc.DST_ALPHA,
- BlendSrcFunc.valueOf("DST_ALPHA"));
- assertEquals(BlendSrcFunc.ONE_MINUS_DST_ALPHA,
- BlendSrcFunc.valueOf("ONE_MINUS_DST_ALPHA"));
- assertEquals(BlendSrcFunc.SRC_ALPHA_SATURATE,
- BlendSrcFunc.valueOf("SRC_ALPHA_SATURATE"));
- // Make sure no new enums are added
- assertEquals(9, BlendSrcFunc.values().length);
- }
- public void testProgramStoreDepthFunc() {
- assertEquals(DepthFunc.ALWAYS,
- DepthFunc.valueOf("ALWAYS"));
- assertEquals(DepthFunc.LESS,
- DepthFunc.valueOf("LESS"));
- assertEquals(DepthFunc.LESS_OR_EQUAL,
- DepthFunc.valueOf("LESS_OR_EQUAL"));
- assertEquals(DepthFunc.GREATER,
- DepthFunc.valueOf("GREATER"));
- assertEquals(DepthFunc.GREATER_OR_EQUAL,
- DepthFunc.valueOf("GREATER_OR_EQUAL"));
- assertEquals(DepthFunc.EQUAL,
- DepthFunc.valueOf("EQUAL"));
- assertEquals(DepthFunc.NOT_EQUAL,
- DepthFunc.valueOf("NOT_EQUAL"));
- // Make sure no new enums are added
- assertEquals(7, DepthFunc.values().length);
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramVertexFixedFunctionTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramVertexFixedFunctionTest.java
deleted file mode 100644
index 0adab9a..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ProgramVertexFixedFunctionTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * 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.ProgramVertexFixedFunction;
-import android.renderscript.ProgramVertexFixedFunction.Builder;
-import android.renderscript.ScriptC;
-import android.renderscript.Matrix4f;
-
-public class ProgramVertexFixedFunctionTest extends RSBaseGraphics {
-
- ScriptC_graphics_runner mScript;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mScript = new ScriptC_graphics_runner(mRS, mRes, R.raw.graphics_runner);
- mRS.bindRootScript(mScript);
- }
-
- @Override
- protected void tearDown() throws Exception {
- mRS.bindRootScript(null);
- super.tearDown();
- }
-
- public void testConstants() {
- ProgramVertexFixedFunction.Constants pva;
- for (int isM = 0; isM <= 1; isM++) {
- for (int isP = 0; isP <= 1; isP++) {
- for (int isT = 0; isT <= 1; isT++) {
- pva = new ProgramVertexFixedFunction.Constants(mRS);
- if (isM == 1) {
- pva.setModelview(new Matrix4f());
- }
- if (isP == 1) {
- pva.setProjection(new Matrix4f());
- }
- if (isT == 1) {
- pva.setTexture(new Matrix4f());
- }
- pva.destroy();
- }
- }
- }
- }
-
- void testProgramVertexFixedFunctionBuilder(boolean testBind) {
- ProgramVertexFixedFunction.Constants pva;
- pva = new ProgramVertexFixedFunction.Constants(mRS);
-
- ProgramVertexFixedFunction.Builder b;
- b = new ProgramVertexFixedFunction.Builder(mRS);
- b.setTextureMatrixEnable(false);
- ProgramVertexFixedFunction pv = b.create();
- assertTrue(pv != null);
- pv.bindConstants(pva);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- }
- pv.destroy();
- b.setTextureMatrixEnable(true);
- pv = b.create();
- assertTrue(pv != null);
- pv.bindConstants(pva);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- }
- pv.destroy();
- }
-
- public void testProgramVertexFixedFunctionBuilder() {
- testProgramVertexFixedFunctionBuilder(false);
- testProgramVertexFixedFunctionBuilder(true);
- }
-
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ProgramVertexTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ProgramVertexTest.java
deleted file mode 100644
index 3c2c188..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ProgramVertexTest.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * 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.Element;
-import android.renderscript.Program;
-import android.renderscript.ProgramVertex;
-
-public class ProgramVertexTest extends RSBaseGraphics {
-
- ScriptC_graphics_runner mScript;
- Element mAttrPosElem;
- Element mAttrNormTexElem;
- Element mAttrPosNormTexElem;
- Element mAttrExtra;
-
- Allocation mConstMatrix;
- Allocation mConstComplex;
- Allocation mConstExtra;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- // Build elements for shader inputs
- Element.Builder eb = new Element.Builder(mRS);
- eb.add(Element.F32_4(mRS), "position");
- mAttrPosElem = eb.create();
-
- eb = new Element.Builder(mRS);
- eb.add(Element.F32_3(mRS), "normal");
- eb.add(Element.F32_2(mRS), "texture0");
- mAttrNormTexElem = eb.create();
-
- eb = new Element.Builder(mRS);
- eb.add(Element.F32_4(mRS), "position");
- eb.add(Element.F32_3(mRS), "normal");
- eb.add(Element.F32_2(mRS), "texture0");
- mAttrPosNormTexElem = eb.create();
-
- eb.add(Element.F32(mRS), "extra1");
- eb.add(Element.F32_2(mRS), "extra2");
- eb.add(Element.F32_3(mRS), "extra3");
- eb.add(Element.F32_4(mRS), "extra4");
- mAttrExtra = eb.create();
-
- ScriptField_ConstMatrix c1 = new ScriptField_ConstMatrix(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- c1.set(new ScriptField_ConstMatrix.Item(), 0, true);
- mConstMatrix = c1.getAllocation();
-
- ScriptField_ConstComplex c2 = new ScriptField_ConstComplex(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- c2.set(new ScriptField_ConstComplex.Item(), 0, true);
- mConstComplex = c2.getAllocation();
-
- ScriptField_ConstExtra c3 = new ScriptField_ConstExtra(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- c3.set(new ScriptField_ConstExtra.Item(), 0, true);
- mConstExtra = c3.getAllocation();
-
- mScript = new ScriptC_graphics_runner(mRS, mRes, R.raw.graphics_runner);
- mRS.bindRootScript(mScript);
- }
-
- @Override
- protected void tearDown() throws Exception {
- mRS.bindRootScript(null);
- super.tearDown();
- }
-
- ProgramVertex buildShader(Element[] input, Allocation[] constInput, String shader) {
- ProgramVertex.Builder pvb = new ProgramVertex.Builder(mRS);
- Program.BaseProgramBuilder bpb = pvb;
- if (input != null) {
- for (int i = 0; i < input.length; i++) {
- pvb.addInput(input[i]);
- }
- }
- if (constInput != null) {
- for (int i = 0; i < constInput.length; i++) {
- // Add constants through the base builder class to
- // tick cts test coverage (doesn't register through subclass)
- bpb.addConstant(constInput[i].getType());
- bpb.getCurrentConstantIndex();
- }
- }
-
- bpb.setShader(shader);
- ProgramVertex pv = pvb.create();
- if (constInput != null) {
- for (int i = 0; i < constInput.length; i++) {
- pv.bindConstants(constInput[i], i);
- // Go through the base class code as well
- Program p = pv;
- p.bindConstants(constInput[i], i);
- }
- }
- return pv;
- }
-
- void testProgramVertexBuilderHelper(boolean testBind) {
- String simpleAttr = "void main() {\n"+
- " gl_Position = ATTRIB_position;\n"+
- "}";
-
- String multiAttr = "void main() {\n"+
- " vec4 temp = ATTRIB_position;\n"+
- " temp.xyz += ATTRIB_normal;\n"+
- " temp.xy += ATTRIB_texture0;\n"+
- " gl_Position = temp;\n"+
- "}";
-
- String multiAttr2 = "void main() {\n"+
- " vec4 temp = ATTRIB_position;\n"+
- " temp.xyz += ATTRIB_normal;\n"+
- " temp.xy += ATTRIB_texture0;\n"+
- " temp += ATTRIB_extra4;\n"+
- " temp.xyz += ATTRIB_extra3;\n "+
- " temp.xy += ATTRIB_extra2;\n"+
- " temp.x += ATTRIB_extra1;\n"+
- " gl_Position = temp;\n"+
- "}";
-
- String simpleAttrSimpleUni = "void main() {\n"+
- " gl_Position = UNI_MATRIX * ATTRIB_position;\n"+
- "}";
-
- String multiAttrMultiUni = "void main() {\n"+
- " vec4 temp = UNI_MATRIX * ATTRIB_position;\n"+
- " temp = UNI_EXTRA * temp;\n"+
- " temp.xyz += ATTRIB_normal;\n"+
- " temp.xy += ATTRIB_texture0;\n"+
- " temp += UNI_extra4;\n"+
- " temp.xyz += UNI_extra3;\n "+
- " temp.xy += UNI_extra2;\n"+
- " temp.x += UNI_extra1;\n"+
- " gl_Position = temp;\n"+
- "}";
-
- // Create a series of shaders that do nothing useful
- // but exercise creation pipeline
- Element[] inputs = new Element[1];
- inputs[0] = mAttrPosElem;
- ProgramVertex pv = buildShader(inputs, null, simpleAttr);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- inputs[0] = mAttrPosNormTexElem;
- pv = buildShader(inputs, null, multiAttr);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- inputs[0] = mAttrExtra;
- pv = buildShader(inputs, null, multiAttr2);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- // Now with constant inputs
- Allocation[] constInput = new Allocation[1];
- inputs[0] = mAttrPosElem;
- constInput[0] = mConstMatrix;
- pv = buildShader(inputs, constInput, simpleAttrSimpleUni);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- inputs[0] = mAttrPosNormTexElem;
- constInput[0] = mConstComplex;
- pv = buildShader(inputs, constInput, multiAttrMultiUni);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- // Now with multiple input and const structs
- constInput = new Allocation[2];
- constInput[0] = mConstMatrix;
- constInput[1] = mConstExtra;
- inputs[0] = mAttrPosNormTexElem;
- pv = buildShader(inputs, constInput, multiAttrMultiUni);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- inputs = new Element[2];
- inputs[0] = mAttrPosElem;
- inputs[1] = mAttrNormTexElem;
- pv = buildShader(inputs, null, multiAttr);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
-
- constInput[0] = mConstMatrix;
- constInput[1] = mConstExtra;
- inputs[0] = mAttrPosElem;
- inputs[1] = mAttrNormTexElem;
- pv = buildShader(inputs, constInput, multiAttrMultiUni);
- if (testBind) {
- mScript.invoke_testProgramVertex(pv);
- mRS.bindProgramVertex(pv);
- }
- }
-
- public void testProgramVertexBuilder() {
- testProgramVertexBuilderHelper(false);
- }
-
- public void testProgramVertexCreation() {
- testProgramVertexBuilderHelper(true);
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java b/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
deleted file mode 100644
index 56838e1..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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;
-
-/**
- * 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
deleted file mode 100644
index 3278113..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/RSBaseCompute.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.renderscript.RenderScript;
-
-/**
- * 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
deleted file mode 100644
index 986a50d..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/RSBaseGraphics.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.renderscript.RenderScriptGL;
-import android.renderscript.RenderScriptGL.SurfaceConfig;
-
-/**
- * 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/RSSurfaceViewTest.java b/tests/tests/renderscript/src/android/renderscript/cts/RSSurfaceViewTest.java
deleted file mode 100644
index 9cf8f65..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/RSSurfaceViewTest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.renderscript.RSSurfaceView;
-import android.renderscript.RenderScriptGL;
-import android.renderscript.RenderScriptGL.SurfaceConfig;
-import android.util.AttributeSet;
-
-public class RSSurfaceViewTest extends RSBaseGraphics {
-
- public void testCreation() {
- RSSurfaceView view = new RSSurfaceView(mCtx);
- view = new RSSurfaceView(mCtx, null);
- }
-
- public void testCreateRenderScriptGL() {
- RSSurfaceView view = new RSSurfaceView(mCtx);
- RenderScriptGL rs = view.createRenderScriptGL(new SurfaceConfig());
- assertTrue(rs != null);
- }
-
- public void testGetSetRenderScriptGL() {
- RSSurfaceView view = new RSSurfaceView(mCtx);
- RenderScriptGL rs = view.createRenderScriptGL(new SurfaceConfig());
- assertTrue(rs != null);
- assertEquals(view.getRenderScriptGL(), rs);
-
- view = new RSSurfaceView(mCtx);
- view.setRenderScriptGL(mRS);
- assertEquals(view.getRenderScriptGL(), mRS);
- }
-
- public void testDestroyRenderScriptGL() {
- RSSurfaceView view = new RSSurfaceView(mCtx);
- RenderScriptGL rs = view.createRenderScriptGL(new SurfaceConfig());
- assertTrue(rs != null);
- view.destroyRenderScriptGL();
- assertTrue(view.getRenderScriptGL() == null);
- }
-
- public void testPauseResume() {
- RSSurfaceView view = new RSSurfaceView(mCtx);
- view.pause();
- view.resume();
-
- view.setRenderScriptGL(mRS);
- view.pause();
- view.resume();
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RenderScriptTest.java b/tests/tests/renderscript/src/android/renderscript/cts/RenderScriptTest.java
deleted file mode 100644
index 9e61526..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/RenderScriptTest.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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();
- }
-
- /**
- * Verify Priority enum properties.
- */
- public void testPriority() {
- assertEquals(RenderScript.Priority.LOW,
- RenderScript.Priority.valueOf("LOW"));
- assertEquals(RenderScript.Priority.NORMAL,
- RenderScript.Priority.valueOf("NORMAL"));
- assertEquals(2, RenderScript.Priority.values().length);
- }
-
- /**
- * Create a base RSMessageHandler object and run() it.
- * Note that most developers will subclass RSMessageHandler and use
- * their own non-empty implementation.
- */
- public void testRSMessageHandler() {
- RenderScript.RSMessageHandler mMH = new RenderScript.RSMessageHandler();
- mMH.run();
- }
-
- /**
- * Create a base RSErrorHandler object and run() it.
- * Note that most developers will subclass RSErrorHandler and use
- * their own non-empty implementation.
- */
- public void testRSErrorHandler() {
- RenderScript.RSErrorHandler mEH = new RenderScript.RSErrorHandler();
- mEH.run();
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/SamplerTest.java b/tests/tests/renderscript/src/android/renderscript/cts/SamplerTest.java
deleted file mode 100644
index 35e813e..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/SamplerTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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.renderscript.Sampler;
-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);
- }
-
- public void testSamplerValue() {
- assertEquals(Value.NEAREST, Value.valueOf("NEAREST"));
- assertEquals(Value.LINEAR, Value.valueOf("LINEAR"));
- assertEquals(Value.LINEAR_MIP_LINEAR, Value.valueOf("LINEAR_MIP_LINEAR"));
- assertEquals(Value.LINEAR_MIP_NEAREST, Value.valueOf("LINEAR_MIP_NEAREST"));
- assertEquals(Value.WRAP, Value.valueOf("WRAP"));
- assertEquals(Value.CLAMP, Value.valueOf("CLAMP"));
-
- // Make sure no new enums are added
- assertEquals(6, Value.values().length);
- }
-}
-
-
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ScriptCTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ScriptCTest.java
deleted file mode 100644
index 7f4ba93..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ScriptCTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.res.Resources;
-
-import android.renderscript.RenderScript;
-import android.renderscript.ScriptC;
-
-import com.android.cts.stub.R;
-
-public class ScriptCTest extends RSBaseCompute {
-
- class ScriptCHelper extends ScriptC {
- public ScriptCHelper(int id, RenderScript rs) {
- super(id, rs);
- }
-
- public ScriptCHelper(RenderScript rs,
- Resources resources,
- int resourceID) {
- super(rs, resources, resourceID);
- }
- }
-
- public void testScriptC() {
- // Test basic constructor
- ScriptCHelper h = new ScriptCHelper(0, mRS);
-
- // Test actual constructor
- h = new ScriptCHelper(mRS, mRes, R.raw.negate);
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ScriptTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ScriptTest.java
deleted file mode 100644
index 90b847a..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/ScriptTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.res.Resources;
-
-import android.renderscript.Allocation;
-import android.renderscript.Element;
-import android.renderscript.FieldPacker;
-import android.renderscript.RenderScript;
-import android.renderscript.Script;
-import android.renderscript.ScriptC;
-import android.renderscript.Type;
-
-import android.renderscript.cts.ScriptC_negate;
-
-import com.android.cts.stub.R;
-
-public class ScriptTest extends RSBaseCompute {
-
- public void testScript() {
- Script S = new ScriptC_primitives(mRS, mRes, R.raw.primitives);
-
- S.setTimeZone("America/New_York");
-
- S.setVar(4, 9.0f); // floatTest
- S.setVar(5, 9.0); // doubleTest
- S.setVar(6, 7); // charTest
- S.setVar(7, 300); // shortTest
- S.setVar(8, 20000); // intTest
- S.setVar(9, 20000000000l); // longTest
- S.setVar(11, true); // boolTest
-
- FieldPacker fp = new FieldPacker(4);
- fp.addI32(3);
- S.setVar(12, fp); // structTest
-
- Type.Builder tb = new Type.Builder(mRS, Element.I32(mRS));
- Allocation a = Allocation.createTyped(mRS, tb.create());
- S.setVar(13, a); // allocationTest
-
- S.bindAllocation(a, 14); // intPtrTest
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/StructPadTest.java b/tests/tests/renderscript/src/android/renderscript/cts/StructPadTest.java
deleted file mode 100644
index 884a0dc..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/StructPadTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.renderscript.Float4;
-
-public class StructPadTest extends RSBaseCompute {
- /**
- * Test for appropriate alignment/padding of structures.
- */
- public void testStructPadding() {
- ScriptField_PadMe S = new ScriptField_PadMe(mRS, 1);
- Float4 F4 = new Float4(1.0f, 2.0f, 3.0f, 4.0f);
-
- S.set_i(0, 7, true);
- S.set_f4(0, F4, true);
- S.set_j(0, 9, true);
-
- S.set(new ScriptField_PadMe.Item(), 0, true);
- }
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/SurfaceConfigTest.java b/tests/tests/renderscript/src/android/renderscript/cts/SurfaceConfigTest.java
deleted file mode 100644
index 94d784e..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/SurfaceConfigTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * 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.test.AndroidTestCase;
-
-import android.renderscript.RSIllegalArgumentException;
-import android.renderscript.RenderScriptGL.SurfaceConfig;
-
-public class SurfaceConfigTest extends AndroidTestCase {
-
- public void testSimpleCreate() {
- SurfaceConfig sc = new SurfaceConfig();
- }
-
- public void testSetColor() {
- SurfaceConfig sc = new SurfaceConfig();
- try {
- sc.setColor(-1, 8);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setColor(9, 8);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setColor(5, -1);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- sc.setColor(5, 8);
- sc = new SurfaceConfig();
- sc.setColor(8, 8);
- }
-
- public void testSetAlpha() {
- SurfaceConfig sc = new SurfaceConfig();
- try {
- sc.setAlpha(-1, 8);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setAlpha(9, 8);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setAlpha(0, -1);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- sc.setAlpha(0, 8);
- sc = new SurfaceConfig();
- sc.setAlpha(8, 8);
- }
-
- public void testSetDepth() {
- SurfaceConfig sc = new SurfaceConfig();
- try {
- sc.setDepth(-1, 8);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setDepth(45, 8);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setDepth(0, -1);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- sc.setDepth(0, 16);
- sc = new SurfaceConfig();
- sc.setDepth(16, 24);
- sc = new SurfaceConfig();
- sc.setDepth(24, 24);
- }
-
- public void testSetSamples() {
- SurfaceConfig sc = new SurfaceConfig();
- try {
- sc.setSamples(-1, 8, 1.0f);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setSamples(45, 8, 1.0f);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setSamples(1, -1, 1.0f);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setSamples(1, 1, -1.0f);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- try {
- sc.setSamples(1, 1, 10.0f);
- fail("should throw RSIllegalArgumentException.");
- } catch (RSIllegalArgumentException e) {
- }
- sc = new SurfaceConfig();
- sc.setSamples(1, 4, 1.0f);
- sc = new SurfaceConfig();
- sc.setSamples(4, 32, 1.0f);
- sc = new SurfaceConfig();
- sc.setSamples(4, 64, 0.5f);
- }
-
- public void testCopyConstructor() {
- SurfaceConfig sc = new SurfaceConfig();
- sc.setAlpha(1, 7);
- sc.setColor(5, 8);
- sc.setDepth(0, 16);
- sc.setSamples(1, 4, 0.71f);
- SurfaceConfig sc2 = new SurfaceConfig(sc);
- }
-
-}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/TypeTest.java b/tests/tests/renderscript/src/android/renderscript/cts/TypeTest.java
deleted file mode 100644
index 13d4977..0000000
--- a/tests/tests/renderscript/src/android/renderscript/cts/TypeTest.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * 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.renderscript.Element;
-import android.renderscript.Type;
-
-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);
- }
-
- public void testGetElement() {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- b.setX(1);
- assertTrue(b.create().getElement() == Element.F32(mRS));
- }
-
- public void testGetX() {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- b.setX(3);
- assertTrue(b.create().getX() == 3);
- }
-
- public void testGetY() {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- b.setX(3).setY(4);
- Type t = b.create();
- assertTrue(t.getX() == 3);
- assertTrue(t.getY() == 4);
- }
-
- public void testGetZ() {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- b.setX(3).setY(4);
- assertTrue(b.create().getZ() == 0);
- }
-
- public void testHasFaces() {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- b.setX(4).setY(4).setFaces(true);
- assertTrue(b.create().hasFaces());
- b.setFaces(false);
- assertFalse(b.create().hasFaces());
- }
-
- public void testGetMipmaps() {
- Type.Builder b = new Type.Builder(mRS, Element.F32(mRS));
- b.setX(4).setY(4).setMipmaps(true);
- assertTrue(b.create().hasMipmaps());
- b.setMipmaps(false);
- assertFalse(b.create().hasMipmaps());
- }
-
- public void testTypeCubemapFace() {
- assertEquals(Type.CubemapFace.NEGATIVE_X, Type.CubemapFace.valueOf("NEGATIVE_X"));
- assertEquals(Type.CubemapFace.NEGATIVE_Y, Type.CubemapFace.valueOf("NEGATIVE_Y"));
- assertEquals(Type.CubemapFace.NEGATIVE_Z, Type.CubemapFace.valueOf("NEGATIVE_Z"));
- assertEquals(Type.CubemapFace.POSITIVE_X, Type.CubemapFace.valueOf("POSITIVE_X"));
- assertEquals(Type.CubemapFace.POSITIVE_Y, Type.CubemapFace.valueOf("POSITIVE_Y"));
- assertEquals(Type.CubemapFace.POSITIVE_Z, Type.CubemapFace.valueOf("POSITIVE_Z"));
- // Legacy typo enums
- assertEquals(Type.CubemapFace.POSITVE_X, Type.CubemapFace.valueOf("POSITVE_X"));
- assertEquals(Type.CubemapFace.POSITVE_Y, Type.CubemapFace.valueOf("POSITVE_Y"));
- assertEquals(Type.CubemapFace.POSITVE_Z, Type.CubemapFace.valueOf("POSITVE_Z"));
- // Make sure no new enums are added
- assertEquals(9, Type.CubemapFace.values().length);
- }
-
- public void testEquals() {
- Type.Builder b1 = new Type.Builder(mRS, Element.F32(mRS));
- Type t1 = b1.setX(5).setY(5).create();
-
- Type.Builder b2 = new Type.Builder(mRS, Element.F32(mRS));
- Type t2 = b2.setX(5).setY(5).create();
-
- assertTrue(t1.equals(t2));
- assertTrue(t2.equals(t1));
- assertTrue(t1.hashCode() == t2.hashCode());
-
- t2 = b2.setX(4).create();
- assertFalse(t1.equals(t2));
- assertFalse(t2.equals(t1));
- }
-}
-
-
diff --git a/tests/tests/security/src/android/security/cts/BannedFilesTest.java b/tests/tests/security/src/android/security/cts/BannedFilesTest.java
deleted file mode 100644
index 017bac0..0000000
--- a/tests/tests/security/src/android/security/cts/BannedFilesTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.security.cts;
-
-import android.os.cts.FileUtils;
-
-import junit.framework.TestCase;
-
-public class BannedFilesTest extends TestCase {
-
- /**
- * setuid or setgid "ip" command can be used to modify the
- * routing tables of a device, potentially allowing a malicious
- * program to intercept all network traffic to and from
- * the device.
- */
- public void testNoSetuidIp() {
- assertNotSetugid("/system/bin/ip");
- assertNotSetugid("/system/xbin/ip");
- assertNotSetugid("/vendor/bin/ip");
- }
-
- /**
- * setuid or setgid tcpdump can be used maliciously to monitor
- * all traffic in and out of the device.
- */
- public void testNoSetuidTcpdump() {
- assertNotSetugid("/system/bin/tcpdump");
- assertNotSetugid("/system/bin/tcpdump-arm");
- assertNotSetugid("/system/xbin/tcpdump");
- assertNotSetugid("/system/xbin/tcpdump-arm");
- assertNotSetugid("/vendor/bin/tcpdump");
- assertNotSetugid("/vendor/bin/tcpdump-arm");
- }
-
- private static void assertNotSetugid(String file) {
- FileUtils.FileStatus fs = new FileUtils.FileStatus();
- if (!FileUtils.getFileStatus(file, fs, false)) {
- return;
- }
- assertTrue((fs.mode & FileUtils.S_ISUID) == 0);
- assertTrue((fs.mode & FileUtils.S_ISGID) == 0);
- }
-}
diff --git a/tests/tests/security/src/android/security/cts/BrowserTest.java b/tests/tests/security/src/android/security/cts/BrowserTest.java
deleted file mode 100644
index 7991933..0000000
--- a/tests/tests/security/src/android/security/cts/BrowserTest.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.security.cts;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.net.Uri;
-import android.test.AndroidTestCase;
-import android.webkit.cts.CtsTestServer;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Test for browsers which share state across multiple javascript intents.
- * Such browsers may be vulnerable to a data stealing attack.
- *
- * In particular, this test detects CVE-2011-2357. Patches for CVE-2011-2357
- * are available at:
- *
- * http://android.git.kernel.org/?p=platform/packages/apps/Browser.git;a=commit;h=afa4ab1e4c1d645e34bd408ce04cadfd2e5dae1e
- * http://android.git.kernel.org/?p=platform/packages/apps/Browser.git;a=commit;h=096bae248453abe83cbb2e5a2c744bd62cdb620b
- *
- * See also: http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-2357
- */
-public class BrowserTest extends AndroidTestCase {
- private CtsTestServer mWebServer;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mWebServer = new CtsTestServer(mContext);
- }
-
- @Override
- protected void tearDown() throws Exception {
- mWebServer.shutdown();
- super.tearDown();
- }
-
- /**
- * Verify that no state is preserved across multiple intents sent
- * to the browser when we reuse a browser tab.
- *
- * In this test, we send two intents to the Android browser. The first
- * intent sets document.b2 to 1. The second intent attempts to read
- * document.b2. If the read is successful, then state was preserved
- * across the two intents.
- *
- * If state is preserved across browser tabs, we ask
- * the browser to send an HTTP request to our local server.
- */
- public void testTabReuse() throws InterruptedException {
- List intents = getAllJavascriptIntents();
- for (Intent i : intents) {
- mContext.startActivity(i);
- mContext.startActivity(i);
-
- /*
- * Wait 5 seconds for the browser to contact the server, but
- * fail fast if we detect the bug
- */
- for (int j = 0; j < 5; j++) {
- assertEquals("javascript handler preserves state across "
- + "multiple intents. Vulnerable to CVE-2011-2357?",
- 0, mWebServer.getRequestCount());
- Thread.sleep(1000);
- }
- }
- }
-
- /**
- * Verify that no state is preserved across multiple intents sent
- * to the browser when we run out of usable browser tabs.
- *
- * In this test, we send 20 intents to the Android browser. Each
- * intent sets the variable "document.b1" equal to 1. If we are able
- * read document.b1 in subsequent invocations of the intent, then
- * we know state was preserved. In that case, we send a message
- * to the local server, recording this fact.
- *
- * Our test fails if the local server ever receives an HTTP request.
- */
- public void testTabExhaustion() throws InterruptedException {
- List intents = getAllJavascriptIntents();
- for (Intent i : intents) {
- i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
-
- /*
- * Send 20 intents. 20 is greater than the maximum number
- * of tabs allowed by the Android browser.
- */
- for (int j = 0; j < 20; j++) {
- mContext.startActivity(i);
- }
-
- /*
- * Wait 5 seconds for the browser to contact the server, but
- * fail fast if we detect the bug
- */
- for (int j = 0; j < 5; j++) {
- assertEquals("javascript handler preserves state across "
- + "multiple intents. Vulnerable to CVE-2011-2357?",
- 0, mWebServer.getRequestCount());
- Thread.sleep(1000);
- }
- }
- }
-
- /**
- * This method returns a List of explicit Intents for all programs
- * which handle javascript URIs.
- */
- private List getAllJavascriptIntents() {
- String localServerUri = mWebServer.getBaseUri();
- String varName = "document.b" + System.currentTimeMillis();
-
- /*
- * Build a javascript URL containing the following (without spaces and newlines)
- *
- * if (document.b12345 == 1) {
- * document.location = "http://localhost:1234/";
- * }
- * document.b12345 = 1;
- *
- */
- String javascript = "javascript:if(" + varName + "==1){"
- + "document.location=\"" + localServerUri + "\""
- + "};"
- + varName + "=1";
- Uri uri = Uri.parse(javascript);
-
- Intent implicit = new Intent(Intent.ACTION_VIEW);
- implicit.setData(uri);
-
- /* convert our implicit Intent into multiple explicit Intents */
- List retval = new ArrayList();
- PackageManager pm = mContext.getPackageManager();
- List list = pm.queryIntentActivities(implicit, PackageManager.GET_META_DATA);
- for (ResolveInfo i : list) {
- Intent explicit = new Intent(Intent.ACTION_VIEW);
- explicit.setClassName(i.activityInfo.packageName, i.activityInfo.name);
- explicit.setData(uri);
- explicit.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- retval.add(explicit);
- }
-
- return retval;
- }
-}
diff --git a/tests/tests/security/src/android/security/cts/CertificateData.java b/tests/tests/security/src/android/security/cts/CertificateData.java
deleted file mode 100644
index 85e5965..0000000
--- a/tests/tests/security/src/android/security/cts/CertificateData.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * 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.security.cts;
-
-/**
- * Run "./cts/tools/utils/java-cert-list-generator.sh >
- * cts/tests/tests/security/src/android/security/cts/CertificateData.java"
- * to generate this file.
- */
-class CertificateData {
- static final String[] CERTIFICATE_DATA = {
- "91:C6:D6:EE:3E:8A:C8:63:84:E5:48:C2:99:29:5C:75:6C:81:7B:81",
- "A4:34:89:15:9A:52:0F:0D:93:D0:32:CC:AF:37:E7:FE:20:A8:B4:19",
- "E7:B4:F6:9D:61:EC:90:69:DB:7E:90:A7:40:1A:3C:F4:7D:4F:E8:EE",
- "DD:E1:D2:A9:01:80:2E:1D:87:5E:84:B3:80:7E:4B:B1:FD:99:41:34",
- "92:5A:8F:8D:2C:6D:04:E0:66:5F:59:6A:FF:22:D8:63:E8:25:6F:3F",
- "75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE",
- "A9:62:8F:4B:98:A9:1B:48:35:BA:D2:C1:46:32:86:BB:66:64:6A:8C",
- "40:9D:4B:D9:17:B5:5C:27:B6:9B:64:CB:98:22:44:0D:CD:09:B8:89",
- "87:81:C2:5A:96:BD:C2:FB:4C:65:06:4F:F9:39:0B:26:04:8A:0E:01",
- "DA:C9:02:4F:54:D8:F6:DF:94:93:5F:B1:73:26:38:CA:6A:D7:7C:13",
- "74:20:74:41:72:9C:DD:92:EC:79:31:D8:23:10:8D:C2:81:92:E2:BB",
- "3C:71:D7:0E:35:A5:DA:A8:B2:E3:81:2D:C3:67:74:17:F5:99:0D:F3",
- "40:54:DA:6F:1C:3F:40:74:AC:ED:0F:EC:CD:DB:79:D1:53:FB:90:1D",
- "43:F9:B1:10:D5:BA:FD:48:22:52:31:B0:D0:08:2B:37:2F:EF:9A:54",
- "F4:8B:11:BF:DE:AB:BE:94:54:20:71:E6:41:DE:6B:BE:88:2B:40:B9",
- "96:56:CD:7B:57:96:98:95:D0:E1:41:46:68:06:FB:B8:C6:11:06:87",
- "D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD",
- "78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C",
- "27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4",
- "AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A",
- "8D:17:84:D5:37:F3:03:7D:EC:70:FE:57:8B:51:9A:99:E6:10:D7:B0",
- "AE:50:83:ED:7C:F4:5C:BC:8F:61:C6:21:FE:68:5D:79:42:21:15:6E",
- "5F:4E:1F:CF:31:B7:91:3B:85:0B:54:F6:E5:FF:50:1A:2B:6F:C6:CF",
- "74:F8:A3:C3:EF:E7:B3:90:06:4B:83:90:3C:21:64:60:20:E5:DF:CE",
- "85:B5:FF:67:9B:0C:79:96:1F:C8:6E:44:22:00:46:13:DB:17:92:84",
- "3E:2B:F7:F2:03:1B:96:F3:8C:E6:C4:D8:A8:5D:3E:2D:58:47:6A:0F",
- "5F:43:E5:B1:BF:F8:78:8C:AC:1C:C7:CA:4A:9A:C6:22:2B:CC:34:C6",
- "A8:98:5D:3A:65:E5:E5:C4:B2:D7:D6:6D:40:C6:DD:2F:B1:9C:54:36",
- "59:22:A1:E1:5A:EA:16:35:21:F8:98:39:6A:46:46:B0:44:1B:0F:A9",
- "D4:DE:20:D0:5E:66:FC:53:FE:1A:50:88:2C:78:DB:28:52:CA:E4:74",
- "02:FA:F3:E2:91:43:54:68:60:78:57:69:4D:F5:E4:5B:68:85:18:68",
- "D8:C5:38:8A:B7:30:1B:1B:6E:D4:7A:E6:45:25:3A:6F:9F:1A:27:61",
- "59:AF:82:79:91:86:C7:B4:75:07:CB:CF:03:57:46:EB:04:DD:B7:16",
- "50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31",
- "1B:4B:39:61:26:27:6B:64:91:A2:68:6D:D7:02:43:21:2D:1F:1D:96",
- "8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4",
- "56:E0:FA:C0:3B:8F:18:23:55:18:E5:D3:11:CA:E8:C2:43:31:AB:66",
- "02:72:68:29:3E:5F:5D:17:AA:A4:B3:C3:E6:36:1E:1F:92:57:5E:AA",
- "97:81:79:50:D8:1C:96:70:CC:34:D8:09:CF:79:44:31:36:7E:F4:74",
- "85:A4:08:C0:9C:19:3E:5D:51:58:7D:CD:D6:13:30:FD:8C:DE:37:BF",
- "58:11:9F:0E:12:82:87:EA:50:FD:D9:87:45:6F:4F:78:DC:FA:D6:D4",
- "6B:2F:34:AD:89:58:BE:62:FD:B0:6B:5C:CE:BB:9D:D9:4F:4E:39:F3",
- "9B:AA:E5:9F:56:EE:21:CB:43:5A:BE:25:93:DF:A7:F0:40:D1:1D:CB",
- "36:79:CA:35:66:87:72:30:4D:30:A5:FB:87:3B:0F:A7:7B:B7:0D:54",
- "B4:35:D4:E1:11:9D:1C:66:90:A7:49:EB:B3:94:BD:63:7B:A7:82:B7",
- "A9:E9:78:08:14:37:58:88:F2:05:19:B0:6D:2B:0D:2B:60:16:90:7D",
- "60:D6:89:74:B5:C2:65:9E:8A:0F:C1:88:7C:88:D2:46:69:1B:18:2C",
- "D2:32:09:AD:23:D3:14:23:21:74:E4:0D:7F:9D:62:13:97:86:63:3A",
- "66:31:BF:9E:F7:4F:9E:B6:C9:D5:A6:0C:BA:6A:BE:D1:F7:BD:EF:7B",
- "87:9F:4B:EE:05:DF:98:58:3B:E3:60:D6:33:E7:0D:3F:FE:98:71:AF",
- "DE:3F:40:BD:50:93:D3:9B:6C:60:F6:DA:BC:07:62:01:00:89:76:C9",
- "22:D5:D8:DF:8F:02:31:D1:8D:F7:9D:B7:CF:8A:2D:64:C9:3F:6C:3A",
- "06:08:3F:59:3F:15:A1:04:A0:69:A4:6B:A9:03:D0:06:B7:97:09:91",
- "E3:92:51:2F:0A:CF:F5:05:DF:F6:DE:06:7F:75:37:E1:65:EA:57:4B",
- "F1:8B:53:8D:1B:E9:03:B6:A6:F0:56:43:5B:17:15:89:CA:F3:6B:F2",
- "05:63:B8:63:0D:62:D7:5A:BB:C8:AB:1E:4B:DF:B5:A8:99:B2:4D:43",
- "93:E6:AB:22:03:03:B5:23:28:DC:DA:56:9E:BA:E4:D1:D1:CC:FB:65",
- "62:52:DC:40:F7:11:43:A2:2F:DE:9E:F7:34:8E:06:42:51:B1:81:18",
- "70:17:9B:86:8C:00:A4:FA:60:91:52:22:3F:9F:3E:32:BD:E0:05:62",
- "A0:A1:AB:90:C9:FC:84:7B:3B:12:61:E8:97:7D:5F:D3:22:61:D3:CC",
- "85:37:1C:A6:E5:50:14:3D:CE:28:03:47:1B:DE:3A:09:E8:F8:77:0F",
- "7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45",
- "D1:EB:23:A4:6D:17:D6:8F:D9:25:64:C2:F1:F1:60:17:64:D8:E3:49",
- "A1:DB:63:93:91:6F:17:E4:18:55:09:40:04:15:C7:02:40:B0:AE:6B",
- "B8:01:86:D1:EB:9C:86:A5:41:04:CF:30:54:F3:4C:52:B7:E5:58:C6",
- "DE:28:F4:A4:FF:E5:B9:2F:A3:C5:03:D1:A3:49:A7:F9:96:2A:82:12",
- "80:25:EF:F4:6E:70:C8:D4:72:24:65:84:FE:40:3B:8A:8D:6A:DB:F5",
- "CA:3A:FB:CF:12:40:36:4B:44:B2:16:20:88:80:48:39:19:93:7C:F7",
- "69:BD:8C:F4:9C:D3:00:FB:59:2E:17:93:CA:55:6A:F3:EC:AA:35:FB",
- "13:2D:0D:45:53:4B:69:97:CD:B2:D5:C3:39:E2:55:76:60:9B:5C:C6",
- "5F:B7:EE:06:33:E2:59:DB:AD:0C:4C:9A:E6:D3:8F:1A:61:C7:DC:25",
- "25:01:90:19:CF:FB:D9:99:1C:B7:68:25:74:8D:94:5F:30:93:95:42",
- "79:98:A3:08:E1:4D:65:85:E6:C2:1E:15:3A:71:9F:BA:5A:D3:4A:D9",
- "B5:1C:06:7C:EE:2B:0C:3D:F8:55:AB:2D:92:F4:FE:39:D4:E7:0F:0E",
- "37:9A:19:7B:41:85:45:35:0C:A6:03:69:F3:3C:2E:AF:47:4F:20:79",
- "FA:B7:EE:36:97:26:62:FB:2D:B0:2A:F6:BF:03:FD:E8:7C:4B:2F:9B",
- "8B:AF:4C:9B:1D:F0:2A:92:F7:DA:12:8E:B9:1B:AC:F4:98:60:4B:6F",
- "9F:74:4E:9F:2B:4D:BA:EC:0F:31:2C:50:B6:56:3B:8E:2D:93:C3:11",
- "39:4F:F6:85:0B:06:BE:52:E5:18:56:CC:10:E1:80:E8:82:B3:85:CC",
- "1F:49:14:F7:D8:74:95:1D:DD:AE:02:C0:BE:FD:3A:2D:82:75:51:85",
- "07:E0:32:E0:20:B7:2C:3F:19:2F:06:28:A2:59:3A:19:A7:0F:06:9E",
- "D6:DA:A8:20:8D:09:D2:15:4D:24:B5:2F:CB:34:6E:B2:58:B2:8A:58",
- "32:3C:11:8E:1B:F7:B8:B6:52:54:E2:E2:10:0D:D6:02:90:37:F0:96",
- "67:65:0D:F1:7E:8E:7E:5B:82:40:A4:F4:56:4B:CF:E2:3D:69:C6:F0",
- "FE:B8:C4:32:DC:F9:76:9A:CE:AE:3D:D8:90:8F:FD:28:86:65:64:7D",
- "4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C",
- "33:9B:6B:14:50:24:9B:55:7A:01:87:72:84:D9:E0:2F:C3:D2:D8:E9",
- "AB:48:F3:33:DB:04:AB:B9:C0:72:DA:5B:0C:C1:D0:57:F0:36:9B:46",
- "36:B1:2B:49:F9:81:9E:D7:4C:9E:BC:38:0F:C6:56:8F:5D:AC:B2:F7",
- "37:F7:6D:E6:07:7C:90:C5:B1:3E:93:1A:B7:41:10:B4:F2:E4:9A:27",
- "AA:DB:BC:22:23:8F:C4:01:A1:27:BB:38:DD:F4:1D:DB:08:9E:F0:12",
- "3B:C4:9F:48:F8:F3:73:A0:9C:1E:BD:F8:5B:B1:C3:65:C7:D8:11:B3",
- "AC:ED:5F:65:53:FD:25:CE:01:5F:1F:7A:48:3B:6A:74:9F:61:78:C6",
- "B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C",
- "CF:9E:87:6D:D3:EB:FC:42:26:97:A3:B5:A3:7A:A0:76:A9:06:23:48",
- "47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B",
- "31:7A:2A:D0:7F:2B:33:5E:F5:A1:C3:4E:4B:57:E8:B7:D8:F1:FC:A6",
- "39:21:C1:15:C1:5D:0E:CA:5C:CB:5B:C4:F0:7D:21:D8:05:0B:56:6A",
- "3A:44:73:5A:E5:81:90:1F:24:86:61:46:1E:3B:9C:C4:5F:F5:3A:1B",
- "B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9",
- "81:96:8B:3A:EF:1C:DC:70:F5:FA:32:69:C2:92:A3:63:5B:D1:23:D3",
- "62:7F:8D:78:27:65:63:99:D2:7D:7F:90:44:C9:FE:B3:F3:3E:FA:9A",
- "C8:EC:8C:87:92:69:CB:4B:AB:39:E9:8D:7E:57:67:F3:14:95:73:9D",
- "03:9E:ED:B8:0B:E7:A0:3C:69:53:89:3B:20:D2:D9:32:3A:4C:2A:FD",
- "CB:A1:C5:F8:B0:E3:5E:B8:B9:45:12:D3:F9:34:A2:E9:06:10:D3:36",
- "B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB",
- "10:1D:FA:3F:D5:0B:CB:BB:9B:B5:60:0C:19:55:A4:1A:F4:73:3A:04",
- "87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11",
- "AE:C5:FB:3F:C8:E1:BF:C4:E5:4F:03:07:5A:9A:E8:00:B7:F7:B6:FA",
- "21:FC:BD:8E:7F:6C:AF:05:1B:D1:B3:43:EC:A8:E7:61:47:F2:0F:8A",
- "2A:C8:D5:8B:57:CE:BF:2F:49:AF:F2:FC:76:8F:51:14:62:90:7A:41",
- "CA:BB:51:67:24:00:58:8E:64:19:F1:D4:08:78:D0:40:3A:A2:02:64",
- "5D:98:9C:DB:15:96:11:36:51:65:64:1B:56:0F:DB:EA:2A:C2:3E:F1",
- "23:E5:94:94:51:95:F2:41:48:03:B4:D5:64:D2:A3:A3:F5:D8:8B:8C",
- "5F:3A:FC:0A:8B:64:F6:86:67:34:74:DF:7E:A9:A2:FE:F9:FA:7A:51",
- "E6:21:F3:35:43:79:05:9A:4B:68:30:9D:8A:2F:74:22:15:87:EC:79",
- "DA:40:18:8B:91:89:A3:ED:EE:AE:DA:97:FE:2F:9D:F5:B7:D1:8A:41",
- "89:DF:74:FE:5C:F4:0F:4A:80:F9:E3:37:7D:54:DA:91:E1:01:31:8E",
- "E0:B4:32:2E:B2:F6:A5:68:B6:54:53:84:48:18:4A:50:36:87:43:84",
- "61:57:3A:11:DF:0E:D8:7E:D5:92:65:22:EA:D0:56:D7:44:B3:23:71",
- "0B:77:BE:BB:CB:7A:A2:47:05:DE:CC:0F:BD:6A:02:FC:7A:BD:9B:52",
- "99:A6:9B:E6:1A:FE:88:6B:4D:2B:82:00:7C:B8:54:FC:31:7E:15:39",
- "6E:3A:55:A4:19:0C:19:5C:93:84:3C:C0:DB:72:2E:31:30:61:F0:B1",
- "E5:DF:74:3C:B6:01:C4:9B:98:43:DC:AB:8C:E8:6A:81:10:9F:E4:8E",
- "F9:CD:0E:2C:DA:76:24:C1:8F:BD:F0:F0:AB:B6:45:B8:F7:FE:D5:7A",
- "23:88:C9:D3:71:CC:9E:96:3D:FF:7D:3C:A7:CE:FC:D6:25:EC:19:0D",
- "8C:96:BA:EB:DD:2B:07:07:48:EE:30:32:66:A0:F3:98:6E:7C:AE:58",
- "7F:8A:B0:CF:D0:51:87:6A:66:F3:36:0F:47:C8:8D:8C:D3:35:FC:74",
- "4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5",
- "B1:2E:13:63:45:86:A4:6F:1A:B2:60:68:37:58:2D:C4:AC:FD:94:97",
- "04:83:ED:33:99:AC:36:08:05:87:22:ED:BC:5E:46:00:E3:BE:F9:D7",
- };
-}
diff --git a/tests/tests/security/src/android/security/cts/CertificateTest.java b/tests/tests/security/src/android/security/cts/CertificateTest.java
deleted file mode 100644
index 844621b..0000000
--- a/tests/tests/security/src/android/security/cts/CertificateTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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.security.cts;
-
-import android.test.AndroidTestCase;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class CertificateTest extends AndroidTestCase {
-
- public void testCertificates() throws Exception {
- Set expectedCertificates = getExpectedCertificates();
- Set deviceCertificates = getDeviceCertificates();
- expectedCertificates.removeAll(deviceCertificates);
- assertTrue("Missing certificates: " + expectedCertificates, expectedCertificates.isEmpty());
- }
-
- public void testBlockCertificates() throws Exception {
- Set blockCertificates = new HashSet();
- blockCertificates.add("C0:60:ED:44:CB:D8:81:BD:0E:F8:6C:0B:A2:87:DD:CF:81:67:47:8C");
-
- Set deviceCertificates = getDeviceCertificates();
- deviceCertificates.retainAll(blockCertificates);
- assertTrue("Blocked certificates: " + deviceCertificates, deviceCertificates.isEmpty());
- }
-
- private Set getExpectedCertificates() {
- Set certificates = new HashSet();
- for (int i = 0; i < CertificateData.CERTIFICATE_DATA.length; i++) {
- certificates.add(CertificateData.CERTIFICATE_DATA[i]);
- }
- return certificates;
- }
-
- private Set getDeviceCertificates() throws KeyStoreException,
- NoSuchAlgorithmException, CertificateException, IOException {
- KeyStore keyStore = KeyStore.getInstance("AndroidCAStore");
- keyStore.load(null, null);
-
- List aliases = Collections.list(keyStore.aliases());
- assertFalse(aliases.isEmpty());
-
- Set certificates = new HashSet();
- for (String alias : aliases) {
- assertTrue(keyStore.isCertificateEntry(alias));
- X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
- assertEquals(certificate.getSubjectUniqueID(), certificate.getIssuerUniqueID());
- assertNotNull(certificate.getSubjectDN());
- assertNotNull(certificate.getIssuerDN());
- String fingerprint = getFingerprint(certificate);
- certificates.add(fingerprint);
- }
- return certificates;
- }
-
- private String getFingerprint(X509Certificate certificate) throws CertificateEncodingException,
- NoSuchAlgorithmException {
- MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
- messageDigest.update(certificate.getEncoded());
- byte[] sha1 = messageDigest.digest();
- return convertToHexFingerprint(sha1);
- }
-
- private String convertToHexFingerprint(byte[] sha1) {
- StringBuilder fingerprint = new StringBuilder();
- for (int i = 0; i < sha1.length; i++) {
- fingerprint.append(String.format("%02X", sha1[i]));
- if (i + 1 < sha1.length) {
- fingerprint.append(":");
- }
- }
- return fingerprint.toString();
- }
-}
diff --git a/tests/tests/security/src/android/security/cts/PackageSignatureTest.java b/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
index 3822035..cff19af 100644
--- a/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
+++ b/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
@@ -31,7 +31,6 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -72,25 +71,11 @@ public class PackageSignatureTest extends AndroidTestCase {
return wellKnownSignatures;
}
- private static final Set WHITELISTED_PACKAGES = new HashSet(Arrays.asList(
- // The accessibility APK required to be installed while running CTS
- "android.accessibilityservice.delegate",
-
- // The device management APK required to be installed while running CTS
- "android.deviceadmin.cts",
-
- // APK for an activity that collects information printed in the CTS report header
- "android.tests.devicesetup",
-
- // APK for the Android core tests runner used only during CTS
- "android.core.tests.runner"
- ));
-
private boolean isWhitelistedPackage(String packageName) {
// Don't check the signatures of CTS test packages on the device.
// devicesetup is the APK CTS loads to collect information needed in the final report
return packageName.startsWith("com.android.cts")
- || WHITELISTED_PACKAGES.contains(packageName);
+ || packageName.equalsIgnoreCase("android.tests.devicesetup");
}
private static final int DEFAULT_BUFFER_BYTES = 1024 * 4;
diff --git a/tests/tests/security/src/android/security/cts/VoldExploitTest.java b/tests/tests/security/src/android/security/cts/VoldExploitTest.java
index 1f0929f..38eece7 100644
--- a/tests/tests/security/src/android/security/cts/VoldExploitTest.java
+++ b/tests/tests/security/src/android/security/cts/VoldExploitTest.java
@@ -56,6 +56,12 @@ public class VoldExploitTest extends TestCase {
return;
}
+ // Verify that all processes listening for netlink messages
+ // currently exist.
+ for (int i : pids) {
+ assertTrue(new File("/proc/" + i + "/cmdline").exists());
+ }
+
NetlinkSocket ns = NetlinkSocket.create();
for (int i : pids) {
for (String j : devices) {
@@ -109,9 +115,6 @@ public class VoldExploitTest extends TestCase {
private static Set getSysFsPath(String file) throws IOException {
Set retval = new HashSet();
File netlink = new File(file);
- if (!netlink.canRead()) {
- return retval;
- }
Scanner scanner = null;
try {
scanner = new Scanner(netlink);
@@ -169,7 +172,7 @@ public class VoldExploitTest extends TestCase {
for (List i : netlink) {
// The PID is in column 3
int pid = Integer.decode(i.get(2));
- if (new File("/proc/" + pid + "/cmdline").exists()) {
+ if (pid > 0) {
retval.add(pid);
}
}
diff --git a/tests/tests/speech/Android.mk b/tests/tests/speech/Android.mk
index 932c564..a15b2ec 100755
--- a/tests/tests/speech/Android.mk
+++ b/tests/tests/speech/Android.mk
@@ -29,7 +29,5 @@ LOCAL_PACKAGE_NAME := CtsSpeechTestCases
LOCAL_SDK_VERSION := current
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
include $(BUILD_PACKAGE)
diff --git a/tests/tests/speech/AndroidManifest.xml b/tests/tests/speech/AndroidManifest.xml
index 778f763..6e1e528 100755
--- a/tests/tests/speech/AndroidManifest.xml
+++ b/tests/tests/speech/AndroidManifest.xml
@@ -24,8 +24,9 @@
-
+
diff --git a/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechServiceTest.java b/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechServiceTest.java
deleted file mode 100644
index c19f6c0..0000000
--- a/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechServiceTest.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.speech.tts.cts;
-
-import android.os.Environment;
-import android.speech.tts.TextToSpeech;
-import android.test.AndroidTestCase;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.util.HashMap;
-
-/**
- * Tests for {@link android.speech.tts.TextToSpeechService} using StubTextToSpeechService.
- */
-public class TextToSpeechServiceTest extends AndroidTestCase {
-
- private static final String UTTERANCE_ID = "utterance";
- private static final String UTTERANCE = "text to speech cts test";
- private static final String SAMPLE_FILE_NAME = "mytts.wav";
-
- private TextToSpeechWrapper mTts;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mTts = TextToSpeechWrapper.createTextToSpeechMockWrapper(getContext());
- assertNotNull(mTts);
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- mTts.shutdown();
- }
-
- private TextToSpeech getTts() {
- return mTts.getTts();
- }
-
- public void testSynthesizeToFile() throws Exception {
- File sampleFile = new File(Environment.getExternalStorageDirectory(), SAMPLE_FILE_NAME);
- try {
- assertFalse(sampleFile.exists());
-
- int result = getTts().synthesizeToFile(UTTERANCE, createParams(), sampleFile.getPath());
- assertEquals("synthesizeToFile() failed", TextToSpeech.SUCCESS, result);
-
- assertTrue("synthesizeToFile() completion timeout", mTts.waitForComplete(UTTERANCE_ID));
- assertTrue("synthesizeToFile() didn't produce a file", sampleFile.exists());
- assertTrue("synthesizeToFile() produced a non-sound file",
- TextToSpeechWrapper.isSoundFile(sampleFile.getPath()));
- } finally {
- sampleFile.delete();
- }
- }
-
- public void testSpeak() throws Exception {
- int result = getTts().speak(UTTERANCE, TextToSpeech.QUEUE_FLUSH, createParams());
- assertEquals("speak() failed", TextToSpeech.SUCCESS, result);
- assertTrue("speak() completion timeout", waitForUtterance());
- }
-
- public void testMediaPlayerFails() throws Exception {
- File sampleFile = new File(Environment.getExternalStorageDirectory(), "notsound.wav");
- try {
- assertFalse(TextToSpeechWrapper.isSoundFile(sampleFile.getPath()));
- FileOutputStream out = new FileOutputStream(sampleFile);
- out.write(new byte[] { 0x01, 0x02 });
- out.close();
- assertFalse(TextToSpeechWrapper.isSoundFile(sampleFile.getPath()));
- } finally {
- sampleFile.delete();
- }
- }
-
- private HashMap createParams() {
- HashMap params = new HashMap();
- params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, UTTERANCE_ID);
- return params;
- }
-
- private boolean waitForUtterance() throws InterruptedException {
- return mTts.waitForComplete(UTTERANCE_ID);
- }
-
-}
diff --git a/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechTest.java b/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechTest.java
index 799fd8d..e012fe3 100644
--- a/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechTest.java
+++ b/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechTest.java
@@ -15,31 +15,98 @@
*/
package android.speech.tts.cts;
+import dalvik.annotation.TestTargetClass;
+
+import android.media.MediaPlayer;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
+import android.speech.tts.TextToSpeech.OnInitListener;
+import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.test.AndroidTestCase;
+import android.util.Log;
import java.io.File;
import java.util.HashMap;
-import java.util.List;
import java.util.Locale;
/**
* Tests for {@link android.speech.tts.TextToSpeech}
*/
+@TestTargetClass(TextToSpeech.class)
public class TextToSpeechTest extends AndroidTestCase {
- private static final String UTTERANCE_ID = "utterance";
+ private TextToSpeech mTts;
+
+ private static final String UTTERANCE = "utterance";
private static final String SAMPLE_TEXT = "This is a sample text to speech string";
private static final String SAMPLE_FILE_NAME = "mytts.wav";
+ /** maximum time to wait for tts to be initialized */
+ private static final int TTS_INIT_MAX_WAIT_TIME = 30 * 1000;
+ /** maximum time to wait for speech call to be complete */
+ private static final int TTS_SPEECH_MAX_WAIT_TIME = 5 * 1000;
+ private static final String LOG_TAG = "TextToSpeechTest";
+
+ /**
+ * Listener for waiting for TTS engine initialization completion.
+ */
+ private static class InitWaitListener implements OnInitListener {
+ private int mStatus = TextToSpeech.ERROR;
+
+ public void onInit(int status) {
+ mStatus = status;
+ synchronized(this) {
+ notify();
+ }
+ }
+
+ public boolean waitForInit() throws InterruptedException {
+ if (mStatus == TextToSpeech.SUCCESS) {
+ return true;
+ }
+ synchronized (this) {
+ wait(TTS_INIT_MAX_WAIT_TIME);
+ }
+ return mStatus == TextToSpeech.SUCCESS;
+ }
+ }
+
+ /**
+ * Listener for waiting for utterance completion.
+ */
+ private static class UtteranceWaitListener implements OnUtteranceCompletedListener {
+ private boolean mIsComplete = false;
+ private final String mExpectedUtterance;
- private TextToSpeechWrapper mTts;
+ public UtteranceWaitListener(String expectedUtteranceId) {
+ mExpectedUtterance = expectedUtteranceId;
+ }
+
+ public void onUtteranceCompleted(String utteranceId) {
+ if (mExpectedUtterance.equals(utteranceId)) {
+ synchronized(this) {
+ mIsComplete = true;
+ notify();
+ }
+ }
+ }
+
+ public boolean waitForComplete() throws InterruptedException {
+ if (mIsComplete) {
+ return true;
+ }
+ synchronized (this) {
+ wait(TTS_SPEECH_MAX_WAIT_TIME);
+ return mIsComplete;
+ }
+ }
+ }
@Override
protected void setUp() throws Exception {
super.setUp();
- mTts = TextToSpeechWrapper.createTextToSpeechWrapper(getContext());
- assertNotNull(mTts);
+ InitWaitListener listener = new InitWaitListener();
+ mTts = new TextToSpeech(getContext(), listener);
+ assertTrue(listener.waitForInit());
assertTrue(checkAndSetLanguageAvailable());
}
@@ -49,92 +116,76 @@ public class TextToSpeechTest extends AndroidTestCase {
mTts.shutdown();
}
- private TextToSpeech getTts() {
- return mTts.getTts();
- }
-
/**
* Ensures at least one language is available for tts
*/
- private boolean checkAndSetLanguageAvailable() {
+ private boolean checkAndSetLanguageAvailable() {
// checks if at least one language is available in Tts
- final Locale defaultLocale = Locale.getDefault();
- // If the language for the default locale is available, then
- // use that.
- int defaultAvailability = getTts().isLanguageAvailable(defaultLocale);
-
- if (defaultAvailability == TextToSpeech.LANG_AVAILABLE ||
- defaultAvailability == TextToSpeech.LANG_COUNTRY_AVAILABLE ||
- defaultAvailability == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE) {
- getTts().setLanguage(defaultLocale);
- return true;
- }
-
for (Locale locale : Locale.getAvailableLocales()) {
- int availability = getTts().isLanguageAvailable(locale);
+ int availability = mTts.isLanguageAvailable(locale);
if (availability == TextToSpeech.LANG_AVAILABLE ||
availability == TextToSpeech.LANG_COUNTRY_AVAILABLE ||
availability == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE) {
- getTts().setLanguage(locale);
+ mTts.setLanguage(locale);
return true;
}
}
return false;
}
+ /**
+ * Tests that {@link TextToSpeech#synthesizeToFile(String, java.util.HashMap, String)} produces
+ * a non-zero sized file.
+ * @throws InterruptedException
+ */
public void testSynthesizeToFile() throws Exception {
File sampleFile = new File(Environment.getExternalStorageDirectory(), SAMPLE_FILE_NAME);
try {
assertFalse(sampleFile.exists());
+ // use an utterance listener to determine when synthesizing is complete
+ HashMap param = new HashMap();
+ param.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, UTTERANCE);
+ UtteranceWaitListener listener = new UtteranceWaitListener(UTTERANCE);
+ mTts.setOnUtteranceCompletedListener(listener);
+
+ int result = mTts.synthesizeToFile(SAMPLE_TEXT, param, sampleFile.getPath());
+ assertEquals(TextToSpeech.SUCCESS, result);
- int result = getTts().synthesizeToFile(SAMPLE_TEXT, createParams(),
- sampleFile.getPath());
- assertEquals("synthesizeToFile() failed", TextToSpeech.SUCCESS, result);
+ assertTrue(listener.waitForComplete());
+ assertTrue(sampleFile.exists());
+ assertTrue(isMusicFile(sampleFile.getPath()));
- assertTrue("synthesizeToFile() completion timeout", waitForUtterance());
- assertTrue("synthesizeToFile() didn't produce a file", sampleFile.exists());
- assertTrue("synthesizeToFile() produced a non-sound file",
- TextToSpeechWrapper.isSoundFile(sampleFile.getPath()));
} finally {
- sampleFile.delete();
+ deleteFile(sampleFile);
}
}
- public void testSpeak() throws Exception {
- int result = getTts().speak(SAMPLE_TEXT, TextToSpeech.QUEUE_FLUSH, createParams());
- assertEquals("speak() failed", TextToSpeech.SUCCESS, result);
- assertTrue("speak() completion timeout", waitForUtterance());
- }
-
- public void testGetEnginesIncludesDefault() throws Exception {
- List engines = getTts().getEngines();
- assertNotNull("getEngines() returned null", engines);
- assertContainsEngine(getTts().getDefaultEngine(), engines);
- }
-
- public void testGetEnginesIncludesMock() throws Exception {
- List engines = getTts().getEngines();
- assertNotNull("getEngines() returned null", engines);
- assertContainsEngine(TextToSpeechWrapper.MOCK_TTS_ENGINE, engines);
- }
-
- private void assertContainsEngine(String engine, List engines) {
- for (TextToSpeech.EngineInfo engineInfo : engines) {
- if (engineInfo.name.equals(engine)) {
- return;
- }
+ /**
+ * Determine if given file path is a valid, playable music file.
+ */
+ private boolean isMusicFile(String filePath) {
+ // use media player to play the file. If it succeeds with no exceptions, assume file is
+ //valid
+ try {
+ MediaPlayer mp = new MediaPlayer();
+ mp.setDataSource(filePath);
+ mp.prepare();
+ mp.start();
+ mp.stop();
+ return true;
+ } catch (Exception e) {
+ Log.e(LOG_TAG, "Exception while attempting to play music file", e);
+ return false;
}
- fail("Engine " + engine + " not found");
}
- private HashMap createParams() {
- HashMap params = new HashMap();
- params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, UTTERANCE_ID);
- return params;
- }
-
- private boolean waitForUtterance() throws InterruptedException {
- return mTts.waitForComplete(UTTERANCE_ID);
+ /**
+ * Deletes the file at given path
+ * @param sampleFilePath
+ */
+ private void deleteFile(File file) {
+ if (file != null && file.exists()) {
+ file.delete();
+ }
}
-
}
diff --git a/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechWrapper.java b/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechWrapper.java
deleted file mode 100644
index cba242f..0000000
--- a/tests/tests/speech/src/android/speech/tts/cts/TextToSpeechWrapper.java
+++ /dev/null
@@ -1,199 +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.speech.tts.cts;
-
-import android.content.Context;
-import android.media.MediaPlayer;
-import android.speech.tts.TextToSpeech;
-import android.speech.tts.TextToSpeech.OnInitListener;
-import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
-import android.util.Log;
-
-import java.util.HashSet;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * Wrapper for {@link TextToSpeech} with some handy test functionality.
- */
-public class TextToSpeechWrapper {
- private static final String LOG_TAG = "TextToSpeechServiceTest";
-
- public static final String MOCK_TTS_ENGINE = "com.android.cts.stub";
-
- private final Context mContext;
- private TextToSpeech mTts;
- private final InitWaitListener mInitListener;
- private final UtteranceWaitListener mUtteranceListener;
-
- /** maximum time to wait for tts to be initialized */
- private static final int TTS_INIT_MAX_WAIT_TIME = 30 * 1000;
- /** maximum time to wait for speech call to be complete */
- private static final int TTS_SPEECH_MAX_WAIT_TIME = 5 * 1000;
-
- private TextToSpeechWrapper(Context context) {
- mContext = context;
- mInitListener = new InitWaitListener();
- mUtteranceListener = new UtteranceWaitListener();
- }
-
- private boolean initTts() throws InterruptedException {
- return initTts(new TextToSpeech(mContext, mInitListener));
- }
-
- private boolean initTts(String engine) throws InterruptedException {
- return initTts(new TextToSpeech(mContext, mInitListener, engine));
- }
-
- private boolean initTts(TextToSpeech tts) throws InterruptedException {
- mTts = tts;
- if (!mInitListener.waitForInit()) {
- return false;
- }
- mTts.setOnUtteranceCompletedListener(mUtteranceListener);
- return true;
- }
-
- public boolean waitForComplete(String utteranceId) throws InterruptedException {
- return mUtteranceListener.waitForComplete(utteranceId);
- }
-
- public TextToSpeech getTts() {
- return mTts;
- }
-
- public void shutdown() {
- mTts.shutdown();
- }
-
- public static TextToSpeechWrapper createTextToSpeechWrapper(Context context)
- throws InterruptedException {
- TextToSpeechWrapper wrapper = new TextToSpeechWrapper(context);
- if (wrapper.initTts()) {
- return wrapper;
- } else {
- return null;
- }
- }
-
- public static TextToSpeechWrapper createTextToSpeechMockWrapper(Context context)
- throws InterruptedException {
- TextToSpeechWrapper wrapper = new TextToSpeechWrapper(context);
- if (wrapper.initTts(MOCK_TTS_ENGINE)) {
- return wrapper;
- } else {
- return null;
- }
- }
-
- /**
- * Listener for waiting for TTS engine initialization completion.
- */
- private static class InitWaitListener implements OnInitListener {
- private final Lock mLock = new ReentrantLock();
- private final Condition mDone = mLock.newCondition();
- private Integer mStatus = null;
-
- public void onInit(int status) {
- mLock.lock();
- try {
- mStatus = new Integer(status);
- mDone.signal();
- } finally {
- mLock.unlock();
- }
- }
-
- public boolean waitForInit() throws InterruptedException {
- long timeOutNanos = TimeUnit.MILLISECONDS.toNanos(TTS_INIT_MAX_WAIT_TIME);
- mLock.lock();
- try {
- while (mStatus == null) {
- if (timeOutNanos <= 0) {
- return false;
- }
- timeOutNanos = mDone.awaitNanos(timeOutNanos);
- }
- return mStatus == TextToSpeech.SUCCESS;
- } finally {
- mLock.unlock();
- }
- }
- }
-
- /**
- * Listener for waiting for utterance completion.
- */
- private static class UtteranceWaitListener implements OnUtteranceCompletedListener {
- private final Lock mLock = new ReentrantLock();
- private final Condition mDone = mLock.newCondition();
- private final HashSet mCompletedUtterances = new HashSet();
-
- public void onUtteranceCompleted(String utteranceId) {
- mLock.lock();
- try {
- mCompletedUtterances.add(utteranceId);
- mDone.signal();
- } finally {
- mLock.unlock();
- }
- }
-
- public boolean waitForComplete(String utteranceId)
- throws InterruptedException {
- long timeOutNanos = TimeUnit.MILLISECONDS.toNanos(TTS_INIT_MAX_WAIT_TIME);
- mLock.lock();
- try {
- while (!mCompletedUtterances.remove(utteranceId)) {
- if (timeOutNanos <= 0) {
- return false;
- }
- timeOutNanos = mDone.awaitNanos(timeOutNanos);
- }
- return true;
- } finally {
- mLock.unlock();
- }
- }
- }
-
- /**
- * Determines if given file path is a valid, playable music file.
- */
- public static boolean isSoundFile(String filePath) {
- // use media player to play the file. If it succeeds with no exceptions, assume file is
- //valid
- MediaPlayer mp = null;
- try {
- mp = new MediaPlayer();
- mp.setDataSource(filePath);
- mp.prepare();
- mp.start();
- mp.stop();
- return true;
- } catch (Exception e) {
- Log.e(LOG_TAG, "Exception while attempting to play music file", e);
- return false;
- } finally {
- if (mp != null) {
- mp.release();
- }
- }
- }
-
-}
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
index 7ea9612..44af455 100755
--- a/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
@@ -31,8 +31,6 @@ import android.os.SystemClock;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
-import android.telephony.SmsMessage;
-import android.os.Bundle;
import java.util.ArrayList;
import java.util.Arrays;
@@ -56,7 +54,6 @@ public class SmsManagerTest extends AndroidTestCase {
private static final String SMS_SEND_ACTION = "CTS_SMS_SEND_ACTION";
private static final String SMS_DELIVERY_ACTION = "CTS_SMS_DELIVERY_ACTION";
- private static final String DATA_SMS_RECEIVED_ACTION = "android.intent.action.DATA_SMS_RECEIVED";
// List of network operators that don't support SMS delivery report
private static final List NO_DELIVERY_REPORTS =
@@ -77,39 +74,21 @@ public class SmsManagerTest extends AndroidTestCase {
"44073", // KDDI
"44074", // KDDI
"44075", // KDDI
- "44076", // KDDI
- "311870", // Boost Mobile
- "311220", // USCC
- "302720", // Rogers
- "30272", // Rogers
- "302370", // Fido
- "30237", // Fido
- "311490", // Virgin Mobile
- "310000" // Tracfone
+ "44076" // KDDI
);
// List of network operators that doesn't support Data(binary) SMS message
private static final List UNSUPPORT_DATA_SMS_MESSAGES =
Arrays.asList(
"44010", // NTT DOCOMO
- "44020", // SBM
- "302720", // Rogers
- "30272", // Rogers
- "302370", // Fido
- "30237", // Fido
- "45008" // KT
+ "44020" // SBM
);
// List of network operators that doesn't support Maltipart SMS message
private static final List UNSUPPORT_MULTIPART_SMS_MESSAGES =
Arrays.asList(
"44010", // NTT DOCOMO
- "44020", // SBM
- "302720", // Rogers
- "30272", // Rogers
- "302370", // Fido
- "30237", // Fido
- "45008" // KT
+ "44020" // SBM
);
private TelephonyManager mTelephonyManager;
@@ -118,14 +97,11 @@ public class SmsManagerTest extends AndroidTestCase {
private String mText;
private SmsBroadcastReceiver mSendReceiver;
private SmsBroadcastReceiver mDeliveryReceiver;
- private SmsBroadcastReceiver mDataSmsReceiver;
private PendingIntent mSentIntent;
private PendingIntent mDeliveredIntent;
private Intent mSendIntent;
private Intent mDeliveryIntent;
private boolean mDeliveryReportSupported;
- private static boolean mReceivedDataSms;
- private static String mReceivedText;
private static final int TIME_OUT = 1000 * 60 * 5;
@@ -191,17 +167,12 @@ public class SmsManagerTest extends AndroidTestCase {
IntentFilter sendIntentFilter = new IntentFilter(SMS_SEND_ACTION);
IntentFilter deliveryIntentFilter = new IntentFilter(SMS_DELIVERY_ACTION);
- IntentFilter dataSmsReceivedIntentFilter = new IntentFilter(DATA_SMS_RECEIVED_ACTION);
- dataSmsReceivedIntentFilter.addDataScheme("sms");
- dataSmsReceivedIntentFilter.addDataAuthority("localhost", "19989");
mSendReceiver = new SmsBroadcastReceiver(SMS_SEND_ACTION);
mDeliveryReceiver = new SmsBroadcastReceiver(SMS_DELIVERY_ACTION);
- mDataSmsReceiver = new SmsBroadcastReceiver(DATA_SMS_RECEIVED_ACTION);
getContext().registerReceiver(mSendReceiver, sendIntentFilter);
getContext().registerReceiver(mDeliveryReceiver, deliveryIntentFilter);
- getContext().registerReceiver(mDataSmsReceiver, dataSmsReceivedIntentFilter);
// send single text sms
init();
@@ -227,9 +198,6 @@ public class SmsManagerTest extends AndroidTestCase {
if (mDeliveryReportSupported) {
assertTrue(mDeliveryReceiver.waitForCalls(1, TIME_OUT));
}
- mDataSmsReceiver.waitForCalls(1, TIME_OUT);
- assertTrue(mReceivedDataSms);
- assertEquals(mReceivedText, mText);
} else {
// This GSM network doesn't support Data(binary) SMS message.
// Skip the test.
@@ -260,8 +228,6 @@ public class SmsManagerTest extends AndroidTestCase {
private void init() {
mSendReceiver.reset();
mDeliveryReceiver.reset();
- mDataSmsReceiver.reset();
- mReceivedDataSms = false;
mSentIntent = PendingIntent.getBroadcast(getContext(), 0, mSendIntent,
PendingIntent.FLAG_ONE_SHOT);
mDeliveredIntent = PendingIntent.getBroadcast(getContext(), 0, mDeliveryIntent,
@@ -317,25 +283,6 @@ public class SmsManagerTest extends AndroidTestCase {
@Override
public void onReceive(Context context, Intent intent) {
- if(mAction.equals(DATA_SMS_RECEIVED_ACTION)){
- StringBuilder sb = new StringBuilder();
- Bundle bundle = intent.getExtras();
- if (bundle != null) {
- Object[] obj = (Object[]) bundle.get("pdus");
- SmsMessage[] message = new SmsMessage[obj.length];
- for (int i = 0; i < obj.length; i++) {
- message[i] = SmsMessage.createFromPdu((byte[]) obj[i]);
- }
-
- for (SmsMessage currentMessage : message) {
- byte[] binaryContent = currentMessage.getUserData();
- String readableContent = new String(binaryContent);
- sb.append(readableContent);
- }
- }
- mReceivedDataSms = true;
- mReceivedText=sb.toString();
- }
if (intent.getAction().equals(mAction)) {
synchronized (mLock) {
mCalls += 1;
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
index 8c6ad01..515f8b5 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
@@ -22,7 +22,6 @@ import dalvik.annotation.TestTargetNew;
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;
@@ -31,7 +30,6 @@ import android.test.AndroidTestCase;
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[^~\\] }";
@@ -71,7 +69,7 @@ public class SmsMessageTest extends AndroidTestCase{
super.setUp();
mTelephonyManager =
(TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
- mPackageManager = getContext().getPackageManager();
+ assertNotNull(mTelephonyManager);
}
@SuppressWarnings("deprecation")
@@ -173,12 +171,10 @@ public class SmsMessageTest extends AndroidTestCase{
)
})
public void testCreateFromPdu() throws Exception {
- if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
- || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
+ 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());
@@ -258,8 +254,7 @@ public class SmsMessageTest extends AndroidTestCase{
)
})
public void testCPHSVoiceMail() throws Exception {
- if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
- || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
+ if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
// TODO: temp workaround, need to adjust test to use CDMA pdus
return;
}
@@ -307,8 +302,7 @@ public class SmsMessageTest extends AndroidTestCase{
)
})
public void testGetUserData() throws Exception {
- if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
- || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
+ if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
// TODO: temp workaround, need to adjust test to use CDMA pdus
return;
}
@@ -337,10 +331,6 @@ public class SmsMessageTest extends AndroidTestCase{
)
})
public void testGetSubmitPdu() throws Exception {
- if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
- return;
- }
-
String scAddress = null, destinationAddress = null;
String message = null;
boolean statusReportRequested = false;
@@ -413,12 +403,10 @@ public class SmsMessageTest extends AndroidTestCase{
)
})
public void testEmailGateway() throws Exception {
- if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
- || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
+ if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_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 645eb81..6e8aa27 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -296,6 +296,7 @@ public class TelephonyManagerTest extends AndroidTestCase {
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
new file mode 100644
index 0000000..8b26880
--- /dev/null
+++ b/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java
@@ -0,0 +1,468 @@
+/*
+ * 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 60bac35..4c305bb 100644
--- a/tests/tests/text/src/android/text/cts/LayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/LayoutTest.java
@@ -21,7 +21,12 @@ import dalvik.annotation.TestTargetClass;
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;
@@ -77,6 +82,53 @@ public class LayoutTest extends AndroidTestCase {
@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 = {}
)
@@ -228,6 +280,66 @@ public class LayoutTest extends AndroidTestCase {
@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}
)
@@ -256,6 +368,23 @@ public class LayoutTest extends AndroidTestCase {
@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}
)
@@ -321,6 +450,84 @@ public class LayoutTest extends AndroidTestCase {
@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 4fc3386..11ba854 100644
--- a/tests/tests/text/src/android/text/cts/SelectionTest.java
+++ b/tests/tests/text/src/android/text/cts/SelectionTest.java
@@ -16,16 +16,15 @@
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 {
@@ -107,6 +106,12 @@ public class SelectionTest extends AndroidTestCase {
fail("should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
}
+
+ try {
+ Selection.setSelection(null, 3, 6);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
}
@TestTargetNew(
@@ -140,6 +145,12 @@ public class SelectionTest extends AndroidTestCase {
fail("should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
}
+
+ try {
+ Selection.setSelection(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
}
@TestTargetNew(
@@ -147,6 +158,7 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -164,6 +176,12 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -171,6 +189,7 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -195,6 +214,12 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -202,6 +227,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -209,6 +236,12 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -227,6 +260,24 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -234,6 +285,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -241,6 +294,12 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -263,6 +322,24 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -270,6 +347,7 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -302,6 +380,14 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -309,6 +395,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -316,6 +404,12 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -339,6 +433,18 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -346,6 +452,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -397,6 +505,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -404,6 +514,12 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -421,6 +537,24 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -428,6 +562,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -435,6 +571,12 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -448,6 +590,24 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -455,6 +615,7 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -479,6 +640,18 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -490,6 +663,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -497,6 +672,12 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -509,6 +690,24 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -516,6 +715,7 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -542,6 +742,18 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -556,6 +768,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -580,6 +794,24 @@ public class SelectionTest extends AndroidTestCase {
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(
@@ -587,6 +819,7 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -612,6 +845,18 @@ public class SelectionTest extends AndroidTestCase {
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));
@@ -623,6 +868,8 @@ public class SelectionTest extends AndroidTestCase {
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);
@@ -647,5 +894,23 @@ public class SelectionTest extends AndroidTestCase {
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 f8b4336..26ebfb5 100644
--- a/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
+++ b/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
@@ -16,12 +16,6 @@
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;
@@ -30,6 +24,11 @@ import android.text.Spanned;
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}.
@@ -251,28 +250,6 @@ public class SpannableStringBuilderTest extends AndroidTestCase {
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/StaticLayoutTest.java b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
index a806e0a..f0f9627 100644
--- a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
@@ -19,7 +19,6 @@ package android.text.cts;
import android.test.AndroidTestCase;
import android.text.Editable;
import android.text.StaticLayout;
-import android.text.TextDirectionHeuristics;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.Layout.Alignment;
@@ -44,8 +43,6 @@ public class StaticLayoutTest extends AndroidTestCase {
private static final CharSequence LAYOUT_TEXT = "CharSe\tq\nChar"
+ "Sequence\nCharSequence\nHelllo\n, world\nLongLongLong";
- private static final CharSequence LAYOUT_TEXT_SINGLE_LINE = "CharSequence";
-
private static final int VERTICAL_BELOW_TEXT = 1000;
private static final Alignment DEFAULT_ALIGN = Alignment.ALIGN_CENTER;
@@ -77,19 +74,6 @@ public class StaticLayoutTest extends AndroidTestCase {
TextUtils.TruncateAt.MIDDLE, ELLIPSIZE_WIDTH);
}
- private StaticLayout createEllipsizeStaticLayout(CharSequence text,
- TextUtils.TruncateAt ellipsize, int maxLines) {
- return new StaticLayout(text, 0, text.length(),
- mDefaultPaint, DEFAULT_OUTER_WIDTH, DEFAULT_ALIGN,
- TextDirectionHeuristics.FIRSTSTRONG_LTR,
- SPACE_MULTI, SPACE_ADD, true /* include pad */,
- ellipsize,
- ELLIPSIZE_WIDTH,
- maxLines);
- }
-
-
-
/**
* Constructor test
*/
@@ -378,17 +362,9 @@ public class StaticLayoutTest extends AndroidTestCase {
@ToBeFixed(bug = "1695243", explanation = "should add @throws clause into javadoc "
+ " of StaticLayout#getEllipsisCount(int) when line is out of bound")
public void testGetEllipsisCount() {
- // Multilines (6 lines) and TruncateAt.START so no ellipsis at all
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT,
- TextUtils.TruncateAt.MIDDLE,
- Integer.MAX_VALUE /* maxLines */);
-
- assertTrue(mDefaultLayout.getEllipsisCount(0) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(1) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(2) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(3) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(4) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(5) == 0);
+ mDefaultLayout = createEllipsizeStaticLayout();
+ assertTrue(mDefaultLayout.getEllipsisCount(0) > 0);
+ assertTrue(mDefaultLayout.getEllipsisCount(1) > 0);
try {
mDefaultLayout.getEllipsisCount(-1);
@@ -401,66 +377,6 @@ public class StaticLayoutTest extends AndroidTestCase {
fail("should throw ArrayIndexOutOfBoundsException");
} catch (ArrayIndexOutOfBoundsException e) {
}
-
- // Multilines (6 lines) and TruncateAt.MIDDLE so no ellipsis at all
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT,
- TextUtils.TruncateAt.MIDDLE,
- Integer.MAX_VALUE /* maxLines */);
-
- assertTrue(mDefaultLayout.getEllipsisCount(0) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(1) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(2) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(3) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(4) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(5) == 0);
-
- // Multilines (6 lines) and TruncateAt.END so ellipsis only on the last line
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT,
- TextUtils.TruncateAt.END,
- Integer.MAX_VALUE /* maxLines */);
-
- assertTrue(mDefaultLayout.getEllipsisCount(0) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(1) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(2) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(3) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(4) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(5) > 0);
-
- // Multilines (6 lines) and TruncateAt.MARQUEE so ellipsis only on the last line
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT,
- TextUtils.TruncateAt.END,
- Integer.MAX_VALUE /* maxLines */);
-
- assertTrue(mDefaultLayout.getEllipsisCount(0) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(1) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(2) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(3) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(4) == 0);
- assertTrue(mDefaultLayout.getEllipsisCount(5) > 0);
-
- // Single line case and TruncateAt.END so that we have some ellipsis
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT_SINGLE_LINE,
- TextUtils.TruncateAt.END,
- 1);
- assertTrue(mDefaultLayout.getEllipsisCount(0) > 0);
-
- // Single line case and TruncateAt.MIDDLE so that we have some ellipsis
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT_SINGLE_LINE,
- TextUtils.TruncateAt.MIDDLE,
- 1);
- assertTrue(mDefaultLayout.getEllipsisCount(0) > 0);
-
- // Single line case and TruncateAt.END so that we have some ellipsis
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT_SINGLE_LINE,
- TextUtils.TruncateAt.END,
- 1);
- assertTrue(mDefaultLayout.getEllipsisCount(0) > 0);
-
- // Single line case and TruncateAt.MARQUEE so that we have NO ellipsis
- mDefaultLayout = createEllipsizeStaticLayout(LAYOUT_TEXT_SINGLE_LINE,
- TextUtils.TruncateAt.MARQUEE,
- 1);
- assertTrue(mDefaultLayout.getEllipsisCount(0) == 0);
}
/*
diff --git a/tests/tests/text/src/android/text/cts/TextUtilsTest.java b/tests/tests/text/src/android/text/cts/TextUtilsTest.java
index 99f4f40..0b274f5 100755
--- a/tests/tests/text/src/android/text/cts/TextUtilsTest.java
+++ b/tests/tests/text/src/android/text/cts/TextUtilsTest.java
@@ -139,6 +139,14 @@ public class TextUtilsTest extends AndroidTestCase {
} 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(
@@ -357,11 +365,11 @@ public class TextUtilsTest extends AndroidTestCase {
" 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");
@@ -383,14 +391,16 @@ public class TextUtilsTest extends AndroidTestCase {
TextUtils.ellipsize(text, p, textWidth, TruncateAt.MARQUEE).toString());
textWidth = p.measureText(mEllipsis);
- assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.END).toString());
+ assertEquals(mEllipsis, 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("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.START).toString());
- assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.MIDDLE).toString());
+ assertEquals(mEllipsis,
+ TextUtils.ellipsize(text, p, textWidth, TruncateAt.START).toString());
+ assertEquals(mEllipsis,
+ TextUtils.ellipsize(text, p, textWidth, TruncateAt.MIDDLE).toString());
try {
TextUtils.ellipsize(text, null, textWidth, TruncateAt.MIDDLE);
@@ -426,7 +436,7 @@ public class TextUtilsTest extends AndroidTestCase {
// 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;
@@ -513,14 +523,14 @@ public class TextUtilsTest extends AndroidTestCase {
// avail is long enough for ELLIPSIS, and preserveLength is specified.
resetRange();
- assertEquals(getBlankString(false, text.length()),
+ assertEquals(getBlankString(true, 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("",
+ assertEquals(mEllipsis,
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 5d92a18..37b337f 100644
--- a/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
+++ b/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
@@ -32,7 +32,6 @@ import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
-import java.util.TimeZone;
@TestTargetClass(DateFormat.class)
public class DateFormatTest extends AndroidTestCase {
@@ -175,29 +174,4 @@ public class DateFormatTest extends AndroidTestCase {
actual = DateFormat.format(format, formatDate.getTime());
assertEquals(expectedString, actual.toString());
}
-
- @TestTargetNew(level = TestLevel.ADDITIONAL)
- public void test2038() {
- Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+00:00"));
-
- 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 9e773cb..6d034b9 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,32 +302,4 @@ public class DateUtilsTest extends AndroidTestCase {
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/format/cts/TimeTest.java b/tests/tests/text/src/android/text/format/cts/TimeTest.java
index 0fb3f2a..a8f2acd 100644
--- a/tests/tests/text/src/android/text/format/cts/TimeTest.java
+++ b/tests/tests/text/src/android/text/format/cts/TimeTest.java
@@ -584,31 +584,6 @@ public class TimeTest extends AndroidTestCase {
assertTrue(Time.compare(a, a) == 0);
}
- public void testCompareNullFailure() throws Exception {
- Time a = new Time(Time.TIMEZONE_UTC);
-
- try {
- Time.compare(a, null);
- fail("Should throw NullPointerException on second argument");
- } catch (NullPointerException e) {
- // pass
- }
-
- try {
- Time.compare(null, a);
- fail("Should throw NullPointerException on first argument");
- } catch (NullPointerException e) {
- // pass
- }
-
- try {
- Time.compare(null, null);
- fail("Should throw NullPointerException because both args are null");
- } catch (NullPointerException e) {
- // pass
- }
- }
-
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "format",
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 ba2bcdd..1d6c109 100644
--- a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
@@ -70,6 +70,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
mArrowKeyMovementMethod = new ArrowKeyMovementMethod();
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
@@ -196,6 +197,8 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
+ "document about the behaviour of this method.")
public void testOnTakeFoucusWithNullLayout() {
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
+
assertSelectEndOfContent();
}
@@ -211,6 +214,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
+ "Spannable, int)} when the params view or text is null")
public void testOnTakeFocusWithNullParameters() {
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
try {
mArrowKeyMovementMethod.onTakeFocus(null, mEditable, View.FOCUS_DOWN);
fail("The method did not throw NullPointerException when param textView is null.");
@@ -243,8 +247,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_UP)));
+ KeyEvent.KEYCODE_DPAD_UP, null));
// |first line
// second |line
// last line
@@ -253,8 +256,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_UP)));
+ KeyEvent.KEYCODE_DPAD_UP, null));
// first lin|e
// second |line
// last line
@@ -265,8 +267,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_UP)));
+ KeyEvent.KEYCODE_DPAD_UP, null));
// |first line
// second |line
// last line
@@ -275,8 +276,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_UP)));
+ KeyEvent.KEYCODE_DPAD_UP, null));
// |first line
// second line
// last line
@@ -285,16 +285,14 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_UP)));
+ KeyEvent.KEYCODE_DPAD_UP, null));
// first lin|e
// second line
// last line
assertSelection(correspondingIn1stLine);
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_UP)));
+ KeyEvent.KEYCODE_DPAD_UP, null));
// first lin|e
// second line
// last line
@@ -318,8 +316,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_DOWN)));
+ KeyEvent.KEYCODE_DPAD_DOWN, null));
// first line
// second |line
// last line|
@@ -328,8 +325,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_DOWN)));
+ KeyEvent.KEYCODE_DPAD_DOWN, null));
// first line
// second |line
// last lin|e
@@ -340,8 +336,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_DOWN)));
+ KeyEvent.KEYCODE_DPAD_DOWN, null));
// first line
// second |line
// last line|
@@ -350,8 +345,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_DOWN)));
+ KeyEvent.KEYCODE_DPAD_DOWN, null));
// first line
// second line
// last line|
@@ -360,16 +354,14 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_DOWN)));
+ KeyEvent.KEYCODE_DPAD_DOWN, null));
// first line
// second line
// last lin|e
assertSelection(correspondingIn3rdLine);
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_DOWN)));
+ KeyEvent.KEYCODE_DPAD_DOWN, null));
// first line
// second line
// last lin|e
@@ -393,8 +385,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// |second |line
// last line
@@ -402,8 +393,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// |second |line
// last line
@@ -412,8 +402,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// second| |line
// last line
@@ -421,8 +410,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// secon|d |line
// last line
@@ -431,8 +419,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// |second line
// last line
@@ -440,8 +427,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// |second line
// last line
@@ -450,8 +436,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line
// second| line
// last line
@@ -462,8 +447,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
// |second line
// last line
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT)));
+ KeyEvent.KEYCODE_DPAD_LEFT, null));
// first line|
// second line
// last line
@@ -487,8 +471,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second |line|
// last line
@@ -496,8 +479,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressBothShiftAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second |line|
// last line
@@ -506,8 +488,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second |l|ine
// last line
@@ -515,8 +496,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressShift();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second |li|ne
// last line
@@ -525,8 +505,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second line|
// last line
@@ -534,8 +513,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressAlt();
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second line|
// last line
@@ -544,8 +522,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
MetaKeyKeyListener.resetMetaState(mEditable);
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second l|ine
// last line
@@ -556,8 +533,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
// second line|
// last line
assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT)));
+ KeyEvent.KEYCODE_DPAD_RIGHT, null));
// first line
// second line
// |last line
@@ -576,6 +552,8 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
+ "Spannable, int, KeyEvent)} when the view does not get layout")
public void testOnKeyDownWithNullLayout() {
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
+
try {
mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable, KeyEvent.KEYCODE_DPAD_RIGHT,
null);
@@ -646,15 +624,43 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_DPAD_CENTER, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_CENTER)));
+ KeyEvent.KEYCODE_DPAD_CENTER, null));
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_0, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_0)));
+ KeyEvent.KEYCODE_0, null));
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_E, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E)));
+ KeyEvent.KEYCODE_E, null));
assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
- KeyEvent.KEYCODE_UNKNOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_UNKNOWN)));
+ 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
+ }
}
@TestTargetNew(
@@ -692,6 +698,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
+ "Spannable, MotionEvent)} when the view does not get layout")
public void testOnTouchEventWithNullLayout() {
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
mTextView.setFocusable(true);
mTextView.requestFocus();
assertTrue(mTextView.isFocused());
@@ -731,6 +738,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
+ "Spannable, MotionEvent)} when the params view, buffer or event is null")
public void testOnTouchEventWithNullParameters() {
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
try {
mArrowKeyMovementMethod.onTouchEvent(null, mEditable,
MotionEvent.obtain(0, 0, 0, 1, 1, 0));
@@ -804,6 +812,7 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
MotionEvent.obtain(0, 0, 0, 1, 1, 0)));
initTextViewWithNullLayout();
+ mEditable = (Editable) mTextView.getText();
assertFalse(mArrowKeyMovementMethod.onTrackballEvent(mTextView, mEditable,
MotionEvent.obtain(0, 0, 0, 1, 1, 0)));
@@ -837,411 +846,10 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
assertFalse(method.onKeyUp(view, spannable, KeyEvent.KEYCODE_0, null));
}
- private static final String TEXT_WORDS =
- "Lorem ipsum; dolor sit \u00e4met, conse\u0ca0_\u0ca0ctetur? Adipiscing"
- + ".elit.integ\u00e9r. Etiam tristique\ntortor nec ?:? \n\n"
- + "lectus porta consequ\u00e4t... LOReM iPSuM";
-
- @UiThreadTest
- public void testFollowingWordStartToEnd() {
-
- // NOTE: there seems to be much variation in how word boundaries are
- // navigated; the behaviors asserted here were derived from Google
- // Chrome 10.0.648.133 beta.
-
- initTextViewWithNullLayout(TEXT_WORDS);
-
- // |Lorem ipsum; dolor sit $met,
- Selection.setSelection(mEditable, 0);
- assertSelection(0);
-
- // Lorem| ipsum; dolor sit $met,
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(5);
-
- // Lorem ipsum|; dolor sit $met,
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(11);
-
- // Lorem ipsum; dolor| sit $met,
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(18);
-
- // Lorem ipsum; dolor sit| $met,
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(22);
-
- // $met|, conse$_$ctetur$ Adipiscing.elit.integ$r.
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(27);
-
- // $met, conse$_$ctetur|$ Adipiscing.elit.integ$r.
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(43);
-
- // TODO: enable these two additional word breaks when implemented
-// // $met, conse$_$ctetur$ Adipiscing|.elit.integ$r.
-// assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
-// assertSelection(61);
-//
-// // $met, conse$_$ctetur$ Adipiscing.elit|.integ$r.
-// assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
-// assertSelection(66);
-
- // $met, conse$_$ctetur$ Adipiscing.elit.integ$r|.
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(74);
-
- // integ$r. Etiam| tristique$tortor nec ?:? $$lectus porta
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(81);
-
- // integ$r. Etiam tristique|$tortor nec ?:? $$lectus porta
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(94);
-
- // integ$r. Etiam tristique$tortor| nec ?:? $$lectus porta
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(101);
-
- // integ$r. Etiam tristique$tortor nec| ?:? $$lectus porta
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(105);
-
- // integ$r. Etiam tristique$tortor nec ?:? $$lectus| porta
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(123);
-
- // $$lectus porta| consequ$t... LOReM iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(129);
-
- // $$lectus porta consequ$t|... LOReM iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(139);
-
- // $$lectus porta consequ$t... LOReM| iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(149);
-
- // $$lectus porta consequ$t... LOReM iPSuM|
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(155);
-
- // keep trying to push beyond end, which should fail
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(155);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(155);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(155);
-
- }
-
- @UiThreadTest
- public void testPrecedingWordEndToStart() {
-
- // NOTE: there seems to be much variation in how word boundaries are
- // navigated; the behaviors asserted here were derived from Google
- // Chrome 10.0.648.133 beta.
-
- initTextViewWithNullLayout(TEXT_WORDS);
-
- // $$lectus porta consequ$t... LOReM iPSuM|
- Selection.setSelection(mEditable, mEditable.length());
- assertSelection(155);
-
- // $$lectus porta consequ$t... LOReM |iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(150);
-
- // $$lectus porta consequ$t... |LOReM iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(144);
-
- // $$lectus porta |consequ$t... LOReM iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(130);
-
- // $$lectus |porta consequ$t... LOReM iPSuM
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(124);
-
- // integ$r. Etiam tristique$tortor nec ?:? $$|lectus
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(117);
-
- // integ$r. Etiam tristique$tortor |nec ?:? $$lectus
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(102);
-
- // integ$r. Etiam tristique$|tortor nec ?:? $$lectus
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(95);
-
- // integ$r. Etiam |tristique$tortor nec ?:? $$lectus
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(85);
-
- // integ$r. |Etiam tristique$tortor nec ?:? $$lectus
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(76);
-
- // TODO: enable these two additional word breaks when implemented
-// // dolor sit $met, conse$_$ctetur$ Adipiscing.elit.|integ$r.
-// assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
-// assertSelection(67);
-//
-// // dolor sit $met, conse$_$ctetur$ Adipiscing.|elit.integ$r.
-// assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
-// assertSelection(62);
-
- // dolor sit $met, conse$_$ctetur$ |Adipiscing.elit.integ$r.
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(51);
-
- // dolor sit $met, |conse$_$ctetur$ Adipiscing.elit.integ$r.
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(29);
-
- // dolor sit |$met, conse$_$ctetur$ Adipiscing.elit.integ$r.
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(23);
-
- // Lorem ipsum; dolor |sit $met
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(19);
-
- // Lorem ipsum; |dolor sit $met
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(13);
-
- // Lorem |ipsum; dolor sit $met
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(6);
-
- // |Lorem ipsum; dolor sit $met
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
-
- // keep trying to push before beginning, which should fail
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
-
- }
-
- private static final String TEXT_WORDS_WITH_NUMBERS =
- "Lorem ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4";
-
- @UiThreadTest
- public void testFollowingWordStartToEndWithNumbers() {
-
- initTextViewWithNullLayout(TEXT_WORDS_WITH_NUMBERS);
-
- // |Lorem ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4
- Selection.setSelection(mEditable, 0);
- assertSelection(0);
-
- // Lorem| ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(5);
-
- // Lorem ipsum123,456.90| dolor sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(21);
-
- // Lorem ipsum123,456.90 dolor| sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(29);
-
- // Lorem ipsum123,456.90 dolor sit|.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(33);
-
- // Lorem ipsum123,456.90 dolor sit.. 4|-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(37);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-0.0|=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(41);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-0.0=2| ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(43);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4|
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(55);
-
- // keep trying to push beyond end, which should fail
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(55);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(55);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(55);
-
- }
-
- @UiThreadTest
- public void testFollowingWordEndToStartWithNumbers() {
-
- initTextViewWithNullLayout(TEXT_WORDS_WITH_NUMBERS);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4|
- Selection.setSelection(mEditable, mEditable.length());
- assertSelection(55);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-0.0=2 |ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(44);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-0.0=|2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(42);
-
- // Lorem ipsum123,456.90 dolor sit.. 4-|0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(38);
-
- // Lorem ipsum123,456.90 dolor sit.. |4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(36);
-
- // Lorem ipsum123,456.90 dolor |sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(30);
-
- // Lorem ipsum123,456.90 |dolor sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(24);
-
- // Lorem |ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(6);
-
- // |Lorem ipsum123,456.90 dolor sit.. 4-0.0=2 ADipiscing4
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
-
- // keep trying to push before beginning, which should fail
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
-
- }
-
- private static final String TEXT_WORDS_WITH_1CHAR_FINAL_WORD = "abc d";
-
- @UiThreadTest
- public void testFollowingWordStartToEndWithOneCharFinalWord() {
-
- initTextViewWithNullLayout(TEXT_WORDS_WITH_1CHAR_FINAL_WORD);
-
- // |abc d
- Selection.setSelection(mEditable, 0);
- assertSelection(0);
-
- // abc| d
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(3);
-
- // abc d|
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(mEditable.length());
-
- }
-
- @UiThreadTest
- public void testFollowingWordEndToStartWithOneCharFinalWord() {
-
- initTextViewWithNullLayout(TEXT_WORDS_WITH_1CHAR_FINAL_WORD);
-
- // abc d|
- Selection.setSelection(mEditable, mEditable.length());
- assertSelection(5);
-
- // abc |d
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(4);
-
- // |abc d
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(0);
-
- }
-
- @UiThreadTest
- public void testMovementFromMiddleOfWord() {
-
- initTextViewWithNullLayout("before word after");
- checkMoveFromInsideWord(7, 10);
-
- // Surrogate characters: bairkan should be considered as a standard letter
- final String BAIRKAN = "\uD800\uDF31";
-
- initTextViewWithNullLayout("before wo" + BAIRKAN + "rd after");
- checkMoveFromInsideWord(7, 12);
-
- initTextViewWithNullLayout("before " + BAIRKAN + BAIRKAN + "xx after");
- checkMoveFromInsideWord(7, 12);
-
- initTextViewWithNullLayout("before xx" + BAIRKAN + BAIRKAN + " after");
- checkMoveFromInsideWord(7, 12);
-
- initTextViewWithNullLayout("before x" + BAIRKAN + "x" + BAIRKAN + " after");
- checkMoveFromInsideWord(7, 12);
-
- initTextViewWithNullLayout("before " + BAIRKAN + "x" + BAIRKAN + "x after");
- checkMoveFromInsideWord(7, 12);
-
- initTextViewWithNullLayout("before " + BAIRKAN + BAIRKAN + BAIRKAN + " after");
- checkMoveFromInsideWord(7, 12);
- }
-
- private void checkMoveFromInsideWord(int wordStart, int wordEnd) {
-
- CharSequence text = mTextView.getText();
-
- // Check following always goes at the end of the word
- for (int offset = wordStart; offset != wordEnd + 1; offset++) {
- // Skip positions located between a pair of surrogate characters
- if (Character.isSurrogatePair(text.charAt(offset - 1), text.charAt(offset))) {
- continue;
- }
- Selection.setSelection(mEditable, offset);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertSelection(wordEnd + 1);
- }
-
- // Check preceding always goes at the beginning of the word
- for (int offset = wordEnd + 1; offset != wordStart; offset--) {
- if (Character.isSurrogatePair(text.charAt(offset - 1), text.charAt(offset))) {
- continue;
- }
- Selection.setSelection(mEditable, offset);
- assertTrue(pressCtrlChord(KeyEvent.KEYCODE_DPAD_LEFT));
- assertSelection(wordStart);
- }
- }
-
private void initTextViewWithNullLayout() {
- initTextViewWithNullLayout(THREE_LINES_TEXT);
- }
-
- private void initTextViewWithNullLayout(CharSequence text) {
mTextView = new TextView(getActivity());
- mTextView.setText(text, BufferType.EDITABLE);
+ mTextView.setText(THREE_LINES_TEXT, BufferType.EDITABLE);
assertNull(mTextView.getLayout());
- mEditable = (Editable) mTextView.getText();
}
private void pressMetaKey(int metakey, int expectedState) {
@@ -1265,38 +873,13 @@ public class ArrowKeyMovementMethodTest extends ActivityInstrumentationTestCase2
pressMetaKey(KeyEvent.KEYCODE_ALT_LEFT, MetaKeyKeyListener.META_ALT_ON);
}
- private boolean pressCtrlChord(int keyCode) {
- final long now = System.currentTimeMillis();
- final KeyEvent keyEvent = new KeyEvent(
- now, now, KeyEvent.ACTION_DOWN, keyCode, 0, KeyEvent.META_CTRL_LEFT_ON);
- return mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable, keyCode, keyEvent);
- }
-
- private void assertSelection(int expectedPosition) {
- assertSelection(expectedPosition, expectedPosition);
+ private void assertSelection(int position) {
+ assertSelection(position, position);
}
- private void assertSelection(int expectedStart, int expectedEnd) {
- final int actualStart = Selection.getSelectionStart(mEditable);
- final int actualEnd = Selection.getSelectionEnd(mEditable);
-
- assertCharSequenceIndexEquals(mEditable, expectedStart, actualStart);
- assertCharSequenceIndexEquals(mEditable, expectedEnd, actualEnd);
- }
-
- private static void assertCharSequenceIndexEquals(CharSequence text, int expected, int actual) {
- final String message = "expected <" + getCursorSnippet(text, expected) + "> but was <"
- + getCursorSnippet(text, actual) + ">";
- assertEquals(message, expected, actual);
- }
-
- private static String getCursorSnippet(CharSequence text, int index) {
- if (index >= 0 && index < text.length()) {
- return text.subSequence(Math.max(0, index - 5), index) + "|"
- + text.subSequence(index, Math.min(text.length() - 1, index + 5));
- } else {
- return null;
- }
+ private void assertSelection(int start, int end) {
+ assertEquals(start, Selection.getSelectionStart(mEditable));
+ assertEquals(end, Selection.getSelectionEnd(mEditable));
}
private void assertSelectEndOfContent() {
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 0383463..2f8cbfd 100644
--- a/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
@@ -62,89 +62,117 @@ public class BaseKeyListenerTest extends
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() {
- final Editable content = Editable.Factory.getInstance().newEditable(TEST_STRING);
- setTextViewText(content);
-
- // Nothing to delete when the cursor is at the beginning.
+ Editable content;
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());
- // Delete the first three letters using a selection.
- setTextViewText(content);
+ content = Editable.Factory.getInstance().newEditable(TEST_STRING);
Selection.setSelection(content, 0, 3);
baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, delKeyEvent);
assertEquals("456", content.toString());
- // 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());
- }
+ 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.
+ }
- private void setTextViewText(final CharSequence content) {
+ final String str = "123456";
mActivity.runOnUiThread(new Runnable() {
public void run() {
- mTextView.setText(content, BufferType.EDITABLE);
+ mTextView.setText(str, BufferType.EDITABLE);
+ mTextView.setKeyListener(baseKeyListener);
+ mTextView.requestFocus();
+ Selection.setSelection((Editable) mTextView.getText(), 1, 1);
}
});
mInstrumentation.waitForIdleSync();
- }
-
- public void testBackspace_withSendKeys() {
- final MockBaseKeyListener baseKeyListener = new MockBaseKeyListener();
- final String str = "123456";
-
- // Delete the first character '1'
- prepareTextView(str, baseKeyListener, 1, 1);
+ assertEquals(str, mTextView.getText().toString());
+ // delete the first character '1'
sendKeys(KeyEvent.KEYCODE_DEL);
assertEquals("23456", mTextView.getText().toString());
- // Delete character '2' and '3'
- prepareTextView(str, baseKeyListener, 1, 3);
+ 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'
sendKeys(KeyEvent.KEYCODE_DEL);
assertEquals("1456", mTextView.getText().toString());
- // Delete everything on the line the cursor is on.
- prepareTextView(str, baseKeyListener, 0, 0);
- sendAltDelete();
+ 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);
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.
- prepareTextView(str, baseKeyListener, 2, 4);
- sendAltDelete();
- assertEquals("1256", mTextView.getText().toString());
-
- // DEL key does not take effect when TextView does not have BaseKeyListener.
- prepareTextView(str, null, 1, 1);
+ sendKeys(KeyEvent.KEYCODE_ALT_LEFT);
sendKeys(KeyEvent.KEYCODE_DEL);
- assertEquals(str, mTextView.getText().toString());
- }
+ assertEquals("1256", mTextView.getText().toString());
- private void prepareTextView(final CharSequence content, final BaseKeyListener keyListener,
- final int selectionStart, final int selectionEnd) {
+ // text view does not have BaseKeyListener
mActivity.runOnUiThread(new Runnable() {
public void run() {
- mTextView.setText(content, BufferType.EDITABLE);
- mTextView.setKeyListener(keyListener);
+ mTextView.setText(str, BufferType.EDITABLE);
+ mTextView.setKeyListener(null);
mTextView.requestFocus();
- Selection.setSelection((Editable) mTextView.getText(), selectionStart,
- selectionEnd);
+ Selection.setSelection((Editable) mTextView.getText(), 1, 1);
}
});
mInstrumentation.waitForIdleSync();
- }
-
- private void sendAltDelete() {
- mInstrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ALT_LEFT));
+ assertEquals(str, mTextView.getText().toString());
+ // DEL key does not take effect
sendKeys(KeyEvent.KEYCODE_DEL);
- mInstrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ALT_LEFT));
+ assertEquals(str, mTextView.getText().toString());
}
/**
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 daaedf4..b3d3a39 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 @@ public class DateTimeKeyListenerTest extends
assertEquals(expectedText, mTextView.getText().toString());
// press 'a' key if producible
- KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
+ KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_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 6a67a5c..32a98e9 100644
--- a/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
@@ -29,7 +29,6 @@ import android.text.Spannable;
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;
@@ -427,10 +426,9 @@ public class MetaKeyKeyListenerTest extends AndroidTestCase {
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, fullEvent);
+ KeyEvent.KEYCODE_SHIFT_LEFT,
+ new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT));
assertEquals(0, state);
}
@@ -440,11 +438,10 @@ public class MetaKeyKeyListenerTest extends AndroidTestCase {
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, fullEvent);
- assertEquals(0, state);
+ KeyEvent.KEYCODE_SHIFT_LEFT,
+ new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT));
+ assertEquals(MetaKeyKeyListener.META_CAP_LOCKED, 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 6dde08d..ed7be70 100755
--- a/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
@@ -147,7 +147,8 @@ public class PasswordTransformationMethodTest extends
mMethod.reset();
// 12-key support
- KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
+ KeyCharacterMap keymap
+ = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_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 78ebfa4..be2eede 100755
--- a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
@@ -486,9 +486,8 @@ public class ScrollingMovementMethodTest extends ActivityInstrumentationTestCase
int previousScrollX = mTextView.getScrollX();
runActionOnUiThread(new Runnable() {
public void run() {
- method.onKeyDown(mTextView, (Spannable) mTextView.getText(),
- KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_RIGHT));
+ method.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_RIGHT,
+ new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
}
});
assertTrue(mTextView.getScrollX() > previousScrollX);
@@ -496,9 +495,8 @@ public class ScrollingMovementMethodTest extends ActivityInstrumentationTestCase
previousScrollX = mTextView.getScrollX();
runActionOnUiThread(new Runnable() {
public void run() {
- method.onKeyDown(mTextView, (Spannable) mTextView.getText(),
- KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_DPAD_LEFT));
+ method.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_LEFT,
+ new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
}
});
assertTrue(mTextView.getScrollX() < previousScrollX);
@@ -507,8 +505,7 @@ public class ScrollingMovementMethodTest extends ActivityInstrumentationTestCase
assertVisibleLineInTextView(0);
runActionOnUiThread(new Runnable() {
public void run() {
- assertFalse(method.onKeyDown(mTextView, mSpannable, 0,
- new KeyEvent(KeyEvent.ACTION_DOWN, 0)));
+ assertFalse(method.onKeyDown(mTextView, mSpannable, 0, null));
}
});
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 8062adf..d087fc4 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 @@ public class TimeKeyListenerTest extends
assertEquals("12", mTextView.getText().toString());
// press 'a' key if producible
- KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
+ KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_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/WordIteratorTest.java b/tests/tests/text/src/android/text/method/cts/WordIteratorTest.java
deleted file mode 100644
index 2954087..0000000
--- a/tests/tests/text/src/android/text/method/cts/WordIteratorTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * 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.text.method.cts;
-
-import android.text.method.WordIterator;
-
-import java.text.BreakIterator;
-
-import junit.framework.TestCase;
-
-public class WordIteratorTest extends TestCase {
-
- WordIterator wi = new WordIterator();
-
- private void checkIsWordWithSurrogate(int beginning, int end, int surrogateIndex) {
- for (int i = beginning; i <= end; i++) {
- if (i == surrogateIndex) continue;
- assertEquals(beginning, wi.getBeginning(i));
- assertEquals(end, wi.getEnd(i));
- }
- }
-
- private void setCharSequence(String string) {
- wi.setCharSequence(string, 0, string.length());
- }
-
- private void checkIsWord(int beginning, int end) {
- checkIsWordWithSurrogate(beginning, end, -1);
- }
-
- private void checkIsNotWord(int beginning, int end) {
- for (int i = beginning; i <= end; i++) {
- assertEquals(BreakIterator.DONE, wi.getBeginning(i));
- assertEquals(BreakIterator.DONE, wi.getEnd(i));
- }
- }
-
- public void testEmptyString() {
- setCharSequence("");
- assertEquals(BreakIterator.DONE, wi.following(0));
- assertEquals(BreakIterator.DONE, wi.preceding(0));
-
- assertEquals(BreakIterator.DONE, wi.getBeginning(0));
- assertEquals(BreakIterator.DONE, wi.getEnd(0));
- }
-
- public void testOneWord() {
- setCharSequence("I");
- checkIsWord(0, 1);
-
- setCharSequence("am");
- checkIsWord(0, 2);
-
- setCharSequence("zen");
- checkIsWord(0, 3);
- }
-
- public void testSpacesOnly() {
- setCharSequence(" ");
- checkIsNotWord(0, 1);
-
- setCharSequence(", ");
- checkIsNotWord(0, 2);
-
- setCharSequence(":-)");
- checkIsNotWord(0, 3);
- }
-
- public void testBeginningEnd() {
- setCharSequence("Well hello, there! ");
- // 0123456789012345678901
- checkIsWord(0, 4);
- checkIsWord(5, 10);
- checkIsNotWord(11, 13);
- checkIsWord(14, 19);
- checkIsNotWord(20, 21);
-
- setCharSequence(" Another - sentence");
- // 012345678901234567890
- checkIsNotWord(0, 1);
- checkIsWord(2, 9);
- checkIsNotWord(10, 11);
- checkIsWord(12, 20);
-
- setCharSequence("This is \u0644\u0627 tested"); // Lama-aleph
- // 012345678 9 01234567
- checkIsWord(0, 4);
- checkIsWord(5, 7);
- checkIsWord(8, 10);
- checkIsWord(11, 17);
- }
-
- public void testSurrogate() {
- final String BAIRKAN = "\uD800\uDF31";
-
- setCharSequence("one we" + BAIRKAN + "ird word");
- // 012345 67 890123456
-
- checkIsWord(0, 3);
- // Skip index 7 (there is no point in starting between the two surrogate characters)
- checkIsWordWithSurrogate(4, 11, 7);
- checkIsWord(12, 16);
-
- setCharSequence("one " + BAIRKAN + "xxx word");
- // 0123 45 678901234
-
- checkIsWord(0, 3);
- checkIsWordWithSurrogate(4, 9, 5);
- checkIsWord(10, 14);
-
- setCharSequence("one xxx" + BAIRKAN + " word");
- // 0123456 78 901234
-
- checkIsWord(0, 3);
- checkIsWordWithSurrogate(4, 9, 8);
- checkIsWord(10, 14);
- }
-}
diff --git a/tests/tests/theme/Android.mk b/tests/tests/theme/Android.mk
deleted file mode 100644
index b28e6b3..0000000
--- a/tests/tests/theme/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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
-
-# Include all test java files.
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsThemeTestCases
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
-include $(BUILD_PACKAGE)
diff --git a/tests/tests/theme/AndroidManifest.xml b/tests/tests/theme/AndroidManifest.xml
deleted file mode 100644
index 55afc7d..0000000
--- a/tests/tests/theme/AndroidManifest.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/tests/theme/src/android/theme/cts/ActivitySnapshotTests.java b/tests/tests/theme/src/android/theme/cts/ActivitySnapshotTests.java
deleted file mode 100644
index 0e93a75..0000000
--- a/tests/tests/theme/src/android/theme/cts/ActivitySnapshotTests.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.theme.cts;
-
-import android.test.ActivityInstrumentationTestCase2;
-
-/**
- * This class performs both the generation and testing for all of the tests
- * that take a snapshot of an entire activity and compare against a known-good version.
- */
-public class ActivitySnapshotTests
- extends ActivityInstrumentationTestCase2 implements TestReset {
- /**
- * Creates an {@link ActivityInstrumentationTestCase2}
- * for the {@link SnapshotActivity} activity.
- */
- public ActivitySnapshotTests() {
- super(SnapshotActivity.class);
- }
-
- /**
- * Generates the master versions of the bitmaps for the activity tests
- * in the normal mode.
- */
- public void generateActivityBitmaps() {
- ActivitySnapshotTester tester = new ActivitySnapshotTester(this, false);
- tester.genOrTestActivityBitmaps(true, true);
- tester.genOrTestActivityBitmaps(true, false);
- }
-
- /**
- * Runs the activity snapshot tests.
- */
- public void testActivityBitmaps() {
- ActivitySnapshotTester tester = new ActivitySnapshotTester(this, false);
- tester.genOrTestActivityBitmaps(false, true);
- tester.genOrTestActivityBitmaps(false, false);
- }
-
- public void reset() {
- try {
- tearDown();
- setUp();
- } catch (Exception e) {
- fail("Failed at tearing down the activity so we can start a new one.");
- }
- }
-}
diff --git a/tests/tests/theme/src/android/theme/cts/SplitActivitySnapshotTests.java b/tests/tests/theme/src/android/theme/cts/SplitActivitySnapshotTests.java
deleted file mode 100644
index 9a71a6c..0000000
--- a/tests/tests/theme/src/android/theme/cts/SplitActivitySnapshotTests.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.theme.cts;
-
-import android.test.ActivityInstrumentationTestCase2;
-
-/**
- * This class performs both the generation and testing for all of the tests
- * that take a snapshot of an entire activity and compare against a known-good version.
- *
- * Note that this class is essentially duplicated from {@link ActivitySnapshotTests}.
- * This unfortunate situation occurs because taking tests with a SplitActionBar
- * requires setting uiOptions on an activity in the AndroidManifest.xml. Since
- * this class requires an activity via generics, there has to be two separate
- * classes ({@link ActivitySnapshotTests} and this one) so that the tests can
- * be run both in normal mode and SplitActionBar mode.
- */
-public class SplitActivitySnapshotTests
- extends ActivityInstrumentationTestCase2 implements TestReset {
- /**
- * Creates an {@link ActivityInstrumentationTestCase2}
- * for the {@link SplitSnapshotActivity} activity.
- */
- public SplitActivitySnapshotTests() {
- super(SplitSnapshotActivity.class);
- }
-
- /**
- * Generates the master versions of the bitmaps for the activity tests
- * in the normal mode.
- */
- public void generateActivityBitmaps() {
- ActivitySnapshotTester tester = new ActivitySnapshotTester(this, true);
- tester.genOrTestActivityBitmaps(true, true);
- tester.genOrTestActivityBitmaps(true, false);
- }
-
- /**
- * Runs the activity snapshot tests.
- */
- public void testActivityBitmaps() {
- ActivitySnapshotTester tester = new ActivitySnapshotTester(this, true);
- tester.genOrTestActivityBitmaps(false, true);
- tester.genOrTestActivityBitmaps(false, false);
- }
-
- public void reset() {
- try {
- tearDown();
- setUp();
- } catch (Exception e) {
- fail("Failed at tearing down the activity so we can start a new one.");
- }
- }
-}
diff --git a/tests/tests/theme/src/android/theme/cts/ThemeGenerator.java b/tests/tests/theme/src/android/theme/cts/ThemeGenerator.java
deleted file mode 100644
index 4fe2a25..0000000
--- a/tests/tests/theme/src/android/theme/cts/ThemeGenerator.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.theme.cts;
-
-import android.app.Instrumentation;
-import android.content.Intent;
-import android.content.pm.ActivityInfo;
-import android.test.ActivityInstrumentationTestCase2;
-
-/**
- * This class generates the masters for the theme tests that
- * takes snapshots of views (typically widgets such as buttons, etc).
- */
-public class ThemeGenerator extends ActivityInstrumentationTestCase2 {
- /**
- * Creates an {@link ActivityInstrumentationTestCase2}
- * for the {@link ThemeTestGeneratorActivity} activity.
- */
- public ThemeGenerator() {
- super(ThemeTestGeneratorActivity.class);
- }
-
- /**
- * Generates the master bitmaps for all of the themes. Since it is not named "test something"
- * it is not run by CTS by default. However, you can run it via am instrument by specifying
- * the method name.
- */
- public void generateThemeBitmaps() {
- ThemeInfo[] themes = ThemeTests.getThemes();
-
- for (ThemeInfo theme : themes) {
- generateThemeBitmap(theme.getResourceId(), theme.getThemeName(),
- ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- generateThemeBitmap(theme.getResourceId(), theme.getThemeName(),
- ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
- }
- }
-
- private void generateThemeBitmap(int resourceId, String themeName, int orientation) {
- Instrumentation instrumentation = getInstrumentation();
-
- Intent intent = new Intent();
- intent.putExtra(ThemeTests.EXTRA_THEME_ID, resourceId);
- intent.putExtra(ThemeTests.EXTRA_THEME_NAME, themeName);
- intent.putExtra(ThemeTests.EXTRA_ORIENTATION, orientation);
- setActivityIntent(intent);
-
- final ThemeTestGeneratorActivity activity = getActivity();
-
- activity.runOnUiThread(new Runnable() {
- public void run() {
- activity.generateTests();
- }
- });
-
- instrumentation.waitForIdleSync();
-
- try {
- tearDown();
- setUp();
- } catch (Exception e) {
- fail("Failed at tearing down the activity so we can start a new one.");
- }
- }
-}
diff --git a/tests/tests/theme/src/android/theme/cts/ThemeTest.java b/tests/tests/theme/src/android/theme/cts/ThemeTest.java
deleted file mode 100644
index 4871a0e..0000000
--- a/tests/tests/theme/src/android/theme/cts/ThemeTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.theme.cts;
-
-import android.app.Instrumentation;
-import android.content.Intent;
-import android.content.pm.ActivityInfo;
-import android.test.ActivityInstrumentationTestCase2;
-
-/**
- * This class runs the theme tests that takes snapshots of views (typically widgets
- * such as buttons, etc).
- */
-public class ThemeTest extends ActivityInstrumentationTestCase2 {
- /**
- * Creates an {@link ActivityInstrumentationTestCase2}
- * for the {@link ThemeTestRunnerActivity} activity.
- */
- public ThemeTest() {
- super(ThemeTestRunnerActivity.class);
- }
-
- public void testThemes() {
- ThemeInfo[] themes = ThemeTests.getThemes();
-
- for (ThemeInfo theme : themes) {
- runThemeTest(theme.getResourceId(), theme.getThemeName(),
- ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- runThemeTest(theme.getResourceId(), theme.getThemeName(),
- ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
- }
- }
-
- /**
- * Runs the theme test given the appropriate theme resource id and theme name.
- * @param resourceId Resource ID of the theme being tested.
- * @param themeName Name of the theme being tested, e.g., "holo", "holo_light", etc
- */
- private void runThemeTest(int resourceId, String themeName, int orientation) {
- Instrumentation instrumentation = getInstrumentation();
-
- Intent intent = new Intent();
- intent.putExtra(ThemeTests.EXTRA_THEME_ID, resourceId);
- intent.putExtra(ThemeTests.EXTRA_THEME_NAME, themeName);
- intent.putExtra(ThemeTests.EXTRA_ORIENTATION, orientation);
- setActivityIntent(intent);
-
- final ThemeTestRunnerActivity activity = getActivity();
-
- activity.runOnUiThread(new Runnable() {
- public void run() {
- activity.runTests();
- }
- });
-
- instrumentation.waitForIdleSync();
-
- try {
- tearDown();
- setUp();
- } catch (Exception e) {
- fail("Failed at tearing down the activity so we can start a new one.");
- }
- }
-}
diff --git a/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java b/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
index 1f888e8..731784a 100644
--- a/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
+++ b/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
@@ -20,7 +20,6 @@ import android.os.Message;
import android.os.Parcel;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.accessibility.AccessibilityEvent;
-import android.view.accessibility.AccessibilityRecord;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
@@ -35,10 +34,10 @@ import junit.framework.TestCase;
public class AccessibilityEventTest extends TestCase {
/** The number of properties of the {@link AccessibilityEvent} class. */
- private static final int NON_STATIC_FIELD_COUNT = 28;
+ private static final int NON_STATIC_FIELD_COUNT = 16;
@MediumTest
- public void testMarshaling() throws Exception {
+ public void testMarshalling() throws Exception {
// no new fields, so we are testing marshaling of all such
assertNoNewNonStaticFieldsAdded();
@@ -91,17 +90,13 @@ public class AccessibilityEventTest extends TestCase {
private void assertNoNewNonStaticFieldsAdded() {
int nonStaticFieldCount = 0;
- Class> clazz = AccessibilityEvent.class;
- while (clazz != null) {
- for (Field field : clazz.getDeclaredFields()) {
- if ((field.getModifiers() & Modifier.STATIC) == 0) {
- nonStaticFieldCount++;
- }
+ for (Field field : AccessibilityEvent.class.getDeclaredFields()) {
+ if ((field.getModifiers() & Modifier.STATIC) == 0) {
+ nonStaticFieldCount++;
}
- clazz = clazz.getSuperclass();
}
- String message = "New fields have been added, so add code to test marshaling them.";
+ String message = "New fields have been added, so add code to test marchalling them.";
assertEquals(message, NON_STATIC_FIELD_COUNT, nonStaticFieldCount);
}
@@ -128,25 +123,6 @@ public class AccessibilityEventTest extends TestCase {
sentEvent.setPassword(true);
sentEvent.setRemovedCount(1);
sentEvent.getText().add("Foo");
- sentEvent.setMaxScrollX(1);
- sentEvent.setMaxScrollY(1);
-
- AccessibilityRecord record = AccessibilityRecord.obtain();
- record.setAddedCount(1);
- record.setBeforeText("BeforeText");
- record.setChecked(true);
- record.setClassName("foo.bar.baz.Class");
- record.setContentDescription("ContentDescription");
- record.setCurrentItemIndex(1);
- record.setEnabled(true);
- record.setFromIndex(1);
- record.setFullScreen(true);
- record.setItemCount(1);
- record.setParcelableData(Message.obtain(null, 1, 2, 3));
- record.setPassword(true);
- record.setRemovedCount(1);
- record.getText().add("Foo");
- sentEvent.appendRecord(record);
}
/**
@@ -182,42 +158,7 @@ public class AccessibilityEventTest extends TestCase {
.isPassword());
assertEquals("removedCount has incorrect value", expectedEvent.getRemovedCount(),
receivedEvent.getRemovedCount());
- assertEqualsText(expectedEvent.getText(), receivedEvent.getText());
- assertEquals("must have one record", expectedEvent.getRecordCount(),
- receivedEvent.getRecordCount());
- assertSame("maxScrollX has incorect value", expectedEvent.getMaxScrollX(),
- receivedEvent.getMaxScrollX());
- assertSame("maxScrollY has incorect value", expectedEvent.getMaxScrollY(),
- receivedEvent.getMaxScrollY());
-
- AccessibilityRecord expectedRecord = expectedEvent.getRecord(0);
- AccessibilityRecord receivedRecord = receivedEvent.getRecord(0);
-
- assertEquals("addedCount has incorrect value", expectedRecord.getAddedCount(),
- receivedRecord.getAddedCount());
- assertEquals("beforeText has incorrect value", expectedRecord.getBeforeText(),
- receivedRecord.getBeforeText());
- assertEquals("checked has incorrect value", expectedRecord.isChecked(),
- receivedRecord.isChecked());
- assertEquals("className has incorrect value", expectedRecord.getClassName(),
- receivedRecord.getClassName());
- assertEquals("contentDescription has incorrect value",
- expectedRecord.getContentDescription(), receivedRecord.getContentDescription());
- assertEquals("currentItemIndex has incorrect value", expectedRecord.getCurrentItemIndex(),
- receivedRecord.getCurrentItemIndex());
- assertEquals("enabled has incorrect value", expectedRecord.isEnabled(),
- receivedRecord.isEnabled());
- assertEquals("fromIndex has incorrect value", expectedRecord.getFromIndex(),
- receivedRecord.getFromIndex());
- assertEquals("fullScreen has incorrect value", expectedRecord.isFullScreen(),
- receivedRecord.isFullScreen());
- assertEquals("itemCount has incorrect value", expectedRecord.getItemCount(),
- receivedRecord.getItemCount());
- assertEquals("password has incorrect value", expectedRecord.isPassword(),
- receivedRecord.isPassword());
- assertEquals("removedCount has incorrect value", expectedRecord.getRemovedCount(),
- receivedRecord.getRemovedCount());
- assertEqualsText(expectedRecord.getText(), receivedRecord.getText());
+ assertEqualsText(expectedEvent, receivedEvent);
}
/**
@@ -225,9 +166,11 @@ public class AccessibilityEventTest extends TestCase {
* receivedEvent by comparing the string representation of the
* corresponding {@link CharSequence}s.
*/
- public static void assertEqualsText(List expectedText,
- List receivedText ) {
+ public static void assertEqualsText(AccessibilityEvent expectedEvent,
+ AccessibilityEvent receivedEvent) {
String message = "text has incorrect value";
+ List expectedText = expectedEvent.getText();
+ List receivedText = receivedEvent.getText();
TestCase.assertEquals(message, expectedText.size(), receivedText.size());
@@ -247,7 +190,7 @@ public class AccessibilityEventTest extends TestCase {
* @param event The event to check.
*/
public static void assertAccessibilityEventCleared(AccessibilityEvent event) {
- TestCase.assertEquals("addedCount not properly recycled", -1, event.getAddedCount());
+ TestCase.assertEquals("addedCount not properly recycled", 0, event.getAddedCount());
TestCase.assertNull("beforeText not properly recycled", event.getBeforeText());
TestCase.assertNull("className not properly recycled", event.getClassName());
TestCase.assertNull("contentDescription not properly recycled", event
@@ -256,11 +199,12 @@ public class AccessibilityEventTest extends TestCase {
.getCurrentItemIndex());
TestCase.assertEquals("eventTime not properly recycled", 0, event.getEventTime());
TestCase.assertEquals("eventType not properly recycled", 0, event.getEventType());
- TestCase.assertEquals("fromIndex not properly recycled", -1, event.getFromIndex());
- TestCase.assertEquals("itemCount not properly recycled", -1, event.getItemCount());
+ 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());
- TestCase.assertNull("parcelableData not properly recycled", event.getParcelableData());
- TestCase.assertEquals("removedCount not properly recycled", -1, event.getRemovedCount());
+ // This will fail and is fixed in Gingerbread Bug: 2593810
+ // 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/GestureDetectorTestUtil.java b/tests/tests/view/src/android/view/cts/GestureDetectorTestUtil.java
index b43c8e2..ff4fe5a 100644
--- a/tests/tests/view/src/android/view/cts/GestureDetectorTestUtil.java
+++ b/tests/tests/view/src/android/view/cts/GestureDetectorTestUtil.java
@@ -16,11 +16,9 @@
package android.view.cts;
-import android.graphics.Rect;
import android.test.InstrumentationTestCase;
import android.test.TouchUtils;
import android.view.View;
-import android.view.Window;
class GestureDetectorTestUtil {
@@ -36,18 +34,11 @@ class GestureDetectorTestUtil {
TouchUtils.longClickView(testcase, view);
TouchUtils.scrollToBottom(testcase, activity, activity.getViewGroup());
TouchUtils.touchAndCancelView(testcase, view);
-
- Rect windowRect = new Rect();
- Window window = activity.getWindow();
- window.getDecorView().getWindowVisibleDisplayFrame(windowRect);
- int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
- int statusBarHeight = contentViewTop - windowRect.top;
-
int fromX = 1;
int toX = 10;
// Y has to be outside the status bar bounding box
- int fromY = statusBarHeight + 1;
- int toY = statusBarHeight + 51;
+ int fromY = 50;
+ int toY = 100;
int stepCount = 20;
TouchUtils.drag(testcase, fromX, toX, fromY, toY, stepCount);
InstrumentationTestCase.assertTrue(activity.isDown);
diff --git a/tests/tests/view/src/android/view/cts/GestureDetector_SimpleOnGestureListenerTest.java b/tests/tests/view/src/android/view/cts/GestureDetector_SimpleOnGestureListenerTest.java
new file mode 100644
index 0000000..b16f894
--- /dev/null
+++ b/tests/tests/view/src/android/view/cts/GestureDetector_SimpleOnGestureListenerTest.java
@@ -0,0 +1,114 @@
+/*
+ * 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 {
+
+ 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/GravityTest.java b/tests/tests/view/src/android/view/cts/GravityTest.java
index 1b5d06d..aee209e 100644
--- a/tests/tests/view/src/android/view/cts/GravityTest.java
+++ b/tests/tests/view/src/android/view/cts/GravityTest.java
@@ -16,7 +16,6 @@
package android.view.cts;
-import android.view.View;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
@@ -52,11 +51,6 @@ public class GravityTest extends AndroidTestCase {
new Gravity();
}
- private void applyGravity(int gravity, int w, int h, Rect container, Rect outRect, boolean bRtl) {
- final int layoutDirection = bRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR;
- Gravity.apply(gravity, w, h, mInRect, mOutRect, layoutDirection);
- }
-
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
@@ -85,16 +79,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(26, mOutRect.right);
assertEquals(25, mOutRect.top);
assertEquals(28, mOutRect.bottom);
- applyGravity(Gravity.TOP, 2, 3, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(20, mOutRect.top);
- assertEquals(23, mOutRect.bottom);
- applyGravity(Gravity.TOP, 2, 3, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(20, mOutRect.top);
- assertEquals(23, mOutRect.bottom);
Gravity.apply(Gravity.BOTTOM, 2, 3, mInRect, mOutRect);
assertEquals(19, mOutRect.left);
@@ -106,16 +90,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(26, mOutRect.right);
assertEquals(32, mOutRect.top);
assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.BOTTOM, 2, 3, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(37, mOutRect.top);
- assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.BOTTOM, 2, 3, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(37, mOutRect.top);
- assertEquals(40, mOutRect.bottom);
Gravity.apply(Gravity.LEFT, 2, 10, mInRect, mOutRect);
assertEquals(10, mOutRect.left);
@@ -127,37 +101,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(17, mOutRect.right);
assertEquals(30, mOutRect.top);
assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.LEFT, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(10, mOutRect.left);
- assertEquals(12, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.LEFT, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(10, mOutRect.left);
- assertEquals(12, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
-
- Gravity.apply(Gravity.START, 2, 10, mInRect, mOutRect);
- assertEquals(10, mOutRect.left);
- assertEquals(12, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- Gravity.apply(Gravity.START, 2, 10, mInRect, 5, 5, mOutRect);
- assertEquals(15, mOutRect.left);
- assertEquals(17, mOutRect.right);
- assertEquals(30, mOutRect.top);
- assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.START, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(10, mOutRect.left);
- assertEquals(12, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.START, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(28, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
Gravity.apply(Gravity.RIGHT, 2, 10, mInRect, mOutRect);
assertEquals(28, mOutRect.left);
@@ -169,37 +112,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(25, mOutRect.right);
assertEquals(30, mOutRect.top);
assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.RIGHT, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(28, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.RIGHT, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(28, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
-
- Gravity.apply(Gravity.END, 2, 10, mInRect, mOutRect);
- assertEquals(28, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- Gravity.apply(Gravity.END, 2, 10, mInRect, 5, 5, mOutRect);
- assertEquals(23, mOutRect.left);
- assertEquals(25, mOutRect.right);
- assertEquals(30, mOutRect.top);
- assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.END, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(28, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.END, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(10, mOutRect.left);
- assertEquals(12, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
Gravity.apply(Gravity.CENTER_VERTICAL, 2, 10, mInRect, mOutRect);
assertEquals(19, mOutRect.left);
@@ -211,16 +123,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(26, mOutRect.right);
assertEquals(30, mOutRect.top);
assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.CENTER_VERTICAL, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.CENTER_VERTICAL, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
Gravity.apply(Gravity.FILL_VERTICAL, 2, 10, mInRect, mOutRect);
assertEquals(19, mOutRect.left);
@@ -232,16 +134,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(26, mOutRect.right);
assertEquals(25, mOutRect.top);
assertEquals(45, mOutRect.bottom);
- applyGravity(Gravity.FILL_VERTICAL, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(20, mOutRect.top);
- assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.FILL_VERTICAL, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(20, mOutRect.top);
- assertEquals(40, mOutRect.bottom);
Gravity.apply(Gravity.CENTER_HORIZONTAL, 2, 10, mInRect, mOutRect);
assertEquals(19, mOutRect.left);
@@ -253,16 +145,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(26, mOutRect.right);
assertEquals(30, mOutRect.top);
assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.CENTER_HORIZONTAL, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.CENTER_HORIZONTAL, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(19, mOutRect.left);
- assertEquals(21, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
Gravity.apply(Gravity.FILL_HORIZONTAL, 2, 10, mInRect, mOutRect);
assertEquals(10, mOutRect.left);
@@ -274,16 +156,6 @@ public class GravityTest extends AndroidTestCase {
assertEquals(35, mOutRect.right);
assertEquals(30, mOutRect.top);
assertEquals(40, mOutRect.bottom);
- applyGravity(Gravity.FILL_HORIZONTAL, 2, 10, mInRect, mOutRect, false /* LTR direction */);
- assertEquals(10, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
- applyGravity(Gravity.FILL_HORIZONTAL, 2, 10, mInRect, mOutRect, true /* RTL direction */);
- assertEquals(10, mOutRect.left);
- assertEquals(30, mOutRect.right);
- assertEquals(25, mOutRect.top);
- assertEquals(35, mOutRect.bottom);
}
@TestTargetNew(
@@ -307,7 +179,6 @@ public class GravityTest extends AndroidTestCase {
public void testIsHorizontal() {
assertFalse(Gravity.isHorizontal(-1));
assertTrue(Gravity.isHorizontal(Gravity.HORIZONTAL_GRAVITY_MASK));
- assertTrue(Gravity.isHorizontal(Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK));
assertFalse(Gravity.isHorizontal(Gravity.NO_GRAVITY));
}
diff --git a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
index 156dc49..4ab38df 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 @@ public class KeyCharacterMapTest extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
- mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
+ mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
}
@TestTargetNew(
@@ -113,7 +113,6 @@ public class KeyCharacterMapTest extends AndroidTestCase {
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));
@@ -134,131 +133,11 @@ public class KeyCharacterMapTest extends AndroidTestCase {
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 6689ca4..dc1696c 100644
--- a/tests/tests/view/src/android/view/cts/KeyEventTest.java
+++ b/tests/tests/view/src/android/view/cts/KeyEventTest.java
@@ -31,8 +31,6 @@ import android.view.KeyEvent;
import android.view.KeyCharacterMap.KeyData;
import android.view.KeyEvent.Callback;
-import junit.framework.Assert;
-
/**
* Test {@link KeyEvent}.
*/
@@ -185,16 +183,23 @@ public class KeyEventTest extends AndroidTestCase {
args = {android.view.KeyCharacterMap.KeyData.class}
)
public void testGetKeyData() {
- KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_Z);
KeyData keyData = new KeyData();
- assertTrue(keyEvent.getKeyData(keyData));
-
- 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]);
+ 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(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]);
}
@TestTargetNew(
@@ -290,7 +295,6 @@ public class KeyEventTest extends AndroidTestCase {
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'
@@ -313,7 +317,6 @@ public class KeyEventTest extends AndroidTestCase {
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));
@@ -394,205 +397,21 @@ public class KeyEventTest extends AndroidTestCase {
assertFalse(mKeyEvent.isAltPressed());
}
- 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);
- }
-
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "Test {@link KeyEvent#isModifierKey(int)}",
+ method = "isModifierKey",
+ args = {int.class}
+ )
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()}",
@@ -690,6 +509,8 @@ public class KeyEventTest extends AndroidTestCase {
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));
@@ -700,6 +521,13 @@ public class KeyEventTest extends AndroidTestCase {
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(
@@ -914,7 +742,7 @@ public class KeyEventTest extends AndroidTestCase {
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 f5bd8f4..6f637fc 100644
--- a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
+++ b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
@@ -16,14 +16,6 @@
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;
@@ -31,7 +23,6 @@ import android.content.ComponentName;
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;
@@ -44,13 +35,21 @@ import android.view.ViewGroup;
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 final Factory mFactory = new Factory() {
+ private Factory mFactory = new Factory() {
public View onCreateView(String name, Context context,
AttributeSet attrs) {
@@ -58,7 +57,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
}
};
private boolean isOnLoadClass;
- private final Filter mFilter = new Filter() {
+ private Filter mFilter = new Filter() {
@SuppressWarnings("unchecked")
public boolean onLoadClass(Class clazz) {
@@ -173,7 +172,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
}
String nodeName = parser.getName();
if (!"alias".equals(nodeName)) {
- throw new InflateException();
+ throw new RuntimeException();
}
int outerDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
@@ -297,7 +296,8 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(-1, null);
fail("should throw exception");
- } catch (Resources.NotFoundException e) {
+ } catch (RuntimeException e) {
+
}
LinearLayout mLayout;
mLayout = new LinearLayout(mContext);
@@ -335,7 +335,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(-1, null, false);
fail("should throw exception");
- } catch (Resources.NotFoundException e) {
+ } catch (RuntimeException e) {
}
LinearLayout mLayout;
@@ -381,7 +381,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(null, null);
fail("should throw exception");
- } catch (NullPointerException e) {
+ } catch (RuntimeException e) {
}
LinearLayout mLayout;
mLayout = new LinearLayout(mContext);
@@ -395,7 +395,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(parser, mLayout);
fail("should throw exception");
- } catch (NullPointerException e) {
+ } catch (RuntimeException e) {
}
parser = getContext().getResources().getLayout(
R.layout.inflater_layout);
@@ -440,7 +440,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(null, null, false);
fail("should throw exception");
- } catch (NullPointerException e) {
+ } catch (RuntimeException e) {
}
LinearLayout mLayout;
mLayout = new LinearLayout(mContext);
@@ -454,7 +454,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(parser, mLayout, false);
fail("should throw exception");
- } catch (NullPointerException e) {
+ } catch (RuntimeException e) {
}
parser = getContext().getResources().getLayout(
R.layout.inflater_layout);
@@ -475,7 +475,7 @@ public class LayoutInflaterTest extends AndroidTestCase {
try {
view = mLayoutInflater.inflate(parser, mLayout, false);
fail("should throw exception");
- } catch (InflateException e) {
+ } catch (RuntimeException e) {
}
parser = null;
@@ -497,7 +497,6 @@ public class LayoutInflaterTest extends AndroidTestCase {
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 945cefc..e4df594 100644
--- a/tests/tests/view/src/android/view/cts/MotionEventTest.java
+++ b/tests/tests/view/src/android/view/cts/MotionEventTest.java
@@ -22,16 +22,12 @@ import dalvik.annotation.TestTargetNew;
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;
-import android.view.MotionEvent.PointerProperties;
/**
* Test {@link MotionEvent}.
@@ -501,198 +497,4 @@ public class MotionEventTest extends AndroidTestCase {
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());
- }
- }
-
- public void testPointerCoordsDefaultConstructor() {
- PointerCoords coords = new PointerCoords();
-
- assertEquals(0f, coords.x);
- assertEquals(0f, coords.y);
- assertEquals(0f, coords.pressure);
- assertEquals(0f, coords.size);
- assertEquals(0f, coords.touchMajor);
- assertEquals(0f, coords.touchMinor);
- assertEquals(0f, coords.toolMajor);
- assertEquals(0f, coords.toolMinor);
- assertEquals(0f, coords.orientation);
- }
-
- public void testPointerCoordsCopyConstructor() {
- PointerCoords coords = new PointerCoords();
- coords.x = 1;
- coords.y = 2;
- coords.pressure = 3;
- coords.size = 4;
- coords.touchMajor = 5;
- coords.touchMinor = 6;
- coords.toolMajor = 7;
- coords.toolMinor = 8;
- coords.orientation = 9;
- coords.setAxisValue(MotionEvent.AXIS_GENERIC_1, 10);
-
- PointerCoords copy = new PointerCoords(coords);
- assertEquals(1f, copy.x);
- assertEquals(2f, copy.y);
- assertEquals(3f, copy.pressure);
- assertEquals(4f, copy.size);
- assertEquals(5f, copy.touchMajor);
- assertEquals(6f, copy.touchMinor);
- assertEquals(7f, copy.toolMajor);
- assertEquals(8f, copy.toolMinor);
- assertEquals(9f, copy.orientation);
- assertEquals(10f, coords.getAxisValue(MotionEvent.AXIS_GENERIC_1));
- }
-
- public void testPointerCoordsCopyFrom() {
- PointerCoords coords = new PointerCoords();
- coords.x = 1;
- coords.y = 2;
- coords.pressure = 3;
- coords.size = 4;
- coords.touchMajor = 5;
- coords.touchMinor = 6;
- coords.toolMajor = 7;
- coords.toolMinor = 8;
- coords.orientation = 9;
- coords.setAxisValue(MotionEvent.AXIS_GENERIC_1, 10);
-
- PointerCoords copy = new PointerCoords();
- copy.copyFrom(coords);
- assertEquals(1f, copy.x);
- assertEquals(2f, copy.y);
- assertEquals(3f, copy.pressure);
- assertEquals(4f, copy.size);
- assertEquals(5f, copy.touchMajor);
- assertEquals(6f, copy.touchMinor);
- assertEquals(7f, copy.toolMajor);
- assertEquals(8f, copy.toolMinor);
- assertEquals(9f, copy.orientation);
- assertEquals(10f, coords.getAxisValue(MotionEvent.AXIS_GENERIC_1));
- }
-
- public void testPointerPropertiesDefaultConstructor() {
- PointerProperties properties = new PointerProperties();
-
- assertEquals(MotionEvent.INVALID_POINTER_ID, properties.id);
- assertEquals(MotionEvent.TOOL_TYPE_UNKNOWN, properties.toolType);
- }
-
- public void testPointerPropertiesCopyConstructor() {
- PointerProperties properties = new PointerProperties();
- properties.id = 1;
- properties.toolType = MotionEvent.TOOL_TYPE_MOUSE;
-
- PointerProperties copy = new PointerProperties(properties);
- assertEquals(1, copy.id);
- assertEquals(MotionEvent.TOOL_TYPE_MOUSE, copy.toolType);
- }
-
- public void testPointerPropertiesCopyFrom() {
- PointerProperties properties = new PointerProperties();
- properties.id = 1;
- properties.toolType = MotionEvent.TOOL_TYPE_MOUSE;
-
- PointerProperties copy = new PointerProperties();
- copy.copyFrom(properties);
- assertEquals(1, copy.id);
- assertEquals(MotionEvent.TOOL_TYPE_MOUSE, copy.toolType);
- }
}
diff --git a/tests/tests/view/src/android/view/cts/VelocityTrackerTest.java b/tests/tests/view/src/android/view/cts/VelocityTrackerTest.java
index 3a68233..35254b6 100644
--- a/tests/tests/view/src/android/view/cts/VelocityTrackerTest.java
+++ b/tests/tests/view/src/android/view/cts/VelocityTrackerTest.java
@@ -96,7 +96,7 @@ public class VelocityTrackerTest extends AndroidTestCase {
VelocityTracker vt = VelocityTracker.obtain();
assertNotNull(vt);
- MotionEvent me = MotionEvent.obtain(0L, 10L, MotionEvent.ACTION_MOVE, .0f, .0f, 0);
+ MotionEvent me = MotionEvent.obtain(0L, 10, 1, .0f, .0f, 0);
vt.clear();
me.addBatch(20L, 20, 20, .0f, .0f, 0);
@@ -112,14 +112,14 @@ public class VelocityTrackerTest extends AndroidTestCase {
assertEquals(XVelocity, vt.getXVelocity(), ERROR_TOLERANCE);
assertEquals(YVelocity, vt.getYVelocity(), ERROR_TOLERANCE);
- for (int i = 3; i < 10; i++) {
- me.addBatch((long)i * 10, (float)i * 10, (float)i * 10, .0f, .0f, 0);
+ for (int i = 30; i < 100; i += 10) {
+ me.addBatch((long)i, (float)i, (float)i, .0f, .0f, 0);
}
vt.clear();
vt.addMovement(me);
vt.computeCurrentVelocity(1);
- XVelocity = 0.8242369f;
- YVelocity = 0.8242369f;
+ XVelocity = 1.1875744f;
+ YVelocity = 1.1875744f;
assertEquals(XVelocity, vt.getXVelocity(), ERROR_TOLERANCE);
assertEquals(YVelocity, vt.getYVelocity(), ERROR_TOLERANCE);
@@ -127,21 +127,11 @@ public class VelocityTrackerTest extends AndroidTestCase {
me.addBatch(100L, 100, 100, .0f, .0f, 0);
vt.addMovement(me);
vt.computeCurrentVelocity(1);
- XVelocity = 0.8500008f;
- YVelocity = 0.8500008f;
+ XVelocity = 1.1562872f;
+ YVelocity = 1.1562872f;
assertEquals(XVelocity, vt.getXVelocity(), ERROR_TOLERANCE);
assertEquals(YVelocity, vt.getYVelocity(), ERROR_TOLERANCE);
- me.recycle();
- me = MotionEvent.obtain(0L, 110L, MotionEvent.ACTION_UP, 100f, 100f, 0);
- vt.addMovement(me);
- vt.computeCurrentVelocity(1);
- XVelocity = 0.8500008f;
- YVelocity = 0.8500008f;
- assertEquals(XVelocity, vt.getXVelocity(), ERROR_TOLERANCE);
- assertEquals(YVelocity, vt.getYVelocity(), ERROR_TOLERANCE);
-
- me.recycle();
vt.recycle();
}
}
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupTest.java b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
index 2498700..ebcee54 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
@@ -16,13 +16,7 @@
package android.view.cts;
-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 java.util.ArrayList;
import android.app.cts.CTSResult;
import android.content.Context;
@@ -61,7 +55,13 @@ import android.view.animation.Animation.AnimationListener;
import android.widget.TextView;
import android.widget.cts.ViewGroupStubActivity;
-import java.util.ArrayList;
+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;
@TestTargetClass(ViewGroup.class)
public class ViewGroupTest extends InstrumentationTestCase implements CTSResult{
@@ -1557,6 +1557,20 @@ public class ViewGroupTest extends InstrumentationTestCase implements CTSResult{
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,
@@ -1934,7 +1948,6 @@ public class ViewGroupTest extends InstrumentationTestCase implements CTSResult{
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 be60976..87b3eae 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -16,14 +16,15 @@
package android.view.cts;
-import com.google.android.collect.Lists;
-
import com.android.cts.stub.R;
import com.android.internal.view.menu.ContextMenuBuilder;
+import com.google.android.collect.Lists;
-import java.util.ArrayList;
-import java.util.Arrays;
-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 android.app.Activity;
import android.content.Context;
@@ -45,9 +46,7 @@ import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.Xml;
-import android.view.ActionMode;
import android.view.ContextMenu;
-import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
@@ -55,6 +54,11 @@ import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.TouchDelegate;
import android.view.View;
+import android.view.ViewConfiguration;
+import android.view.ViewGroup;
+import android.view.ViewParent;
+import android.view.WindowManagerImpl;
+import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.BaseSavedState;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
@@ -62,11 +66,6 @@ import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
-import android.view.ViewConfiguration;
-import android.view.ViewGroup;
-import android.view.ViewParent;
-import android.view.WindowManagerImpl;
-import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.cts.DelayedCheck;
@@ -79,11 +78,10 @@ import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.cts.StubActivity;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
/**
* Test {@link View}.
@@ -2030,6 +2028,10 @@ public class ViewTest extends ActivityInstrumentationTestCase2 1) {
- handler.cancel();
- return;
- }
this.realm = realm;
this.useHttpAuthUsernamePassword = handler.useHttpAuthUsernamePassword();
if (mProceed) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/SslErrorHandlerTest.java b/tests/tests/webkit/src/android/webkit/cts/SslErrorHandlerTest.java
new file mode 100644
index 0000000..d0e42c7
--- /dev/null
+++ b/tests/tests/webkit/src/android/webkit/cts/SslErrorHandlerTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.webkit.cts;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import android.os.Message;
+
+import junit.framework.TestCase;
+
+@TestTargetClass(android.webkit.SslErrorHandler.class)
+public class SslErrorHandlerTest extends TestCase {
+
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "WebViewClient.onReceivedSslError() is hidden. Cannot test.",
+ method = "cancel",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "WebViewClient.onReceivedSslError() is hidden. Cannot test.",
+ method = "handleMessage",
+ args = {Message.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "WebViewClient.onReceivedSslError() is hidden. Cannot test.",
+ method = "proceed",
+ args = {}
+ )
+ })
+ public void testSslErrorHandler() {
+ }
+}
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index 639f795..b8f6059 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 class WebSettingsTest extends ActivityInstrumentationTestCase2 {
- private static final String LOGTAG = "WebViewTest";
private static final int INITIAL_PROGRESS = 100;
private static long TEST_TIMEOUT = 20000L;
private static long TIME_FOR_LAYOUT = 1000L;
private WebView mWebView;
private CtsTestServer mWebServer;
- private boolean mIsUiThreadDone;
public WebViewTest() {
super("com.android.cts.stub", WebViewStubActivity.class);
}
@Override
- public void runTestOnUiThread(Runnable runnable) throws Throwable {
- mIsUiThreadDone = false;
- super.runTestOnUiThread(runnable);
- }
-
- @Override
protected void setUp() throws Exception {
super.setUp();
mWebView = getActivity().getWebView();
@@ -104,16 +88,8 @@ public class WebViewTest extends ActivityInstrumentationTestCase2Test scroll bar overlay.
";
+ mWebView.loadData("" + p + "", "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
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({
@@ -397,7 +410,6 @@ public class WebViewTest extends ActivityInstrumentationTestCase2";
-
- // Test that the property is initially undefined.
- mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
- waitForLoadComplete();
- 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();
- assertEquals("undefined", mWebView.getTitle());
-
- // Test that adding an object gives an object type.
- final Object obj = new Object();
- mWebView.addJavascriptInterface(obj, "injectedObject");
- mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
- waitForLoadComplete();
- 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();
- 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}
- )
- })
- @UiThreadTest
- public void testAddJavascriptInterfaceOddName() throws Exception {
- WebSettings settings = mWebView.getSettings();
- settings.setJavaScriptEnabled(true);
- final Object obj = new Object();
-
- // 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 = "" +
- "" +
- "";
-
- mWebView.addJavascriptInterface(obj, name);
- mWebView.loadData(Uri.encode(setTitleToPropertyTypeHtml), "text/html", "UTF-8");
- waitForLoadComplete();
- assertEquals("object", mWebView.getTitle());
-
- mWebView.removeJavascriptInterface(name);
- mWebView.loadData(Uri.encode(setTitleToPropertyTypeHtml), "text/html", "UTF-8");
- waitForLoadComplete();
- assertEquals("undefined", mWebView.getTitle());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "removeJavascriptInterface",
- args = {String.class}
- )
- @UiThreadTest
- public void testRemoveJavascriptInterface() throws Exception {
- WebSettings settings = mWebView.getSettings();
- settings.setJavaScriptEnabled(true);
- String setTitleToPropertyTypeHtml = "" +
- "";
-
- // Test that adding an object gives an object type.
- mWebView.addJavascriptInterface(new Object(), "injectedObject");
- mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
- waitForLoadComplete();
- assertEquals("object", mWebView.getTitle());
-
- // Test that reloading the page after removing the object leaves the property undefined.
- mWebView.removeJavascriptInterface("injectedObject");
- mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
- waitForLoadComplete();
- assertEquals("undefined", mWebView.getTitle());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "removeJavascriptInterface",
- args = {String.class}
- )
- public void testUseRemovedJavascriptInterface() throws Throwable {
- class RemovedObject {
+ assertLoadUrlSuccessfully(mWebView, url);
+ new DelayedCheck() {
@Override
- public String toString() {
- return "removedObject";
- }
- public void remove() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWebView.removeJavascriptInterface("removedObject");
- System.gc();
- }
- });
- }
- }
- class ResultObject {
- private String mResult;
- private boolean mIsResultAvailable;
- public synchronized void setResult(String result) {
- mResult = result;
- mIsResultAvailable = true;
- notify();
- }
- public synchronized String getResult() {
- while (!mIsResultAvailable) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- return mResult;
- }
- }
- final ResultObject resultObject = new ResultObject();
-
- // Test that an object is still usable if removed while the page is in use, even if we have
- // no external references to it.
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWebView.getSettings().setJavaScriptEnabled(true);
- mWebView.addJavascriptInterface(new RemovedObject(), "removedObject");
- mWebView.addJavascriptInterface(resultObject, "resultObject");
- mWebView.loadData("" +
- "",
- "text/html", "UTF-8");
+ protected boolean check() {
+ return obj.hasChangedTitle();
}
- });
- assertEquals("removedObject", resultObject.getResult());
+ }.run();
}
@TestTargets({
@@ -786,55 +594,27 @@ public class WebViewTest extends ActivityInstrumentationTestCase2 0;
@@ -873,12 +637,8 @@ public class WebViewTest extends ActivityInstrumentationTestCase2 oldCallCount;
@@ -907,13 +667,8 @@ public class WebViewTest extends ActivityInstrumentationTestCase2Hello,World!" +
- "",
- "text/html", "UTF-8");
- waitForLoadComplete();
- assertEquals("Hello,World!", mWebView.getTitle());
- }
- });
+ public void testLoadData() throws Exception {
+ assertNull(mWebView.getTitle());
+ mWebView.loadData("Hello,World!",
+ "text/html", "UTF-8");
+ waitForLoadComplete(mWebView, TEST_TIMEOUT);
+ assertEquals("Hello,World!", mWebView.getTitle());
- // Test that JavaScript can't access cross-origin content.
- class ConsoleMessageWebChromeClient extends WebChromeClient {
- private boolean mIsMessageLevelAvailable;
- private ConsoleMessage.MessageLevel mMessageLevel;
- @Override
- public synchronized boolean onConsoleMessage(ConsoleMessage message) {
- mMessageLevel = message.messageLevel();
- mIsMessageLevelAvailable = true;
- notify();
- return true;
- }
- public synchronized ConsoleMessage.MessageLevel getMessageLevel() {
- while (!mIsMessageLevelAvailable) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- return mMessageLevel;
- }
- }
startWebServer(false);
- final ConsoleMessageWebChromeClient webChromeClient = new ConsoleMessageWebChromeClient();
- final String crossOriginUrl = mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
- runTestOnUiThread(new Runnable() {
- public void run() {
- mWebView.getSettings().setJavaScriptEnabled(true);
- mWebView.setWebChromeClient(webChromeClient);
- mWebView.loadData("