Merge "Fix ExcludeWatch"
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
index 13b2ec3..b4b99db 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
@@ -16,15 +16,20 @@
 
 package com.android.cts.verifier;
 
+import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
+
+import android.Manifest;
 import android.app.AlertDialog;
 import android.app.ListActivity;
 import android.content.DialogInterface;
+import android.content.Intent;
 import android.content.SharedPreferences;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.PermissionInfo;
+import android.net.Uri;
 import android.os.Bundle;
+import android.provider.Settings;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuInflater;
@@ -35,9 +40,13 @@
 import android.widget.Switch;
 import android.widget.Toast;
 
+import java.util.Arrays;
+import java.util.Objects;
+
 /** Top-level {@link ListActivity} for launching tests and managing results. */
 public class TestListActivity extends AbstractTestListActivity implements View.OnClickListener {
     private static final int CTS_VERIFIER_PERMISSION_REQUEST = 1;
+    private static final int CTS_VERIFIER_BACKGROUND_LOCATION_PERMISSION_REQUEST = 2;
 
     private static final String TAG = TestListActivity.class.getSimpleName();
     // Records the current display mode.
@@ -84,25 +93,17 @@
                     getApplicationInfo().packageName, PackageManager.GET_PERMISSIONS);
 
             if (packageInfo.requestedPermissions != null) {
-                for (String permission : packageInfo.requestedPermissions) {
-                    Log.v(TAG, "Checking permissions for: " + permission);
+                String[] permissionsToRequest = removeString(packageInfo.requestedPermissions,
+                                Manifest.permission.ACCESS_BACKGROUND_LOCATION);
+                permissionsToRequest = Arrays.stream(permissionsToRequest).filter(s -> {
                     try {
-                        PermissionInfo info = pm.getPermissionInfo(permission, 0);
-                        if ((info.protectionLevel & PermissionInfo.PROTECTION_DANGEROUS) == 0) {
-                            continue;
-                        }
+                        return (pm.getPermissionInfo(s, 0).getProtection() & PROTECTION_DANGEROUS)
+                                != 0;
                     } catch (NameNotFoundException e) {
-                        Log.v(TAG, "Checking permissions for: " + permission + "not found");
-                        continue;
+                        return false;
                     }
-                    if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
-                        requestPermissions(packageInfo.requestedPermissions,
-                                CTS_VERIFIER_PERMISSION_REQUEST);
-                        /* don't return here. Some tests (i.e. USB Restrict Access test)
-                         * which need to run even if permissions are incomplete.
-                         */
-                    }
-                }
+                }).toArray(String[]::new);
+                requestPermissions(permissionsToRequest, CTS_VERIFIER_PERMISSION_REQUEST);
             }
             createContinue();
         } catch (NameNotFoundException e) {
@@ -117,6 +118,11 @@
         }
         sInitialLaunch = true;
 
+        // Restores the last display mode when launching the app after killing the process.
+        if (getCurrentDisplayMode().equals(DisplayMode.FOLDED.toString())) {
+            sCurrentDisplayMode = DisplayMode.FOLDED.toString();
+        }
+
         setTitle(getString(R.string.title_version, Version.getVersionName(this)));
 
         if (!getWindow().hasFeature(Window.FEATURE_ACTION_BAR)) {
@@ -135,13 +141,37 @@
     public void onRequestPermissionsResult(
             int requestCode, String permissions[], int[] grantResults) {
         if (requestCode == CTS_VERIFIER_PERMISSION_REQUEST) {
-            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
-                createContinue();
-                return;
+            if (arrayContains(grantResults, PackageManager.PERMISSION_DENIED)) {
+                Log.v(TAG, "Didn't grant all permissions.");
+                // If we're sending them to settings we don't need to request background location
+                // since they can just grant in settings.
+                sendUserToSettings();
+            } else {
+                requestPermissions(new String[] {Manifest.permission.ACCESS_BACKGROUND_LOCATION},
+                        CTS_VERIFIER_BACKGROUND_LOCATION_PERMISSION_REQUEST);
             }
-            Log.v(TAG, "Permission not granted.");
-            Toast.makeText(this, R.string.runtime_permissions_error, Toast.LENGTH_SHORT).show();
         }
+        if (requestCode == CTS_VERIFIER_BACKGROUND_LOCATION_PERMISSION_REQUEST) {
+            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
+                Log.v(TAG, "Didn't grant background permission.");
+                sendUserToSettings();
+            }
+            return;
+        }
+    }
+
+    private AlertDialog sendUserToSettings() {
+        return new AlertDialog.Builder(this)
+                .setTitle("Please grant all permissions")
+                .setPositiveButton(
+                        "Ok", (dialog, which) -> {
+                            if (which == AlertDialog.BUTTON_POSITIVE) {
+                                startActivity(new Intent(
+                                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(
+                                        Uri.fromParts("package", getPackageName(), null)));
+                            }
+                        })
+                .show();
     }
 
     @Override
@@ -154,14 +184,8 @@
         item.setActionView(R.layout.display_mode_switch);
         Switch displayModeSwitch = item.getActionView().findViewById(R.id.switch_button);
 
-        // Restores the original display mode when launching the app after killing the process.
-        // Otherwise, gets the current display mode to show switch status.
-        boolean isFoldedMode;
-        if (sInitialLaunch) {
-            isFoldedMode = getCurrentDisplayMode().equals(DisplayMode.FOLDED.toString());
-        } else {
-            isFoldedMode = sCurrentDisplayMode.equals(DisplayMode.FOLDED.toString());
-        }
+        // Get the current display mode to show switch status.
+        boolean isFoldedMode = sCurrentDisplayMode.equals(DisplayMode.FOLDED.toString());
         displayModeSwitch.setChecked(isFoldedMode);
 
         displayModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@@ -244,4 +268,34 @@
             .getString(DisplayMode.class.getName(), "");
         return mode;
     }
-}
\ No newline at end of file
+
+    private static boolean arrayContains(int[] array, int value) {
+        if (array == null) return false;
+        for (int element : array) {
+            if (element == value) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static String[] removeString(String[] cur, String val) {
+        if (cur == null) {
+            return null;
+        }
+        final int n = cur.length;
+        for (int i = 0; i < n; i++) {
+            if (Objects.equals(cur[i], val)) {
+                String[] ret = new String[n - 1];
+                if (i > 0) {
+                    System.arraycopy(cur, 0, ret, 0, i);
+                }
+                if (i < (n - 1)) {
+                    System.arraycopy(cur, i + 1, ret, i, n - i - 1);
+                }
+                return ret;
+            }
+        }
+        return cur;
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java
index 24f55a4..4b682c1 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java
@@ -14,15 +14,16 @@
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
 import android.os.Bundle;
+import android.os.UserHandle;
 import android.util.Log;
 
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
 @TargetApi(19)
 public abstract class BaseEmulatorActivity extends PassFailButtons.Activity {
     static final String TAG = "BaseEmulatorActivity";
@@ -105,10 +106,14 @@
             builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
-                Intent changeDefault = new Intent(CardEmulation.ACTION_CHANGE_DEFAULT);
-                changeDefault.putExtra(CardEmulation.EXTRA_CATEGORY, CardEmulation.CATEGORY_PAYMENT);
-                changeDefault.putExtra(CardEmulation.EXTRA_SERVICE_COMPONENT, defaultComponent);
-                startActivityForResult(changeDefault, 0);
+                    Intent changeDefault = new Intent(CardEmulation.ACTION_CHANGE_DEFAULT);
+                    changeDefault.putExtra(CardEmulation.EXTRA_CATEGORY,
+                            CardEmulation.CATEGORY_PAYMENT);
+                    changeDefault.putExtra(CardEmulation.EXTRA_SERVICE_COMPONENT, defaultComponent);
+                    changeDefault.putExtra(CardEmulation.EXTRA_USERID,
+                            UserHandle.getUserHandleForUid(getApplicationInfo().uid)
+                            .getIdentifier());
+                    startActivityForResult(changeDefault, 0);
                 }
             });
             builder.show();
diff --git a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
index 0ce176e..d6a3548 100644
--- a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
+++ b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
@@ -26,6 +26,7 @@
 import android.compat.testing.Classpaths;
 
 import com.android.compatibility.common.util.ApiLevelUtil;
+import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.log.LogUtil;
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
@@ -195,6 +196,28 @@
                     "Lcom/android/internal/util/FrameworkStatsLog;"
             );
 
+    private static final String FEATURE_WEARABLE = "android.hardware.type.watch";
+    private static final String FEATURE_AUTOMOTIVE = "android.hardware.type.automotive";
+
+    private static final Set<String> WEAR_HIDL_OVERLAP_BURNDOWN_LIST =
+        ImmutableSet.of(
+            "Landroid/hidl/base/V1_0/DebugInfo$Architecture;",
+            "Landroid/hidl/base/V1_0/IBase;",
+            "Landroid/hidl/base/V1_0/IBase$Proxy;",
+            "Landroid/hidl/base/V1_0/IBase$Stub;",
+            "Landroid/hidl/base/V1_0/DebugInfo;",
+            "Landroid/hidl/safe_union/V1_0/Monostate;"
+        );
+
+    private static final Set<String> AUTOMOTIVE_HIDL_OVERLAP_BURNDOWN_LIST =
+        ImmutableSet.of(
+            "Landroid/hidl/base/V1_0/DebugInfo$Architecture;",
+            "Landroid/hidl/base/V1_0/IBase;",
+            "Landroid/hidl/base/V1_0/IBase$Proxy;",
+            "Landroid/hidl/base/V1_0/IBase$Stub;",
+            "Landroid/hidl/base/V1_0/DebugInfo;"
+        );
+
     /**
      * Ensure that there are no duplicate classes among jars listed in BOOTCLASSPATH.
      */
@@ -214,7 +237,19 @@
         assumeTrue(ApiLevelUtil.isAfter(getDevice(), 29));
         ImmutableList<String> jars =
                 Classpaths.getJarsOnClasspath(getDevice(), SYSTEMSERVERCLASSPATH);
-        assertThat(getDuplicateClasses(jars)).isEmpty();
+        ImmutableSet<String> overlapBurndownList;
+        if (hasFeature(FEATURE_AUTOMOTIVE)) {
+            overlapBurndownList = ImmutableSet.copyOf(AUTOMOTIVE_HIDL_OVERLAP_BURNDOWN_LIST);
+        } else if (hasFeature(FEATURE_WEARABLE)) {
+            overlapBurndownList = ImmutableSet.copyOf(WEAR_HIDL_OVERLAP_BURNDOWN_LIST);
+        } else {
+            overlapBurndownList = ImmutableSet.of();
+        }
+        Multimap<String, String> duplicates = getDuplicateClasses(jars);
+        Multimap<String, String> filtered = Multimaps.filterKeys(duplicates,
+                duplicate -> !overlapBurndownList.contains(duplicate));
+
+        assertThat(filtered).isEmpty();
     }
 
     /**
@@ -227,10 +262,21 @@
         ImmutableList.Builder<String> jars = ImmutableList.builder();
         jars.addAll(Classpaths.getJarsOnClasspath(getDevice(), BOOTCLASSPATH));
         jars.addAll(Classpaths.getJarsOnClasspath(getDevice(), SYSTEMSERVERCLASSPATH));
-
+        ImmutableSet<String> overlapBurndownList;
+        if (hasFeature(FEATURE_AUTOMOTIVE)) {
+            overlapBurndownList = ImmutableSet.<String>builder()
+                    .addAll(BCP_AND_SSCP_OVERLAP_BURNDOWN_LIST)
+                    .addAll(AUTOMOTIVE_HIDL_OVERLAP_BURNDOWN_LIST).build();
+        } else if (hasFeature(FEATURE_WEARABLE)) {
+            overlapBurndownList = ImmutableSet.<String>builder()
+                    .addAll(BCP_AND_SSCP_OVERLAP_BURNDOWN_LIST)
+                    .addAll(WEAR_HIDL_OVERLAP_BURNDOWN_LIST).build();
+        } else {
+            overlapBurndownList = ImmutableSet.copyOf(BCP_AND_SSCP_OVERLAP_BURNDOWN_LIST);
+        }
         Multimap<String, String> duplicates = getDuplicateClasses(jars.build());
         Multimap<String, String> filtered = Multimaps.filterKeys(duplicates,
-                duplicate -> !BCP_AND_SSCP_OVERLAP_BURNDOWN_LIST.contains(duplicate));
+                duplicate -> !overlapBurndownList.contains(duplicate));
 
         assertThat(filtered).isEmpty();
     }
@@ -314,4 +360,8 @@
 
         return duplicates;
     }
+
+    private boolean hasFeature(String featureName) throws DeviceNotAvailableException {
+        return getDevice().executeShellCommand("pm list features").contains(featureName);
+    }
 }
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
index 2e48fa5..0405b52 100755
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
@@ -522,6 +522,9 @@
      * algorithms.
      */
     public void testCanGenerateKeyPairWithKeyAttestation() throws Exception {
+        if (!isAttestationSupported()) {
+            return;
+        }
         for (SupportedKeyAlgorithm supportedKey : SUPPORTED_KEY_ALGORITHMS) {
             assertThat(
                     generateKeyAndCheckAttestation(
@@ -1022,4 +1025,8 @@
     boolean isUniqueDeviceAttestationSupported() {
         return mDevicePolicyManager.isUniqueDeviceAttestationSupported();
     }
+
+    private boolean isAttestationSupported() {
+        return Build.VERSION.DEVICE_INITIAL_SDK_INT >= Build.VERSION_CODES.O;
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
index 499a0e4..33a58ed 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -186,6 +186,8 @@
     /** Users we shouldn't delete in the tests */
     private ArrayList<Integer> mFixedUsers;
 
+    protected boolean mHasAttestation;
+
     private static final String VERIFY_CREDENTIAL_CONFIRMATION = "Lock credential verified";
 
     @Rule
@@ -205,6 +207,10 @@
         mFixedPackages = getDevice().getInstalledPackageNames();
         mBuildHelper = new CompatibilityBuildHelper(getBuild());
 
+        String propertyValue = getDevice().getProperty("ro.product.first_api_level");
+        if (propertyValue != null && !propertyValue.isEmpty()) {
+            mHasAttestation = Integer.parseInt(propertyValue) >= 26;
+        }
         if (hasDeviceFeature(FEATURE_SECURE_LOCK_SCREEN)) {
             ensurePrimaryUserHasNoPassword();
         }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index fa044ad..56e62f7 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -830,6 +830,8 @@
     // the DelegatedCertinstallerTest.
     @Test
     public void testDelegatedCertInstallerDirectly() throws Exception {
+        assumeTrue(mHasAttestation);
+
         setUpDelegatedCertInstallerAndRunTests(() ->
             runDeviceTestsAsUser("com.android.cts.certinstaller",
                     ".DirectDelegatedCertInstallerTest", mUserId));
@@ -839,6 +841,8 @@
     // access to it.
     @Test
     public void testSetKeyGrant() throws Exception {
+        assumeTrue(mHasAttestation);
+
         // Install an app
         installAppAsUser(CERT_INSTALLER_APK, mUserId);
 
@@ -1335,6 +1339,8 @@
 
     @Test
     public void testGenerateKeyPairLogged() throws Exception {
+        assumeTrue(mHasAttestation);
+
         assertMetricsLogged(getDevice(), () -> {
                 executeDeviceTestMethod(
                         ".KeyManagementTest", "testCanGenerateKeyPairWithKeyAttestation");
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java
index 9a1cc98..bc9e497 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java
@@ -414,11 +414,16 @@
 
     /** Sends a message to the output console of the cec-client */
     public void sendConsoleMessage(String message) throws CecClientWrapperException {
-        checkCecClient();
+        sendConsoleMessage(message, mOutputConsole);
+    }
+
+    /** Sends a message to the output console of the cec-client */
+    public void sendConsoleMessage(String message, BufferedWriter outputConsole)
+            throws CecClientWrapperException {
         CLog.v("Sending console message:: " + message);
         try {
-            mOutputConsole.write(message);
-            mOutputConsole.flush();
+            outputConsole.write(message);
+            outputConsole.flush();
         } catch (IOException ioe) {
             throw new CecClientWrapperException(ErrorCodes.WriteConsole, ioe);
         }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java
index 4f1915a..4709374 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java
@@ -37,6 +37,7 @@
 import java.io.File;
 import java.io.FileWriter;
 import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.concurrent.TimeUnit;
@@ -112,6 +113,8 @@
                     BaseHdmiCecCtsTest.getTargetLogicalAddress(device).getDeviceType();
             int toDevice;
             launchCommand.add("-t");
+            launchCommand.add("r");
+            launchCommand.add("-t");
             if (targetDeviceType == HdmiCecConstants.CEC_DEVICE_TYPE_TV) {
                 toDevice = LogicalAddress.PLAYBACK_1.getLogicalAddressAsInt();
                 launchCommand.add("p");
@@ -161,6 +164,27 @@
                             device.executeShellCommand(sendVendorCommand.toString());
                             if (cecClientWrapper.checkConsoleOutput(
                                     serialNoParam, TIMEOUT_MILLIS, inputConsole)) {
+                                if (targetDeviceType != HdmiCecConstants.CEC_DEVICE_TYPE_TV) {
+                                    // Timeout in milliseconds
+                                    long getVersionTimeout = 3000;
+                                    BufferedWriter outputConsole =
+                                            new BufferedWriter(
+                                                    new OutputStreamWriter(
+                                                            mCecClient.getOutputStream()));
+
+                                    String getVersionMessage = "tx 10:9f";
+                                    cecClientWrapper.sendConsoleMessage(
+                                            getVersionMessage, outputConsole);
+                                    String getVersionResponse = "01:9e";
+                                    if (cecClientWrapper.checkConsoleOutput(
+                                            getVersionResponse, getVersionTimeout, inputConsole)) {
+                                        throw new Exception(
+                                                "Setup error! The sink device (TV) in the test setup"
+                                                    + " seems to have CEC enabled. Please disable"
+                                                    + " and retry tests.");
+                                    }
+                                }
+
                                 writeMapping(port, serialNo);
                                 return;
                             }
diff --git a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
index e2d4d87..47e7b51 100644
--- a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
@@ -89,6 +89,7 @@
     }
 
     public void testJankyDrawFrame() throws Exception {
+        String origRefreshRate[] = setRefreshRate(new String[]{"60", "60"});
         GraphicsStatsProto[] results = runDrawTest("testDrawJankyFrames");
         GraphicsStatsProto statsBefore = results[0];
         GraphicsStatsProto statsAfter = results[1];
@@ -155,7 +156,7 @@
     }
 
     public void testDaveyDrawFrame() throws Exception {
-        String origRefreshRate[] = setRefreshRate(new String[]{"61", "60"});
+        String origRefreshRate[] = setRefreshRate(new String[]{"60", "60"});
         GraphicsStatsProto[] results = runDrawTest("testDrawDaveyFrames");
         setRefreshRate(origRefreshRate);
         GraphicsStatsProto statsBefore = results[0];
diff --git a/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java b/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
index cb42a35..067d7da 100644
--- a/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
+++ b/hostsidetests/webkit/app/src/com/android/cts/webkit/WebViewDeviceSideStartupTest.java
@@ -16,12 +16,7 @@
 
 package com.android.cts.webkit;
 
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
 import android.net.http.SslError;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
 import android.os.StrictMode;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
@@ -33,8 +28,6 @@
 import android.webkit.cts.CtsTestServer;
 import android.webkit.cts.WebViewSyncLoader;
 import android.webkit.cts.WebViewSyncLoader.WaitForLoadedClient;
-import android.webkit.cts.WebkitUtils;
-import android.webkit.WebView;
 
 import com.android.compatibility.common.util.NullWebViewUtils;
 
@@ -119,48 +112,6 @@
     }
 
     @UiThreadTest
-    public void testGetCurrentWebViewPackageOnUiThread() throws Throwable {
-        runCurrentWebViewPackageTest(true /* alreadyOnMainThread */);
-    }
-
-    public void testGetCurrentWebViewPackage() throws Throwable {
-        runCurrentWebViewPackageTest(false /* alreadyOnMainThread */);
-    }
-
-    private void runCurrentWebViewPackageTest(boolean alreadyOnMainThread) throws Exception {
-        PackageManager pm = mActivity.getPackageManager();
-        if (pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
-            PackageInfo webViewPackage = WebView.getCurrentWebViewPackage();
-            // Ensure that getCurrentWebViewPackage returns a package recognized by the package
-            // manager.
-            assertPackageEquals(pm.getPackageInfo(webViewPackage.packageName, 0), webViewPackage);
-
-            // Create WebView on the app's main thread
-            if (alreadyOnMainThread) {
-                mActivity.createAndAttachWebView();
-            } else {
-                WebkitUtils.onMainThreadSync(() -> {
-                    mActivity.createAndAttachWebView();
-                });
-            }
-
-            // Ensure we are still using the same WebView package.
-            assertPackageEquals(webViewPackage, WebView.getCurrentWebViewPackage());
-        } else {
-            // if WebView isn't supported the API should return null.
-            assertNull(WebView.getCurrentWebViewPackage());
-        }
-    }
-
-    private void assertPackageEquals(PackageInfo expected, PackageInfo actual) {
-        if (expected == null) assertNull(actual);
-        assertEquals(expected.packageName, actual.packageName);
-        assertEquals(expected.versionCode, actual.versionCode);
-        assertEquals(expected.versionName, actual.versionName);
-        assertEquals(expected.lastUpdateTime, actual.lastUpdateTime);
-    }
-
-    @UiThreadTest
     public void testStrictModeNotViolatedOnStartup() throws Throwable {
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
@@ -204,65 +155,4 @@
         syncLoader.detach();
     }
 
-    @UiThreadTest
-    public void testGetWebViewLooperOnUiThread() {
-        if (!NullWebViewUtils.isWebViewAvailable()) {
-            return;
-        }
-
-        createAndCheckWebViewLooper();
-    }
-
-    /**
-     * Ensure that a WebView created on the UI thread returns that thread as its creator thread.
-     * This ensures WebView.getWebViewLooper() is not implemented as 'return Looper.myLooper();'.
-     */
-    public void testGetWebViewLooperCreatedOnUiThreadFromInstrThread() {
-        if (!NullWebViewUtils.isWebViewAvailable()) {
-            return;
-        }
-
-        // Create the WebView on the UI thread and then ensure webview.getWebViewLooper() returns
-        // the UI thread.
-        WebView webView = WebkitUtils.onMainThreadSync(() -> {
-            return createAndCheckWebViewLooper();
-        });
-        assertEquals(Looper.getMainLooper(), webView.getWebViewLooper());
-    }
-
-    /**
-     * Ensure that a WebView created on a background thread returns that thread as its creator
-     * thread.
-     * This ensures WebView.getWebViewLooper() is not bound to the UI thread regardless of the
-     * thread it is created on..
-     */
-    public void testGetWebViewLooperCreatedOnBackgroundThreadFromInstThread()
-            throws InterruptedException {
-        if (!NullWebViewUtils.isWebViewAvailable()) {
-            return;
-        }
-
-        // Create a WebView on a background thread, check it from the UI thread
-        final WebView webviewHolder[] = new WebView[1];
-
-        // Use a HandlerThread, because such a thread owns a Looper.
-        HandlerThread backgroundThread = new HandlerThread("WebViewLooperCtsHandlerThread");
-        backgroundThread.start();
-        new Handler(backgroundThread.getLooper()).post(new Runnable() {
-            @Override
-            public void run() {
-                webviewHolder[0] = createAndCheckWebViewLooper();
-            }
-        });
-        backgroundThread.join(TEST_TIMEOUT_MS);
-        assertEquals(backgroundThread.getLooper(), webviewHolder[0].getWebViewLooper());
-    }
-
-    private WebView createAndCheckWebViewLooper() {
-        // Ensure we are running this on a thread with a Looper - otherwise there's no point.
-        assertNotNull(Looper.myLooper());
-        WebView webview = new WebView(mActivity);
-        assertEquals(Looper.myLooper(), webview.getWebViewLooper());
-        return webview;
-    }
 }
diff --git a/hostsidetests/webkit/src/com/android/cts/webkit/WebViewHostSideStartupTest.java b/hostsidetests/webkit/src/com/android/cts/webkit/WebViewHostSideStartupTest.java
index d403618..37fecb2 100644
--- a/hostsidetests/webkit/src/com/android/cts/webkit/WebViewHostSideStartupTest.java
+++ b/hostsidetests/webkit/src/com/android/cts/webkit/WebViewHostSideStartupTest.java
@@ -42,31 +42,10 @@
         assertDeviceTestPasses("testCookieManagerBlockingUiThread");
     }
 
-    public void testWebViewVersionApiOnUiThread() throws DeviceNotAvailableException {
-        assertDeviceTestPasses("testGetCurrentWebViewPackageOnUiThread");
-    }
-
-    public void testWebViewVersionApi() throws DeviceNotAvailableException {
-        assertDeviceTestPasses("testGetCurrentWebViewPackage");
-    }
-
     public void testStrictMode() throws DeviceNotAvailableException {
         assertDeviceTestPasses("testStrictModeNotViolatedOnStartup");
     }
 
-    public void testGetWebViewLooperOnUiThread() throws DeviceNotAvailableException {
-        assertDeviceTestPasses("testGetWebViewLooperOnUiThread");
-    }
-
-    public void testGetWebViewLooperFromUiThread() throws DeviceNotAvailableException {
-        assertDeviceTestPasses("testGetWebViewLooperCreatedOnUiThreadFromInstrThread");
-    }
-
-    public void testGetWebViewLooperCreatedOnBackgroundThreadFromInstThread()
-            throws DeviceNotAvailableException {
-        assertDeviceTestPasses("testGetWebViewLooperCreatedOnBackgroundThreadFromInstThread");
-    }
-
     private void assertDeviceTestPasses(String testMethodName) throws DeviceNotAvailableException {
         TestRunResult testRunResult = runSingleDeviceTest(DEVICE_WEBVIEW_STARTUP_PKG,
                                                  DEVICE_WEBVIEW_STARTUP_TEST_CLASS,
diff --git a/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
index 6e64204..48f8c55 100644
--- a/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
+++ b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
@@ -71,6 +71,8 @@
      * A new WebViewOnUiThread should be called during setUp so as to
      * reinitialize between calls.
      *
+     * The caller is responsible for destroying the WebView instance.
+     *
      * @param webView The webView that the methods should call.
      */
     public WebViewOnUiThread(WebView webView) {
diff --git a/libs/deviceutillegacy/src/android/webkit/cts/WebViewSyncLoader.java b/libs/deviceutillegacy/src/android/webkit/cts/WebViewSyncLoader.java
index d856480..7976f1f 100644
--- a/libs/deviceutillegacy/src/android/webkit/cts/WebViewSyncLoader.java
+++ b/libs/deviceutillegacy/src/android/webkit/cts/WebViewSyncLoader.java
@@ -105,11 +105,10 @@
         mWebView.setWebChromeClient(null);
         mWebView.setWebViewClient(null);
         mWebView.setPictureListener(null);
-        mWebView = null;
     }
 
     /**
-     * Detach listeners, and destroy this webview.
+     * Detach listeners.
      */
     public void destroy() {
         if (!isUiThread()) {
@@ -120,7 +119,6 @@
         detach();
         webView.clearHistory();
         webView.clearCache(true);
-        webView.destroy();
     }
 
     /**
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
index 571c0d9..ecdab0f 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
@@ -70,6 +70,7 @@
 import android.graphics.Rect;
 import android.platform.test.annotations.AppModeFull;
 import android.test.suitebuilder.annotation.MediumTest;
+import android.text.TextUtils;
 import android.util.Log;
 import android.util.SparseArray;
 import android.view.Display;
@@ -231,7 +232,11 @@
         final int windowCount = windows.size();
         for (int i = 0; i < windowCount; i++) {
             AccessibilityWindowInfo window = windows.get(i);
-
+            // Skip other Apps windows since their state might not be stable while querying.
+            if (window.getType() == AccessibilityWindowInfo.TYPE_APPLICATION
+                    && !TextUtils.equals(window.getTitle(), mActivity.getTitle())) {
+                continue;
+            }
             window.getBoundsInScreen(boundsInScreen);
             assertFalse(boundsInScreen.isEmpty()); // Varies on screen size, emptiness check.
             assertNull(window.getParent());
diff --git a/tests/camera/src/android/hardware/cts/CameraGLTest.java b/tests/camera/src/android/hardware/cts/CameraGLTest.java
index 7478e79..030b5ab 100644
--- a/tests/camera/src/android/hardware/cts/CameraGLTest.java
+++ b/tests/camera/src/android/hardware/cts/CameraGLTest.java
@@ -39,6 +39,8 @@
 
 import androidx.test.rule.ActivityTestRule;
 
+import com.android.compatibility.common.util.WindowUtil;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
@@ -104,6 +106,11 @@
     public void setUp() throws Exception {
         // Start CameraCtsActivity.
         GLSurfaceViewCtsActivity ctsActivity = mActivityRule.getActivity();
+        // Some of the tests run on the UI thread. In case some of the operations take a long time
+        // to complete,  wait for window to receive focus. This ensure that the focus event from
+        // input flinger has been handled, and avoids getting ANR.
+        WindowUtil.waitForFocus(ctsActivity);
+
         // Store a link to the view so we can redraw it when needed
         mGLView = ctsActivity.getView();
 
diff --git a/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java b/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java
index e803863..ae9054f 100644
--- a/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java
+++ b/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java
@@ -219,6 +219,7 @@
             queueEOS();
             waitForAllOutputs();
             mCodec.reset();
+            mCodec.release();
         }
         tearDownSurface();
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/AESCBCCipherTestBase.java b/tests/tests/keystore/src/android/keystore/cts/AESCBCCipherTestBase.java
index 8f1aed69..cedb3b4 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AESCBCCipherTestBase.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AESCBCCipherTestBase.java
@@ -22,6 +22,8 @@
 
 import javax.crypto.spec.IvParameterSpec;
 
+import org.junit.Test;
+
 abstract class AESCBCCipherTestBase extends BlockCipherTestBase {
 
     @Override
diff --git a/tests/tests/keystore/src/android/keystore/cts/AESCipherNistCavpKatTest.java b/tests/tests/keystore/src/android/keystore/cts/AESCipherNistCavpKatTest.java
index 1f6ebd7..41c4456 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AESCipherNistCavpKatTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AESCipherNistCavpKatTest.java
@@ -16,9 +16,15 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
-import android.test.AndroidTestCase;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
@@ -36,98 +42,130 @@
 import javax.crypto.spec.IvParameterSpec;
 import javax.crypto.spec.SecretKeySpec;
 
-public class AESCipherNistCavpKatTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
+@RunWith(AndroidJUnit4.class)
+public class AESCipherNistCavpKatTest {
+
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testECBVarKey128() throws Exception {
         runTestsForKatFile("ECBVarKey128.rsp");
     }
 
+    @Test
     public void testECBVarKey192() throws Exception {
         runTestsForKatFile("ECBVarKey192.rsp");
     }
+    @Test
     public void testECBVarKey256() throws Exception {
         runTestsForKatFile("ECBVarKey256.rsp");
     }
 
+    @Test
     public void testECBVarTxt128() throws Exception {
         runTestsForKatFile("ECBVarTxt128.rsp");
     }
 
+    @Test
     public void testECBVarTxt192() throws Exception {
         runTestsForKatFile("ECBVarTxt192.rsp");
     }
 
+    @Test
     public void testECBVarTxt256() throws Exception {
         runTestsForKatFile("ECBVarTxt256.rsp");
     }
 
+    @Test
     public void testECBGFSbox128() throws Exception {
         runTestsForKatFile("ECBGFSbox128.rsp");
     }
 
+    @Test
     public void testECBGFSbox192() throws Exception {
         runTestsForKatFile("ECBGFSbox192.rsp");
     }
 
+    @Test
     public void testECBGFSbox256() throws Exception {
         runTestsForKatFile("ECBGFSbox256.rsp");
     }
 
+    @Test
     public void testECBKeySbox128() throws Exception {
         runTestsForKatFile("ECBKeySbox128.rsp");
     }
 
+    @Test
     public void testECBKeySbox192() throws Exception {
         runTestsForKatFile("ECBKeySbox192.rsp");
     }
 
+    @Test
     public void testECBKeySbox256() throws Exception {
         runTestsForKatFile("ECBKeySbox256.rsp");
     }
 
+    @Test
     public void testCBCVarKey128() throws Exception {
         runTestsForKatFile("CBCVarKey128.rsp");
     }
 
+    @Test
     public void testCBCVarKey192() throws Exception {
         runTestsForKatFile("CBCVarKey192.rsp");
     }
+    @Test
     public void testCBCVarKey256() throws Exception {
         runTestsForKatFile("CBCVarKey256.rsp");
     }
 
+    @Test
     public void testCBCVarTxt128() throws Exception {
         runTestsForKatFile("CBCVarTxt128.rsp");
     }
 
+    @Test
     public void testCBCVarTxt192() throws Exception {
         runTestsForKatFile("CBCVarTxt192.rsp");
     }
 
+    @Test
     public void testCBCVarTxt256() throws Exception {
         runTestsForKatFile("CBCVarTxt256.rsp");
     }
 
+    @Test
     public void testCBCGFSbox128() throws Exception {
         runTestsForKatFile("CBCGFSbox128.rsp");
     }
 
+    @Test
     public void testCBCGFSbox192() throws Exception {
         runTestsForKatFile("CBCGFSbox192.rsp");
     }
 
+    @Test
     public void testCBCGFSbox256() throws Exception {
         runTestsForKatFile("CBCGFSbox256.rsp");
     }
 
+    @Test
     public void testCBCKeySbox128() throws Exception {
         runTestsForKatFile("CBCKeySbox128.rsp");
     }
 
+    @Test
     public void testCBCKeySbox192() throws Exception {
         runTestsForKatFile("CBCKeySbox192.rsp");
     }
 
+    @Test
     public void testCBCKeySbox256() throws Exception {
         runTestsForKatFile("CBCKeySbox256.rsp");
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/AESECBCipherTestBase.java b/tests/tests/keystore/src/android/keystore/cts/AESECBCipherTestBase.java
index b2752dc..796527f 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AESECBCipherTestBase.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AESECBCipherTestBase.java
@@ -16,10 +16,14 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.fail;
+
 import java.security.AlgorithmParameters;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.InvalidParameterSpecException;
 
+import org.junit.Test;
+
 abstract class AESECBCipherTestBase extends BlockCipherTestBase {
 
     @Override
@@ -55,6 +59,7 @@
         return null;
     }
 
+    @Test
     public void testInitRejectsIvParameterSpec() throws Exception {
         assertInitRejectsIvParameterSpec(new byte[getBlockSize()]);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/AESGCMCipherTestBase.java b/tests/tests/keystore/src/android/keystore/cts/AESGCMCipherTestBase.java
index 1c3404a..0c8add9 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AESGCMCipherTestBase.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AESGCMCipherTestBase.java
@@ -16,6 +16,9 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.fail;
+
 import java.nio.ByteBuffer;
 import java.security.AlgorithmParameters;
 import java.security.Key;
@@ -26,6 +29,8 @@
 import javax.crypto.Cipher;
 import javax.crypto.spec.GCMParameterSpec;
 
+import org.junit.Test;
+
 abstract class AESGCMCipherTestBase extends BlockCipherTestBase {
 
     protected abstract byte[] getKatAad();
@@ -62,6 +67,7 @@
         return spec.getIV();
     }
 
+    @Test
     public void testKatEncryptWithAadProvidedInOneGo() throws Exception {
         createCipher();
         assertKatTransformWithAadProvidedInOneGo(
@@ -71,6 +77,7 @@
                 getKatCiphertextWhenKatAadPresent());
     }
 
+    @Test
     public void testKatDecryptWithAadProvidedInOneGo() throws Exception {
         createCipher();
         assertKatTransformWithAadProvidedInOneGo(
@@ -80,6 +87,7 @@
                 getKatPlaintext());
     }
 
+    @Test
     public void testKatEncryptWithAadProvidedInChunks() throws Exception {
         createCipher();
         assertKatTransformWithAadProvidedInChunks(
@@ -114,6 +122,7 @@
                 23);
     }
 
+    @Test
     public void testKatDecryptWithAadProvidedInChunks() throws Exception {
         createCipher();
         assertKatTransformWithAadProvidedInChunks(
@@ -152,15 +161,15 @@
             byte[] aad, byte[] input, byte[] expectedOutput) throws Exception {
         initKat(opmode);
         updateAAD(aad);
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
 
         initKat(opmode);
         updateAAD(aad, 0, aad.length);
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
 
         initKat(opmode);
         updateAAD(ByteBuffer.wrap(aad));
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
     }
 
     private void assertKatTransformWithAadProvidedInChunks(int opmode,
@@ -173,9 +182,10 @@
             updateAAD(aad, aadOffset, chunkSize);
             aadOffset += chunkSize;
         }
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
     }
 
+    @Test
     public void testCiphertextBitflipDetectedWhenDecrypting() throws Exception {
         createCipher();
         Key key = importKey(getKatKey());
@@ -188,6 +198,7 @@
         } catch (AEADBadTagException expected) {}
     }
 
+    @Test
     public void testAadBitflipDetectedWhenDecrypting() throws Exception {
         createCipher();
         Key key = importKey(getKatKey());
@@ -202,6 +213,7 @@
         } catch (AEADBadTagException expected) {}
     }
 
+    @Test
     public void testInitRejectsIvParameterSpec() throws Exception {
         assertInitRejectsIvParameterSpec(getKatIv());
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
index 078e73a..7943538 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
@@ -16,18 +16,26 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.content.pm.PackageManager;
 import android.keystore.cts.util.TestUtils;
 import android.security.KeyPairGeneratorSpec;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
-import android.test.AndroidTestCase;
-import android.test.MoreAsserts;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.util.Log;
 
-import org.junit.Assert;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -70,7 +78,13 @@
 import javax.crypto.SecretKey;
 import javax.security.auth.x500.X500Principal;
 
-public class AndroidKeyStoreTest extends AndroidTestCase {
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class AndroidKeyStoreTest {
     private static final String TAG = AndroidKeyStoreTest.class.getSimpleName();
 
     private KeyStore mKeyStore;
@@ -727,10 +741,12 @@
      */
     private static final long SLOP_TIME_MILLIS = 15000L;
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
 
+    @Before
+    public void setUp() throws Exception {
         // Wipe any existing entries in the KeyStore
         KeyStore ksTemp = KeyStore.getInstance("AndroidKeyStore");
         ksTemp.load(null, null);
@@ -750,18 +766,14 @@
                         : LARGE_NUMBER_OF_KEYS_TEST_MAX_DURATION;
     }
 
-    @Override
-    protected void tearDown() throws Exception {
-        try {
-            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
-            keyStore.load(null, null);
-            Enumeration<String> aliases = keyStore.aliases();
-            while (aliases.hasMoreElements()) {
-                String alias = aliases.nextElement();
-                keyStore.deleteEntry(alias);
-            }
-        } finally {
-            super.tearDown();
+    @After
+    public void tearDown() throws Exception {
+        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+        keyStore.load(null, null);
+        Enumeration<String> aliases = keyStore.aliases();
+        while (aliases.hasMoreElements()) {
+            String alias = aliases.nextElement();
+            keyStore.deleteEntry(alias);
         }
     }
 
@@ -811,6 +823,7 @@
                 expectedAliases.length, count);
     }
 
+    @Test
     public void testKeyStore_Aliases_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -825,6 +838,7 @@
         assertAliases(new String[] { getTestAlias1(), getTestAlias2() });
     }
 
+    @Test
     public void testKeyStore_Aliases_NotInitialized_Unencrypted_Failure() throws Exception {
         try {
             mKeyStore.aliases();
@@ -833,6 +847,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_ContainsAliases_PrivateAndCA_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -850,6 +865,7 @@
                 mKeyStore.containsAlias(getTestAlias3()));
     }
 
+    @Test
     public void testKeyStore_ContainsAliases_CAOnly_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -858,12 +874,14 @@
         assertTrue("Should contain added CA certificate", mKeyStore.containsAlias(getTestAlias2()));
     }
 
+    @Test
     public void testKeyStore_ContainsAliases_NonExistent_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
         assertFalse("Should contain added CA certificate", mKeyStore.containsAlias(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_DeleteEntry_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -891,6 +909,7 @@
         assertAliases(new String[] { });
     }
 
+    @Test
     public void testKeyStore_DeleteEntry_EmptyStore_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -898,6 +917,7 @@
         mKeyStore.deleteEntry(getTestAlias1());
     }
 
+    @Test
     public void testKeyStore_DeleteEntry_NonExistent_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -908,6 +928,7 @@
         mKeyStore.deleteEntry(getTestAlias2());
     }
 
+    @Test
     public void testKeyStore_GetCertificate_Single_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -928,6 +949,7 @@
         assertEquals("Actual and retrieved certificates should be the same", actual, retrieved);
     }
 
+    @Test
     public void testKeyStore_GetCertificate_NonExist_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -935,6 +957,7 @@
                 mKeyStore.getCertificate(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_GetCertificateAlias_CAEntry_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -945,6 +968,7 @@
                 mKeyStore.getCertificateAlias(cert));
     }
 
+    @Test
     public void testKeyStore_GetCertificateAlias_PrivateKeyEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -958,6 +982,7 @@
                 mKeyStore.getCertificateAlias(actual));
     }
 
+    @Test
     public void testKeyStore_GetCertificateAlias_CAEntry_WithPrivateKeyUsingCA_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -974,6 +999,7 @@
                 mKeyStore.getCertificateAlias(actual));
     }
 
+    @Test
     public void testKeyStore_GetCertificateAlias_NonExist_Empty_Unencrypted_Failure()
             throws Exception {
         mKeyStore.load(null, null);
@@ -985,6 +1011,7 @@
                 mKeyStore.getCertificateAlias(actual));
     }
 
+    @Test
     public void testKeyStore_GetCertificateAlias_NonExist_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -999,6 +1026,7 @@
                 mKeyStore.getCertificateAlias(userCert));
     }
 
