Merge "Enable PresentationSyncTest" into klp-dev
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index 37f7ac6..2c25d3d 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -39,6 +39,7 @@
 	SignatureTest \
 	TestDeviceSetup \
 	CtsUiAutomatorApp \
+	CtsUsbSerialTestApp \
 	$(cts_security_apps_list)
 
 cts_external_packages := \
@@ -118,7 +119,8 @@
 	$(PTS_HOST_CASES) \
 	CtsAdbTests \
 	CtsAppSecurityTests \
-	CtsMonkeyTestCases
+	CtsMonkeyTestCases \
+	CtsUsbTests
 
 
 # Native test executables that need to have associated test XMLs.
diff --git a/hostsidetests/usb/Android.mk b/hostsidetests/usb/Android.mk
new file mode 100644
index 0000000..488acbb
--- /dev/null
+++ b/hostsidetests/usb/Android.mk
@@ -0,0 +1,31 @@
+# Copyright (C) 2013 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)
+
+# Only compile source java files in this apk.
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE := CtsUsbTests
+
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed-prebuilt ddmlib-prebuilt junit
+
+LOCAL_CTS_TEST_PACKAGE := android.usb
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
+
+# Build the test APKs using their own makefiles
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/usb/SerialTestApp/Android.mk b/hostsidetests/usb/SerialTestApp/Android.mk
new file mode 100644
index 0000000..d36b98e
--- /dev/null
+++ b/hostsidetests/usb/SerialTestApp/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2013 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
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_JAVA_LIBRARIES := android.test.runner
+
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsUsbSerialTestApp
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/usb/SerialTestApp/AndroidManifest.xml b/hostsidetests/usb/SerialTestApp/AndroidManifest.xml
new file mode 100644
index 0000000..0667d60
--- /dev/null
+++ b/hostsidetests/usb/SerialTestApp/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2013 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.usb.serialtest">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+    <instrumentation
+        android:targetPackage="com.android.cts.usb.serialtest"
+        android:name="android.test.InstrumentationCtsTestRunner" />
+</manifest>
diff --git a/hostsidetests/usb/SerialTestApp/src/com/android/cts/usb/serialtest/UsbSerialTest.java b/hostsidetests/usb/SerialTestApp/src/com/android/cts/usb/serialtest/UsbSerialTest.java
new file mode 100644
index 0000000..a2b0c72
--- /dev/null
+++ b/hostsidetests/usb/SerialTestApp/src/com/android/cts/usb/serialtest/UsbSerialTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2013 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.usb.serialtest;
+
+import android.os.Build;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+
+/**
+ * Device test which reads Build.SERIAL and just print it.
+ */
+public class UsbSerialTest extends AndroidTestCase {
+    private static final String TAG = "CtsUsbSerialTest";
+
+    public void testSerial() throws Exception {
+        Log.e(TAG, Build.SERIAL);
+    }
+}
diff --git a/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java b/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java
new file mode 100644
index 0000000..f53d210
--- /dev/null
+++ b/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2013 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.usb;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.ddmlib.IDevice;
+import com.android.ddmlib.Log;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.IFileEntry;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.result.InputStreamSource;
+import com.android.tradefed.result.TestRunResult;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
+import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.RunUtil;
+import com.android.tradefed.util.StreamUtil;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Functional tests for usb connection
+ */
+public class TestUsbTest extends DeviceTestCase implements IBuildReceiver {
+
+    private static final String LOG_TAG = "TestUsbTest";
+    private static final String CTS_RUNNER = "android.test.InstrumentationCtsTestRunner";
+    private static final String PACKAGE_NAME = "com.android.cts.usb.serialtest";
+    private static final String APK_NAME="CtsUsbSerialTestApp.apk";
+    private ITestDevice mDevice;
+    private CtsBuildHelper mBuild;
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mDevice = getDevice();
+        mDevice.uninstallPackage(PACKAGE_NAME);
+        File app = mBuild.getTestApp(APK_NAME);
+        mDevice.installPackage(app, false);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        mDevice.uninstallPackage(PACKAGE_NAME);
+    }
+
+    /**
+     * Check if adb serial number, USB serial number, ro.serialno, and android.os.Build.SERIAL
+     * all matches and meets the format requirement [a-zA-Z0-9]{6,20}
+     */
+    public void testUsbSerial() throws Exception {
+        String adbSerial = mDevice.getSerialNumber().toLowerCase().trim();
+        if (adbSerial.startsWith("emulator-")) {
+            return;
+        }
+        if (mDevice.isAdbTcp()) { // adb over WiFi, no point checking it
+            return;
+        }
+
+        String roSerial = mDevice.executeShellCommand("getprop ro.serialno").toLowerCase().
+                trim();
+        assertEquals("adb serial != ro.serialno" , adbSerial, roSerial);
+
+        CommandResult result = RunUtil.getDefault().runTimedCmd(5000, "lsusb", "-v");
+        assertTrue("lsusb -v failed", result.getStatus() == CommandStatus.SUCCESS);
+        String lsusbOutput = result.getStdout();
+        Pattern pattern = Pattern.compile("^\\s+iSerial\\s+\\d+\\s+([a-zA-Z0-9]{6,20})",
+                Pattern.MULTILINE);
+        Matcher matcher = pattern.matcher(lsusbOutput);
+        String usbSerial = "";
+        while (matcher.find()) {
+            String currentSerial = matcher.group(1).toLowerCase();
+            if (adbSerial.compareTo(currentSerial) == 0) {
+                usbSerial = currentSerial;
+                break;
+            }
+        }
+        assertEquals("usb serial != adb serial" , usbSerial, adbSerial);
+
+        // now check Build.SERIAL
+        clearLogCat();
+        CollectingTestListener listener = new CollectingTestListener();
+        RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(PACKAGE_NAME, CTS_RUNNER,
+                mDevice.getIDevice());
+        mDevice.runInstrumentationTests(testRunner, listener);
+        TestRunResult runResult = listener.getCurrentRunResults();
+        if (runResult.isRunFailure()) {
+            fail(runResult.getRunFailureMessage());
+        }
+        String logs = mDevice.executeAdbCommand("logcat", "-d", "CtsUsbSerialTest:W", "*:S");
+        pattern = Pattern.compile("^.*CtsUsbSerialTest\\(.*\\):\\s+([a-zA-Z0-9]{6,20})",
+                Pattern.MULTILINE);
+        matcher = pattern.matcher(logs);
+        String buildSerial = "";
+        while (matcher.find()) {
+            String currentSerial = matcher.group(1).toLowerCase();
+            if (usbSerial.compareTo(currentSerial) == 0) {
+                buildSerial = currentSerial;
+                break;
+            }
+        }
+        assertEquals("usb serial != Build.SERIAL" , usbSerial, buildSerial);
+    }
+
+    private void clearLogCat() throws DeviceNotAvailableException {
+        mDevice.executeAdbCommand("logcat", "-c");
+    }
+}
diff --git a/tests/deviceadmin/AndroidManifest.xml b/tests/deviceadmin/AndroidManifest.xml
index 69bc74d..2395d99 100644
--- a/tests/deviceadmin/AndroidManifest.xml
+++ b/tests/deviceadmin/AndroidManifest.xml
@@ -40,6 +40,17 @@
             </intent-filter>
         </receiver>
 
