Initial BiometricServiceTest

1) Moves re-usable components up one level (e.g. SensorStates)
2) Adds BiometricServiceTest and related test activities, etc

Fixes: 171357779
Test: atest CtsBiometricsTestCases on face and fingerprint devices

Change-Id: Iac637805927d85a192dd3593c4ecea52f69617ec
diff --git a/tests/framework/base/biometrics/Android.bp b/tests/framework/base/biometrics/Android.bp
index f7d006f..057a2f8 100644
--- a/tests/framework/base/biometrics/Android.bp
+++ b/tests/framework/base/biometrics/Android.bp
@@ -51,6 +51,7 @@
     ],
 
     srcs: [
-        "src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java",
+        "src/android/server/biometrics/BiometricCallbackHelper.java",
+        "src/android/server/biometrics/fingerprint/FingerprintCallbackHelper.java",
     ],
 }
\ No newline at end of file
diff --git a/tests/framework/base/biometrics/AndroidTest.xml b/tests/framework/base/biometrics/AndroidTest.xml
index 803cbae..1e7854c 100644
--- a/tests/framework/base/biometrics/AndroidTest.xml
+++ b/tests/framework/base/biometrics/AndroidTest.xml
@@ -23,6 +23,7 @@
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsBiometricsTestCases.apk" />
+        <option name="test-file-name" value="CtsBiometricServiceTestApp.apk" />
         <option name="test-file-name" value="CtsFingerprintServiceTestApp.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
diff --git a/tests/framework/base/biometrics/apps/biometrics/Android.bp b/tests/framework/base/biometrics/apps/biometrics/Android.bp
new file mode 100644
index 0000000..186d46c
--- /dev/null
+++ b/tests/framework/base/biometrics/apps/biometrics/Android.bp
@@ -0,0 +1,35 @@
+// Copyright (C) 2020 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.
+
+android_test {
+    name: "CtsBiometricServiceTestApp",
+    defaults: ["cts_support_defaults"],
+
+    static_libs: [
+        "cts-biometric-util",
+        "cts-wm-app-base",
+    ],
+
+    srcs: [
+        "src/**/*.java",
+    ],
+
+    sdk_version: "test_current",
+
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
\ No newline at end of file
diff --git a/tests/framework/base/biometrics/apps/biometrics/AndroidManifest.xml b/tests/framework/base/biometrics/apps/biometrics/AndroidManifest.xml
new file mode 100644
index 0000000..ce2c3b1
--- /dev/null
+++ b/tests/framework/base/biometrics/apps/biometrics/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.server.biometrics">
+
+    <uses-permission android:name="android.permission.USE_BIOMETRIC"/>
+
+    <application>
+        <activity android:name="android.server.biometrics.Class2BiometricOrCredentialActivity"
+            android:exported="true"/>
+        <activity android:name="android.server.biometrics.Class3BiometricActivity"
+            android:exported="true"/>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/tests/framework/base/biometrics/apps/biometrics/OWNERS b/tests/framework/base/biometrics/apps/biometrics/OWNERS
new file mode 100644
index 0000000..15711bb
--- /dev/null
+++ b/tests/framework/base/biometrics/apps/biometrics/OWNERS
@@ -0,0 +1,2 @@
+# Bug component: 879035
+kchyn@google.com
\ No newline at end of file
diff --git a/tests/framework/base/biometrics/apps/biometrics/src/android/server/biometrics/Class2BiometricOrCredentialActivity.java b/tests/framework/base/biometrics/apps/biometrics/src/android/server/biometrics/Class2BiometricOrCredentialActivity.java
new file mode 100644
index 0000000..be3b0dd
--- /dev/null
+++ b/tests/framework/base/biometrics/apps/biometrics/src/android/server/biometrics/Class2BiometricOrCredentialActivity.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import android.app.Activity;
+import android.hardware.biometrics.BiometricManager;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.Bundle;
+import android.os.CancellationSignal;
+import android.os.Handler;
+import android.os.Looper;
+
+import androidx.annotation.Nullable;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Test app that invokes authentication in onCreate
+ */
+public class Class2BiometricOrCredentialActivity extends Activity {
+    @Override
+    protected void onCreate(@Nullable Bundle bundle) {
+        super.onCreate(bundle);
+        final Handler handler = new Handler(Looper.getMainLooper());
+        final Executor executor = handler::post;
+        final BiometricCallbackHelper callbackHelper = new BiometricCallbackHelper(this);
+
+        final BiometricPrompt bp = new BiometricPrompt.Builder(this)
+                .setTitle("Title")
+                .setSubtitle("Subtitle")
+                .setDescription("Description")
+                .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_WEAK
+                        | BiometricManager.Authenticators.DEVICE_CREDENTIAL)
+                .build();
+
+        bp.authenticate(new CancellationSignal(), executor, callbackHelper);
+    }
+}
diff --git a/tests/framework/base/biometrics/apps/biometrics/src/android/server/biometrics/Class3BiometricActivity.java b/tests/framework/base/biometrics/apps/biometrics/src/android/server/biometrics/Class3BiometricActivity.java
new file mode 100644
index 0000000..cd7be8d
--- /dev/null
+++ b/tests/framework/base/biometrics/apps/biometrics/src/android/server/biometrics/Class3BiometricActivity.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import android.app.Activity;
+import android.hardware.biometrics.BiometricManager;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.Bundle;
+import android.os.CancellationSignal;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+
+import androidx.annotation.Nullable;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Test app that invokes authentication in onCreate
+ */
+public class Class3BiometricActivity extends Activity {
+    private static final String TAG = "Class3OnlyBiometricActivity";
+
+    @Override
+    protected void onCreate(@Nullable Bundle bundle) {
+        super.onCreate(bundle);
+        final Handler handler = new Handler(Looper.getMainLooper());
+        final Executor executor = handler::post;
+        final BiometricCallbackHelper callbackHelper = new BiometricCallbackHelper(this);
+
+        final BiometricPrompt bp = new BiometricPrompt.Builder(this)
+                .setTitle("Title")
+                .setSubtitle("Subtitle")
+                .setDescription("Description")
+                .setNegativeButton("Negative Button", executor, (dialog, which) -> {
+                    callbackHelper.onNegativeButtonPressed();
+                })
+                .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
+                .build();
+
+        bp.authenticate(new CancellationSignal(), executor, callbackHelper);
+    }
+}
diff --git a/tests/framework/base/biometrics/apps/fingerprint/src/android/server/biometrics/fingerprint/AuthOnCreateActivity.java b/tests/framework/base/biometrics/apps/fingerprint/src/android/server/biometrics/fingerprint/AuthOnCreateActivity.java
index 2af0db4..85a9230 100644
--- a/tests/framework/base/biometrics/apps/fingerprint/src/android/server/biometrics/fingerprint/AuthOnCreateActivity.java
+++ b/tests/framework/base/biometrics/apps/fingerprint/src/android/server/biometrics/fingerprint/AuthOnCreateActivity.java
@@ -35,6 +35,6 @@
         super.onCreate(bundle);
         final FingerprintManager fpm = getSystemService(FingerprintManager.class);
         fpm.authenticate(null /* crypto */, new CancellationSignal(), 0 /* flags */,
-                new AuthenticationCallbackHelper(this), null /* handler */);
+                new FingerprintCallbackHelper(this), null /* handler */);
     }
 }
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricCallbackHelper.java
similarity index 66%
copy from tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java
copy to tests/framework/base/biometrics/src/android/server/biometrics/BiometricCallbackHelper.java
index c73cfb5..c7edf36 100644
--- a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricCallbackHelper.java
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-package android.server.biometrics.fingerprint;
+package android.server.biometrics;
 
 import android.app.Activity;