+    @Test
     public void testKeyStore_GetCertificateChain_SingleLength_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1022,6 +1050,7 @@
                 mKeyStore.getCertificateChain(getTestAlias2()));
     }
 
+    @Test
     public void testKeyStore_GetCertificateChain_NonExist_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1029,6 +1058,7 @@
                 mKeyStore.getCertificateChain(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_GetCreationDate_PrivateKeyEntry_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1045,6 +1075,7 @@
         assertTrue("Time should be close to current time", actual.after(expectedAfter));
     }
 
+    @Test
     public void testKeyStore_GetCreationDate_CAEntry_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1062,6 +1093,7 @@
         assertTrue("Time should be close to current time", actual.after(expectedAfter));
     }
 
+    @Test
     public void testKeyStore_GetEntry_NullParams_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1078,6 +1110,7 @@
         assertPrivateKeyEntryEquals(keyEntry, "RSA", FAKE_RSA_KEY_1, FAKE_RSA_USER_1, FAKE_RSA_CA_1);
     }
 
+    @Test
     public void testKeyStore_GetEntry_EC_NullParams_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1094,6 +1127,7 @@
         assertPrivateKeyEntryEquals(keyEntry, "EC", FAKE_EC_KEY_1, FAKE_EC_USER_1, FAKE_EC_CA_1);
     }
 
+    @Test
     public void testKeyStore_GetEntry_RSA_NullParams_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1177,6 +1211,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_GetEntry_Nonexistent_NullParams_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1184,6 +1219,7 @@
                 mKeyStore.getEntry(getTestAlias1(), null));
     }
 
+    @Test
     public void testKeyStore_GetKey_NoPassword_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1205,6 +1241,7 @@
                 ((RSAKey) expectedKey).getModulus(), actualKey.getModulus());
     }
 
+    @Test
     public void testKeyStore_GetKey_Certificate_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1214,20 +1251,24 @@
         assertNull("Certificate entries should return null", mKeyStore.getKey(getTestAlias1(), null));
     }
 
+    @Test
     public void testKeyStore_GetKey_NonExistent_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
         assertNull("A non-existent entry should return null", mKeyStore.getKey(getTestAlias1(), null));
     }
 
+    @Test
     public void testKeyStore_GetProvider_Unencrypted_Success() throws Exception {
         assertEquals("AndroidKeyStore", mKeyStore.getProvider().getName());
     }
 
+    @Test
     public void testKeyStore_GetType_Unencrypted_Success() throws Exception {
         assertEquals("AndroidKeyStore", mKeyStore.getType());
     }
 