+        <!-- Device Admin that needs to be in the deactivated state in order
+             for tests to pass. -->
+        <receiver android:name="android.deviceadmin.cts.CtsDeviceAdminDeactivatedReceiver"
+                android:permission="android.permission.BIND_DEVICE_ADMIN">
+            <meta-data android:name="android.app.device_admin"
+                    android:resource="@xml/device_admin" />
+            <intent-filter>
+                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
+            </intent-filter>
+        </receiver>
+
         <!-- Helper Activity used by Device Admin activation tests -->
         <activity android:name="android.deviceadmin.cts.CtsDeviceAdminActivationTestActivity"
                 android:label="Device Admin activation test" />
diff --git a/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminDeactivatedReceiver.java b/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminDeactivatedReceiver.java
new file mode 100644
index 0000000..ec59f63
--- /dev/null
+++ b/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminDeactivatedReceiver.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2013 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.deviceadmin.cts;
+
+import android.app.admin.DeviceAdminReceiver;
+
+public class CtsDeviceAdminDeactivatedReceiver extends DeviceAdminReceiver {
+}
diff --git a/tests/res/drawable/premul_data.png b/tests/res/drawable/premul_data.png
new file mode 100644
index 0000000..92d7e37
--- /dev/null
+++ b/tests/res/drawable/premul_data.png
Binary files differ
diff --git a/tests/src/android/renderscript/cts/intrinsic_colormatrix.rs b/tests/src/android/renderscript/cts/intrinsic_colormatrix.rs
index 6a13fe1..30b40c4 100644
--- a/tests/src/android/renderscript/cts/intrinsic_colormatrix.rs
+++ b/tests/src/android/renderscript/cts/intrinsic_colormatrix.rs
@@ -65,7 +65,7 @@
                     u.x = rsGetElementAt_uchar(in, x, y);
                     break;
                 }
-                pin = convert_float4(u) * (1.f / 255.f);
+                pin = rsUnpackColor8888(u);
             }
 
             pin = rsMatrixMultiply(&m, pin);
@@ -88,7 +88,7 @@
                 }
             }
 
-            if (dtout == RS_TYPE_FLOAT_32) {
+            if (dtout == RS_TYPE_UNSIGNED_8) {
                 uchar4 u = rsPackColorTo8888(pin);
                 switch(vsout) {
                 case 4:
diff --git a/tests/src/android/renderscript/cts/verify.rs b/tests/src/android/renderscript/cts/verify.rs
index d100eb4..85deb31 100644
--- a/tests/src/android/renderscript/cts/verify.rs
+++ b/tests/src/android/renderscript/cts/verify.rs
@@ -216,33 +216,42 @@
     }
 }
 
-void verify(rs_allocation in1, rs_allocation in2, int etype)
+void verify(rs_allocation in1, rs_allocation in2)
 {
-    switch(etype) {
-    case 0:
-        verify_uchar4(in1, in2);
-        break;
-    case 1:
-        verify_uchar3(in1, in2);
-        break;
-    case 2:
-        verify_uchar2(in1, in2);
-        break;
-    case 3:
-        verify_uchar(in1, in2);
-        break;
-    case 4:
-        verify_float4(in1, in2);
-        break;
-    case 5:
-        verify_float3(in1, in2);
-        break;
-    case 6:
-        verify_float2(in1, in2);
-        break;
-    case 7:
-        verify_float(in1, in2);
-        break;
+    rs_element e = rsAllocationGetElement(in1);
+    rs_data_type dt = rsElementGetDataType(e);
+    uint32_t vs = rsElementGetVectorSize(e);
+
+    if (dt == RS_TYPE_UNSIGNED_8) {
+        switch(vs) {
+        case 4:
+            verify_uchar4(in1, in2);
+            break;
+        case 3:
+            verify_uchar3(in1, in2);
+            break;
+        case 2:
+            verify_uchar2(in1, in2);
+            break;
+        case 1:
+            verify_uchar(in1, in2);
+            break;
+        }
+    } else {
+        switch(vs) {
+        case 4:
+            verify_float4(in1, in2);
+            break;
+        case 3:
+            verify_float3(in1, in2);
+            break;
+        case 2:
+            verify_float2(in1, in2);
+            break;
+        case 1:
+            verify_float(in1, in2);
+            break;
+        }
     }
 
 }
diff --git a/tests/tests/admin/src/android/admin/cts/DeviceAdminActivationTest.java b/tests/tests/admin/src/android/admin/cts/DeviceAdminActivationTest.java
index 2c7d7e9..3e60be1 100644
--- a/tests/tests/admin/src/android/admin/cts/DeviceAdminActivationTest.java
+++ b/tests/tests/admin/src/android/admin/cts/DeviceAdminActivationTest.java
@@ -19,13 +19,14 @@
 import android.app.Activity;
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
+import android.content.Context;
 import android.content.Intent;
 import android.deviceadmin.cts.CtsDeviceAdminBrokenReceiver;
 import android.deviceadmin.cts.CtsDeviceAdminBrokenReceiver2;
 import android.deviceadmin.cts.CtsDeviceAdminBrokenReceiver3;
 import android.deviceadmin.cts.CtsDeviceAdminBrokenReceiver4;
 import android.deviceadmin.cts.CtsDeviceAdminBrokenReceiver5;
-import android.deviceadmin.cts.CtsDeviceAdminReceiver;
+import android.deviceadmin.cts.CtsDeviceAdminDeactivatedReceiver;
 import android.deviceadmin.cts.CtsDeviceAdminActivationTestActivity;
 import android.deviceadmin.cts.CtsDeviceAdminActivationTestActivity.OnActivityResultListener;
 import android.os.SystemClock;
@@ -79,37 +80,49 @@
     }
 
     public void testActivateGoodReceiverDisplaysActivationUi() throws Exception {
-        startAddDeviceAdminActivityForResult(CtsDeviceAdminReceiver.class);
+        assertDeviceAdminDeactivated(CtsDeviceAdminDeactivatedReceiver.class);
+        startAddDeviceAdminActivityForResult(CtsDeviceAdminDeactivatedReceiver.class);
         assertWithTimeoutOnActivityResultNotInvoked();
         // The UI is up and running. Assert that dismissing the UI returns the corresponding result
         // to the test activity.
         finishActivateDeviceAdminActivity();
         assertWithTimeoutOnActivityResultInvokedWithResultCode(Activity.RESULT_CANCELED);
+        assertDeviceAdminDeactivated(CtsDeviceAdminDeactivatedReceiver.class);
     }
 
     public void testActivateBrokenReceiverFails() throws Exception {
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver.class);
         startAddDeviceAdminActivityForResult(CtsDeviceAdminBrokenReceiver.class);
         assertWithTimeoutOnActivityResultInvokedWithResultCode(Activity.RESULT_CANCELED);
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver.class);
     }
 
     public void testActivateBrokenReceiver2Fails() throws Exception {
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver2.class);
         startAddDeviceAdminActivityForResult(CtsDeviceAdminBrokenReceiver2.class);
         assertWithTimeoutOnActivityResultInvokedWithResultCode(Activity.RESULT_CANCELED);
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver2.class);
     }
 
     public void testActivateBrokenReceiver3Fails() throws Exception {
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver3.class);
         startAddDeviceAdminActivityForResult(CtsDeviceAdminBrokenReceiver3.class);
         assertWithTimeoutOnActivityResultInvokedWithResultCode(Activity.RESULT_CANCELED);
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver3.class);
     }
 
     public void testActivateBrokenReceiver4Fails() throws Exception {
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver4.class);
         startAddDeviceAdminActivityForResult(CtsDeviceAdminBrokenReceiver4.class);
         assertWithTimeoutOnActivityResultInvokedWithResultCode(Activity.RESULT_CANCELED);
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver4.class);
     }
 
     public void testActivateBrokenReceiver5Fails() throws Exception {
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver5.class);
         startAddDeviceAdminActivityForResult(CtsDeviceAdminBrokenReceiver5.class);
         assertWithTimeoutOnActivityResultInvokedWithResultCode(Activity.RESULT_CANCELED);