-import android.hardware.fingerprint.FingerprintManager;
+import android.hardware.biometrics.BiometricPrompt;
 import android.os.Bundle;
 import android.server.wm.TestJournalProvider;
 
@@ -25,16 +25,7 @@
 
 import java.util.ArrayList;
 
-/**
- * Authentication callback helper that allows easy transfer between test activities and
- * CTS via {@link android.server.wm.TestJournalProvider.TestJournal}, as well as serialization
- * and deserialization.
- *
- * Note that generally a single instance of this helper should only be used for a single
- * authentication.
- */
-@SuppressWarnings("deprecation")
-public class AuthenticationCallbackHelper extends FingerprintManager.AuthenticationCallback {
+public class BiometricCallbackHelper extends BiometricPrompt.AuthenticationCallback {
 
     public static final String KEY = "key_auth_callback";
 
@@ -43,11 +34,13 @@
         private static final String KEY_ACQUIRED_RECEIVED = "key_acquired_received";
         private static final String KEY_NUM_ACCEPTED = "key_num_accepted";
         private static final String KEY_NUM_REJECTED = "key_num_rejected";
+        private static final String KEY_NEGATIVE_BUTTON_PRESSED = "key_negative_button_pressed";
 
         public final ArrayList<Integer> mErrorsReceived;
         public final ArrayList<Integer> mAcquiredReceived;
         public int mNumAuthAccepted;
         public int mNumAuthRejected;
+        public boolean mNegativeButtonPressed;
 
         public State() {
             mErrorsReceived = new ArrayList<>();
@@ -60,23 +53,37 @@
             bundle.putIntegerArrayList(KEY_ACQUIRED_RECEIVED, mAcquiredReceived);
             bundle.putInt(KEY_NUM_ACCEPTED, mNumAuthAccepted);
             bundle.putInt(KEY_NUM_REJECTED, mNumAuthRejected);
+            bundle.putBoolean(KEY_NEGATIVE_BUTTON_PRESSED, mNegativeButtonPressed);
             return bundle;
         }
 
         private State(ArrayList<Integer> errorsReceived, ArrayList<Integer> acquiredReceived,
-                int numAuthAccepted, int numAuthRejected) {
+                int numAuthAccepted, int numAuthRejected, boolean negativeButtonPressed) {
             mErrorsReceived = errorsReceived;
             mAcquiredReceived = acquiredReceived;
             mNumAuthAccepted = numAuthAccepted;
             mNumAuthRejected = numAuthRejected;
+            mNegativeButtonPressed = negativeButtonPressed;
         }
 
-        public static State fromBundle(@NonNull Bundle bundle) {
-            return new State(
+        public static BiometricCallbackHelper.State fromBundle(@NonNull Bundle bundle) {
+            return new BiometricCallbackHelper.State(
                     bundle.getIntegerArrayList(KEY_ERRORS_RECEIVED),
                     bundle.getIntegerArrayList(KEY_ACQUIRED_RECEIVED),
                     bundle.getInt(KEY_NUM_ACCEPTED),
-                    bundle.getInt(KEY_NUM_REJECTED));
+                    bundle.getInt(KEY_NUM_REJECTED),
+                    bundle.getBoolean(KEY_NEGATIVE_BUTTON_PRESSED));
+        }
+
+        @Override
+        public String toString() {
+            final StringBuilder sb = new StringBuilder();
+            sb.append("Accept: ").append(mNumAuthAccepted)
+                    .append(", Reject: ").append(mNumAuthRejected)
+                    .append(", Acquired Count: " ).append(mAcquiredReceived.size())
+                    .append(", Errors Count: ").append(mErrorsReceived.size())
+                    .append(", Negative pressed: ").append(mNegativeButtonPressed);
+            return sb.toString();
         }
     }
 
@@ -96,7 +103,7 @@
     }
 
     @Override
-    public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
+    public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
         mState.mNumAuthAccepted++;
         updateJournal();
     }
@@ -107,9 +114,14 @@
         updateJournal();
     }
 
