Merge changes from topic "presubmit-am-907fdfc5a90b43a49557602baf5c6723"

* changes:
  [automerge] Add unit tests 2p: e62ae09e52
  Add unit tests
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/RangingUtilsTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/RangingUtilsTest.java
index ebe72b3..29f8d4e 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/RangingUtilsTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/RangingUtilsTest.java
@@ -48,8 +48,10 @@
         // RSSI expected at 1 meter based on the calibrated tx field of -41dBm
         // Using params: distance (m), int calibratedTxPower (dBm),
         int rssi = RangingUtils.rssiFromTargetDistance(1.0, -41);
+        int rssi1 = RangingUtils.rssiFromTargetDistance(0.0, -41);
 
         assertThat(rssi).isEqualTo(-82);
+        assertThat(rssi1).isEqualTo(-41);
     }
 
     @Test
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/StringUtilsTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/StringUtilsTest.java
index 0f5877b..6b20fdd 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/StringUtilsTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/ble/util/StringUtilsTest.java
@@ -18,10 +18,16 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.os.ParcelUuid;
+import android.util.SparseArray;
+
 import com.android.server.nearby.common.ble.BleRecord;
 
 import org.junit.Test;
 
+import java.util.HashMap;
+import java.util.Map;
+
 public class StringUtilsTest {
     // iBeacon (Apple) Packet 1
     private static final byte[] BEACON = {
@@ -100,6 +106,12 @@
     @Test
     public void testToString() {
         BleRecord record = BleRecord.parseFromBytes(BEACON);
+        assertThat(StringUtils.toString((SparseArray<byte[]>) null)).isEqualTo("null");
+        assertThat(StringUtils.toString(new SparseArray<byte[]>())).isEqualTo("{}");
+        assertThat(StringUtils
+                .toString((Map<ParcelUuid, byte[]>) null)).isEqualTo("null");
+        assertThat(StringUtils
+                .toString(new HashMap<ParcelUuid, byte[]>())).isEqualTo("{}");
         assertThat(StringUtils.toString(record.getManufacturerSpecificData()))
                 .isEqualTo("{76=[2, 21, -9, -126, 109, -90, 79, -94, 78, -104, -128,"
                         + " 36, -68, 91, 113, -32, -119, 62, 68, -48, 37, 34, -77]}");
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/AdditionalDataEncoderTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/AdditionalDataEncoderTest.java
index 28d2fca..cf40fc6 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/AdditionalDataEncoderTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/AdditionalDataEncoderTest.java
@@ -63,6 +63,21 @@
 
     @Test
     @SdkSuppress(minSdkVersion = 32, codeName = "T")
+    public void inputNullSecretKeyToEncode_mustThrowException() {
+        byte[] rawData = base16().decode("00112233445566778899AABBCCDDEEFF");
+
+        GeneralSecurityException exception =
+                assertThrows(
+                        GeneralSecurityException.class,
+                        () -> AdditionalDataEncoder.encodeAdditionalDataPacket(null, rawData));
+
+        assertThat(exception)
+                .hasMessageThat()
+                .contains("Incorrect secret for encoding additional data packet");
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 32, codeName = "T")
     public void inputIncorrectKeySizeToEncode_mustThrowException() {
         byte[] secret = new byte[KEY_LENGTH - 1];
         byte[] rawData = base16().decode("00112233445566778899AABBCCDDEEFF");
@@ -79,6 +94,54 @@
 
     @Test
     @SdkSuppress(minSdkVersion = 32, codeName = "T")
+    public void inputNullAdditionalDataToEncode_mustThrowException()
+            throws GeneralSecurityException {
+        byte[] secret = AesCtrMultipleBlockEncryption.generateKey();
+
+        GeneralSecurityException exception =
+                assertThrows(
+                        GeneralSecurityException.class,
+                        () -> AdditionalDataEncoder.encodeAdditionalDataPacket(secret, null));
+
+        assertThat(exception)
+                .hasMessageThat()
+                .contains("Invalid data for encoding additional data packet");
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 32, codeName = "T")
+    public void inputInvalidAdditionalDataSizeToEncode_mustThrowException()
+            throws GeneralSecurityException {
+        byte[] secret = AesCtrMultipleBlockEncryption.generateKey();
+        byte[] rawData = base16().decode("");
+        GeneralSecurityException exception =
+                assertThrows(
+                        GeneralSecurityException.class,
+                        () -> AdditionalDataEncoder.encodeAdditionalDataPacket(secret, rawData));
+
+        assertThat(exception)
+                .hasMessageThat()
+                .contains("Invalid data for encoding additional data packet");
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 32, codeName = "T")
+    public void inputTooLargeAdditionalDataSizeToEncode_mustThrowException()
+            throws GeneralSecurityException {
+        byte[] secret = AesCtrMultipleBlockEncryption.generateKey();
+        byte[] rawData = new byte[MAX_LENGTH_OF_DATA + 1];
+        GeneralSecurityException exception =
+                assertThrows(
+                        GeneralSecurityException.class,
+                        () -> AdditionalDataEncoder.encodeAdditionalDataPacket(secret, rawData));
+
+        assertThat(exception)
+                .hasMessageThat()
+                .contains("Invalid data for encoding additional data packet");
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 32, codeName = "T")
     public void inputIncorrectKeySizeToDecode_mustThrowException() {
         byte[] secret = new byte[KEY_LENGTH - 1];
         byte[] packet = base16().decode("01234567890123456789");
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothAudioPairerTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothAudioPairerTest.java
index 0a56f2f..6871024 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothAudioPairerTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothAudioPairerTest.java
@@ -84,6 +84,23 @@
     }
 
     @SdkSuppress(minSdkVersion = 32, codeName = "T")
+    public void getDevice() {
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        try {
+            assertThat(new BluetoothAudioPairer(
+                    context,
+                    BLUETOOTH_DEVICE,
+                    Preferences.builder().build(),
+                    new EventLoggerWrapper(new TestEventLogger()),
+                    null /* KeyBasePairingInfo */,
+                    null /*PasskeyConfirmationHandler */,
+                    new TimingLogger(EVENT_NAME, Preferences.builder().build())).getDevice())
+                    .isEqualTo(BLUETOOTH_DEVICE);
+        } catch (PairingException e) {
+        }
+    }
+
+    @SdkSuppress(minSdkVersion = 32, codeName = "T")
     public void testBluetoothAudioPairerUnpairNoCrash() {
         Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
         try {
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothClassicPairerTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothClassicPairerTest.java
new file mode 100644
index 0000000..6f55f6a
--- /dev/null
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/bluetooth/fastpair/BluetoothClassicPairerTest.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.nearby.common.bluetooth.fastpair;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertThrows;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+
+public class BluetoothClassicPairerTest {
+    @Mock
+    PasskeyConfirmationHandler mPasskeyConfirmationHandler;
+    private static final BluetoothDevice BLUETOOTH_DEVICE = BluetoothAdapter.getDefaultAdapter()
+            .getRemoteDevice("11:22:33:44:55:66");
+    private  BluetoothClassicPairer mBluetoothClassicPairer;
+
+    @Before
+    public void setUp() {
+        mBluetoothClassicPairer = new BluetoothClassicPairer(
+                ApplicationProvider.getApplicationContext(),
+                BLUETOOTH_DEVICE,
+                Preferences.builder().build(),
+                mPasskeyConfirmationHandler);
+    }
+
+    @Test
+    public void pair() throws PairingException {
+        PairingException exception =
+                assertThrows(
+                        PairingException.class,
+                        () -> mBluetoothClassicPairer.pair());
+
+        assertThat(exception)
+                .hasMessageThat()
+                .contains("BluetoothClassicPairer, createBond failed");
+        assertThat(mBluetoothClassicPairer.isPaired()).isFalse();
+    }
+}
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/locator/LocatorTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/locator/LocatorTest.java
index ff7f6f9..c3a4e55 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/common/locator/LocatorTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/locator/LocatorTest.java
@@ -33,6 +33,8 @@
 
 import java.time.Clock;
 
+import src.com.android.server.nearby.fastpair.testing.MockingLocator;
+
 public class LocatorTest {
     private Locator mLocator;
 
@@ -79,4 +81,11 @@
                         + "Searched locators:\n" + "android.app.Application ->\n"
                                 + "android.app.Application ->\n" + "android.app.Application");
     }
+
+    @Test
+    public void getContextForTest() {
+        src.com.android.server.nearby.fastpair.testing.MockingLocator  mockingLocator =
+                new MockingLocator(ApplicationProvider.getApplicationContext(), mLocator);
+        assertThat(mockingLocator.getContextForTest()).isNotNull();
+    }
 }
diff --git a/nearby/tests/unit/src/com/android/server/nearby/common/servicemonitor/PackageWatcherTest.java b/nearby/tests/unit/src/com/android/server/nearby/common/servicemonitor/PackageWatcherTest.java
new file mode 100644
index 0000000..eafc7db
--- /dev/null
+++ b/nearby/tests/unit/src/com/android/server/nearby/common/servicemonitor/PackageWatcherTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.nearby.common.servicemonitor;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Intent;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import org.junit.Test;
+
+public class PackageWatcherTest {
+    private PackageWatcher mPackageWatcher = new PackageWatcher() {
+        @Override
+        public void onSomePackagesChanged() {
+        }
+    };
+
+    @Test
+    public void getPackageName() {
+        Intent intent = new Intent("Action", null);
+        assertThat(mPackageWatcher.getPackageName(intent)).isNull();
+    }
+
+    @Test
+    public void onReceive() {
+        Intent intent = new Intent(Intent.ACTION_PACKAGES_UNSUSPENDED, null);
+        mPackageWatcher.onReceive(ApplicationProvider.getApplicationContext(), intent);
+    }
+}
diff --git a/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/NotificationPairingProgressHandlerTest.java b/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/NotificationPairingProgressHandlerTest.java
index 0405d04..24f296c 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/NotificationPairingProgressHandlerTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/NotificationPairingProgressHandlerTest.java
@@ -20,12 +20,16 @@
 
 import static org.mockito.Mockito.when;
 
+import android.bluetooth.BluetoothManager;
+
 import androidx.annotation.Nullable;
 
+import com.android.server.nearby.common.bluetooth.fastpair.FastPairConnection;
 import com.android.server.nearby.common.locator.Locator;
 import com.android.server.nearby.common.locator.LocatorContextWrapper;
 import com.android.server.nearby.fastpair.cache.DiscoveryItem;
 import com.android.server.nearby.fastpair.cache.FastPairCacheManager;
+import com.android.server.nearby.fastpair.footprint.FootprintsDeviceManager;
 import com.android.server.nearby.fastpair.halfsheet.FastPairHalfSheetManager;
 import com.android.server.nearby.fastpair.notification.FastPairNotificationManager;
 import com.android.server.nearby.fastpair.testing.FakeDiscoveryItems;
@@ -43,6 +47,7 @@
 import service.proto.Rpcs;
 
 public class NotificationPairingProgressHandlerTest {
+
     @Mock
     Locator mLocator;
     @Mock
@@ -51,7 +56,14 @@
     Clock mClock;
     @Mock
     FastPairCacheManager mFastPairCacheManager;
+    @Mock
+    FastPairConnection mFastPairConnection;
+    @Mock
+    FootprintsDeviceManager mFootprintsDeviceManager;
+    @Mock
+    android.bluetooth.BluetoothManager mBluetoothManager;
 
+    private static final String MAC_ADDRESS = "00:11:22:33:44:55";
     private static final byte[] ACCOUNT_KEY = new byte[]{0x01, 0x02};
     private static final int SUBSEQUENT_PAIR_START = 1310;
     private static final int SUBSEQUENT_PAIR_END = 1320;
@@ -61,6 +73,8 @@
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
+        when(mContextWrapper.getSystemService(BluetoothManager.class))
+                .thenReturn(mBluetoothManager);
         when(mContextWrapper.getLocator()).thenReturn(mLocator);
         mLocator.overrideBindingForTest(FastPairCacheManager.class,
                 mFastPairCacheManager);
@@ -94,6 +108,12 @@
     }
 
     @Test
+    public void onPairedCallbackCalled() {
+        sNotificationPairingProgressHandler.onPairedCallbackCalled(mFastPairConnection,
+                    ACCOUNT_KEY, mFootprintsDeviceManager, MAC_ADDRESS);
+    }
+
+    @Test
     public void  onPairingFailed() {
         Throwable e = new Throwable("Pairing Failed");
         sNotificationPairingProgressHandler.onPairingFailed(e);
diff --git a/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/PairingProgressHandlerBaseTest.java b/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/PairingProgressHandlerBaseTest.java
index b4b4f78..a3eb50c 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/PairingProgressHandlerBaseTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/fastpair/pairinghandler/PairingProgressHandlerBaseTest.java
@@ -22,6 +22,7 @@
 
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothManager;
 
 import androidx.annotation.Nullable;
 
@@ -48,6 +49,7 @@
 import service.proto.Cache;
 import service.proto.Rpcs;
 public class PairingProgressHandlerBaseTest {
+
     @Mock
     Locator mLocator;
     @Mock
@@ -60,7 +62,10 @@
     FootprintsDeviceManager mFootprintsDeviceManager;
     @Mock
     FastPairConnection mFastPairConnection;
+    @Mock
+    BluetoothManager mBluetoothManager;
 
+    private static final String MAC_ADDRESS = "00:11:22:33:44:55";
     private static final byte[] ACCOUNT_KEY = new byte[]{0x01, 0x02};
     private static final int PASSKEY = 1234;
     private static DiscoveryItem sDiscoveryItem;
@@ -70,6 +75,8 @@
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
+        when(mContextWrapper.getSystemService(BluetoothManager.class))
+                .thenReturn(mBluetoothManager);
         when(mContextWrapper.getLocator()).thenReturn(mLocator);
         mLocator.overrideBindingForTest(FastPairCacheManager.class,
                 mFastPairCacheManager);
@@ -169,6 +176,12 @@
     }
 
     @Test
+    public void onPairedCallbackCalled() {
+        sPairingProgressHandlerBase.onPairedCallbackCalled(mFastPairConnection,
+                ACCOUNT_KEY, mFootprintsDeviceManager, MAC_ADDRESS);
+    }
+
+    @Test
     public void onPairingFailed() {
         Throwable e = new Throwable("Pairing Failed");
         sPairingProgressHandlerBase.onPairingFailed(e);
diff --git a/nearby/tests/unit/src/com/android/server/nearby/fastpair/testing/MockingLocator.java b/nearby/tests/unit/src/com/android/server/nearby/fastpair/testing/MockingLocator.java
index b261b26..c9a4533 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/fastpair/testing/MockingLocator.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/fastpair/testing/MockingLocator.java
@@ -41,7 +41,7 @@
     }
 
     @SuppressWarnings("nullness") // due to passing in this before initialized.
-    private MockingLocator(Context context, Locator locator) {
+    public MockingLocator(Context context, Locator locator) {
         super(context, locator);
         this.mLocatorContextWrapper = new LocatorContextWrapper(context, this);
     }
diff --git a/nearby/tests/unit/src/com/android/server/nearby/injector/ContextHubManagerAdapterTest.java b/nearby/tests/unit/src/com/android/server/nearby/injector/ContextHubManagerAdapterTest.java
new file mode 100644
index 0000000..b577064
--- /dev/null
+++ b/nearby/tests/unit/src/com/android/server/nearby/injector/ContextHubManagerAdapterTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.nearby.injector;
+
+import android.hardware.location.ContextHubInfo;
+import android.hardware.location.ContextHubManager;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+public class ContextHubManagerAdapterTest {
+    private ContextHubManagerAdapter mContextHubManagerAdapter;
+
+    @Mock
+    ContextHubManager mContextHubManager;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+        mContextHubManagerAdapter = new ContextHubManagerAdapter(mContextHubManager);
+    }
+
+    @Test
+    public void getContextHubs() {
+        mContextHubManagerAdapter.getContextHubs();
+    }
+
+    @Test
+    public void queryNanoApps() {
+        mContextHubManagerAdapter.queryNanoApps(new ContextHubInfo());
+    }
+}
diff --git a/nearby/tests/unit/src/com/android/server/nearby/util/BroadcastPermissionsTest.java b/nearby/tests/unit/src/com/android/server/nearby/util/BroadcastPermissionsTest.java
index 1a22412..71ade2a 100644
--- a/nearby/tests/unit/src/com/android/server/nearby/util/BroadcastPermissionsTest.java
+++ b/nearby/tests/unit/src/com/android/server/nearby/util/BroadcastPermissionsTest.java
@@ -93,4 +93,9 @@
         assertThat(BroadcastPermissions.getPermissionLevel(mMockContext, UID, PID))
                 .isEqualTo(PERMISSION_BLUETOOTH_ADVERTISE);
     }
+
+    @Test
+    public void test_enforceBroadcastPermission() {
+        BroadcastPermissions.enforceBroadcastPermission(mMockContext, mCallerIdentity);
+    }
 }