+        assertDeviceAdminDeactivated(CtsDeviceAdminBrokenReceiver5.class);
     }
 
     private void startAddDeviceAdminActivityForResult(Class<?> receiverClass) {
@@ -149,4 +162,12 @@
     private void finishActivateDeviceAdminActivity() {
         getActivity().finishActivity(REQUEST_CODE_ACTIVATE_ADMIN);
     }
+
+    private void assertDeviceAdminDeactivated(Class<?> receiverClass) {
+        DevicePolicyManager devicePolicyManager =
+                (DevicePolicyManager) getActivity().getSystemService(
+                        Context.DEVICE_POLICY_SERVICE);
+        assertFalse(devicePolicyManager.isAdminActive(
+                new ComponentName(getInstrumentation().getTargetContext(), receiverClass)));
+    }
 }
diff --git a/tests/tests/content/src/android/content/cts/ContentProviderTest.java b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
index 34b1e8c..2312e53 100644
--- a/tests/tests/content/src/android/content/cts/ContentProviderTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
@@ -16,33 +16,22 @@
 
 package android.content.cts;
 
-import com.android.cts.stub.R;
-
-
 import android.content.ContentProvider;
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.content.Context;
-import android.content.IContentProvider;
-import android.content.ContentProviderResult;
-import android.content.ContentProviderOperation;
-import android.content.OperationApplicationException;
 import android.content.pm.ProviderInfo;
-import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.net.Uri;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.ICancellationSignal;
 import android.os.ParcelFileDescriptor;
-import android.os.RemoteException;
 import android.test.AndroidTestCase;
 