+    @Test
     public void testKeyStore_IsCertificateEntry_CA_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1238,6 +1279,7 @@
                 mKeyStore.isCertificateEntry(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_IsCertificateEntry_PrivateKey_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1248,6 +1290,7 @@
                 mKeyStore.isCertificateEntry(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_IsCertificateEntry_NonExist_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1255,6 +1298,7 @@
                 mKeyStore.isCertificateEntry(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_IsKeyEntry_PrivateKey_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1264,6 +1308,7 @@
         assertTrue("Should return true for PrivateKeyEntry", mKeyStore.isKeyEntry(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_IsKeyEntry_CA_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1272,6 +1317,7 @@
         assertFalse("Should return false for CA certificate", mKeyStore.isKeyEntry(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_IsKeyEntry_NonExist_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1279,6 +1325,7 @@
                 mKeyStore.isKeyEntry(getTestAlias1()));
     }
 
+    @Test
     public void testKeyStore_SetCertificate_CA_Unencrypted_Success() throws Exception {
         final Certificate actual = generateCertificate(FAKE_RSA_CA_1);
 
@@ -1293,6 +1340,7 @@
                 retrieved);
     }
 
+    @Test
     public void testKeyStore_SetCertificate_CAExists_Overwrite_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1309,6 +1357,7 @@
         assertAliases(new String[] { getTestAlias1() });
     }
 
+    @Test
     public void testKeyStore_SetCertificate_PrivateKeyExists_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1325,6 +1374,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetEntry_PrivateKeyEntry_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1352,6 +1402,7 @@
         assertPrivateKeyEntryEquals(actual, "RSA", FAKE_RSA_KEY_1, FAKE_RSA_USER_1, FAKE_RSA_CA_1);
     }
 
+    @Test
     public void testKeyStore_SetEntry_PrivateKeyEntry_Overwrites_PrivateKeyEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1411,6 +1462,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetEntry_CAEntry_Overwrites_PrivateKeyEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1459,6 +1511,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetEntry_PrivateKeyEntry_Overwrites_CAEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1506,6 +1559,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetEntry_PrivateKeyEntry_Overwrites_ShortPrivateKeyEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1560,6 +1614,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetEntry_CAEntry_Overwrites_CAEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1603,6 +1658,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetKeyEntry_ProtectedKey_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1623,6 +1679,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetKeyEntry_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1649,6 +1706,7 @@
         assertPrivateKeyEntryEquals(actual, "RSA", FAKE_RSA_KEY_1, FAKE_RSA_USER_1, FAKE_RSA_CA_1);
     }
 
+    @Test
     public void testKeyStore_SetKeyEntry_Replaced_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1702,6 +1760,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetKeyEntry_ReplacedChain_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1745,6 +1804,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetKeyEntry_ReplacedChain_DifferentPrivateKey_Unencrypted_Failure()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1770,6 +1830,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_SetKeyEntry_ReplacedWithSame_UnencryptedToUnencrypted_Failure()
             throws Exception {
         mKeyStore.load(null, null);
@@ -1785,6 +1846,7 @@
     /*
      * Replacing an existing secret key with itself should be a no-op.
      */
+    @Test
     public void testKeyStore_SetKeyEntry_ReplacedWithSameGeneratedSecretKey()
             throws Exception {
         final String plaintext = "My awesome plaintext message!";
@@ -1815,10 +1877,11 @@
         cipher = Cipher.getInstance(algorithm);
         cipher.init(Cipher.DECRYPT_MODE, key2, params);
         byte[] plaintext2 = cipher.doFinal(ciphertext);
-        Assert.assertArrayEquals("The plaintext2 should match the original plaintext.",
+        assertArrayEquals("The plaintext2 should match the original plaintext.",
                 plaintext2, plaintext.getBytes());
     }
 
+    @Test
     public void testKeyStore_Size_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1848,6 +1911,7 @@
         assertAliases(new String[] { getTestAlias2() });
     }
 
+    @Test
     public void testKeyStore_Store_LoadStoreParam_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1858,6 +1922,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_Load_InputStreamSupplied_Unencrypted_Failure() throws Exception {
         byte[] buf = "FAKE KEYSTORE".getBytes();
         ByteArrayInputStream is = new ByteArrayInputStream(buf);
@@ -1869,6 +1934,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_Load_PasswordSupplied_Unencrypted_Failure() throws Exception {
         try {
             mKeyStore.load(null, "password".toCharArray());
@@ -1877,6 +1943,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_Store_OutputStream_Unencrypted_Failure() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1894,6 +1961,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_KeyOperations_Wrap_Unencrypted_Success() throws Exception {
         mKeyStore.load(null, null);
 
@@ -1928,6 +1996,7 @@
                 Arrays.toString(actualSecret.getEncoded()));
     }
 
+    @Test
     public void testKeyStore_Encrypting_RSA_NONE_NOPADDING() throws Exception {
 
         String alias = "MyKey";
@@ -1945,7 +2014,7 @@
 
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
         assertNotNull(kpg);
-        kpg.initialize(new KeyPairGeneratorSpec.Builder(mContext)
+        kpg.initialize(new KeyPairGeneratorSpec.Builder(getContext())
                 .setAlias(alias)
                 .setStartDate(now)
                 .setEndDate(end)
@@ -1980,6 +2049,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_PrivateKeyEntry_RSA_PublicKeyWorksWithCrypto()
             throws Exception {
         mKeyStore.load(null, null);
@@ -2000,6 +2070,7 @@
         Cipher.getInstance("RSA/ECB/OAEPPadding").init(Cipher.ENCRYPT_MODE, publicKey);
     }
 
+    @Test
     public void testKeyStore_PrivateKeyEntry_EC_PublicKeyWorksWithCrypto()
             throws Exception {
         mKeyStore.load(null, null);
@@ -2015,6 +2086,7 @@
         Signature.getInstance("NONEwithECDSA").initVerify(publicKey);
     }
 
+    @Test
     public void testKeyStore_TrustedCertificateEntry_RSA_PublicKeyWorksWithCrypto()
             throws Exception {
         mKeyStore.load(null, null);
@@ -2029,6 +2101,7 @@
         Cipher.getInstance("RSA/ECB/NoPadding").init(Cipher.ENCRYPT_MODE, publicKey);
     }
 
+    @Test
     public void testKeyStore_TrustedCertificateEntry_EC_PublicKeyWorksWithCrypto()
             throws Exception {
         mKeyStore.load(null, null);
@@ -2066,6 +2139,7 @@
     }
 
     @LargeTest
+    @Test
     public void testKeyStore_LargeNumberOfKeysSupported_RSA() throws Exception {
         // This test imports key1, then lots of other keys, then key2, and then confirms that
         // key1 and key2 backed by Android Keystore work fine. The assumption is that if the
@@ -2137,6 +2211,7 @@
     }
 
     @LargeTest
+    @Test
     public void testKeyStore_LargeNumberOfKeysSupported_EC() throws Exception {
         // This test imports key1, then lots of other keys, then key2, and then confirms that
         // key1 and key2 backed by Android Keystore work fine. The assumption is that if the
@@ -2210,6 +2285,7 @@
     }
 
     @LargeTest
+    @Test
     public void testKeyStore_LargeNumberOfKeysSupported_AES() throws Exception {
         // This test imports key1, then lots of other keys, then key2, and then confirms that
         // key1 and key2 backed by Android Keystore work fine. The assumption is that if the
@@ -2259,7 +2335,7 @@
             AlgorithmParameters cipherParams = cipher.getParameters();
             cipher = Cipher.getInstance(cipher.getAlgorithm());
             cipher.init(Cipher.DECRYPT_MODE, key1, cipherParams);
-            MoreAsserts.assertEquals(plaintext, cipher.doFinal(ciphertext));
+            assertArrayEquals(plaintext, cipher.doFinal(ciphertext));
 
             cipher = Cipher.getInstance(cipher.getAlgorithm());
             cipher.init(Cipher.ENCRYPT_MODE, keystoreKey2);
@@ -2267,13 +2343,14 @@
             cipherParams = cipher.getParameters();
             cipher = Cipher.getInstance(cipher.getAlgorithm());
             cipher.init(Cipher.DECRYPT_MODE, key2, cipherParams);
-            MoreAsserts.assertEquals(plaintext, cipher.doFinal(ciphertext));
+            assertArrayEquals(plaintext, cipher.doFinal(ciphertext));
         } finally {
             deleteManyTestKeys(keyCount, ALIAS_PREFIX);
         }
     }
 
     @LargeTest
+    @Test
     public void testKeyStore_LargeNumberOfKeysSupported_HMAC() throws Exception {
         // This test imports key1, then lots of other keys, then key2, and then confirms that
         // key1 and key2 backed by Android Keystore work fine. The assumption is that if the
@@ -2319,14 +2396,14 @@
             byte[] message = "This is a test".getBytes("UTF-8");
             Mac mac = Mac.getInstance(key1.getAlgorithm());
             mac.init(keystoreKey1);
-            MoreAsserts.assertEquals(
+            assertArrayEquals(
                     HexEncoding.decode(
                             "905e36f5a175f4ca54ad56b860b46f6502f883a90628dca2d33a953fb7224eaf"),
                     mac.doFinal(message));
 
             mac = Mac.getInstance(key2.getAlgorithm());
             mac.init(keystoreKey2);
-            MoreAsserts.assertEquals(
+            assertArrayEquals(
                     HexEncoding.decode(
                             "59b57e77e4e2cb36b5c7b84af198ac004327bc549de6931a1b5505372dd8c957"),
                     mac.doFinal(message));
@@ -2335,6 +2412,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_OnlyOneDigestCanBeAuthorized_HMAC() throws Exception {
         mKeyStore.load(null);
 
@@ -2397,6 +2475,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_ImportSupportedSizes_AES() throws Exception {
         mKeyStore.load(null);
 
@@ -2433,6 +2512,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_ImportSupportedSizes_HMAC() throws Exception {
         mKeyStore.load(null);
 
@@ -2469,6 +2549,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_ImportSupportedSizes_EC() throws Exception {
         mKeyStore.load(null);
         KeyProtection params =
@@ -2483,6 +2564,7 @@
                 "secp512r1", R.raw.ec_key6_secp521r1_pkcs8, R.raw.ec_key6_secp521r1_cert, params);
     }
 
+    @Test
     public void testKeyStore_ImportSupportedSizes_RSA() throws Exception {
         mKeyStore.load(null);
         KeyProtection params =
diff --git a/tests/tests/keystore/src/android/keystore/cts/BackendBusyExceptionTest.java b/tests/tests/keystore/src/android/keystore/cts/BackendBusyExceptionTest.java
index 32b83dc..91804ac 100644
--- a/tests/tests/keystore/src/android/keystore/cts/BackendBusyExceptionTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/BackendBusyExceptionTest.java
@@ -16,18 +16,28 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.security.keystore.BackendBusyException;
-import android.test.AndroidTestCase;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests basic functionality of the BackendBusyException.
  */
-public class BackendBusyExceptionTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class BackendBusyExceptionTest {
     /**
      * Tests if a BackendBusyException constructed with a given backoff hint returns
      * that value through getBackOffHintMillis().
      * Also the constructor must throw IllegalArgumentException if the backoff hint is negative.
      */
+    @Test
     public void testBackOffHint () {
         BackendBusyException backendBusyException = new BackendBusyException(1);
         assertEquals(backendBusyException.getBackOffHintMillis(), 1);
@@ -61,6 +71,7 @@
     /**
      * Test that getMessage returns the message passed to the constructor.
      */
+    @Test
     public void testMessage() {
         BackendBusyException backendBusyException = new BackendBusyException(1, "My test Message.");
         assertTrue(backendBusyException.getMessage().equals("My test Message."));
@@ -71,6 +82,7 @@
     /**
      * Test that getCause returns the cause passed to the constructor.
      */
+    @Test
     public void testCause() {
         Exception cause = new Exception("My Cause");
 
diff --git a/tests/tests/keystore/src/android/keystore/cts/BlockCipherTestBase.java b/tests/tests/keystore/src/android/keystore/cts/BlockCipherTestBase.java
index ccbadf9..055fa8c 100644
--- a/tests/tests/keystore/src/android/keystore/cts/BlockCipherTestBase.java
+++ b/tests/tests/keystore/src/android/keystore/cts/BlockCipherTestBase.java
@@ -16,11 +16,21 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.keystore.cts.util.EmptyArray;
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
-import android.test.AndroidTestCase;
+
+import androidx.test.runner.AndroidJUnit4;
 
 import junit.framework.AssertionFailedError;
 
@@ -51,7 +61,13 @@
 import javax.crypto.spec.IvParameterSpec;
 import javax.crypto.spec.SecretKeySpec;
 
-abstract class BlockCipherTestBase extends AndroidTestCase {
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+abstract class BlockCipherTestBase {
 
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_CRYPTO_OP_PROVIDER_NAME;
     private static final int LARGE_MESSAGE_SIZE = 100 * 1024;
@@ -60,13 +76,11 @@
     private int mNextKeyId;
     private SecureRandom mRand = new SecureRandom();
 
-    @Override
-    protected void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         if (isStrongbox()) {
             TestUtils.assumeStrongBox();
         }
-
-        super.setUp();
         mAndroidKeyStore = KeyStore.getInstance("AndroidKeyStore");
         mAndroidKeyStore.load(null);
         for (Enumeration<String> e = mAndroidKeyStore.aliases(); e.hasMoreElements();) {
@@ -74,14 +88,12 @@
         }
     }
 
-    @Override
-    protected void tearDown() throws Exception {
-        try {
+    @After
+    public void tearDown() throws Exception {
+        if (mAndroidKeyStore != null) {
             for (Enumeration<String> e = mAndroidKeyStore.aliases(); e.hasMoreElements();) {
                 mAndroidKeyStore.deleteEntry(e.nextElement());
             }
-        } finally {
-            super.tearDown();
         }
     }
 
@@ -100,7 +112,7 @@
     protected abstract byte[] getIv(AlgorithmParameters params)
             throws InvalidParameterSpecException;
 
-    protected abstract boolean isStrongbox();
+    abstract protected boolean isStrongbox();
 
     private byte[] getKatInput(int opmode) {
         switch (opmode) {
@@ -127,27 +139,32 @@
     private Cipher mCipher;
     private int mOpmode;
 
+    @Test
     public void testGetAlgorithm() throws Exception {
         createCipher();
         assertEquals(getTransformation(), mCipher.getAlgorithm());
     }
 
+    @Test
     public void testGetProvider() throws Exception {
         createCipher();
         Provider expectedProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertSame(expectedProvider, mCipher.getProvider());
     }
 
+    @Test
     public void testGetBlockSize() throws Exception {
         createCipher();
         assertEquals(getBlockSize(), mCipher.getBlockSize());
     }
 
+    @Test
     public void testGetExemptionMechanism() throws Exception {
         createCipher();
         assertNull(mCipher.getExemptionMechanism());
     }
 
+    @Test
     public void testGetParameters() throws Exception {
         createCipher();
         assertAlgoritmParametersIv(null);
@@ -170,10 +187,11 @@
             assertNull(actualParameters);
         } else {
             byte[] actualIv = getIv(actualParameters);
-            assertEquals(expectedIv, actualIv);
+            assertArrayEquals(expectedIv, actualIv);
         }
     }
 
+    @Test
     public void testGetOutputSizeInEncryptionMode() throws Exception {
         int blockSize = getBlockSize();
         createCipher();
@@ -240,6 +258,7 @@
         }
     }
 
+    @Test
     public void testGetOutputSizeInDecryptionMode() throws Exception {
         int blockSize = getBlockSize();
         createCipher();
@@ -317,6 +336,7 @@
         }
     }
 
+    @Test
     public void testInitRequiresIvInDecryptMode() throws Exception {
         if (getKatIv() == null) {
             // IV not used in this transformation.
@@ -360,24 +380,26 @@
         } catch (InvalidAlgorithmParameterException expected) {}
     }
 
+    @Test
     public void testGetIV() throws Exception {
         createCipher();
         assertNull(mCipher.getIV());
 
         initKat(Cipher.ENCRYPT_MODE);
-        assertEquals(getKatIv(), mCipher.getIV());
+        assertArrayEquals(getKatIv(), mCipher.getIV());
 
         byte[] ciphertext = doFinal(new byte[getBlockSize()]);
-        assertEquals(getKatIv(), mCipher.getIV());
+        assertArrayEquals(getKatIv(), mCipher.getIV());
 
         createCipher();
         initKat(Cipher.DECRYPT_MODE);
-        assertEquals(getKatIv(), mCipher.getIV());
+        assertArrayEquals(getKatIv(), mCipher.getIV());
 
         doFinal(ciphertext);
-        assertEquals(getKatIv(), mCipher.getIV());
+        assertArrayEquals(getKatIv(), mCipher.getIV());
     }
 
+    @Test
     public void testIvGeneratedAndUsedWhenEncryptingWithoutExplicitIv() throws Exception {
         createCipher();
         SecretKey key = getKey();
@@ -393,7 +415,7 @@
             assertNotNull(generatedIv);
             assertEquals(getKatIv().length, generatedIv.length);
             assertNotNull(generatedParams);
-            assertEquals(generatedIv, getIv(generatedParams));
+            assertArrayEquals(generatedIv, getIv(generatedParams));
         }
 
         // Assert that encrypting then decrypting using the above IV (or null) results in the
@@ -403,9 +425,10 @@
         createCipher();
         init(Cipher.DECRYPT_MODE, key, generatedParams);
         byte[] decryptedPlaintext = mCipher.doFinal(ciphertext);
-        assertEquals(plaintext, decryptedPlaintext);
+        assertArrayEquals(plaintext, decryptedPlaintext);
     }
 
+    @Test
     public void testGeneratedIvSurvivesReset() throws Exception {
         if (getKatIv() == null) {
             // This transformation does not use an IV
@@ -418,7 +441,7 @@
         AlgorithmParameters generatedParams = mCipher.getParameters();
         byte[] ciphertext = mCipher.doFinal(getKatPlaintext());
         // Assert that the IV is still there
-        assertEquals(iv, mCipher.getIV());
+        assertArrayEquals(iv, mCipher.getIV());
         assertAlgoritmParametersIv(iv);
 
         if (getKatIv() != null) {
@@ -427,17 +450,18 @@
         }
 
         // Assert that encrypting the same input after the above reset produces the same ciphertext.
-        assertEquals(ciphertext, mCipher.doFinal(getKatPlaintext()));
+        assertArrayEquals(ciphertext, mCipher.doFinal(getKatPlaintext()));
 
-        assertEquals(iv, mCipher.getIV());
+        assertArrayEquals(iv, mCipher.getIV());
         assertAlgoritmParametersIv(iv);
 
         // Just in case, test with a new instance of Cipher with the same parameters
         createCipher();
         init(Cipher.ENCRYPT_MODE, getKey(), generatedParams);
-        assertEquals(ciphertext, mCipher.doFinal(getKatPlaintext()));
+        assertArrayEquals(ciphertext, mCipher.doFinal(getKatPlaintext()));
     }
 
+    @Test
     public void testGeneratedIvDoesNotSurviveReinitialization() throws Exception {
         if (getKatIv() == null) {
             // This transformation does not use an IV
@@ -457,6 +481,7 @@
         }
     }
 
+    @Test
     public void testExplicitlySetIvDoesNotSurviveReinitialization() throws Exception {
         if (getKatIv() == null) {
             // This transformation does not use an IV
@@ -474,6 +499,7 @@
         }
     }
 
+    @Test
     public void testReinitializingInDecryptModeDoesNotUsePreviouslyUsedIv() throws Exception {
         if (getKatIv() == null) {
             // This transformation does not use an IV
@@ -534,6 +560,7 @@
         } catch (InvalidAlgorithmParameterException expected) {}
     }
 
+    @Test
     public void testKeyDoesNotSurviveReinitialization() throws Exception {
         assertKeyDoesNotSurviveReinitialization(Cipher.ENCRYPT_MODE);
         assertKeyDoesNotSurviveReinitialization(Cipher.DECRYPT_MODE);
@@ -573,6 +600,7 @@
         }
     }
 
+    @Test
     public void testDoFinalResets() throws Exception {
         assertDoFinalResetsCipher(Cipher.DECRYPT_MODE);
         assertDoFinalResetsCipher(Cipher.ENCRYPT_MODE);
@@ -584,7 +612,7 @@
 
         createCipher();
         initKat(opmode);
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
 
         if ((opmode == Cipher.ENCRYPT_MODE) && (getKatIv() != null)) {
             // Assert that this cipher cannot be reused (thus making IV reuse harder)
@@ -596,27 +624,28 @@
         }
 
         // Assert that the same output is produced after the above reset
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
 
         // Assert that the same output is produced after the above reset. This time, make update()
         // buffer half a block of input.
         if (input.length < getBlockSize() * 2) {
             fail("This test requires an input which is at least two blocks long");
         }
-        assertEquals(expectedOutput, concat(
+        assertArrayEquals(expectedOutput, concat(
                 update(subarray(input, 0, getBlockSize() * 3 / 2)),
                 doFinal(subarray(input, getBlockSize() * 3 / 2, input.length))));
 
         // Assert that the same output is produced after the above reset, despite half of the block
         // having been buffered prior to the reset. This is in case the implementation does not
         // empty that buffer when resetting.
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
 
         // Assert that the IV with which the cipher was initialized is still there after the resets.
-        assertEquals(getKatIv(), mCipher.getIV());
+        assertArrayEquals(getKatIv(), mCipher.getIV());
         assertAlgoritmParametersIv(getKatIv());
     }
 
+    @Test
     public void testUpdateWithEmptyInputReturnsCorrectValue() throws Exception {
         // Test encryption
         createCipher();
@@ -646,6 +675,7 @@
         assertEquals(null, update(new byte[getBlockSize()], 0, 0));
     }
 
+    @Test
     public void testUpdateDoesNotProduceOutputWhenInsufficientInput() throws Exception {
         if (isStreamCipher()) {
             // Stream ciphers always produce output for non-empty input.
@@ -693,12 +723,14 @@
         assertEquals(0, update(ByteBuffer.allocate(1), ByteBuffer.allocate(getBlockSize())));
     }
 
+    @Test
     public void testKatOneShotEncryptUsingDoFinal() throws Exception {
         createCipher();
         assertKatOneShotTransformUsingDoFinal(
                 Cipher.ENCRYPT_MODE, getKatPlaintext(), getKatCiphertext());
     }
 
+    @Test
     public void testKatOneShotDecryptUsingDoFinal() throws Exception {
         createCipher();
         assertKatOneShotTransformUsingDoFinal(
@@ -714,11 +746,11 @@
                 new byte[4]);
 
         initKat(opmode);
-        assertEquals(expectedOutput, doFinal(input));
+        assertArrayEquals(expectedOutput, doFinal(input));
         initKat(opmode);
-        assertEquals(expectedOutput, doFinal(input, 0, input.length));
+        assertArrayEquals(expectedOutput, doFinal(input, 0, input.length));
         initKat(opmode);
-        assertEquals(expectedOutput,
+        assertArrayEquals(expectedOutput,
                 doFinal(bufferWithInputInTheMiddle,
                         bufferWithInputInTheMiddleCleartextOffset,
                         input.length));
@@ -736,6 +768,7 @@
                 actualOutputBuffer);
     }
 
+    @Test
     public void testKatEncryptOneByteAtATime() throws Exception {
         createCipher();
         initKat(Cipher.ENCRYPT_MODE);
@@ -758,7 +791,7 @@
             } else {
                 expectedFinalOutput = EmptyArray.BYTE;
             }
-            assertEquals(expectedFinalOutput, finalOutput);
+            assertArrayEquals(expectedFinalOutput, finalOutput);
         } else {
             // Not a stream cipher -- operates on full blocks only.
 
@@ -773,7 +806,7 @@
                         additionalInformation = " (b/194134359)";
                     }
                     // Cipher.update is expected to have output a new block
-                    assertEquals(
+                    assertArrayEquals(
                             "plaintext index: " + plaintextIndex + additionalInformation,
                             subarray(
                                     expectedCiphertext,
@@ -782,7 +815,7 @@
                             output);
                 } else {
                     // Cipher.update is expected to have produced no output
-                    assertEquals("plaintext index: " + plaintextIndex, null, output);
+                    assertArrayEquals("plaintext index: " + plaintextIndex, null, output);
                 }
                 if (output != null) {
                     ciphertextIndex += output.length;
@@ -792,10 +825,11 @@
             byte[] actualFinalOutput = doFinal();
             byte[] expectedFinalOutput =
                     subarray(expectedCiphertext, ciphertextIndex, expectedCiphertext.length);
-            assertEquals(expectedFinalOutput, actualFinalOutput);
+            assertArrayEquals(expectedFinalOutput, actualFinalOutput);
         }
     }
 
+    @Test
     public void testKatDecryptOneByteAtATime() throws Exception {
         createCipher();
         initKat(Cipher.DECRYPT_MODE);
@@ -812,7 +846,7 @@
                         0, (output != null) ? output.length : 0);
             }
             byte[] finalOutput = doFinal();
-            assertEquals(expectedPlaintext, finalOutput);
+            assertArrayEquals(expectedPlaintext, finalOutput);
         } else if (isStreamCipher()) {
             // Unauthenticated stream cipher -- one byte in, one byte out
             for (int ciphertextIndex = 0; ciphertextIndex < ciphertext.length; ciphertextIndex++) {
@@ -841,7 +875,7 @@
                     if (isStrongbox()) {
                         additionalInformation = " (b/194134040)";
                     }
-                    assertEquals(
+                    assertArrayEquals(
                             "ciphertext index: " + ciphertextIndex + additionalInformation,
                             subarray(expectedPlaintext, plaintextIndex, plaintextIndex + blockSize),
                             output);
@@ -857,10 +891,11 @@
             byte[] actualFinalOutput = doFinal();
             byte[] expectedFinalOutput =
                     subarray(expectedPlaintext, plaintextIndex, expectedPlaintext.length);
-            assertEquals(expectedFinalOutput, actualFinalOutput);
+            assertArrayEquals(expectedFinalOutput, actualFinalOutput);
         }
     }
 
+    @Test
     public void testUpdateAADNotSupported() throws Exception {
         if (isAuthenticatedCipher()) {
             // Not applicable to authenticated ciphers where updateAAD is supported.
@@ -876,6 +911,7 @@
         assertUpdateAADNotSupported();
     }
 
+    @Test
     public void testUpdateAADSupported() throws Exception {
         if (!isAuthenticatedCipher()) {
             // Not applicable to unauthenticated ciphers where updateAAD is not supported.
@@ -919,6 +955,7 @@
 
     // TODO: Add tests for WRAP and UNWRAP
 
+    @Test
     public void testUpdateAndDoFinalNotSupportedInWrapAndUnwrapModes() throws Exception {
         createCipher();
         assertUpdateAndDoFinalThrowIllegalStateExceprtion(
@@ -1011,6 +1048,7 @@
         } catch (IllegalStateException expected) {}
     }
 
+    @Test
     public void testGeneratedPadding() throws Exception {
         // Assert that the Cipher under test correctly handles plaintexts of various lengths.
         if (isStreamCipher()) {
@@ -1043,7 +1081,7 @@
             }
             byte[] ciphertext = doFinal(plaintext);
 
-            assertEquals(
+            assertArrayEquals(
                     "lastInputBlockUnusedByteCount: " + lastInputBlockUnusedByteCount,
                     baseCiphertext,
                     subarray(ciphertext, 0, baseCiphertext.length));
@@ -1061,13 +1099,14 @@
                     "lastInputBlockUnusedByteCount: " + lastInputBlockUnusedByteCount,
                     expectedDecryptedPlaintextLength,
                     decryptedPlaintext.length);
-            assertEquals(
+            assertArrayEquals(
                     "lastInputBlockUnusedByteCount: " + lastInputBlockUnusedByteCount,
                     basePlaintext,
                     subarray(decryptedPlaintext, 0, basePlaintext.length));
         }
     }
 
+    @Test
     public void testDecryptWithMangledPadding() throws Exception {
         if (!isPaddingEnabled()) {
             // Test not applicable when padding not in use
@@ -1093,6 +1132,7 @@
         }
     }
 
+    @Test
     public void testDecryptWithMissingPadding() throws Exception {
         if (!isPaddingEnabled()) {
             // Test not applicable when padding not in use
@@ -1115,6 +1155,7 @@
         }
     }
 
+    @Test
     public void testUpdateCopySafe() throws Exception {
         // Assert that when input and output buffers passed to Cipher.update reference the same
         // byte array, then no input data is overwritten before it's consumed.
@@ -1202,7 +1243,7 @@
         assertEquals(additionalInformation, expectedOutput.length,
                 update(buffer, inputOffsetInBuffer, input.length,
                         buffer, outputOffsetInBuffer));
-        assertEquals(expectedOutput,
+        assertArrayEquals(expectedOutput,
                 subarray(buffer, outputOffsetInBuffer, outputEndIndexInBuffer));
 
         if (outputOffsetInBuffer == 0) {
@@ -1213,7 +1254,7 @@
             initKat(opmode);
             assertEquals(expectedOutput.length,
                     update(buffer, inputOffsetInBuffer, input.length, buffer));
-            assertEquals(expectedOutput,
+            assertArrayEquals(expectedOutput,
                     subarray(buffer, outputOffsetInBuffer, outputEndIndexInBuffer));
         }
 
@@ -1226,10 +1267,11 @@
         createCipher();
         initKat(opmode);
         assertEquals(expectedOutput.length, update(inputBuffer, outputBuffer));
-        assertEquals(expectedOutput,
+        assertArrayEquals(expectedOutput,
                 subarray(buffer, outputOffsetInBuffer, outputEndIndexInBuffer));
     }
 
+    @Test
     public void testDoFinalCopySafe() throws Exception {
         // Assert that when input and output buffers passed to Cipher.doFinal reference the same
         // byte array, then no input data is overwritten before it's consumed.
@@ -1271,7 +1313,7 @@
         assertEquals(expectedOutput.length,
                 doFinal(buffer, inputOffsetInBuffer, input.length,
                         buffer, outputOffsetInBuffer));
-        assertEquals(expectedOutput,
+        assertArrayEquals(expectedOutput,
                 subarray(buffer, outputOffsetInBuffer, outputEndIndexInBuffer));
 
         if (outputOffsetInBuffer == 0) {
@@ -1282,7 +1324,7 @@
             initKat(opmode);
             assertEquals(expectedOutput.length,
                     doFinal(buffer, inputOffsetInBuffer, input.length, buffer));
-            assertEquals(expectedOutput,
+            assertArrayEquals(expectedOutput,
                     subarray(buffer, outputOffsetInBuffer, outputEndIndexInBuffer));
         }
 
@@ -1295,10 +1337,11 @@
         createCipher();
         initKat(opmode);
         assertEquals(expectedOutput.length, doFinal(inputBuffer, outputBuffer));
-        assertEquals(expectedOutput,
+        assertArrayEquals(expectedOutput,
                 subarray(buffer, outputOffsetInBuffer, outputEndIndexInBuffer));
     }
 
+    @Test
     public void testVeryLargeBlock() throws Exception {
         createCipher();
         Key key = importKey(getKatKey());
@@ -1564,13 +1607,6 @@
         mCipher.updateAAD(input);
     }
 
-    @SuppressWarnings("unused")
-    protected static void assertEquals(Buffer expected, Buffer actual) {
-        throw new RuntimeException(
-                "Comparing ByteBuffers using their .equals is probably not what you want"
-                + " -- use assertByteBufferEquals instead.");
-    }
-
     /**
      * Asserts that the position, limit, and capacity of the provided buffers are the same, and that
      * their contents (from position {@code 0} to capacity) are the same.
@@ -1647,33 +1683,6 @@
         return result;
     }
 
-    protected static void assertEquals(byte[] expected, byte[] actual) {
-        assertEquals(null, expected, actual);
-    }
-
-    protected static void assertEquals(String message, byte[] expected, byte[] actual) {
-        if (!Arrays.equals(expected, actual)) {
-            StringBuilder detail = new StringBuilder();
-            if (expected != null) {
-                detail.append("Expected (" + expected.length + " bytes): <"
-                        + HexEncoding.encode(expected) + ">");
-            } else {
-                detail.append("Expected: null");
-            }
-            if (actual != null) {
-                detail.append(", actual (" + actual.length + " bytes): <"
-                        + HexEncoding.encode(actual) + ">");
-            } else {
-                detail.append(", actual: null");
-            }
-            if (message != null) {
-                fail(message + ": " + detail);
-            } else {
-                fail(detail.toString());
-            }
-        }
-    }
-
     protected final void assertInitRejectsIvParameterSpec(byte[] iv) throws Exception {
         Key key = importKey(getKatKey());
         createCipher();
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index 562910b..94dd585 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -16,6 +16,14 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.app.KeyguardManager;
 import android.content.Context;
 import android.content.pm.PackageManager;
@@ -28,8 +36,9 @@
 import android.security.keystore.KeyProtection;
 import android.server.wm.ActivityManagerTestBase;
 import android.server.wm.UiDeviceUtils;
-import android.test.AndroidTestCase;
-import android.test.MoreAsserts;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.google.common.collect.ObjectArrays;
 
@@ -65,11 +74,15 @@
 import javax.crypto.spec.PSource;
 import javax.crypto.spec.SecretKeySpec;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 /**
  * Tests for algorithm-agnostic functionality of {@code Cipher} implementations backed by Android
  * Keystore.
  */
-public class CipherTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class CipherTest {
 
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_CRYPTO_OP_PROVIDER_NAME;
 
@@ -277,7 +290,11 @@
     private static final byte[] DESede_KAT_KEY_BYTES = HexEncoding.decode(
             "5EBE2294ECD0E0F08EAB7690D2A6EE6926AE5CC854E36B6B");
 
-    private class DeviceLockSession  extends ActivityManagerTestBase implements AutoCloseable {
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    private class DeviceLockSession extends ActivityManagerTestBase implements AutoCloseable {
 
         private LockScreenSession mLockCredential;
 
@@ -311,11 +328,11 @@
         @Override
         public void close() throws Exception {
             mLockCredential.close();
-            tearDown();
         }
     }
 
     @Presubmit
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected Cipher
         // transformations. We don't care whether the transformations are exposed via aliases, as
@@ -340,6 +357,7 @@
                 expectedAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testAndroidKeyStoreKeysHandledByAndroidKeyStoreProviderWhenDecrypting()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -377,6 +395,7 @@
         }
     }
 
+    @Test
     public void testAndroidKeyStorePublicKeysAcceptedByHighestPriorityProviderWhenEncrypting()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -402,6 +421,7 @@
         }
     }
 
+    @Test
     public void testEmptyPlaintextEncryptsAndDecrypts()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -437,7 +457,7 @@
                     Key decryptionKey = key.getKeystoreBackedDecryptionKey();
                     cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
                     byte[] actualPlaintext = cipher.doFinal(ciphertext);
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias(),
@@ -452,6 +472,7 @@
      * is in interrupted state which cannot be signaled to the user of the Java Crypto
      * API.
      */
+    @Test
     public void testEncryptsAndDecryptsInterrupted()
             throws Exception {
 
@@ -490,7 +511,7 @@
                     cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
                     byte[] actualPlaintext = cipher.doFinal(ciphertext);
                     assertTrue(Thread.currentThread().interrupted());
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias(),
@@ -503,6 +524,7 @@
     /*
      * This test performs a round trip en/decryption using Cipher*Streams.
      */
+    @Test
     public void testEncryptsAndDecryptsUsingCipherStreams()
             throws Exception {
 
@@ -580,7 +602,7 @@
             Key decryptionKey = key.getKeystoreBackedDecryptionKey();
             cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
             byte[] actualPlaintext = cipher.doFinal(ciphertext);
-            MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+            assertArrayEquals(expectedPlaintext, actualPlaintext);
             return true;
         } catch (Throwable e) {
             return false;
@@ -598,6 +620,7 @@
     }
 
     @Presubmit
+    @Test
     public void testKeyguardLockAndUnlock()
             throws Exception {
         if (!hasSecureLockScreen()) {
@@ -616,6 +639,7 @@
         }
     }
 
+    @Test
     public void testEmptyPlaintextEncryptsAndDecryptsWhenUnlockedRequired()
             throws Exception {
         final boolean isUnlockedDeviceRequired = true;
@@ -706,6 +730,7 @@
         }
     }
 
+    @Test
     public void testCiphertextGeneratedByAndroidKeyStoreDecryptsByAndroidKeyStore()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -741,7 +766,7 @@
                     Key decryptionKey = key.getKeystoreBackedDecryptionKey();
                     cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
                     byte[] actualPlaintext = cipher.doFinal(ciphertext);
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias(),
@@ -751,6 +776,7 @@
         }
     }
 
+    @Test
     public void testCiphertextGeneratedByHighestPriorityProviderDecryptsByAndroidKeyStore()
             throws Exception {
         Provider keystoreProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -852,7 +878,7 @@
                     Key decryptionKey = key.getKeystoreBackedDecryptionKey();
                     cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
                     byte[] actualPlaintext = cipher.doFinal(ciphertext);
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias()
@@ -863,6 +889,7 @@
         }
     }
 
+    @Test
     public void testCiphertextGeneratedByAndroidKeyStoreDecryptsByHighestPriorityProvider()
             throws Exception {
         Provider keystoreProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -914,7 +941,7 @@
                         continue;
                     }
                     byte[] actualPlaintext = cipher.doFinal(ciphertext);
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias()
@@ -925,6 +952,7 @@
         }
     }
 
+    @Test
     public void testMaxSizedPlaintextSupported() throws Exception {
         Provider keystoreProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(keystoreProvider);
@@ -975,7 +1003,7 @@
                     Key decryptionKey = key.getKeystoreBackedDecryptionKey();
                     cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
                     byte[] actualPlaintext = cipher.doFinal(ciphertext);
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
 
                     // Check that ciphertext decrypts using the highest-priority provider.
                     cipher = Cipher.getInstance(algorithm);
@@ -992,7 +1020,7 @@
                         continue;
                     }
                     actualPlaintext = cipher.doFinal(ciphertext);
-                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                    assertArrayEquals(expectedPlaintext, actualPlaintext);
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias()
@@ -1004,6 +1032,7 @@
         }
     }
 
+    @Test
     public void testLargerThanMaxSizedPlaintextRejected() throws Exception {
         Provider keystoreProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(keystoreProvider);
@@ -1083,6 +1112,7 @@
         }
     }
 
+    @Test
     public void testKat() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -1105,7 +1135,7 @@
                     expectedPlaintext = TestUtils.leftPadWithZeroBytes(
                             expectedPlaintext, modulusLengthBytes);
                 }
-                MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                assertArrayEquals(expectedPlaintext, actualPlaintext);
                 if (!isRandomizedEncryption(algorithm)) {
                     // Deterministic encryption: ciphertext depends only on plaintext and input
                     // parameters. Assert that encrypting the plaintext results in the same
@@ -1114,7 +1144,7 @@
                     cipher = Cipher.getInstance(algorithm, provider);
                     cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, testVector.params);
                     byte[] actualCiphertext = cipher.doFinal(testVector.plaintext);
-                    MoreAsserts.assertEquals(testVector.ciphertext, actualCiphertext);
+                    assertArrayEquals(testVector.ciphertext, actualCiphertext);
                 }
             } catch (Throwable e) {
                 throw new RuntimeException("Failed for " + algorithm, e);
@@ -1128,6 +1158,7 @@
                 || (transformationUpperCase.contains("OAEP"));
     }
 
+    @Test
     public void testCanCreateAuthBoundKeyWhenScreenLocked() throws Exception {
         final boolean isUnlockedDeviceRequired = false;
         final boolean isUserAuthRequired = true;
@@ -1155,6 +1186,7 @@
         }
     }
 
+    @Test
     public void testCannotCreateAuthBoundKeyWhenDevicePinNotSet() throws Exception {
         final boolean isUserAuthRequired = true;
         final boolean isUnlockedDeviceRequired = false;
@@ -1177,6 +1209,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptFailsWhenNotAuthorizedToDecrypt() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             try {
@@ -1192,6 +1225,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricFailsWhenNotAuthorizedToEncrypt() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (!isSymmetric(transformation)) {
@@ -1211,6 +1245,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptAsymmetricIgnoresAuthorizedPurposes() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (isSymmetric(transformation)) {
@@ -1230,6 +1265,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptFailsWhenBlockModeNotAuthorized() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(
@@ -1258,6 +1294,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricFailsWhenBlockModeNotAuthorized() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (!isSymmetric(transformation)) {
@@ -1291,6 +1328,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptAsymmetricIgnoresAuthorizedBlockModes() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (isSymmetric(transformation)) {
@@ -1311,6 +1349,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptFailsWhenDigestNotAuthorized() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             String impliedDigest = TestUtils.getCipherDigest(transformation);
@@ -1344,6 +1383,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricFailsWhenDigestNotAuthorized() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (!isSymmetric(transformation)) {
@@ -1381,6 +1421,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptAsymmetricIgnoresAuthorizedDigests() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (isSymmetric(transformation)) {
@@ -1399,6 +1440,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptFailsWhenPaddingSchemeNotAuthorized() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             String impliedEncryptionPadding = TestUtils.getCipherEncryptionPadding(transformation);
@@ -1445,6 +1487,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricFailsWhenPaddingSchemeNotAuthorized() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (!isSymmetric(transformation)) {
@@ -1484,6 +1527,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptAsymmetricIgnoresAuthorizedPaddingSchemes() throws Exception {
         for (String transformation : EXPECTED_ALGORITHMS) {
             if (isSymmetric(transformation)) {
@@ -1506,6 +1550,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptFailsWhenKeyNotYetValid() throws Exception {
         Date badStartDate = new Date(System.currentTimeMillis() + DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
@@ -1523,6 +1568,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricFailsWhenKeyNotYetValid() throws Exception {
         Date badStartDate = new Date(System.currentTimeMillis() + DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
@@ -1543,6 +1589,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptAsymmetricIgnoresThatKeyNotYetValid() throws Exception {
         Date badStartDate = new Date(System.currentTimeMillis() + DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
@@ -1563,6 +1610,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptFailsWhenKeyNoLongerValidForConsumption() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
@@ -1582,6 +1630,7 @@
         }
     }
 
+    @Test
     public void testInitDecryptIgnoresThatKeyNoLongerValidForOrigination() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
@@ -1601,6 +1650,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricFailsWhenKeyNoLongerValidForOrigination() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
@@ -1623,6 +1673,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptSymmetricIgnoresThatKeyNoLongerValidForConsumption()
             throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
@@ -1646,6 +1697,7 @@
         }
     }
 
+    @Test
     public void testInitEncryptAsymmetricIgnoresThatKeyNoLongerValid() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String transformation : EXPECTED_ALGORITHMS) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/DESedeCipherTestBase.java b/tests/tests/keystore/src/android/keystore/cts/DESedeCipherTestBase.java
index cc3bac1..ae6ea57 100644
--- a/tests/tests/keystore/src/android/keystore/cts/DESedeCipherTestBase.java
+++ b/tests/tests/keystore/src/android/keystore/cts/DESedeCipherTestBase.java
@@ -2,6 +2,8 @@
 
 import android.keystore.cts.util.TestUtils;
 
+import org.junit.Test;
+
 public abstract class DESedeCipherTestBase extends BlockCipherTestBase {
 
     private static final byte[] KAT_KEY = HexEncoding.decode(
@@ -40,6 +42,7 @@
     }
 
     @java.lang.Override
+    @Test
     public void testGetProvider() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testGetProvider();
@@ -47,6 +50,7 @@
     }
 
     @java.lang.Override
+    @Test
     public void testGetAlgorithm() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testGetProvider();
@@ -54,6 +58,7 @@
     }
 
     @java.lang.Override
+    @Test
     public void testGetBlockSize() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testGetProvider();
@@ -61,6 +66,7 @@
     }
 
     @java.lang.Override
+    @Test
     public void testGetExemptionMechanism() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testGetProvider();
@@ -68,6 +74,7 @@
     }
 
   @Override
+    @Test
     public void testUpdateCopySafe() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateCopySafe();
@@ -75,6 +82,7 @@
     }
 
     @Override
+    @Test
     public void testUpdateAndDoFinalNotSupportedInWrapAndUnwrapModes() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -82,6 +90,7 @@
     }
 
     @Override
+    @Test
     public void testKeyDoesNotSurviveReinitialization() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -89,6 +98,7 @@
     }
 
     @Override
+    @Test
     public void testKatOneShotEncryptUsingDoFinal() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -96,6 +106,7 @@
     }
 
     @Override
+    @Test
     public void testKatOneShotDecryptUsingDoFinal() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -103,6 +114,7 @@
     }
 
     @Override
+    @Test
     public void testKatEncryptOneByteAtATime() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -110,6 +122,7 @@
     }
 
     @Override
+    @Test
     public void testKatDecryptOneByteAtATime() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -117,6 +130,7 @@
     }
 
     @Override
+    @Test
     public void testIvGeneratedAndUsedWhenEncryptingWithoutExplicitIv() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -124,6 +138,7 @@
     }
 
     @Override
+    @Test
     public void testGetParameters() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -131,6 +146,7 @@
     }
 
     @Override
+    @Test
     public void testGetOutputSizeInEncryptionMode() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -138,6 +154,7 @@
     }
 
     @Override
+    @Test
     public void testGetOutputSizeInDecryptionMode() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -145,6 +162,7 @@
     }
 
     @Override
+    @Test
     public void testGetIV() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -152,6 +170,7 @@
     }
 
     @Override
+    @Test
     public void testUpdateWithEmptyInputReturnsCorrectValue() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -159,6 +178,7 @@
     }
 
     @Override
+    @Test
     public void testUpdateDoesNotProduceOutputWhenInsufficientInput() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -166,6 +186,7 @@
     }
 
     @Override
+    @Test
     public void testUpdateAADNotSupported() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -173,6 +194,7 @@
     }
 
     @Override
+    @Test
     public void testGeneratedPadding() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -180,6 +202,7 @@
     }
 
     @Override
+    @Test
     public void testDoFinalResets() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -187,6 +210,7 @@
     }
 
     @Override
+    @Test
     public void testDoFinalCopySafe() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -194,6 +218,7 @@
     }
 
     @Override
+    @Test
     public void testDecryptWithMissingPadding() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -201,6 +226,7 @@
     }
 
     @Override
+    @Test
     public void testDecryptWithMangledPadding() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -208,6 +234,7 @@
     }
 
     @Override
+    @Test
     public void testReinitializingInDecryptModeDoesNotUsePreviouslyUsedIv() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -215,6 +242,7 @@
     }
 
     @Override
+    @Test
     public void testInitRequiresIvInDecryptMode() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -222,6 +250,7 @@
     }
 
     @Override
+    @Test
     public void testGeneratedIvSurvivesReset() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -229,6 +258,7 @@
     }
 
     @Override
+    @Test
     public void testGeneratedIvDoesNotSurviveReinitialization() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -236,6 +266,7 @@
     }
 
     @Override