-    public AuthenticationCallbackHelper(@NonNull Activity activity) {
+    void onNegativeButtonPressed() {
+        mState.mNegativeButtonPressed = true;
+        updateJournal();
+    }
+
+    public BiometricCallbackHelper(@NonNull Activity activity) {
         mActivity = activity;
-        mState = new State();
+        mState = new BiometricCallbackHelper.State();
 
         // Update with empty state. It's faster than waiting/retrying for null on CTS-side.
         updateJournal();
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricServiceState.java b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricServiceState.java
new file mode 100644
index 0000000..91f788a
--- /dev/null
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricServiceState.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import static com.android.server.biometrics.nano.BiometricServiceStateProto.*;
+
+import androidx.annotation.IntDef;
+import androidx.annotation.NonNull;
+
+import com.android.server.biometrics.nano.BiometricServiceStateProto;
+import com.android.server.biometrics.nano.SensorServiceStateProto;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
+import java.util.List;
+
+public class BiometricServiceState {
+
+    /**
+     * Defined in biometrics.proto
+     */
+    @IntDef({
+            STATE_AUTH_IDLE,
+            STATE_AUTH_CALLED,
+            STATE_AUTH_STARTED,
+            STATE_AUTH_PAUSED,
+            STATE_AUTH_PAUSED_RESUMING,
+            STATE_AUTH_PENDING_CONFIRM,
+            STATE_AUTHENTICATED_PENDING_SYSUI,
+            STATE_ERROR_PENDING_SYSUI,
+            STATE_SHOWING_DEVICE_CREDENTIAL})
+    @Retention(RetentionPolicy.SOURCE)
+    @interface AuthSessionState {}
+
+    @AuthSessionState public final int mState;
+    @NonNull public final SensorStates mSensorStates;
+
+    @NonNull
+    public static BiometricServiceState parseFrom(@NonNull BiometricServiceStateProto proto) {
+        final List<SensorStates> sensorStates = new ArrayList<>();
+        for (SensorServiceStateProto sensorServiceState : proto.sensorServiceStates) {
+            sensorStates.add(SensorStates.parseFrom(sensorServiceState));
+        }
+
+        @AuthSessionState int state = proto.authSessionState;
+
+        return new BiometricServiceState(SensorStates.merge(sensorStates), state);
+    }
+
+    private BiometricServiceState(@NonNull SensorStates sensorStates, @AuthSessionState int state) {
+        mSensorStates = sensorStates;
+        mState = state;
+    }
+
+    int getFirstAuthenticatingSensorId() {
+        for (int i = 0; i < mSensorStates.sensorStates.size(); i++) {
+            if (mSensorStates.sensorStates.valueAt(i).isBusy()) {
+                return mSensorStates.sensorStates.keyAt(i);
+            }
+        }
+        throw new IllegalStateException("No authenticating sensors");
+    }
+
+    @Override
+    public String toString() {
+        final StringBuilder sb = new StringBuilder();
+        sb.append(mSensorStates.toString());
+        return sb.toString();
+    }
+}
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricServiceTest.java b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricServiceTest.java
new file mode 100644
index 0000000..9898674
--- /dev/null
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricServiceTest.java
@@ -0,0 +1,504 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import static android.os.PowerManager.FULL_WAKE_LOCK;
+import static android.server.biometrics.Components.CLASS_2_BIOMETRIC_OR_CREDENTIAL_ACTIVITY;
+import static android.server.biometrics.Components.CLASS_3_BIOMETRIC_ACTIVITY;
+import static android.server.biometrics.SensorStates.SensorState;
+import static android.server.biometrics.SensorStates.UserState;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.android.server.biometrics.nano.BiometricServiceStateProto.STATE_AUTH_IDLE;
+import static com.android.server.biometrics.nano.BiometricServiceStateProto.STATE_AUTH_PAUSED;
+import static com.android.server.biometrics.nano.BiometricServiceStateProto.STATE_AUTH_PENDING_CONFIRM;
+import static com.android.server.biometrics.nano.BiometricServiceStateProto.STATE_AUTH_STARTED;
+import static com.android.server.biometrics.nano.BiometricServiceStateProto.STATE_SHOWING_DEVICE_CREDENTIAL;
+
+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.Assume.assumeTrue;
+
+import android.app.Instrumentation;
+import android.hardware.biometrics.BiometricManager;
+import android.hardware.biometrics.BiometricPrompt;
+import android.hardware.biometrics.BiometricTestSession;
+import android.hardware.biometrics.SensorProperties;
+import android.os.Bundle;
+import android.os.PowerManager;
+import android.platform.test.annotations.Presubmit;
+import android.server.wm.TestJournalProvider.TestJournal;
+import android.server.wm.TestJournalProvider.TestJournalContainer;
+import android.server.wm.UiDeviceUtils;
+import android.server.wm.WindowManagerState;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObject2;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import com.android.server.biometrics.nano.BiometricServiceStateProto;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Presubmit
+public class BiometricServiceTest extends BiometricTestBase {
+
+    private static final String TAG = "BiometricServiceTest";
+    private static final String DUMPSYS_BIOMETRIC = "dumpsys biometric --proto";
+
+    // Negative-side (left) buttons
+    private static final String BUTTON_ID_NEGATIVE = "button_negative";
+    private static final String BUTTON_ID_CANCEL = "button_cancel";
+    private static final String BUTTON_ID_USE_CREDENTIAL = "button_use_credential";
+
+    // Positive-side (right) buttons
+    private static final String BUTTON_ID_CONFIRM = "button_confirm";
+    private static final String BUTTON_ID_TRY_AGAIN = "button_try_again";
+
+    private static final String VIEW_ID_PASSWORD_FIELD = "lockPassword";
+
+    @NonNull private Instrumentation mInstrumentation;
+    @Nullable private BiometricManager mBiometricManager;
+    @NonNull private List<SensorProperties> mSensorProperties;
+    @NonNull private PowerManager.WakeLock mWakeLock;
+    @NonNull private UiDevice mDevice;
+
+    /**
+     * Retrieves the current states of all biometric sensor services (e.g. FingerprintService,
+     * FaceService, etc).
+     *
+     * Note that the states are retrieved from BiometricService, instead of individual services.
+     * This is because 1) BiometricService is the source of truth for all public API-facing things,
+     * and 2) This to include other information, such as UI states, etc as well.
+     */
+    @NonNull
+    private BiometricServiceState getCurrentState() throws Exception {
+        final byte[] dump = Utils.executeShellCommand(DUMPSYS_BIOMETRIC);
+        final BiometricServiceStateProto proto = BiometricServiceStateProto.parseFrom(dump);
+        return BiometricServiceState.parseFrom(proto);
+    }
+
+    @Nullable
+    private UiObject2 findView(String id) {
+        return mDevice.findObject(By.res(mBiometricManager.getUiPackage(), id));
+    }
+
+    private void findAndPressButton(String id) {
+        final UiObject2 button = findView(id);
+        assertNotNull(button);
+        button.click();
+    }
+
+    private void waitForState(@BiometricServiceState.AuthSessionState int state) throws Exception {
+        for (int i = 0; i < 10; i++) {
+            BiometricServiceState serviceState = getCurrentState();
+            if (serviceState.mState != state) {
+                Log.d(TAG, "Not in state " + state + " yet, current: " + serviceState.mState);
+                Thread.sleep(300);
+            } else {
+                return;
+            }
+        }
+        Log.d(TAG, "Timed out waiting for state to become: " + state);
+    }
+
+    private void waitForStateNotEqual(@BiometricServiceState.AuthSessionState int state)
+            throws Exception {
+        for (int i = 0; i < 10; i++) {
+            BiometricServiceState serviceState = getCurrentState();
+            if (serviceState.mState == state) {
+                Log.d(TAG, "Not out of state yet, current: " + serviceState.mState);
+                Thread.sleep(300);
+            } else {
+                return;
+            }
+        }
+        Log.d(TAG, "Timed out waiting for state to not equal: " + state);
+    }
+
+    @NonNull
+    private static BiometricCallbackHelper.State getCallbackState(@NonNull TestJournal journal) {
+        waitFor("Waiting for authentication callback",
+                () -> journal.extras.containsKey(BiometricCallbackHelper.KEY));
+
+        final Bundle bundle = journal.extras.getBundle(BiometricCallbackHelper.KEY);
+        if (bundle == null) {
+            return new BiometricCallbackHelper.State();
+        }
+
+        final BiometricCallbackHelper.State state =
+                BiometricCallbackHelper.State.fromBundle(bundle);
+
+        // Clear the extras since we want to wait for the journal to sync any new info the next
+        // time it's read
+        journal.extras.clear();
+
+        return state;
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        mInstrumentation = getInstrumentation();
+        mBiometricManager = mInstrumentation.getContext().getSystemService(BiometricManager.class);
+
+        mInstrumentation.getUiAutomation().adoptShellPermissionIdentity();
+        mDevice = UiDevice.getInstance(mInstrumentation);
+        mSensorProperties = mBiometricManager.getSensorProperties();
+
+        // Keep the screen on for the duration of each test, since BiometricPrompt goes away
+        // when screen turns off.
+        final PowerManager pm = mInstrumentation.getContext().getSystemService(PowerManager.class);
+        mWakeLock = pm.newWakeLock(FULL_WAKE_LOCK, TAG);
+        mWakeLock.acquire();
+    }
+
+    @After
+    public void cleanup() throws Exception {
+        mInstrumentation.waitForIdleSync();
+        waitForIdleService(getCurrentState().mSensorStates);
+
+        final BiometricServiceState state = getCurrentState();
+
+        for (int i = 0; i < state.mSensorStates.sensorStates.size(); i++) {
+            final SensorState sensorState = state.mSensorStates.sensorStates.valueAt(i);
+            for (int j = 0; j < sensorState.getUserStates().size(); j++) {
+                final UserState userState = sensorState.getUserStates().valueAt(j);
+                assertEquals(0, userState.numEnrolled);
+            }
+        }
+
+        mWakeLock.release();
+        mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
+    }
+
+    @Test
+    public void testEnroll() throws Exception {
+        for (SensorProperties prop : mSensorProperties) {
+            try (BiometricTestSession session
+                         = mBiometricManager.createTestSession(prop.getSensorId())){
+                enrollForSensor(session, prop.getSensorId());
+            }
+        }
+    }
+
+    @Test
+    public void testSensorPropertiesAndDumpsysMatch() throws Exception {
+        final BiometricServiceState state = getCurrentState();
+
+        assertEquals(mSensorProperties.size(), state.mSensorStates.sensorStates.size());
+        for (SensorProperties prop : mSensorProperties) {
+            assertTrue(state.mSensorStates.sensorStates.contains(prop.getSensorId()));
+        }
+    }
+
+    private void enrollForSensor(@NonNull BiometricTestSession session, int sensorId)
+            throws Exception {
+        final int userId = 0;
+
+        session.startEnroll(userId);
+        mInstrumentation.waitForIdleSync();
+        waitForBusySensor(getCurrentState().mSensorStates, sensorId);
+
+        session.finishEnroll(userId);
+        mInstrumentation.waitForIdleSync();
+        waitForIdleService(getCurrentState().mSensorStates);
+
+        final BiometricServiceState state = getCurrentState();
+        assertEquals(1, state.mSensorStates.sensorStates
+                .get(sensorId).getUserStates().get(userId).numEnrolled);
+    }
+
+    @Test
+    public void testBiometricOnly_authenticateFromForegroundActivity() throws Exception {
+        assumeTrue(!mSensorProperties.isEmpty());
+
+        // Turn screen on and dismiss keyguard
+        UiDeviceUtils.pressWakeupButton();
+        UiDeviceUtils.pressUnlockButton();
+
+        // Manually keep track and close the sessions, since we want to enroll all sensors before
+        // requesting auth.
+        final Map<Integer, BiometricTestSession> testSessions = new HashMap<>();
+
+        final int userId = 0;
+        for (SensorProperties prop : mSensorProperties) {
+            BiometricTestSession session = mBiometricManager.createTestSession(prop.getSensorId());
+            testSessions.put(prop.getSensorId(), session);
+            enrollForSensor(session, prop.getSensorId());
+        }
+
+        final TestJournal journal = TestJournalContainer.get(CLASS_3_BIOMETRIC_ACTIVITY);
+
+        // Launch test activity
+        launchActivity(CLASS_3_BIOMETRIC_ACTIVITY);
+        mWmState.waitForActivityState(CLASS_3_BIOMETRIC_ACTIVITY, WindowManagerState.STATE_RESUMED);
+        mInstrumentation.waitForIdleSync();
+
+        // At least one sensor should be authenticating
+        BiometricServiceState state = getCurrentState();
+        assertFalse(state.mSensorStates.areAllSensorsIdle());
+        // Find the sensor that's authenticating
+        final int runningSensorId = state.getFirstAuthenticatingSensorId();
+
+        // Nothing happened yet
+        BiometricCallbackHelper.State callbackState = getCallbackState(journal);
+        assertNotNull(callbackState);
+        assertEquals(0, callbackState.mNumAuthRejected);
+        assertEquals(0, callbackState.mNumAuthAccepted);
+        assertEquals(0, callbackState.mAcquiredReceived.size());
+        assertEquals(0, callbackState.mErrorsReceived.size());
+
+        // Auth and check again now
+        testSessions.get(runningSensorId).acceptAuthentication(userId);
+        mInstrumentation.waitForIdleSync();
+
+        waitForStateNotEqual(STATE_AUTH_STARTED);
+
+        state = getCurrentState();
+        if (state.mState == STATE_AUTH_PENDING_CONFIRM) {
+            findAndPressButton(BUTTON_ID_CONFIRM);
+            mInstrumentation.waitForIdleSync();
+            waitForState(STATE_AUTH_IDLE);
+        }
+
+        mInstrumentation.waitForIdleSync();
+        callbackState = getCallbackState(journal);
+        assertNotNull(callbackState);
+        assertTrue(callbackState.mErrorsReceived.isEmpty());
+        assertTrue(callbackState.mAcquiredReceived.isEmpty());
+        assertEquals(1, callbackState.mNumAuthAccepted);
+        assertEquals(0, callbackState.mNumAuthRejected);
+
+        // Cleanup
+        for (BiometricTestSession session : testSessions.values()) {
+            session.close();
+        }
+    }
+
+    @Test
+    public void testBiometricOnly_rejectThenErrorFromForegroundActivity() throws Exception {
+        assumeTrue(!mSensorProperties.isEmpty());
+
+        // Turn screen on and dismiss keyguard
+        UiDeviceUtils.pressWakeupButton();
+        UiDeviceUtils.pressUnlockButton();
+
+        // Manually keep track and close the sessions, since we want to enroll all sensors before
+        // requesting auth.
+        final Map<Integer, BiometricTestSession> testSessions = new HashMap<>();
+
+        final int userId = 0;
+        for (SensorProperties prop : mSensorProperties) {
+            BiometricTestSession session = mBiometricManager.createTestSession(prop.getSensorId());
+            testSessions.put(prop.getSensorId(), session);
+            enrollForSensor(session, prop.getSensorId());
+        }
+
+        final TestJournal journal =
+                TestJournalContainer.get(CLASS_3_BIOMETRIC_ACTIVITY);
+
+        // Launch test activity
+        launchActivity(CLASS_3_BIOMETRIC_ACTIVITY);
+        mWmState.waitForActivityState(CLASS_3_BIOMETRIC_ACTIVITY, WindowManagerState.STATE_RESUMED);
+        mInstrumentation.waitForIdleSync();
+        BiometricCallbackHelper.State callbackState = getCallbackState(journal);
+        assertNotNull(callbackState);
+
+        BiometricServiceState state = getCurrentState();
+        assertFalse(state.mSensorStates.areAllSensorsIdle());
+        // Find the sensor that's authenticating
+        final int runningSensorId = state.getFirstAuthenticatingSensorId();
+
+        // Biometric rejected
+        testSessions.get(runningSensorId).rejectAuthentication(userId);
+        mInstrumentation.waitForIdleSync();
+        callbackState = getCallbackState(journal);
+        assertNotNull(callbackState);
+        assertEquals(1, callbackState.mNumAuthRejected);
+        assertEquals(0, callbackState.mNumAuthAccepted);
+        assertEquals(0, callbackState.mAcquiredReceived.size());
+        assertEquals(0, callbackState.mErrorsReceived.size());
+
+        state = getCurrentState();
+        if (state.mState == STATE_AUTH_PAUSED) {
+            findAndPressButton(BUTTON_ID_TRY_AGAIN);
+            mInstrumentation.waitForIdleSync();
+            waitForState(STATE_AUTH_STARTED);
+        }
+
+        // Send an error
+        testSessions.get(runningSensorId).notifyError(userId,
+                BiometricPrompt.BIOMETRIC_ERROR_CANCELED);
+        mInstrumentation.waitForIdleSync();
+        callbackState = getCallbackState(journal);
+        assertNotNull(callbackState);
+        assertEquals(1, callbackState.mNumAuthRejected);
+        assertEquals(0, callbackState.mNumAuthAccepted);
+        assertEquals(0, callbackState.mAcquiredReceived.size());
+        assertEquals(1, callbackState.mErrorsReceived.size());
+        assertEquals(BiometricPrompt.BIOMETRIC_ERROR_CANCELED,
+                (int) callbackState.mErrorsReceived.get(0));
+
+        // Authentication lifecycle is done
+        assertTrue(getCurrentState().mSensorStates.areAllSensorsIdle());
+
+        // Cleanup
+        for (BiometricTestSession session : testSessions.values()) {
+            session.close();
+        }
+    }
+
+    @Test
+    public void testBiometricOnly_negativeButtonInvoked() throws Exception {
+        assumeTrue(!mSensorProperties.isEmpty());
+
+        // Turn screen on and dismiss keyguard
+        UiDeviceUtils.pressWakeupButton();
+        UiDeviceUtils.pressUnlockButton();
+
+        // Manually keep track and close the sessions, since we want to enroll all sensors before
+        // requesting auth.
+        final Map<Integer, BiometricTestSession> testSessions = new HashMap<>();
+
+        for (SensorProperties prop : mSensorProperties) {
+            BiometricTestSession session = mBiometricManager.createTestSession(prop.getSensorId());
+            testSessions.put(prop.getSensorId(), session);
+            enrollForSensor(session, prop.getSensorId());
+        }
+
+        final TestJournal journal = TestJournalContainer.get(CLASS_3_BIOMETRIC_ACTIVITY);
+
+        // Launch test activity
+        launchActivity(CLASS_3_BIOMETRIC_ACTIVITY);
+        mWmState.waitForActivityState(CLASS_3_BIOMETRIC_ACTIVITY, WindowManagerState.STATE_RESUMED);
+        mInstrumentation.waitForIdleSync();
+        BiometricCallbackHelper.State callbackState = getCallbackState(journal);
+        assertNotNull(callbackState);
+
+        BiometricServiceState state = getCurrentState();
+        assertFalse(state.mSensorStates.areAllSensorsIdle());
+        assertFalse(callbackState.mNegativeButtonPressed);
+
+        // Press the negative button
+        findAndPressButton(BUTTON_ID_NEGATIVE);
+
+        callbackState = getCallbackState(journal);
+        assertTrue(callbackState.mNegativeButtonPressed);
+        assertEquals(0, callbackState.mNumAuthRejected);
+        assertEquals(0, callbackState.mNumAuthAccepted);
+        assertEquals(0, callbackState.mAcquiredReceived.size());
+        assertEquals(0, callbackState.mErrorsReceived.size());
+
+        // All sensors are idle, BiometricService is idle
+        state = getCurrentState();
+        assertTrue(state.mSensorStates.areAllSensorsIdle());
+        assertEquals(STATE_AUTH_IDLE, state.mState);
+
+        // Cleanup
+        for (BiometricTestSession session : testSessions.values()) {
+            session.close();
+        }
+    }
+
+    @Test
+    public void testBiometricOrCredential_credentialButtonInvoked() throws Exception {
+        // Turn screen on and dismiss keyguard
+        UiDeviceUtils.pressWakeupButton();
+        UiDeviceUtils.pressUnlockButton();
+
+        // Manually keep track and close the sessions, since we want to enroll all sensors before
+        // requesting auth.
+        final Map<Integer, BiometricTestSession> testSessions = new HashMap<>();
+
+        for (SensorProperties prop : mSensorProperties) {
+            BiometricTestSession session = mBiometricManager.createTestSession(prop.getSensorId());
+            testSessions.put(prop.getSensorId(), session);
+            enrollForSensor(session, prop.getSensorId());
+        }
+
+        final LockScreenSession lockscreenSession = new LockScreenSession();
+        lockscreenSession.setLockCredential();
+
+        final TestJournal journal = TestJournalContainer
+                .get(CLASS_2_BIOMETRIC_OR_CREDENTIAL_ACTIVITY);
+
+        // Launch test activity
+        launchActivity(CLASS_2_BIOMETRIC_OR_CREDENTIAL_ACTIVITY);
+        mWmState.waitForActivityState(CLASS_2_BIOMETRIC_OR_CREDENTIAL_ACTIVITY,
+                WindowManagerState.STATE_RESUMED);
+        mInstrumentation.waitForIdleSync();
+        BiometricCallbackHelper.State callbackState;
+
+        BiometricServiceState state = getCurrentState();
+        if (!mSensorProperties.isEmpty()) {
+            waitForState(STATE_AUTH_STARTED);
+            assertFalse(state.mSensorStates.areAllSensorsIdle());
+            // Press the credential button
+            findAndPressButton(BUTTON_ID_USE_CREDENTIAL);
+            callbackState = getCallbackState(journal);
+            assertFalse(callbackState.mNegativeButtonPressed);
+            assertEquals(0, callbackState.mNumAuthRejected);
+            assertEquals(0, callbackState.mNumAuthAccepted);
+            assertEquals(0, callbackState.mAcquiredReceived.size());
+            assertEquals(0, callbackState.mErrorsReceived.size());
+            waitForState(STATE_SHOWING_DEVICE_CREDENTIAL);
+        }
+
+        // All sensors are idle, BiometricService is waiting for device credential
+        state = getCurrentState();
+        assertTrue(state.mSensorStates.areAllSensorsIdle());
+        assertEquals(STATE_SHOWING_DEVICE_CREDENTIAL, state.mState);
+
+        // Wait for any animations to complete. Ideally, this should be reflected in
+        // STATE_SHOWING_DEVICE_CREDENTIAL, but SysUI and BiometricService are different processes
+        // so we'd need to add some additional plumbing. We can improve this in the future.
+        Thread.sleep(1000);
+
+        // Enter credential. AuthSession done, authentication callback received
+        final UiObject2 passwordField = findView(VIEW_ID_PASSWORD_FIELD);
+        passwordField.click();
+        passwordField.setText(LOCK_CREDENTIAL);
+        mDevice.pressEnter();
+        waitForState(STATE_AUTH_IDLE);
+
+        state = getCurrentState();
+        assertEquals(STATE_AUTH_IDLE, state.mState);
+        callbackState = getCallbackState(journal);
+        assertEquals(0, callbackState.mNumAuthRejected);
+        assertEquals(1, callbackState.mNumAuthAccepted);
+        assertEquals(0, callbackState.mAcquiredReceived.size());
+        assertEquals(0, callbackState.mErrorsReceived.size());
+
+        // Cleanup
+        for (BiometricTestSession session : testSessions.values()) {
+            session.close();
+        }
+        lockscreenSession.close();
+    }
+}
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricTestBase.java b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricTestBase.java
new file mode 100644
index 0000000..8a01644
--- /dev/null
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricTestBase.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import android.server.wm.ActivityManagerTestBase;
+import android.server.wm.Condition;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+
+import java.util.function.BooleanSupplier;
+
+/**
+ * Base class for biometric tests, containing common useful logic.
+ */
+public class BiometricTestBase extends ActivityManagerTestBase {
+
+    private static final String TAG = "BiometricTestBase";
+
+    /**
+     * Waits for the service to become idle
+     * @param state Current service state
+     * @throws Exception
+     */
+    protected void waitForIdleService(@NonNull SensorStates state) throws Exception {
+        for (int i = 0; i < 10; i++) {
+            if (!state.areAllSensorsIdle()) {
+                Log.d(TAG, "Not idle yet..");
+                Thread.sleep(300);
+            } else {
+                return;
+            }
+        }
+        Log.d(TAG, "Timed out waiting for idle");
+    }
+
+    protected void waitForBusySensor(@NonNull SensorStates state, int sensorId) throws Exception {
+        for (int i = 0; i < 10; i++) {
+            if (!state.sensorStates.get(sensorId).isBusy()) {
+                Log.d(TAG, "Not busy yet..");
+                Thread.sleep(300);
+            } else {
+                return;
+            }
+        }
+        Log.d(TAG, "Timed out waiting to become busy");
+    }
+
+    protected static void waitFor(@NonNull String message, @NonNull BooleanSupplier condition) {
+        Condition.waitFor(new Condition<>(message, condition)
+                .setRetryIntervalMs(500)
+                .setRetryLimit(20));
+    }
+}
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/Components.java b/tests/framework/base/biometrics/src/android/server/biometrics/Components.java
new file mode 100644
index 0000000..67458d4
--- /dev/null
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/Components.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import android.content.ComponentName;
+import android.server.wm.component.ComponentsBase;
+
+public class Components extends ComponentsBase {
+    public static final ComponentName CLASS_2_BIOMETRIC_OR_CREDENTIAL_ACTIVITY =
+            component("Class2BiometricOrCredentialActivity");
+    public static final ComponentName CLASS_3_BIOMETRIC_ACTIVITY =
+            component("Class3BiometricActivity");
+
+    private static ComponentName component(String className) {
+        return component(Components.class, className);
+    }
+}
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/SensorStates.java b/tests/framework/base/biometrics/src/android/server/biometrics/SensorStates.java
new file mode 100644
index 0000000..1e80d7d
--- /dev/null
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/SensorStates.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2020 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.server.biometrics;
+
+import android.util.SparseArray;
+
+import androidx.annotation.NonNull;
+
+import com.android.server.biometrics.nano.SensorServiceStateProto;
+import com.android.server.biometrics.nano.SensorStateProto;
+import com.android.server.biometrics.nano.UserStateProto;
+
+import java.util.List;
+
+/**
+ * The overall state for a list of sensors. This could be either:
+ *
+ * 1) A list of sensors from a single instance of a <Biometric>Service such as
+ * {@link com.android.server.biometrics.sensors.fingerprint.FingerprintService} or
+ * {@link com.android.server.biometrics.sensors.face.FaceService}, or
+ *
+ * 2) A list of sensors from multiple instances of <Biometric>Services.
+ *
+ * Note that a single service may provide multiple sensors.
+ */
+public class SensorStates {
+
+    @NonNull public final SparseArray<SensorState> sensorStates;
+
+    public static class SensorState {
+        private final boolean mIsBusy;
+        @NonNull private final SparseArray<UserState> mUserStates;
+
+        public SensorState(boolean isBusy, @NonNull SparseArray<UserState> userStates) {
+            this.mIsBusy = isBusy;
+            this.mUserStates = userStates;
+        }
+
+        public boolean isBusy() {
+            return mIsBusy;
+        }
+
+        @NonNull public SparseArray<UserState> getUserStates() {
+            return mUserStates;
+        }
+    }
+
+    public static class UserState {
+        public final int numEnrolled;
+
+        public UserState(int numEnrolled) {
+            this.numEnrolled = numEnrolled;
+        }
+    }
+
+    @NonNull
+    public static SensorStates parseFrom(@NonNull SensorServiceStateProto proto) {
+        final SparseArray<SensorState> sensorStates = new SparseArray<>();
+
+        for (SensorStateProto sensorStateProto : proto.sensorStates) {
+            final SparseArray<UserState> userStates = new SparseArray<>();
+            for (UserStateProto userStateProto : sensorStateProto.userStates) {
+                userStates.put(userStateProto.userId, new UserState(userStateProto.numEnrolled));
+            }
+
+            final SensorState sensorState = new SensorState(sensorStateProto.isBusy, userStates);
+            sensorStates.put(sensorStateProto.sensorId, sensorState);
+        }
+
+        return new SensorStates(sensorStates);
+    }
+
+    /**
+     * Combines multiple {@link SensorStates} into a single instance.
+     */
+    @NonNull
+    public static SensorStates merge(@NonNull List<SensorStates> sensorServiceStates) {
+        final SparseArray<SensorState> sensorStates = new SparseArray<>();
+
+        for (SensorStates sensorServiceState : sensorServiceStates) {
+            for (int i = 0; i < sensorServiceState.sensorStates.size(); i++) {
+                final int sensorId = sensorServiceState.sensorStates.keyAt(i);
+                final SensorState sensorState = sensorServiceState.sensorStates.valueAt(i);
+                if (sensorStates.contains(sensorId)) {
+                    throw new IllegalStateException("Duplicate sensorId found: " + sensorId);
+                }
+
+                sensorStates.put(sensorId, sensorState);
+            }
+        }
+
+        return new SensorStates(sensorStates);
+    }
+
+    public boolean areAllSensorsIdle() {
+        for (int i = 0; i < sensorStates.size(); i++) {
+            if (sensorStates.valueAt(i).isBusy()) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private SensorStates(@NonNull SparseArray<SensorState> sensorStates) {
+        this.sensorStates = sensorStates;
+    }
+
+    @Override
+    public String toString() {
+        final StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < sensorStates.size(); i++) {
+            sb.append("SensorId: ").append(sensorStates.keyAt(i));
+            sb.append(", busy: ").append(sensorStates.get(i).isBusy());
+
+            final SparseArray<UserState> userStates = sensorStates.get(i).getUserStates();
+            for (int j = 0; j < userStates.size(); j++) {
+                sb.append(", UserId: ").append(userStates.keyAt(j));
+                sb.append(", NumEnrolled: ").append(userStates.get(j).numEnrolled);
+            }
+
+            sb.append(" | ");
+        }
+        return sb.toString();
+    }
+}
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java b/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintCallbackHelper.java
similarity index 96%
rename from tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java
rename to tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintCallbackHelper.java
index c73cfb5..21d3ff0 100644
--- a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/AuthenticationCallbackHelper.java
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintCallbackHelper.java
@@ -34,7 +34,7 @@
  * authentication.
  */
 @SuppressWarnings("deprecation")
-public class AuthenticationCallbackHelper extends FingerprintManager.AuthenticationCallback {
+public class FingerprintCallbackHelper extends FingerprintManager.AuthenticationCallback {
 
     public static final String KEY = "key_auth_callback";
 
@@ -107,7 +107,7 @@
         updateJournal();
     }
 
-    public AuthenticationCallbackHelper(@NonNull Activity activity) {
+    public FingerprintCallbackHelper(@NonNull Activity activity) {
         mActivity = activity;
         mState = new State();
 
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceState.java b/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceState.java
deleted file mode 100644
index af5ae8f..0000000
--- a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceState.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2020 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.server.biometrics.fingerprint;
-
-import android.util.SparseArray;
-
-import androidx.annotation.NonNull;
-
-import com.android.server.biometrics.fingerprint.nano.FingerprintServiceStateProto;
-import com.android.server.biometrics.fingerprint.nano.SensorStateProto;
-import com.android.server.biometrics.fingerprint.nano.UserStateProto;
-
-public class FingerprintServiceState {
-
-    @NonNull final SparseArray<SensorState> sensorStates;
-
-    public static class SensorState {
-        private final boolean mIsBusy;
-        @NonNull private final SparseArray<UserState> mUserStates;
-
-        public SensorState(boolean isBusy, @NonNull SparseArray<UserState> userStates) {
-            this.mIsBusy = isBusy;
-            this.mUserStates = userStates;
-        }
-
-        boolean isBusy() {
-            return mIsBusy;
-        }
-
-        @NonNull SparseArray<UserState> getUserStates() {
-            return mUserStates;
-        }
-    }
-
-    public static class UserState {
-        final int numEnrolled;
-
-        public UserState(int numEnrolled) {
-            this.numEnrolled = numEnrolled;
-        }
-    }
-
-    @NonNull
-    public static FingerprintServiceState parseFrom(@NonNull FingerprintServiceStateProto proto) {
-        final SparseArray<SensorState> sensorStates = new SparseArray<>();
-
-        for (SensorStateProto sensorStateProto : proto.sensorStates) {
-            final SparseArray<UserState> userStates = new SparseArray<>();
-            for (UserStateProto userStateProto : sensorStateProto.userStates) {
-                userStates.put(userStateProto.userId, new UserState(userStateProto.numEnrolled));
-            }
-
-            final SensorState sensorState = new SensorState(sensorStateProto.isBusy, userStates);
-            sensorStates.put(sensorStateProto.sensorId, sensorState);
-        }
-
-        return new FingerprintServiceState(sensorStates);
-    }
-
-    public boolean areAllSensorsIdle() {
-        for (int i = 0; i < sensorStates.size(); i++) {
-            if (sensorStates.valueAt(i).isBusy()) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    private FingerprintServiceState(@NonNull SparseArray<SensorState> sensorStates) {
-        this.sensorStates = sensorStates;
-    }
-
-    @Override
-    public String toString() {
-        final StringBuilder sb = new StringBuilder();
-        for (int i = 0; i < sensorStates.size(); i++) {
-            sb.append("SensorId: ").append(sensorStates.keyAt(i));
-            sb.append(", busy: ").append(sensorStates.get(i).isBusy());
-
-            final SparseArray<UserState> userStates = sensorStates.get(i).getUserStates();
-            for (int j = 0; j < userStates.size(); j++) {
-                sb.append(", UserId: ").append(userStates.keyAt(j));
-                sb.append(", NumEnrolled: ").append(userStates.get(j).numEnrolled);
-            }
-
-            sb.append(" | ");
-        }
-        return sb.toString();
-    }
-}
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceTest.java b/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceTest.java
index f009d095..d5d8657 100644
--- a/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceTest.java
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/fingerprint/FingerprintServiceTest.java
@@ -16,9 +16,9 @@
 
 package android.server.biometrics.fingerprint;
 
+import static android.server.biometrics.SensorStates.SensorState;
+import static android.server.biometrics.SensorStates.UserState;
 import static android.server.biometrics.fingerprint.Components.AUTH_ON_CREATE_ACTIVITY;
-import static android.server.biometrics.fingerprint.FingerprintServiceState.SensorState;
-import static android.server.biometrics.fingerprint.FingerprintServiceState.UserState;
 
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
@@ -34,19 +34,18 @@
 import android.hardware.fingerprint.FingerprintManager;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
+import android.server.biometrics.BiometricTestBase;
+import android.server.biometrics.SensorStates;
 import android.server.biometrics.Utils;
-import android.server.wm.ActivityManagerTestBase;
-import android.server.wm.Condition;
 import android.server.wm.TestJournalProvider.TestJournal;
 import android.server.wm.TestJournalProvider.TestJournalContainer;
 import android.server.wm.UiDeviceUtils;
 import android.server.wm.WindowManagerState;
-import android.util.Log;
 
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 
-import com.android.server.biometrics.fingerprint.nano.FingerprintServiceStateProto;
+import com.android.server.biometrics.nano.SensorServiceStateProto;
 
 import org.junit.After;
 import org.junit.Before;
@@ -54,40 +53,32 @@
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.function.BooleanSupplier;
 
 @SuppressWarnings("deprecation")
 @Presubmit
-public class FingerprintServiceTest extends ActivityManagerTestBase {
+public class FingerprintServiceTest extends BiometricTestBase {
     private static final String TAG = "FingerprintServiceTest";
 
     private static final String DUMPSYS_FINGERPRINT = "dumpsys fingerprint --proto --state";
 
-    private static FingerprintServiceState getCurrentState() throws Exception {
+    protected SensorStates getCurrentState() throws Exception {
         final byte[] dump = Utils.executeShellCommand(DUMPSYS_FINGERPRINT);
-        FingerprintServiceStateProto proto = FingerprintServiceStateProto.parseFrom(dump);
-        return FingerprintServiceState.parseFrom(proto);
-    }
-
-    private static void waitFor(@NonNull String message, @NonNull BooleanSupplier condition) {
-        Condition.waitFor(new Condition<>(message, condition)
-                .setRetryIntervalMs(500)
-                .setRetryLimit(20));
+        SensorServiceStateProto proto = SensorServiceStateProto.parseFrom(dump);
+        return SensorStates.parseFrom(proto);
     }
 
     @Nullable
-    private static AuthenticationCallbackHelper.State getCallbackState(
-            @NonNull TestJournal journal) {
+    private static FingerprintCallbackHelper.State getCallbackState(@NonNull TestJournal journal) {
         waitFor("Waiting for authentication callback",
-                () -> journal.extras.containsKey(AuthenticationCallbackHelper.KEY));
+                () -> journal.extras.containsKey(FingerprintCallbackHelper.KEY));
 
-        final Bundle bundle = journal.extras.getBundle(AuthenticationCallbackHelper.KEY);
+        final Bundle bundle = journal.extras.getBundle(FingerprintCallbackHelper.KEY);
         if (bundle == null) {
             return null;
         }
 
-        final AuthenticationCallbackHelper.State state =
-                AuthenticationCallbackHelper.State.fromBundle(bundle);
+        final FingerprintCallbackHelper.State state =
+                FingerprintCallbackHelper.State.fromBundle(bundle);
 
         // Clear the extras since we want to wait for the journal to sync any new info the next
         // time it's read
@@ -96,37 +87,6 @@
         return state;
     }
 
-    private static void waitForIdleService() throws Exception {
-        for (int i = 0; i < 10; i++) {
-            final FingerprintServiceState serviceState = getCurrentState();
-            if (!serviceState.areAllSensorsIdle()) {
-                Log.d(TAG, "Not idle yet..");
-                Thread.sleep(300);
-            } else {
-                return;
-            }
-        }
-        Log.d(TAG, "Timed out waiting for idle");
-    }
-
-    /**
-     * This method should only be used when we know that at least one sensor must be busy, such
-     * as when authenticate() is invoked.
-     *
-     * @return The first sensor that's non-idle.
-     * @throws IllegalStateException if no sensors are busy.
-     */
-    public static int getFirstNonIdleSensor() throws Exception {
-        final FingerprintServiceState state = getCurrentState();
-        for (int i = 0; i < state.sensorStates.size(); i++) {
-            if (state.sensorStates.valueAt(i).isBusy()) {
-                return state.sensorStates.keyAt(i);
-            }
-        }
-
-        throw new IllegalStateException("All sensors idle");
-    }
-
     @NonNull private Instrumentation mInstrumentation;
     @Nullable private FingerprintManager mFingerprintManager;
     @NonNull private List<SensorProperties> mSensorProperties;
@@ -150,8 +110,7 @@
 
     @After
     public void cleanup() throws Exception {
-        if (mFingerprintManager == null || mSensorProperties == null
-                || mSensorProperties.isEmpty()) {
+        if (mFingerprintManager == null || mSensorProperties.isEmpty()) {
             // The tests were skipped anyway, nothing to clean up. Maybe we can use JUnit test
             // annotations in the future.
             return;
@@ -159,11 +118,11 @@
 
 
         mInstrumentation.waitForIdleSync();
-        waitForIdleService();
+        waitForIdleService(getCurrentState());
 
-        final FingerprintServiceState serviceState = getCurrentState();
-        for (int i = 0; i < serviceState.sensorStates.size(); i++) {
-            final SensorState sensorState = serviceState.sensorStates.valueAt(i);
+        final SensorStates sensorStates = getCurrentState();
+        for (int i = 0; i < sensorStates.sensorStates.size(); i++) {
+            final SensorState sensorState = sensorStates.sensorStates.valueAt(i);
             for (int j = 0; j < sensorState.getUserStates().size(); j++) {
                 final UserState userState = sensorState.getUserStates().valueAt(j);
                 assertEquals(0, userState.numEnrolled);
@@ -188,16 +147,16 @@
 
         session.startEnroll(userId);
         mInstrumentation.waitForIdleSync();
-        waitForIdleService();
+        waitForIdleService(getCurrentState());
 
         session.finishEnroll(userId);
         mInstrumentation.waitForIdleSync();
-        waitForIdleService();
+        waitForIdleService(getCurrentState());
 
-        final FingerprintServiceState serviceState = getCurrentState();
+        final SensorStates sensorStates = getCurrentState();
 
         // The (sensorId, userId) has one finger enrolled.
-        assertEquals(1, serviceState.sensorStates
+        assertEquals(1, sensorStates.sensorStates
                 .get(sensorId).getUserStates().get(userId).numEnrolled);
     }
 
@@ -219,11 +178,11 @@
 
             session.startEnroll(userId);
             mInstrumentation.waitForIdleSync();
-            waitForIdleService();
+            waitForIdleService(getCurrentState());
 
             session.finishEnroll(userId);
             mInstrumentation.waitForIdleSync();
-            waitForIdleService();
+            waitForIdleService(getCurrentState());
         }
 
         final TestJournal journal = TestJournalContainer.get(AUTH_ON_CREATE_ACTIVITY);
@@ -237,7 +196,7 @@
         assertFalse(getCurrentState().areAllSensorsIdle());
 
         // Nothing happened yet
-        AuthenticationCallbackHelper.State callbackState = getCallbackState(journal);
+        FingerprintCallbackHelper.State callbackState = getCallbackState(journal);
         assertNotNull(callbackState);
         assertEquals(0, callbackState.mNumAuthRejected);
         assertEquals(0, callbackState.mNumAuthAccepted);
@@ -278,11 +237,11 @@
 
             session.startEnroll(userId);
             mInstrumentation.waitForIdleSync();
-            waitForIdleService();
+            waitForIdleService(getCurrentState());
 
             session.finishEnroll(userId);
             mInstrumentation.waitForIdleSync();
-            waitForIdleService();
+            waitForIdleService(getCurrentState());
         }
 
         final TestJournal journal = TestJournalContainer.get(AUTH_ON_CREATE_ACTIVITY);
@@ -291,7 +250,7 @@
         launchActivity(AUTH_ON_CREATE_ACTIVITY);
         mWmState.waitForActivityState(AUTH_ON_CREATE_ACTIVITY, WindowManagerState.STATE_RESUMED);
         mInstrumentation.waitForIdleSync();
-        AuthenticationCallbackHelper.State callbackState = getCallbackState(journal);
+        FingerprintCallbackHelper.State callbackState = getCallbackState(journal);
         assertNotNull(callbackState);
 
         // Fingerprint rejected
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index a2e4042..6536db5 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -213,7 +213,7 @@
     protected static final String MSG_NO_MOCK_IME =
             "MockIme cannot be used for devices that do not support installable IMEs";
 
-    private static final String LOCK_CREDENTIAL = "1234";
+    protected static final String LOCK_CREDENTIAL = "1234";
 
     private static final int UI_MODE_TYPE_MASK = 0x0f;
     private static final int UI_MODE_TYPE_VR_HEADSET = 0x07;