+import com.android.cts.stub.R;
+
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.util.ArrayList;
 
 /**
  * Test {@link ContentProvider}.
@@ -241,93 +230,6 @@
         // cannot trigger this callback reliably
     }
 
-    public void testCoerceToLocalContentProvider() {
-        MockContentProvider mockContentProvider = new MockContentProvider();
-
-        IContentProvider transport = mockContentProvider.getIContentProvider();
-        assertSame(mockContentProvider, ContentProvider.coerceToLocalContentProvider(transport));
-
-        IContentProvider iContentProvider = new IContentProvider() {
-            @Override
-            public int bulkInsert(String callingPkg, Uri url, ContentValues[] initialValues) {
-                return 0;
-            }
-
-            @Override
-            public int delete(String callingPkg, Uri url, String selection, String[] selectionArgs) {
-                return 0;
-            }
-
-            @Override
-            public String getType(Uri url) {
-                return null;
-            }
-
-            @Override
-            public Uri insert(String callingPkg, Uri url, ContentValues initialValues) {
-                return null;
-            }
-
-            @Override
-            public ParcelFileDescriptor openFile(String callingPkg, Uri url, String mode) {
-                return null;
-            }
-
-            @Override
-            public AssetFileDescriptor openAssetFile(String callingPkg, Uri url, String mode) {
-                return null;
-            }
-
-            @Override
-            public ContentProviderResult[] applyBatch(String callingPkg,
-                    ArrayList<ContentProviderOperation> operations)
-                    throws RemoteException, OperationApplicationException {
-                return null;
-            }
-
-            @Override
-            public Cursor query(String callingPkg, Uri url, String[] projection, String selection,
-                    String[] selectionArgs, String sortOrder,
-                    ICancellationSignal cancellationSignal) {
-                return null;
-            }
-
-            @Override
-            public int update(String callingPkg, Uri url, ContentValues values, String selection,
-                    String[] selectionArgs) {
-                return 0;
-            }
-
-            @Override
-            public IBinder asBinder() {
-                return null;
-            }
-
-            @Override
-            public Bundle call(String callingPkg, String method, String request, Bundle args) {
-                return null;
-            }
-
-            @Override
-            public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException {
-                return null;
-            }
-
-            @Override
-            public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri url,
-                    String mimeType, Bundle opts)
-                    throws RemoteException, FileNotFoundException {
-                return null;
-            }
-
-            @Override
-            public ICancellationSignal createCancellationSignal() throws RemoteException {
-                return null;
-            }
-        };
-        assertNull(ContentProvider.coerceToLocalContentProvider(iContentProvider));
-    }
-
     public void testGetIContentProvider() {
         MockContentProvider mockContentProvider = new MockContentProvider();
 
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
index 60259df..49121fb 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
@@ -72,6 +72,22 @@
         Config.ARGB_4444};
     private static int[] COLOR_TOLS = new int[] {16, 49, 576};
 
+    private static int[] RAW_COLORS = new int[] {
+        // raw data from R.drawable.premul_data
+        Color.argb(255, 0, 0, 0),
+        Color.argb(128, 255, 0, 0),
+        Color.argb(128, 25, 26, 27),
+        Color.argb(2, 255, 254, 253),
+    };
+
+    private static int[] DEPREMUL_COLORS = new int[] {
+        // data from R.drawable.premul_data, after premultiplied store + un-premultiplied load
+        Color.argb(255, 0, 0, 0),
+        Color.argb(128, 255, 0, 0),
+        Color.argb(128, 26, 26, 28),
+        Color.argb(2, 255, 255, 255),
+    };
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -285,13 +301,11 @@
 
         options.inBitmap = reduced;
         options.inSampleSize = 1;
-        boolean failedCorrectly = false;
         try {
             Bitmap original = BitmapFactory.decodeResource(mRes, R.drawable.robot, options);
+            fail("should throw exception due to lack of space");
         } catch (IllegalArgumentException e) {
-            failedCorrectly = true; // fails due to lack of space
         }
-        assertTrue(failedCorrectly);
     }
 
     public void testDecodeReuseScaling() throws IOException {
@@ -351,6 +365,31 @@
         assertSame(densityReduced, scaleReduced);
     }
 
+    public void testDecodePremultipliedDefault() throws IOException {
+        Bitmap simplePremul = BitmapFactory.decodeResource(mRes, R.drawable.premul_data);
+        assertTrue(simplePremul.isPremultiplied());
+    }
+
+    public void testDecodePremultipliedData() throws IOException {
+        BitmapFactory.Options options = new BitmapFactory.Options();
+        options.inScaled = false;
+        Bitmap premul = BitmapFactory.decodeResource(mRes, R.drawable.premul_data, options);
+        options.inPremultiplied = false;
+        Bitmap unpremul = BitmapFactory.decodeResource(mRes, R.drawable.premul_data, options);
+        assertEquals(premul.getConfig(), Bitmap.Config.ARGB_8888);
+        assertEquals(unpremul.getConfig(), Bitmap.Config.ARGB_8888);
+        assertTrue(premul.getHeight() == 1 && unpremul.getHeight() == 1);
+        assertTrue(premul.getWidth() == unpremul.getWidth() &&
+                   DEPREMUL_COLORS.length == RAW_COLORS.length &&
+                   premul.getWidth() == DEPREMUL_COLORS.length);
+
+        // verify pixel data - unpremul should have raw values, premul will have rounding errors
+        for (int i = 0; i < premul.getWidth(); i++) {
+            assertEquals(premul.getPixel(i, 0), DEPREMUL_COLORS[i]);
+            assertEquals(unpremul.getPixel(i, 0), RAW_COLORS[i]);
+        }
+    }
+
     private byte[] obtainArray() {
         ByteArrayOutputStream stm = new ByteArrayOutputStream();
         Options opt = new BitmapFactory.Options();
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
index b6621e8..ce9b6aa 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
@@ -43,6 +43,11 @@
     private Bitmap mBitmap;
     private BitmapFactory.Options mOptions;
 
+    // small alpha values cause color values to be pre-multiplied down, losing accuracy
+    private final int PREMUL_COLOR = Color.argb(2, 255, 254, 253);
+    private final int PREMUL_ROUNDED_COLOR = Color.argb(2, 255, 255, 255);
+    private final int PREMUL_STORED_COLOR = Color.argb(2, 2, 2, 2);
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -695,6 +700,94 @@
         }
     }
 
+    private void checkPremultipliedBitmapConfig(Config config, boolean expectedPremul) {
+        Bitmap bitmap = Bitmap.createBitmap(1, 1, config);
+        bitmap.setPremultiplied(true);
+        bitmap.setPixel(0, 0, Color.TRANSPARENT);
+        assertTrue(bitmap.isPremultiplied() == expectedPremul);
+
+        bitmap.setHasAlpha(false);
+        assertFalse(bitmap.isPremultiplied());
+    }
+
+    public void testSetPremultipliedSimple() {
+        checkPremultipliedBitmapConfig(Bitmap.Config.ALPHA_8, true);
+        checkPremultipliedBitmapConfig(Bitmap.Config.RGB_565, false);
+        checkPremultipliedBitmapConfig(Bitmap.Config.ARGB_4444, true);
+        checkPremultipliedBitmapConfig(Bitmap.Config.ARGB_8888, true);
+    }
+
+    public void testSetPremultipliedData() {
+        // with premul, will store 2,2,2,2, so it doesn't get value correct
+        Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        bitmap.setPixel(0, 0, PREMUL_COLOR);
+        assertEquals(bitmap.getPixel(0, 0), PREMUL_ROUNDED_COLOR);
+
+        // read premultiplied value directly
+        bitmap.setPremultiplied(false);
+        assertEquals(bitmap.getPixel(0, 0), PREMUL_STORED_COLOR);
+
+        // value can now be stored/read correctly
+        bitmap.setPixel(0, 0, PREMUL_COLOR);
+        assertEquals(bitmap.getPixel(0, 0), PREMUL_COLOR);
+
+        // verify with array methods
+        int testArray[] = new int[] { PREMUL_COLOR };
+        bitmap.setPixels(testArray, 0, 1, 0, 0, 1, 1);
+        bitmap.getPixels(testArray, 0, 1, 0, 0, 1, 1);
+        assertEquals(bitmap.getPixel(0, 0), PREMUL_COLOR);
+    }
+
+    public void testPremultipliedCanvas() {
+        Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        bitmap.setHasAlpha(true);
+        bitmap.setPremultiplied(false);
+        assertFalse(bitmap.isPremultiplied());
+
+        Canvas c = new Canvas();
+        try {
+            c.drawBitmap(bitmap, 0, 0, null);
+            fail("canvas should fail with exception");
+        } catch (RuntimeException e) {
+        }
+    }
+
+    private int getBitmapRawInt(Bitmap bitmap) {
+        IntBuffer buffer = IntBuffer.allocate(1);
+        bitmap.copyPixelsToBuffer(buffer);
+        return buffer.get(0);
+    }
+
+    private void bitmapStoreRawInt(Bitmap bitmap, int value) {
+        IntBuffer buffer = IntBuffer.allocate(1);
+        buffer.put(0, value);
+        bitmap.copyPixelsFromBuffer(buffer);
+    }
+
+    public void testSetPremultipliedToBuffer() {
+        Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        bitmap.setPixel(0, 0, PREMUL_COLOR);
+        int storedPremul = getBitmapRawInt(bitmap);
+
+        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        bitmap.setPremultiplied(false);
+        bitmap.setPixel(0, 0, PREMUL_STORED_COLOR);
+
+        assertEquals(getBitmapRawInt(bitmap), storedPremul);
+    }
+
+    public void testSetPremultipliedFromBuffer() {
+        Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        bitmap.setPremultiplied(false);
+        bitmap.setPixel(0, 0, PREMUL_COLOR);
+        int rawTestColor = getBitmapRawInt(bitmap);
+
+        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        bitmap.setPremultiplied(false);
+        bitmapStoreRawInt(bitmap, rawTestColor);
+        assertEquals(bitmap.getPixel(0, 0), PREMUL_COLOR);
+    }
+
     public void testSetWidth() {
         mBitmap = Bitmap.createBitmap(100, 200, Bitmap.Config.ARGB_8888);
         int alloc = mBitmap.getAllocationByteCount();
diff --git a/tests/tests/hardware/Android.mk b/tests/tests/hardware/Android.mk
index 76088a0..77bd2fb 100644
--- a/tests/tests/hardware/Android.mk
+++ b/tests/tests/hardware/Android.mk
@@ -20,7 +20,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner mockito-target
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
new file mode 100644
index 0000000..8509491
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -0,0 +1,417 @@
+/*
+ * Copyright 2013 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.camera2.cts;
+
+import android.content.Context;
+import android.graphics.ImageFormat;
+import android.hardware.camera2.CameraDevice;
+import android.hardware.camera2.CameraManager;
+import android.hardware.camera2.CameraMetadata;
+import android.hardware.camera2.CameraProperties;
+import android.hardware.camera2.CaptureRequest;
+import android.hardware.camera2.CaptureResult;
+import android.media.Image;
+import android.media.ImageReader;
+import android.os.SystemClock;
+import android.test.AndroidTestCase;
+import android.util.Log;
+import android.view.Surface;
+
+import org.mockito.ArgumentMatcher;
+import static org.mockito.Mockito.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * <p>Basic test for CameraDevice APIs.</p>
+ */
+public class CameraDeviceTest extends AndroidTestCase {
+    private static final String TAG = "CameraDeviceTest";
+    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
+
+    private CameraManager mCameraManager;
+    private CameraDevice.ErrorListener mMockErrorListener;
+
+    /**
+     * The error triggered flag starts out as false, and it will flip to true if any errors
+     * are ever caught; it won't be reset to false after that happens. This is due to the
+     * fact that when multiple tests are run back to back (as they are here), it's hard
+     * to associate the asynchronous error with the test that caused it (so we won't even try).
+     */
+    private boolean mErrorTriggered = false;
+    private ImageReader mReader;
+    private CameraTestThread mDummyThread;
+    private Surface mSurface;
+
+    private static final int CAPTURE_WAIT_TIMEOUT_MS = 1000;
+    private static final int ERROR_LISTENER_WAIT_TIMEOUT_MS = 1000;
+    private static final int REPEATING_CAPTURE_EXPECTED_RESULT_COUNT = 5;
+    // VGA size capture is required by CDD.
+    private static final int DEFAULT_CAPTURE_WIDTH = 640;
+    private static final int DEFAULT_CAPTURE_HEIGHT = 480;
+    private static final int MAX_NUM_IMAGES = 5;
+
+    private static int[] mTemplates = new int[] {
+            CameraDevice.TEMPLATE_MANUAL,
+            CameraDevice.TEMPLATE_PREVIEW,
+            CameraDevice.TEMPLATE_RECORD,
+            CameraDevice.TEMPLATE_STILL_CAPTURE,
+            CameraDevice.TEMPLATE_VIDEO_SNAPSHOT
+    };
+
+    @Override
+    public void setContext(Context context) {
+        super.setContext(context);
+        /**
+         * Workaround for mockito and JB-MR2 incompatibility
+         *
+         * Avoid java.lang.IllegalArgumentException: dexcache == null
+         * https://code.google.com/p/dexmaker/issues/detail?id=2
+         */
+        System.setProperty("dexmaker.dexcache", mContext.getCacheDir().toString());
+        /**
+         * Create errorlistener in context scope, to catch asynchronous device error.
+         * Use spy object here since we want to use the SimpleErrorListener callback
+         * implementation (spy doesn't stub the functions unless we ask it to do so).
+         */
+        mMockErrorListener = spy(new SimpleErrorListener());
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        /**
+         * Due to the asynchronous nature of camera device error callback, we
+         * have to make sure device doesn't run into error state before. If so,
+         * fail the rest of the tests. This is especially needed when error
+         * callback is fired too late.
+         */
+        assertFalse("Camera Device runs into error state", mErrorTriggered);
+        mCameraManager = (CameraManager)mContext.getSystemService(Context.CAMERA_SERVICE);
+        assertNotNull("Can't connect to camera manager", mCameraManager);
+        createDefaultSurface();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        mDummyThread.close();
+        mReader.close();
+        super.tearDown();
+    }
+
+    /**
+     * This class need to be public because spy need access it.
+     */
+    public class SimpleErrorListener implements CameraDevice.ErrorListener {
+        @Override
+        public void onCameraDeviceError(CameraDevice camera, int error) {
+            mErrorTriggered = true;
+        }
+    }
+
+    public void testCameraDeviceCreateCaptureRequest() throws Exception {
+        String[] ids = mCameraManager.getDeviceIdList();
+        for (int i = 0; i < ids.length; i++) {
+            CameraDevice camera = null;
+            try {
+                camera = mCameraManager.openCamera(ids[i]);
+                assertNotNull(
+                        String.format("Failed to open camera device ID: %s", ids[i]), camera);
+
+                /**
+                 * Test: that each template type is supported, and that its required fields are
+                 * present.
+                 */
+                for (int j = 0; j < mTemplates.length; j++) {
+                    CaptureRequest capReq = camera.createCaptureRequest(mTemplates[j]);
+                    assertNotNull("Failed to create capture request", capReq);
+                    assertNotNull("Missing field: SENSOR_EXPOSURE_TIME",
+                            capReq.get(CaptureRequest.SENSOR_EXPOSURE_TIME));
+                    assertNotNull("Missing field: SENSOR_SENSITIVITY",
+                            capReq.get(CaptureRequest.SENSOR_SENSITIVITY));
+
+                    // TODO: Add more tests to check more fields.
+                }
+            }
+            finally {
+                if (camera != null) {
+                    camera.close();
+                }
+            }
+        }
+    }
+
+    public void testCameraDeviceGetProperties() throws Exception {
+        String[] ids = mCameraManager.getDeviceIdList();
+        for (int i = 0; i < ids.length; i++) {
+            CameraDevice camera = null;
+            try {
+                camera = mCameraManager.openCamera(ids[i]);
+                assertNotNull(
+                        String.format("Failed to open camera device %s", ids[i]), camera);
+
+                /**
+                 * Test: that the properties can be queried for this device.
+                 */
+                CameraProperties props = camera.getProperties();
+                assertNotNull("Failed to get camera properties", props);
+
+                // TODO: Add more tests to check more fields.
+            }
+            finally {
+                if (camera != null) {
+                    camera.close();
+                }
+            }
+        }
+    }
+
+    public void testCameraDeviceSetErrorListener() throws Exception {
+        String[] ids = mCameraManager.getDeviceIdList();
+        for (int i = 0; i < ids.length; i++) {
+            CameraDevice camera = null;
+            try {
+                camera = mCameraManager.openCamera(ids[i]);
+                assertNotNull(
+                        String.format("Failed to open camera device %s", ids[i]), camera);
+
+                /**
+                 * Test: that the error listener can be set without problems.
+                 * Also, wait some time to check if device doesn't run into error.
+                 */
+                camera.setErrorListener(mMockErrorListener);
+                SystemClock.sleep(ERROR_LISTENER_WAIT_TIMEOUT_MS);
+                verify(mMockErrorListener, never())
+                        .onCameraDeviceError(
+                                any(CameraDevice.class),
+                                anyInt());
+            }
+            finally {
+                if (camera != null) {
+                    camera.close();
+                }
+            }
+        }
+    }
+
+    public void testCameraDeviceCapture() throws Exception {
+        runCaptureTest(false, false);
+    }
+
+    public void testCameraDeviceCaptureBurst() throws Exception {
+        runCaptureTest(true, false);
+    }
+
+    public void testCameraDeviceRepeatingRequest() throws Exception {
+        runCaptureTest(false, true);
+    }
+
+    public void testCameraDeviceRepeatingBurst() throws Exception {
+        runCaptureTest(true, true);
+    }
+
+    private class IsCameraMetadataNotEmpty<T extends CameraMetadata>
+            extends ArgumentMatcher<T> {
+        public boolean matches(Object obj) {
+            /**
+             * Do the simple verification here. Only verify the timestamp for now.
+             * TODO: verify more required capture result metadata fields.
+             */
+            CameraMetadata result = (CameraMetadata) obj;
+            Long timeStamp = result.get(CaptureResult.SENSOR_TIMESTAMP);
+            if (timeStamp != null && timeStamp.longValue() > 0L) {
+                return true;
+            }
+            return false;
+        }
+    }
+
+    private void runCaptureTest(boolean burst, boolean repeating) throws Exception {
+        String[] ids = mCameraManager.getDeviceIdList();
+        for (int i = 0; i < ids.length; i++) {
+            CameraDevice camera = null;
+            try {
+                camera = mCameraManager.openCamera(ids[i]);
+                assertNotNull(
+                        String.format("Failed to open camera device %s", ids[i]), camera);
+                camera.setErrorListener(mMockErrorListener);
+
+                prepareCapture(camera);
+
+                if (!burst) {
+                    // Test: that a single capture of each template type succeeds.
+                    for (int j = 0; j < mTemplates.length; j++) {
+                        captureSingleShot(camera, ids[i], mTemplates[j], repeating);
+                    }
+                }
+                else {
+                    // Test: burst of zero shots
+                    captureBurstShot(camera, ids[i], mTemplates, 0, repeating);
+
+                    // Test: burst of one shot
+                    captureBurstShot(camera, ids[i], mTemplates, 1, repeating);
+
+                    int[] templates = new int[] {
+                            CameraDevice.TEMPLATE_STILL_CAPTURE,
+                            CameraDevice.TEMPLATE_STILL_CAPTURE,
+                            CameraDevice.TEMPLATE_STILL_CAPTURE,
+                            CameraDevice.TEMPLATE_STILL_CAPTURE,
+                            CameraDevice.TEMPLATE_STILL_CAPTURE
+                            };
+
+                    // Test: burst of 5 shots of the same template type
+                    captureBurstShot(camera, ids[i], templates, templates.length, repeating);
+
+                    // Test: burst of 5 shots of different template types
+                    captureBurstShot(camera, ids[i], mTemplates, mTemplates.length, repeating);
+                }
+                verify(mMockErrorListener, never())
+                        .onCameraDeviceError(
+                                any(CameraDevice.class),
+                                anyInt());
+            }
+            finally {
+                if (camera != null) {
+                    camera.close();
+                }
+            }
+        }
+    }
+
+    private void captureSingleShot(
+            CameraDevice camera,
+            String id,
+            int template,
+            boolean repeating) throws Exception {
+
+        CaptureRequest request = camera.createCaptureRequest(template);
+        assertNotNull("Failed to create capture request", request);
+        request.addTarget(mSurface);
+        CameraDevice.CaptureListener mockCaptureListener =
+                mock(CameraDevice.CaptureListener.class);
+
+        if (VERBOSE) {
+            Log.v(TAG, String.format("Capturing shot for device %s, template %d",
+                    id, template));
+        }
+        if (!repeating) {
+            camera.capture(request, mockCaptureListener);
+        }
+        else {
+            camera.setRepeatingRequest(request, mockCaptureListener);
+        }
+
+        int expectedCaptureResultCount = repeating ? REPEATING_CAPTURE_EXPECTED_RESULT_COUNT : 1;
+        verifyCaptureResults(mockCaptureListener, expectedCaptureResultCount);
+
+        if (repeating) {
+            camera.stopRepeating();
+            camera.waitUntilIdle();
+        }
+    }
+
+    private void captureBurstShot(
+            CameraDevice camera,
+            String id,
+            int[] templates,
+            int len,
+            boolean repeating) throws Exception {
+
+        assertTrue("Invalid args to capture function", len <= templates.length);
+        List<CaptureRequest> requests = new ArrayList<CaptureRequest>();
+        for (int i = 0; i < len; i++) {
+            CaptureRequest request = camera.createCaptureRequest(templates[i]);
+            assertNotNull("Failed to create capture request", request);
+            request.addTarget(mSurface);
+            requests.add(request);
+        }
+        CameraDevice.CaptureListener mockCaptureListener =
+                mock(CameraDevice.CaptureListener.class);
+
+        if (VERBOSE) {
+            Log.v(TAG, String.format("Capturing burst shot for device %s", id));
+        }
+
+        if (!repeating) {
+            camera.captureBurst(requests, mockCaptureListener);
+        }
+        else {
+            camera.setRepeatingBurst(requests, mockCaptureListener);
+        }
+        int expectedResultCount = len;
+        if (repeating) {
+            expectedResultCount *= REPEATING_CAPTURE_EXPECTED_RESULT_COUNT;
+        }
+
+        verifyCaptureResults(mockCaptureListener, expectedResultCount);
+
+        if (repeating) {
+            camera.stopRepeating();
+            camera.waitUntilIdle();
+        }
+    }
+
+    private void prepareCapture(CameraDevice camera) throws Exception {
+        List<Surface> outputSurfaces = new ArrayList<Surface>(1);
+        outputSurfaces.add(mSurface);
+        camera.configureOutputs(outputSurfaces);
+    }
+
+    /**
+     * Dummy listener that release the image immediately once it is available.
+     * It can be used for the case where we don't care the image data at all.
+     * TODO: move it to the CameraTestUtil class.
+     */
+    private class ImageDropperListener implements ImageReader.OnImageAvailableListener {
+        @Override
+        public void onImageAvailable(ImageReader reader) {
+            Image image = reader.getNextImage();
+            image.close();
+        }
+    }
+
+    private void createDefaultSurface() throws Exception {
+        ImageReader mReader =
+                new ImageReader(DEFAULT_CAPTURE_WIDTH,
+                        DEFAULT_CAPTURE_HEIGHT,
+                        ImageFormat.YUV_420_888,
+                        MAX_NUM_IMAGES);
+        mSurface = mReader.getSurface();
+        // Create dummy image listener since we don't care the image data in this test.
+        ImageReader.OnImageAvailableListener listener = new ImageDropperListener();
+        CameraTestThread mDummyThread = new CameraTestThread();
+        mReader.setImageAvailableListener(listener, mDummyThread.start());
+    }
+
+    private void verifyCaptureResults(
+            CameraDevice.CaptureListener mockListener,
+            int expectResultCount) {
+        // Should receive expected number of capture results.
+        verify(mockListener,
+                timeout(CAPTURE_WAIT_TIMEOUT_MS).atLeast(expectResultCount))
+                        .onCaptureComplete(
+                                any(CameraDevice.class),
+                                argThat(new IsCameraMetadataNotEmpty<CaptureRequest>()),
+                                argThat(new IsCameraMetadataNotEmpty<CaptureResult>()));
+        // Should not receive any capture failed callbacks.
+        verify(mockListener, never())
+                        .onCaptureFailed(
+                                any(CameraDevice.class),
+                                argThat(new IsCameraMetadataNotEmpty<CaptureRequest>()));
+    }
+}
diff --git a/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java b/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java
index a8131bf..fe145cf 100644
--- a/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java
@@ -49,6 +49,16 @@
         assertFalse(MediaDrm.isCryptoSchemeSupported(badScheme));
     }
 