+    @Test
     public void testExplicitlySetIvDoesNotSurviveReinitialization() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testUpdateWithEmptyInputReturnsCorrectValue();
@@ -243,6 +274,7 @@
     }
 
     @Override
+    @Test
     public void testVeryLargeBlock() throws Exception {
         if (TestUtils.supports3DES()) {
             super.testVeryLargeBlock();
diff --git a/tests/tests/keystore/src/android/keystore/cts/DESedeECBNoPaddingCipherTest.java b/tests/tests/keystore/src/android/keystore/cts/DESedeECBNoPaddingCipherTest.java
index 38670a4..36148e9 100644
--- a/tests/tests/keystore/src/android/keystore/cts/DESedeECBNoPaddingCipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/DESedeECBNoPaddingCipherTest.java
@@ -1,5 +1,7 @@
 package android.keystore.cts;
 
+import static org.junit.Assert.fail;
+
 import java.security.AlgorithmParameters;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.InvalidParameterSpecException;
diff --git a/tests/tests/keystore/src/android/keystore/cts/DESedeECBPKCS7PaddingCipherTest.java b/tests/tests/keystore/src/android/keystore/cts/DESedeECBPKCS7PaddingCipherTest.java
index 2030b20..ad140ce 100644
--- a/tests/tests/keystore/src/android/keystore/cts/DESedeECBPKCS7PaddingCipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/DESedeECBPKCS7PaddingCipherTest.java
@@ -1,5 +1,7 @@
 package android.keystore.cts;
 
+import static org.junit.Assert.fail;
+
 import java.security.AlgorithmParameters;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.InvalidParameterSpecException;
diff --git a/tests/tests/keystore/src/android/keystore/cts/ECDSASignatureTest.java b/tests/tests/keystore/src/android/keystore/cts/ECDSASignatureTest.java
index cff3033..3339fd8 100644
--- a/tests/tests/keystore/src/android/keystore/cts/ECDSASignatureTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/ECDSASignatureTest.java
@@ -16,13 +16,19 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.content.Context;
+import android.keystore.cts.R;
 import android.keystore.cts.util.ImportedKey;
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProtection;
-import android.test.AndroidTestCase;
 
-import android.keystore.cts.R;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import java.security.KeyPair;
 import java.security.Security;
@@ -30,8 +36,17 @@
 import java.util.Arrays;
 import java.util.Collection;
 
-public class ECDSASignatureTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
+@RunWith(AndroidJUnit4.class)
+public class ECDSASignatureTest {
+
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testNONEwithECDSATruncatesInputToFieldSize() throws Exception {
         for (ImportedKey key : importKatKeyPairs("NONEwithECDSA")) {
             try {
@@ -79,6 +94,7 @@
         assertFalse(signature.verify(sigBytes));
     }
 
+    @Test
     public void testNONEwithECDSASupportsMessagesShorterThanFieldSize() throws Exception {
         for (ImportedKey key : importKatKeyPairs("NONEwithECDSA")) {
             try {
diff --git a/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java b/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java
index b30b3d2..4b66992 100644
--- a/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java
@@ -27,6 +27,11 @@
 import static android.security.keymaster.KeymasterDefs.KM_PURPOSE_ENCRYPT;
 import static android.security.keystore.KeyProperties.PURPOSE_WRAP_KEY;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.content.pm.PackageManager;
 import android.keystore.cts.util.TestUtils;
 import android.os.SystemProperties;
@@ -35,7 +40,9 @@
 import android.security.keystore.SecureKeyImportUnavailableException;
 import android.security.keystore.StrongBoxUnavailableException;
 import android.security.keystore.WrappedKeyEntry;
-import android.test.AndroidTestCase;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import org.bouncycastle.asn1.ASN1Encoding;
 import org.bouncycastle.asn1.DEREncodableVector;
@@ -74,7 +81,11 @@
 import java.io.IOException;
 import java.lang.InterruptedException;
 
-public class ImportWrappedKeyTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class ImportWrappedKeyTest {
     private static final String TAG = "ImportWrappedKeyTest";
 
     private static final String ALIAS = "my key";
@@ -85,6 +96,11 @@
 
     SecureRandom random = new SecureRandom();
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testKeyStore_ImportWrappedKey() throws Exception {
         random.setSeed(0);
 
@@ -127,6 +143,7 @@
         assertEquals(new String(c.doFinal(encrypted)), "hello, world");
     }
 
+    @Test
     public void testKeyStore_ImportWrappedKeyWrappingKeyMissing() throws Exception {
         final String EXPECTED_FAILURE = "Failed to import wrapped key. Keystore error code: 7";
         String failureMessage = null;
@@ -145,6 +162,7 @@
         assertEquals(failureMessage, EXPECTED_FAILURE);
     }
 
+    @Test
     public void testKeyStore_ImportWrappedKey_3DES() throws Exception {
       if (!TestUtils.supports3DES()) {
           return;
@@ -191,6 +209,7 @@
         assertEquals(new String(c.doFinal(encrypted)), "hello, world");
     }
 
+    @Test
     public void testKeyStore_ImportWrappedKey_3DES_StrongBox() throws Exception {
       if (!TestUtils.supports3DES()) {
           return;
@@ -235,6 +254,7 @@
         }
     }
 
+    @Test
     public void testKeyStore_ImportWrappedKey_AES_StrongBox() throws Exception {
         if (TestUtils.hasStrongBox(getContext())) {
             random.setSeed(0);
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java
index 1c84c6e..303bd7e 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java
@@ -16,6 +16,11 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import java.security.GeneralSecurityException;
 import java.security.InvalidKeyException;
 import java.security.KeyFactory;
@@ -30,6 +35,7 @@
 import junit.framework.TestCase;
 
 import org.junit.Assert;
+import org.junit.Test;
 
 import android.content.Context;
 import android.keystore.cts.util.TestUtils;
@@ -38,9 +44,10 @@
 import android.security.keystore.KeyInfo;
 import androidx.test.InstrumentationRegistry;
 
-public class KeyAgreementTest extends TestCase {
+public class KeyAgreementTest {
     private static final String PRIVATE_KEY_ALIAS = "TemporaryPrivateKey";
 
+    @Test
     public void testGenerateSecret_succeeds() throws Exception {
         KeyAgreement ka = getKeyStoreKeyAgreement();
         ka.init(generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS).getPrivate());
@@ -49,6 +56,7 @@
         assertNotNull(sharedSecret);
     }
 
+    @Test
     public void testGenerateSecret_forTwoParties_returnsSameSharedSecret() throws Exception {
         KeyPair ourKeyPair = generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS);
         KeyPair theirKeyPair = generateEphemeralServerKeyPair();
@@ -67,6 +75,7 @@
         Assert.assertArrayEquals(ourSharedSecret, theirSharedSecret);
     }
 
+    @Test
     public void testGenerateSecret_preservesPrivateKeyAndNothingElse() throws Exception {
         KeyPair otherPartyKey = generateEphemeralServerKeyPair();
         KeyAgreement ka = getKeyStoreKeyAgreement();
@@ -88,6 +97,7 @@
         Assert.assertArrayEquals(sharedSecret1, sharedSecret2);
     }
 
+    @Test
     public void testInit_withNonPrivateKey_fails() throws Exception {
         KeyAgreement ka = getKeyStoreKeyAgreement();
         try {
@@ -98,6 +108,7 @@
         }
     }
 
+    @Test
     public void testInit_withNonEcKey_fails() throws Exception {
         KeyPairGenerator kpg =
                 KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
@@ -114,6 +125,7 @@
         }
     }
 
+    @Test
     public void testDoPhase_withoutInitialization_fails() throws Exception {
         KeyAgreement ka = getKeyStoreKeyAgreement();
         try {
@@ -124,6 +136,7 @@
         }
     }
 
+    @Test
     public void testGenerateSecret_withoutSecondPartyKey_fails() throws Exception {
         KeyAgreement ka = getKeyStoreKeyAgreement();
         ka.init(generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS).getPrivate());
@@ -135,6 +148,7 @@
         }
     }
 
+    @Test
     public void testDoPhase_multiparty_fails() throws Exception {
         // Multi-party key agreement is not supported by Keymint
         KeyAgreement ka = getKeyStoreKeyAgreement();
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 7fa5af7..d0adb09 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -54,8 +54,16 @@
 import static org.hamcrest.Matchers.greaterThanOrEqualTo;
 import static org.hamcrest.Matchers.hasItems;
 import static org.hamcrest.Matchers.lessThanOrEqualTo;
-import static org.junit.Assert.assertNotEquals;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.keystore.cts.util.TestUtils;
@@ -67,14 +75,14 @@
 import android.security.keystore.DeviceIdAttestationException;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyProperties;
-import android.test.AndroidTestCase;
 import android.util.ArraySet;
 import android.util.Log;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.RequiresDevice;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.google.common.collect.ImmutableSet;
 
-import androidx.test.filters.RequiresDevice;
-
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 
@@ -102,13 +110,18 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import javax.crypto.KeyGenerator;
+
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 /**
  * Tests for Android KeysStore attestation.
  */
-public class KeyAttestationTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class KeyAttestationTest {
 
     private static final String TAG = AndroidKeyStoreTest.class.getSimpleName();
 
@@ -135,6 +148,11 @@
     private static final int KM_ERROR_INVALID_INPUT_LENGTH = -21;
     private static final int KM_ERROR_PERMISSION_DENIED = 6;
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testVersionParser() throws Exception {
         // Non-numerics/empty give version 0
         assertEquals(0, parseSystemOsVersion(""));
@@ -159,7 +177,12 @@
     }
 
     @RequiresDevice
+    @Test
     public void testEcAttestation() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
             return;
 
@@ -212,7 +235,12 @@
         }
     }
 
+    @Test
     public void testEcAttestation_TooLargeChallenge() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         boolean[] devicePropertiesAttestationValues = {true, false};
         for (boolean devicePropertiesAttestation : devicePropertiesAttestationValues) {
             try {
@@ -229,6 +257,7 @@
         }
     }
 
+    @Test
     public void testEcAttestation_NoChallenge() throws Exception {
         boolean[] devicePropertiesAttestationValues = {true, false};
         for (boolean devicePropertiesAttestation : devicePropertiesAttestationValues) {
@@ -266,7 +295,12 @@
 
     @RestrictedBuildTest
     @RequiresDevice
+    @Test
     public void testEcAttestation_DeviceLocked() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
             return;
 
@@ -305,6 +339,7 @@
         }
     }
 
+    @Test
     public void testAttestationKmVersionMatchesFeatureVersion() throws Exception {
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
             return;
@@ -349,6 +384,7 @@
         }
     }
 
+    @Test
     public void testAttestationKmVersionMatchesFeatureVersionStrongBox() throws Exception {
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
             return;
@@ -402,6 +438,7 @@
         }
     }
 
+    @Test
     public void testEcAttestation_KeyStoreExceptionWhenRequestingUniqueId() throws Exception {
         String keystoreAlias = "test_key";
         KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(keystoreAlias, PURPOSE_SIGN)
@@ -426,7 +463,12 @@
     }
 
     @RequiresDevice
+    @Test
     public void testRsaAttestation() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
             return;
 
@@ -488,7 +530,12 @@
         }
     }
 
+    @Test
     public void testRsaAttestation_TooLargeChallenge() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         boolean[] devicePropertiesAttestationValues = {true, false};
         for (boolean devicePropertiesAttestation : devicePropertiesAttestationValues) {
             try {
@@ -507,6 +554,7 @@
         }
     }
 
+    @Test
     public void testRsaAttestation_NoChallenge() throws Exception {
         boolean[] devicePropertiesAttestationValues = {true, false};
         for (boolean devicePropertiesAttestation : devicePropertiesAttestationValues) {
@@ -542,7 +590,12 @@
 
     @RestrictedBuildTest
     @RequiresDevice  // Emulators have no place to store the needed key
+    @Test
     public void testRsaAttestation_DeviceLocked() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
             return;
 
@@ -581,6 +634,7 @@
         }
     }
 
+    @Test
     public void testAesAttestation() throws Exception {
         boolean[] devicePropertiesAttestationValues = {true, false};
         for (boolean devicePropertiesAttestation : devicePropertiesAttestationValues) {
@@ -604,6 +658,7 @@
         }
     }
 
+    @Test
     public void testHmacAttestation() throws Exception {
         boolean[] devicePropertiesAttestationValues = {true, false};
         for (boolean devicePropertiesAttestation : devicePropertiesAttestationValues) {
@@ -649,6 +704,7 @@
         }
     }
 
+    @Test
     public void testDeviceIdAttestation() throws Exception {
         testDeviceIdAttestationFailure(AttestationUtils.ID_TYPE_SERIAL, null);
         testDeviceIdAttestationFailure(AttestationUtils.ID_TYPE_IMEI, "Unable to retrieve IMEI");
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java
index 77cde44..1d3d02f 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyChainTest.java
@@ -16,21 +16,39 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.content.pm.PackageManager;
 import android.os.Handler;
 import android.security.KeyChain;
 import android.security.KeyChainException;
-import android.test.AndroidTestCase;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import java.util.concurrent.CountDownLatch;
 
-public class KeyChainTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class KeyChainTest {
+
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testIsKeyAlgorithmSupported_RequiredAlgorithmsSupported() throws Exception {
         assertFalse("DSA must not be supported", KeyChain.isKeyAlgorithmSupported("DSA"));
         assertTrue("EC must be supported", KeyChain.isKeyAlgorithmSupported("EC"));
         assertTrue("RSA must be supported", KeyChain.isKeyAlgorithmSupported("RSA"));
     }
 
+    @Test
     public void testNullPrivateKeyArgumentsFail()
             throws KeyChainException, InterruptedException {
         try {
@@ -41,6 +59,7 @@
         }
     }
 
+    @Test
     public void testNullPrivateKeyAliasArgumentFails()
             throws KeyChainException, InterruptedException {
         try {
@@ -51,6 +70,7 @@
         }
     }
 
+    @Test
     public void testNullPrivateKeyContextArgumentFails()
             throws KeyChainException, InterruptedException {
         try {
@@ -68,6 +88,7 @@
      * hardware/libhardware/include/hardware/keymaster.h and the associated
      * tests in hardware/libhardware/tests/keymaster/
      */
+    @Test
     public void testIsBoundKeyAlgorithm_RequiredAlgorithmsSupported() throws Exception {
         if (isLeanbackOnly()) {
             KeyChain.isBoundKeyAlgorithm("RSA");
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyFactoryTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyFactoryTest.java
index d318e24..98cb2c3 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyFactoryTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyFactoryTest.java
@@ -16,14 +16,21 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.keystore.cts.util.TestUtils;
+import android.keystore.cts.R;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
 import android.security.keystore.KeyProperties;
-import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 
-import android.keystore.cts.R;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import java.io.InputStream;
 import java.security.InvalidKeyException;
@@ -58,7 +65,11 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
 
-public class KeyFactoryTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class KeyFactoryTest {
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_PROVIDER_NAME;
 
     private static final String[] EXPECTED_ALGORITHMS = {
@@ -66,6 +77,11 @@
         "RSA",
     };
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected KeyFactory algorithms.
         // We don't care whether the algorithms are exposed via aliases, as long as canonical names
@@ -89,6 +105,7 @@
                 expectedAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testGetKeySpecWithKeystorePrivateKeyAndKeyInfoReflectsAllAuthorizations()
             throws Exception {
         Date keyValidityStart = new Date(System.currentTimeMillis() - TestUtils.DAY_IN_MILLIS);
@@ -152,6 +169,7 @@
         }
     }
 
+    @Test
     public void testGetKeySpecWithKeystorePublicKeyRejectsKeyInfo()
             throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
@@ -171,6 +189,7 @@
         }
     }
 
+    @Test
     public void testGetKeySpecWithKeystorePrivateKeyRejectsTransparentKeySpecAndEncodedKeySpec()
             throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
@@ -205,6 +224,7 @@
         }
     }
 
+    @Test
     public void testGetKeySpecWithKeystorePublicKeyAcceptsX509EncodedKeySpec()
             throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
@@ -225,6 +245,7 @@
         }
     }
 
+    @Test
     public void testGetKeySpecWithKeystorePublicKeyAcceptsTransparentKeySpec()
             throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
@@ -258,6 +279,7 @@
         }
     }
 
+    @Test
     public void testTranslateKeyWithNullKeyThrowsInvalidKeyException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -272,6 +294,7 @@
         }
     }
 
+    @Test
     public void testTranslateKeyRejectsNonAndroidKeystoreKeys() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -287,6 +310,7 @@
         }
     }
 
+    @Test
     public void testTranslateKeyAcceptsAndroidKeystoreKeys() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -304,6 +328,7 @@
         }
     }
 
+    @Test
     public void testGeneratePrivateWithNullSpecThrowsInvalidKeySpecException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -318,6 +343,7 @@
         }
     }
 