+    public void testIsMimeTypeSupported() throws Exception {
+        String mimeType = "video/mp4";
+        assertTrue(MediaDrm.isCryptoSchemeSupported(mockScheme, mimeType));
+    }
+
+    public void testIsMimeTypeNotSupported() throws Exception {
+        String mimeType = "video/foo";
+        assertFalse(MediaDrm.isCryptoSchemeSupported(mockScheme, mimeType));
+    }
+
     public void testMediaDrmConstructor() throws Exception {
         if (isMockPluginInstalled()) {
             MediaDrm md = new MediaDrm(mockScheme);
diff --git a/tests/tests/media/src/android/media/cts/StreamingMediaPlayerTest.java b/tests/tests/media/src/android/media/cts/StreamingMediaPlayerTest.java
index a3c9454..1d78967 100644
--- a/tests/tests/media/src/android/media/cts/StreamingMediaPlayerTest.java
+++ b/tests/tests/media/src/android/media/cts/StreamingMediaPlayerTest.java
@@ -96,7 +96,7 @@
                 + "&sparams=ip,ipbits,expire,id,itag,source"
                 + "&signature=3CFCAFB87EB9FC943FACDC54FEC8C725A801642C."
                 + "7D77ACBC4CAF40349BF093E302B635757E45F345"
-                + "&key=test_key1&user=android-device-test", 480, 270);
+                + "&key=test_key1&user=android-device-test", 640, 360);
     }
     public void testHTTP_H264Base_AAC_Video2() throws Exception {
         playVideoTest("http://redirector.c.youtube.com/videoplayback?id=c80658495af60617"
@@ -104,7 +104,7 @@
                 + "&sparams=ip,ipbits,expire,id,itag,source"
                 + "&signature=A11D8BA0AA67A27F1409BE0C0B96B756625DB88B."
                 + "9BF4C93A130583ADBDF2B953AD5A8A58F518B012"
-                + "&key=test_key1&user=android-device-test", 480, 270);
+                + "&key=test_key1&user=android-device-test", 640, 360);
     }
 
     // Streaming HLS video from YouTube
diff --git a/tests/tests/net/src/android/net/cts/SSLCertificateSocketFactoryTest.java b/tests/tests/net/src/android/net/cts/SSLCertificateSocketFactoryTest.java
index 70ab54d..ceb74d1 100644
--- a/tests/tests/net/src/android/net/cts/SSLCertificateSocketFactoryTest.java
+++ b/tests/tests/net/src/android/net/cts/SSLCertificateSocketFactoryTest.java
@@ -86,9 +86,9 @@
     }
 
     // a host and port that are expected to be available but have
-    // a cert with a different CN, in this case CN=mtalk.google.com
-    private static String TEST_CREATE_SOCKET_HOST = "mobile-gtalk.l.google.com";
-    private static int TEST_CREATE_SOCKET_PORT = 5228;
+    // a cert with a different CN, in this case CN=mail.google.com
+    private static String TEST_CREATE_SOCKET_HOST = "googlemail.com";
+    private static int TEST_CREATE_SOCKET_PORT = 443;
 
     /**
      * b/2807618 Make sure that hostname verifcation in cases were it
diff --git a/tests/tests/net/src/android/net/ipv6/cts/PingTest.java b/tests/tests/net/src/android/net/ipv6/cts/PingTest.java
new file mode 100644
index 0000000..41eb03d
--- /dev/null
+++ b/tests/tests/net/src/android/net/ipv6/cts/PingTest.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2013 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.ipv6.cts;
+
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import libcore.io.ErrnoException;
+import libcore.io.Libcore;
+import libcore.io.StructTimeval;
+import static libcore.io.OsConstants.*;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Inet6Address;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Random;
+
+public class PingTest extends AndroidTestCase {
+    /** Maximum size of the packets we're using to test. */
+    private static final int MAX_SIZE = 4096;
+
+    /** Number of packets to test. */
+    private static final int NUM_PACKETS = 10;
+
+    /** The beginning of an ICMPv6 echo request: type, code, and uninitialized checksum. */
+    private static final byte[] PING_HEADER = new byte[] {
+        (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00
+    };
+
+    /**
+     * Returns a byte array containing an ICMPv6 echo request with the specified payload length.
+     */
+    private byte[] pingPacket(int payloadLength) {
+        byte[] packet = new byte[payloadLength + 8];
+        new Random().nextBytes(packet);
+        System.arraycopy(PING_HEADER, 0, packet, 0, PING_HEADER.length);
+        return packet;
+    }
+
+    /**
+     * Checks that the first length bytes of two byte arrays are equal.
+     */
+    private void assertArrayBytesEqual(byte[] expected, byte[] actual, int length) {
+        for (int i = 0; i < length; i++) {
+            assertEquals("Arrays differ at index " + i + ":", expected[i], actual[i]);
+        }
+    }
+
+    /**
+     * Creates an IPv6 ping socket and sets a receive timeout of 100ms.
+     */
+    private FileDescriptor createPingSocket() throws ErrnoException {
+        FileDescriptor s = Libcore.os.socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
+        Libcore.os.setsockoptTimeval(s, SOL_SOCKET, SO_RCVTIMEO, StructTimeval.fromMillis(100));
+        return s;
+    }
+
+    /**
+     * Sends a ping packet to a random port on the specified address on the specified socket.
+     */
+    private void sendPing(FileDescriptor s,
+            InetAddress address, byte[] packet) throws ErrnoException, IOException {
+        // Pick a random port. Choose a range that gives a reasonable chance of picking a low port.
+        int port = (int) (Math.random() * 2048);
+
+        // Send the packet.
+        int ret = Libcore.os.sendto(s, ByteBuffer.wrap(packet), 0, address, port);
+        assertEquals(packet.length, ret);
+    }
+
+    /**
+     * Checks that a socket has received a response appropriate to the specified packet.
+     */
+    private void checkResponse(FileDescriptor s,
+            InetAddress dest, byte[] sent) throws ErrnoException, IOException {
+        // Receive the response.
+        InetSocketAddress from = new InetSocketAddress();
+        ByteBuffer responseBuffer = ByteBuffer.allocate(MAX_SIZE);
+        int bytesRead = Libcore.os.recvfrom(s, responseBuffer, 0, from);
+
+        // Check the source address and scope ID.
+        assertTrue(from.getAddress() instanceof Inet6Address);
+        Inet6Address fromAddress = (Inet6Address) from.getAddress();
+        assertEquals(0, fromAddress.getScopeId());
+        assertNull(fromAddress.getScopedInterface());
+        assertEquals(dest.getHostAddress(), fromAddress.getHostAddress());
+
+        // Check the packet length.
+        assertEquals(sent.length, bytesRead);
+
+        // Check the response is an echo reply.
+        byte[] response = new byte[bytesRead];
+        responseBuffer.get(response, 0, bytesRead);
+        assertEquals((byte) 0x81, response[0]);
+
+        // Find out what ICMP ID was used in the packet that was sent.
+        int id = ((InetSocketAddress) Libcore.os.getsockname(s)).getPort();
+        sent[4] = (byte) (id / 256);
+        sent[5] = (byte) (id % 256);
+
+        // Ensure the response is the same as the packet, except for the type (which is 0x81)
+        // and the ID and checksum,  which are set by the kernel.
+        response[0] = (byte) 0x80;                 // Type.
+        response[2] = response[3] = (byte) 0x00;   // Checksum.
+        assertArrayBytesEqual(response, sent, bytesRead);
+    }
+
+    /**
+     * Sends NUM_PACKETS random ping packets to ::1 and checks the replies.
+     */
+    public void testLoopbackPing() throws ErrnoException, IOException {
+        // Generate a random ping packet and send it to localhost.
+        InetAddress ipv6Loopback = InetAddress.getByName(null);
+        assertEquals("localhost/::1", ipv6Loopback.toString());
+
+        for (int i = 0; i < NUM_PACKETS; i++) {
+            byte[] packet = pingPacket((int) (Math.random() * MAX_SIZE));
+            FileDescriptor s = createPingSocket();
+            sendPing(s, ipv6Loopback, packet);
+            checkResponse(s, ipv6Loopback, packet);
+            // Check closing the socket doesn't raise an exception.
+            Libcore.os.close(s);
+        }
+    }
+}
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index fae7d1f..3f6743e 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -157,7 +157,7 @@
     private static final Pattern PRODUCT_PATTERN =
         Pattern.compile("^([0-9A-Za-z._-]+)$");
     private static final Pattern SERIAL_NUMBER_PATTERN =