+    @Test
     public void testGeneratePublicWithNullSpecThrowsInvalidKeySpecException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -332,6 +358,7 @@
         }
     }
 
+    @Test
     public void testGeneratePrivateRejectsPKCS8EncodedKeySpec() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             int resId;
@@ -360,6 +387,7 @@
         }
     }
 
+    @Test
     public void testGeneratePublicRejectsX509EncodedKeySpec() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             int resId;
@@ -388,6 +416,7 @@
         }
     }
 
+    @Test
     public void testGeneratePrivateRejectsTransparentKeySpec() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             int resId;
@@ -417,6 +446,7 @@
         }
     }
 
+    @Test
     public void testGeneratePublicRejectsTransparentKeySpec() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             int resId;
@@ -446,6 +476,7 @@
         }
     }
 
+    @Test
     public void testGeneratePrivateAndPublicRejectKeyInfo() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java
index 2cda759..de4dbb6 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java
@@ -16,6 +16,14 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import static org.testng.Assert.assertThrows;
 
 import android.os.Process;
@@ -35,13 +43,16 @@
 import javax.crypto.KeyGenerator;
 import javax.security.auth.x500.X500Principal;
 
-public class KeyGenParameterSpecTest extends TestCase {
+import org.junit.Test;
+
+public class KeyGenParameterSpecTest {
 
     private static final X500Principal DEFAULT_CERT_SUBJECT = new X500Principal("CN=fake");
     private static final BigInteger DEFAULT_CERT_SERIAL_NUMBER = new BigInteger("1");
     private static final Date DEFAULT_CERT_NOT_BEFORE = new Date(0L); // Jan 1 1970
     private static final Date DEFAULT_CERT_NOT_AFTER = new Date(2461449600000L); // Jan 1 2048
 
+    @Test
     public void testDefaults() {
         // Set only the mandatory parameters and assert values returned by getters.
 
@@ -76,6 +87,7 @@
         assertEquals(KeyProperties.UNRESTRICTED_USAGE_COUNT, spec.getMaxUsageCount());
     }
 
+    @Test
     public void testSettersReflectedInGetters() {
         // Set all parameters to non-default values and then assert that getters reflect that.
 
@@ -142,6 +154,7 @@
         assertEquals(maxUsageCount, spec.getMaxUsageCount());
     }
 
+    @Test
     public void testNullAliasNotPermitted() {
         try {
             new KeyGenParameterSpec.Builder(null, KeyProperties.PURPOSE_ENCRYPT);
@@ -149,6 +162,7 @@
         } catch (NullPointerException expected) {}
     }
 
+    @Test
     public void testEmptyAliasNotPermitted() {
         try {
             new KeyGenParameterSpec.Builder("", KeyProperties.PURPOSE_ENCRYPT);
@@ -156,6 +170,7 @@
         } catch (IllegalArgumentException expected) {}
     }
 
+    @Test
     public void testSetKeyValidityEndDateAppliesToBothEndDates() {
         Date date = new Date(System.currentTimeMillis() + 555555);
         KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
@@ -166,6 +181,7 @@
         assertEquals(date, spec.getKeyValidityForConsumptionEnd());
     }
 
+    @Test
     public void testSetUserAuthenticationValidityDurationSecondsValidityCheck() {
         KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder("alias", 0);
         try {
@@ -194,6 +210,7 @@
         } catch (IllegalArgumentException expected) {}
     }
 
+    @Test
     public void testImmutabilityViaSetterParams() {
         // Assert that all mutable parameters provided to setters are copied to ensure that values
         // returned by getters never change.
@@ -279,6 +296,7 @@
                 Arrays.asList(spec.getSignaturePaddings()));
     }
 
+    @Test
     public void testImmutabilityViaGetterReturnValues() {
         // Assert that none of the mutable return values from getters modify the state of the spec.
 
@@ -346,6 +364,7 @@
      * Test that generating a key with UID throws an exception since CTS doesn't have the necessary
      * permissions.
      */
+    @Test
     public void testBuilderSetUidGenerateKeyThrowsException() throws Exception {
         KeyGenerator keyGenerator = KeyGenerator.getInstance(
                 KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
@@ -356,6 +375,7 @@
         assertThrows(ProviderException.class, keyGenerator::generateKey);
     }
 
+    @Test
     public void testIllegalMaxUsageCountNotPermitted() {
         try {
             new KeyGenParameterSpec.Builder("LimitedUseKey", KeyProperties.PURPOSE_ENCRYPT)
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
index e213cde..bc99b75 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
@@ -16,13 +16,21 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
 import android.security.keystore.KeyProperties;
-import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
 import com.google.common.collect.ObjectArrays;
 
 import junit.framework.TestCase;
@@ -47,8 +55,11 @@
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class KeyGeneratorTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class KeyGeneratorTest {
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_PROVIDER_NAME;
 
     static String[] EXPECTED_ALGORITHMS = {
@@ -87,6 +98,11 @@
     static final int[] AES_STRONGBOX_SUPPORTED_KEY_SIZES = new int[] {128, 256};
     static final int[] DES_SUPPORTED_KEY_SIZES = new int[] {168};
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected KeyGenerator
         // algorithms. We don't care whether the algorithms are exposed via aliases, as long as
@@ -110,6 +126,7 @@
                 expectedAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testGenerateWithoutInitThrowsIllegalStateException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -124,6 +141,7 @@
         }
     }
 
+    @Test
     public void testInitWithKeySizeThrowsUnsupportedOperationException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -139,6 +157,7 @@
         }
     }
 
+    @Test
     public void testInitWithKeySizeAndSecureRandomThrowsUnsupportedOperationException()
             throws Exception {
         SecureRandom rng = new SecureRandom();
@@ -156,6 +175,7 @@
         }
     }
 
+    @Test
     public void testInitWithNullAlgParamsThrowsInvalidAlgorithmParameterException()
             throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
@@ -171,6 +191,7 @@
         }
     }
 
+    @Test
     public void testInitWithNullAlgParamsAndSecureRandomThrowsInvalidAlgorithmParameterException()
             throws Exception {
         SecureRandom rng = new SecureRandom();
@@ -187,6 +208,7 @@
         }
     }
 
+    @Test
     public void testInitWithAlgParamsAndNullSecureRandom()
             throws Exception {
         testInitWithAlgParamsAndNullSecureRandomHelper(false /* useStrongbox */);
@@ -214,6 +236,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnsupportedAlgParamsTypeThrowsInvalidAlgorithmParameterException()
             throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
@@ -229,6 +252,7 @@
         }
     }
 
+    @Test
     public void testDefaultKeySize() throws Exception {
         testDefaultKeySize(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -251,6 +275,7 @@
         }
     }
 
+    @Test
     public void testAesKeySupportedSizes() throws Exception {
         testAesKeySupportedSizesHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -302,6 +327,7 @@
     }
 
     // TODO: This test will fail until b/117509689 is resolved.
+    @Test
     public void testDESKeySupportedSizes() throws Exception {
         if (!TestUtils.supports3DES()) {
             return;
@@ -342,6 +368,7 @@
         }
     }
 
+    @Test
     public void testHmacKeySupportedSizes() throws Exception {
         testHmacKeySupportedSizesHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -406,6 +433,7 @@
         }
     }
 
+    @Test
     public void testHmacKeyOnlyOneDigestCanBeAuthorized() throws Exception {
         testHmacKeyOnlyOneDigestCanBeAuthorizedHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -480,6 +508,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownBlockModeFails() {
         testInitWithUnknownBlockModeFailsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -487,7 +516,7 @@
         }
     }
 
-    public void testInitWithUnknownBlockModeFailsHelper(boolean useStrongbox) {
+    private void testInitWithUnknownBlockModeFailsHelper(boolean useStrongbox) {
         for (String algorithm :
             useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
@@ -506,6 +535,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownEncryptionPaddingFails() {
         testInitWithUnknownEncryptionPaddingFailsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -532,6 +562,7 @@
         }
     }
 
+    @Test
     public void testInitWithSignaturePaddingFails() {
         testInitWithSignaturePaddingFailsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -557,6 +588,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownDigestFails() {
         testInitWithUnknownDigestFailsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -564,7 +596,7 @@
         }
     }
 
-    public void testInitWithUnknownDigestFailsHelper(boolean useStrongbox) {
+    private void testInitWithUnknownDigestFailsHelper(boolean useStrongbox) {
         for (String algorithm :
             useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
@@ -591,6 +623,7 @@
         }
     }
 
+    @Test
     public void testInitWithKeyAlgorithmDigestMissingFromAuthorizedDigestFails() {
         testInitWithKeyAlgorithmDigestMissingFromAuthorizedDigestFailsHelper(
             false /* useStrongbox */);
@@ -637,6 +670,7 @@
         }
     }
 
+    @Test
     public void testInitRandomizedEncryptionRequiredButViolatedFails() throws Exception {
         testInitRandomizedEncryptionRequiredButViolatedFailsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -644,7 +678,7 @@
         }
     }
 
-    public void testInitRandomizedEncryptionRequiredButViolatedFailsHelper(boolean useStrongbox)
+    private void testInitRandomizedEncryptionRequiredButViolatedFailsHelper(boolean useStrongbox)
         throws Exception {
         for (String algorithm :
             useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
@@ -664,6 +698,7 @@
         }
     }
 
+    @Test
     public void testGenerateHonorsRequestedAuthorizations() throws Exception {
         testGenerateHonorsRequestedAuthorizationsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -731,6 +766,7 @@
         }
     }
 
+    @Test
     public void testLimitedUseKey() throws Exception {
         testLimitedUseKey(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java
index d14f6d2..704d1957 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java
@@ -16,10 +16,14 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
 import android.security.keystore.KeyProperties;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import junit.framework.TestCase;
 
 import java.security.KeyFactory;
@@ -32,8 +36,13 @@
 import java.util.Arrays;
 import java.util.Date;
 
-public class KeyInfoTest extends TestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
+@RunWith(AndroidJUnit4.class)
+public class KeyInfoTest {
+
+    @Test
     public void testImmutabilityViaGetterReturnValues() throws Exception {
         // Assert that none of the mutable return values from getters modify the state of the
         // instance.
@@ -103,6 +112,7 @@
         assertEquals(KeyProperties.UNRESTRICTED_USAGE_COUNT, remainingUsageCount);
     }
 
+    @Test
     public void testLimitedUseKey() throws Exception {
         Date keyValidityStartDate = new Date(System.currentTimeMillis() - 2222222);
         Date keyValidityEndDateForOrigination = new Date(System.currentTimeMillis() + 11111111);
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java
index 6004432..96e3bca 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java
@@ -16,15 +16,26 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.security.KeyPairGeneratorSpec;
-import android.test.AndroidTestCase;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import java.math.BigInteger;
 import java.util.Date;
 
 import javax.security.auth.x500.X500Principal;
 
-public class KeyPairGeneratorSpecTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class KeyPairGeneratorSpecTest {
     private static final String TEST_ALIAS_1 = "test1";
 
     private static final X500Principal TEST_DN_1 = new X500Principal("CN=test1");
@@ -39,6 +50,11 @@
     @SuppressWarnings("deprecation")
     private static final Date NOW_PLUS_10_YEARS = new Date(NOW.getYear() + 10, 0, 1);
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testBuilder_Unencrypted_Success() throws Exception {
         KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext())
                 .setAlias(TEST_ALIAS_1)
@@ -61,6 +77,7 @@
         assertFalse("encryption flag should not be on", spec.isEncryptionRequired());
     }
 
+    @Test
     public void testBuilder_NullContext_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(null);
@@ -69,6 +86,7 @@
         }
     }
 
+    @Test
     public void testBuilder_MissingAlias_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(getContext())
@@ -82,6 +100,7 @@
         }
     }
 
+    @Test
     public void testBuilder_MissingSubjectDN_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(getContext())
@@ -95,6 +114,7 @@
         }
     }
 
+    @Test
     public void testBuilder_MissingSerialNumber_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(getContext())
@@ -108,6 +128,7 @@
         }
     }
 
+    @Test
     public void testBuilder_MissingStartDate_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(getContext())
@@ -121,6 +142,7 @@
         }
     }
 
+    @Test
     public void testBuilder_MissingEndDate_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(getContext())
@@ -134,6 +156,7 @@
         }
     }
 
+    @Test
     public void testBuilder_EndBeforeStart_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(getContext())
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
index acf0d48..e931f3e5 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
@@ -16,14 +16,22 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
 import android.keystore.cts.util.TestUtils;
 import android.security.KeyPairGeneratorSpec;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
 import android.security.keystore.KeyProperties;
-import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 import android.util.Log;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.util.HexDump;
 
@@ -80,7 +88,12 @@
 import libcore.javax.net.ssl.TestKeyManager;
 import libcore.javax.net.ssl.TestSSLContext;
 
-public class KeyPairGeneratorTest extends AndroidTestCase {
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class KeyPairGeneratorTest {
     private KeyStore mKeyStore;
 
     private CountingSecureRandom mRng;
@@ -128,14 +141,18 @@
         DEFAULT_KEY_SIZES.put("RSA", 2048);
     }
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Before
+    public void setUp() throws Exception {
         mRng = new CountingSecureRandom();
         mKeyStore = KeyStore.getInstance("AndroidKeyStore");
         mKeyStore.load(null, null);
     }
 
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected KeyPairGenerator
         // algorithms. We don't care whether the algorithms are exposed via aliases, as long as
@@ -159,6 +176,7 @@
                 expectedAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testInitialize_LegacySpec() throws Exception {
         @SuppressWarnings("deprecation")
         KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext())
@@ -175,6 +193,7 @@
         getEcGenerator().initialize(spec, new SecureRandom());
     }
 
+    @Test
     public void testInitialize_ModernSpec() throws Exception {
         KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
@@ -187,6 +206,7 @@
         getEcGenerator().initialize(spec, new SecureRandom());
     }
 
+    @Test
     public void testInitialize_KeySizeOnly() throws Exception {
         try {
             getRsaGenerator().initialize(1024);
@@ -201,6 +221,7 @@
         }
     }
 
+    @Test
     public void testInitialize_KeySizeAndSecureRandomOnly()
             throws Exception {
         try {
@@ -216,6 +237,7 @@
         }
     }
 
+    @Test
     public void testDefaultKeySize() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -231,6 +253,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownBlockModeFails() {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -245,6 +268,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownEncryptionPaddingFails() {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -259,6 +283,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownSignaturePaddingFails() {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -273,6 +298,7 @@
         }
     }
 
+    @Test
     public void testInitWithUnknownDigestFails() {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -287,6 +313,7 @@
         }
     }
 
+    @Test
     public void testInitRandomizedEncryptionRequiredButViolatedFails() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -304,6 +331,7 @@
         }
     }
 
+    @Test
     public void testGenerateHonorsRequestedAuthorizations() throws Exception {
         testGenerateHonorsRequestedAuthorizationsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -374,6 +402,7 @@
     }
 
     @SuppressWarnings("deprecation")
+    @Test
     public void testGenerate_EC_LegacySpec() throws Exception {
         // There are three legacy ways to generate an EC key pair using Android Keystore
         // KeyPairGenerator:
@@ -523,6 +552,7 @@
         MoreAsserts.assertEmpty(Arrays.asList(keyInfo.getEncryptionPaddings()));
     }
 
+    @Test
     public void testGenerate_RSA_LegacySpec() throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         generator.initialize(new KeyPairGeneratorSpec.Builder(getContext())
@@ -577,6 +607,7 @@
                 KeyProperties.SIGNATURE_PADDING_RSA_PKCS1);
     }
 
+    @Test
     public void testGenerate_ReplacesOldEntryWithSameAlias() throws Exception {
         replacesOldEntryWithSameAliasHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -642,6 +673,7 @@
         }
     }
 
+    @Test
     public void testGenerate_DoesNotReplaceOtherEntries() throws Exception {
         doesNotReplaceOtherEntriesHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -715,6 +747,7 @@
                 NOW_PLUS_10_YEARS);
     }
 
+    @Test
     public void testGenerate_EC_Different_Keys() throws Exception {
         testGenerate_EC_Different_KeysHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -744,6 +777,7 @@
         }
     }
 
+    @Test
     public void testGenerate_RSA_Different_Keys() throws Exception {
         testGenerate_RSA_Different_KeysHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -773,6 +807,7 @@
         }
     }
 
+    @Test
     public void testGenerate_EC_ModernSpec_Defaults() throws Exception {
         testGenerate_EC_ModernSpec_DefaultsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -816,6 +851,7 @@
         MoreAsserts.assertEmpty(Arrays.asList(keyInfo.getEncryptionPaddings()));
     }
 
+    @Test
     public void testGenerate_RSA_ModernSpec_Defaults() throws Exception {
         testGenerate_RSA_ModernSpec_DefaultsHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -860,6 +896,7 @@
         MoreAsserts.assertEmpty(Arrays.asList(keyInfo.getEncryptionPaddings()));
     }
 
+    @Test
     public void testGenerate_EC_ModernSpec_AsCustomAsPossible() throws Exception {
         KeyPairGenerator generator = getEcGenerator();
         Date keyValidityStart = new Date(System.currentTimeMillis());
@@ -926,6 +963,7 @@
     // This is a reworking of the generic test to still be as custom as possible while
     // respecting the spec constraints.
     // Test fails until the resolution of b/113276806
+    @Test
     public void testGenerate_EC_ModernSpec_AsCustomAsPossibleStrongbox() throws Exception {
         if (!TestUtils.hasStrongBox(getContext())) {
             return;
@@ -992,6 +1030,7 @@
         assertEquals(0, keyInfo.getUserAuthenticationValidityDurationSeconds());
     }
 
+    @Test
     public void testGenerate_RSA_ModernSpec_AsCustomAsPossible() throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         Date keyValidityStart = new Date(System.currentTimeMillis());
@@ -1077,6 +1116,7 @@
     // This is a reworking of the generic test to still be as custom as possible while
     // respecting the spec constraints.
     // Test fails until the resolution of b/113276806
+    @Test
     public void testGenerate_RSA_ModernSpec_AsCustomAsPossibleStrongbox() throws Exception {
         if (!TestUtils.hasStrongBox(getContext())) {
             return;
@@ -1162,6 +1202,7 @@
         assertEquals(0, keyInfo.getUserAuthenticationValidityDurationSeconds());
     }
 
+    @Test
     public void testGenerate_EC_ModernSpec_UsableForTLSPeerAuth() throws Exception {
         testGenerate_EC_ModernSpec_UsableForTLSPeerAuthHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -1197,6 +1238,7 @@
         assertKeyPairAndCertificateUsableForTLSPeerAuthentication(TEST_ALIAS_1);
     }
 
+    @Test
     public void testGenerate_RSA_ModernSpec_UsableForTLSPeerAuth() throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
@@ -1241,6 +1283,7 @@
     // currently be tested here because CTS does not require that secure lock screen is set up and
     // that at least one fingerprint is enrolled.
 
+    @Test
     public void testGenerate_EC_ModernSpec_KeyNotYetValid() throws Exception {
         testGenerate_EC_ModernSpec_KeyNotYetValidHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -1273,6 +1316,7 @@
         assertEquals(validityStart, keyInfo.getKeyValidityStart());
     }
 
+    @Test
     public void testGenerate_RSA_ModernSpec_KeyExpiredForOrigination() throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         Date originationEnd = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
@@ -1298,6 +1342,7 @@
         assertEquals(originationEnd, keyInfo.getKeyValidityForOriginationEnd());
     }
 
+    @Test
     public void testGenerate_EC_ModernSpec_SupportedSizes() throws Exception {
         assertKeyGenUsingECSizeOnlyUsesCorrectCurve(224, ECCurves.NIST_P_224_SPEC);
         assertKeyGenUsingECSizeOnlyUsesCorrectCurve(256, ECCurves.NIST_P_256_SPEC);
@@ -1309,6 +1354,7 @@
     }
 
     //TODO: Fix b/113108008 so this test will pass for strongbox.
+    @Test
     public void testGenerate_EC_ModernSpec_UnsupportedSizesRejected() throws Exception {
         for (int keySizeBits = 0; keySizeBits <= 1024; keySizeBits++) {
             testGenerate_EC_ModernSpec_UnsupportedSizesRejectedHelper(false, keySizeBits);
@@ -1347,6 +1393,7 @@
         }
     }
 
+    @Test
     public void testGenerate_EC_ModernSpec_SupportedNamedCurves() throws Exception {
         assertKeyGenUsingECNamedCurveSupported("P-224", ECCurves.NIST_P_224_SPEC);
         assertKeyGenUsingECNamedCurveSupported("p-224", ECCurves.NIST_P_224_SPEC);
@@ -1380,6 +1427,7 @@
         assertKeyGenUsingECNamedCurveSupported("SECP521R1", ECCurves.NIST_P_521_SPEC);
     }
 
+    @Test
     public void testGenerate_RSA_ModernSpec_SupportedSizes() throws Exception {
         assertKeyGenUsingRSASizeOnlySupported(512);
         assertKeyGenUsingRSASizeOnlySupported(768);
@@ -1397,6 +1445,7 @@
                 2048, RSAKeyGenParameterSpec.F0));
     }
 
+    @Test
     public void testGenerate_RSA_IndCpaEnforced() throws Exception {
         testGenerate_RSA_IndCpaEnforcedHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -1436,6 +1485,7 @@
                         .build());
     }
 
+    @Test
     public void testGenerate_EC_IndCpaEnforced() throws Exception {
         testGenerate_EC_IndCpaEnforcedHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
@@ -1468,6 +1518,7 @@
     }
 
     // http://b/28384942
+    @Test
     public void testGenerateWithFarsiLocale() throws Exception {
         testGenerateWithFarsiLocaleHelper(false /* useStrongbox */);
         if (TestUtils.hasStrongBox(getContext())) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java
index 22c5a17..44996c4 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java
@@ -16,18 +16,31 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.security.GateKeeper;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
 import android.test.MoreAsserts;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import junit.framework.TestCase;
 
 import java.util.Arrays;
 import java.util.Date;
 
-public class KeyProtectionTest extends TestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class KeyProtectionTest {
+    @Test
     public void testDefaults() {
         // Set only the mandatory parameters and assert values returned by getters.
 
@@ -56,6 +69,7 @@
         assertEquals(spec.isStrongBoxBacked(), false);
     }
 
+    @Test
     public void testSettersReflectedInGetters() {
         // Set all parameters to non-default values and then assert that getters reflect that.
 
@@ -110,6 +124,7 @@
         assertEquals(spec.isStrongBoxBacked(), true);
     }
 
+    @Test
     public void testSetKeyValidityEndDateAppliesToBothEndDates() {
         Date date = new Date(System.currentTimeMillis() + 555555);
         KeyProtection spec = new KeyProtection.Builder(
@@ -120,6 +135,7 @@
         assertEquals(date, spec.getKeyValidityForConsumptionEnd());
     }
 
+    @Test
     public void testSetUserAuthenticationValidityDurationSecondsValidityCheck() {
         KeyProtection.Builder builder = new KeyProtection.Builder(0);
         try {
@@ -148,6 +164,7 @@
         } catch (IllegalArgumentException expected) {}
     }
 
+    @Test
     public void testImmutabilityViaSetterParams() {
         // Assert that all mutable parameters provided to setters are copied to ensure that values
         // returned by getters never change.
@@ -219,6 +236,7 @@
                 Arrays.asList(spec.getSignaturePaddings()));
     }
 
+    @Test
     public void testImmutabilityViaGetterReturnValues() {
         // Assert that none of the mutable return values from getters modify the state of the spec.
 
@@ -272,6 +290,7 @@
                 Arrays.asList(spec.getSignaturePaddings()));
     }
 
+    @Test
     public void testIllegalMaxUsageCountNotPermitted() {
         try {
             new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT).setMaxUsageCount(0);
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java
index 383e483..0186cff 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java
@@ -16,6 +16,14 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -59,7 +67,9 @@
 import libcore.java.security.StandardNames;
 import libcore.java.security.TestKeyStore;
 
-public class KeyStoreTest extends TestCase {
+import org.junit.Test;
+
+public class KeyStoreTest {
 
     private static final HashMap<String, PrivateKeyEntry> sPrivateKeys
             = new HashMap<String, PrivateKeyEntry>();
@@ -439,6 +449,7 @@
                      Arrays.asList(actual));
     }
 
+    @Test
     public void test_KeyStore_create() throws Exception {
         Provider[] providers = Security.getProviders();
         for (Provider provider : providers) {
@@ -456,6 +467,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getInstance() throws Exception {
         String type = KeyStore.getDefaultType();
         try {
@@ -507,6 +519,7 @@
         assertNotNull(KeyStore.getInstance(type, provider));
     }
 
+    @Test
     public void test_KeyStore_getDefaultType() throws Exception {
         String type = KeyStore.getDefaultType();
         assertNotNull(type);
@@ -515,6 +528,7 @@
         assertEquals(type, ks.getType());
     }
 
+    @Test
     public void test_KeyStore_getProvider() throws Exception {
         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
         assertNotNull(ks.getProvider());
@@ -525,6 +539,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getType() throws Exception {
         String type = KeyStore.getDefaultType();
         KeyStore ks = KeyStore.getInstance(type);
@@ -536,6 +551,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getKey() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -661,6 +677,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getCertificateChain() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -702,6 +719,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getCertificate() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -743,6 +761,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getCreationDate() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -791,6 +810,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_setKeyEntry_Key() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1000,6 +1020,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_setKeyEntry_array() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1154,6 +1175,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_setCertificateEntry() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1265,6 +1287,7 @@
             }
         }
     }
+    @Test
     public void test_KeyStore_deleteEntry() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1377,6 +1400,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_aliases() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1430,6 +1454,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_containsAlias() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1477,6 +1502,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_size() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1527,6 +1553,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_isKeyEntry() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1573,6 +1600,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_isCertificateEntry() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1622,6 +1650,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getCertificateAlias() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1695,6 +1724,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_store_OutputStream() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1790,6 +1820,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_store_LoadStoreParameter() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1813,6 +1844,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_load_InputStream() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             keyStore.load(null, null);
@@ -1846,6 +1878,7 @@
         // test_KeyStore_store_OutputStream effectively tests load as well as store
     }
 
+    @Test
     public void test_KeyStore_load_LoadStoreParameter() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             keyStore.load(null);
@@ -1873,6 +1906,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_getEntry() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -1997,6 +2031,7 @@
     public static class FakeProtectionParameter implements ProtectionParameter {
     }
 
+    @Test
     public void test_KeyStore_setEntry() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             keyStore.load(null, null);
@@ -2282,6 +2317,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_entryInstanceOf() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             try {
@@ -2384,6 +2420,7 @@
     }
 
     // TODO(27810271): investigate why this is taking too long for armeabi-v7a
+    @Test
     public void test_KeyStore_Builder() throws Exception {
         for (KeyStore keyStore : keyStores()) {
             keyStore.load(null, null);
@@ -2490,6 +2527,7 @@
         }
     }
 
+    @Test
     public void test_KeyStore_cacerts() throws Exception {
         if (StandardNames.IS_RI) {
             return;
@@ -2528,6 +2566,7 @@
     }
 
     // http://b/857840: want JKS key store
+    @Test
     public void testDefaultKeystore() {
         String type = KeyStore.getDefaultType();
         assertEquals(StandardNames.KEY_STORE_ALGORITHM, type);
diff --git a/tests/tests/keystore/src/android/keystore/cts/MacTest.java b/tests/tests/keystore/src/android/keystore/cts/MacTest.java
index 0ad28b9..3e0699d 100644
--- a/tests/tests/keystore/src/android/keystore/cts/MacTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/MacTest.java
@@ -16,10 +16,16 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
+
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import junit.framework.TestCase;
 
 import java.security.InvalidKeyException;
@@ -39,10 +45,15 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 /**
  * Tests for algorithm-agnostic functionality of MAC implementations backed by Android Keystore.
  */
-public class MacTest extends TestCase {
+ @RunWith(AndroidJUnit4.class)
+public class MacTest {
 
     /**
      * Override to test Strongbox.
@@ -74,13 +85,11 @@
         }
     }
 
-    @Override
-    protected void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         if (isStrongbox()) {
             TestUtils.assumeStrongBox();
         }
-
-        super.setUp();
     }
 
     private static final byte[] KAT_KEY = HexEncoding.decode(
@@ -212,6 +221,7 @@
 
     private static final long DAY_IN_MILLIS = TestUtils.DAY_IN_MILLIS;
 
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected MAC algorithms. We
         // don't care whether the algorithms are exposed via aliases, as long as the canonical names
@@ -241,6 +251,7 @@
                 expectedAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testAndroidKeyStoreKeysHandledByAndroidKeyStoreProvider() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -258,6 +269,7 @@
         }
     }
 
+    @Test
     public void testMacGeneratedForEmptyMessage() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -279,6 +291,7 @@
         }
     }
 
+    @Test
     public void testMacGeneratedByAndroidKeyStoreVerifiesByAndroidKeyStore() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -299,6 +312,7 @@
         }
     }
 
+    @Test
     public void testMacGeneratedByAndroidKeyStoreVerifiesByHighestPriorityProvider()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -321,6 +335,7 @@
         }
     }
 
+    @Test
     public void testMacGeneratedByHighestPriorityProviderVerifiesByAndroidKeyStore()
             throws Exception {
         Provider keystoreProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -347,6 +362,7 @@
         }
     }
 
+    @Test
     public void testSmallMsgKat() throws Exception {
         byte[] message = SHORT_MSG_KAT_MESSAGE;
 
@@ -382,6 +398,7 @@
         }
     }
 
+    @Test
     public void testLargeMsgKat() throws Exception {
         byte[] message = TestUtils.generateLargeKatMsg(LONG_MSG_KAT_SEED, LONG_MSG_KAT_SIZE_BYTES);
 
@@ -402,6 +419,7 @@
         }
     }
 
+    @Test
     public void testInitFailsWhenNotAuthorizedToSign() throws Exception {
         int badPurposes = KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
                 | KeyProperties.PURPOSE_VERIFY;
@@ -418,6 +436,7 @@
         }
     }
 
+    @Test
     public void testInitFailsWhenDigestNotAuthorized() throws Exception {
         // TEE algorithms are used here even if Strongbox is tested because
         // the outer loop iterates through algorithms that are not to be supported
@@ -442,6 +461,7 @@
         }
     }
 
+    @Test
     public void testInitFailsWhenKeyNotYetValid() throws Exception {
         for (String algorithm : expectedAlgorithms()) {
             try {
@@ -459,6 +479,7 @@
         }
     }
 
+    @Test
     public void testInitFailsWhenKeyNoLongerValidForOrigination() throws Exception {
         for (String algorithm : expectedAlgorithms()) {
             try {
@@ -479,6 +500,7 @@
         }
     }
 
+    @Test
     public void testInitIgnoresThatKeyNoLongerValidForConsumption() throws Exception {
         for (String algorithm : expectedAlgorithms()) {
             try {
diff --git a/tests/tests/keystore/src/android/keystore/cts/NoAttestKeyTest.java b/tests/tests/keystore/src/android/keystore/cts/NoAttestKeyTest.java
new file mode 100644
index 0000000..77535a0
--- /dev/null
+++ b/tests/tests/keystore/src/android/keystore/cts/NoAttestKeyTest.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2021 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.keystore.cts;
+
+import static android.security.keystore.KeyProperties.KEY_ALGORITHM_EC;
+import static android.security.keystore.KeyProperties.PURPOSE_ATTEST_KEY;
+import static android.security.keystore.KeyProperties.PURPOSE_SIGN;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeFalse;
+
+import android.content.pm.PackageManager;
+import android.security.keystore.KeyGenParameterSpec;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+
+public class NoAttestKeyTest {
+    private KeyStore mKeyStore;
+    private ArrayList<String> mAliasesToDelete = new ArrayList();
+
+    @Before
+    public void setUp() throws Exception {
+        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
+        mKeyStore.load(null);
+
+        // Assume no attest key support for all tests in this class.
+        assumeNoAttestKey();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        for (String alias : mAliasesToDelete) {
+            try {
+                mKeyStore.deleteEntry(alias);
+            } catch (Throwable t) {
+                // Ignore any exception and delete the other aliases in the list.
+            }
+        }
+    }
+
+    @Test
+    public void testEcAttestKeyFail() throws Exception {
+        final String attestKeyAlias = "attestKey";
+        final String attestedKeyAlias = "attestedKey";
+
+        // The device does not have the attest key feature, so attempting to create and use a
+        // key with ATTEST_KEY purpose should fail.
+        try {
+            Certificate attestKeyCertChain[] = generateKeyPair(KEY_ALGORITHM_EC,
+                    new KeyGenParameterSpec.Builder(attestKeyAlias, PURPOSE_ATTEST_KEY)
+                            .setAttestationChallenge("challenge".getBytes())
+                            .build());
+            Certificate attestedKeyCertChain[] = generateKeyPair(KEY_ALGORITHM_EC,
+                    new KeyGenParameterSpec.Builder(attestedKeyAlias, PURPOSE_SIGN)
+                            .setAttestationChallenge("challenge".getBytes())
+                            .setAttestKeyAlias(attestKeyAlias)
+                            .build());
+            fail("Expected exception.");
+        } catch (InvalidAlgorithmParameterException e) {
+            // ATTEST_KEY generation/use has failed as expected
+        }
+    }
+
+    private Certificate[] generateKeyPair(String algorithm, KeyGenParameterSpec spec)
+            throws NoSuchAlgorithmException, NoSuchProviderException,
+            InvalidAlgorithmParameterException, KeyStoreException {
+        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm,
+                "AndroidKeyStore");
+        keyPairGenerator.initialize(spec);
+        keyPairGenerator.generateKeyPair();
+        mAliasesToDelete.add(spec.getKeystoreAlias());
+
+        return mKeyStore.getCertificateChain(spec.getKeystoreAlias());
+    }
+
+    private void assumeNoAttestKey() {
+        PackageManager packageManager =
+                InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager();
+        assumeFalse("Can only test if we do *not* have the attest key feature.",
+                packageManager.hasSystemFeature(PackageManager.FEATURE_KEYSTORE_APP_ATTEST_KEY));
+    }
+
+}
diff --git a/tests/tests/keystore/src/android/keystore/cts/PutOverflowTest.java b/tests/tests/keystore/src/android/keystore/cts/PutOverflowTest.java
index 088af35..2b3bd81 100644
--- a/tests/tests/keystore/src/android/keystore/cts/PutOverflowTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/PutOverflowTest.java
@@ -16,10 +16,18 @@
 
 package android.keystore.cts;
 
-import android.test.AndroidTestCase;
+import static org.junit.Assert.assertTrue;
+
+import androidx.test.runner.AndroidJUnit4;
+
 import java.lang.reflect.Method;
 
-public class PutOverflowTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class PutOverflowTest {
+    @Test
     public void testCrash() throws Exception {
         try {
             Class<?> keystoreClass = Class.forName("android.security.KeyStore");
diff --git a/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java b/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
index 8a20cb7..92590c6 100644
--- a/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
@@ -16,6 +16,13 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
+
 import java.math.BigInteger;
 import java.security.PrivateKey;
 import java.security.Provider;
@@ -31,13 +38,23 @@
 import android.keystore.cts.util.ImportedKey;
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
-import android.test.AndroidTestCase;
-import android.test.MoreAsserts;
 
-public class RSACipherTest extends AndroidTestCase {
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class RSACipherTest {
 
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_CRYPTO_OP_PROVIDER_NAME;
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testNoPaddingEncryptionAndDecryptionSucceedsWithInputShorterThanModulus()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -61,16 +78,17 @@
 
                 Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", provider);
                 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
-                MoreAsserts.assertEquals(expectedOutput, cipher.doFinal(input));
+                assertArrayEquals(expectedOutput, cipher.doFinal(input));
 
                 cipher.init(Cipher.DECRYPT_MODE, privateKey);
-                MoreAsserts.assertEquals(expectedOutput, cipher.doFinal(input));
+                assertArrayEquals(expectedOutput, cipher.doFinal(input));
             } catch (Throwable e) {
                 throw new RuntimeException("Failed for key " + key.getAlias(), e);
             }
         }
     }
 
+    @Test
     public void testNoPaddingEncryptionSucceedsWithPlaintextOneSmallerThanModulus()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -93,13 +111,14 @@
                 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                 byte[] ciphertext = cipher.doFinal(plaintext);
                 cipher.init(Cipher.DECRYPT_MODE, privateKey);
-                MoreAsserts.assertEquals(plaintext, cipher.doFinal(ciphertext));
+                assertArrayEquals(plaintext, cipher.doFinal(ciphertext));
             } catch (Throwable e) {
                 throw new RuntimeException("Failed for key " + key.getAlias(), e);
             }
         }
     }
 
+    @Test
     public void testNoPaddingEncryptionFailsWithPlaintextEqualToModulus() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -128,6 +147,7 @@
         }
     }
 
+    @Test
     public void testNoPaddingEncryptionFailsWithPlaintextOneLargerThanModulus() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -157,6 +177,7 @@
         }
     }
 
+    @Test
     public void testNoPaddingEncryptionFailsWithPlaintextOneByteLongerThanModulus()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -189,6 +210,7 @@
         }
     }
 
+    @Test
     public void testNoPaddingDecryptionFailsWithCiphertextOneByteLongerThanModulus()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -221,6 +243,7 @@
         }
     }
 
+    @Test
     public void testNoPaddingWithZeroMessage() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -240,12 +263,12 @@
                 byte[] ciphertext = cipher.doFinal(plaintext);
                 // Ciphertext should be all zero bytes
                 byte[] expectedCiphertext = new byte[(TestUtils.getKeySizeBits(publicKey) + 7) / 8];
-                MoreAsserts.assertEquals(expectedCiphertext, ciphertext);
+                assertArrayEquals(expectedCiphertext, ciphertext);
 
                 cipher.init(Cipher.DECRYPT_MODE, privateKey);
                 // Decrypted plaintext should also be all zero bytes
                 byte[] expectedPlaintext = new byte[expectedCiphertext.length];
-                MoreAsserts.assertEquals(expectedPlaintext, cipher.doFinal(ciphertext));
+                assertArrayEquals(expectedPlaintext, cipher.doFinal(ciphertext));
             } catch (Throwable e) {
                 throw new RuntimeException("Failed for key " + key.getAlias(), e);
             }
diff --git a/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java b/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java
index bf03f28..c145e88 100644
--- a/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java
@@ -14,6 +14,11 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import java.security.InvalidKeyException;
 import java.security.KeyPair;
 import java.security.PrivateKey;
@@ -28,16 +33,20 @@
 import java.util.Collection;
 import java.util.List;
 
-import android.keystore.cts.R;
-
 import android.content.Context;
+import android.keystore.cts.R;
 import android.keystore.cts.util.ImportedKey;
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
-import android.test.AndroidTestCase;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
-public class RSASignatureTest extends AndroidTestCase {
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class RSASignatureTest {
 
     private static final String EXPECTED_PROVIDER_NAME = SignatureTest.EXPECTED_PROVIDER_NAME;
 
@@ -54,6 +63,11 @@
         SIGNATURE_ALGORITHMS = sigAlgs.toArray(new String[sigAlgs.size()]);
     }
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testMaxMessageSizeWhenNoDigestUsed() throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
@@ -104,6 +118,7 @@
         }
     }
 
+    @Test
     public void testSmallKeyRejected() throws Exception {
         // Use a 512 bit key which should prevent the use of any digests larger than SHA-256
         // because the padded form of the digested message will be larger than modulus size.
diff --git a/tests/tests/keystore/src/android/keystore/cts/SecretKeyFactoryTest.java b/tests/tests/keystore/src/android/keystore/cts/SecretKeyFactoryTest.java
index ae50228..f9d97b1 100644
--- a/tests/tests/keystore/src/android/keystore/cts/SecretKeyFactoryTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/SecretKeyFactoryTest.java
@@ -16,6 +16,11 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
+
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
@@ -44,7 +49,9 @@
 import javax.crypto.SecretKeyFactory;
 import javax.crypto.spec.SecretKeySpec;
 
-public class SecretKeyFactoryTest extends TestCase {
+import org.junit.Test;
+
+public class SecretKeyFactoryTest {
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_PROVIDER_NAME;
 
     private static String[] EXPECTED_ALGORITHMS = {
@@ -62,6 +69,7 @@
         }
     }
 
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected SecretKeyFactory
         // algorithms. We don't care whether the algorithms are exposed via aliases, as long as
@@ -85,6 +93,7 @@
                 expectedAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testGetKeySpecWithKeystoreKeyAndKeyInfoReflectsAllAuthorizations()
             throws Exception {
         Date keyValidityStart = new Date(System.currentTimeMillis() - TestUtils.DAY_IN_MILLIS);
@@ -143,6 +152,7 @@
         }
     }
 
+    @Test
     public void testTranslateKeyWithNullKeyThrowsInvalidKeyException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -157,6 +167,7 @@
         }
     }
 
+    @Test
     public void testTranslateKeyRejectsNonAndroidKeystoreKeys() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -172,6 +183,7 @@
         }
     }
 
+    @Test
     public void testTranslateKeyAcceptsAndroidKeystoreKeys() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -198,6 +210,7 @@
         }
     }
 
+    @Test
     public void testGenerateSecretWithNullSpecThrowsInvalidKeySpecException() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -212,6 +225,7 @@
         }
     }
 
+    @Test
     public void testGenerateSecretRejectsSecretKeySpec() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
@@ -226,6 +240,7 @@
         }
     }
 
+    @Test
     public void testGenerateSecretRejectsKeyInfo() throws Exception {
         for (String algorithm : EXPECTED_ALGORITHMS) {
             try {
diff --git a/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java b/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java
index 533f522..c72fc6e 100644
--- a/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java
@@ -16,6 +16,14 @@
 
 package android.keystore.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.keystore.cts.R;
 import android.keystore.cts.util.EmptyArray;
 import android.keystore.cts.util.ImportedKey;
@@ -47,14 +55,18 @@
 import android.security.keystore.KeyPermanentlyInvalidatedException;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
-import android.test.AndroidTestCase;
-import android.test.MoreAsserts;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for algorithm-agnostic functionality of {@code Signature} implementations backed by Android
  * Keystore.
  */
-public class SignatureTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class SignatureTest {
 
     static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_CRYPTO_OP_PROVIDER_NAME;
 
@@ -336,6 +348,11 @@
 
     private static final long DAY_IN_MILLIS = TestUtils.DAY_IN_MILLIS;
 
+    private Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
+    @Test
     public void testAlgorithmList() {
         // Assert that Android Keystore Provider exposes exactly the expected signature algorithms.
         // We don't care whether the algorithms are exposed via aliases, as long as the canonical
@@ -369,6 +386,7 @@
                 expectedSigAlgsLowerCase.toArray(new String[0]));
     }
 
+    @Test
     public void testAndroidKeyStoreKeysHandledByAndroidKeyStoreProviderWhenSigning()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -385,6 +403,7 @@
         }
     }
 
+    @Test
     public void testAndroidKeyStorePublicKeysAcceptedByHighestPriorityProviderWhenVerifying()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -400,6 +419,7 @@
         }
     }
 
+    @Test
     public void testValidSignatureGeneratedForEmptyMessage()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -429,6 +449,7 @@
         }
     }
 
+    @Test
     public void testValidSignatureGeneratedForEmptyMessageByLimitedUseKey()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -485,6 +506,7 @@
         }
     }
 
+    @Test
     public void testEmptySignatureDoesNotVerify()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -508,6 +530,7 @@
         }
     }
 
+    @Test
     public void testSignatureGeneratedByAndroidKeyStoreVerifiesByAndroidKeyStore()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -539,6 +562,7 @@
         }
     }
 
+    @Test
     public void testSignatureGeneratedByAndroidKeyStoreVerifiesByHighestPriorityProvider()
             throws Exception {
         Provider keystoreProvider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -583,6 +607,7 @@
         }
     }
 
+    @Test
     public void testSignatureGeneratedByHighestPriorityProviderVerifiesByAndroidKeyStore()
             throws Exception {
 
@@ -626,6 +651,7 @@
         }
     }
 
+    @Test
     public void testSmallMsgKat() throws Exception {
         byte[] message = SHORT_MSG_KAT_MESSAGE;
 
@@ -662,7 +688,7 @@
                 boolean deterministicSignatureScheme =
                         algorithm.toLowerCase().endsWith("withrsa");
                 if (deterministicSignatureScheme) {
-                    MoreAsserts.assertEquals(goodSigBytes, generatedSigBytes);
+                    assertArrayEquals(goodSigBytes, generatedSigBytes);
                 } else {
                     if (Math.abs(goodSigBytes.length - generatedSigBytes.length) > 2) {
                         fail("Generated signature expected to be between "
@@ -695,7 +721,7 @@
                 }
                 generatedSigBytes = signature.sign();
                 if (deterministicSignatureScheme) {
-                    MoreAsserts.assertEquals(goodSigBytes, generatedSigBytes);
+                    assertArrayEquals(goodSigBytes, generatedSigBytes);
                 } else {
                     if (Math.abs(goodSigBytes.length - generatedSigBytes.length) > 2) {
                         fail("Generated signature expected to be between "
@@ -724,6 +750,7 @@
         }
     }
 
+    @Test
     public void testLongMsgKat() throws Exception {
         byte[] message = TestUtils.generateLargeKatMsg(LONG_MSG_KAT_SEED, LONG_MSG_KAT_SIZE_BYTES);
 
@@ -781,7 +808,7 @@
                 boolean deterministicSignatureScheme =
                         KeyProperties.SIGNATURE_PADDING_RSA_PKCS1.equalsIgnoreCase(paddingScheme);
                 if (deterministicSignatureScheme) {
-                    MoreAsserts.assertEquals(goodSigBytes, generatedSigBytes);
+                    assertArrayEquals(goodSigBytes, generatedSigBytes);
                 } else {
                     if (Math.abs(goodSigBytes.length - generatedSigBytes.length) > 2) {
                         fail("Generated signature expected to be between "
@@ -808,7 +835,7 @@
                 generatedSigBytes = generateSignatureFedUsingFixedSizeChunks(
                         algorithm, provider, keyPair.getPrivate(), message, 444307);
                 if (deterministicSignatureScheme) {
-                    MoreAsserts.assertEquals(goodSigBytes, generatedSigBytes);
+                    assertArrayEquals(goodSigBytes, generatedSigBytes);
                 } else {
                     if (Math.abs(goodSigBytes.length - generatedSigBytes.length) > 2) {
                         fail("Generated signature expected to be between "
@@ -835,6 +862,7 @@
         }
     }
 
+    @Test
     public void testInitVerifySucceedsDespiteMissingAuthorizations() throws Exception {
         KeyProtection spec = new KeyProtection.Builder(0).build();
 
@@ -847,6 +875,7 @@
         }
     }
 
+    @Test
     public void testInitSignFailsWhenNotAuthorizedToSign() throws Exception {
         int badPurposes = KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
                 | KeyProperties.PURPOSE_VERIFY;
@@ -863,6 +892,7 @@
         }
     }
 
+    @Test
     public void testInitVerifyIgnoresThatNotAuthorizedToVerify() throws Exception {
         int badPurposes = KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
                 | KeyProperties.PURPOSE_SIGN;
@@ -879,6 +909,7 @@
         }
     }
 
+    @Test
     public void testInitSignFailsWhenDigestNotAuthorized() throws Exception {
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
             try {
@@ -905,6 +936,7 @@
         }
     }
 
+    @Test
     public void testInitVerifyIgnoresThatDigestNotAuthorized() throws Exception {
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
             try {
@@ -923,6 +955,7 @@
         }
     }
 
+    @Test
     public void testInitSignFailsWhenPaddingNotAuthorized() throws Exception {
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
             try {
@@ -951,6 +984,7 @@
         }
     }
 
+    @Test
     public void testInitVerifyIgnoresThatPaddingNotAuthorized() throws Exception {
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
             try {
@@ -979,6 +1013,7 @@
         }
     }
 
+    @Test
     public void testInitSignFailsWhenKeyNotYetValid() throws Exception {
         Date badStartDate = new Date(System.currentTimeMillis() + DAY_IN_MILLIS);
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
@@ -993,6 +1028,7 @@
         }
     }
 
+    @Test
     public void testInitVerifyIgnoresThatKeyNotYetValid() throws Exception {
         Date badStartDate = new Date(System.currentTimeMillis() + DAY_IN_MILLIS);
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
@@ -1007,6 +1043,7 @@
         }
     }
 
+    @Test
     public void testInitSignFailsWhenKeyNoLongerValidForOrigination() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
@@ -1023,6 +1060,7 @@
         }
     }
 
+    @Test
     public void testInitVerifyIgnoresThatKeyNoLongerValidForOrigination() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
@@ -1039,6 +1077,7 @@
         }
     }
 
+    @Test
     public void testInitSignIgnoresThatKeyNoLongerValidForConsumption() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
@@ -1055,6 +1094,7 @@
         }
     }
 