-        Pattern.compile("^([0-9A-Za-z]{0,20})$");
+        Pattern.compile("^([0-9A-Za-z]{6,20})$");
     private static final Pattern TAGS_PATTERN =
         Pattern.compile("^([0-9A-Za-z.,_-]+)$");
     private static final Pattern TYPE_PATTERN =
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index 633d5d7..f42b7f2 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -762,6 +762,24 @@
                 insecure.isEmpty());
     }
 
+    public void testDevRandomWorldReadableAndWritable() throws Exception {
+        FileUtils.FileStatus status = new FileUtils.FileStatus();
+        assertTrue(FileUtils.getFileStatus("/dev/random", status, false));
+        assertTrue(
+                "/dev/random not world-readable/writable. Actual mode: 0"
+                        + Integer.toString(status.mode, 8),
+                (status.mode & 0666) == 0666);
+    }
+
+    public void testDevUrandomWorldReadableAndWritable() throws Exception {
+        FileUtils.FileStatus status = new FileUtils.FileStatus();
+        assertTrue(FileUtils.getFileStatus("/dev/urandom", status, false));
+        assertTrue(
+                "/dev/urandom not world-readable/writable. Actual mode: 0"
+                        + Integer.toString(status.mode, 8),
+                (status.mode & 0666) == 0666);
+    }
+
     private static Set<File>
     getAllInsecureDevicesInDirAndSubdir(File dir, int type) throws Exception {
         assertTrue(dir.isDirectory());
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java
index 179f2eb..8e43aeb 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java
@@ -59,19 +59,6 @@
         return e;
     }
 