+    @Test
     public void testInitVerifyIgnoresThatKeyNoLongerValidForConsumption() throws Exception {
         Date badEndDate = new Date(System.currentTimeMillis() - DAY_IN_MILLIS);
         for (String algorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/AesCipherPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/AesCipherPerformanceTest.java
index 1730607..62c3358 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/AesCipherPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/AesCipherPerformanceTest.java
@@ -31,26 +31,32 @@
     final int[] SUPPORTED_AES_KEY_SIZES = {128, 256};
     final int[] TEST_MESSAGE_SIZES = {1 << 6, 1 << 10, 1 << 17};
 
+    @Test
     public void testAES_CBC_NoPadding() throws Exception {
         testAesCipher("AES/CBC/NoPadding", SUPPORTED_AES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testAES_CBC_PKCS7Padding() throws Exception {
         testAesCipher("AES/CBC/PKCS7Padding", SUPPORTED_AES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testAES_CTR_NoPadding() throws Exception {
         testAesCipher("AES/CTR/NoPadding", SUPPORTED_AES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testAES_ECB_NoPadding() throws Exception {
         testAesCipher("AES/ECB/NoPadding", SUPPORTED_AES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testAES_ECB_PKCS7Padding() throws Exception {
         testAesCipher("AES/ECB/PKCS7Padding", SUPPORTED_AES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testAES_GCM_NoPadding() throws Exception {
         testAesCipher("AES/GCM/NoPadding", SUPPORTED_AES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/AesKeyGenPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/AesKeyGenPerformanceTest.java
index 3e1b86b..f72707c 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/AesKeyGenPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/AesKeyGenPerformanceTest.java
@@ -18,12 +18,17 @@
 
 import android.security.keystore.KeyProperties;
 
-import org.junit.Test;
+import androidx.test.runner.AndroidJUnit4;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
 public class AesKeyGenPerformanceTest extends PerformanceTestBase {
 
     final int[] SUPPORTED_AES_KEY_SIZES = {128, 256};
 
+    @Test
     public void testAesKeyGen() throws Exception {
         for (int keySize : SUPPORTED_AES_KEY_SIZES) {
             measure(
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/AttestationPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/AttestationPerformanceTest.java
index ba3aab4..929f505 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/AttestationPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/AttestationPerformanceTest.java
@@ -20,10 +20,10 @@
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
 
-import org.junit.Test;
-
 import java.security.spec.ECGenParameterSpec;
 
+import org.junit.Test;
+
 public class AttestationPerformanceTest extends PerformanceTestBase {
 
     private final int[] RSA_KEY_SIZES = {2048, 3072, 4096};
@@ -35,7 +35,12 @@
         new byte[128], // long challenge
     };
 
+    @Test
     public void testRsaKeyAttestation() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         for (byte[] challenge : ATTESTATION_CHALLENGES) {
             for (int keySize : RSA_KEY_SIZES) {
                 measure(new KeystoreAttestationMeasurable(
@@ -45,7 +50,12 @@
         }
     }
 
+    @Test
     public void testEcKeyAttestation() throws Exception {
+        if (!TestUtils.isAttestationSupported()) {
+            return;
+        }
+
         for (byte[] challenge : ATTESTATION_CHALLENGES) {
             for (int curve : EC_CURVES) {
                 measure(new KeystoreAttestationMeasurable(
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/DesCipherPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/DesCipherPerformanceTest.java
index 498735e..6d6dbc4 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/DesCipherPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/DesCipherPerformanceTest.java
@@ -24,11 +24,14 @@
 import javax.crypto.Cipher;
 import javax.crypto.SecretKey;
 
+import org.junit.Test;
+
 public class DesCipherPerformanceTest extends PerformanceTestBase {
 
     final int[] SUPPORTED_DES_KEY_SIZES = {168};
     final int[] TEST_MESSAGE_SIZES = {1 << 6, 1 << 10, 1 << 17};
 
+    @Test
     public void testDESede_CBC_NoPadding() throws Exception {
         if (!TestUtils.supports3DES()) {
             return;
@@ -36,6 +39,7 @@
         testDesCipher("DESede/CBC/NoPadding", SUPPORTED_DES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testDESede_CBC_PKCS7Padding() throws Exception {
         if (!TestUtils.supports3DES()) {
             return;
@@ -43,6 +47,7 @@
         testDesCipher("DESede/CBC/PKCS7Padding", SUPPORTED_DES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testDESede_ECB_NoPadding() throws Exception {
         if (!TestUtils.supports3DES()) {
             return;
@@ -50,6 +55,7 @@
         testDesCipher("DESede/ECB/NoPadding", SUPPORTED_DES_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testDESede_ECB_PKCS7Padding() throws Exception {
         if (!TestUtils.supports3DES()) {
             return;
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/DesKeyGenPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/DesKeyGenPerformanceTest.java
index 48d3e73..cbb01e1 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/DesKeyGenPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/DesKeyGenPerformanceTest.java
@@ -19,10 +19,13 @@
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
 
+import org.junit.Test;
+
 public class DesKeyGenPerformanceTest extends PerformanceTestBase {
 
     final int[] SUPPORTED_DES_KEY_SIZES = {168};
 
+    @Test
     public void testDesKeyGen() throws Exception {
         if (!TestUtils.supports3DES()) {
             return;
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/EcKeyGenPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/EcKeyGenPerformanceTest.java
index c6161da..f4f891b 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/EcKeyGenPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/EcKeyGenPerformanceTest.java
@@ -18,14 +18,19 @@
 
 import android.security.keystore.KeyProperties;
 
+import androidx.test.runner.AndroidJUnit4;
+
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.security.spec.ECGenParameterSpec;
 
+@RunWith(AndroidJUnit4.class)
 public class EcKeyGenPerformanceTest extends PerformanceTestBase {
 
     final int[] SUPPORTED_CURVES = {224, 256, 384, 521};
 
+    @Test
     public void testEcKeyGen() throws Exception {
         for (int curve : SUPPORTED_CURVES) {
             measure(
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/EcdsaSignaturePerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/EcdsaSignaturePerformanceTest.java
index 0609105..f44ffee 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/EcdsaSignaturePerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/EcdsaSignaturePerformanceTest.java
@@ -30,26 +30,32 @@
     final int[] SUPPORTED_KEY_SIZES = {224, 256, 384, 521};
     final int[] TEST_MESSAGE_SIZES = {1 << 6, 1 << 10, 1 << 17};
 
+    @Test
     public void testNONEwithECDSA() throws Exception {
         testEcdsaSign("NONEwithECDSA", TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA1withECDSA() throws Exception {
         testEcdsaSign("SHA1withECDSA", TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA224withECDSA() throws Exception {
         testEcdsaSign("SHA224withECDSA", TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA256withECDSA() throws Exception {
         testEcdsaSign("SHA256withECDSA", TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA384withECDSA() throws Exception {
         testEcdsaSign("SHA384withECDSA", TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA512withECDSA() throws Exception {
         testEcdsaSign("SHA512withECDSA", TEST_MESSAGE_SIZES);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/HmacKeyGenPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/HmacKeyGenPerformanceTest.java
index 7fb161d..44f3d01 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/HmacKeyGenPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/HmacKeyGenPerformanceTest.java
@@ -18,12 +18,17 @@
 
 import android.security.keystore.KeyProperties;
 
-import org.junit.Test;
+import androidx.test.runner.AndroidJUnit4;
 
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
 public class HmacKeyGenPerformanceTest extends PerformanceTestBase {
 
     final int[] SUPPORTED_KEY_SIZES = {64, 128, 256, 512};
 
+    @Test
     public void testHmacKeyGen() throws Exception {
         for (int keySize : SUPPORTED_KEY_SIZES) {
             measure(
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/HmacMacPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/HmacMacPerformanceTest.java
index 2048b26..76b4093 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/HmacMacPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/HmacMacPerformanceTest.java
@@ -28,22 +28,27 @@
     final int[] SUPPORTED_KEY_SIZES = {64, 128, 256, 512};
     final int[] TEST_MESSAGE_SIZES = {1 << 6, 1 << 10, 1 << 17};
 
+    @Test
     public void testHmacSHA1() throws Exception {
         testHmac("HmacSHA1", SUPPORTED_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testHmacSHA224() throws Exception {
         testHmac("HmacSHA224", SUPPORTED_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testHmacSHA256() throws Exception {
         testHmac("HmacSHA256", SUPPORTED_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testHmacSHA384() throws Exception {
         testHmac("HmacSHA384", SUPPORTED_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testHmacSHA512() throws Exception {
         testHmac("HmacSHA512", SUPPORTED_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/PerformanceTestBase.java b/tests/tests/keystore/src/android/keystore/cts/performance/PerformanceTestBase.java
index 396b806..26eb0b7 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/PerformanceTestBase.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/PerformanceTestBase.java
@@ -17,11 +17,12 @@
 package android.keystore.cts.performance;
 
 import android.keystore.cts.util.TestUtils;
+import android.os.Build;
 import android.os.SystemClock;
 import android.security.keystore.KeyGenParameterSpec;
-import android.test.AndroidTestCase;
 
 import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
 
 import com.android.compatibility.common.util.DeviceReportLog;
 import com.android.compatibility.common.util.ResultType;
@@ -36,9 +37,10 @@
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 
-import android.os.Build;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class PerformanceTestBase extends AndroidTestCase {
+public class PerformanceTestBase {
 
     public static final long MS_PER_NS = 1000000L;
     protected static final String TAG = "KeystorePerformanceTest";
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/RsaCipherPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/RsaCipherPerformanceTest.java
index 71548a3..fe6a9d2 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/RsaCipherPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/RsaCipherPerformanceTest.java
@@ -20,31 +20,35 @@
 import android.keystore.cts.util.TestUtils;
 import android.security.keystore.KeyProperties;
 
-import org.junit.Test;
-
 import java.security.AlgorithmParameters;
 import java.security.KeyPair;
 
 import javax.crypto.Cipher;
 
+import org.junit.Test;
+
 public class RsaCipherPerformanceTest extends PerformanceTestBase {
 
     final int[] SUPPORTED_RSA_KEY_SIZES = {2048, 3072, 4096};
     final int[] TEST_MESSAGE_SIZES = {1 << 6, 1 << 10};
 
+    @Test
     public void testRSA_ECB_NoPadding() throws Exception {
         testRsaCipher("RSA/ECB/NoPadding", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testRSA_ECB_PKCS1Padding() throws Exception {
         testRsaCipher("RSA/ECB/PKCS1Padding", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testRSA_ECB_OAEPWithSHA_1AndMGF1Padding() throws Exception {
         testRsaCipher(
                 "RSA/ECB/OAEPWithSHA-1AndMGF1Padding", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testRSA_ECB_OAEPPadding() throws Exception {
         testRsaCipher("RSA/ECB/OAEPPadding", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/RsaKeyGenPerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/RsaKeyGenPerformanceTest.java
index 2666ab8..448af5b 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/RsaKeyGenPerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/RsaKeyGenPerformanceTest.java
@@ -18,28 +18,36 @@
 
 import android.security.keystore.KeyProperties;
 
+import org.junit.Test;
+
 public class RsaKeyGenPerformanceTest extends PerformanceTestBase {
 
+    @Test
     public void testRsa2048KeyGenWithAndroidProvider() throws Exception {
         measureKeyGenWithAndroidProvider(2048);
     }
 
+    @Test
     public void testRsa3072KeyGenWithAndroidProvider() throws Exception {
         measureKeyGenWithAndroidProvider(3072);
     }
 
+    @Test
     public void testRsa4096KeyGenWithAndroidProvider() throws Exception {
         measureKeyGenWithAndroidProvider(4096);
     }
 
+    @Test
     public void testRsa2048KeyGenWithDefaultProvider() throws Exception {
         measureKeyGenWithDefaultProvider(2048);
     }
 
+    @Test
     public void testRsa3072KeyGenWithDefaultProvider() throws Exception {
         measureKeyGenWithDefaultProvider(3072);
     }
 
+    @Test
     public void testRsa4096KeyGenWithDefaultProvider() throws Exception {
         measureKeyGenWithDefaultProvider(4096);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/performance/RsaSignaturePerformanceTest.java b/tests/tests/keystore/src/android/keystore/cts/performance/RsaSignaturePerformanceTest.java
index 28ac330..81839d4 100644
--- a/tests/tests/keystore/src/android/keystore/cts/performance/RsaSignaturePerformanceTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/performance/RsaSignaturePerformanceTest.java
@@ -30,6 +30,7 @@
     final int[] SUPPORTED_RSA_KEY_SIZES = {2048, 3072, 4096};
     final int[] TEST_MESSAGE_SIZES = {1 << 6, 1 << 10, 1 << 17};
 
+    @Test
     public void testNONEwithRSA() throws Exception {
         for (int keySize : SUPPORTED_RSA_KEY_SIZES) {
             int modulusSizeBytes = (keySize + 7) / 8;
@@ -39,46 +40,57 @@
         }
     }
 
+    @Test
     public void testMD5withRSA() throws Exception {
         testRsaSign("MD5withRSA", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA1withRSA() throws Exception {
         testRsaSign("SHA1withRSA", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA224withRSA() throws Exception {
         testRsaSign("SHA224withRSA", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA256withRSA() throws Exception {
         testRsaSign("SHA256withRSA", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA384withRSA() throws Exception {
         testRsaSign("SHA384withRSA", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA512withRSA() throws Exception {
         testRsaSign("SHA512withRSA", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA1withRSA_PSS() throws Exception {
         testRsaSign("SHA1withRSA/PSS", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA224withRSA_PSS() throws Exception {
         testRsaSign("SHA224withRSA/PSS", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA256withRSA_PSS() throws Exception {
         testRsaSign("SHA256withRSA/PSS", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA384withRSA_PSS() throws Exception {
         testRsaSign("SHA384withRSA/PSS", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
 
+    @Test
     public void testSHA512withRSA_PSS() throws Exception {
         testRsaSign("SHA512withRSA/PSS", SUPPORTED_RSA_KEY_SIZES, TEST_MESSAGE_SIZES);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/util/TestUtils.java b/tests/tests/keystore/src/android/keystore/cts/util/TestUtils.java
index 1782aaa..c82d9bc 100644
--- a/tests/tests/keystore/src/android/keystore/cts/util/TestUtils.java
+++ b/tests/tests/keystore/src/android/keystore/cts/util/TestUtils.java
@@ -16,11 +16,17 @@
 
 package android.keystore.cts.util;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeTrue;
 
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.content.pm.FeatureInfo;
+import android.os.Build;
 import android.os.SystemProperties;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
@@ -78,7 +84,7 @@
 import javax.crypto.SecretKeyFactory;
 import javax.crypto.spec.SecretKeySpec;
 
-abstract public class TestUtils extends Assert {
+public class TestUtils {
 
     public static final String EXPECTED_CRYPTO_OP_PROVIDER_NAME = "AndroidKeyStoreBCWorkaround";
     public static final String EXPECTED_PROVIDER_NAME = "AndroidKeyStore";
@@ -1091,4 +1097,8 @@
         new SecureRandom().nextBytes(message);
         return message;
     }
+
+    public static boolean isAttestationSupported() {
+        return Build.VERSION.DEVICE_INITIAL_SDK_INT >= Build.VERSION_CODES.O;
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/MediaSessionTest.java b/tests/tests/media/src/android/media/cts/MediaSessionTest.java
index 016c9ba..04f2662 100644
--- a/tests/tests/media/src/android/media/cts/MediaSessionTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaSessionTest.java
@@ -933,7 +933,7 @@
     }
 
     public void testSetQueueWithLargeNumberOfItems() throws Exception {
-        int queueSize = 1_000_000;
+        int queueSize = 500_000;
         List<QueueItem> queue = new ArrayList<>();
         for (int id = 0; id < queueSize; id++) {
             MediaDescription description = new MediaDescription.Builder()
diff --git a/tests/tests/mediatranscoding/src/android/media/mediatranscoding/cts/MediaTranscodingManagerTest.java b/tests/tests/mediatranscoding/src/android/media/mediatranscoding/cts/MediaTranscodingManagerTest.java
index 9cc7e1f..78e7b33 100644
--- a/tests/tests/mediatranscoding/src/android/media/mediatranscoding/cts/MediaTranscodingManagerTest.java
+++ b/tests/tests/mediatranscoding/src/android/media/mediatranscoding/cts/MediaTranscodingManagerTest.java
@@ -91,6 +91,8 @@
     private static final int BIT_RATE = 4000000;            // 4Mbps
     private static final int WIDTH = 720;
     private static final int HEIGHT = 480;
+    private static final int FRAME_RATE = 30;
+    private static final int INT_NOT_SET = Integer.MIN_VALUE;
 
     // Threshold for the psnr to make sure the transcoded video is valid.
     private static final int PSNR_THRESHOLD = 20;
@@ -128,9 +130,33 @@
     /**
      * Creates a MediaFormat with the default settings.
      */
-    private static MediaFormat createMediaFormat() {
-        MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, WIDTH, HEIGHT);
-        format.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
+    private static MediaFormat createDefaultMediaFormat() {
+        return createMediaFormat(MIME_TYPE, WIDTH, HEIGHT, INT_NOT_SET /* frameRate */,
+                BIT_RATE /* bitrate */);
+    }
+
+    /**
+     * Creates a MediaFormat with custom settings.
+     */
+    private static MediaFormat createMediaFormat(String mime, int width, int height, int frameRate,
+            int bitrate) {
+        MediaFormat format = new MediaFormat();
+        // Set mime if it not null.
+        if (mime != null) {
+            format.setString(MediaFormat.KEY_MIME, mime);
+        }
+        if (width != INT_NOT_SET) {
+            format.setInteger(MediaFormat.KEY_WIDTH, width);
+        }
+        if (height != INT_NOT_SET) {
+            format.setInteger(MediaFormat.KEY_HEIGHT, height);
+        }
+        if (frameRate != INT_NOT_SET) {
+            format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
+        }
+        if (bitrate != INT_NOT_SET) {
+            format.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
+        }
         return format;
     }
 
@@ -185,7 +211,7 @@
         assertThrows(IllegalArgumentException.class, () -> {
             VideoTranscodingRequest request =
                     new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, null,
-                            createMediaFormat())
+                            createDefaultMediaFormat())
                             .build();
         });
     }
@@ -200,7 +226,7 @@
         assertThrows(IllegalArgumentException.class, () -> {
             VideoTranscodingRequest request =
                     new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, mDestinationUri,
-                            createMediaFormat())
+                            createDefaultMediaFormat())
                             .setClientPid(-1)
                             .build();
         });
@@ -216,7 +242,7 @@
         assertThrows(IllegalArgumentException.class, () -> {
             VideoTranscodingRequest request =
                     new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, mDestinationUri,
-                            createMediaFormat())
+                            createDefaultMediaFormat())
                             .setClientUid(-1)
                             .build();
         });
@@ -231,7 +257,8 @@
         }
         assertThrows(IllegalArgumentException.class, () -> {
             VideoTranscodingRequest request =
-                    new VideoTranscodingRequest.Builder(null, mDestinationUri, createMediaFormat())
+                    new VideoTranscodingRequest.Builder(null, mDestinationUri,
+                            createDefaultMediaFormat())
                             .build();
         });
     }
@@ -245,7 +272,8 @@
         }
         assertThrows(IllegalArgumentException.class, () -> {
             VideoTranscodingRequest request =
-                    new VideoTranscodingRequest.Builder(null, mDestinationUri, createMediaFormat())
+                    new VideoTranscodingRequest.Builder(null, mDestinationUri,
+                            createDefaultMediaFormat())
                             .build();
         });
     }
@@ -260,7 +288,7 @@
         assertThrows(IllegalArgumentException.class, () -> {
             VideoTranscodingRequest request =
                     new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, null,
-                            createMediaFormat())
+                            createDefaultMediaFormat())
                             .build();
         });
     }
@@ -288,7 +316,7 @@
         Semaphore transcodeCompleteSemaphore = new Semaphore(0);
 
         VideoTranscodingRequest request =
-                new VideoTranscodingRequest.Builder(srcUri, dstUri, createMediaFormat())
+                new VideoTranscodingRequest.Builder(srcUri, dstUri, createDefaultMediaFormat())
                         .build();
         Executor listenerExecutor = Executors.newSingleThreadExecutor();
 
@@ -558,6 +586,135 @@
                 stats.mAveragePSNR >= PSNR_THRESHOLD);
     }
 
+    private void testVideoFormatResolverShouldTranscode(String mime, int width, int height,
+            int frameRate) {
+        ApplicationMediaCapabilities clientCaps =
+                new ApplicationMediaCapabilities.Builder().build();
+
+        MediaFormat mediaFormat = createMediaFormat(mime, width, height, frameRate, BIT_RATE);
+
+        TranscodingRequest.VideoFormatResolver
+                resolver = new TranscodingRequest.VideoFormatResolver(clientCaps,
+                mediaFormat);
+        assertTrue(resolver.shouldTranscode());
+        MediaFormat videoTrackFormat = resolver.resolveVideoFormat();
+        assertNotNull(videoTrackFormat);
+    }
+
+    public void testVideoFormatResolverValidArgs() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverShouldTranscode(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH, HEIGHT,
+                FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverAv1Mime() {
+        if (shouldSkip()) {
+            return;
+        }
+        ApplicationMediaCapabilities clientCaps =
+                new ApplicationMediaCapabilities.Builder().build();
+
+        MediaFormat mediaFormat = createMediaFormat(MediaFormat.MIMETYPE_VIDEO_AV1, WIDTH, HEIGHT,
+                FRAME_RATE, BIT_RATE);
+
+        TranscodingRequest.VideoFormatResolver
+                resolver = new TranscodingRequest.VideoFormatResolver(clientCaps,
+                mediaFormat);
+        assertFalse(resolver.shouldTranscode());
+        MediaFormat videoTrackFormat = resolver.resolveVideoFormat();
+        assertNull(videoTrackFormat);
+    }
+
+    private void testVideoFormatResolverInvalidArgs(String mime, int width, int height,
+            int frameRate) {
+        ApplicationMediaCapabilities clientCaps =
+                new ApplicationMediaCapabilities.Builder().build();
+
+        MediaFormat mediaFormat = createMediaFormat(mime, width, height, frameRate, BIT_RATE);
+
+        TranscodingRequest.VideoFormatResolver
+                resolver = new TranscodingRequest.VideoFormatResolver(clientCaps,
+                mediaFormat);
+
+        assertThrows(IllegalArgumentException.class, () -> {
+            MediaFormat videoTrackFormat = resolver.resolveVideoFormat();
+        });
+    }
+
+    public void testVideoFormatResolverZeroWidth() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, 0 /* width */,
+                HEIGHT, FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverZeroHeight() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH,
+                0 /* height */, FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverZeroFrameRate() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH,
+                HEIGHT, 0 /* frameRate */);
+    }
+
+    public void testVideoFormatResolverNegativeWidth() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, -WIDTH,
+                HEIGHT, FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverNegativeHeight() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH,
+                -HEIGHT, FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverNegativeFrameRate() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH,
+                HEIGHT, -FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverMissingWidth() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, INT_NOT_SET /* width*/,
+                HEIGHT /* height */, FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverMissingHeight() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverInvalidArgs(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH,
+                INT_NOT_SET /* height */, FRAME_RATE);
+    }
+
+    public void testVideoFormatResolverMissingFrameRate() {
+        if (shouldSkip()) {
+            return;
+        }
+        testVideoFormatResolverShouldTranscode(MediaFormat.MIMETYPE_VIDEO_HEVC, WIDTH, HEIGHT,
+                INT_NOT_SET /* frameRate */);
+    }
+
     private boolean compareFormat(MediaFormat fmt1, MediaFormat fmt2) {
         if (fmt1 == fmt2) return true;
         if (fmt1 == null || fmt2 == null) return false;
@@ -582,7 +739,7 @@
 
         VideoTranscodingRequest request =
                 new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, destinationUri,
-                        createMediaFormat())
+                        createDefaultMediaFormat())
                         .build();
         Executor listenerExecutor = Executors.newSingleThreadExecutor();
 
@@ -646,7 +803,7 @@
                             .setClientPid(pid)
                             .setClientUid(uid)
                             .setPriority(MediaTranscodingManager.PRIORITY_REALTIME)
-                            .setVideoTrackFormat(createMediaFormat())
+                            .setVideoTrackFormat(createDefaultMediaFormat())
                             .build();
             Executor listenerExecutor = Executors.newSingleThreadExecutor();
 
@@ -674,7 +831,7 @@
 
         VideoTranscodingRequest request =
                 new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, destinationUri,
-                        createMediaFormat())
+                        createDefaultMediaFormat())
                         .build();
         Executor listenerExecutor = Executors.newSingleThreadExecutor();
 
@@ -726,7 +883,7 @@
 
         VideoTranscodingRequest request =
                 new VideoTranscodingRequest.Builder(mSourceHEVCVideoUri, destinationUri,
-                        createMediaFormat())
+                        createDefaultMediaFormat())
                         .build();
         Executor listenerExecutor = Executors.newSingleThreadExecutor();
 
diff --git a/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java b/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java
index f25be15..c769a09 100644
--- a/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java
+++ b/tests/tests/nfc/src/android/nfc/cts/NfcPreferredPaymentTest.java
@@ -48,6 +48,9 @@
     private static final ComponentName CtsNfcTestService =
             new ComponentName("android.nfc.cts", "android.nfc.cts.CtsMyHostApduService");
 
+    private static final int MAX_TIMEOUT_MS = 5000;
+    private static final int TEST_DURATION_MS = 100;
+
     private NfcAdapter mAdapter;
     private CardEmulation mCardEmulation;
     private Context mContext;
@@ -67,6 +70,7 @@
         Settings.Secure.putString(mContext.getContentResolver(),
                 NFC_PAYMENT_DEFAULT_COMPONENT,
                 CtsNfcTestService.flattenToString());
+        waitPreferredPaymentSettingDone();
     }
 
     @After
@@ -146,4 +150,29 @@
             fail("Unexpected Exception " + e);
         }
     }
+
+    public void waitPreferredPaymentSettingDone() {
+        try {
+            for (int i = 0; i < MAX_TIMEOUT_MS / TEST_DURATION_MS; i++) {
+                CharSequence description =
+                        mCardEmulation.getDescriptionForPreferredPaymentService();
+
+                if (description != null && description.toString().equals(mDescription)) return;
+
+                msleep(TEST_DURATION_MS);
+            }
+
+            fail("Unable to set the preferred payment service");
+        } catch (Exception e) {
+            fail("Unexpected Exception " + e);
+        }
+    }
+
+    private void msleep(int millis) {
+        try {
+            Thread.sleep(millis);
+        } catch (InterruptedException e) {
+            fail("Unexpected Exception " + e);
+        }
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java
index f142758..91a4bd9 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java
@@ -1133,21 +1133,38 @@
 
         requestCapabilities(uceAdapter, contacts, callback);
 
+        List<RcsContactUceCapability> resultCapList = new ArrayList<>();
+
         // Verify that all the three contact's capabilities are received
         RcsContactUceCapability capability = waitForResult(capabilityQueue);
-        assertNotNull("Capabilities were not received for contact: " + contact1, capability);
-        verifyCapabilityResult(capability, contact1, SOURCE_TYPE_NETWORK, REQUEST_RESULT_FOUND,
-                true, true);
+        assertNotNull("Cannot receive the first capabilities result.", capability);
+        resultCapList.add(capability);
 
         capability = waitForResult(capabilityQueue);
-        assertNotNull("Capabilities were not received for contact: " + contact2, capability);
-        verifyCapabilityResult(capability, contact2, SOURCE_TYPE_NETWORK, REQUEST_RESULT_FOUND,
-                true, false);
+        assertNotNull("Cannot receive the second capabilities result.", capability);
+        resultCapList.add(capability);
 
         capability = waitForResult(capabilityQueue);
-        assertNotNull("Capabilities were not received for contact: " + contact3, capability);
-        verifyCapabilityResult(capability, contact3, SOURCE_TYPE_NETWORK, REQUEST_RESULT_FOUND,
-                false, false);
+        assertNotNull("Cannot receive the third capabilities result.", capability);
+        resultCapList.add(capability);
+
+        // Verify contact1's capabilities from the received capabilities list
+        RcsContactUceCapability resultCapability = getContactCapability(resultCapList, contact1);
+        assertNotNull("Cannot find the contact: " + contact1, resultCapability);
+        verifyCapabilityResult(resultCapability, contact1, SOURCE_TYPE_NETWORK,
+                REQUEST_RESULT_FOUND, true, true);
+
+        // Verify contact2's capabilities from the received capabilities list
+        resultCapability = getContactCapability(resultCapList, contact2);
+        assertNotNull("Cannot find the contact: " + contact2, resultCapability);
+        verifyCapabilityResult(resultCapability, contact2, SOURCE_TYPE_NETWORK,
+                REQUEST_RESULT_FOUND, true, false);
+
+        // Verify contact3's capabilities from the received capabilities list
+        resultCapability = getContactCapability(resultCapList, contact3);
+        assertNotNull("Cannot find the contact: " + contact3, resultCapability);
+        verifyCapabilityResult(resultCapability, contact3, SOURCE_TYPE_NETWORK,
+                REQUEST_RESULT_FOUND, false, false);
 
         // Verify the onCompleted is called
         waitForResult(completeQueue);
@@ -1156,6 +1173,7 @@
         errorRetryQueue.clear();
         completeQueue.clear();
         capabilityQueue.clear();
+        resultCapList.clear();
 
         // The request should not be called because the capabilities should be retrieved from cache.
         capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
@@ -1166,18 +1184,33 @@
 
         // Verify that all the three contact's capabilities are received
         capability = waitForResult(capabilityQueue);
-        assertNotNull("Capabilities were not received for contact: " + contact1, capability);
-        verifyCapabilityResult(capability, contact1, SOURCE_TYPE_CACHED, REQUEST_RESULT_FOUND,
+        assertNotNull("Cannot receive the first capabilities result.", capability);
+        resultCapList.add(capability);
+
+        capability = waitForResult(capabilityQueue);
+        assertNotNull("Cannot receive the second capabilities result.", capability);
+        resultCapList.add(capability);
+
+        capability = waitForResult(capabilityQueue);
+        assertNotNull("Cannot receive the third capabilities result.", capability);
+        resultCapList.add(capability);
+
+        // Verify contact1's capabilities from the received capabilities list
+        resultCapability = getContactCapability(resultCapList, contact1);
+        assertNotNull("Cannot find the contact: " + contact1, resultCapability);
+        verifyCapabilityResult(resultCapability, contact1, SOURCE_TYPE_CACHED, REQUEST_RESULT_FOUND,
                 true, true);
 
-        capability = waitForResult(capabilityQueue);
-        assertNotNull("Capabilities were not received for contact: " + contact2, capability);
-        verifyCapabilityResult(capability, contact2, SOURCE_TYPE_CACHED, REQUEST_RESULT_FOUND,
+        // Verify contact2's capabilities from the received capabilities list
+        resultCapability = getContactCapability(resultCapList, contact2);
+        assertNotNull("Cannot find the contact: " + contact2, resultCapability);
+        verifyCapabilityResult(resultCapability, contact2, SOURCE_TYPE_CACHED, REQUEST_RESULT_FOUND,
                 true, false);
 
-        capability = waitForResult(capabilityQueue);
-        assertNotNull("Capabilities were not received for contact: " + contact3, capability);
-        verifyCapabilityResult(capability, contact3, SOURCE_TYPE_CACHED, REQUEST_RESULT_FOUND,
+        // Verify contact3's capabilities from the received capabilities list
+        resultCapability = getContactCapability(resultCapList, contact3);
+        assertNotNull("Cannot find the contact: " + contact3, resultCapability);
+        verifyCapabilityResult(resultCapability, contact3, SOURCE_TYPE_CACHED, REQUEST_RESULT_FOUND,
                 false, false);
 
         // Verify the onCompleted is called
@@ -1187,6 +1220,7 @@
         errorRetryQueue.clear();
         completeQueue.clear();
         capabilityQueue.clear();
+        resultCapList.clear();
         removeTestContactFromEab();
 
         overrideCarrierConfig(null);
@@ -1859,6 +1893,7 @@
         // Override the carrier config of SIP 489 request forbidden.
         PersistableBundle bundle = new PersistableBundle();
         bundle.putBoolean(CarrierConfigManager.Ims.KEY_RCS_REQUEST_FORBIDDEN_BY_SIP_489_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_GROUP_SUBSCRIBE_BOOL, true);
         overrideCarrierConfig(bundle);
 
         // Connect to the ImsService
@@ -2670,6 +2705,17 @@
         return pidfBuilder.toString();
     }
 
+    private RcsContactUceCapability getContactCapability(
+            List<RcsContactUceCapability> resultCapList, Uri targetUri) {
+        if (resultCapList == null) {
+            return null;
+        }
+        return resultCapList.stream()
+            .filter(capability -> targetUri.equals(capability.getContactUri()))
+            .findFirst()
+            .orElse(null);
+    }
+
     private void verifyCapabilityResult(RcsContactUceCapability resultCapability, Uri expectedUri,
             int expectedSourceType, int expectedResult, boolean expectedAudioSupported,
             boolean expectedVideoSupported) {
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
index a7652df..e871f52 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
@@ -148,7 +148,7 @@
                 .runWithVerifier(getVerifier(
                             new Point[] { new Point(0, 0), new Point(50, 50) },
                             new Color[] { greenP3, greenP3 },
-                            .002f));
+                            .006f));
     }
 
     private static Color plus(Color a, Color b) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/PacProcessorTest.java b/tests/tests/webkit/src/android/webkit/cts/PacProcessorTest.java
index 2843011..5204f56 100644
--- a/tests/tests/webkit/src/android/webkit/cts/PacProcessorTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/PacProcessorTest.java
@@ -28,8 +28,6 @@
 import org.junit.Test;
 
 public final class PacProcessorTest {
-    private static final String TAG = "PacProcessorCtsTest";
-    private static final long REMOTE_TIMEOUT_MS = 5000;
 
     private TestProcessClient mProcess;
 
@@ -48,21 +46,22 @@
             Assert.assertNotNull("createPacProcessor must not return null", pacProcessor);
             Assert.assertNotNull("createPacProcessor must not return null", otherPacProcessor);
 
-            Assert.assertFalse("createPacProcessor must return different objects", pacProcessor == otherPacProcessor);
+            Assert.assertFalse(
+                    "createPacProcessor must return different objects",
+                    pacProcessor == otherPacProcessor);
 
             pacProcessor.setProxyScript(
-                    "function FindProxyForURL(url, host) {" +
-                            "return \"PROXY 1.2.3.4:8080\";" +
-                            "}"
-            );
+                    "function FindProxyForURL(url, host) {"
+                            + "return \"PROXY 1.2.3.4:8080\";"
+                            + "}");
             otherPacProcessor.setProxyScript(
-                    "function FindProxyForURL(url, host) {" +
-                            "return \"PROXY 5.6.7.8:8080\";" +
-                            "}"
-            );
+                    "function FindProxyForURL(url, host) {"
+                            + "return \"PROXY 5.6.7.8:8080\";"
+                            + "}");
 
             Assert.assertEquals("PROXY 1.2.3.4:8080", pacProcessor.findProxyForUrl("test.url"));
-            Assert.assertEquals("PROXY 5.6.7.8:8080", otherPacProcessor.findProxyForUrl("test.url"));
+            Assert.assertEquals(
+                    "PROXY 5.6.7.8:8080", otherPacProcessor.findProxyForUrl("test.url"));
 
             pacProcessor.release();
             otherPacProcessor.release();
@@ -74,7 +73,7 @@
      */
     @Test
     public void testCreatePacProcessor() throws Throwable {
-        mProcess.run(TestCreatePacProcessor.class, REMOTE_TIMEOUT_MS);
+        mProcess.run(TestCreatePacProcessor.class);
     }
 
     static class TestDefaultNetworkIsNull extends TestProcessClient.TestRunnable {
@@ -92,7 +91,7 @@
      */
     @Test
     public void testDefaultNetworkIsNull() throws Throwable {
-        mProcess.run(TestDefaultNetworkIsNull.class, REMOTE_TIMEOUT_MS);
+        mProcess.run(TestDefaultNetworkIsNull.class);
     }
 
     static class TestSetNetwork extends TestProcessClient.TestRunnable {
@@ -101,14 +100,17 @@
             ConnectivityManager connectivityManager =
                     ctx.getSystemService(ConnectivityManager.class);
             Network[] networks = connectivityManager.getAllNetworks();
-            Assert.assertTrue("testSetNetwork requires at least one available Network", networks.length > 0);
+            Assert.assertTrue(
+                    "testSetNetwork requires at least one available Network", networks.length > 0);
 
             PacProcessor pacProcessor = PacProcessor.createInstance();
             PacProcessor otherPacProcessor = PacProcessor.createInstance();
 
             pacProcessor.setNetwork(networks[0]);
             Assert.assertEquals("Network is not set", networks[0], pacProcessor.getNetwork());
-            Assert.assertNull("setNetwork must not affect other PacProcessors", otherPacProcessor.getNetwork());
+            Assert.assertNull(
+                    "setNetwork must not affect other PacProcessors",
+                    otherPacProcessor.getNetwork());
 
             pacProcessor.setNetwork(null);
             Assert.assertNull("Network is not unset", pacProcessor.getNetwork());
@@ -117,11 +119,12 @@
             otherPacProcessor.release();
         }
     }
+
     /**
      * Test that setNetwork correctly set Network to PacProcessor.
      */
     @Test
     public void testSetNetwork() throws Throwable {
-        mProcess.run(TestSetNetwork.class, REMOTE_TIMEOUT_MS);
+        mProcess.run(TestSetNetwork.class);
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/webkit/src/android/webkit/cts/TestProcessClient.java b/tests/tests/webkit/src/android/webkit/cts/TestProcessClient.java
index 1854641..ba6ae47 100644
--- a/tests/tests/webkit/src/android/webkit/cts/TestProcessClient.java
+++ b/tests/tests/webkit/src/android/webkit/cts/TestProcessClient.java
@@ -16,7 +16,6 @@
 
 package android.webkit.cts;
 
-
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -30,12 +29,16 @@
 
 import com.android.internal.annotations.GuardedBy;
 
+import com.google.common.util.concurrent.SettableFuture;
+
 import junit.framework.Assert;
 import junit.framework.AssertionFailedError;
 
 class TestProcessClient extends Assert implements AutoCloseable, ServiceConnection {
     private Context mContext;
 
+    static final long REMOTE_TIMEOUT_MS = 5000;
+
     private static final long CONNECT_TIMEOUT_MS = 5000;
 
     private Object mLock = new Object();
@@ -60,7 +63,34 @@
      * Subclass this to implement test code to run on the service side.
      */
     static abstract class TestRunnable extends Assert {
-        public abstract void run(Context ctx);
+        public abstract void run(Context ctx) throws Throwable;
+    }
+
+    /**
+     * Subclass this to implement test code that runs on the main looper on the service side.
+     */
+    static abstract class UiThreadTestRunnable extends TestRunnable {
+        // A handler for the main thread.
+        private static final Handler sMainThreadHandler = new Handler(Looper.getMainLooper());
+
+        @Override
+        final public void run(Context ctx) throws Throwable {
+            final SettableFuture<Void> exceptionPropagatingFuture = SettableFuture.create();
+            sMainThreadHandler.post(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        runOnUiThread(ctx);
+                        exceptionPropagatingFuture.set(null);
+                    } catch (Throwable t) {
+                        exceptionPropagatingFuture.setException(t);
+                    }
+                }
+            });
+            WebkitUtils.waitForFuture(exceptionPropagatingFuture);
+        }
+
+        protected abstract void runOnUiThread(Context ctx) throws Throwable;
     }
 
     static class ProcessFreshChecker extends TestRunnable {
@@ -98,6 +128,10 @@
         run(ProcessFreshChecker.class, 1000);
     }
 
+    public void run(Class runnableClass) throws Throwable {
+        run(runnableClass, REMOTE_TIMEOUT_MS);
+    }
+
     public void run(Class runnableClass, long timeoutMs) throws Throwable {
         Message m = Message.obtain(null, TestProcessService.MSG_RUN_TEST);
         m.replyTo = mReplyHandler;
diff --git a/tests/tests/webkit/src/android/webkit/cts/TestProcessService.java b/tests/tests/webkit/src/android/webkit/cts/TestProcessService.java
index 6ce8c4c..499d18c 100644
--- a/tests/tests/webkit/src/android/webkit/cts/TestProcessService.java
+++ b/tests/tests/webkit/src/android/webkit/cts/TestProcessService.java
@@ -16,16 +16,16 @@
 
 package android.webkit.cts;
 
-
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Handler;
+import android.os.HandlerThread;
 import android.os.IBinder;
+import android.os.Looper;
 import android.os.Message;
 import android.os.Messenger;
 import android.os.RemoteException;
-import android.util.Log;
 
 import junit.framework.Assert;
 import junit.framework.AssertionFailedError;
@@ -45,9 +45,19 @@
         return mMessenger.getBinder();
     }
 
-    final Messenger mMessenger = new Messenger(new IncomingHandler());
+    final Messenger mMessenger;
+
+    public TestProcessService() {
+        HandlerThread backgroundThread = new HandlerThread("TestThread");
+        backgroundThread.start();
+        mMessenger = new Messenger(new IncomingHandler(backgroundThread.getLooper()));
+    }
 
     private class IncomingHandler extends Handler {
+        IncomingHandler(Looper looper) {
+            super(looper);
+        }
+
         @Override
         public void handleMessage(Message msg) {
             if (msg.what == MSG_EXIT_PROCESS) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewDataDirTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewDataDirTest.java
index 0dec681..8e12c7a 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewDataDirTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewDataDirTest.java
@@ -16,7 +16,6 @@
 
 package android.webkit.cts;
 
-
 import android.content.Context;
 import android.test.ActivityInstrumentationTestCase2;
 import android.webkit.CookieManager;
@@ -26,7 +25,6 @@
 
 public class WebViewDataDirTest extends ActivityInstrumentationTestCase2<WebViewCtsActivity> {
 
-    private static final long REMOTE_TIMEOUT_MS = 5000;
     private static final String ALTERNATE_DIR_NAME = "test";
     private static final String COOKIE_URL = "https://www.webviewdatadirtest.com/";
     private static final String COOKIE_VALUE = "foo=main";
@@ -53,7 +51,7 @@
         }
 
         try (TestProcessClient process = TestProcessClient.createProcessA(getActivity())) {
-            process.run(TestDisableThenUseImpl.class, REMOTE_TIMEOUT_MS);
+            process.run(TestDisableThenUseImpl.class);
         }
     }
 
@@ -97,7 +95,7 @@
         }
 
         try (TestProcessClient process = TestProcessClient.createProcessA(getActivity())) {
-            process.run(TestInvalidDirImpl.class, REMOTE_TIMEOUT_MS);
+            process.run(TestInvalidDirImpl.class);
         }
     }
 
@@ -119,7 +117,7 @@
         assertNotNull(getActivity().getWebView());
 
         try (TestProcessClient processA = TestProcessClient.createProcessA(getActivity())) {
-            processA.run(TestDefaultDirDisallowed.class, REMOTE_TIMEOUT_MS);
+            processA.run(TestDefaultDirDisallowed.class);
         }
     }
 
@@ -145,7 +143,7 @@
         assertEquals("wrong cookie in default cookie jar", COOKIE_VALUE, cookie);
 
         try (TestProcessClient processA = TestProcessClient.createProcessA(getActivity())) {
-            processA.run(TestCookieInAlternateDir.class, REMOTE_TIMEOUT_MS);
+            processA.run(TestCookieInAlternateDir.class);
         }
     }
 }
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java
new file mode 100644
index 0000000..014d150
--- /dev/null
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2021 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 android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.test.InstrumentationTestCase;
+import android.webkit.WebView;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.NullWebViewUtils;
+
+/**
+ * Test class testing different aspects of WebView loading.
+ *
+ * <p>Each test method in this class has to run in a freshly created process to ensure we don't run
+ * the tests in the same process (since we can only load WebView into a process once - after that we
+ * will reuse the same webview provider).
+ *
+ * <p>Tests in this class are moved from {@link com.android.cts.webkit.WebViewHostSideStartupTest},
+ * see http://b/72376996 for the migration of these tests.
+ */
+public class WebViewStartupTest extends InstrumentationTestCase {
+    private static final String TEST_PROCESS_DATA_DIR_SUFFIX = "WebViewStartupTestDir";
+    private static final long TEST_TIMEOUT_MS = 3000;
+
+    private static void runCurrentWebViewPackageTest(Context ctx, boolean alreadyOnMainThread)
+            throws Throwable {
+        // Have to set data dir suffix because this runs in a new process, and WebView might
+        // already be used in other processes.
+        WebView.setDataDirectorySuffix(TEST_PROCESS_DATA_DIR_SUFFIX);
+
+        PackageManager pm = ctx.getPackageManager();
+        if (pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
+            PackageInfo webViewPackage = WebView.getCurrentWebViewPackage();
+            // Ensure that getCurrentWebViewPackage returns a package recognized by the package
+            // manager.
+            assertPackageEquals(pm.getPackageInfo(webViewPackage.packageName, 0), webViewPackage);
+
+            // Create WebView on the app's main thread
+            if (alreadyOnMainThread) {
+                new WebView(ctx);
+            } else {
+                WebkitUtils.onMainThreadSync(() -> { new WebView(ctx); });
+            }
+
+            // Ensure we are still using the same WebView package.
+            assertPackageEquals(webViewPackage, WebView.getCurrentWebViewPackage());
+        } else {
+            // if WebView isn't supported the API should return null.
+            assertNull(WebView.getCurrentWebViewPackage());
+        }
+    }
+
+    private static void assertPackageEquals(PackageInfo expected, PackageInfo actual) {
+        if (expected == null)
+            assertNull(actual);
+        assertEquals(expected.packageName, actual.packageName);
+        assertEquals(expected.versionCode, actual.versionCode);
+        assertEquals(expected.versionName, actual.versionName);
+        assertEquals(expected.lastUpdateTime, actual.lastUpdateTime);
+    }
+
+    static class TestGetCurrentWebViewPackageOnUiThread
+            extends TestProcessClient.UiThreadTestRunnable {
+        @Override
+        protected void runOnUiThread(Context ctx) throws Throwable {
+            runCurrentWebViewPackageTest(ctx, true /* alreadyOnMainThread */);
+        }
+    }
+
+    public void testGetCurrentWebViewPackageOnUiThread() throws Throwable {
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        try (TestProcessClient process = TestProcessClient.createProcessA(context)) {
+            process.run(TestGetCurrentWebViewPackageOnUiThread.class);
+        }
+    }
+
+    static class TestGetCurrentWebViewPackageOnBackgroundThread
+            extends TestProcessClient.TestRunnable {
+        @Override
+        public void run(Context ctx) throws Throwable {
+            runCurrentWebViewPackageTest(ctx, false /* alreadyOnMainThread */);
+        }
+    }
+
+    public void testGetCurrentWebViewPackageOnBackgroundThread() throws Throwable {
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        try (TestProcessClient process = TestProcessClient.createProcessA(context)) {
+            process.run(TestGetCurrentWebViewPackageOnBackgroundThread.class);
+        }
+    }
+
+    static class TestGetWebViewLooperOnUiThread extends TestProcessClient.UiThreadTestRunnable {
+        @Override
+        protected void runOnUiThread(Context ctx) {
+            // Have to set data dir suffix because this runs in a new process, and WebView might
+            // already be used in other processes.
+            WebView.setDataDirectorySuffix(TEST_PROCESS_DATA_DIR_SUFFIX);
+
+            createAndCheckWebViewLooper(ctx);
+        }
+    }
+
+    public void testGetWebViewLooperOnUiThread() throws Throwable {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        try (TestProcessClient process = TestProcessClient.createProcessA(context)) {
+            process.run(TestGetWebViewLooperOnUiThread.class);
+        }
+    }
+
+    static class TestGetWebViewLooperCreatedOnUiThreadFromInstrThread
+            extends TestProcessClient.TestRunnable {
+        @Override
+        public void run(Context ctx) {
+            // Have to set data dir suffix because this runs in a new process, and WebView might
+            // already be used in other processes.
+            WebView.setDataDirectorySuffix(TEST_PROCESS_DATA_DIR_SUFFIX);
+
+            // Create the WebView on the UI thread and then ensure webview.getWebViewLooper()
+            // returns the UI thread.
+            WebView webView =
+                    WebkitUtils.onMainThreadSync(() -> createAndCheckWebViewLooper(ctx));
+            assertEquals(Looper.getMainLooper(), webView.getWebViewLooper());
+        }
+    }
+
+    /**
+     * Ensure that a WebView created on the UI thread returns that thread as its creator thread.
+     * This ensures WebView.getWebViewLooper() is not implemented as 'return Looper.myLooper();'.
+     */
+    public void testGetWebViewLooperCreatedOnUiThreadFromInstrThread() throws Throwable {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        try (TestProcessClient process = TestProcessClient.createProcessA(context)) {
+            process.run(TestGetWebViewLooperCreatedOnUiThreadFromInstrThread.class);
+        }
+    }
+
+    static class TestGetWebViewLooperCreatedOnBackgroundThreadFromInstThread
+            extends TestProcessClient.TestRunnable {
+        @Override
+        public void run(Context ctx) throws InterruptedException {
+            // Have to set data dir suffix because this runs in a new process, and WebView might
+            // already be used in other processes.
+            WebView.setDataDirectorySuffix(TEST_PROCESS_DATA_DIR_SUFFIX);
+
+            // Create a WebView on a background thread, check it from the UI thread
+            final WebView webviewHolder[] = new WebView[1];
+
+            // Use a HandlerThread, because such a thread owns a Looper.
+            HandlerThread backgroundThread = new HandlerThread("WebViewLooperCtsHandlerThread");
+            backgroundThread.start();
+            new Handler(backgroundThread.getLooper())
+                    .post(() -> webviewHolder[0] = createAndCheckWebViewLooper(ctx));
+            backgroundThread.join(TEST_TIMEOUT_MS);
+            assertEquals(backgroundThread.getLooper(), webviewHolder[0].getWebViewLooper());
+        }
+    }
+
+    /**
+     * Ensure that a WebView created on a background thread returns that thread as its creator
+     * thread. This ensures WebView.getWebViewLooper() is not bound to the UI thread regardless of
+     * the thread it is created on..
+     */
+    public void testGetWebViewLooperCreatedOnBackgroundThreadFromInstThread()
+            throws Throwable {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        try (TestProcessClient process = TestProcessClient.createProcessA(context)) {
+            process.run(TestGetWebViewLooperCreatedOnBackgroundThreadFromInstThread.class);
+        }
+    }
+
+    private static WebView createAndCheckWebViewLooper(Context context) {
+        // Ensure we are running this on a thread with a Looper - otherwise there's no point.
+        assertNotNull(Looper.myLooper());
+        WebView webview = new WebView(context);
+        assertEquals(Looper.myLooper(), webview.getWebViewLooper());
+        return webview;
+    }
+}
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index 856be32..e5a0041 100755
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -223,9 +223,12 @@
             return;
         }
 
-        new WebView(getActivity());
-        new WebView(getActivity(), null);
-        new WebView(getActivity(), null, 0);
+        WebView webView = new WebView(getActivity());
+        webView.destroy();
+        webView = new WebView(getActivity(), null);
+        webView.destroy();
+        webView = new WebView(getActivity(), null, 0);
+        webView.destroy();
     }
 
     @UiThreadTest
@@ -237,12 +240,9 @@
         Context deviceEncryptedContext = getActivity().createDeviceProtectedStorageContext();
         try {
             new WebView(deviceEncryptedContext);
-        } catch (IllegalArgumentException e) {
-            return;
-        }
-
-        fail("WebView should have thrown exception when creating with a device " +
+            fail("WebView should have thrown exception when creating with a device " +
                 "protected storage context");
+        } catch (IllegalArgumentException e) {}
     }
 
     @UiThreadTest
@@ -256,16 +256,14 @@
         Context deviceEncryptedContext = getActivity().createDeviceProtectedStorageContext();
 
         // No exception should be thrown with credential encryption context.
-        new WebView(credentialEncryptedContext);
+        WebView webView = new WebView(credentialEncryptedContext);
+        webView.destroy();
 
         try {
             new WebView(deviceEncryptedContext);
-        } catch (IllegalArgumentException e) {
-            return;
-        }
-
-        fail("WebView should have thrown exception when creating with a device " +
+            fail("WebView should have thrown exception when creating with a device " +
                 "protected storage context");
+        } catch (IllegalArgumentException e) {}
     }
 
     @UiThreadTest
@@ -273,8 +271,9 @@
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
         }
-        new WebView(getActivity());
+        WebView webView = new WebView(getActivity());
         assertNotNull(CookieSyncManager.getInstance());
+        webView.destroy();
     }
 
     // Static methods should be safe to call on non-UI threads
@@ -2065,6 +2064,8 @@
         assertEquals(url1, copyListAfterRestore.getItemAtIndex(0).getUrl());
         assertEquals(url2, copyListAfterRestore.getItemAtIndex(1).getUrl());
         assertEquals(url3, copyListAfterRestore.getItemAtIndex(2).getUrl());
+
+        newWebView.destroy();
     }
 
     public void testRequestChildRectangleOnScreen() throws Throwable {
@@ -2525,6 +2526,7 @@
         assertNotSame(client, client2);
         webView.setWebViewClient(client2);
         assertSame(client2, webView.getWebViewClient());
+        webView.destroy();
     }
 
     /**
@@ -2548,6 +2550,7 @@
         assertNotSame(client, client2);
         webView.setWebChromeClient(client2);
         assertSame(client2, webView.getWebChromeClient());
+        webView.destroy();
     }
 
     @UiThreadTest
@@ -2580,6 +2583,7 @@
         WebView webView = new WebView(getActivity());
         webView.setTextClassifier(classifier);
         assertSame(webView.getTextClassifier(), classifier);
+        webView.destroy();
     }
 
     private static class MockContext extends ContextWrapper {
diff --git a/tests/video/src/android/video/cts/CodecEncoderPerformanceTestBase.java b/tests/video/src/android/video/cts/CodecEncoderPerformanceTestBase.java
index d95e069..1c4e6d8 100644
--- a/tests/video/src/android/video/cts/CodecEncoderPerformanceTestBase.java
+++ b/tests/video/src/android/video/cts/CodecEncoderPerformanceTestBase.java
@@ -121,6 +121,17 @@
             if (mMaxOpRateScalingFactor < 1.0f) {
                 mOperatingRateExpected = operatingRateToSet;
             }
+
+            if (EXCLUDE_ENCODER_OPRATE_0_TO_30_FOR_4K) {
+                int width = mEncoderFormat.getInteger(MediaFormat.KEY_WIDTH);
+                int height = mEncoderFormat.getInteger(MediaFormat.KEY_HEIGHT);
+                if (width >= 3840 && height >= 2160) {
+                    assumeTrue("For devices launched with Android R and below, operating rate " +
+                            "tests are limited to operating rate <= 0 or >= 30 for 4k and" +
+                            " above", operatingRateToSet <= 0 || operatingRateToSet >= 30);
+                }
+            }
+
             mDecoderFormat.setInteger(MediaFormat.KEY_OPERATING_RATE, operatingRateToSet);
             mEncoderFormat.setInteger(MediaFormat.KEY_OPERATING_RATE, operatingRateToSet);
         } else if (mMaxOpRateScalingFactor < 0.0f) {
diff --git a/tests/video/src/android/video/cts/CodecPerformanceTestBase.java b/tests/video/src/android/video/cts/CodecPerformanceTestBase.java
index 448f078..2e261cf 100644
--- a/tests/video/src/android/video/cts/CodecPerformanceTestBase.java
+++ b/tests/video/src/android/video/cts/CodecPerformanceTestBase.java
@@ -58,6 +58,10 @@
     // resolutions that are less than half of max supported frame sizes of encoder.
     static final boolean EXCLUDE_ENCODER_MAX_RESOLUTION;
 
+    // Some older devices can not support concurrent instances of both decoder and encoder
+    // for operating rates > 0 and < 30 for resolutions 4k
+    static final boolean EXCLUDE_ENCODER_OPRATE_0_TO_30_FOR_4K;
+
     static final String mInputPrefix = WorkDir.getMediaDirString();
 
     ArrayList<MediaCodec.BufferInfo> mBufferInfos;
@@ -100,6 +104,10 @@
 
         // Encoders on devices launched on Android Q and lower aren't tested at maximum resolution
         EXCLUDE_ENCODER_MAX_RESOLUTION = DEVICE_INITIAL_SDK <= Build.VERSION_CODES.Q;
+
+        // Encoders on devices launched on Android R and lower aren't tested when operating rate
+        // that is set is > 0 and < 30 for resolution 4k
+        EXCLUDE_ENCODER_OPRATE_0_TO_30_FOR_4K = DEVICE_INITIAL_SDK <= Build.VERSION_CODES.R;
     }
 
     @Before
diff --git a/tools/cts-tradefed/res/config/cts-validation.xml b/tools/cts-tradefed/res/config/cts-validation.xml
index fa8a666..5c34cb3 100644
--- a/tools/cts-tradefed/res/config/cts-validation.xml
+++ b/tools/cts-tradefed/res/config/cts-validation.xml
@@ -14,8 +14,8 @@
      limitations under the License.
 -->
 <configuration description="Runs a subset of CTS tests using a general kernel image (GKI)">
-    <option name="plan" value="cts-validation" />
     <option name="result-attribute" key="GKI" value="1" />
     <include name="cts-on-gsi" />
     <include name="cts-validation-exclude" />
+    <option name="plan" value="cts-validation" />
 </configuration>
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
index a5f1dfb..97ee339 100644
--- a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
@@ -22,6 +22,7 @@
 import com.android.tradefed.testtype.suite.TestSuiteInfo;
 import com.android.tradefed.util.AaptParser;
 import com.android.tradefed.util.AbiUtils;
+import com.android.tradefed.util.FileUtil;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -29,6 +30,7 @@
 
 import java.io.File;
 import java.io.FilenameFilter;
+import java.io.IOException;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
@@ -98,12 +100,6 @@
          * This binary is a host side helper, so we do not need to check it.
          */
         BINARY_EXCEPTIONS.add("sepolicy-analyze");
-
-        /**
-         * This binary is a python script.
-         * TODO(b/207155369): Update ValidateTestsAbi to exampt abi checking for all Python scripts.
-         */
-        BINARY_EXCEPTIONS.add("CtsSampleMoblyTestCases");
     }
 
     private static final String BINARY_EXCEPTIONS_REGEX [] = {
@@ -237,6 +233,14 @@
                 if (!file.canExecute()) {
                     return false;
                 }
+                try {
+                    // Ignore python binaries
+                    if (FileUtil.readStringFromFile(file).startsWith("#!/usr/bin/env python")) {
+                        return false;
+                    }
+                } catch (IOException e) {
+                    throw new RuntimeException(e);
+                }
                 for(String pattern: BINARY_EXCEPTIONS_REGEX) {
                     Matcher matcher = Pattern.compile(pattern).matcher(name);
                     if (matcher.matches()) {