-    protected int getVerifyEnum(Element.DataType dt, int vecSize) {
-        if (dt == Element.DataType.FLOAT_32) {
-            return 8 - vecSize;
-        }
-
-        // U8
-        return 4 - vecSize;
-    }
-
-    protected int getVerifyEnum(Element e) {
-        return getVerifyEnum(e.getDataType(), e.getVectorSize());
-    }
-
     protected void makeSource(int w, int h, Element e) {
         System.gc();
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java
index 0c44e34..20ee2e6 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java
@@ -51,20 +51,52 @@
         mSr.invoke_reference(mat, add, mAllocSrc, mAllocRef);
 
         android.util.Log.e("RSI test", "test ColorMatrix U8_" + vsIn + " 1 " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst, getVerifyEnum(eout));
+        mVerify.invoke_verify(mAllocRef, mAllocDst);
         mRS.finish();
     }
 
 
-    public void test_U8_4() {
+    public void test_U8_U8() {
         Float4 add = new Float4();
         Matrix4f mat = new Matrix4f();
+        java.util.Random r = new java.util.Random(100);
 
-        subtest(100, 100, mat, add,
-                Element.DataType.UNSIGNED_8, 4,
-                Element.DataType.UNSIGNED_8, 4);
-        checkError();
+        for (int t=0; t < 1; t++) {
+            float f[] = mat.getArray();
+            for (int i=0; i < f.length; i++) {
+                f[i] = 0.f;
+            }
+
+
+            switch (t) {
+            case 0:
+                mat.loadIdentity();
+                break;
+            case 1:
+                mat.set(0, 0, 1.f);
+                mat.set(0, 1, 1.f);
+                mat.set(0, 2, 1.f);
+                break;
+            case 2:
+                for (int i=0; i < f.length; i++) {
+                    if (r.nextFloat() > 0.2f) {
+                        f[i] = 10.f * r.nextFloat();
+                    }
+                }
+
+            }
+
+            for (int i=1; i <= 4; i++) {
+                for (int j=1; j <=4; j++) {
+                    subtest(100, 100, mat, add,
+                            Element.DataType.UNSIGNED_8, i,
+                            Element.DataType.UNSIGNED_8, j);
+                    checkError();
+                }
+            }
+        }
     }
 
 
+
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java
index 11a70c3..7354db5 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java
@@ -74,7 +74,7 @@
         }
 
         android.util.Log.e("RSI test", "test convolve U8_" + vecSize + " 1 " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst, getVerifyEnum(e));
+        mVerify.invoke_verify(mAllocRef, mAllocDst);
 
         si.setCoefficients(cf2);
         sr.set_gCoeffs(cf2);
@@ -111,7 +111,7 @@
             }
         }
         android.util.Log.e("RSI test", "test convolve U8_" + vecSize + " 2 " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst, getVerifyEnum(e));
+        mVerify.invoke_verify(mAllocRef, mAllocDst);
         mRS.finish();
     }
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java
index 69ab17a..ebdf501 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java
@@ -63,7 +63,7 @@
         }
 
         android.util.Log.e("RSI test", name + "  " + e.getVectorSize() + " " + num + " " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst, getVerifyEnum(e));
+        mVerify.invoke_verify(mAllocRef, mAllocDst);
         mRS.finish();
     }